blob: bbf62de6102ae4be483639f2bb0cd56b4599a339 [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"
Nick Kledzike34182f2013-11-06 21:36:55 +000028#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringRef.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/Debug.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000033#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000034#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/FileOutputBuffer.h"
Nick Kledzik141330a2014-09-03 19:52:50 +000036#include "llvm/Support/Format.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000037#include "llvm/Support/Host.h"
Nick Kledzik00a15d92013-11-09 01:00:51 +000038#include "llvm/Support/LEB128.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000039#include "llvm/Support/MachO.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/raw_ostream.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000042#include <functional>
Nick Kledzik07ba5122014-12-02 01:50:44 +000043#include <list>
Nick Kledzike34182f2013-11-06 21:36:55 +000044#include <map>
Rafael Espindola54427cc2014-06-12 17:15:58 +000045#include <system_error>
Nick Kledzike34182f2013-11-06 21:36:55 +000046
47using namespace llvm::MachO;
48
49namespace lld {
50namespace mach_o {
51namespace normalized {
52
53/// Utility class for writing a mach-o binary file given an in-memory
Shankar Easwaran3d8de472014-01-27 03:09:26 +000054/// normalized file.
Nick Kledzike34182f2013-11-06 21:36:55 +000055class MachOFileLayout {
56public:
Joey Goulyb275d7f2013-12-23 23:29:50 +000057 /// All layout computation is done in the constructor.
58 MachOFileLayout(const NormalizedFile &file);
59
Nick Kledzike34182f2013-11-06 21:36:55 +000060 /// Returns the final file size as computed in the constructor.
61 size_t size() const;
62
Nick Kledzik2fcbe822014-07-30 00:58:06 +000063 // Returns size of the mach_header and load commands.
64 size_t headerAndLoadCommandsSize() const;
65
Shankar Easwaran3d8de472014-01-27 03:09:26 +000066 /// Writes the normalized file as a binary mach-o file to the specified
Nick Kledzike34182f2013-11-06 21:36:55 +000067 /// path. This does not have a stream interface because the generated
68 /// file may need the 'x' bit set.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000069 std::error_code writeBinary(StringRef path);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000070
Nick Kledzike34182f2013-11-06 21:36:55 +000071private:
72 uint32_t loadCommandsSize(uint32_t &count);
73 void buildFileOffsets();
74 void writeMachHeader();
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000075 std::error_code writeLoadCommands();
Nick Kledzike34182f2013-11-06 21:36:55 +000076 void writeSectionContent();
77 void writeRelocations();
78 void writeSymbolTable();
79 void writeRebaseInfo();
80 void writeBindingInfo();
81 void writeLazyBindingInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +000082 void writeExportInfo();
Nick Kledzik21921372014-07-24 23:06:56 +000083 void writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +000084 void writeLinkEditContent();
85 void buildLinkEditInfo();
86 void buildRebaseInfo();
87 void buildBindInfo();
88 void buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +000089 void buildExportTrie();
Nick Kledzik21921372014-07-24 23:06:56 +000090 void computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +000091 void computeSymbolTableSizes();
92 void buildSectionRelocations();
93 void appendSymbols(const std::vector<Symbol> &symbols,
94 uint32_t &symOffset, uint32_t &strOffset);
95 uint32_t indirectSymbolIndex(const Section &sect, uint32_t &index);
96 uint32_t indirectSymbolElementSize(const Section &sect);
97
Nick Kledzik29f749e2013-11-09 00:07:28 +000098 // For use as template parameter to load command methods.
99 struct MachO64Trait {
100 typedef llvm::MachO::segment_command_64 command;
101 typedef llvm::MachO::section_64 section;
102 enum { LC = llvm::MachO::LC_SEGMENT_64 };
103 };
104
105 // For use as template parameter to load command methods.
106 struct MachO32Trait {
107 typedef llvm::MachO::segment_command command;
108 typedef llvm::MachO::section section;
109 enum { LC = llvm::MachO::LC_SEGMENT };
110 };
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000111
Nick Kledzik29f749e2013-11-09 00:07:28 +0000112 template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000113 std::error_code writeSingleSegmentLoadCommand(uint8_t *&lc);
114 template <typename T> std::error_code writeSegmentLoadCommands(uint8_t *&lc);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000115
Nick Kledzike34182f2013-11-06 21:36:55 +0000116 uint32_t pointerAlign(uint32_t value);
117 static StringRef dyldPath();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000118
Nick Kledzike34182f2013-11-06 21:36:55 +0000119 class ByteBuffer {
120 public:
Nick Kledzik00a15d92013-11-09 01:00:51 +0000121 ByteBuffer() : _ostream(_bytes) { }
Nick Kledzik141330a2014-09-03 19:52:50 +0000122
Nick Kledzik00a15d92013-11-09 01:00:51 +0000123 void append_byte(uint8_t b) {
124 _ostream << b;
125 }
126 void append_uleb128(uint64_t value) {
127 llvm::encodeULEB128(value, _ostream);
128 }
Nick Kledzikf373c772014-11-11 01:31:18 +0000129 void append_uleb128Fixed(uint64_t value, unsigned byteCount) {
130 unsigned min = llvm::getULEB128Size(value);
131 assert(min <= byteCount);
132 unsigned pad = byteCount - min;
133 llvm::encodeULEB128(value, _ostream, pad);
134 }
Nick Kledzik00a15d92013-11-09 01:00:51 +0000135 void append_sleb128(int64_t value) {
136 llvm::encodeSLEB128(value, _ostream);
137 }
138 void append_string(StringRef str) {
139 _ostream << str;
140 append_byte(0);
141 }
142 void align(unsigned alignment) {
143 while ( (_ostream.tell() % alignment) != 0 )
144 append_byte(0);
145 }
146 size_t size() {
147 return _ostream.tell();
148 }
149 const uint8_t *bytes() {
150 return reinterpret_cast<const uint8_t*>(_ostream.str().data());
151 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000152 private:
Nick Kledzik00a15d92013-11-09 01:00:51 +0000153 SmallVector<char, 128> _bytes;
154 // Stream ivar must be after SmallVector ivar to construct properly.
155 llvm::raw_svector_ostream _ostream;
Nick Kledzike34182f2013-11-06 21:36:55 +0000156 };
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000157
Nick Kledzik141330a2014-09-03 19:52:50 +0000158 struct TrieNode; // Forward declaration.
159
160 struct TrieEdge {
161 TrieEdge(StringRef s, TrieNode *node) : _subString(s), _child(node) {}
Nick Kledzik141330a2014-09-03 19:52:50 +0000162
163 StringRef _subString;
164 struct TrieNode *_child;
165 };
166
167 struct TrieNode {
168 TrieNode(StringRef s)
169 : _cummulativeString(s), _address(0), _flags(0), _other(0),
170 _trieOffset(0), _hasExportInfo(false) {}
171 ~TrieNode() {}
172
173 void addSymbol(const Export &entry, BumpPtrAllocator &allocator,
174 std::vector<TrieNode *> &allNodes);
175 bool updateOffset(uint32_t &offset);
176 void appendToByteBuffer(ByteBuffer &out);
177
178private:
179 StringRef _cummulativeString;
Nick Kledzik07ba5122014-12-02 01:50:44 +0000180 std::list<TrieEdge> _children;
Nick Kledzik141330a2014-09-03 19:52:50 +0000181 uint64_t _address;
182 uint64_t _flags;
183 uint64_t _other;
184 StringRef _importedName;
185 uint32_t _trieOffset;
186 bool _hasExportInfo;
187 };
Nick Kledzik00a15d92013-11-09 01:00:51 +0000188
Nick Kledzike34182f2013-11-06 21:36:55 +0000189 struct SegExtraInfo {
190 uint32_t fileOffset;
Tim Northover08d6a7b2014-06-30 09:49:30 +0000191 uint32_t fileSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000192 std::vector<const Section*> sections;
193 };
194 typedef std::map<const Segment*, SegExtraInfo> SegMap;
195 struct SectionExtraInfo {
196 uint32_t fileOffset;
197 };
198 typedef std::map<const Section*, SectionExtraInfo> SectionMap;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000199
Nick Kledzike34182f2013-11-06 21:36:55 +0000200 const NormalizedFile &_file;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000201 std::error_code _ec;
Nick Kledzike34182f2013-11-06 21:36:55 +0000202 uint8_t *_buffer;
203 const bool _is64;
204 const bool _swap;
205 const bool _bigEndianArch;
206 uint64_t _seg1addr;
207 uint32_t _startOfLoadCommands;
208 uint32_t _countOfLoadCommands;
209 uint32_t _endOfLoadCommands;
210 uint32_t _startOfRelocations;
Nick Kledzik21921372014-07-24 23:06:56 +0000211 uint32_t _startOfDataInCode;
Nick Kledzike34182f2013-11-06 21:36:55 +0000212 uint32_t _startOfSymbols;
213 uint32_t _startOfIndirectSymbols;
214 uint32_t _startOfSymbolStrings;
215 uint32_t _endOfSymbolStrings;
216 uint32_t _symbolTableLocalsStartIndex;
217 uint32_t _symbolTableGlobalsStartIndex;
218 uint32_t _symbolTableUndefinesStartIndex;
219 uint32_t _symbolStringPoolSize;
220 uint32_t _symbolTableSize;
Nick Kledzik21921372014-07-24 23:06:56 +0000221 uint32_t _dataInCodeSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000222 uint32_t _indirectSymbolTableCount;
223 // Used in object file creation only
224 uint32_t _startOfSectionsContent;
225 uint32_t _endOfSectionsContent;
226 // Used in final linked image only
227 uint32_t _startOfLinkEdit;
228 uint32_t _startOfRebaseInfo;
229 uint32_t _endOfRebaseInfo;
230 uint32_t _startOfBindingInfo;
231 uint32_t _endOfBindingInfo;
232 uint32_t _startOfLazyBindingInfo;
233 uint32_t _endOfLazyBindingInfo;
Nick Kledzik141330a2014-09-03 19:52:50 +0000234 uint32_t _startOfExportTrie;
235 uint32_t _endOfExportTrie;
Nick Kledzike34182f2013-11-06 21:36:55 +0000236 uint32_t _endOfLinkEdit;
237 uint64_t _addressOfLinkEdit;
238 SegMap _segInfo;
239 SectionMap _sectInfo;
240 ByteBuffer _rebaseInfo;
241 ByteBuffer _bindingInfo;
242 ByteBuffer _lazyBindingInfo;
243 ByteBuffer _weakBindingInfo;
Nick Kledzik141330a2014-09-03 19:52:50 +0000244 ByteBuffer _exportTrie;
Nick Kledzike34182f2013-11-06 21:36:55 +0000245};
246
247size_t headerAndLoadCommandsSize(const NormalizedFile &file) {
248 MachOFileLayout layout(file);
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000249 return layout.headerAndLoadCommandsSize();
Nick Kledzike34182f2013-11-06 21:36:55 +0000250}
251
252StringRef MachOFileLayout::dyldPath() {
253 return "/usr/lib/dyld";
254}
255
256uint32_t MachOFileLayout::pointerAlign(uint32_t value) {
257 return llvm::RoundUpToAlignment(value, _is64 ? 8 : 4);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000258}
Nick Kledzike34182f2013-11-06 21:36:55 +0000259
260
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000261size_t MachOFileLayout::headerAndLoadCommandsSize() const {
262 return _endOfLoadCommands;
263}
Nick Kledzike34182f2013-11-06 21:36:55 +0000264
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000265
266MachOFileLayout::MachOFileLayout(const NormalizedFile &file)
Nick Kledzike34182f2013-11-06 21:36:55 +0000267 : _file(file),
268 _is64(MachOLinkingContext::is64Bit(file.arch)),
269 _swap(!MachOLinkingContext::isHostEndian(file.arch)),
270 _bigEndianArch(MachOLinkingContext::isBigEndian(file.arch)),
271 _seg1addr(INT64_MAX) {
272 _startOfLoadCommands = _is64 ? sizeof(mach_header_64) : sizeof(mach_header);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000273 const size_t segCommandBaseSize =
Nick Kledzike34182f2013-11-06 21:36:55 +0000274 (_is64 ? sizeof(segment_command_64) : sizeof(segment_command));
275 const size_t sectsSize = (_is64 ? sizeof(section_64) : sizeof(section));
276 if (file.fileType == llvm::MachO::MH_OBJECT) {
277 // object files have just one segment load command containing all sections
278 _endOfLoadCommands = _startOfLoadCommands
279 + segCommandBaseSize
280 + file.sections.size() * sectsSize
281 + sizeof(symtab_command);
282 _countOfLoadCommands = 2;
Nick Kledzik21921372014-07-24 23:06:56 +0000283 if (!_file.dataInCode.empty()) {
284 _endOfLoadCommands += sizeof(linkedit_data_command);
285 _countOfLoadCommands++;
286 }
Nick Kledzikb072c362014-11-18 00:30:29 +0000287 // Assign file offsets to each section.
Nick Kledzike34182f2013-11-06 21:36:55 +0000288 _startOfSectionsContent = _endOfLoadCommands;
Nick Kledzike34182f2013-11-06 21:36:55 +0000289 unsigned relocCount = 0;
Nick Kledzikb072c362014-11-18 00:30:29 +0000290 uint64_t offset = _startOfSectionsContent;
Nick Kledzike34182f2013-11-06 21:36:55 +0000291 for (const Section &sect : file.sections) {
Nick Kledzikb072c362014-11-18 00:30:29 +0000292 if (sect.type != llvm::MachO::S_ZEROFILL) {
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000293 offset = llvm::RoundUpToAlignment(offset, sect.alignment);
Nick Kledzikb072c362014-11-18 00:30:29 +0000294 _sectInfo[&sect].fileOffset = offset;
295 offset += sect.content.size();
296 } else {
297 _sectInfo[&sect].fileOffset = 0;
298 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000299 relocCount += sect.relocations.size();
300 }
Nick Kledzikb072c362014-11-18 00:30:29 +0000301 _endOfSectionsContent = offset;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000302
Nick Kledzike34182f2013-11-06 21:36:55 +0000303 computeSymbolTableSizes();
Nick Kledzik21921372014-07-24 23:06:56 +0000304 computeDataInCodeSize();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000305
Nick Kledzike34182f2013-11-06 21:36:55 +0000306 // Align start of relocations.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000307 _startOfRelocations = pointerAlign(_endOfSectionsContent);
Nick Kledzik21921372014-07-24 23:06:56 +0000308 _startOfDataInCode = _startOfRelocations + relocCount * 8;
309 _startOfSymbols = _startOfDataInCode + _dataInCodeSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000310 // Add Indirect symbol table.
311 _startOfIndirectSymbols = _startOfSymbols + _symbolTableSize;
312 // Align start of symbol table and symbol strings.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000313 _startOfSymbolStrings = _startOfIndirectSymbols
Nick Kledzike34182f2013-11-06 21:36:55 +0000314 + pointerAlign(_indirectSymbolTableCount * sizeof(uint32_t));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000315 _endOfSymbolStrings = _startOfSymbolStrings
Nick Kledzike34182f2013-11-06 21:36:55 +0000316 + pointerAlign(_symbolStringPoolSize);
317 _endOfLinkEdit = _endOfSymbolStrings;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000318 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000319 llvm::dbgs() << "MachOFileLayout()\n"
320 << " startOfLoadCommands=" << _startOfLoadCommands << "\n"
321 << " countOfLoadCommands=" << _countOfLoadCommands << "\n"
322 << " endOfLoadCommands=" << _endOfLoadCommands << "\n"
323 << " startOfRelocations=" << _startOfRelocations << "\n"
324 << " startOfSymbols=" << _startOfSymbols << "\n"
325 << " startOfSymbolStrings=" << _startOfSymbolStrings << "\n"
326 << " endOfSymbolStrings=" << _endOfSymbolStrings << "\n"
327 << " startOfSectionsContent=" << _startOfSectionsContent << "\n"
328 << " endOfSectionsContent=" << _endOfSectionsContent << "\n");
329 } else {
330 // Final linked images have one load command per segment.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000331 _endOfLoadCommands = _startOfLoadCommands
Nick Kledzike34182f2013-11-06 21:36:55 +0000332 + loadCommandsSize(_countOfLoadCommands);
333
334 // Assign section file offsets.
335 buildFileOffsets();
336 buildLinkEditInfo();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000337
Nick Kledzike34182f2013-11-06 21:36:55 +0000338 // LINKEDIT of final linked images has in order:
339 // rebase info, binding info, lazy binding info, weak binding info,
Nick Kledzik21921372014-07-24 23:06:56 +0000340 // data-in-code, symbol table, indirect symbol table, symbol table strings.
Nick Kledzike34182f2013-11-06 21:36:55 +0000341 _startOfRebaseInfo = _startOfLinkEdit;
342 _endOfRebaseInfo = _startOfRebaseInfo + _rebaseInfo.size();
343 _startOfBindingInfo = _endOfRebaseInfo;
344 _endOfBindingInfo = _startOfBindingInfo + _bindingInfo.size();
345 _startOfLazyBindingInfo = _endOfBindingInfo;
346 _endOfLazyBindingInfo = _startOfLazyBindingInfo + _lazyBindingInfo.size();
Nick Kledzik141330a2014-09-03 19:52:50 +0000347 _startOfExportTrie = _endOfLazyBindingInfo;
348 _endOfExportTrie = _startOfExportTrie + _exportTrie.size();
349 _startOfDataInCode = _endOfExportTrie;
Nick Kledzik21921372014-07-24 23:06:56 +0000350 _startOfSymbols = _startOfDataInCode + _dataInCodeSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000351 _startOfIndirectSymbols = _startOfSymbols + _symbolTableSize;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000352 _startOfSymbolStrings = _startOfIndirectSymbols
Nick Kledzike34182f2013-11-06 21:36:55 +0000353 + pointerAlign(_indirectSymbolTableCount * sizeof(uint32_t));
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000354 _endOfSymbolStrings = _startOfSymbolStrings
Nick Kledzike34182f2013-11-06 21:36:55 +0000355 + pointerAlign(_symbolStringPoolSize);
356 _endOfLinkEdit = _endOfSymbolStrings;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000357 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000358 llvm::dbgs() << "MachOFileLayout()\n"
359 << " startOfLoadCommands=" << _startOfLoadCommands << "\n"
360 << " countOfLoadCommands=" << _countOfLoadCommands << "\n"
361 << " endOfLoadCommands=" << _endOfLoadCommands << "\n"
362 << " startOfLinkEdit=" << _startOfLinkEdit << "\n"
363 << " startOfRebaseInfo=" << _startOfRebaseInfo << "\n"
364 << " endOfRebaseInfo=" << _endOfRebaseInfo << "\n"
365 << " startOfBindingInfo=" << _startOfBindingInfo << "\n"
366 << " endOfBindingInfo=" << _endOfBindingInfo << "\n"
367 << " startOfLazyBindingInfo=" << _startOfLazyBindingInfo << "\n"
368 << " endOfLazyBindingInfo=" << _endOfLazyBindingInfo << "\n"
Nick Kledzik141330a2014-09-03 19:52:50 +0000369 << " startOfExportTrie=" << _startOfExportTrie << "\n"
370 << " endOfExportTrie=" << _endOfExportTrie << "\n"
Nick Kledzik21921372014-07-24 23:06:56 +0000371 << " startOfDataInCode=" << _startOfDataInCode << "\n"
Nick Kledzike34182f2013-11-06 21:36:55 +0000372 << " startOfSymbols=" << _startOfSymbols << "\n"
373 << " startOfSymbolStrings=" << _startOfSymbolStrings << "\n"
374 << " endOfSymbolStrings=" << _endOfSymbolStrings << "\n"
375 << " addressOfLinkEdit=" << _addressOfLinkEdit << "\n");
376 }
377}
378
379uint32_t MachOFileLayout::loadCommandsSize(uint32_t &count) {
380 uint32_t size = 0;
381 count = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000382
383 const size_t segCommandSize =
Nick Kledzike34182f2013-11-06 21:36:55 +0000384 (_is64 ? sizeof(segment_command_64) : sizeof(segment_command));
385 const size_t sectionSize = (_is64 ? sizeof(section_64) : sizeof(section));
386
387 // Add LC_SEGMENT for each segment.
388 size += _file.segments.size() * segCommandSize;
389 count += _file.segments.size();
390 // Add section record for each section.
391 size += _file.sections.size() * sectionSize;
392 // Add one LC_SEGMENT for implicit __LINKEDIT segment
393 size += segCommandSize;
394 ++count;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000395
Tim Northover301c4e62014-07-01 08:15:41 +0000396 // If creating a dylib, add LC_ID_DYLIB.
397 if (_file.fileType == llvm::MachO::MH_DYLIB) {
398 size += sizeof(dylib_command) + pointerAlign(_file.installName.size() + 1);
399 ++count;
400 }
401
Nick Kledzike34182f2013-11-06 21:36:55 +0000402 // Add LC_DYLD_INFO
403 size += sizeof(dyld_info_command);
404 ++count;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000405
Nick Kledzike34182f2013-11-06 21:36:55 +0000406 // Add LC_SYMTAB
407 size += sizeof(symtab_command);
408 ++count;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000409
Nick Kledzike34182f2013-11-06 21:36:55 +0000410 // Add LC_DYSYMTAB
411 if (_file.fileType != llvm::MachO::MH_PRELOAD) {
412 size += sizeof(dysymtab_command);
413 ++count;
414 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000415
Nick Kledzike34182f2013-11-06 21:36:55 +0000416 // If main executable add LC_LOAD_DYLINKER and LC_MAIN
417 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
418 size += pointerAlign(sizeof(dylinker_command) + dyldPath().size()+1);
419 ++count;
420 size += sizeof(entry_point_command);
421 ++count;
422 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000423
Nick Kledzike34182f2013-11-06 21:36:55 +0000424 // Add LC_LOAD_DYLIB for each dependent dylib.
425 for (const DependentDylib &dep : _file.dependentDylibs) {
426 size += sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
427 ++count;
428 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000429
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000430 // Add LC_RPATH
431 for (const StringRef &path : _file.rpaths) {
432 size += sizeof(rpath_command) + pointerAlign(path.size()+1);
433 ++count;
434 }
435
Nick Kledzik54ce29582014-10-28 22:21:10 +0000436 // Add LC_DATA_IN_CODE if needed
437 if (!_file.dataInCode.empty()) {
438 size += sizeof(linkedit_data_command);
439 ++count;
440 }
441
Nick Kledzike34182f2013-11-06 21:36:55 +0000442 return size;
443}
444
445static bool overlaps(const Segment &s1, const Segment &s2) {
446 if (s2.address >= s1.address+s1.size)
447 return false;
448 if (s1.address >= s2.address+s2.size)
449 return false;
450 return true;
451}
452
453static bool overlaps(const Section &s1, const Section &s2) {
454 if (s2.address >= s1.address+s1.content.size())
455 return false;
456 if (s1.address >= s2.address+s2.content.size())
457 return false;
458 return true;
459}
460
461void MachOFileLayout::buildFileOffsets() {
462 // Verify no segments overlap
463 for (const Segment &sg1 : _file.segments) {
464 for (const Segment &sg2 : _file.segments) {
465 if (&sg1 == &sg2)
466 continue;
467 if (overlaps(sg1,sg2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000468 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000469 return;
470 }
471 }
472 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000473
474 // Verify no sections overlap
Nick Kledzike34182f2013-11-06 21:36:55 +0000475 for (const Section &s1 : _file.sections) {
476 for (const Section &s2 : _file.sections) {
477 if (&s1 == &s2)
478 continue;
479 if (overlaps(s1,s2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000480 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000481 return;
482 }
483 }
484 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000485
Nick Kledzike34182f2013-11-06 21:36:55 +0000486 // Build side table of extra info about segments and sections.
487 SegExtraInfo t;
488 t.fileOffset = 0;
489 for (const Segment &sg : _file.segments) {
490 _segInfo[&sg] = t;
491 }
492 SectionExtraInfo t2;
493 t2.fileOffset = 0;
494 // Assign sections to segments.
495 for (const Section &s : _file.sections) {
496 _sectInfo[&s] = t2;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000497 bool foundSegment = false;
Nick Kledzike34182f2013-11-06 21:36:55 +0000498 for (const Segment &sg : _file.segments) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000499 if (sg.name.equals(s.segmentName)) {
500 if ((s.address >= sg.address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000501 && (s.address+s.content.size() <= sg.address+sg.size)) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000502 _segInfo[&sg].sections.push_back(&s);
503 foundSegment = true;
504 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000505 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000506 }
507 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000508 if (!foundSegment) {
509 _ec = make_error_code(llvm::errc::executable_format_error);
510 return;
511 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000512 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000513
Nick Kledzike34182f2013-11-06 21:36:55 +0000514 // Assign file offsets.
515 uint32_t fileOffset = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000516 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000517 llvm::dbgs() << "buildFileOffsets()\n");
518 for (const Segment &sg : _file.segments) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000519 _segInfo[&sg].fileOffset = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000520 if ((_seg1addr == INT64_MAX) && sg.access)
521 _seg1addr = sg.address;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000522 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000523 llvm::dbgs() << " segment=" << sg.name
524 << ", fileOffset=" << _segInfo[&sg].fileOffset << "\n");
Tim Northover08d6a7b2014-06-30 09:49:30 +0000525
526 uint32_t segFileSize = 0;
Nick Kledzik761d6542014-10-24 22:19:22 +0000527 // A segment that is not zero-fill must use a least one page of disk space.
528 if (sg.access)
529 segFileSize = _file.pageSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000530 for (const Section *s : _segInfo[&sg].sections) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000531 uint32_t sectOffset = s->address - sg.address;
532 uint32_t sectFileSize =
533 s->type == llvm::MachO::S_ZEROFILL ? 0 : s->content.size();
534 segFileSize = std::max(segFileSize, sectOffset + sectFileSize);
535
536 _sectInfo[s].fileOffset = _segInfo[&sg].fileOffset + sectOffset;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000537 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000538 llvm::dbgs() << " section=" << s->sectionName
539 << ", fileOffset=" << fileOffset << "\n");
540 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000541
Nick Kledzik1bebb282014-09-09 23:52:59 +0000542 _segInfo[&sg].fileSize = llvm::RoundUpToAlignment(segFileSize,
543 _file.pageSize);
544 fileOffset = llvm::RoundUpToAlignment(fileOffset + segFileSize,
545 _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000546 _addressOfLinkEdit = sg.address + sg.size;
547 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000548 _startOfLinkEdit = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000549}
550
551
552size_t MachOFileLayout::size() const {
553 return _endOfSymbolStrings;
554}
555
556void MachOFileLayout::writeMachHeader() {
557 mach_header *mh = reinterpret_cast<mach_header*>(_buffer);
558 mh->magic = _is64 ? llvm::MachO::MH_MAGIC_64 : llvm::MachO::MH_MAGIC;
559 mh->cputype = MachOLinkingContext::cpuTypeFromArch(_file.arch);
560 mh->cpusubtype = MachOLinkingContext::cpuSubtypeFromArch(_file.arch);
561 mh->filetype = _file.fileType;
562 mh->ncmds = _countOfLoadCommands;
563 mh->sizeofcmds = _endOfLoadCommands - _startOfLoadCommands;
564 mh->flags = _file.flags;
565 if (_swap)
566 swapStruct(*mh);
567}
568
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000569uint32_t MachOFileLayout::indirectSymbolIndex(const Section &sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000570 uint32_t &index) {
571 if (sect.indirectSymbols.empty())
572 return 0;
573 uint32_t result = index;
574 index += sect.indirectSymbols.size();
575 return result;
576}
577
578uint32_t MachOFileLayout::indirectSymbolElementSize(const Section &sect) {
579 if (sect.indirectSymbols.empty())
580 return 0;
581 if (sect.type != S_SYMBOL_STUBS)
582 return 0;
583 return sect.content.size() / sect.indirectSymbols.size();
584}
585
Nick Kledzik29f749e2013-11-09 00:07:28 +0000586template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000587std::error_code MachOFileLayout::writeSingleSegmentLoadCommand(uint8_t *&lc) {
Nick Kledzik29f749e2013-11-09 00:07:28 +0000588 typename T::command* seg = reinterpret_cast<typename T::command*>(lc);
589 seg->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000590 seg->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000591 + _file.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000592 uint8_t *next = lc + seg->cmdsize;
593 memset(seg->segname, 0, 16);
594 seg->vmaddr = 0;
Nick Kledzikb072c362014-11-18 00:30:29 +0000595 seg->vmsize = _file.sections.back().address
596 + _file.sections.back().content.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000597 seg->fileoff = _endOfLoadCommands;
598 seg->filesize = seg->vmsize;
599 seg->maxprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
600 seg->initprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
601 seg->nsects = _file.sections.size();
602 seg->flags = 0;
603 if (_swap)
604 swapStruct(*seg);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000605 typename T::section *sout = reinterpret_cast<typename T::section*>
606 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000607 uint32_t relOffset = _startOfRelocations;
Nick Kledzike34182f2013-11-06 21:36:55 +0000608 uint32_t indirectSymRunningIndex = 0;
609 for (const Section &sin : _file.sections) {
610 setString16(sin.sectionName, sout->sectname);
611 setString16(sin.segmentName, sout->segname);
612 sout->addr = sin.address;
613 sout->size = sin.content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000614 sout->offset = _sectInfo[&sin].fileOffset;
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000615 sout->align = llvm::Log2_32(sin.alignment);
Nick Kledzike34182f2013-11-06 21:36:55 +0000616 sout->reloff = sin.relocations.empty() ? 0 : relOffset;
617 sout->nreloc = sin.relocations.size();
618 sout->flags = sin.type | sin.attributes;
619 sout->reserved1 = indirectSymbolIndex(sin, indirectSymRunningIndex);
620 sout->reserved2 = indirectSymbolElementSize(sin);
621 relOffset += sin.relocations.size() * sizeof(any_relocation_info);
Nick Kledzike34182f2013-11-06 21:36:55 +0000622 if (_swap)
623 swapStruct(*sout);
624 ++sout;
625 }
626 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000627 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000628}
629
Nick Kledzik29f749e2013-11-09 00:07:28 +0000630template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000631std::error_code MachOFileLayout::writeSegmentLoadCommands(uint8_t *&lc) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000632 uint32_t indirectSymRunningIndex = 0;
633 for (const Segment &seg : _file.segments) {
634 // Write segment command with trailing sections.
635 SegExtraInfo &segInfo = _segInfo[&seg];
Nick Kledzik29f749e2013-11-09 00:07:28 +0000636 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
637 cmd->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000638 cmd->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000639 + segInfo.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000640 uint8_t *next = lc + cmd->cmdsize;
641 setString16(seg.name, cmd->segname);
642 cmd->vmaddr = seg.address;
643 cmd->vmsize = seg.size;
644 cmd->fileoff = segInfo.fileOffset;
Tim Northover08d6a7b2014-06-30 09:49:30 +0000645 cmd->filesize = segInfo.fileSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000646 cmd->maxprot = seg.access;
647 cmd->initprot = seg.access;
648 cmd->nsects = segInfo.sections.size();
649 cmd->flags = 0;
650 if (_swap)
651 swapStruct(*cmd);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000652 typename T::section *sect = reinterpret_cast<typename T::section*>
653 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000654 for (const Section *section : segInfo.sections) {
655 setString16(section->sectionName, sect->sectname);
656 setString16(section->segmentName, sect->segname);
657 sect->addr = section->address;
658 sect->size = section->content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000659 if (section->type == llvm::MachO::S_ZEROFILL)
660 sect->offset = 0;
661 else
662 sect->offset = section->address - seg.address + segInfo.fileOffset;
Rui Ueyamaf217ef02015-03-26 02:03:44 +0000663 sect->align = llvm::Log2_32(section->alignment);
Nick Kledzike34182f2013-11-06 21:36:55 +0000664 sect->reloff = 0;
665 sect->nreloc = 0;
666 sect->flags = section->type | section->attributes;
667 sect->reserved1 = indirectSymbolIndex(*section, indirectSymRunningIndex);
668 sect->reserved2 = indirectSymbolElementSize(*section);
669 if (_swap)
670 swapStruct(*sect);
671 ++sect;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000672 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000673 lc = reinterpret_cast<uint8_t*>(next);
674 }
675 // Add implicit __LINKEDIT segment
Nick Kledzik1bebb282014-09-09 23:52:59 +0000676 size_t linkeditSize = _endOfLinkEdit - _startOfLinkEdit;
Nick Kledzik29f749e2013-11-09 00:07:28 +0000677 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
678 cmd->cmd = T::LC;
679 cmd->cmdsize = sizeof(typename T::command);
Nick Kledzike34182f2013-11-06 21:36:55 +0000680 uint8_t *next = lc + cmd->cmdsize;
681 setString16("__LINKEDIT", cmd->segname);
682 cmd->vmaddr = _addressOfLinkEdit;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000683 cmd->vmsize = llvm::RoundUpToAlignment(linkeditSize, _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000684 cmd->fileoff = _startOfLinkEdit;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000685 cmd->filesize = linkeditSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000686 cmd->maxprot = VM_PROT_READ;
687 cmd->initprot = VM_PROT_READ;
688 cmd->nsects = 0;
689 cmd->flags = 0;
690 if (_swap)
691 swapStruct(*cmd);
692 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000693 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000694}
695
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000696std::error_code MachOFileLayout::writeLoadCommands() {
697 std::error_code ec;
Nick Kledzike34182f2013-11-06 21:36:55 +0000698 uint8_t *lc = &_buffer[_startOfLoadCommands];
699 if (_file.fileType == llvm::MachO::MH_OBJECT) {
700 // Object files have one unnamed segment which holds all sections.
701 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000702 ec = writeSingleSegmentLoadCommand<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000703 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000704 ec = writeSingleSegmentLoadCommand<MachO32Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000705 // Add LC_SYMTAB with symbol table info
706 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
707 st->cmd = LC_SYMTAB;
708 st->cmdsize = sizeof(symtab_command);
709 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000710 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000711 + _file.undefinedSymbols.size();
712 st->stroff = _startOfSymbolStrings;
713 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
714 if (_swap)
715 swapStruct(*st);
Nick Kledzik21921372014-07-24 23:06:56 +0000716 lc += sizeof(symtab_command);
717 // Add LC_DATA_IN_CODE if needed.
718 if (_dataInCodeSize != 0) {
719 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
720 dl->cmd = LC_DATA_IN_CODE;
721 dl->cmdsize = sizeof(linkedit_data_command);
722 dl->dataoff = _startOfDataInCode;
723 dl->datasize = _dataInCodeSize;
724 if (_swap)
725 swapStruct(*dl);
726 lc += sizeof(linkedit_data_command);
727 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000728 } else {
729 // Final linked images have sections under segments.
730 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000731 ec = writeSegmentLoadCommands<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000732 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000733 ec = writeSegmentLoadCommands<MachO32Trait>(lc);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000734
Tim Northover301c4e62014-07-01 08:15:41 +0000735 // Add LC_ID_DYLIB command for dynamic libraries.
736 if (_file.fileType == llvm::MachO::MH_DYLIB) {
737 dylib_command *dc = reinterpret_cast<dylib_command*>(lc);
738 StringRef path = _file.installName;
739 uint32_t size = sizeof(dylib_command) + pointerAlign(path.size() + 1);
740 dc->cmd = LC_ID_DYLIB;
741 dc->cmdsize = size;
742 dc->dylib.name = sizeof(dylib_command); // offset
Jean-Daniel Dupasedefccc2014-12-20 09:22:56 +0000743 // needs to be some constant value different than the one in LC_LOAD_DYLIB
744 dc->dylib.timestamp = 1;
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000745 dc->dylib.current_version = _file.currentVersion;
746 dc->dylib.compatibility_version = _file.compatVersion;
Tim Northover301c4e62014-07-01 08:15:41 +0000747 if (_swap)
748 swapStruct(*dc);
749 memcpy(lc + sizeof(dylib_command), path.begin(), path.size());
750 lc[sizeof(dylib_command) + path.size()] = '\0';
751 lc += size;
752 }
753
Nick Kledzike34182f2013-11-06 21:36:55 +0000754 // Add LC_DYLD_INFO_ONLY.
755 dyld_info_command* di = reinterpret_cast<dyld_info_command*>(lc);
756 di->cmd = LC_DYLD_INFO_ONLY;
757 di->cmdsize = sizeof(dyld_info_command);
758 di->rebase_off = _rebaseInfo.size() ? _startOfRebaseInfo : 0;
759 di->rebase_size = _rebaseInfo.size();
760 di->bind_off = _bindingInfo.size() ? _startOfBindingInfo : 0;
761 di->bind_size = _bindingInfo.size();
762 di->weak_bind_off = 0;
763 di->weak_bind_size = 0;
764 di->lazy_bind_off = _lazyBindingInfo.size() ? _startOfLazyBindingInfo : 0;
765 di->lazy_bind_size = _lazyBindingInfo.size();
Nick Kledzik141330a2014-09-03 19:52:50 +0000766 di->export_off = _exportTrie.size() ? _startOfExportTrie : 0;
767 di->export_size = _exportTrie.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000768 if (_swap)
769 swapStruct(*di);
770 lc += sizeof(dyld_info_command);
771
772 // Add LC_SYMTAB with symbol table info.
773 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
774 st->cmd = LC_SYMTAB;
775 st->cmdsize = sizeof(symtab_command);
776 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000777 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000778 + _file.undefinedSymbols.size();
779 st->stroff = _startOfSymbolStrings;
780 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
781 if (_swap)
782 swapStruct(*st);
783 lc += sizeof(symtab_command);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000784
Nick Kledzike34182f2013-11-06 21:36:55 +0000785 // Add LC_DYSYMTAB
786 if (_file.fileType != llvm::MachO::MH_PRELOAD) {
787 dysymtab_command* dst = reinterpret_cast<dysymtab_command*>(lc);
788 dst->cmd = LC_DYSYMTAB;
789 dst->cmdsize = sizeof(dysymtab_command);
790 dst->ilocalsym = _symbolTableLocalsStartIndex;
791 dst->nlocalsym = _file.localSymbols.size();
792 dst->iextdefsym = _symbolTableGlobalsStartIndex;
793 dst->nextdefsym = _file.globalSymbols.size();
794 dst->iundefsym = _symbolTableUndefinesStartIndex;
795 dst->nundefsym = _file.undefinedSymbols.size();
796 dst->tocoff = 0;
797 dst->ntoc = 0;
798 dst->modtaboff = 0;
799 dst->nmodtab = 0;
800 dst->extrefsymoff = 0;
801 dst->nextrefsyms = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000802 dst->indirectsymoff = _startOfIndirectSymbols;
Nick Kledzike34182f2013-11-06 21:36:55 +0000803 dst->nindirectsyms = _indirectSymbolTableCount;
804 dst->extreloff = 0;
805 dst->nextrel = 0;
806 dst->locreloff = 0;
807 dst->nlocrel = 0;
808 if (_swap)
809 swapStruct(*dst);
810 lc += sizeof(dysymtab_command);
811 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000812
Nick Kledzike34182f2013-11-06 21:36:55 +0000813 // If main executable, add LC_LOAD_DYLINKER and LC_MAIN.
814 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
815 // Build LC_LOAD_DYLINKER load command.
816 uint32_t size=pointerAlign(sizeof(dylinker_command)+dyldPath().size()+1);
817 dylinker_command* dl = reinterpret_cast<dylinker_command*>(lc);
818 dl->cmd = LC_LOAD_DYLINKER;
819 dl->cmdsize = size;
820 dl->name = sizeof(dylinker_command); // offset
821 if (_swap)
822 swapStruct(*dl);
823 memcpy(lc+sizeof(dylinker_command), dyldPath().data(), dyldPath().size());
824 lc[sizeof(dylinker_command)+dyldPath().size()] = '\0';
825 lc += size;
826 // Build LC_MAIN load command.
827 entry_point_command* ep = reinterpret_cast<entry_point_command*>(lc);
828 ep->cmd = LC_MAIN;
829 ep->cmdsize = sizeof(entry_point_command);
830 ep->entryoff = _file.entryAddress - _seg1addr;
Lang Hames65a64c92015-05-20 22:10:50 +0000831 ep->stacksize = _file.stackSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000832 if (_swap)
833 swapStruct(*ep);
834 lc += sizeof(entry_point_command);
835 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000836
Nick Kledzike34182f2013-11-06 21:36:55 +0000837 // Add LC_LOAD_DYLIB commands
838 for (const DependentDylib &dep : _file.dependentDylibs) {
839 dylib_command* dc = reinterpret_cast<dylib_command*>(lc);
840 uint32_t size = sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
Nick Kledzik51720672014-10-16 19:31:28 +0000841 dc->cmd = dep.kind;
Nick Kledzike34182f2013-11-06 21:36:55 +0000842 dc->cmdsize = size;
843 dc->dylib.name = sizeof(dylib_command); // offset
Jean-Daniel Dupasedefccc2014-12-20 09:22:56 +0000844 // needs to be some constant value different than the one in LC_ID_DYLIB
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000845 dc->dylib.timestamp = 2;
846 dc->dylib.current_version = dep.currentVersion;
847 dc->dylib.compatibility_version = dep.compatVersion;
Nick Kledzike34182f2013-11-06 21:36:55 +0000848 if (_swap)
849 swapStruct(*dc);
850 memcpy(lc+sizeof(dylib_command), dep.path.begin(), dep.path.size());
851 lc[sizeof(dylib_command)+dep.path.size()] = '\0';
852 lc += size;
853 }
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000854
855 // Add LC_RPATH
856 for (const StringRef &path : _file.rpaths) {
857 rpath_command *rpc = reinterpret_cast<rpath_command *>(lc);
858 uint32_t size = sizeof(rpath_command) + pointerAlign(path.size()+1);
859 rpc->cmd = LC_RPATH;
860 rpc->cmdsize = size;
861 rpc->path = sizeof(rpath_command); // offset
862 if (_swap)
863 swapStruct(*rpc);
864 memcpy(lc+sizeof(rpath_command), path.begin(), path.size());
865 lc[sizeof(rpath_command)+path.size()] = '\0';
866 lc += size;
867 }
868
Nick Kledzik54ce29582014-10-28 22:21:10 +0000869 // Add LC_DATA_IN_CODE if needed.
870 if (_dataInCodeSize != 0) {
871 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
872 dl->cmd = LC_DATA_IN_CODE;
873 dl->cmdsize = sizeof(linkedit_data_command);
874 dl->dataoff = _startOfDataInCode;
875 dl->datasize = _dataInCodeSize;
876 if (_swap)
877 swapStruct(*dl);
878 lc += sizeof(linkedit_data_command);
879 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000880 }
881 return ec;
882}
883
884
885void MachOFileLayout::writeSectionContent() {
886 for (const Section &s : _file.sections) {
887 // Copy all section content to output buffer.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000888 if (s.type == llvm::MachO::S_ZEROFILL)
889 continue;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000890 if (s.content.empty())
891 continue;
Nick Kledzike34182f2013-11-06 21:36:55 +0000892 uint32_t offset = _sectInfo[&s].fileOffset;
893 uint8_t *p = &_buffer[offset];
894 memcpy(p, &s.content[0], s.content.size());
895 p += s.content.size();
896 }
897}
898
899void MachOFileLayout::writeRelocations() {
900 uint32_t relOffset = _startOfRelocations;
901 for (Section sect : _file.sections) {
902 for (Relocation r : sect.relocations) {
903 any_relocation_info* rb = reinterpret_cast<any_relocation_info*>(
904 &_buffer[relOffset]);
905 *rb = packRelocation(r, _swap, _bigEndianArch);
906 relOffset += sizeof(any_relocation_info);
907 }
908 }
909}
910
911
912void MachOFileLayout::appendSymbols(const std::vector<Symbol> &symbols,
913 uint32_t &symOffset, uint32_t &strOffset) {
914 for (const Symbol &sym : symbols) {
915 if (_is64) {
916 nlist_64* nb = reinterpret_cast<nlist_64*>(&_buffer[symOffset]);
917 nb->n_strx = strOffset - _startOfSymbolStrings;
918 nb->n_type = sym.type | sym.scope;
919 nb->n_sect = sym.sect;
920 nb->n_desc = sym.desc;
921 nb->n_value = sym.value;
922 if (_swap)
923 swapStruct(*nb);
924 symOffset += sizeof(nlist_64);
925 } else {
926 nlist* nb = reinterpret_cast<nlist*>(&_buffer[symOffset]);
927 nb->n_strx = strOffset - _startOfSymbolStrings;
928 nb->n_type = sym.type | sym.scope;
929 nb->n_sect = sym.sect;
930 nb->n_desc = sym.desc;
931 nb->n_value = sym.value;
932 if (_swap)
933 swapStruct(*nb);
934 symOffset += sizeof(nlist);
935 }
936 memcpy(&_buffer[strOffset], sym.name.begin(), sym.name.size());
937 strOffset += sym.name.size();
938 _buffer[strOffset++] ='\0'; // Strings in table have nul terminator.
939 }
940}
941
Nick Kledzik21921372014-07-24 23:06:56 +0000942void MachOFileLayout::writeDataInCodeInfo() {
943 uint32_t offset = _startOfDataInCode;
944 for (const DataInCode &entry : _file.dataInCode) {
945 data_in_code_entry *dst = reinterpret_cast<data_in_code_entry*>(
946 &_buffer[offset]);
947 dst->offset = entry.offset;
948 dst->length = entry.length;
949 dst->kind = entry.kind;
950 if (_swap)
951 swapStruct(*dst);
952 offset += sizeof(data_in_code_entry);
953 }
954}
955
Nick Kledzike34182f2013-11-06 21:36:55 +0000956void MachOFileLayout::writeSymbolTable() {
957 // Write symbol table and symbol strings in parallel.
958 uint32_t symOffset = _startOfSymbols;
959 uint32_t strOffset = _startOfSymbolStrings;
960 _buffer[strOffset++] = '\0'; // Reserve n_strx offset of zero to mean no name.
961 appendSymbols(_file.localSymbols, symOffset, strOffset);
962 appendSymbols(_file.globalSymbols, symOffset, strOffset);
963 appendSymbols(_file.undefinedSymbols, symOffset, strOffset);
964 // Write indirect symbol table array.
965 uint32_t *indirects = reinterpret_cast<uint32_t*>
966 (&_buffer[_startOfIndirectSymbols]);
967 if (_file.fileType == llvm::MachO::MH_OBJECT) {
968 // Object files have sections in same order as input normalized file.
969 for (const Section &section : _file.sections) {
970 for (uint32_t index : section.indirectSymbols) {
971 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +0000972 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +0000973 else
974 *indirects++ = index;
975 }
976 }
977 } else {
978 // Final linked images must sort sections from normalized file.
979 for (const Segment &seg : _file.segments) {
980 SegExtraInfo &segInfo = _segInfo[&seg];
981 for (const Section *section : segInfo.sections) {
982 for (uint32_t index : section->indirectSymbols) {
983 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +0000984 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +0000985 else
986 *indirects++ = index;
987 }
988 }
989 }
990 }
991}
992
993void MachOFileLayout::writeRebaseInfo() {
994 memcpy(&_buffer[_startOfRebaseInfo], _rebaseInfo.bytes(), _rebaseInfo.size());
995}
996
997void MachOFileLayout::writeBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000998 memcpy(&_buffer[_startOfBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +0000999 _bindingInfo.bytes(), _bindingInfo.size());
1000}
1001
1002void MachOFileLayout::writeLazyBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001003 memcpy(&_buffer[_startOfLazyBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +00001004 _lazyBindingInfo.bytes(), _lazyBindingInfo.size());
1005}
1006
Nick Kledzik141330a2014-09-03 19:52:50 +00001007void MachOFileLayout::writeExportInfo() {
1008 memcpy(&_buffer[_startOfExportTrie], _exportTrie.bytes(), _exportTrie.size());
1009}
1010
Nick Kledzike34182f2013-11-06 21:36:55 +00001011void MachOFileLayout::buildLinkEditInfo() {
1012 buildRebaseInfo();
1013 buildBindInfo();
1014 buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +00001015 buildExportTrie();
Nick Kledzike34182f2013-11-06 21:36:55 +00001016 computeSymbolTableSizes();
Nick Kledzik21921372014-07-24 23:06:56 +00001017 computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +00001018}
1019
1020void MachOFileLayout::buildSectionRelocations() {
1021
1022}
1023
1024void MachOFileLayout::buildRebaseInfo() {
1025 // TODO: compress rebasing info.
1026 for (const RebaseLocation& entry : _file.rebasingInfo) {
1027 _rebaseInfo.append_byte(REBASE_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001028 _rebaseInfo.append_byte(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001029 | entry.segIndex);
1030 _rebaseInfo.append_uleb128(entry.segOffset);
1031 _rebaseInfo.append_uleb128(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 1);
1032 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001033 _rebaseInfo.append_byte(REBASE_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001034 _rebaseInfo.align(_is64 ? 8 : 4);
1035}
1036
1037void MachOFileLayout::buildBindInfo() {
1038 // TODO: compress bind info.
Nick Kledzikf373c772014-11-11 01:31:18 +00001039 uint64_t lastAddend = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +00001040 for (const BindLocation& entry : _file.bindingInfo) {
1041 _bindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001042 _bindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001043 | entry.segIndex);
1044 _bindingInfo.append_uleb128(entry.segOffset);
Lang Hames5c692002015-09-28 20:25:14 +00001045 if (entry.ordinal > 0)
1046 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
1047 (entry.ordinal & 0xF));
1048 else
1049 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1050 (entry.ordinal & 0xF));
Nick Kledzike34182f2013-11-06 21:36:55 +00001051 _bindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1052 _bindingInfo.append_string(entry.symbolName);
Nick Kledzikf373c772014-11-11 01:31:18 +00001053 if (entry.addend != lastAddend) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001054 _bindingInfo.append_byte(BIND_OPCODE_SET_ADDEND_SLEB);
1055 _bindingInfo.append_sleb128(entry.addend);
Nick Kledzikf373c772014-11-11 01:31:18 +00001056 lastAddend = entry.addend;
Nick Kledzike34182f2013-11-06 21:36:55 +00001057 }
1058 _bindingInfo.append_byte(BIND_OPCODE_DO_BIND);
1059 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001060 _bindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001061 _bindingInfo.align(_is64 ? 8 : 4);
1062}
1063
1064void MachOFileLayout::buildLazyBindInfo() {
1065 for (const BindLocation& entry : _file.lazyBindingInfo) {
1066 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001067 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001068 | entry.segIndex);
Nick Kledzikf373c772014-11-11 01:31:18 +00001069 _lazyBindingInfo.append_uleb128Fixed(entry.segOffset, 5);
Lang Hames5c692002015-09-28 20:25:14 +00001070 if (entry.ordinal > 0)
1071 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
1072 (entry.ordinal & 0xF));
1073 else
1074 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
1075 (entry.ordinal & 0xF));
Nick Kledzike34182f2013-11-06 21:36:55 +00001076 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1077 _lazyBindingInfo.append_string(entry.symbolName);
1078 _lazyBindingInfo.append_byte(BIND_OPCODE_DO_BIND);
Nick Kledzikf373c772014-11-11 01:31:18 +00001079 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001080 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001081 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001082 _lazyBindingInfo.align(_is64 ? 8 : 4);
1083}
1084
Nick Kledzik141330a2014-09-03 19:52:50 +00001085void MachOFileLayout::TrieNode::addSymbol(const Export& entry,
1086 BumpPtrAllocator &allocator,
1087 std::vector<TrieNode*> &allNodes) {
1088 StringRef partialStr = entry.name.drop_front(_cummulativeString.size());
1089 for (TrieEdge &edge : _children) {
1090 StringRef edgeStr = edge._subString;
1091 if (partialStr.startswith(edgeStr)) {
1092 // Already have matching edge, go down that path.
1093 edge._child->addSymbol(entry, allocator, allNodes);
1094 return;
1095 }
1096 // See if string has commmon prefix with existing edge.
1097 for (int n=edgeStr.size()-1; n > 0; --n) {
1098 if (partialStr.substr(0, n).equals(edgeStr.substr(0, n))) {
1099 // Splice in new node: was A -> C, now A -> B -> C
1100 StringRef bNodeStr = edge._child->_cummulativeString;
1101 bNodeStr = bNodeStr.drop_back(edgeStr.size()-n).copy(allocator);
1102 TrieNode* bNode = new (allocator) TrieNode(bNodeStr);
1103 allNodes.push_back(bNode);
1104 TrieNode* cNode = edge._child;
1105 StringRef abEdgeStr = edgeStr.substr(0,n).copy(allocator);
1106 StringRef bcEdgeStr = edgeStr.substr(n).copy(allocator);
1107 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1108 << "splice in TrieNode('" << bNodeStr
1109 << "') between edge '"
1110 << abEdgeStr << "' and edge='"
1111 << bcEdgeStr<< "'\n");
1112 TrieEdge& abEdge = edge;
1113 abEdge._subString = abEdgeStr;
1114 abEdge._child = bNode;
Nick Kledzik07ba5122014-12-02 01:50:44 +00001115 TrieEdge *bcEdge = new (allocator) TrieEdge(bcEdgeStr, cNode);
1116 bNode->_children.push_back(std::move(*bcEdge));
Nick Kledzik141330a2014-09-03 19:52:50 +00001117 bNode->addSymbol(entry, allocator, allNodes);
1118 return;
1119 }
1120 }
1121 }
1122 if (entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1123 assert(entry.otherOffset != 0);
1124 }
1125 if (entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
1126 assert(entry.otherOffset != 0);
1127 }
1128 // No commonality with any existing child, make a new edge.
1129 TrieNode* newNode = new (allocator) TrieNode(entry.name.copy(allocator));
Nick Kledzik07ba5122014-12-02 01:50:44 +00001130 TrieEdge *newEdge = new (allocator) TrieEdge(partialStr, newNode);
1131 _children.push_back(std::move(*newEdge));
Nick Kledzik141330a2014-09-03 19:52:50 +00001132 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1133 << "new TrieNode('" << entry.name << "') with edge '"
1134 << partialStr << "' from node='"
1135 << _cummulativeString << "'\n");
1136 newNode->_address = entry.offset;
1137 newNode->_flags = entry.flags | entry.kind;
1138 newNode->_other = entry.otherOffset;
1139 if ((entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) && !entry.otherName.empty())
1140 newNode->_importedName = entry.otherName.copy(allocator);
1141 newNode->_hasExportInfo = true;
1142 allNodes.push_back(newNode);
1143}
1144
1145bool MachOFileLayout::TrieNode::updateOffset(uint32_t& offset) {
1146 uint32_t nodeSize = 1; // Length when no export info
1147 if (_hasExportInfo) {
1148 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1149 nodeSize = llvm::getULEB128Size(_flags);
1150 nodeSize += llvm::getULEB128Size(_other); // Other contains ordinal.
1151 nodeSize += _importedName.size();
1152 ++nodeSize; // Trailing zero in imported name.
1153 } else {
1154 nodeSize = llvm::getULEB128Size(_flags) + llvm::getULEB128Size(_address);
1155 if (_flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1156 nodeSize += llvm::getULEB128Size(_other);
1157 }
1158 // Overall node size so far is uleb128 of export info + actual export info.
1159 nodeSize += llvm::getULEB128Size(nodeSize);
1160 }
1161 // Compute size of all child edges.
1162 ++nodeSize; // Byte for number of chidren.
1163 for (TrieEdge &edge : _children) {
1164 nodeSize += edge._subString.size() + 1 // String length.
1165 + llvm::getULEB128Size(edge._child->_trieOffset); // Offset len.
1166 }
1167 // On input, 'offset' is new prefered location for this node.
1168 bool result = (_trieOffset != offset);
1169 // Store new location in node object for use by parents.
1170 _trieOffset = offset;
1171 // Update offset for next iteration.
1172 offset += nodeSize;
1173 // Return true if _trieOffset was changed.
1174 return result;
1175}
1176
1177void MachOFileLayout::TrieNode::appendToByteBuffer(ByteBuffer &out) {
1178 if (_hasExportInfo) {
1179 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1180 if (!_importedName.empty()) {
1181 // nodes with re-export info: size, flags, ordinal, import-name
1182 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1183 + llvm::getULEB128Size(_other)
1184 + _importedName.size() + 1;
1185 assert(nodeSize < 256);
1186 out.append_byte(nodeSize);
1187 out.append_uleb128(_flags);
1188 out.append_uleb128(_other);
1189 out.append_string(_importedName);
1190 } else {
1191 // nodes without re-export info: size, flags, ordinal, empty-string
1192 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1193 + llvm::getULEB128Size(_other) + 1;
1194 assert(nodeSize < 256);
1195 out.append_byte(nodeSize);
1196 out.append_uleb128(_flags);
1197 out.append_uleb128(_other);
1198 out.append_byte(0);
1199 }
1200 } else if ( _flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) {
1201 // Nodes with export info: size, flags, address, other
1202 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1203 + llvm::getULEB128Size(_address)
1204 + llvm::getULEB128Size(_other);
1205 assert(nodeSize < 256);
1206 out.append_byte(nodeSize);
1207 out.append_uleb128(_flags);
1208 out.append_uleb128(_address);
1209 out.append_uleb128(_other);
1210 } else {
1211 // Nodes with export info: size, flags, address
1212 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1213 + llvm::getULEB128Size(_address);
1214 assert(nodeSize < 256);
1215 out.append_byte(nodeSize);
1216 out.append_uleb128(_flags);
1217 out.append_uleb128(_address);
1218 }
1219 } else {
1220 // Node with no export info.
1221 uint32_t nodeSize = 0;
1222 out.append_byte(nodeSize);
1223 }
1224 // Add number of children.
1225 assert(_children.size() < 256);
1226 out.append_byte(_children.size());
1227 // Append each child edge substring and node offset.
1228 for (TrieEdge &edge : _children) {
1229 out.append_string(edge._subString);
1230 out.append_uleb128(edge._child->_trieOffset);
1231 }
1232}
1233
1234void MachOFileLayout::buildExportTrie() {
1235 if (_file.exportInfo.empty())
1236 return;
1237
1238 // For all temporary strings and objects used building trie.
1239 BumpPtrAllocator allocator;
1240
1241 // Build trie of all exported symbols.
1242 TrieNode* rootNode = new (allocator) TrieNode(StringRef());
1243 std::vector<TrieNode*> allNodes;
1244 allNodes.reserve(_file.exportInfo.size()*2);
1245 allNodes.push_back(rootNode);
1246 for (const Export& entry : _file.exportInfo) {
1247 rootNode->addSymbol(entry, allocator, allNodes);
1248 }
1249
1250 // Assign each node in the vector an offset in the trie stream, iterating
1251 // until all uleb128 sizes have stabilized.
1252 bool more;
1253 do {
1254 uint32_t offset = 0;
1255 more = false;
1256 for (TrieNode* node : allNodes) {
1257 if (node->updateOffset(offset))
1258 more = true;
1259 }
1260 } while (more);
1261
1262 // Serialize trie to ByteBuffer.
1263 for (TrieNode* node : allNodes) {
1264 node->appendToByteBuffer(_exportTrie);
1265 }
1266 _exportTrie.align(_is64 ? 8 : 4);
1267}
1268
1269
Nick Kledzike34182f2013-11-06 21:36:55 +00001270void MachOFileLayout::computeSymbolTableSizes() {
1271 // MachO symbol tables have three ranges: locals, globals, and undefines
1272 const size_t nlistSize = (_is64 ? sizeof(nlist_64) : sizeof(nlist));
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001273 _symbolTableSize = nlistSize * (_file.localSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +00001274 + _file.globalSymbols.size()
1275 + _file.undefinedSymbols.size());
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001276 _symbolStringPoolSize = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +00001277 for (const Symbol &sym : _file.localSymbols) {
1278 _symbolStringPoolSize += (sym.name.size()+1);
1279 }
1280 for (const Symbol &sym : _file.globalSymbols) {
1281 _symbolStringPoolSize += (sym.name.size()+1);
1282 }
1283 for (const Symbol &sym : _file.undefinedSymbols) {
1284 _symbolStringPoolSize += (sym.name.size()+1);
1285 }
1286 _symbolTableLocalsStartIndex = 0;
1287 _symbolTableGlobalsStartIndex = _file.localSymbols.size();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001288 _symbolTableUndefinesStartIndex = _symbolTableGlobalsStartIndex
Nick Kledzike34182f2013-11-06 21:36:55 +00001289 + _file.globalSymbols.size();
1290
1291 _indirectSymbolTableCount = 0;
1292 for (const Section &sect : _file.sections) {
1293 _indirectSymbolTableCount += sect.indirectSymbols.size();
1294 }
1295}
1296
Nick Kledzik21921372014-07-24 23:06:56 +00001297void MachOFileLayout::computeDataInCodeSize() {
1298 _dataInCodeSize = _file.dataInCode.size() * sizeof(data_in_code_entry);
1299}
Nick Kledzike34182f2013-11-06 21:36:55 +00001300
1301void MachOFileLayout::writeLinkEditContent() {
1302 if (_file.fileType == llvm::MachO::MH_OBJECT) {
1303 writeRelocations();
Nick Kledzik21921372014-07-24 23:06:56 +00001304 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001305 writeSymbolTable();
1306 } else {
1307 writeRebaseInfo();
1308 writeBindingInfo();
1309 writeLazyBindingInfo();
1310 // TODO: add weak binding info
Nick Kledzik141330a2014-09-03 19:52:50 +00001311 writeExportInfo();
Nick Kledzik54ce29582014-10-28 22:21:10 +00001312 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001313 writeSymbolTable();
1314 }
1315}
1316
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001317std::error_code MachOFileLayout::writeBinary(StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001318 // Check for pending error from constructor.
1319 if (_ec)
1320 return _ec;
1321 // Create FileOutputBuffer with calculated size.
Nick Kledzike34182f2013-11-06 21:36:55 +00001322 unsigned flags = 0;
1323 if (_file.fileType != llvm::MachO::MH_OBJECT)
1324 flags = llvm::FileOutputBuffer::F_executable;
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001325 ErrorOr<std::unique_ptr<llvm::FileOutputBuffer>> fobOrErr =
1326 llvm::FileOutputBuffer::create(path, size(), flags);
1327 if (std::error_code ec = fobOrErr.getError())
Nick Kledzike34182f2013-11-06 21:36:55 +00001328 return ec;
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001329 std::unique_ptr<llvm::FileOutputBuffer> &fob = *fobOrErr;
Nick Kledzike34182f2013-11-06 21:36:55 +00001330 // Write content.
1331 _buffer = fob->getBufferStart();
1332 writeMachHeader();
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001333 std::error_code ec = writeLoadCommands();
Nick Kledzike34182f2013-11-06 21:36:55 +00001334 if (ec)
1335 return ec;
1336 writeSectionContent();
1337 writeLinkEditContent();
1338 fob->commit();
1339
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001340 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +00001341}
1342
1343
Nick Kledzike34182f2013-11-06 21:36:55 +00001344/// Takes in-memory normalized view and writes a mach-o object file.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001345std::error_code writeBinary(const NormalizedFile &file, StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001346 MachOFileLayout layout(file);
1347 return layout.writeBinary(path);
1348}
1349
1350
1351} // namespace normalized
1352} // namespace mach_o
1353} // namespace lld