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   // TODO: Add proper support for re-exports & stub-and-resolver flags.
63 };
64 
65 } // namespace
66 
67 namespace lld {
68 namespace macho {
69 
70 struct TrieNode {
71   std::vector<Edge> edges;
72   Optional<ExportInfo> info;
73   // Estimated offset from the start of the serialized trie to the current node.
74   // This will converge to the true offset when updateOffset() is run to a
75   // fixpoint.
76   size_t offset = 0;
77 
78   // Returns whether the new estimated offset differs from the old one.
79   bool updateOffset(size_t &nextOffset);
80   void writeTo(uint8_t *buf) const;
81 };
82 
83 bool TrieNode::updateOffset(size_t &nextOffset) {
84   // Size of the whole node (including the terminalSize and the outgoing edges.)
85   // In contrast, terminalSize only records the size of the other data in the
86   // node.
87   size_t nodeSize;
88   if (info) {
89     uint64_t flags = 0;
90     uint32_t terminalSize =
91         getULEB128Size(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     uint64_t flags = 0; // TODO: emit proper flags
117     uint32_t terminalSize =
118         getULEB128Size(flags) + getULEB128Size(info->address);
119     buf += encodeULEB128(terminalSize, buf);
120     buf += encodeULEB128(flags, buf);
121     buf += encodeULEB128(info->address, buf);
122   } else {
123     // TrieNode with no Symbol info.
124     *buf++ = 0; // terminalSize
125   }
126   // Add number of children. TODO: Handle case where we have more than 256.
127   assert(edges.size() < 256);
128   *buf++ = edges.size();
129   // Append each child edge substring and node offset.
130   for (const Edge &edge : edges) {
131     memcpy(buf, edge.substring.data(), edge.substring.size());
132     buf += edge.substring.size();
133     *buf++ = '\0';
134     buf += encodeULEB128(edge.child->offset, buf);
135   }
136 }
137 
138 TrieNode *TrieBuilder::makeNode() {
139   auto *node = make<TrieNode>();
140   nodes.emplace_back(node);
141   return node;
142 }
143 
144 static int charAt(const Symbol *sym, size_t pos) {
145   StringRef str = sym->getName();
146   if (pos >= str.size())
147     return -1;
148   return str[pos];
149 }
150 
151 // Build the trie by performing a three-way radix quicksort: We start by sorting
152 // the strings by their first characters, then sort the strings with the same
153 // first characters by their second characters, and so on recursively. Each
154 // time the prefixes diverge, we add a node to the trie.
155 //
156 // node:    The most recently created node along this path in the trie (i.e.
157 //          the furthest from the root.)
158 // lastPos: The prefix length of the most recently created node, i.e. the number
159 //          of characters along its path from the root.
160 // pos:     The string index we are currently sorting on. Note that each symbol
161 //          S contained in vec has the same prefix S[0...pos).
162 void TrieBuilder::sortAndBuild(MutableArrayRef<const Symbol *> vec,
163                                TrieNode *node, size_t lastPos, size_t pos) {
164 tailcall:
165   if (vec.empty())
166     return;
167 
168   // Partition items so that items in [0, i) are less than the pivot,
169   // [i, j) are the same as the pivot, and [j, vec.size()) are greater than
170   // the pivot.
171   const Symbol *pivotSymbol = vec[vec.size() / 2];
172   int pivot = charAt(pivotSymbol, pos);
173   size_t i = 0;
174   size_t j = vec.size();
175   for (size_t k = 0; k < j;) {
176     int c = charAt(vec[k], pos);
177     if (c < pivot)
178       std::swap(vec[i++], vec[k++]);
179     else if (c > pivot)
180       std::swap(vec[--j], vec[k]);
181     else
182       k++;
183   }
184 
185   bool isTerminal = pivot == -1;
186   bool prefixesDiverge = i != 0 || j != vec.size();
187   if (lastPos != pos && (isTerminal || prefixesDiverge)) {
188     TrieNode *newNode = makeNode();
189     node->edges.emplace_back(pivotSymbol->getName().slice(lastPos, pos),
190                              newNode);
191     node = newNode;
192     lastPos = pos;
193   }
194 
195   sortAndBuild(vec.slice(0, i), node, lastPos, pos);
196   sortAndBuild(vec.slice(j), node, lastPos, pos);
197 
198   if (isTerminal) {
199     assert(j - i == 1); // no duplicate symbols
200     node->info = {pivotSymbol->getVA()};
201   } else {
202     // This is the tail-call-optimized version of the following:
203     // sortAndBuild(vec.slice(i, j - i), node, lastPos, pos + 1);
204     vec = vec.slice(i, j - i);
205     ++pos;
206     goto tailcall;
207   }
208 }
209 
210 size_t TrieBuilder::build() {
211   if (exported.empty())
212     return 0;
213 
214   TrieNode *root = makeNode();
215   sortAndBuild(exported, root, 0, 0);
216 
217   // Assign each node in the vector an offset in the trie stream, iterating
218   // until all uleb128 sizes have stabilized.
219   size_t offset;
220   bool more;
221   do {
222     offset = 0;
223     more = false;
224     for (TrieNode *node : nodes)
225       more |= node->updateOffset(offset);
226   } while (more);
227 
228   return offset;
229 }
230 
231 void TrieBuilder::writeTo(uint8_t *buf) const {
232   for (TrieNode *node : nodes)
233     node->writeTo(buf);
234 }
235 
236 namespace {
237 
238 // Parse a serialized trie and invoke a callback for each entry.
239 class TrieParser {
240 public:
241   TrieParser(const uint8_t *buf, size_t size, const TrieEntryCallback &callback)
242       : start(buf), end(start + size), callback(callback) {}
243 
244   void parse(const uint8_t *buf, const Twine &cumulativeString);
245 
246   void parse() { parse(start, ""); }
247 
248   const uint8_t *start;
249   const uint8_t *end;
250   const TrieEntryCallback &callback;
251 };
252 
253 } // namespace
254 
255 void TrieParser::parse(const uint8_t *buf, const Twine &cumulativeString) {
256   if (buf >= end)
257     fatal("Node offset points outside export section");
258 
259   unsigned ulebSize;
260   uint64_t terminalSize = decodeULEB128(buf, &ulebSize);
261   buf += ulebSize;
262   uint64_t flags = 0;
263   size_t offset;
264   if (terminalSize != 0) {
265     flags = decodeULEB128(buf, &ulebSize);
266     callback(cumulativeString, flags);
267   }
268   buf += terminalSize;
269   uint8_t numEdges = *buf++;
270   for (uint8_t i = 0; i < numEdges; ++i) {
271     const char *cbuf = reinterpret_cast<const char *>(buf);
272     StringRef substring = StringRef(cbuf, strnlen(cbuf, end - buf));
273     buf += substring.size() + 1;
274     offset = decodeULEB128(buf, &ulebSize);
275     buf += ulebSize;
276     parse(start + offset, cumulativeString + substring);
277   }
278 }
279 
280 void parseTrie(const uint8_t *buf, size_t size,
281                const TrieEntryCallback &callback) {
282   if (size == 0)
283     return;
284 
285   TrieParser(buf, size, callback).parse();
286 }
287 
288 } // namespace macho
289 } // namespace lld
290