1 //===- ExportTrie.cpp -----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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):
32 // More documentation of the format can be found in
33 // llvm/tools/obj2yaml/macho2yaml.cpp.
35 //===----------------------------------------------------------------------===//
37 #include "ExportTrie.h"
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"
48 using namespace lld::macho
;
53 Edge(StringRef s
, TrieNode
*node
) : substring(s
), child(node
) {}
56 struct TrieNode
*child
;
62 ExportInfo(const Symbol
&sym
, uint64_t imageBase
)
63 : address(sym
.getVA() - imageBase
) {
64 using namespace llvm::MachO
;
65 // Set the symbol type.
67 flags
|= EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION
;
68 // TODO: Add proper support for re-exports & stub-and-resolver flags.
70 // Set the symbol kind.
72 flags
|= EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL
;
73 } else if (auto *defined
= dyn_cast
<Defined
>(&sym
)) {
74 if (defined
->isAbsolute())
75 flags
|= EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE
;
82 struct macho::TrieNode
{
83 std::vector
<Edge
> edges
;
84 Optional
<ExportInfo
> info
;
85 // Estimated offset from the start of the serialized trie to the current node.
86 // This will converge to the true offset when updateOffset() is run to a
90 // Returns whether the new estimated offset differs from the old one.
91 bool updateOffset(size_t &nextOffset
);
92 void writeTo(uint8_t *buf
) const;
95 bool TrieNode::updateOffset(size_t &nextOffset
) {
96 // Size of the whole node (including the terminalSize and the outgoing edges.)
97 // In contrast, terminalSize only records the size of the other data in the
101 uint32_t terminalSize
=
102 getULEB128Size(info
->flags
) + getULEB128Size(info
->address
);
103 // Overall node size so far is the uleb128 size of the length of the symbol
104 // info + the symbol info itself.
105 nodeSize
= terminalSize
+ getULEB128Size(terminalSize
);
107 nodeSize
= 1; // Size of terminalSize (which has a value of 0)
109 // Compute size of all child edges.
110 ++nodeSize
; // Byte for number of children.
111 for (const Edge
&edge
: edges
) {
112 nodeSize
+= edge
.substring
.size() + 1 // String length.
113 + getULEB128Size(edge
.child
->offset
); // Offset len.
115 // On input, 'nextOffset' is the new preferred location for this node.
116 bool result
= (offset
!= nextOffset
);
117 // Store new location in node object for use by parents.
119 nextOffset
+= nodeSize
;
123 void TrieNode::writeTo(uint8_t *buf
) const {
126 // TrieNodes with Symbol info: size, flags address
127 uint32_t terminalSize
=
128 getULEB128Size(info
->flags
) + getULEB128Size(info
->address
);
129 buf
+= encodeULEB128(terminalSize
, buf
);
130 buf
+= encodeULEB128(info
->flags
, buf
);
131 buf
+= encodeULEB128(info
->address
, buf
);
133 // TrieNode with no Symbol info.
134 *buf
++ = 0; // terminalSize
136 // Add number of children. TODO: Handle case where we have more than 256.
137 assert(edges
.size() < 256);
138 *buf
++ = edges
.size();
139 // Append each child edge substring and node offset.
140 for (const Edge
&edge
: edges
) {
141 memcpy(buf
, edge
.substring
.data(), edge
.substring
.size());
142 buf
+= edge
.substring
.size();
144 buf
+= encodeULEB128(edge
.child
->offset
, buf
);
148 TrieBuilder::~TrieBuilder() {
149 for (TrieNode
*node
: nodes
)
153 TrieNode
*TrieBuilder::makeNode() {
154 auto *node
= new TrieNode();
155 nodes
.emplace_back(node
);
159 static int charAt(const Symbol
*sym
, size_t pos
) {
160 StringRef str
= sym
->getName();
161 if (pos
>= str
.size())
166 // Build the trie by performing a three-way radix quicksort: We start by sorting
167 // the strings by their first characters, then sort the strings with the same
168 // first characters by their second characters, and so on recursively. Each
169 // time the prefixes diverge, we add a node to the trie.
171 // node: The most recently created node along this path in the trie (i.e.
172 // the furthest from the root.)
173 // lastPos: The prefix length of the most recently created node, i.e. the number
174 // of characters along its path from the root.
175 // pos: The string index we are currently sorting on. Note that each symbol
176 // S contained in vec has the same prefix S[0...pos).
177 void TrieBuilder::sortAndBuild(MutableArrayRef
<const Symbol
*> vec
,
178 TrieNode
*node
, size_t lastPos
, size_t pos
) {
183 // Partition items so that items in [0, i) are less than the pivot,
184 // [i, j) are the same as the pivot, and [j, vec.size()) are greater than
186 const Symbol
*pivotSymbol
= vec
[vec
.size() / 2];
187 int pivot
= charAt(pivotSymbol
, pos
);
189 size_t j
= vec
.size();
190 for (size_t k
= 0; k
< j
;) {
191 int c
= charAt(vec
[k
], pos
);
193 std::swap(vec
[i
++], vec
[k
++]);
195 std::swap(vec
[--j
], vec
[k
]);
200 bool isTerminal
= pivot
== -1;
201 bool prefixesDiverge
= i
!= 0 || j
!= vec
.size();
202 if (lastPos
!= pos
&& (isTerminal
|| prefixesDiverge
)) {
203 TrieNode
*newNode
= makeNode();
204 node
->edges
.emplace_back(pivotSymbol
->getName().slice(lastPos
, pos
),
210 sortAndBuild(vec
.slice(0, i
), node
, lastPos
, pos
);
211 sortAndBuild(vec
.slice(j
), node
, lastPos
, pos
);
214 assert(j
- i
== 1); // no duplicate symbols
215 node
->info
= ExportInfo(*pivotSymbol
, imageBase
);
217 // This is the tail-call-optimized version of the following:
218 // sortAndBuild(vec.slice(i, j - i), node, lastPos, pos + 1);
219 vec
= vec
.slice(i
, j
- i
);
225 size_t TrieBuilder::build() {
226 if (exported
.empty())
229 TrieNode
*root
= makeNode();
230 sortAndBuild(exported
, root
, 0, 0);
232 // Assign each node in the vector an offset in the trie stream, iterating
233 // until all uleb128 sizes have stabilized.
239 for (TrieNode
*node
: nodes
)
240 more
|= node
->updateOffset(offset
);
246 void TrieBuilder::writeTo(uint8_t *buf
) const {
247 for (TrieNode
*node
: nodes
)
253 // Parse a serialized trie and invoke a callback for each entry.
256 TrieParser(const uint8_t *buf
, size_t size
, const TrieEntryCallback
&callback
)
257 : start(buf
), end(start
+ size
), callback(callback
) {}
259 void parse(const uint8_t *buf
, const Twine
&cumulativeString
);
261 void parse() { parse(start
, ""); }
263 const uint8_t *start
;
265 const TrieEntryCallback
&callback
;
270 void TrieParser::parse(const uint8_t *buf
, const Twine
&cumulativeString
) {
272 fatal("Node offset points outside export section");
275 uint64_t terminalSize
= decodeULEB128(buf
, &ulebSize
);
279 if (terminalSize
!= 0) {
280 flags
= decodeULEB128(buf
, &ulebSize
);
281 callback(cumulativeString
, flags
);
284 uint8_t numEdges
= *buf
++;
285 for (uint8_t i
= 0; i
< numEdges
; ++i
) {
286 const char *cbuf
= reinterpret_cast<const char *>(buf
);
287 StringRef substring
= StringRef(cbuf
, strnlen(cbuf
, end
- buf
));
288 buf
+= substring
.size() + 1;
289 offset
= decodeULEB128(buf
, &ulebSize
);
291 parse(start
+ offset
, cumulativeString
+ substring
);
295 void macho::parseTrie(const uint8_t *buf
, size_t size
,
296 const TrieEntryCallback
&callback
) {
300 TrieParser(buf
, size
, callback
).parse();