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/Memory.h" 41 #include "llvm/ADT/Optional.h" 42 #include "llvm/BinaryFormat/MachO.h" 43 #include "llvm/Support/LEB128.h" 44 45 using namespace llvm; 46 using namespace llvm::MachO; 47 using namespace lld; 48 using namespace lld::macho; 49 50 namespace { 51 52 struct Edge { 53 Edge(StringRef s, TrieNode *node) : substring(s), child(node) {} 54 55 StringRef substring; 56 struct TrieNode *child; 57 }; 58 59 struct ExportInfo { 60 uint64_t address; 61 // TODO: Add proper support for re-exports & stub-and-resolver flags. 62 }; 63 64 } // namespace 65 66 namespace lld { 67 namespace macho { 68 69 struct TrieNode { 70 std::vector<Edge> edges; 71 Optional<ExportInfo> info; 72 // Estimated offset from the start of the serialized trie to the current node. 73 // This will converge to the true offset when updateOffset() is run to a 74 // fixpoint. 75 size_t offset = 0; 76 77 // Returns whether the new estimated offset differs from the old one. 78 bool updateOffset(size_t &nextOffset); 79 void writeTo(uint8_t *buf) const; 80 }; 81 82 bool TrieNode::updateOffset(size_t &nextOffset) { 83 // Size of the whole node (including the terminalSize and the outgoing edges.) 84 // In contrast, terminalSize only records the size of the other data in the 85 // node. 86 size_t nodeSize; 87 if (info) { 88 uint64_t flags = 0; 89 uint32_t terminalSize = 90 getULEB128Size(flags) + getULEB128Size(info->address); 91 // Overall node size so far is the uleb128 size of the length of the symbol 92 // info + the symbol info itself. 93 nodeSize = terminalSize + getULEB128Size(terminalSize); 94 } else { 95 nodeSize = 1; // Size of terminalSize (which has a value of 0) 96 } 97 // Compute size of all child edges. 98 ++nodeSize; // Byte for number of children. 99 for (Edge &edge : edges) { 100 nodeSize += edge.substring.size() + 1 // String length. 101 + getULEB128Size(edge.child->offset); // Offset len. 102 } 103 // On input, 'nextOffset' is the new preferred location for this node. 104 bool result = (offset != nextOffset); 105 // Store new location in node object for use by parents. 106 offset = nextOffset; 107 nextOffset += nodeSize; 108 return result; 109 } 110 111 void TrieNode::writeTo(uint8_t *buf) const { 112 buf += offset; 113 if (info) { 114 // TrieNodes with Symbol info: size, flags address 115 uint64_t flags = 0; // TODO: emit proper flags 116 uint32_t terminalSize = 117 getULEB128Size(flags) + getULEB128Size(info->address); 118 buf += encodeULEB128(terminalSize, buf); 119 buf += encodeULEB128(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 = {pivotSymbol->getVA()}; 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 macho 236 } // namespace lld 237