blob: d46cf2ce386d5dcd7434dc85f55c7bdddb99b8ab [file] [log] [blame]
Nick Kledzike34182f2013-11-06 21:36:55 +00001//===- lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp ---------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10///
Shankar Easwaran3d8de472014-01-27 03:09:26 +000011/// \file For mach-o object files, this implementation converts normalized
Nick Kledzike34182f2013-11-06 21:36:55 +000012/// mach-o in memory to mach-o binary on disk.
13///
Shankar Easwaran3d8de472014-01-27 03:09:26 +000014/// +---------------+
15/// | binary mach-o |
16/// +---------------+
Nick Kledzike34182f2013-11-06 21:36:55 +000017/// ^
18/// |
19/// |
Shankar Easwaran3d8de472014-01-27 03:09:26 +000020/// +------------+
21/// | normalized |
22/// +------------+
Nick Kledzike34182f2013-11-06 21:36:55 +000023
24#include "MachONormalizedFile.h"
25#include "MachONormalizedFileBinaryUtils.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000026#include "lld/Core/Error.h"
27#include "lld/Core/LLVM.h"
Pete Coopere420dd42016-01-25 21:50:54 +000028#include "llvm/ADT/ilist.h"
29#include "llvm/ADT/ilist_node.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000030#include "llvm/ADT/SmallString.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/Debug.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000035#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000036#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/FileOutputBuffer.h"
Nick Kledzik141330a2014-09-03 19:52:50 +000038#include "llvm/Support/Format.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000039#include "llvm/Support/Host.h"
Nick Kledzik00a15d92013-11-09 01:00:51 +000040#include "llvm/Support/LEB128.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000041#include "llvm/Support/MachO.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/raw_ostream.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000044#include <functional>
Nick Kledzik07ba5122014-12-02 01:50:44 +000045#include <list>
Nick Kledzike34182f2013-11-06 21:36:55 +000046#include <map>
Rafael Espindola54427cc2014-06-12 17:15:58 +000047#include <system_error>
Nick Kledzike34182f2013-11-06 21:36:55 +000048
49using namespace llvm::MachO;
50
51namespace lld {
52namespace mach_o {
53namespace normalized {
54
Pete Coopere420dd42016-01-25 21:50:54 +000055class ByteBuffer {
56public:
57 ByteBuffer() : _ostream(_bytes) { }
58
59 void append_byte(uint8_t b) {
60 _ostream << b;
61 }
62 void append_uleb128(uint64_t value) {
63 llvm::encodeULEB128(value, _ostream);
64 }
65 void append_uleb128Fixed(uint64_t value, unsigned byteCount) {
66 unsigned min = llvm::getULEB128Size(value);
67 assert(min <= byteCount);
68 unsigned pad = byteCount - min;
69 llvm::encodeULEB128(value, _ostream, pad);
70 }
71 void append_sleb128(int64_t value) {
72 llvm::encodeSLEB128(value, _ostream);
73 }
74 void append_string(StringRef str) {
75 _ostream << str;
76 append_byte(0);
77 }
78 void align(unsigned alignment) {
79 while ( (_ostream.tell() % alignment) != 0 )
80 append_byte(0);
81 }
82 size_t size() {
83 return _ostream.tell();
84 }
85 const uint8_t *bytes() {
86 return reinterpret_cast<const uint8_t*>(_ostream.str().data());
87 }
88
89private:
90 SmallVector<char, 128> _bytes;
91 // Stream ivar must be after SmallVector ivar to construct properly.
92 llvm::raw_svector_ostream _ostream;
93};
94
95struct TrieNode; // Forward declaration.
96
97struct TrieEdge : public llvm::ilist_node<TrieEdge> {
98 TrieEdge(StringRef s, TrieNode *node) : _subString(s), _child(node) {}
99
100 StringRef _subString;
101 struct TrieNode *_child;
102};
103
104} // namespace normalized
105} // namespace mach_o
106} // namespace lld
107
108
109namespace llvm {
110 using lld::mach_o::normalized::TrieEdge;
111 template <>
112 struct ilist_traits<TrieEdge>
113 : public ilist_default_traits<TrieEdge> {
114 private:
115 mutable ilist_half_node<TrieEdge> Sentinel;
116 public:
117 TrieEdge *createSentinel() const {
118 return static_cast<TrieEdge*>(&Sentinel);
119 }
120 void destroySentinel(TrieEdge *) const {}
121
122 TrieEdge *provideInitialHead() const { return createSentinel(); }
123 TrieEdge *ensureHead(TrieEdge*) const { return createSentinel(); }
124 static void noteHead(TrieEdge*, TrieEdge*) {}
125 void deleteNode(TrieEdge *N) {}
126
127 private:
128 void createNode(const TrieEdge &);
129 };
130} // namespace llvm
131
132
133namespace lld {
134namespace mach_o {
135namespace normalized {
136
137struct TrieNode {
138 typedef llvm::ilist<TrieEdge> TrieEdgeList;
139
140 TrieNode(StringRef s)
141 : _cummulativeString(s), _address(0), _flags(0), _other(0),
142 _trieOffset(0), _hasExportInfo(false) {}
143 ~TrieNode() = default;
144
145 void addSymbol(const Export &entry, BumpPtrAllocator &allocator,
146 std::vector<TrieNode *> &allNodes);
147 bool updateOffset(uint32_t &offset);
148 void appendToByteBuffer(ByteBuffer &out);
149
150private:
151 StringRef _cummulativeString;
152 TrieEdgeList _children;
153 uint64_t _address;
154 uint64_t _flags;
155 uint64_t _other;
156 StringRef _importedName;
157 uint32_t _trieOffset;
158 bool _hasExportInfo;
159};
160
Nick Kledzike34182f2013-11-06 21:36:55 +0000161/// Utility class for writing a mach-o binary file given an in-memory
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000162/// normalized file.
Nick Kledzike34182f2013-11-06 21:36:55 +0000163class MachOFileLayout {
164public:
Joey Goulyb275d7f2013-12-23 23:29:50 +0000165 /// All layout computation is done in the constructor.
166 MachOFileLayout(const NormalizedFile &file);
167
Nick Kledzike34182f2013-11-06 21:36:55 +0000168 /// Returns the final file size as computed in the constructor.
169 size_t size() const;
170
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000171 // Returns size of the mach_header and load commands.
172 size_t headerAndLoadCommandsSize() const;
173
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000174 /// Writes the normalized file as a binary mach-o file to the specified
Nick Kledzike34182f2013-11-06 21:36:55 +0000175 /// path. This does not have a stream interface because the generated
176 /// file may need the 'x' bit set.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000177 std::error_code writeBinary(StringRef path);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000178
Nick Kledzike34182f2013-11-06 21:36:55 +0000179private:
180 uint32_t loadCommandsSize(uint32_t &count);
181 void buildFileOffsets();
182 void writeMachHeader();
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000183 std::error_code writeLoadCommands();
Nick Kledzike34182f2013-11-06 21:36:55 +0000184 void writeSectionContent();
185 void writeRelocations();
186 void writeSymbolTable();
187 void writeRebaseInfo();
188 void writeBindingInfo();
189 void writeLazyBindingInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +0000190 void writeExportInfo();
Nick Kledzik21921372014-07-24 23:06:56 +0000191 void writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +0000192 void writeLinkEditContent();
193 void buildLinkEditInfo();
194 void buildRebaseInfo();
195 void buildBindInfo();
196 void buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +0000197 void buildExportTrie();
Nick Kledzik21921372014-07-24 23:06:56 +0000198 void computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +0000199 void computeSymbolTableSizes();
200 void buildSectionRelocations();
201 void appendSymbols(const std::vector<Symbol> &symbols,
202 uint32_t &symOffset, uint32_t &strOffset);
203 uint32_t indirectSymbolIndex(const Section &sect, uint32_t &index);
204 uint32_t indirectSymbolElementSize(const Section &sect);
205
Nick Kledzik29f749e2013-11-09 00:07:28 +0000206 // For use as template parameter to load command methods.
207 struct MachO64Trait {
208 typedef llvm::MachO::segment_command_64 command;
209 typedef llvm::MachO::section_64 section;
210 enum { LC = llvm::MachO::LC_SEGMENT_64 };
211 };
212
213 // For use as template parameter to load command methods.
214 struct MachO32Trait {
215 typedef llvm::MachO::segment_command command;
216 typedef llvm::MachO::section section;
217 enum { LC = llvm::MachO::LC_SEGMENT };
218 };
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000219
Nick Kledzik29f749e2013-11-09 00:07:28 +0000220 template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000221 std::error_code writeSingleSegmentLoadCommand(uint8_t *&lc);
222 template <typename T> std::error_code writeSegmentLoadCommands(uint8_t *&lc);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000223
Nick Kledzike34182f2013-11-06 21:36:55 +0000224 uint32_t pointerAlign(uint32_t value);
225 static StringRef dyldPath();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000226
Nick Kledzike34182f2013-11-06 21:36:55 +0000227 struct SegExtraInfo {
228 uint32_t fileOffset;
Tim Northover08d6a7b2014-06-30 09:49:30 +0000229 uint32_t fileSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000230 std::vector<const Section*> sections;
231 };
232 typedef std::map<const Segment*, SegExtraInfo> SegMap;
233 struct SectionExtraInfo {
234 uint32_t fileOffset;
235 };
236 typedef std::map<const Section*, SectionExtraInfo> SectionMap;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000237
Nick Kledzike34182f2013-11-06 21:36:55 +0000238 const NormalizedFile &_file;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000239 std::error_code _ec;
Nick Kledzike34182f2013-11-06 21:36:55 +0000240 uint8_t *_buffer;
241 const bool _is64;
242 const bool _swap;
243 const bool _bigEndianArch;
244 uint64_t _seg1addr;
245 uint32_t _startOfLoadCommands;
246 uint32_t _countOfLoadCommands;
247 uint32_t _endOfLoadCommands;
248 uint32_t _startOfRelocations;
Nick Kledzik21921372014-07-24 23:06:56 +0000249 uint32_t _startOfDataInCode;
Nick Kledzike34182f2013-11-06 21:36:55 +0000250 uint32_t _startOfSymbols;
251 uint32_t _startOfIndirectSymbols;
252 uint32_t _startOfSymbolStrings;
253 uint32_t _endOfSymbolStrings;
254 uint32_t _symbolTableLocalsStartIndex;
255 uint32_t _symbolTableGlobalsStartIndex;
256 uint32_t _symbolTableUndefinesStartIndex;
257 uint32_t _symbolStringPoolSize;
258 uint32_t _symbolTableSize;
Nick Kledzik21921372014-07-24 23:06:56 +0000259 uint32_t _dataInCodeSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000260 uint32_t _indirectSymbolTableCount;
261 // Used in object file creation only
262 uint32_t _startOfSectionsContent;
263 uint32_t _endOfSectionsContent;
264 // Used in final linked image only
265 uint32_t _startOfLinkEdit;
266 uint32_t _startOfRebaseInfo;
267 uint32_t _endOfRebaseInfo;
268 uint32_t _startOfBindingInfo;
269 uint32_t _endOfBindingInfo;
270 uint32_t _startOfLazyBindingInfo;
271 uint32_t _endOfLazyBindingInfo;
Nick Kledzik141330a2014-09-03 19:52:50 +0000272 uint32_t _startOfExportTrie;
273 uint32_t _endOfExportTrie;
Nick Kledzike34182f2013-11-06 21:36:55 +0000274 uint32_t _endOfLinkEdit;
275 uint64_t _addressOfLinkEdit;
276 SegMap _segInfo;
277 SectionMap _sectInfo;
278 ByteBuffer _rebaseInfo;
279 ByteBuffer _bindingInfo;
280 ByteBuffer _lazyBindingInfo;
281 ByteBuffer _weakBindingInfo;
Nick Kledzik141330a2014-09-03 19:52:50 +0000282 ByteBuffer _exportTrie;
Nick Kledzike34182f2013-11-06 21:36:55 +0000283};
284
285size_t headerAndLoadCommandsSize(const NormalizedFile &file) {
286 MachOFileLayout layout(file);
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000287 return layout.headerAndLoadCommandsSize();
Nick Kledzike34182f2013-11-06 21:36:55 +0000288}
289
290StringRef MachOFileLayout::dyldPath() {
291 return "/usr/lib/dyld";
292}
293
294uint32_t MachOFileLayout::pointerAlign(uint32_t value) {
Rui Ueyama489a8062016-01-14 20:53:50 +0000295 return llvm::alignTo(value, _is64 ? 8 : 4);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000296}
Nick Kledzike34182f2013-11-06 21:36:55 +0000297
298
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000299size_t MachOFileLayout::headerAndLoadCommandsSize() const {
300 return _endOfLoadCommands;
301}
Nick Kledzike34182f2013-11-06 21:36:55 +0000302
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000303MachOFileLayout::MachOFileLayout(const NormalizedFile &file)
Nick Kledzike34182f2013-11-06 21:36:55 +0000304 : _file(file),
305 _is64(MachOLinkingContext::is64Bit(file.arch)),
306 _swap(!MachOLinkingContext::isHostEndian(file.arch)),
307 _bigEndianArch(MachOLinkingContext::isBigEndian(file.arch)),
308 _seg1addr(INT64_MAX) {
309 _startOfLoadCommands = _is64 ? sizeof(mach_header_64) : sizeof(mach_header);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000310 const size_t segCommandBaseSize =
Nick Kledzike34182f2013-11-06 21:36:55 +0000311 (_is64 ? sizeof(segment_command_64) : sizeof(segment_command));
312 const size_t sectsSize = (_is64 ? sizeof(section_64) : sizeof(section));
313 if (file.fileType == llvm::MachO::MH_OBJECT) {
314 // object files have just one segment load command containing all sections
315 _endOfLoadCommands = _startOfLoadCommands
316 + segCommandBaseSize
317 + file.sections.size() * sectsSize
318 + sizeof(symtab_command);
319 _countOfLoadCommands = 2;
Nick Kledzik21921372014-07-24 23:06:56 +0000320 if (!_file.dataInCode.empty()) {
321 _endOfLoadCommands += sizeof(linkedit_data_command);
322 _countOfLoadCommands++;
323 }
Nick Kledzikb072c362014-11-18 00:30:29 +0000324 // Assign file offsets to each section.
Nick Kledzike34182f2013-11-06 21:36:55 +0000325 _startOfSectionsContent = _endOfLoadCommands;
Nick Kledzike34182f2013-11-06 21:36:55 +0000326 unsigned relocCount = 0;
Nick Kledzikb072c362014-11-18 00:30:29 +0000327 uint64_t offset = _startOfSectionsContent;
Nick Kledzike34182f2013-11-06 21:36:55 +0000328 for (const Section &sect : file.sections) {
Lang Hamesac2adce2015-12-11 23:25:09 +0000329 if (isZeroFillSection(sect.type))
330 _sectInfo[&sect].fileOffset = 0;
331 else {
Rui Ueyama489a8062016-01-14 20:53:50 +0000332 offset = llvm::alignTo(offset, sect.alignment);
Nick Kledzikb072c362014-11-18 00:30:29 +0000333 _sectInfo[&sect].fileOffset = offset;
334 offset += sect.content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000335 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000336 relocCount += sect.relocations.size();
337 }
Nick Kledzikb072c362014-11-18 00:30:29 +0000338 _endOfSectionsContent = offset;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000339
Nick Kledzike34182f2013-11-06 21:36:55 +0000340 computeSymbolTableSizes();
Nick Kledzik21921372014-07-24 23:06:56 +0000341 computeDataInCodeSize();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000342
Nick Kledzike34182f2013-11-06 21:36:55 +0000343 // Align start of relocations.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000344 _startOfRelocations = pointerAlign(_endOfSectionsContent);
Nick Kledzik21921372014-07-24 23:06:56 +0000345 _startOfDataInCode = _startOfRelocations + relocCount * 8;
346 _startOfSymbols = _startOfDataInCode + _dataInCodeSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000347 // Add Indirect symbol table.
348 _startOfIndirectSymbols = _startOfSymbols + _symbolTableSize;
349 // Align start of symbol table and symbol strings.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000350 _startOfSymbolStrings = _startOfIndirectSymbols
Nick Kledzike34182f2013-11-06 21:36:55 +0000351 + pointerAlign(_indirectSymbolTableCount * sizeof(uint32_t));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000352 _endOfSymbolStrings = _startOfSymbolStrings
Nick Kledzike34182f2013-11-06 21:36:55 +0000353 + pointerAlign(_symbolStringPoolSize);
354 _endOfLinkEdit = _endOfSymbolStrings;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000355 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000356 llvm::dbgs() << "MachOFileLayout()\n"
357 << " startOfLoadCommands=" << _startOfLoadCommands << "\n"
358 << " countOfLoadCommands=" << _countOfLoadCommands << "\n"
359 << " endOfLoadCommands=" << _endOfLoadCommands << "\n"
360 << " startOfRelocations=" << _startOfRelocations << "\n"
361 << " startOfSymbols=" << _startOfSymbols << "\n"
362 << " startOfSymbolStrings=" << _startOfSymbolStrings << "\n"
363 << " endOfSymbolStrings=" << _endOfSymbolStrings << "\n"
364 << " startOfSectionsContent=" << _startOfSectionsContent << "\n"
365 << " endOfSectionsContent=" << _endOfSectionsContent << "\n");
366 } else {
367 // Final linked images have one load command per segment.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000368 _endOfLoadCommands = _startOfLoadCommands
Nick Kledzike34182f2013-11-06 21:36:55 +0000369 + loadCommandsSize(_countOfLoadCommands);
370
371 // Assign section file offsets.
372 buildFileOffsets();
373 buildLinkEditInfo();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000374
Nick Kledzike34182f2013-11-06 21:36:55 +0000375 // LINKEDIT of final linked images has in order:
376 // rebase info, binding info, lazy binding info, weak binding info,
Nick Kledzik21921372014-07-24 23:06:56 +0000377 // data-in-code, symbol table, indirect symbol table, symbol table strings.
Nick Kledzike34182f2013-11-06 21:36:55 +0000378 _startOfRebaseInfo = _startOfLinkEdit;
379 _endOfRebaseInfo = _startOfRebaseInfo + _rebaseInfo.size();
380 _startOfBindingInfo = _endOfRebaseInfo;
381 _endOfBindingInfo = _startOfBindingInfo + _bindingInfo.size();
382 _startOfLazyBindingInfo = _endOfBindingInfo;
383 _endOfLazyBindingInfo = _startOfLazyBindingInfo + _lazyBindingInfo.size();
Nick Kledzik141330a2014-09-03 19:52:50 +0000384 _startOfExportTrie = _endOfLazyBindingInfo;
385 _endOfExportTrie = _startOfExportTrie + _exportTrie.size();
386 _startOfDataInCode = _endOfExportTrie;
Nick Kledzik21921372014-07-24 23:06:56 +0000387 _startOfSymbols = _startOfDataInCode + _dataInCodeSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000388 _startOfIndirectSymbols = _startOfSymbols + _symbolTableSize;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000389 _startOfSymbolStrings = _startOfIndirectSymbols
Nick Kledzike34182f2013-11-06 21:36:55 +0000390 + pointerAlign(_indirectSymbolTableCount * sizeof(uint32_t));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000391 _endOfSymbolStrings = _startOfSymbolStrings
Nick Kledzike34182f2013-11-06 21:36:55 +0000392 + pointerAlign(_symbolStringPoolSize);
393 _endOfLinkEdit = _endOfSymbolStrings;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000394 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000395 llvm::dbgs() << "MachOFileLayout()\n"
396 << " startOfLoadCommands=" << _startOfLoadCommands << "\n"
397 << " countOfLoadCommands=" << _countOfLoadCommands << "\n"
398 << " endOfLoadCommands=" << _endOfLoadCommands << "\n"
399 << " startOfLinkEdit=" << _startOfLinkEdit << "\n"
400 << " startOfRebaseInfo=" << _startOfRebaseInfo << "\n"
401 << " endOfRebaseInfo=" << _endOfRebaseInfo << "\n"
402 << " startOfBindingInfo=" << _startOfBindingInfo << "\n"
403 << " endOfBindingInfo=" << _endOfBindingInfo << "\n"
404 << " startOfLazyBindingInfo=" << _startOfLazyBindingInfo << "\n"
405 << " endOfLazyBindingInfo=" << _endOfLazyBindingInfo << "\n"
Nick Kledzik141330a2014-09-03 19:52:50 +0000406 << " startOfExportTrie=" << _startOfExportTrie << "\n"
407 << " endOfExportTrie=" << _endOfExportTrie << "\n"
Nick Kledzik21921372014-07-24 23:06:56 +0000408 << " startOfDataInCode=" << _startOfDataInCode << "\n"
Nick Kledzike34182f2013-11-06 21:36:55 +0000409 << " startOfSymbols=" << _startOfSymbols << "\n"
410 << " startOfSymbolStrings=" << _startOfSymbolStrings << "\n"
411 << " endOfSymbolStrings=" << _endOfSymbolStrings << "\n"
412 << " addressOfLinkEdit=" << _addressOfLinkEdit << "\n");
413 }
414}
415
416uint32_t MachOFileLayout::loadCommandsSize(uint32_t &count) {
417 uint32_t size = 0;
418 count = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000419
420 const size_t segCommandSize =
Nick Kledzike34182f2013-11-06 21:36:55 +0000421 (_is64 ? sizeof(segment_command_64) : sizeof(segment_command));
422 const size_t sectionSize = (_is64 ? sizeof(section_64) : sizeof(section));
423
424 // Add LC_SEGMENT for each segment.
425 size += _file.segments.size() * segCommandSize;
426 count += _file.segments.size();
427 // Add section record for each section.
428 size += _file.sections.size() * sectionSize;
429 // Add one LC_SEGMENT for implicit __LINKEDIT segment
430 size += segCommandSize;
431 ++count;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000432
Tim Northover301c4e62014-07-01 08:15:41 +0000433 // If creating a dylib, add LC_ID_DYLIB.
434 if (_file.fileType == llvm::MachO::MH_DYLIB) {
435 size += sizeof(dylib_command) + pointerAlign(_file.installName.size() + 1);
436 ++count;
437 }
438
Nick Kledzike34182f2013-11-06 21:36:55 +0000439 // Add LC_DYLD_INFO
440 size += sizeof(dyld_info_command);
441 ++count;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000442
Nick Kledzike34182f2013-11-06 21:36:55 +0000443 // Add LC_SYMTAB
444 size += sizeof(symtab_command);
445 ++count;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000446
Nick Kledzike34182f2013-11-06 21:36:55 +0000447 // Add LC_DYSYMTAB
448 if (_file.fileType != llvm::MachO::MH_PRELOAD) {
449 size += sizeof(dysymtab_command);
450 ++count;
451 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000452
Pete Cooper354809e2016-02-03 22:28:29 +0000453 // If main executable add LC_LOAD_DYLINKER
Nick Kledzike34182f2013-11-06 21:36:55 +0000454 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
455 size += pointerAlign(sizeof(dylinker_command) + dyldPath().size()+1);
456 ++count;
Pete Cooper354809e2016-02-03 22:28:29 +0000457 }
458
459 // Add LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_WATCHOS,
460 // LC_VERSION_MIN_TVOS
461 if (_file.hasMinVersionLoadCommand) {
462 size += sizeof(version_min_command);
463 ++count;
464 }
465
466 // If main executable add LC_MAIN
467 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000468 size += sizeof(entry_point_command);
469 ++count;
470 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000471
Nick Kledzike34182f2013-11-06 21:36:55 +0000472 // Add LC_LOAD_DYLIB for each dependent dylib.
473 for (const DependentDylib &dep : _file.dependentDylibs) {
474 size += sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
475 ++count;
476 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000477
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000478 // Add LC_RPATH
479 for (const StringRef &path : _file.rpaths) {
Lang Hames2ed3bf92015-10-29 16:50:26 +0000480 size += pointerAlign(sizeof(rpath_command) + path.size() + 1);
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000481 ++count;
482 }
483
Nick Kledzik54ce29582014-10-28 22:21:10 +0000484 // Add LC_DATA_IN_CODE if needed
485 if (!_file.dataInCode.empty()) {
486 size += sizeof(linkedit_data_command);
487 ++count;
488 }
489
Nick Kledzike34182f2013-11-06 21:36:55 +0000490 return size;
491}
492
493static bool overlaps(const Segment &s1, const Segment &s2) {
494 if (s2.address >= s1.address+s1.size)
495 return false;
496 if (s1.address >= s2.address+s2.size)
497 return false;
498 return true;
499}
500
501static bool overlaps(const Section &s1, const Section &s2) {
502 if (s2.address >= s1.address+s1.content.size())
503 return false;
504 if (s1.address >= s2.address+s2.content.size())
505 return false;
506 return true;
507}
508
509void MachOFileLayout::buildFileOffsets() {
510 // Verify no segments overlap
511 for (const Segment &sg1 : _file.segments) {
512 for (const Segment &sg2 : _file.segments) {
513 if (&sg1 == &sg2)
514 continue;
515 if (overlaps(sg1,sg2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000516 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000517 return;
518 }
519 }
520 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000521
522 // Verify no sections overlap
Nick Kledzike34182f2013-11-06 21:36:55 +0000523 for (const Section &s1 : _file.sections) {
524 for (const Section &s2 : _file.sections) {
525 if (&s1 == &s2)
526 continue;
527 if (overlaps(s1,s2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000528 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000529 return;
530 }
531 }
532 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000533
Nick Kledzike34182f2013-11-06 21:36:55 +0000534 // Build side table of extra info about segments and sections.
535 SegExtraInfo t;
536 t.fileOffset = 0;
537 for (const Segment &sg : _file.segments) {
538 _segInfo[&sg] = t;
539 }
540 SectionExtraInfo t2;
541 t2.fileOffset = 0;
542 // Assign sections to segments.
543 for (const Section &s : _file.sections) {
544 _sectInfo[&s] = t2;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000545 bool foundSegment = false;
Nick Kledzike34182f2013-11-06 21:36:55 +0000546 for (const Segment &sg : _file.segments) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000547 if (sg.name.equals(s.segmentName)) {
548 if ((s.address >= sg.address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000549 && (s.address+s.content.size() <= sg.address+sg.size)) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000550 _segInfo[&sg].sections.push_back(&s);
551 foundSegment = true;
552 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000553 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000554 }
555 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000556 if (!foundSegment) {
557 _ec = make_error_code(llvm::errc::executable_format_error);
558 return;
559 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000560 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000561
Nick Kledzike34182f2013-11-06 21:36:55 +0000562 // Assign file offsets.
563 uint32_t fileOffset = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000564 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000565 llvm::dbgs() << "buildFileOffsets()\n");
566 for (const Segment &sg : _file.segments) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000567 _segInfo[&sg].fileOffset = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000568 if ((_seg1addr == INT64_MAX) && sg.access)
569 _seg1addr = sg.address;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000570 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000571 llvm::dbgs() << " segment=" << sg.name
572 << ", fileOffset=" << _segInfo[&sg].fileOffset << "\n");
Tim Northover08d6a7b2014-06-30 09:49:30 +0000573
574 uint32_t segFileSize = 0;
Nick Kledzik761d6542014-10-24 22:19:22 +0000575 // A segment that is not zero-fill must use a least one page of disk space.
576 if (sg.access)
577 segFileSize = _file.pageSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000578 for (const Section *s : _segInfo[&sg].sections) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000579 uint32_t sectOffset = s->address - sg.address;
580 uint32_t sectFileSize =
Lang Hamesac2adce2015-12-11 23:25:09 +0000581 isZeroFillSection(s->type) ? 0 : s->content.size();
Tim Northover08d6a7b2014-06-30 09:49:30 +0000582 segFileSize = std::max(segFileSize, sectOffset + sectFileSize);
583
584 _sectInfo[s].fileOffset = _segInfo[&sg].fileOffset + sectOffset;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000585 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000586 llvm::dbgs() << " section=" << s->sectionName
587 << ", fileOffset=" << fileOffset << "\n");
588 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000589
Rui Ueyama489a8062016-01-14 20:53:50 +0000590 _segInfo[&sg].fileSize = llvm::alignTo(segFileSize, _file.pageSize);
591 fileOffset = llvm::alignTo(fileOffset + segFileSize, _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000592 _addressOfLinkEdit = sg.address + sg.size;
593 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000594 _startOfLinkEdit = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000595}
596
Nick Kledzike34182f2013-11-06 21:36:55 +0000597size_t MachOFileLayout::size() const {
598 return _endOfSymbolStrings;
599}
600
601void MachOFileLayout::writeMachHeader() {
602 mach_header *mh = reinterpret_cast<mach_header*>(_buffer);
603 mh->magic = _is64 ? llvm::MachO::MH_MAGIC_64 : llvm::MachO::MH_MAGIC;
604 mh->cputype = MachOLinkingContext::cpuTypeFromArch(_file.arch);
605 mh->cpusubtype = MachOLinkingContext::cpuSubtypeFromArch(_file.arch);
606 mh->filetype = _file.fileType;
607 mh->ncmds = _countOfLoadCommands;
608 mh->sizeofcmds = _endOfLoadCommands - _startOfLoadCommands;
609 mh->flags = _file.flags;
610 if (_swap)
611 swapStruct(*mh);
612}
613
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000614uint32_t MachOFileLayout::indirectSymbolIndex(const Section &sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000615 uint32_t &index) {
616 if (sect.indirectSymbols.empty())
617 return 0;
618 uint32_t result = index;
619 index += sect.indirectSymbols.size();
620 return result;
621}
622
623uint32_t MachOFileLayout::indirectSymbolElementSize(const Section &sect) {
624 if (sect.indirectSymbols.empty())
625 return 0;
626 if (sect.type != S_SYMBOL_STUBS)
627 return 0;
628 return sect.content.size() / sect.indirectSymbols.size();
629}
630
Nick Kledzik29f749e2013-11-09 00:07:28 +0000631template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000632std::error_code MachOFileLayout::writeSingleSegmentLoadCommand(uint8_t *&lc) {
Nick Kledzik29f749e2013-11-09 00:07:28 +0000633 typename T::command* seg = reinterpret_cast<typename T::command*>(lc);
634 seg->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000635 seg->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000636 + _file.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000637 uint8_t *next = lc + seg->cmdsize;
638 memset(seg->segname, 0, 16);
639 seg->vmaddr = 0;
Nick Kledzikb072c362014-11-18 00:30:29 +0000640 seg->vmsize = _file.sections.back().address
641 + _file.sections.back().content.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000642 seg->fileoff = _endOfLoadCommands;
643 seg->filesize = seg->vmsize;
644 seg->maxprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
645 seg->initprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
646 seg->nsects = _file.sections.size();
647 seg->flags = 0;
648 if (_swap)
649 swapStruct(*seg);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000650 typename T::section *sout = reinterpret_cast<typename T::section*>
651 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000652 uint32_t relOffset = _startOfRelocations;
Nick Kledzike34182f2013-11-06 21:36:55 +0000653 uint32_t indirectSymRunningIndex = 0;
654 for (const Section &sin : _file.sections) {
655 setString16(sin.sectionName, sout->sectname);
656 setString16(sin.segmentName, sout->segname);
657 sout->addr = sin.address;
658 sout->size = sin.content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000659 sout->offset = _sectInfo[&sin].fileOffset;
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000660 sout->align = llvm::Log2_32(sin.alignment);
Nick Kledzike34182f2013-11-06 21:36:55 +0000661 sout->reloff = sin.relocations.empty() ? 0 : relOffset;
662 sout->nreloc = sin.relocations.size();
663 sout->flags = sin.type | sin.attributes;
664 sout->reserved1 = indirectSymbolIndex(sin, indirectSymRunningIndex);
665 sout->reserved2 = indirectSymbolElementSize(sin);
666 relOffset += sin.relocations.size() * sizeof(any_relocation_info);
Nick Kledzike34182f2013-11-06 21:36:55 +0000667 if (_swap)
668 swapStruct(*sout);
669 ++sout;
670 }
671 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000672 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000673}
674
Nick Kledzik29f749e2013-11-09 00:07:28 +0000675template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000676std::error_code MachOFileLayout::writeSegmentLoadCommands(uint8_t *&lc) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000677 uint32_t indirectSymRunningIndex = 0;
678 for (const Segment &seg : _file.segments) {
679 // Write segment command with trailing sections.
680 SegExtraInfo &segInfo = _segInfo[&seg];
Nick Kledzik29f749e2013-11-09 00:07:28 +0000681 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
682 cmd->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000683 cmd->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000684 + segInfo.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000685 uint8_t *next = lc + cmd->cmdsize;
686 setString16(seg.name, cmd->segname);
687 cmd->vmaddr = seg.address;
688 cmd->vmsize = seg.size;
689 cmd->fileoff = segInfo.fileOffset;
Tim Northover08d6a7b2014-06-30 09:49:30 +0000690 cmd->filesize = segInfo.fileSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000691 cmd->maxprot = seg.access;
692 cmd->initprot = seg.access;
693 cmd->nsects = segInfo.sections.size();
694 cmd->flags = 0;
695 if (_swap)
696 swapStruct(*cmd);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000697 typename T::section *sect = reinterpret_cast<typename T::section*>
698 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000699 for (const Section *section : segInfo.sections) {
700 setString16(section->sectionName, sect->sectname);
701 setString16(section->segmentName, sect->segname);
702 sect->addr = section->address;
703 sect->size = section->content.size();
Lang Hamesac2adce2015-12-11 23:25:09 +0000704 if (isZeroFillSection(section->type))
Nick Kledzikb072c362014-11-18 00:30:29 +0000705 sect->offset = 0;
706 else
707 sect->offset = section->address - seg.address + segInfo.fileOffset;
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000708 sect->align = llvm::Log2_32(section->alignment);
Nick Kledzike34182f2013-11-06 21:36:55 +0000709 sect->reloff = 0;
710 sect->nreloc = 0;
711 sect->flags = section->type | section->attributes;
712 sect->reserved1 = indirectSymbolIndex(*section, indirectSymRunningIndex);
713 sect->reserved2 = indirectSymbolElementSize(*section);
714 if (_swap)
715 swapStruct(*sect);
716 ++sect;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000717 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000718 lc = reinterpret_cast<uint8_t*>(next);
719 }
720 // Add implicit __LINKEDIT segment
Nick Kledzik1bebb282014-09-09 23:52:59 +0000721 size_t linkeditSize = _endOfLinkEdit - _startOfLinkEdit;
Nick Kledzik29f749e2013-11-09 00:07:28 +0000722 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
723 cmd->cmd = T::LC;
724 cmd->cmdsize = sizeof(typename T::command);
Nick Kledzike34182f2013-11-06 21:36:55 +0000725 uint8_t *next = lc + cmd->cmdsize;
726 setString16("__LINKEDIT", cmd->segname);
727 cmd->vmaddr = _addressOfLinkEdit;
Rui Ueyama489a8062016-01-14 20:53:50 +0000728 cmd->vmsize = llvm::alignTo(linkeditSize, _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000729 cmd->fileoff = _startOfLinkEdit;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000730 cmd->filesize = linkeditSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000731 cmd->maxprot = VM_PROT_READ;
732 cmd->initprot = VM_PROT_READ;
733 cmd->nsects = 0;
734 cmd->flags = 0;
735 if (_swap)
736 swapStruct(*cmd);
737 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000738 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000739}
740
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000741std::error_code MachOFileLayout::writeLoadCommands() {
742 std::error_code ec;
Nick Kledzike34182f2013-11-06 21:36:55 +0000743 uint8_t *lc = &_buffer[_startOfLoadCommands];
744 if (_file.fileType == llvm::MachO::MH_OBJECT) {
745 // Object files have one unnamed segment which holds all sections.
746 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000747 ec = writeSingleSegmentLoadCommand<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000748 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000749 ec = writeSingleSegmentLoadCommand<MachO32Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000750 // Add LC_SYMTAB with symbol table info
751 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
752 st->cmd = LC_SYMTAB;
753 st->cmdsize = sizeof(symtab_command);
754 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000755 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000756 + _file.undefinedSymbols.size();
757 st->stroff = _startOfSymbolStrings;
758 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
759 if (_swap)
760 swapStruct(*st);
Nick Kledzik21921372014-07-24 23:06:56 +0000761 lc += sizeof(symtab_command);
762 // Add LC_DATA_IN_CODE if needed.
763 if (_dataInCodeSize != 0) {
764 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
765 dl->cmd = LC_DATA_IN_CODE;
766 dl->cmdsize = sizeof(linkedit_data_command);
767 dl->dataoff = _startOfDataInCode;
768 dl->datasize = _dataInCodeSize;
769 if (_swap)
770 swapStruct(*dl);
771 lc += sizeof(linkedit_data_command);
772 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000773 } else {
774 // Final linked images have sections under segments.
775 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000776 ec = writeSegmentLoadCommands<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000777 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000778 ec = writeSegmentLoadCommands<MachO32Trait>(lc);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000779
Tim Northover301c4e62014-07-01 08:15:41 +0000780 // Add LC_ID_DYLIB command for dynamic libraries.
781 if (_file.fileType == llvm::MachO::MH_DYLIB) {
782 dylib_command *dc = reinterpret_cast<dylib_command*>(lc);
783 StringRef path = _file.installName;
784 uint32_t size = sizeof(dylib_command) + pointerAlign(path.size() + 1);
785 dc->cmd = LC_ID_DYLIB;
786 dc->cmdsize = size;
787 dc->dylib.name = sizeof(dylib_command); // offset
Jean-Daniel Dupasedefccc2014-12-20 09:22:56 +0000788 // needs to be some constant value different than the one in LC_LOAD_DYLIB
789 dc->dylib.timestamp = 1;
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000790 dc->dylib.current_version = _file.currentVersion;
791 dc->dylib.compatibility_version = _file.compatVersion;
Tim Northover301c4e62014-07-01 08:15:41 +0000792 if (_swap)
793 swapStruct(*dc);
794 memcpy(lc + sizeof(dylib_command), path.begin(), path.size());
795 lc[sizeof(dylib_command) + path.size()] = '\0';
796 lc += size;
797 }
798
Nick Kledzike34182f2013-11-06 21:36:55 +0000799 // Add LC_DYLD_INFO_ONLY.
800 dyld_info_command* di = reinterpret_cast<dyld_info_command*>(lc);
801 di->cmd = LC_DYLD_INFO_ONLY;
802 di->cmdsize = sizeof(dyld_info_command);
803 di->rebase_off = _rebaseInfo.size() ? _startOfRebaseInfo : 0;
804 di->rebase_size = _rebaseInfo.size();
805 di->bind_off = _bindingInfo.size() ? _startOfBindingInfo : 0;
806 di->bind_size = _bindingInfo.size();
807 di->weak_bind_off = 0;
808 di->weak_bind_size = 0;
809 di->lazy_bind_off = _lazyBindingInfo.size() ? _startOfLazyBindingInfo : 0;
810 di->lazy_bind_size = _lazyBindingInfo.size();
Nick Kledzik141330a2014-09-03 19:52:50 +0000811 di->export_off = _exportTrie.size() ? _startOfExportTrie : 0;
812 di->export_size = _exportTrie.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000813 if (_swap)
814 swapStruct(*di);
815 lc += sizeof(dyld_info_command);
816
817 // Add LC_SYMTAB with symbol table info.
818 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
819 st->cmd = LC_SYMTAB;
820 st->cmdsize = sizeof(symtab_command);
821 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000822 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000823 + _file.undefinedSymbols.size();
824 st->stroff = _startOfSymbolStrings;
825 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
826 if (_swap)
827 swapStruct(*st);
828 lc += sizeof(symtab_command);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000829
Nick Kledzike34182f2013-11-06 21:36:55 +0000830 // Add LC_DYSYMTAB
831 if (_file.fileType != llvm::MachO::MH_PRELOAD) {
832 dysymtab_command* dst = reinterpret_cast<dysymtab_command*>(lc);
833 dst->cmd = LC_DYSYMTAB;
834 dst->cmdsize = sizeof(dysymtab_command);
835 dst->ilocalsym = _symbolTableLocalsStartIndex;
836 dst->nlocalsym = _file.localSymbols.size();
837 dst->iextdefsym = _symbolTableGlobalsStartIndex;
838 dst->nextdefsym = _file.globalSymbols.size();
839 dst->iundefsym = _symbolTableUndefinesStartIndex;
840 dst->nundefsym = _file.undefinedSymbols.size();
841 dst->tocoff = 0;
842 dst->ntoc = 0;
843 dst->modtaboff = 0;
844 dst->nmodtab = 0;
845 dst->extrefsymoff = 0;
846 dst->nextrefsyms = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000847 dst->indirectsymoff = _startOfIndirectSymbols;
Nick Kledzike34182f2013-11-06 21:36:55 +0000848 dst->nindirectsyms = _indirectSymbolTableCount;
849 dst->extreloff = 0;
850 dst->nextrel = 0;
851 dst->locreloff = 0;
852 dst->nlocrel = 0;
853 if (_swap)
854 swapStruct(*dst);
855 lc += sizeof(dysymtab_command);
856 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000857
Pete Cooper354809e2016-02-03 22:28:29 +0000858 // If main executable, add LC_LOAD_DYLINKER
Nick Kledzike34182f2013-11-06 21:36:55 +0000859 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
860 // Build LC_LOAD_DYLINKER load command.
861 uint32_t size=pointerAlign(sizeof(dylinker_command)+dyldPath().size()+1);
862 dylinker_command* dl = reinterpret_cast<dylinker_command*>(lc);
863 dl->cmd = LC_LOAD_DYLINKER;
864 dl->cmdsize = size;
865 dl->name = sizeof(dylinker_command); // offset
866 if (_swap)
867 swapStruct(*dl);
868 memcpy(lc+sizeof(dylinker_command), dyldPath().data(), dyldPath().size());
869 lc[sizeof(dylinker_command)+dyldPath().size()] = '\0';
870 lc += size;
Pete Cooper354809e2016-02-03 22:28:29 +0000871 }
872
873 // Add LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_WATCHOS,
874 // LC_VERSION_MIN_TVOS
875 if (_file.hasMinVersionLoadCommand) {
876 version_min_command *vm = reinterpret_cast<version_min_command*>(lc);
877 switch (_file.os) {
878 case MachOLinkingContext::OS::unknown:
879 // TODO: We need to emit the load command if we managed to derive
880 // a platform from one of the files we are linking.
881 llvm_unreachable("Version commands for unknown OS aren't supported");
882 break;
883 case MachOLinkingContext::OS::macOSX:
884 vm->cmd = LC_VERSION_MIN_MACOSX;
885 vm->cmdsize = sizeof(version_min_command);
886 vm->version = _file.minOSverson;
887 vm->sdk = _file.sdkVersion;
888 break;
889 case MachOLinkingContext::OS::iOS:
890 case MachOLinkingContext::OS::iOS_simulator:
891 vm->cmd = LC_VERSION_MIN_MACOSX;
892 vm->cmdsize = sizeof(version_min_command);
893 vm->version = _file.minOSverson;
894 vm->sdk = _file.sdkVersion;
895 break;
896 }
897 if (_swap)
898 swapStruct(*vm);
899 lc += sizeof(version_min_command);
900 }
901
902 // If main executable, add LC_MAIN.
903 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000904 // Build LC_MAIN load command.
905 entry_point_command* ep = reinterpret_cast<entry_point_command*>(lc);
906 ep->cmd = LC_MAIN;
907 ep->cmdsize = sizeof(entry_point_command);
908 ep->entryoff = _file.entryAddress - _seg1addr;
Lang Hames65a64c92015-05-20 22:10:50 +0000909 ep->stacksize = _file.stackSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000910 if (_swap)
911 swapStruct(*ep);
912 lc += sizeof(entry_point_command);
913 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000914
Nick Kledzike34182f2013-11-06 21:36:55 +0000915 // Add LC_LOAD_DYLIB commands
916 for (const DependentDylib &dep : _file.dependentDylibs) {
917 dylib_command* dc = reinterpret_cast<dylib_command*>(lc);
918 uint32_t size = sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
Nick Kledzik51720672014-10-16 19:31:28 +0000919 dc->cmd = dep.kind;
Nick Kledzike34182f2013-11-06 21:36:55 +0000920 dc->cmdsize = size;
921 dc->dylib.name = sizeof(dylib_command); // offset
Jean-Daniel Dupasedefccc2014-12-20 09:22:56 +0000922 // needs to be some constant value different than the one in LC_ID_DYLIB
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000923 dc->dylib.timestamp = 2;
924 dc->dylib.current_version = dep.currentVersion;
925 dc->dylib.compatibility_version = dep.compatVersion;
Nick Kledzike34182f2013-11-06 21:36:55 +0000926 if (_swap)
927 swapStruct(*dc);
928 memcpy(lc+sizeof(dylib_command), dep.path.begin(), dep.path.size());
929 lc[sizeof(dylib_command)+dep.path.size()] = '\0';
930 lc += size;
931 }
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000932
933 // Add LC_RPATH
934 for (const StringRef &path : _file.rpaths) {
935 rpath_command *rpc = reinterpret_cast<rpath_command *>(lc);
Lang Hames2ed3bf92015-10-29 16:50:26 +0000936 uint32_t size = pointerAlign(sizeof(rpath_command) + path.size() + 1);
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000937 rpc->cmd = LC_RPATH;
938 rpc->cmdsize = size;
939 rpc->path = sizeof(rpath_command); // offset
940 if (_swap)
941 swapStruct(*rpc);
942 memcpy(lc+sizeof(rpath_command), path.begin(), path.size());
943 lc[sizeof(rpath_command)+path.size()] = '\0';
944 lc += size;
945 }
946
Nick Kledzik54ce29582014-10-28 22:21:10 +0000947 // Add LC_DATA_IN_CODE if needed.
948 if (_dataInCodeSize != 0) {
949 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
950 dl->cmd = LC_DATA_IN_CODE;
951 dl->cmdsize = sizeof(linkedit_data_command);
952 dl->dataoff = _startOfDataInCode;
953 dl->datasize = _dataInCodeSize;
954 if (_swap)
955 swapStruct(*dl);
956 lc += sizeof(linkedit_data_command);
957 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000958 }
959 return ec;
960}
961
Nick Kledzike34182f2013-11-06 21:36:55 +0000962void MachOFileLayout::writeSectionContent() {
963 for (const Section &s : _file.sections) {
964 // Copy all section content to output buffer.
Lang Hamesac2adce2015-12-11 23:25:09 +0000965 if (isZeroFillSection(s.type))
Nick Kledzik61fdef62014-05-15 20:59:23 +0000966 continue;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000967 if (s.content.empty())
968 continue;
Nick Kledzike34182f2013-11-06 21:36:55 +0000969 uint32_t offset = _sectInfo[&s].fileOffset;
970 uint8_t *p = &_buffer[offset];
971 memcpy(p, &s.content[0], s.content.size());
972 p += s.content.size();
973 }
974}
975
976void MachOFileLayout::writeRelocations() {
977 uint32_t relOffset = _startOfRelocations;
978 for (Section sect : _file.sections) {
979 for (Relocation r : sect.relocations) {
980 any_relocation_info* rb = reinterpret_cast<any_relocation_info*>(
981 &_buffer[relOffset]);
982 *rb = packRelocation(r, _swap, _bigEndianArch);
983 relOffset += sizeof(any_relocation_info);
984 }
985 }
986}
987
Nick Kledzike34182f2013-11-06 21:36:55 +0000988void MachOFileLayout::appendSymbols(const std::vector<Symbol> &symbols,
989 uint32_t &symOffset, uint32_t &strOffset) {
990 for (const Symbol &sym : symbols) {
991 if (_is64) {
992 nlist_64* nb = reinterpret_cast<nlist_64*>(&_buffer[symOffset]);
993 nb->n_strx = strOffset - _startOfSymbolStrings;
994 nb->n_type = sym.type | sym.scope;
995 nb->n_sect = sym.sect;
996 nb->n_desc = sym.desc;
997 nb->n_value = sym.value;
998 if (_swap)
999 swapStruct(*nb);
1000 symOffset += sizeof(nlist_64);
1001 } else {
1002 nlist* nb = reinterpret_cast<nlist*>(&_buffer[symOffset]);
1003 nb->n_strx = strOffset - _startOfSymbolStrings;
1004 nb->n_type = sym.type | sym.scope;
1005 nb->n_sect = sym.sect;
1006 nb->n_desc = sym.desc;
1007 nb->n_value = sym.value;
1008 if (_swap)
1009 swapStruct(*nb);
1010 symOffset += sizeof(nlist);
1011 }
1012 memcpy(&_buffer[strOffset], sym.name.begin(), sym.name.size());
1013 strOffset += sym.name.size();
1014 _buffer[strOffset++] ='\0'; // Strings in table have nul terminator.
1015 }
1016}
1017
Nick Kledzik21921372014-07-24 23:06:56 +00001018void MachOFileLayout::writeDataInCodeInfo() {
1019 uint32_t offset = _startOfDataInCode;
1020 for (const DataInCode &entry : _file.dataInCode) {
1021 data_in_code_entry *dst = reinterpret_cast<data_in_code_entry*>(
1022 &_buffer[offset]);
1023 dst->offset = entry.offset;
1024 dst->length = entry.length;
1025 dst->kind = entry.kind;
1026 if (_swap)
1027 swapStruct(*dst);
1028 offset += sizeof(data_in_code_entry);
1029 }
1030}
1031
Nick Kledzike34182f2013-11-06 21:36:55 +00001032void MachOFileLayout::writeSymbolTable() {
1033 // Write symbol table and symbol strings in parallel.
1034 uint32_t symOffset = _startOfSymbols;
1035 uint32_t strOffset = _startOfSymbolStrings;
1036 _buffer[strOffset++] = '\0'; // Reserve n_strx offset of zero to mean no name.
1037 appendSymbols(_file.localSymbols, symOffset, strOffset);
1038 appendSymbols(_file.globalSymbols, symOffset, strOffset);
1039 appendSymbols(_file.undefinedSymbols, symOffset, strOffset);
1040 // Write indirect symbol table array.
1041 uint32_t *indirects = reinterpret_cast<uint32_t*>
1042 (&_buffer[_startOfIndirectSymbols]);
1043 if (_file.fileType == llvm::MachO::MH_OBJECT) {
1044 // Object files have sections in same order as input normalized file.
1045 for (const Section &section : _file.sections) {
1046 for (uint32_t index : section.indirectSymbols) {
1047 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +00001048 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +00001049 else
1050 *indirects++ = index;
1051 }
1052 }
1053 } else {
1054 // Final linked images must sort sections from normalized file.
1055 for (const Segment &seg : _file.segments) {
1056 SegExtraInfo &segInfo = _segInfo[&seg];
1057 for (const Section *section : segInfo.sections) {
1058 for (uint32_t index : section->indirectSymbols) {
1059 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +00001060 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +00001061 else
1062 *indirects++ = index;
1063 }
1064 }
1065 }
1066 }
1067}
1068
1069void MachOFileLayout::writeRebaseInfo() {
1070 memcpy(&_buffer[_startOfRebaseInfo], _rebaseInfo.bytes(), _rebaseInfo.size());
1071}
1072
1073void MachOFileLayout::writeBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001074 memcpy(&_buffer[_startOfBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +00001075 _bindingInfo.bytes(), _bindingInfo.size());
1076}
1077
1078void MachOFileLayout::writeLazyBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001079 memcpy(&_buffer[_startOfLazyBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +00001080 _lazyBindingInfo.bytes(), _lazyBindingInfo.size());
1081}
1082
Nick Kledzik141330a2014-09-03 19:52:50 +00001083void MachOFileLayout::writeExportInfo() {
1084 memcpy(&_buffer[_startOfExportTrie], _exportTrie.bytes(), _exportTrie.size());
1085}
1086
Nick Kledzike34182f2013-11-06 21:36:55 +00001087void MachOFileLayout::buildLinkEditInfo() {
1088 buildRebaseInfo();
1089 buildBindInfo();
1090 buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +00001091 buildExportTrie();
Nick Kledzike34182f2013-11-06 21:36:55 +00001092 computeSymbolTableSizes();
Nick Kledzik21921372014-07-24 23:06:56 +00001093 computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +00001094}
1095
1096void MachOFileLayout::buildSectionRelocations() {
1097
1098}
1099
1100void MachOFileLayout::buildRebaseInfo() {
1101 // TODO: compress rebasing info.
1102 for (const RebaseLocation& entry : _file.rebasingInfo) {
1103 _rebaseInfo.append_byte(REBASE_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001104 _rebaseInfo.append_byte(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001105 | entry.segIndex);
1106 _rebaseInfo.append_uleb128(entry.segOffset);
1107 _rebaseInfo.append_uleb128(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 1);
1108 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001109 _rebaseInfo.append_byte(REBASE_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001110 _rebaseInfo.align(_is64 ? 8 : 4);
1111}
1112
1113void MachOFileLayout::buildBindInfo() {
1114 // TODO: compress bind info.
Nick Kledzikf373c772014-11-11 01:31:18 +00001115 uint64_t lastAddend = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +00001116 for (const BindLocation& entry : _file.bindingInfo) {
1117 _bindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001118 _bindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001119 | entry.segIndex);
1120 _bindingInfo.append_uleb128(entry.segOffset);
Lang Hames5c692002015-09-28 20:25:14 +00001121 if (entry.ordinal > 0)
1122 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
1123 (entry.ordinal & 0xF));
1124 else
1125 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1126 (entry.ordinal & 0xF));
Nick Kledzike34182f2013-11-06 21:36:55 +00001127 _bindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1128 _bindingInfo.append_string(entry.symbolName);
Nick Kledzikf373c772014-11-11 01:31:18 +00001129 if (entry.addend != lastAddend) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001130 _bindingInfo.append_byte(BIND_OPCODE_SET_ADDEND_SLEB);
1131 _bindingInfo.append_sleb128(entry.addend);
Nick Kledzikf373c772014-11-11 01:31:18 +00001132 lastAddend = entry.addend;
Nick Kledzike34182f2013-11-06 21:36:55 +00001133 }
1134 _bindingInfo.append_byte(BIND_OPCODE_DO_BIND);
1135 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001136 _bindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001137 _bindingInfo.align(_is64 ? 8 : 4);
1138}
1139
1140void MachOFileLayout::buildLazyBindInfo() {
1141 for (const BindLocation& entry : _file.lazyBindingInfo) {
1142 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001143 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001144 | entry.segIndex);
Nick Kledzikf373c772014-11-11 01:31:18 +00001145 _lazyBindingInfo.append_uleb128Fixed(entry.segOffset, 5);
Lang Hames5c692002015-09-28 20:25:14 +00001146 if (entry.ordinal > 0)
1147 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
1148 (entry.ordinal & 0xF));
1149 else
1150 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1151 (entry.ordinal & 0xF));
Nick Kledzike34182f2013-11-06 21:36:55 +00001152 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1153 _lazyBindingInfo.append_string(entry.symbolName);
1154 _lazyBindingInfo.append_byte(BIND_OPCODE_DO_BIND);
Nick Kledzikf373c772014-11-11 01:31:18 +00001155 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001156 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001157 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001158 _lazyBindingInfo.align(_is64 ? 8 : 4);
1159}
1160
Pete Coopere420dd42016-01-25 21:50:54 +00001161void TrieNode::addSymbol(const Export& entry,
1162 BumpPtrAllocator &allocator,
1163 std::vector<TrieNode*> &allNodes) {
Nick Kledzik141330a2014-09-03 19:52:50 +00001164 StringRef partialStr = entry.name.drop_front(_cummulativeString.size());
1165 for (TrieEdge &edge : _children) {
1166 StringRef edgeStr = edge._subString;
1167 if (partialStr.startswith(edgeStr)) {
1168 // Already have matching edge, go down that path.
1169 edge._child->addSymbol(entry, allocator, allNodes);
1170 return;
1171 }
1172 // See if string has commmon prefix with existing edge.
1173 for (int n=edgeStr.size()-1; n > 0; --n) {
1174 if (partialStr.substr(0, n).equals(edgeStr.substr(0, n))) {
1175 // Splice in new node: was A -> C, now A -> B -> C
1176 StringRef bNodeStr = edge._child->_cummulativeString;
1177 bNodeStr = bNodeStr.drop_back(edgeStr.size()-n).copy(allocator);
Eugene Zelenko41547942015-11-10 22:37:38 +00001178 auto *bNode = new (allocator) TrieNode(bNodeStr);
Nick Kledzik141330a2014-09-03 19:52:50 +00001179 allNodes.push_back(bNode);
1180 TrieNode* cNode = edge._child;
1181 StringRef abEdgeStr = edgeStr.substr(0,n).copy(allocator);
1182 StringRef bcEdgeStr = edgeStr.substr(n).copy(allocator);
1183 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1184 << "splice in TrieNode('" << bNodeStr
1185 << "') between edge '"
1186 << abEdgeStr << "' and edge='"
1187 << bcEdgeStr<< "'\n");
1188 TrieEdge& abEdge = edge;
1189 abEdge._subString = abEdgeStr;
1190 abEdge._child = bNode;
Eugene Zelenko41547942015-11-10 22:37:38 +00001191 auto *bcEdge = new (allocator) TrieEdge(bcEdgeStr, cNode);
Pete Coopere420dd42016-01-25 21:50:54 +00001192 bNode->_children.insert(bNode->_children.end(), bcEdge);
Nick Kledzik141330a2014-09-03 19:52:50 +00001193 bNode->addSymbol(entry, allocator, allNodes);
1194 return;
1195 }
1196 }
1197 }
1198 if (entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1199 assert(entry.otherOffset != 0);
1200 }
1201 if (entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
1202 assert(entry.otherOffset != 0);
1203 }
1204 // No commonality with any existing child, make a new edge.
Eugene Zelenko41547942015-11-10 22:37:38 +00001205 auto *newNode = new (allocator) TrieNode(entry.name.copy(allocator));
1206 auto *newEdge = new (allocator) TrieEdge(partialStr, newNode);
Pete Coopere420dd42016-01-25 21:50:54 +00001207 _children.insert(_children.end(), newEdge);
Nick Kledzik141330a2014-09-03 19:52:50 +00001208 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1209 << "new TrieNode('" << entry.name << "') with edge '"
1210 << partialStr << "' from node='"
1211 << _cummulativeString << "'\n");
1212 newNode->_address = entry.offset;
1213 newNode->_flags = entry.flags | entry.kind;
1214 newNode->_other = entry.otherOffset;
1215 if ((entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) && !entry.otherName.empty())
1216 newNode->_importedName = entry.otherName.copy(allocator);
1217 newNode->_hasExportInfo = true;
1218 allNodes.push_back(newNode);
1219}
1220
Pete Coopere420dd42016-01-25 21:50:54 +00001221bool TrieNode::updateOffset(uint32_t& offset) {
Nick Kledzik141330a2014-09-03 19:52:50 +00001222 uint32_t nodeSize = 1; // Length when no export info
1223 if (_hasExportInfo) {
1224 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1225 nodeSize = llvm::getULEB128Size(_flags);
1226 nodeSize += llvm::getULEB128Size(_other); // Other contains ordinal.
1227 nodeSize += _importedName.size();
1228 ++nodeSize; // Trailing zero in imported name.
1229 } else {
1230 nodeSize = llvm::getULEB128Size(_flags) + llvm::getULEB128Size(_address);
1231 if (_flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1232 nodeSize += llvm::getULEB128Size(_other);
1233 }
1234 // Overall node size so far is uleb128 of export info + actual export info.
1235 nodeSize += llvm::getULEB128Size(nodeSize);
1236 }
1237 // Compute size of all child edges.
1238 ++nodeSize; // Byte for number of chidren.
1239 for (TrieEdge &edge : _children) {
1240 nodeSize += edge._subString.size() + 1 // String length.
1241 + llvm::getULEB128Size(edge._child->_trieOffset); // Offset len.
1242 }
1243 // On input, 'offset' is new prefered location for this node.
1244 bool result = (_trieOffset != offset);
1245 // Store new location in node object for use by parents.
1246 _trieOffset = offset;
1247 // Update offset for next iteration.
1248 offset += nodeSize;
1249 // Return true if _trieOffset was changed.
1250 return result;
1251}
1252
Pete Coopere420dd42016-01-25 21:50:54 +00001253void TrieNode::appendToByteBuffer(ByteBuffer &out) {
Nick Kledzik141330a2014-09-03 19:52:50 +00001254 if (_hasExportInfo) {
1255 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1256 if (!_importedName.empty()) {
1257 // nodes with re-export info: size, flags, ordinal, import-name
1258 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1259 + llvm::getULEB128Size(_other)
1260 + _importedName.size() + 1;
1261 assert(nodeSize < 256);
1262 out.append_byte(nodeSize);
1263 out.append_uleb128(_flags);
1264 out.append_uleb128(_other);
1265 out.append_string(_importedName);
1266 } else {
1267 // nodes without re-export info: size, flags, ordinal, empty-string
1268 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1269 + llvm::getULEB128Size(_other) + 1;
1270 assert(nodeSize < 256);
1271 out.append_byte(nodeSize);
1272 out.append_uleb128(_flags);
1273 out.append_uleb128(_other);
1274 out.append_byte(0);
1275 }
1276 } else if ( _flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) {
1277 // Nodes with export info: size, flags, address, other
1278 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1279 + llvm::getULEB128Size(_address)
1280 + llvm::getULEB128Size(_other);
1281 assert(nodeSize < 256);
1282 out.append_byte(nodeSize);
1283 out.append_uleb128(_flags);
1284 out.append_uleb128(_address);
1285 out.append_uleb128(_other);
1286 } else {
1287 // Nodes with export info: size, flags, address
1288 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1289 + llvm::getULEB128Size(_address);
1290 assert(nodeSize < 256);
1291 out.append_byte(nodeSize);
1292 out.append_uleb128(_flags);
1293 out.append_uleb128(_address);
1294 }
1295 } else {
1296 // Node with no export info.
1297 uint32_t nodeSize = 0;
1298 out.append_byte(nodeSize);
1299 }
1300 // Add number of children.
1301 assert(_children.size() < 256);
1302 out.append_byte(_children.size());
1303 // Append each child edge substring and node offset.
1304 for (TrieEdge &edge : _children) {
1305 out.append_string(edge._subString);
1306 out.append_uleb128(edge._child->_trieOffset);
1307 }
1308}
1309
1310void MachOFileLayout::buildExportTrie() {
1311 if (_file.exportInfo.empty())
1312 return;
1313
1314 // For all temporary strings and objects used building trie.
1315 BumpPtrAllocator allocator;
1316
1317 // Build trie of all exported symbols.
Eugene Zelenko41547942015-11-10 22:37:38 +00001318 auto *rootNode = new (allocator) TrieNode(StringRef());
Nick Kledzik141330a2014-09-03 19:52:50 +00001319 std::vector<TrieNode*> allNodes;
1320 allNodes.reserve(_file.exportInfo.size()*2);
1321 allNodes.push_back(rootNode);
1322 for (const Export& entry : _file.exportInfo) {
1323 rootNode->addSymbol(entry, allocator, allNodes);
1324 }
1325
1326 // Assign each node in the vector an offset in the trie stream, iterating
1327 // until all uleb128 sizes have stabilized.
1328 bool more;
1329 do {
1330 uint32_t offset = 0;
1331 more = false;
1332 for (TrieNode* node : allNodes) {
1333 if (node->updateOffset(offset))
1334 more = true;
1335 }
1336 } while (more);
1337
1338 // Serialize trie to ByteBuffer.
1339 for (TrieNode* node : allNodes) {
1340 node->appendToByteBuffer(_exportTrie);
1341 }
1342 _exportTrie.align(_is64 ? 8 : 4);
1343}
1344
Nick Kledzike34182f2013-11-06 21:36:55 +00001345void MachOFileLayout::computeSymbolTableSizes() {
1346 // MachO symbol tables have three ranges: locals, globals, and undefines
1347 const size_t nlistSize = (_is64 ? sizeof(nlist_64) : sizeof(nlist));
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001348 _symbolTableSize = nlistSize * (_file.localSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +00001349 + _file.globalSymbols.size()
1350 + _file.undefinedSymbols.size());
Lang Hames201c08f2015-12-10 00:12:24 +00001351 _symbolStringPoolSize = 1; // Always reserve 1-byte for the empty string.
Nick Kledzike34182f2013-11-06 21:36:55 +00001352 for (const Symbol &sym : _file.localSymbols) {
1353 _symbolStringPoolSize += (sym.name.size()+1);
1354 }
1355 for (const Symbol &sym : _file.globalSymbols) {
1356 _symbolStringPoolSize += (sym.name.size()+1);
1357 }
1358 for (const Symbol &sym : _file.undefinedSymbols) {
1359 _symbolStringPoolSize += (sym.name.size()+1);
1360 }
1361 _symbolTableLocalsStartIndex = 0;
1362 _symbolTableGlobalsStartIndex = _file.localSymbols.size();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001363 _symbolTableUndefinesStartIndex = _symbolTableGlobalsStartIndex
Nick Kledzike34182f2013-11-06 21:36:55 +00001364 + _file.globalSymbols.size();
1365
1366 _indirectSymbolTableCount = 0;
1367 for (const Section &sect : _file.sections) {
1368 _indirectSymbolTableCount += sect.indirectSymbols.size();
1369 }
1370}
1371
Nick Kledzik21921372014-07-24 23:06:56 +00001372void MachOFileLayout::computeDataInCodeSize() {
1373 _dataInCodeSize = _file.dataInCode.size() * sizeof(data_in_code_entry);
1374}
Nick Kledzike34182f2013-11-06 21:36:55 +00001375
1376void MachOFileLayout::writeLinkEditContent() {
1377 if (_file.fileType == llvm::MachO::MH_OBJECT) {
1378 writeRelocations();
Nick Kledzik21921372014-07-24 23:06:56 +00001379 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001380 writeSymbolTable();
1381 } else {
1382 writeRebaseInfo();
1383 writeBindingInfo();
1384 writeLazyBindingInfo();
1385 // TODO: add weak binding info
Nick Kledzik141330a2014-09-03 19:52:50 +00001386 writeExportInfo();
Nick Kledzik54ce29582014-10-28 22:21:10 +00001387 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001388 writeSymbolTable();
1389 }
1390}
1391
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001392std::error_code MachOFileLayout::writeBinary(StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001393 // Check for pending error from constructor.
1394 if (_ec)
1395 return _ec;
1396 // Create FileOutputBuffer with calculated size.
Nick Kledzike34182f2013-11-06 21:36:55 +00001397 unsigned flags = 0;
1398 if (_file.fileType != llvm::MachO::MH_OBJECT)
1399 flags = llvm::FileOutputBuffer::F_executable;
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001400 ErrorOr<std::unique_ptr<llvm::FileOutputBuffer>> fobOrErr =
1401 llvm::FileOutputBuffer::create(path, size(), flags);
1402 if (std::error_code ec = fobOrErr.getError())
Nick Kledzike34182f2013-11-06 21:36:55 +00001403 return ec;
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001404 std::unique_ptr<llvm::FileOutputBuffer> &fob = *fobOrErr;
Nick Kledzike34182f2013-11-06 21:36:55 +00001405 // Write content.
1406 _buffer = fob->getBufferStart();
1407 writeMachHeader();
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001408 std::error_code ec = writeLoadCommands();
Nick Kledzike34182f2013-11-06 21:36:55 +00001409 if (ec)
1410 return ec;
1411 writeSectionContent();
1412 writeLinkEditContent();
1413 fob->commit();
1414
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001415 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +00001416}
1417
Nick Kledzike34182f2013-11-06 21:36:55 +00001418/// Takes in-memory normalized view and writes a mach-o object file.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001419std::error_code writeBinary(const NormalizedFile &file, StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001420 MachOFileLayout layout(file);
1421 return layout.writeBinary(path);
1422}
1423
Nick Kledzike34182f2013-11-06 21:36:55 +00001424} // namespace normalized
1425} // namespace mach_o
1426} // namespace lld