1 //===- ExportTrie.cpp -----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is a partial implementation of the Mach-O export trie format. It's 10 // essentially a symbol table encoded as a compressed prefix trie, meaning that 11 // the common prefixes of each symbol name are shared for a more compact 12 // representation. The prefixes are stored on the edges of the trie, and one 13 // edge can represent multiple characters. For example, given two exported 14 // symbols _bar and _baz, we will have a trie like this (terminal nodes are 15 // marked with an asterisk): 16 // 17 // +-+-+ 18 // | | // root node 19 // +-+-+ 20 // | 21 // | _ba 22 // | 23 // +-+-+ 24 // | | 25 // +-+-+ 26 // r / \ z 27 // / \ 28 // +-+-+ +-+-+ 29 // | * | | * | 30 // +-+-+ +-+-+ 31 // 32 // More documentation of the format can be found in 33 // llvm/tools/obj2yaml/macho2yaml.cpp. 34 // 35 //===----------------------------------------------------------------------===// 36 37 #include "ExportTrie.h" 38 #include "Symbols.h" 39 40 #include "lld/Common/ErrorHandler.h" 41 #include "lld/Common/Memory.h" 42 #include "llvm/ADT/Optional.h" 43 #include "llvm/BinaryFormat/MachO.h" 44 #include "llvm/Support/LEB128.h" 45 46 using namespace llvm; 47 using namespace llvm::MachO; 48 using namespace lld; 49 using namespace lld::macho; 50 51 namespace { 52 53 struct Edge { 54 Edge(StringRef s, TrieNode *node) : substring(s), child(node) {} 55 56 StringRef substring; 57 struct TrieNode *child; 58 }; 59 60 struct ExportInfo { 61 uint64_t address; 62 uint8_t flags; 63 explicit ExportInfo(const Symbol &sym) 64 : address(sym.getVA()), 65 flags(sym.isWeakDef() ? EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION : 0) {} 66 // TODO: Add proper support for re-exports & stub-and-resolver flags. 67 }; 68 69 } // namespace 70 71 struct macho::TrieNode { 72 std::vector<Edge> edges; 73 Optional<ExportInfo> info; 74 // Estimated offset from the start of the serialized trie to the current node. 75 // This will converge to the true offset when updateOffset() is run to a 76 // fixpoint. 77 size_t offset = 0; 78 79 // Returns whether the new estimated offset differs from the old one. 80 bool updateOffset(size_t &nextOffset); 81 void writeTo(uint8_t *buf) const; 82 }; 83 84 bool TrieNode::updateOffset(size_t &nextOffset) { 85 // Size of the whole node (including the terminalSize and the outgoing edges.) 86 // In contrast, terminalSize only records the size of the other data in the 87 // node. 88 size_t nodeSize; 89 if (info) { 90 uint32_t terminalSize = 91 getULEB128Size(info->flags) + getULEB128Size(info->address); 92 // Overall node size so far is the uleb128 size of the length of the symbol 93 // info + the symbol info itself. 94 nodeSize = terminalSize + getULEB128Size(terminalSize); 95 } else { 96 nodeSize = 1; // Size of terminalSize (which has a value of 0) 97 } 98 // Compute size of all child edges. 99 ++nodeSize; // Byte for number of children. 100 for (Edge &edge : edges) { 101 nodeSize += edge.substring.size() + 1 // String length. 102 + getULEB128Size(edge.child->offset); // Offset len. 103 } 104 // On input, 'nextOffset' is the new preferred location for this node. 105 bool result = (offset != nextOffset); 106 // Store new location in node object for use by parents. 107 offset = nextOffset; 108 nextOffset += nodeSize; 109 return result; 110 } 111 112 void TrieNode::writeTo(uint8_t *buf) const { 113 buf += offset; 114 if (info) { 115 // TrieNodes with Symbol info: size, flags address 116 uint32_t terminalSize = 117 getULEB128Size(info->flags) + getULEB128Size(info->address); 118 buf += encodeULEB128(terminalSize, buf); 119 buf += encodeULEB128(info->flags, buf); 120 buf += encodeULEB128(info->address, buf); 121 } else { 122 // TrieNode with no Symbol info. 123 *buf++ = 0; // terminalSize 124 } 125 // Add number of children. TODO: Handle case where we have more than 256. 126 assert(edges.size() < 256); 127 *buf++ = edges.size(); 128 // Append each child edge substring and node offset. 129 for (const Edge &edge : edges) { 130 memcpy(buf, edge.substring.data(), edge.substring.size()); 131 buf += edge.substring.size(); 132 *buf++ = '\0'; 133 buf += encodeULEB128(edge.child->offset, buf); 134 } 135 } 136 137 TrieNode *TrieBuilder::makeNode() { 138 auto *node = make<TrieNode>(); 139 nodes.emplace_back(node); 140 return node; 141 } 142 143 static int charAt(const Symbol *sym, size_t pos) { 144 StringRef str = sym->getName(); 145 if (pos >= str.size()) 146 return -1; 147 return str[pos]; 148 } 149 150 // Build the trie by performing a three-way radix quicksort: We start by sorting 151 // the strings by their first characters, then sort the strings with the same 152 // first characters by their second characters, and so on recursively. Each 153 // time the prefixes diverge, we add a node to the trie. 154 // 155 // node: The most recently created node along this path in the trie (i.e. 156 // the furthest from the root.) 157 // lastPos: The prefix length of the most recently created node, i.e. the number 158 // of characters along its path from the root. 159 // pos: The string index we are currently sorting on. Note that each symbol 160 // S contained in vec has the same prefix S[0...pos). 161 void TrieBuilder::sortAndBuild(MutableArrayRef<const Symbol *> vec, 162 TrieNode *node, size_t lastPos, size_t pos) { 163 tailcall: 164 if (vec.empty()) 165 return; 166 167 // Partition items so that items in [0, i) are less than the pivot, 168 // [i, j) are the same as the pivot, and [j, vec.size()) are greater than 169 // the pivot. 170 const Symbol *pivotSymbol = vec[vec.size() / 2]; 171 int pivot = charAt(pivotSymbol, pos); 172 size_t i = 0; 173 size_t j = vec.size(); 174 for (size_t k = 0; k < j;) { 175 int c = charAt(vec[k], pos); 176 if (c < pivot) 177 std::swap(vec[i++], vec[k++]); 178 else if (c > pivot) 179 std::swap(vec[--j], vec[k]); 180 else 181 k++; 182 } 183 184 bool isTerminal = pivot == -1; 185 bool prefixesDiverge = i != 0 || j != vec.size(); 186 if (lastPos != pos && (isTerminal || prefixesDiverge)) { 187 TrieNode *newNode = makeNode(); 188 node->edges.emplace_back(pivotSymbol->getName().slice(lastPos, pos), 189 newNode); 190 node = newNode; 191 lastPos = pos; 192 } 193 194 sortAndBuild(vec.slice(0, i), node, lastPos, pos); 195 sortAndBuild(vec.slice(j), node, lastPos, pos); 196 197 if (isTerminal) { 198 assert(j - i == 1); // no duplicate symbols 199 node->info = ExportInfo(*pivotSymbol); 200 } else { 201 // This is the tail-call-optimized version of the following: 202 // sortAndBuild(vec.slice(i, j - i), node, lastPos, pos + 1); 203 vec = vec.slice(i, j - i); 204 ++pos; 205 goto tailcall; 206 } 207 } 208 209 size_t TrieBuilder::build() { 210 if (exported.empty()) 211 return 0; 212 213 TrieNode *root = makeNode(); 214 sortAndBuild(exported, root, 0, 0); 215 216 // Assign each node in the vector an offset in the trie stream, iterating 217 // until all uleb128 sizes have stabilized. 218 size_t offset; 219 bool more; 220 do { 221 offset = 0; 222 more = false; 223 for (TrieNode *node : nodes) 224 more |= node->updateOffset(offset); 225 } while (more); 226 227 return offset; 228 } 229 230 void TrieBuilder::writeTo(uint8_t *buf) const { 231 for (TrieNode *node : nodes) 232 node->writeTo(buf); 233 } 234 235 namespace { 236 237 // Parse a serialized trie and invoke a callback for each entry. 238 class TrieParser { 239 public: 240 TrieParser(const uint8_t *buf, size_t size, const TrieEntryCallback &callback) 241 : start(buf), end(start + size), callback(callback) {} 242 243 void parse(const uint8_t *buf, const Twine &cumulativeString); 244 245 void parse() { parse(start, ""); } 246 247 const uint8_t *start; 248 const uint8_t *end; 249 const TrieEntryCallback &callback; 250 }; 251 252 } // namespace 253 254 void TrieParser::parse(const uint8_t *buf, const Twine &cumulativeString) { 255 if (buf >= end) 256 fatal("Node offset points outside export section"); 257 258 unsigned ulebSize; 259 uint64_t terminalSize = decodeULEB128(buf, &ulebSize); 260 buf += ulebSize; 261 uint64_t flags = 0; 262 size_t offset; 263 if (terminalSize != 0) { 264 flags = decodeULEB128(buf, &ulebSize); 265 callback(cumulativeString, flags); 266 } 267 buf += terminalSize; 268 uint8_t numEdges = *buf++; 269 for (uint8_t i = 0; i < numEdges; ++i) { 270 const char *cbuf = reinterpret_cast<const char *>(buf); 271 StringRef substring = StringRef(cbuf, strnlen(cbuf, end - buf)); 272 buf += substring.size() + 1; 273 offset = decodeULEB128(buf, &ulebSize); 274 buf += ulebSize; 275 parse(start + offset, cumulativeString + substring); 276 } 277 } 278 279 void macho::parseTrie(const uint8_t *buf, size_t size, 280 const TrieEntryCallback &callback) { 281 if (size == 0) 282 return; 283 284 TrieParser(buf, size, callback).parse(); 285 } 286