blob: 4fc989f031f0453a977562655ff92f355053f9b2 [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
Nick Kledzike34182f2013-11-06 21:36:55 +0000453 // If main executable add LC_LOAD_DYLINKER and LC_MAIN
454 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
455 size += pointerAlign(sizeof(dylinker_command) + dyldPath().size()+1);
456 ++count;
457 size += sizeof(entry_point_command);
458 ++count;
459 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000460
Nick Kledzike34182f2013-11-06 21:36:55 +0000461 // Add LC_LOAD_DYLIB for each dependent dylib.
462 for (const DependentDylib &dep : _file.dependentDylibs) {
463 size += sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
464 ++count;
465 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000466
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000467 // Add LC_RPATH
468 for (const StringRef &path : _file.rpaths) {
Lang Hames2ed3bf92015-10-29 16:50:26 +0000469 size += pointerAlign(sizeof(rpath_command) + path.size() + 1);
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000470 ++count;
471 }
472
Nick Kledzik54ce29582014-10-28 22:21:10 +0000473 // Add LC_DATA_IN_CODE if needed
474 if (!_file.dataInCode.empty()) {
475 size += sizeof(linkedit_data_command);
476 ++count;
477 }
478
Nick Kledzike34182f2013-11-06 21:36:55 +0000479 return size;
480}
481
482static bool overlaps(const Segment &s1, const Segment &s2) {
483 if (s2.address >= s1.address+s1.size)
484 return false;
485 if (s1.address >= s2.address+s2.size)
486 return false;
487 return true;
488}
489
490static bool overlaps(const Section &s1, const Section &s2) {
491 if (s2.address >= s1.address+s1.content.size())
492 return false;
493 if (s1.address >= s2.address+s2.content.size())
494 return false;
495 return true;
496}
497
498void MachOFileLayout::buildFileOffsets() {
499 // Verify no segments overlap
500 for (const Segment &sg1 : _file.segments) {
501 for (const Segment &sg2 : _file.segments) {
502 if (&sg1 == &sg2)
503 continue;
504 if (overlaps(sg1,sg2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000505 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000506 return;
507 }
508 }
509 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000510
511 // Verify no sections overlap
Nick Kledzike34182f2013-11-06 21:36:55 +0000512 for (const Section &s1 : _file.sections) {
513 for (const Section &s2 : _file.sections) {
514 if (&s1 == &s2)
515 continue;
516 if (overlaps(s1,s2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000517 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000518 return;
519 }
520 }
521 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000522
Nick Kledzike34182f2013-11-06 21:36:55 +0000523 // Build side table of extra info about segments and sections.
524 SegExtraInfo t;
525 t.fileOffset = 0;
526 for (const Segment &sg : _file.segments) {
527 _segInfo[&sg] = t;
528 }
529 SectionExtraInfo t2;
530 t2.fileOffset = 0;
531 // Assign sections to segments.
532 for (const Section &s : _file.sections) {
533 _sectInfo[&s] = t2;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000534 bool foundSegment = false;
Nick Kledzike34182f2013-11-06 21:36:55 +0000535 for (const Segment &sg : _file.segments) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000536 if (sg.name.equals(s.segmentName)) {
537 if ((s.address >= sg.address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000538 && (s.address+s.content.size() <= sg.address+sg.size)) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000539 _segInfo[&sg].sections.push_back(&s);
540 foundSegment = true;
541 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000542 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000543 }
544 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000545 if (!foundSegment) {
546 _ec = make_error_code(llvm::errc::executable_format_error);
547 return;
548 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000549 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000550
Nick Kledzike34182f2013-11-06 21:36:55 +0000551 // Assign file offsets.
552 uint32_t fileOffset = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000553 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000554 llvm::dbgs() << "buildFileOffsets()\n");
555 for (const Segment &sg : _file.segments) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000556 _segInfo[&sg].fileOffset = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000557 if ((_seg1addr == INT64_MAX) && sg.access)
558 _seg1addr = sg.address;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000559 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000560 llvm::dbgs() << " segment=" << sg.name
561 << ", fileOffset=" << _segInfo[&sg].fileOffset << "\n");
Tim Northover08d6a7b2014-06-30 09:49:30 +0000562
563 uint32_t segFileSize = 0;
Nick Kledzik761d6542014-10-24 22:19:22 +0000564 // A segment that is not zero-fill must use a least one page of disk space.
565 if (sg.access)
566 segFileSize = _file.pageSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000567 for (const Section *s : _segInfo[&sg].sections) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000568 uint32_t sectOffset = s->address - sg.address;
569 uint32_t sectFileSize =
Lang Hamesac2adce2015-12-11 23:25:09 +0000570 isZeroFillSection(s->type) ? 0 : s->content.size();
Tim Northover08d6a7b2014-06-30 09:49:30 +0000571 segFileSize = std::max(segFileSize, sectOffset + sectFileSize);
572
573 _sectInfo[s].fileOffset = _segInfo[&sg].fileOffset + sectOffset;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000574 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000575 llvm::dbgs() << " section=" << s->sectionName
576 << ", fileOffset=" << fileOffset << "\n");
577 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000578
Rui Ueyama489a8062016-01-14 20:53:50 +0000579 _segInfo[&sg].fileSize = llvm::alignTo(segFileSize, _file.pageSize);
580 fileOffset = llvm::alignTo(fileOffset + segFileSize, _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000581 _addressOfLinkEdit = sg.address + sg.size;
582 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000583 _startOfLinkEdit = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000584}
585
Nick Kledzike34182f2013-11-06 21:36:55 +0000586size_t MachOFileLayout::size() const {
587 return _endOfSymbolStrings;
588}
589
590void MachOFileLayout::writeMachHeader() {
591 mach_header *mh = reinterpret_cast<mach_header*>(_buffer);
592 mh->magic = _is64 ? llvm::MachO::MH_MAGIC_64 : llvm::MachO::MH_MAGIC;
593 mh->cputype = MachOLinkingContext::cpuTypeFromArch(_file.arch);
594 mh->cpusubtype = MachOLinkingContext::cpuSubtypeFromArch(_file.arch);
595 mh->filetype = _file.fileType;
596 mh->ncmds = _countOfLoadCommands;
597 mh->sizeofcmds = _endOfLoadCommands - _startOfLoadCommands;
598 mh->flags = _file.flags;
599 if (_swap)
600 swapStruct(*mh);
601}
602
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000603uint32_t MachOFileLayout::indirectSymbolIndex(const Section &sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000604 uint32_t &index) {
605 if (sect.indirectSymbols.empty())
606 return 0;
607 uint32_t result = index;
608 index += sect.indirectSymbols.size();
609 return result;
610}
611
612uint32_t MachOFileLayout::indirectSymbolElementSize(const Section &sect) {
613 if (sect.indirectSymbols.empty())
614 return 0;
615 if (sect.type != S_SYMBOL_STUBS)
616 return 0;
617 return sect.content.size() / sect.indirectSymbols.size();
618}
619
Nick Kledzik29f749e2013-11-09 00:07:28 +0000620template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000621std::error_code MachOFileLayout::writeSingleSegmentLoadCommand(uint8_t *&lc) {
Nick Kledzik29f749e2013-11-09 00:07:28 +0000622 typename T::command* seg = reinterpret_cast<typename T::command*>(lc);
623 seg->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000624 seg->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000625 + _file.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000626 uint8_t *next = lc + seg->cmdsize;
627 memset(seg->segname, 0, 16);
628 seg->vmaddr = 0;
Nick Kledzikb072c362014-11-18 00:30:29 +0000629 seg->vmsize = _file.sections.back().address
630 + _file.sections.back().content.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000631 seg->fileoff = _endOfLoadCommands;
632 seg->filesize = seg->vmsize;
633 seg->maxprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
634 seg->initprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
635 seg->nsects = _file.sections.size();
636 seg->flags = 0;
637 if (_swap)
638 swapStruct(*seg);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000639 typename T::section *sout = reinterpret_cast<typename T::section*>
640 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000641 uint32_t relOffset = _startOfRelocations;
Nick Kledzike34182f2013-11-06 21:36:55 +0000642 uint32_t indirectSymRunningIndex = 0;
643 for (const Section &sin : _file.sections) {
644 setString16(sin.sectionName, sout->sectname);
645 setString16(sin.segmentName, sout->segname);
646 sout->addr = sin.address;
647 sout->size = sin.content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000648 sout->offset = _sectInfo[&sin].fileOffset;
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000649 sout->align = llvm::Log2_32(sin.alignment);
Nick Kledzike34182f2013-11-06 21:36:55 +0000650 sout->reloff = sin.relocations.empty() ? 0 : relOffset;
651 sout->nreloc = sin.relocations.size();
652 sout->flags = sin.type | sin.attributes;
653 sout->reserved1 = indirectSymbolIndex(sin, indirectSymRunningIndex);
654 sout->reserved2 = indirectSymbolElementSize(sin);
655 relOffset += sin.relocations.size() * sizeof(any_relocation_info);
Nick Kledzike34182f2013-11-06 21:36:55 +0000656 if (_swap)
657 swapStruct(*sout);
658 ++sout;
659 }
660 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000661 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000662}
663
Nick Kledzik29f749e2013-11-09 00:07:28 +0000664template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000665std::error_code MachOFileLayout::writeSegmentLoadCommands(uint8_t *&lc) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000666 uint32_t indirectSymRunningIndex = 0;
667 for (const Segment &seg : _file.segments) {
668 // Write segment command with trailing sections.
669 SegExtraInfo &segInfo = _segInfo[&seg];
Nick Kledzik29f749e2013-11-09 00:07:28 +0000670 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
671 cmd->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000672 cmd->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000673 + segInfo.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000674 uint8_t *next = lc + cmd->cmdsize;
675 setString16(seg.name, cmd->segname);
676 cmd->vmaddr = seg.address;
677 cmd->vmsize = seg.size;
678 cmd->fileoff = segInfo.fileOffset;
Tim Northover08d6a7b2014-06-30 09:49:30 +0000679 cmd->filesize = segInfo.fileSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000680 cmd->maxprot = seg.access;
681 cmd->initprot = seg.access;
682 cmd->nsects = segInfo.sections.size();
683 cmd->flags = 0;
684 if (_swap)
685 swapStruct(*cmd);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000686 typename T::section *sect = reinterpret_cast<typename T::section*>
687 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000688 for (const Section *section : segInfo.sections) {
689 setString16(section->sectionName, sect->sectname);
690 setString16(section->segmentName, sect->segname);
691 sect->addr = section->address;
692 sect->size = section->content.size();
Lang Hamesac2adce2015-12-11 23:25:09 +0000693 if (isZeroFillSection(section->type))
Nick Kledzikb072c362014-11-18 00:30:29 +0000694 sect->offset = 0;
695 else
696 sect->offset = section->address - seg.address + segInfo.fileOffset;
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000697 sect->align = llvm::Log2_32(section->alignment);
Nick Kledzike34182f2013-11-06 21:36:55 +0000698 sect->reloff = 0;
699 sect->nreloc = 0;
700 sect->flags = section->type | section->attributes;
701 sect->reserved1 = indirectSymbolIndex(*section, indirectSymRunningIndex);
702 sect->reserved2 = indirectSymbolElementSize(*section);
703 if (_swap)
704 swapStruct(*sect);
705 ++sect;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000706 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000707 lc = reinterpret_cast<uint8_t*>(next);
708 }
709 // Add implicit __LINKEDIT segment
Nick Kledzik1bebb282014-09-09 23:52:59 +0000710 size_t linkeditSize = _endOfLinkEdit - _startOfLinkEdit;
Nick Kledzik29f749e2013-11-09 00:07:28 +0000711 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
712 cmd->cmd = T::LC;
713 cmd->cmdsize = sizeof(typename T::command);
Nick Kledzike34182f2013-11-06 21:36:55 +0000714 uint8_t *next = lc + cmd->cmdsize;
715 setString16("__LINKEDIT", cmd->segname);
716 cmd->vmaddr = _addressOfLinkEdit;
Rui Ueyama489a8062016-01-14 20:53:50 +0000717 cmd->vmsize = llvm::alignTo(linkeditSize, _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000718 cmd->fileoff = _startOfLinkEdit;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000719 cmd->filesize = linkeditSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000720 cmd->maxprot = VM_PROT_READ;
721 cmd->initprot = VM_PROT_READ;
722 cmd->nsects = 0;
723 cmd->flags = 0;
724 if (_swap)
725 swapStruct(*cmd);
726 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000727 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000728}
729
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000730std::error_code MachOFileLayout::writeLoadCommands() {
731 std::error_code ec;
Nick Kledzike34182f2013-11-06 21:36:55 +0000732 uint8_t *lc = &_buffer[_startOfLoadCommands];
733 if (_file.fileType == llvm::MachO::MH_OBJECT) {
734 // Object files have one unnamed segment which holds all sections.
735 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000736 ec = writeSingleSegmentLoadCommand<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000737 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000738 ec = writeSingleSegmentLoadCommand<MachO32Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000739 // Add LC_SYMTAB with symbol table info
740 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
741 st->cmd = LC_SYMTAB;
742 st->cmdsize = sizeof(symtab_command);
743 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000744 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000745 + _file.undefinedSymbols.size();
746 st->stroff = _startOfSymbolStrings;
747 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
748 if (_swap)
749 swapStruct(*st);
Nick Kledzik21921372014-07-24 23:06:56 +0000750 lc += sizeof(symtab_command);
751 // Add LC_DATA_IN_CODE if needed.
752 if (_dataInCodeSize != 0) {
753 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
754 dl->cmd = LC_DATA_IN_CODE;
755 dl->cmdsize = sizeof(linkedit_data_command);
756 dl->dataoff = _startOfDataInCode;
757 dl->datasize = _dataInCodeSize;
758 if (_swap)
759 swapStruct(*dl);
760 lc += sizeof(linkedit_data_command);
761 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000762 } else {
763 // Final linked images have sections under segments.
764 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000765 ec = writeSegmentLoadCommands<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000766 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000767 ec = writeSegmentLoadCommands<MachO32Trait>(lc);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000768
Tim Northover301c4e62014-07-01 08:15:41 +0000769 // Add LC_ID_DYLIB command for dynamic libraries.
770 if (_file.fileType == llvm::MachO::MH_DYLIB) {
771 dylib_command *dc = reinterpret_cast<dylib_command*>(lc);
772 StringRef path = _file.installName;
773 uint32_t size = sizeof(dylib_command) + pointerAlign(path.size() + 1);
774 dc->cmd = LC_ID_DYLIB;
775 dc->cmdsize = size;
776 dc->dylib.name = sizeof(dylib_command); // offset
Jean-Daniel Dupasedefccc2014-12-20 09:22:56 +0000777 // needs to be some constant value different than the one in LC_LOAD_DYLIB
778 dc->dylib.timestamp = 1;
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000779 dc->dylib.current_version = _file.currentVersion;
780 dc->dylib.compatibility_version = _file.compatVersion;
Tim Northover301c4e62014-07-01 08:15:41 +0000781 if (_swap)
782 swapStruct(*dc);
783 memcpy(lc + sizeof(dylib_command), path.begin(), path.size());
784 lc[sizeof(dylib_command) + path.size()] = '\0';
785 lc += size;
786 }
787
Nick Kledzike34182f2013-11-06 21:36:55 +0000788 // Add LC_DYLD_INFO_ONLY.
789 dyld_info_command* di = reinterpret_cast<dyld_info_command*>(lc);
790 di->cmd = LC_DYLD_INFO_ONLY;
791 di->cmdsize = sizeof(dyld_info_command);
792 di->rebase_off = _rebaseInfo.size() ? _startOfRebaseInfo : 0;
793 di->rebase_size = _rebaseInfo.size();
794 di->bind_off = _bindingInfo.size() ? _startOfBindingInfo : 0;
795 di->bind_size = _bindingInfo.size();
796 di->weak_bind_off = 0;
797 di->weak_bind_size = 0;
798 di->lazy_bind_off = _lazyBindingInfo.size() ? _startOfLazyBindingInfo : 0;
799 di->lazy_bind_size = _lazyBindingInfo.size();
Nick Kledzik141330a2014-09-03 19:52:50 +0000800 di->export_off = _exportTrie.size() ? _startOfExportTrie : 0;
801 di->export_size = _exportTrie.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000802 if (_swap)
803 swapStruct(*di);
804 lc += sizeof(dyld_info_command);
805
806 // Add LC_SYMTAB with symbol table info.
807 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
808 st->cmd = LC_SYMTAB;
809 st->cmdsize = sizeof(symtab_command);
810 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000811 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000812 + _file.undefinedSymbols.size();
813 st->stroff = _startOfSymbolStrings;
814 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
815 if (_swap)
816 swapStruct(*st);
817 lc += sizeof(symtab_command);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000818
Nick Kledzike34182f2013-11-06 21:36:55 +0000819 // Add LC_DYSYMTAB
820 if (_file.fileType != llvm::MachO::MH_PRELOAD) {
821 dysymtab_command* dst = reinterpret_cast<dysymtab_command*>(lc);
822 dst->cmd = LC_DYSYMTAB;
823 dst->cmdsize = sizeof(dysymtab_command);
824 dst->ilocalsym = _symbolTableLocalsStartIndex;
825 dst->nlocalsym = _file.localSymbols.size();
826 dst->iextdefsym = _symbolTableGlobalsStartIndex;
827 dst->nextdefsym = _file.globalSymbols.size();
828 dst->iundefsym = _symbolTableUndefinesStartIndex;
829 dst->nundefsym = _file.undefinedSymbols.size();
830 dst->tocoff = 0;
831 dst->ntoc = 0;
832 dst->modtaboff = 0;
833 dst->nmodtab = 0;
834 dst->extrefsymoff = 0;
835 dst->nextrefsyms = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000836 dst->indirectsymoff = _startOfIndirectSymbols;
Nick Kledzike34182f2013-11-06 21:36:55 +0000837 dst->nindirectsyms = _indirectSymbolTableCount;
838 dst->extreloff = 0;
839 dst->nextrel = 0;
840 dst->locreloff = 0;
841 dst->nlocrel = 0;
842 if (_swap)
843 swapStruct(*dst);
844 lc += sizeof(dysymtab_command);
845 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000846
Nick Kledzike34182f2013-11-06 21:36:55 +0000847 // If main executable, add LC_LOAD_DYLINKER and LC_MAIN.
848 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
849 // Build LC_LOAD_DYLINKER load command.
850 uint32_t size=pointerAlign(sizeof(dylinker_command)+dyldPath().size()+1);
851 dylinker_command* dl = reinterpret_cast<dylinker_command*>(lc);
852 dl->cmd = LC_LOAD_DYLINKER;
853 dl->cmdsize = size;
854 dl->name = sizeof(dylinker_command); // offset
855 if (_swap)
856 swapStruct(*dl);
857 memcpy(lc+sizeof(dylinker_command), dyldPath().data(), dyldPath().size());
858 lc[sizeof(dylinker_command)+dyldPath().size()] = '\0';
859 lc += size;
860 // Build LC_MAIN load command.
861 entry_point_command* ep = reinterpret_cast<entry_point_command*>(lc);
862 ep->cmd = LC_MAIN;
863 ep->cmdsize = sizeof(entry_point_command);
864 ep->entryoff = _file.entryAddress - _seg1addr;
Lang Hames65a64c92015-05-20 22:10:50 +0000865 ep->stacksize = _file.stackSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000866 if (_swap)
867 swapStruct(*ep);
868 lc += sizeof(entry_point_command);
869 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000870
Nick Kledzike34182f2013-11-06 21:36:55 +0000871 // Add LC_LOAD_DYLIB commands
872 for (const DependentDylib &dep : _file.dependentDylibs) {
873 dylib_command* dc = reinterpret_cast<dylib_command*>(lc);
874 uint32_t size = sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
Nick Kledzik51720672014-10-16 19:31:28 +0000875 dc->cmd = dep.kind;
Nick Kledzike34182f2013-11-06 21:36:55 +0000876 dc->cmdsize = size;
877 dc->dylib.name = sizeof(dylib_command); // offset
Jean-Daniel Dupasedefccc2014-12-20 09:22:56 +0000878 // needs to be some constant value different than the one in LC_ID_DYLIB
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000879 dc->dylib.timestamp = 2;
880 dc->dylib.current_version = dep.currentVersion;
881 dc->dylib.compatibility_version = dep.compatVersion;
Nick Kledzike34182f2013-11-06 21:36:55 +0000882 if (_swap)
883 swapStruct(*dc);
884 memcpy(lc+sizeof(dylib_command), dep.path.begin(), dep.path.size());
885 lc[sizeof(dylib_command)+dep.path.size()] = '\0';
886 lc += size;
887 }
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000888
889 // Add LC_RPATH
890 for (const StringRef &path : _file.rpaths) {
891 rpath_command *rpc = reinterpret_cast<rpath_command *>(lc);
Lang Hames2ed3bf92015-10-29 16:50:26 +0000892 uint32_t size = pointerAlign(sizeof(rpath_command) + path.size() + 1);
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000893 rpc->cmd = LC_RPATH;
894 rpc->cmdsize = size;
895 rpc->path = sizeof(rpath_command); // offset
896 if (_swap)
897 swapStruct(*rpc);
898 memcpy(lc+sizeof(rpath_command), path.begin(), path.size());
899 lc[sizeof(rpath_command)+path.size()] = '\0';
900 lc += size;
901 }
902
Nick Kledzik54ce29582014-10-28 22:21:10 +0000903 // Add LC_DATA_IN_CODE if needed.
904 if (_dataInCodeSize != 0) {
905 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
906 dl->cmd = LC_DATA_IN_CODE;
907 dl->cmdsize = sizeof(linkedit_data_command);
908 dl->dataoff = _startOfDataInCode;
909 dl->datasize = _dataInCodeSize;
910 if (_swap)
911 swapStruct(*dl);
912 lc += sizeof(linkedit_data_command);
913 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000914 }
915 return ec;
916}
917
Nick Kledzike34182f2013-11-06 21:36:55 +0000918void MachOFileLayout::writeSectionContent() {
919 for (const Section &s : _file.sections) {
920 // Copy all section content to output buffer.
Lang Hamesac2adce2015-12-11 23:25:09 +0000921 if (isZeroFillSection(s.type))
Nick Kledzik61fdef62014-05-15 20:59:23 +0000922 continue;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000923 if (s.content.empty())
924 continue;
Nick Kledzike34182f2013-11-06 21:36:55 +0000925 uint32_t offset = _sectInfo[&s].fileOffset;
926 uint8_t *p = &_buffer[offset];
927 memcpy(p, &s.content[0], s.content.size());
928 p += s.content.size();
929 }
930}
931
932void MachOFileLayout::writeRelocations() {
933 uint32_t relOffset = _startOfRelocations;
934 for (Section sect : _file.sections) {
935 for (Relocation r : sect.relocations) {
936 any_relocation_info* rb = reinterpret_cast<any_relocation_info*>(
937 &_buffer[relOffset]);
938 *rb = packRelocation(r, _swap, _bigEndianArch);
939 relOffset += sizeof(any_relocation_info);
940 }
941 }
942}
943
Nick Kledzike34182f2013-11-06 21:36:55 +0000944void MachOFileLayout::appendSymbols(const std::vector<Symbol> &symbols,
945 uint32_t &symOffset, uint32_t &strOffset) {
946 for (const Symbol &sym : symbols) {
947 if (_is64) {
948 nlist_64* nb = reinterpret_cast<nlist_64*>(&_buffer[symOffset]);
949 nb->n_strx = strOffset - _startOfSymbolStrings;
950 nb->n_type = sym.type | sym.scope;
951 nb->n_sect = sym.sect;
952 nb->n_desc = sym.desc;
953 nb->n_value = sym.value;
954 if (_swap)
955 swapStruct(*nb);
956 symOffset += sizeof(nlist_64);
957 } else {
958 nlist* nb = reinterpret_cast<nlist*>(&_buffer[symOffset]);
959 nb->n_strx = strOffset - _startOfSymbolStrings;
960 nb->n_type = sym.type | sym.scope;
961 nb->n_sect = sym.sect;
962 nb->n_desc = sym.desc;
963 nb->n_value = sym.value;
964 if (_swap)
965 swapStruct(*nb);
966 symOffset += sizeof(nlist);
967 }
968 memcpy(&_buffer[strOffset], sym.name.begin(), sym.name.size());
969 strOffset += sym.name.size();
970 _buffer[strOffset++] ='\0'; // Strings in table have nul terminator.
971 }
972}
973
Nick Kledzik21921372014-07-24 23:06:56 +0000974void MachOFileLayout::writeDataInCodeInfo() {
975 uint32_t offset = _startOfDataInCode;
976 for (const DataInCode &entry : _file.dataInCode) {
977 data_in_code_entry *dst = reinterpret_cast<data_in_code_entry*>(
978 &_buffer[offset]);
979 dst->offset = entry.offset;
980 dst->length = entry.length;
981 dst->kind = entry.kind;
982 if (_swap)
983 swapStruct(*dst);
984 offset += sizeof(data_in_code_entry);
985 }
986}
987
Nick Kledzike34182f2013-11-06 21:36:55 +0000988void MachOFileLayout::writeSymbolTable() {
989 // Write symbol table and symbol strings in parallel.
990 uint32_t symOffset = _startOfSymbols;
991 uint32_t strOffset = _startOfSymbolStrings;
992 _buffer[strOffset++] = '\0'; // Reserve n_strx offset of zero to mean no name.
993 appendSymbols(_file.localSymbols, symOffset, strOffset);
994 appendSymbols(_file.globalSymbols, symOffset, strOffset);
995 appendSymbols(_file.undefinedSymbols, symOffset, strOffset);
996 // Write indirect symbol table array.
997 uint32_t *indirects = reinterpret_cast<uint32_t*>
998 (&_buffer[_startOfIndirectSymbols]);
999 if (_file.fileType == llvm::MachO::MH_OBJECT) {
1000 // Object files have sections in same order as input normalized file.
1001 for (const Section &section : _file.sections) {
1002 for (uint32_t index : section.indirectSymbols) {
1003 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +00001004 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +00001005 else
1006 *indirects++ = index;
1007 }
1008 }
1009 } else {
1010 // Final linked images must sort sections from normalized file.
1011 for (const Segment &seg : _file.segments) {
1012 SegExtraInfo &segInfo = _segInfo[&seg];
1013 for (const Section *section : segInfo.sections) {
1014 for (uint32_t index : section->indirectSymbols) {
1015 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +00001016 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +00001017 else
1018 *indirects++ = index;
1019 }
1020 }
1021 }
1022 }
1023}
1024
1025void MachOFileLayout::writeRebaseInfo() {
1026 memcpy(&_buffer[_startOfRebaseInfo], _rebaseInfo.bytes(), _rebaseInfo.size());
1027}
1028
1029void MachOFileLayout::writeBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001030 memcpy(&_buffer[_startOfBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +00001031 _bindingInfo.bytes(), _bindingInfo.size());
1032}
1033
1034void MachOFileLayout::writeLazyBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001035 memcpy(&_buffer[_startOfLazyBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +00001036 _lazyBindingInfo.bytes(), _lazyBindingInfo.size());
1037}
1038
Nick Kledzik141330a2014-09-03 19:52:50 +00001039void MachOFileLayout::writeExportInfo() {
1040 memcpy(&_buffer[_startOfExportTrie], _exportTrie.bytes(), _exportTrie.size());
1041}
1042
Nick Kledzike34182f2013-11-06 21:36:55 +00001043void MachOFileLayout::buildLinkEditInfo() {
1044 buildRebaseInfo();
1045 buildBindInfo();
1046 buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +00001047 buildExportTrie();
Nick Kledzike34182f2013-11-06 21:36:55 +00001048 computeSymbolTableSizes();
Nick Kledzik21921372014-07-24 23:06:56 +00001049 computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +00001050}
1051
1052void MachOFileLayout::buildSectionRelocations() {
1053
1054}
1055
1056void MachOFileLayout::buildRebaseInfo() {
1057 // TODO: compress rebasing info.
1058 for (const RebaseLocation& entry : _file.rebasingInfo) {
1059 _rebaseInfo.append_byte(REBASE_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001060 _rebaseInfo.append_byte(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001061 | entry.segIndex);
1062 _rebaseInfo.append_uleb128(entry.segOffset);
1063 _rebaseInfo.append_uleb128(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 1);
1064 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001065 _rebaseInfo.append_byte(REBASE_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001066 _rebaseInfo.align(_is64 ? 8 : 4);
1067}
1068
1069void MachOFileLayout::buildBindInfo() {
1070 // TODO: compress bind info.
Nick Kledzikf373c772014-11-11 01:31:18 +00001071 uint64_t lastAddend = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +00001072 for (const BindLocation& entry : _file.bindingInfo) {
1073 _bindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001074 _bindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001075 | entry.segIndex);
1076 _bindingInfo.append_uleb128(entry.segOffset);
Lang Hames5c692002015-09-28 20:25:14 +00001077 if (entry.ordinal > 0)
1078 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
1079 (entry.ordinal & 0xF));
1080 else
1081 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1082 (entry.ordinal & 0xF));
Nick Kledzike34182f2013-11-06 21:36:55 +00001083 _bindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1084 _bindingInfo.append_string(entry.symbolName);
Nick Kledzikf373c772014-11-11 01:31:18 +00001085 if (entry.addend != lastAddend) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001086 _bindingInfo.append_byte(BIND_OPCODE_SET_ADDEND_SLEB);
1087 _bindingInfo.append_sleb128(entry.addend);
Nick Kledzikf373c772014-11-11 01:31:18 +00001088 lastAddend = entry.addend;
Nick Kledzike34182f2013-11-06 21:36:55 +00001089 }
1090 _bindingInfo.append_byte(BIND_OPCODE_DO_BIND);
1091 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001092 _bindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001093 _bindingInfo.align(_is64 ? 8 : 4);
1094}
1095
1096void MachOFileLayout::buildLazyBindInfo() {
1097 for (const BindLocation& entry : _file.lazyBindingInfo) {
1098 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001099 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001100 | entry.segIndex);
Nick Kledzikf373c772014-11-11 01:31:18 +00001101 _lazyBindingInfo.append_uleb128Fixed(entry.segOffset, 5);
Lang Hames5c692002015-09-28 20:25:14 +00001102 if (entry.ordinal > 0)
1103 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
1104 (entry.ordinal & 0xF));
1105 else
1106 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1107 (entry.ordinal & 0xF));
Nick Kledzike34182f2013-11-06 21:36:55 +00001108 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1109 _lazyBindingInfo.append_string(entry.symbolName);
1110 _lazyBindingInfo.append_byte(BIND_OPCODE_DO_BIND);
Nick Kledzikf373c772014-11-11 01:31:18 +00001111 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001112 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001113 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001114 _lazyBindingInfo.align(_is64 ? 8 : 4);
1115}
1116
Pete Coopere420dd42016-01-25 21:50:54 +00001117void TrieNode::addSymbol(const Export& entry,
1118 BumpPtrAllocator &allocator,
1119 std::vector<TrieNode*> &allNodes) {
Nick Kledzik141330a2014-09-03 19:52:50 +00001120 StringRef partialStr = entry.name.drop_front(_cummulativeString.size());
1121 for (TrieEdge &edge : _children) {
1122 StringRef edgeStr = edge._subString;
1123 if (partialStr.startswith(edgeStr)) {
1124 // Already have matching edge, go down that path.
1125 edge._child->addSymbol(entry, allocator, allNodes);
1126 return;
1127 }
1128 // See if string has commmon prefix with existing edge.
1129 for (int n=edgeStr.size()-1; n > 0; --n) {
1130 if (partialStr.substr(0, n).equals(edgeStr.substr(0, n))) {
1131 // Splice in new node: was A -> C, now A -> B -> C
1132 StringRef bNodeStr = edge._child->_cummulativeString;
1133 bNodeStr = bNodeStr.drop_back(edgeStr.size()-n).copy(allocator);
Eugene Zelenko41547942015-11-10 22:37:38 +00001134 auto *bNode = new (allocator) TrieNode(bNodeStr);
Nick Kledzik141330a2014-09-03 19:52:50 +00001135 allNodes.push_back(bNode);
1136 TrieNode* cNode = edge._child;
1137 StringRef abEdgeStr = edgeStr.substr(0,n).copy(allocator);
1138 StringRef bcEdgeStr = edgeStr.substr(n).copy(allocator);
1139 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1140 << "splice in TrieNode('" << bNodeStr
1141 << "') between edge '"
1142 << abEdgeStr << "' and edge='"
1143 << bcEdgeStr<< "'\n");
1144 TrieEdge& abEdge = edge;
1145 abEdge._subString = abEdgeStr;
1146 abEdge._child = bNode;
Eugene Zelenko41547942015-11-10 22:37:38 +00001147 auto *bcEdge = new (allocator) TrieEdge(bcEdgeStr, cNode);
Pete Coopere420dd42016-01-25 21:50:54 +00001148 bNode->_children.insert(bNode->_children.end(), bcEdge);
Nick Kledzik141330a2014-09-03 19:52:50 +00001149 bNode->addSymbol(entry, allocator, allNodes);
1150 return;
1151 }
1152 }
1153 }
1154 if (entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1155 assert(entry.otherOffset != 0);
1156 }
1157 if (entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
1158 assert(entry.otherOffset != 0);
1159 }
1160 // No commonality with any existing child, make a new edge.
Eugene Zelenko41547942015-11-10 22:37:38 +00001161 auto *newNode = new (allocator) TrieNode(entry.name.copy(allocator));
1162 auto *newEdge = new (allocator) TrieEdge(partialStr, newNode);
Pete Coopere420dd42016-01-25 21:50:54 +00001163 _children.insert(_children.end(), newEdge);
Nick Kledzik141330a2014-09-03 19:52:50 +00001164 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1165 << "new TrieNode('" << entry.name << "') with edge '"
1166 << partialStr << "' from node='"
1167 << _cummulativeString << "'\n");
1168 newNode->_address = entry.offset;
1169 newNode->_flags = entry.flags | entry.kind;
1170 newNode->_other = entry.otherOffset;
1171 if ((entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) && !entry.otherName.empty())
1172 newNode->_importedName = entry.otherName.copy(allocator);
1173 newNode->_hasExportInfo = true;
1174 allNodes.push_back(newNode);
1175}
1176
Pete Coopere420dd42016-01-25 21:50:54 +00001177bool TrieNode::updateOffset(uint32_t& offset) {
Nick Kledzik141330a2014-09-03 19:52:50 +00001178 uint32_t nodeSize = 1; // Length when no export info
1179 if (_hasExportInfo) {
1180 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1181 nodeSize = llvm::getULEB128Size(_flags);
1182 nodeSize += llvm::getULEB128Size(_other); // Other contains ordinal.
1183 nodeSize += _importedName.size();
1184 ++nodeSize; // Trailing zero in imported name.
1185 } else {
1186 nodeSize = llvm::getULEB128Size(_flags) + llvm::getULEB128Size(_address);
1187 if (_flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1188 nodeSize += llvm::getULEB128Size(_other);
1189 }
1190 // Overall node size so far is uleb128 of export info + actual export info.
1191 nodeSize += llvm::getULEB128Size(nodeSize);
1192 }
1193 // Compute size of all child edges.
1194 ++nodeSize; // Byte for number of chidren.
1195 for (TrieEdge &edge : _children) {
1196 nodeSize += edge._subString.size() + 1 // String length.
1197 + llvm::getULEB128Size(edge._child->_trieOffset); // Offset len.
1198 }
1199 // On input, 'offset' is new prefered location for this node.
1200 bool result = (_trieOffset != offset);
1201 // Store new location in node object for use by parents.
1202 _trieOffset = offset;
1203 // Update offset for next iteration.
1204 offset += nodeSize;
1205 // Return true if _trieOffset was changed.
1206 return result;
1207}
1208
Pete Coopere420dd42016-01-25 21:50:54 +00001209void TrieNode::appendToByteBuffer(ByteBuffer &out) {
Nick Kledzik141330a2014-09-03 19:52:50 +00001210 if (_hasExportInfo) {
1211 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1212 if (!_importedName.empty()) {
1213 // nodes with re-export info: size, flags, ordinal, import-name
1214 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1215 + llvm::getULEB128Size(_other)
1216 + _importedName.size() + 1;
1217 assert(nodeSize < 256);
1218 out.append_byte(nodeSize);
1219 out.append_uleb128(_flags);
1220 out.append_uleb128(_other);
1221 out.append_string(_importedName);
1222 } else {
1223 // nodes without re-export info: size, flags, ordinal, empty-string
1224 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1225 + llvm::getULEB128Size(_other) + 1;
1226 assert(nodeSize < 256);
1227 out.append_byte(nodeSize);
1228 out.append_uleb128(_flags);
1229 out.append_uleb128(_other);
1230 out.append_byte(0);
1231 }
1232 } else if ( _flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) {
1233 // Nodes with export info: size, flags, address, other
1234 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1235 + llvm::getULEB128Size(_address)
1236 + llvm::getULEB128Size(_other);
1237 assert(nodeSize < 256);
1238 out.append_byte(nodeSize);
1239 out.append_uleb128(_flags);
1240 out.append_uleb128(_address);
1241 out.append_uleb128(_other);
1242 } else {
1243 // Nodes with export info: size, flags, address
1244 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1245 + llvm::getULEB128Size(_address);
1246 assert(nodeSize < 256);
1247 out.append_byte(nodeSize);
1248 out.append_uleb128(_flags);
1249 out.append_uleb128(_address);
1250 }
1251 } else {
1252 // Node with no export info.
1253 uint32_t nodeSize = 0;
1254 out.append_byte(nodeSize);
1255 }
1256 // Add number of children.
1257 assert(_children.size() < 256);
1258 out.append_byte(_children.size());
1259 // Append each child edge substring and node offset.
1260 for (TrieEdge &edge : _children) {
1261 out.append_string(edge._subString);
1262 out.append_uleb128(edge._child->_trieOffset);
1263 }
1264}
1265
1266void MachOFileLayout::buildExportTrie() {
1267 if (_file.exportInfo.empty())
1268 return;
1269
1270 // For all temporary strings and objects used building trie.
1271 BumpPtrAllocator allocator;
1272
1273 // Build trie of all exported symbols.
Eugene Zelenko41547942015-11-10 22:37:38 +00001274 auto *rootNode = new (allocator) TrieNode(StringRef());
Nick Kledzik141330a2014-09-03 19:52:50 +00001275 std::vector<TrieNode*> allNodes;
1276 allNodes.reserve(_file.exportInfo.size()*2);
1277 allNodes.push_back(rootNode);
1278 for (const Export& entry : _file.exportInfo) {
1279 rootNode->addSymbol(entry, allocator, allNodes);
1280 }
1281
1282 // Assign each node in the vector an offset in the trie stream, iterating
1283 // until all uleb128 sizes have stabilized.
1284 bool more;
1285 do {
1286 uint32_t offset = 0;
1287 more = false;
1288 for (TrieNode* node : allNodes) {
1289 if (node->updateOffset(offset))
1290 more = true;
1291 }
1292 } while (more);
1293
1294 // Serialize trie to ByteBuffer.
1295 for (TrieNode* node : allNodes) {
1296 node->appendToByteBuffer(_exportTrie);
1297 }
1298 _exportTrie.align(_is64 ? 8 : 4);
1299}
1300
Nick Kledzike34182f2013-11-06 21:36:55 +00001301void MachOFileLayout::computeSymbolTableSizes() {
1302 // MachO symbol tables have three ranges: locals, globals, and undefines
1303 const size_t nlistSize = (_is64 ? sizeof(nlist_64) : sizeof(nlist));
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001304 _symbolTableSize = nlistSize * (_file.localSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +00001305 + _file.globalSymbols.size()
1306 + _file.undefinedSymbols.size());
Lang Hames201c08f2015-12-10 00:12:24 +00001307 _symbolStringPoolSize = 1; // Always reserve 1-byte for the empty string.
Nick Kledzike34182f2013-11-06 21:36:55 +00001308 for (const Symbol &sym : _file.localSymbols) {
1309 _symbolStringPoolSize += (sym.name.size()+1);
1310 }
1311 for (const Symbol &sym : _file.globalSymbols) {
1312 _symbolStringPoolSize += (sym.name.size()+1);
1313 }
1314 for (const Symbol &sym : _file.undefinedSymbols) {
1315 _symbolStringPoolSize += (sym.name.size()+1);
1316 }
1317 _symbolTableLocalsStartIndex = 0;
1318 _symbolTableGlobalsStartIndex = _file.localSymbols.size();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001319 _symbolTableUndefinesStartIndex = _symbolTableGlobalsStartIndex
Nick Kledzike34182f2013-11-06 21:36:55 +00001320 + _file.globalSymbols.size();
1321
1322 _indirectSymbolTableCount = 0;
1323 for (const Section &sect : _file.sections) {
1324 _indirectSymbolTableCount += sect.indirectSymbols.size();
1325 }
1326}
1327
Nick Kledzik21921372014-07-24 23:06:56 +00001328void MachOFileLayout::computeDataInCodeSize() {
1329 _dataInCodeSize = _file.dataInCode.size() * sizeof(data_in_code_entry);
1330}
Nick Kledzike34182f2013-11-06 21:36:55 +00001331
1332void MachOFileLayout::writeLinkEditContent() {
1333 if (_file.fileType == llvm::MachO::MH_OBJECT) {
1334 writeRelocations();
Nick Kledzik21921372014-07-24 23:06:56 +00001335 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001336 writeSymbolTable();
1337 } else {
1338 writeRebaseInfo();
1339 writeBindingInfo();
1340 writeLazyBindingInfo();
1341 // TODO: add weak binding info
Nick Kledzik141330a2014-09-03 19:52:50 +00001342 writeExportInfo();
Nick Kledzik54ce29582014-10-28 22:21:10 +00001343 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001344 writeSymbolTable();
1345 }
1346}
1347
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001348std::error_code MachOFileLayout::writeBinary(StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001349 // Check for pending error from constructor.
1350 if (_ec)
1351 return _ec;
1352 // Create FileOutputBuffer with calculated size.
Nick Kledzike34182f2013-11-06 21:36:55 +00001353 unsigned flags = 0;
1354 if (_file.fileType != llvm::MachO::MH_OBJECT)
1355 flags = llvm::FileOutputBuffer::F_executable;
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001356 ErrorOr<std::unique_ptr<llvm::FileOutputBuffer>> fobOrErr =
1357 llvm::FileOutputBuffer::create(path, size(), flags);
1358 if (std::error_code ec = fobOrErr.getError())
Nick Kledzike34182f2013-11-06 21:36:55 +00001359 return ec;
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001360 std::unique_ptr<llvm::FileOutputBuffer> &fob = *fobOrErr;
Nick Kledzike34182f2013-11-06 21:36:55 +00001361 // Write content.
1362 _buffer = fob->getBufferStart();
1363 writeMachHeader();
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001364 std::error_code ec = writeLoadCommands();
Nick Kledzike34182f2013-11-06 21:36:55 +00001365 if (ec)
1366 return ec;
1367 writeSectionContent();
1368 writeLinkEditContent();
1369 fob->commit();
1370
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001371 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +00001372}
1373
Nick Kledzike34182f2013-11-06 21:36:55 +00001374/// Takes in-memory normalized view and writes a mach-o object file.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001375std::error_code writeBinary(const NormalizedFile &file, StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001376 MachOFileLayout layout(file);
1377 return layout.writeBinary(path);
1378}
1379
Nick Kledzike34182f2013-11-06 21:36:55 +00001380} // namespace normalized
1381} // namespace mach_o
1382} // namespace lld