blob: 3bc341ffa3ac6d0930f208dc86afccc878fd4ddc [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>
43#include <map>
Rafael Espindola54427cc2014-06-12 17:15:58 +000044#include <system_error>
Nick Kledzike34182f2013-11-06 21:36:55 +000045
46using namespace llvm::MachO;
47
48namespace lld {
49namespace mach_o {
50namespace normalized {
51
52/// Utility class for writing a mach-o binary file given an in-memory
Shankar Easwaran3d8de472014-01-27 03:09:26 +000053/// normalized file.
Nick Kledzike34182f2013-11-06 21:36:55 +000054class MachOFileLayout {
55public:
Joey Goulyb275d7f2013-12-23 23:29:50 +000056 /// All layout computation is done in the constructor.
57 MachOFileLayout(const NormalizedFile &file);
58
Nick Kledzike34182f2013-11-06 21:36:55 +000059 /// Returns the final file size as computed in the constructor.
60 size_t size() const;
61
Nick Kledzik2fcbe822014-07-30 00:58:06 +000062 // Returns size of the mach_header and load commands.
63 size_t headerAndLoadCommandsSize() const;
64
Shankar Easwaran3d8de472014-01-27 03:09:26 +000065 /// Writes the normalized file as a binary mach-o file to the specified
Nick Kledzike34182f2013-11-06 21:36:55 +000066 /// path. This does not have a stream interface because the generated
67 /// file may need the 'x' bit set.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000068 std::error_code writeBinary(StringRef path);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000069
Nick Kledzike34182f2013-11-06 21:36:55 +000070private:
71 uint32_t loadCommandsSize(uint32_t &count);
72 void buildFileOffsets();
73 void writeMachHeader();
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +000074 std::error_code writeLoadCommands();
Nick Kledzike34182f2013-11-06 21:36:55 +000075 void writeSectionContent();
76 void writeRelocations();
77 void writeSymbolTable();
78 void writeRebaseInfo();
79 void writeBindingInfo();
80 void writeLazyBindingInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +000081 void writeExportInfo();
Nick Kledzik21921372014-07-24 23:06:56 +000082 void writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +000083 void writeLinkEditContent();
84 void buildLinkEditInfo();
85 void buildRebaseInfo();
86 void buildBindInfo();
87 void buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +000088 void buildExportTrie();
Nick Kledzik21921372014-07-24 23:06:56 +000089 void computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +000090 void computeSymbolTableSizes();
91 void buildSectionRelocations();
92 void appendSymbols(const std::vector<Symbol> &symbols,
93 uint32_t &symOffset, uint32_t &strOffset);
94 uint32_t indirectSymbolIndex(const Section &sect, uint32_t &index);
95 uint32_t indirectSymbolElementSize(const Section &sect);
96
Nick Kledzik29f749e2013-11-09 00:07:28 +000097 // For use as template parameter to load command methods.
98 struct MachO64Trait {
99 typedef llvm::MachO::segment_command_64 command;
100 typedef llvm::MachO::section_64 section;
101 enum { LC = llvm::MachO::LC_SEGMENT_64 };
102 };
103
104 // For use as template parameter to load command methods.
105 struct MachO32Trait {
106 typedef llvm::MachO::segment_command command;
107 typedef llvm::MachO::section section;
108 enum { LC = llvm::MachO::LC_SEGMENT };
109 };
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000110
Nick Kledzik29f749e2013-11-09 00:07:28 +0000111 template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000112 std::error_code writeSingleSegmentLoadCommand(uint8_t *&lc);
113 template <typename T> std::error_code writeSegmentLoadCommands(uint8_t *&lc);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000114
Nick Kledzike34182f2013-11-06 21:36:55 +0000115 uint32_t pointerAlign(uint32_t value);
116 static StringRef dyldPath();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000117
Nick Kledzike34182f2013-11-06 21:36:55 +0000118 class ByteBuffer {
119 public:
Nick Kledzik00a15d92013-11-09 01:00:51 +0000120 ByteBuffer() : _ostream(_bytes) { }
Nick Kledzik141330a2014-09-03 19:52:50 +0000121
Nick Kledzik00a15d92013-11-09 01:00:51 +0000122 void append_byte(uint8_t b) {
123 _ostream << b;
124 }
125 void append_uleb128(uint64_t value) {
126 llvm::encodeULEB128(value, _ostream);
127 }
Nick Kledzikf373c772014-11-11 01:31:18 +0000128 void append_uleb128Fixed(uint64_t value, unsigned byteCount) {
129 unsigned min = llvm::getULEB128Size(value);
130 assert(min <= byteCount);
131 unsigned pad = byteCount - min;
132 llvm::encodeULEB128(value, _ostream, pad);
133 }
Nick Kledzik00a15d92013-11-09 01:00:51 +0000134 void append_sleb128(int64_t value) {
135 llvm::encodeSLEB128(value, _ostream);
136 }
137 void append_string(StringRef str) {
138 _ostream << str;
139 append_byte(0);
140 }
141 void align(unsigned alignment) {
142 while ( (_ostream.tell() % alignment) != 0 )
143 append_byte(0);
144 }
145 size_t size() {
146 return _ostream.tell();
147 }
148 const uint8_t *bytes() {
149 return reinterpret_cast<const uint8_t*>(_ostream.str().data());
150 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000151 private:
Nick Kledzik00a15d92013-11-09 01:00:51 +0000152 SmallVector<char, 128> _bytes;
153 // Stream ivar must be after SmallVector ivar to construct properly.
154 llvm::raw_svector_ostream _ostream;
Nick Kledzike34182f2013-11-06 21:36:55 +0000155 };
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000156
Nick Kledzik141330a2014-09-03 19:52:50 +0000157 struct TrieNode; // Forward declaration.
158
159 struct TrieEdge {
160 TrieEdge(StringRef s, TrieNode *node) : _subString(s), _child(node) {}
161 ~TrieEdge() {}
162
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;
180 SmallVector<TrieEdge, 8> _children;
181 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) {
293 offset = llvm::RoundUpToAlignment(offset, 1 << sect.alignment);
294 _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
Nick Kledzik54ce29582014-10-28 22:21:10 +0000430 // Add LC_DATA_IN_CODE if needed
431 if (!_file.dataInCode.empty()) {
432 size += sizeof(linkedit_data_command);
433 ++count;
434 }
435
Nick Kledzike34182f2013-11-06 21:36:55 +0000436 return size;
437}
438
439static bool overlaps(const Segment &s1, const Segment &s2) {
440 if (s2.address >= s1.address+s1.size)
441 return false;
442 if (s1.address >= s2.address+s2.size)
443 return false;
444 return true;
445}
446
447static bool overlaps(const Section &s1, const Section &s2) {
448 if (s2.address >= s1.address+s1.content.size())
449 return false;
450 if (s1.address >= s2.address+s2.content.size())
451 return false;
452 return true;
453}
454
455void MachOFileLayout::buildFileOffsets() {
456 // Verify no segments overlap
457 for (const Segment &sg1 : _file.segments) {
458 for (const Segment &sg2 : _file.segments) {
459 if (&sg1 == &sg2)
460 continue;
461 if (overlaps(sg1,sg2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000462 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000463 return;
464 }
465 }
466 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000467
468 // Verify no sections overlap
Nick Kledzike34182f2013-11-06 21:36:55 +0000469 for (const Section &s1 : _file.sections) {
470 for (const Section &s2 : _file.sections) {
471 if (&s1 == &s2)
472 continue;
473 if (overlaps(s1,s2)) {
Rafael Espindola372bc702014-06-13 17:20:48 +0000474 _ec = make_error_code(llvm::errc::executable_format_error);
Nick Kledzike34182f2013-11-06 21:36:55 +0000475 return;
476 }
477 }
478 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000479
Nick Kledzike34182f2013-11-06 21:36:55 +0000480 // Build side table of extra info about segments and sections.
481 SegExtraInfo t;
482 t.fileOffset = 0;
483 for (const Segment &sg : _file.segments) {
484 _segInfo[&sg] = t;
485 }
486 SectionExtraInfo t2;
487 t2.fileOffset = 0;
488 // Assign sections to segments.
489 for (const Section &s : _file.sections) {
490 _sectInfo[&s] = t2;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000491 bool foundSegment = false;
Nick Kledzike34182f2013-11-06 21:36:55 +0000492 for (const Segment &sg : _file.segments) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000493 if (sg.name.equals(s.segmentName)) {
494 if ((s.address >= sg.address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000495 && (s.address+s.content.size() <= sg.address+sg.size)) {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000496 _segInfo[&sg].sections.push_back(&s);
497 foundSegment = true;
498 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000499 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000500 }
501 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000502 if (!foundSegment) {
503 _ec = make_error_code(llvm::errc::executable_format_error);
504 return;
505 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000506 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000507
Nick Kledzike34182f2013-11-06 21:36:55 +0000508 // Assign file offsets.
509 uint32_t fileOffset = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000510 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000511 llvm::dbgs() << "buildFileOffsets()\n");
512 for (const Segment &sg : _file.segments) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000513 _segInfo[&sg].fileOffset = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000514 if ((_seg1addr == INT64_MAX) && sg.access)
515 _seg1addr = sg.address;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000516 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000517 llvm::dbgs() << " segment=" << sg.name
518 << ", fileOffset=" << _segInfo[&sg].fileOffset << "\n");
Tim Northover08d6a7b2014-06-30 09:49:30 +0000519
520 uint32_t segFileSize = 0;
Nick Kledzik761d6542014-10-24 22:19:22 +0000521 // A segment that is not zero-fill must use a least one page of disk space.
522 if (sg.access)
523 segFileSize = _file.pageSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000524 for (const Section *s : _segInfo[&sg].sections) {
Tim Northover08d6a7b2014-06-30 09:49:30 +0000525 uint32_t sectOffset = s->address - sg.address;
526 uint32_t sectFileSize =
527 s->type == llvm::MachO::S_ZEROFILL ? 0 : s->content.size();
528 segFileSize = std::max(segFileSize, sectOffset + sectFileSize);
529
530 _sectInfo[s].fileOffset = _segInfo[&sg].fileOffset + sectOffset;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000531 DEBUG_WITH_TYPE("MachOFileLayout",
Nick Kledzike34182f2013-11-06 21:36:55 +0000532 llvm::dbgs() << " section=" << s->sectionName
533 << ", fileOffset=" << fileOffset << "\n");
534 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000535
Nick Kledzik1bebb282014-09-09 23:52:59 +0000536 _segInfo[&sg].fileSize = llvm::RoundUpToAlignment(segFileSize,
537 _file.pageSize);
538 fileOffset = llvm::RoundUpToAlignment(fileOffset + segFileSize,
539 _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000540 _addressOfLinkEdit = sg.address + sg.size;
541 }
Tim Northover08d6a7b2014-06-30 09:49:30 +0000542 _startOfLinkEdit = fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000543}
544
545
546size_t MachOFileLayout::size() const {
547 return _endOfSymbolStrings;
548}
549
550void MachOFileLayout::writeMachHeader() {
551 mach_header *mh = reinterpret_cast<mach_header*>(_buffer);
552 mh->magic = _is64 ? llvm::MachO::MH_MAGIC_64 : llvm::MachO::MH_MAGIC;
553 mh->cputype = MachOLinkingContext::cpuTypeFromArch(_file.arch);
554 mh->cpusubtype = MachOLinkingContext::cpuSubtypeFromArch(_file.arch);
555 mh->filetype = _file.fileType;
556 mh->ncmds = _countOfLoadCommands;
557 mh->sizeofcmds = _endOfLoadCommands - _startOfLoadCommands;
558 mh->flags = _file.flags;
559 if (_swap)
560 swapStruct(*mh);
561}
562
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000563uint32_t MachOFileLayout::indirectSymbolIndex(const Section &sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000564 uint32_t &index) {
565 if (sect.indirectSymbols.empty())
566 return 0;
567 uint32_t result = index;
568 index += sect.indirectSymbols.size();
569 return result;
570}
571
572uint32_t MachOFileLayout::indirectSymbolElementSize(const Section &sect) {
573 if (sect.indirectSymbols.empty())
574 return 0;
575 if (sect.type != S_SYMBOL_STUBS)
576 return 0;
577 return sect.content.size() / sect.indirectSymbols.size();
578}
579
Nick Kledzik29f749e2013-11-09 00:07:28 +0000580template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000581std::error_code MachOFileLayout::writeSingleSegmentLoadCommand(uint8_t *&lc) {
Nick Kledzik29f749e2013-11-09 00:07:28 +0000582 typename T::command* seg = reinterpret_cast<typename T::command*>(lc);
583 seg->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000584 seg->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000585 + _file.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000586 uint8_t *next = lc + seg->cmdsize;
587 memset(seg->segname, 0, 16);
588 seg->vmaddr = 0;
Nick Kledzikb072c362014-11-18 00:30:29 +0000589 seg->vmsize = _file.sections.back().address
590 + _file.sections.back().content.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000591 seg->fileoff = _endOfLoadCommands;
592 seg->filesize = seg->vmsize;
593 seg->maxprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
594 seg->initprot = VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE;
595 seg->nsects = _file.sections.size();
596 seg->flags = 0;
597 if (_swap)
598 swapStruct(*seg);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000599 typename T::section *sout = reinterpret_cast<typename T::section*>
600 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000601 uint32_t relOffset = _startOfRelocations;
Nick Kledzike34182f2013-11-06 21:36:55 +0000602 uint32_t indirectSymRunningIndex = 0;
603 for (const Section &sin : _file.sections) {
604 setString16(sin.sectionName, sout->sectname);
605 setString16(sin.segmentName, sout->segname);
606 sout->addr = sin.address;
607 sout->size = sin.content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000608 sout->offset = _sectInfo[&sin].fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000609 sout->align = sin.alignment;
610 sout->reloff = sin.relocations.empty() ? 0 : relOffset;
611 sout->nreloc = sin.relocations.size();
612 sout->flags = sin.type | sin.attributes;
613 sout->reserved1 = indirectSymbolIndex(sin, indirectSymRunningIndex);
614 sout->reserved2 = indirectSymbolElementSize(sin);
615 relOffset += sin.relocations.size() * sizeof(any_relocation_info);
Nick Kledzike34182f2013-11-06 21:36:55 +0000616 if (_swap)
617 swapStruct(*sout);
618 ++sout;
619 }
620 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000621 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000622}
623
Nick Kledzik29f749e2013-11-09 00:07:28 +0000624template <typename T>
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000625std::error_code MachOFileLayout::writeSegmentLoadCommands(uint8_t *&lc) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000626 uint32_t indirectSymRunningIndex = 0;
627 for (const Segment &seg : _file.segments) {
628 // Write segment command with trailing sections.
629 SegExtraInfo &segInfo = _segInfo[&seg];
Nick Kledzik29f749e2013-11-09 00:07:28 +0000630 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
631 cmd->cmd = T::LC;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000632 cmd->cmdsize = sizeof(typename T::command)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000633 + segInfo.sections.size() * sizeof(typename T::section);
Nick Kledzike34182f2013-11-06 21:36:55 +0000634 uint8_t *next = lc + cmd->cmdsize;
635 setString16(seg.name, cmd->segname);
636 cmd->vmaddr = seg.address;
637 cmd->vmsize = seg.size;
638 cmd->fileoff = segInfo.fileOffset;
Tim Northover08d6a7b2014-06-30 09:49:30 +0000639 cmd->filesize = segInfo.fileSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000640 cmd->maxprot = seg.access;
641 cmd->initprot = seg.access;
642 cmd->nsects = segInfo.sections.size();
643 cmd->flags = 0;
644 if (_swap)
645 swapStruct(*cmd);
Nick Kledzik29f749e2013-11-09 00:07:28 +0000646 typename T::section *sect = reinterpret_cast<typename T::section*>
647 (lc+sizeof(typename T::command));
Nick Kledzike34182f2013-11-06 21:36:55 +0000648 for (const Section *section : segInfo.sections) {
649 setString16(section->sectionName, sect->sectname);
650 setString16(section->segmentName, sect->segname);
651 sect->addr = section->address;
652 sect->size = section->content.size();
Nick Kledzikb072c362014-11-18 00:30:29 +0000653 if (section->type == llvm::MachO::S_ZEROFILL)
654 sect->offset = 0;
655 else
656 sect->offset = section->address - seg.address + segInfo.fileOffset;
Nick Kledzike34182f2013-11-06 21:36:55 +0000657 sect->align = section->alignment;
658 sect->reloff = 0;
659 sect->nreloc = 0;
660 sect->flags = section->type | section->attributes;
661 sect->reserved1 = indirectSymbolIndex(*section, indirectSymRunningIndex);
662 sect->reserved2 = indirectSymbolElementSize(*section);
663 if (_swap)
664 swapStruct(*sect);
665 ++sect;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000666 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000667 lc = reinterpret_cast<uint8_t*>(next);
668 }
669 // Add implicit __LINKEDIT segment
Nick Kledzik1bebb282014-09-09 23:52:59 +0000670 size_t linkeditSize = _endOfLinkEdit - _startOfLinkEdit;
Nick Kledzik29f749e2013-11-09 00:07:28 +0000671 typename T::command* cmd = reinterpret_cast<typename T::command*>(lc);
672 cmd->cmd = T::LC;
673 cmd->cmdsize = sizeof(typename T::command);
Nick Kledzike34182f2013-11-06 21:36:55 +0000674 uint8_t *next = lc + cmd->cmdsize;
675 setString16("__LINKEDIT", cmd->segname);
676 cmd->vmaddr = _addressOfLinkEdit;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000677 cmd->vmsize = llvm::RoundUpToAlignment(linkeditSize, _file.pageSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000678 cmd->fileoff = _startOfLinkEdit;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000679 cmd->filesize = linkeditSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000680 cmd->maxprot = VM_PROT_READ;
681 cmd->initprot = VM_PROT_READ;
682 cmd->nsects = 0;
683 cmd->flags = 0;
684 if (_swap)
685 swapStruct(*cmd);
686 lc = next;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000687 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +0000688}
689
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +0000690std::error_code MachOFileLayout::writeLoadCommands() {
691 std::error_code ec;
Nick Kledzike34182f2013-11-06 21:36:55 +0000692 uint8_t *lc = &_buffer[_startOfLoadCommands];
693 if (_file.fileType == llvm::MachO::MH_OBJECT) {
694 // Object files have one unnamed segment which holds all sections.
695 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000696 ec = writeSingleSegmentLoadCommand<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000697 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000698 ec = writeSingleSegmentLoadCommand<MachO32Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000699 // Add LC_SYMTAB with symbol table info
700 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
701 st->cmd = LC_SYMTAB;
702 st->cmdsize = sizeof(symtab_command);
703 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000704 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000705 + _file.undefinedSymbols.size();
706 st->stroff = _startOfSymbolStrings;
707 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
708 if (_swap)
709 swapStruct(*st);
Nick Kledzik21921372014-07-24 23:06:56 +0000710 lc += sizeof(symtab_command);
711 // Add LC_DATA_IN_CODE if needed.
712 if (_dataInCodeSize != 0) {
713 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
714 dl->cmd = LC_DATA_IN_CODE;
715 dl->cmdsize = sizeof(linkedit_data_command);
716 dl->dataoff = _startOfDataInCode;
717 dl->datasize = _dataInCodeSize;
718 if (_swap)
719 swapStruct(*dl);
720 lc += sizeof(linkedit_data_command);
721 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000722 } else {
723 // Final linked images have sections under segments.
724 if (_is64)
Nick Kledzik29f749e2013-11-09 00:07:28 +0000725 ec = writeSegmentLoadCommands<MachO64Trait>(lc);
Nick Kledzike34182f2013-11-06 21:36:55 +0000726 else
Nick Kledzik29f749e2013-11-09 00:07:28 +0000727 ec = writeSegmentLoadCommands<MachO32Trait>(lc);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000728
Tim Northover301c4e62014-07-01 08:15:41 +0000729 // Add LC_ID_DYLIB command for dynamic libraries.
730 if (_file.fileType == llvm::MachO::MH_DYLIB) {
731 dylib_command *dc = reinterpret_cast<dylib_command*>(lc);
732 StringRef path = _file.installName;
733 uint32_t size = sizeof(dylib_command) + pointerAlign(path.size() + 1);
734 dc->cmd = LC_ID_DYLIB;
735 dc->cmdsize = size;
736 dc->dylib.name = sizeof(dylib_command); // offset
737 dc->dylib.timestamp = 0; // FIXME
738 dc->dylib.current_version = 0; // FIXME
739 dc->dylib.compatibility_version = 0; // FIXME
740 if (_swap)
741 swapStruct(*dc);
742 memcpy(lc + sizeof(dylib_command), path.begin(), path.size());
743 lc[sizeof(dylib_command) + path.size()] = '\0';
744 lc += size;
745 }
746
Nick Kledzike34182f2013-11-06 21:36:55 +0000747 // Add LC_DYLD_INFO_ONLY.
748 dyld_info_command* di = reinterpret_cast<dyld_info_command*>(lc);
749 di->cmd = LC_DYLD_INFO_ONLY;
750 di->cmdsize = sizeof(dyld_info_command);
751 di->rebase_off = _rebaseInfo.size() ? _startOfRebaseInfo : 0;
752 di->rebase_size = _rebaseInfo.size();
753 di->bind_off = _bindingInfo.size() ? _startOfBindingInfo : 0;
754 di->bind_size = _bindingInfo.size();
755 di->weak_bind_off = 0;
756 di->weak_bind_size = 0;
757 di->lazy_bind_off = _lazyBindingInfo.size() ? _startOfLazyBindingInfo : 0;
758 di->lazy_bind_size = _lazyBindingInfo.size();
Nick Kledzik141330a2014-09-03 19:52:50 +0000759 di->export_off = _exportTrie.size() ? _startOfExportTrie : 0;
760 di->export_size = _exportTrie.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000761 if (_swap)
762 swapStruct(*di);
763 lc += sizeof(dyld_info_command);
764
765 // Add LC_SYMTAB with symbol table info.
766 symtab_command* st = reinterpret_cast<symtab_command*>(lc);
767 st->cmd = LC_SYMTAB;
768 st->cmdsize = sizeof(symtab_command);
769 st->symoff = _startOfSymbols;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000770 st->nsyms = _file.localSymbols.size() + _file.globalSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +0000771 + _file.undefinedSymbols.size();
772 st->stroff = _startOfSymbolStrings;
773 st->strsize = _endOfSymbolStrings - _startOfSymbolStrings;
774 if (_swap)
775 swapStruct(*st);
776 lc += sizeof(symtab_command);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000777
Nick Kledzike34182f2013-11-06 21:36:55 +0000778 // Add LC_DYSYMTAB
779 if (_file.fileType != llvm::MachO::MH_PRELOAD) {
780 dysymtab_command* dst = reinterpret_cast<dysymtab_command*>(lc);
781 dst->cmd = LC_DYSYMTAB;
782 dst->cmdsize = sizeof(dysymtab_command);
783 dst->ilocalsym = _symbolTableLocalsStartIndex;
784 dst->nlocalsym = _file.localSymbols.size();
785 dst->iextdefsym = _symbolTableGlobalsStartIndex;
786 dst->nextdefsym = _file.globalSymbols.size();
787 dst->iundefsym = _symbolTableUndefinesStartIndex;
788 dst->nundefsym = _file.undefinedSymbols.size();
789 dst->tocoff = 0;
790 dst->ntoc = 0;
791 dst->modtaboff = 0;
792 dst->nmodtab = 0;
793 dst->extrefsymoff = 0;
794 dst->nextrefsyms = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000795 dst->indirectsymoff = _startOfIndirectSymbols;
Nick Kledzike34182f2013-11-06 21:36:55 +0000796 dst->nindirectsyms = _indirectSymbolTableCount;
797 dst->extreloff = 0;
798 dst->nextrel = 0;
799 dst->locreloff = 0;
800 dst->nlocrel = 0;
801 if (_swap)
802 swapStruct(*dst);
803 lc += sizeof(dysymtab_command);
804 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000805
Nick Kledzike34182f2013-11-06 21:36:55 +0000806 // If main executable, add LC_LOAD_DYLINKER and LC_MAIN.
807 if (_file.fileType == llvm::MachO::MH_EXECUTE) {
808 // Build LC_LOAD_DYLINKER load command.
809 uint32_t size=pointerAlign(sizeof(dylinker_command)+dyldPath().size()+1);
810 dylinker_command* dl = reinterpret_cast<dylinker_command*>(lc);
811 dl->cmd = LC_LOAD_DYLINKER;
812 dl->cmdsize = size;
813 dl->name = sizeof(dylinker_command); // offset
814 if (_swap)
815 swapStruct(*dl);
816 memcpy(lc+sizeof(dylinker_command), dyldPath().data(), dyldPath().size());
817 lc[sizeof(dylinker_command)+dyldPath().size()] = '\0';
818 lc += size;
819 // Build LC_MAIN load command.
820 entry_point_command* ep = reinterpret_cast<entry_point_command*>(lc);
821 ep->cmd = LC_MAIN;
822 ep->cmdsize = sizeof(entry_point_command);
823 ep->entryoff = _file.entryAddress - _seg1addr;
824 ep->stacksize = 0;
825 if (_swap)
826 swapStruct(*ep);
827 lc += sizeof(entry_point_command);
828 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000829
Nick Kledzike34182f2013-11-06 21:36:55 +0000830 // Add LC_LOAD_DYLIB commands
831 for (const DependentDylib &dep : _file.dependentDylibs) {
832 dylib_command* dc = reinterpret_cast<dylib_command*>(lc);
833 uint32_t size = sizeof(dylib_command) + pointerAlign(dep.path.size()+1);
Nick Kledzik51720672014-10-16 19:31:28 +0000834 dc->cmd = dep.kind;
Nick Kledzike34182f2013-11-06 21:36:55 +0000835 dc->cmdsize = size;
836 dc->dylib.name = sizeof(dylib_command); // offset
837 dc->dylib.timestamp = 0; // FIXME
838 dc->dylib.current_version = 0; // FIXME
839 dc->dylib.compatibility_version = 0; // FIXME
840 if (_swap)
841 swapStruct(*dc);
842 memcpy(lc+sizeof(dylib_command), dep.path.begin(), dep.path.size());
843 lc[sizeof(dylib_command)+dep.path.size()] = '\0';
844 lc += size;
845 }
Nick Kledzik54ce29582014-10-28 22:21:10 +0000846 // Add LC_DATA_IN_CODE if needed.
847 if (_dataInCodeSize != 0) {
848 linkedit_data_command* dl = reinterpret_cast<linkedit_data_command*>(lc);
849 dl->cmd = LC_DATA_IN_CODE;
850 dl->cmdsize = sizeof(linkedit_data_command);
851 dl->dataoff = _startOfDataInCode;
852 dl->datasize = _dataInCodeSize;
853 if (_swap)
854 swapStruct(*dl);
855 lc += sizeof(linkedit_data_command);
856 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000857 }
858 return ec;
859}
860
861
862void MachOFileLayout::writeSectionContent() {
863 for (const Section &s : _file.sections) {
864 // Copy all section content to output buffer.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000865 if (s.type == llvm::MachO::S_ZEROFILL)
866 continue;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000867 if (s.content.empty())
868 continue;
Nick Kledzike34182f2013-11-06 21:36:55 +0000869 uint32_t offset = _sectInfo[&s].fileOffset;
870 uint8_t *p = &_buffer[offset];
871 memcpy(p, &s.content[0], s.content.size());
872 p += s.content.size();
873 }
874}
875
876void MachOFileLayout::writeRelocations() {
877 uint32_t relOffset = _startOfRelocations;
878 for (Section sect : _file.sections) {
879 for (Relocation r : sect.relocations) {
880 any_relocation_info* rb = reinterpret_cast<any_relocation_info*>(
881 &_buffer[relOffset]);
882 *rb = packRelocation(r, _swap, _bigEndianArch);
883 relOffset += sizeof(any_relocation_info);
884 }
885 }
886}
887
888
889void MachOFileLayout::appendSymbols(const std::vector<Symbol> &symbols,
890 uint32_t &symOffset, uint32_t &strOffset) {
891 for (const Symbol &sym : symbols) {
892 if (_is64) {
893 nlist_64* nb = reinterpret_cast<nlist_64*>(&_buffer[symOffset]);
894 nb->n_strx = strOffset - _startOfSymbolStrings;
895 nb->n_type = sym.type | sym.scope;
896 nb->n_sect = sym.sect;
897 nb->n_desc = sym.desc;
898 nb->n_value = sym.value;
899 if (_swap)
900 swapStruct(*nb);
901 symOffset += sizeof(nlist_64);
902 } else {
903 nlist* nb = reinterpret_cast<nlist*>(&_buffer[symOffset]);
904 nb->n_strx = strOffset - _startOfSymbolStrings;
905 nb->n_type = sym.type | sym.scope;
906 nb->n_sect = sym.sect;
907 nb->n_desc = sym.desc;
908 nb->n_value = sym.value;
909 if (_swap)
910 swapStruct(*nb);
911 symOffset += sizeof(nlist);
912 }
913 memcpy(&_buffer[strOffset], sym.name.begin(), sym.name.size());
914 strOffset += sym.name.size();
915 _buffer[strOffset++] ='\0'; // Strings in table have nul terminator.
916 }
917}
918
Nick Kledzik21921372014-07-24 23:06:56 +0000919void MachOFileLayout::writeDataInCodeInfo() {
920 uint32_t offset = _startOfDataInCode;
921 for (const DataInCode &entry : _file.dataInCode) {
922 data_in_code_entry *dst = reinterpret_cast<data_in_code_entry*>(
923 &_buffer[offset]);
924 dst->offset = entry.offset;
925 dst->length = entry.length;
926 dst->kind = entry.kind;
927 if (_swap)
928 swapStruct(*dst);
929 offset += sizeof(data_in_code_entry);
930 }
931}
932
Nick Kledzike34182f2013-11-06 21:36:55 +0000933void MachOFileLayout::writeSymbolTable() {
934 // Write symbol table and symbol strings in parallel.
935 uint32_t symOffset = _startOfSymbols;
936 uint32_t strOffset = _startOfSymbolStrings;
937 _buffer[strOffset++] = '\0'; // Reserve n_strx offset of zero to mean no name.
938 appendSymbols(_file.localSymbols, symOffset, strOffset);
939 appendSymbols(_file.globalSymbols, symOffset, strOffset);
940 appendSymbols(_file.undefinedSymbols, symOffset, strOffset);
941 // Write indirect symbol table array.
942 uint32_t *indirects = reinterpret_cast<uint32_t*>
943 (&_buffer[_startOfIndirectSymbols]);
944 if (_file.fileType == llvm::MachO::MH_OBJECT) {
945 // Object files have sections in same order as input normalized file.
946 for (const Section &section : _file.sections) {
947 for (uint32_t index : section.indirectSymbols) {
948 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +0000949 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +0000950 else
951 *indirects++ = index;
952 }
953 }
954 } else {
955 // Final linked images must sort sections from normalized file.
956 for (const Segment &seg : _file.segments) {
957 SegExtraInfo &segInfo = _segInfo[&seg];
958 for (const Section *section : segInfo.sections) {
959 for (uint32_t index : section->indirectSymbols) {
960 if (_swap)
Artyom Skrobov17587fb2014-06-14 12:40:04 +0000961 *indirects++ = llvm::sys::getSwappedBytes(index);
Nick Kledzike34182f2013-11-06 21:36:55 +0000962 else
963 *indirects++ = index;
964 }
965 }
966 }
967 }
968}
969
970void MachOFileLayout::writeRebaseInfo() {
971 memcpy(&_buffer[_startOfRebaseInfo], _rebaseInfo.bytes(), _rebaseInfo.size());
972}
973
974void MachOFileLayout::writeBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000975 memcpy(&_buffer[_startOfBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +0000976 _bindingInfo.bytes(), _bindingInfo.size());
977}
978
979void MachOFileLayout::writeLazyBindingInfo() {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000980 memcpy(&_buffer[_startOfLazyBindingInfo],
Nick Kledzike34182f2013-11-06 21:36:55 +0000981 _lazyBindingInfo.bytes(), _lazyBindingInfo.size());
982}
983
Nick Kledzik141330a2014-09-03 19:52:50 +0000984void MachOFileLayout::writeExportInfo() {
985 memcpy(&_buffer[_startOfExportTrie], _exportTrie.bytes(), _exportTrie.size());
986}
987
Nick Kledzike34182f2013-11-06 21:36:55 +0000988void MachOFileLayout::buildLinkEditInfo() {
989 buildRebaseInfo();
990 buildBindInfo();
991 buildLazyBindInfo();
Nick Kledzik141330a2014-09-03 19:52:50 +0000992 buildExportTrie();
Nick Kledzike34182f2013-11-06 21:36:55 +0000993 computeSymbolTableSizes();
Nick Kledzik21921372014-07-24 23:06:56 +0000994 computeDataInCodeSize();
Nick Kledzike34182f2013-11-06 21:36:55 +0000995}
996
997void MachOFileLayout::buildSectionRelocations() {
998
999}
1000
1001void MachOFileLayout::buildRebaseInfo() {
1002 // TODO: compress rebasing info.
1003 for (const RebaseLocation& entry : _file.rebasingInfo) {
1004 _rebaseInfo.append_byte(REBASE_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001005 _rebaseInfo.append_byte(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001006 | entry.segIndex);
1007 _rebaseInfo.append_uleb128(entry.segOffset);
1008 _rebaseInfo.append_uleb128(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 1);
1009 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001010 _rebaseInfo.append_byte(REBASE_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001011 _rebaseInfo.align(_is64 ? 8 : 4);
1012}
1013
1014void MachOFileLayout::buildBindInfo() {
1015 // TODO: compress bind info.
Nick Kledzikf373c772014-11-11 01:31:18 +00001016 uint64_t lastAddend = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +00001017 for (const BindLocation& entry : _file.bindingInfo) {
1018 _bindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001019 _bindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001020 | entry.segIndex);
1021 _bindingInfo.append_uleb128(entry.segOffset);
1022 _bindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | entry.ordinal);
1023 _bindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1024 _bindingInfo.append_string(entry.symbolName);
Nick Kledzikf373c772014-11-11 01:31:18 +00001025 if (entry.addend != lastAddend) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001026 _bindingInfo.append_byte(BIND_OPCODE_SET_ADDEND_SLEB);
1027 _bindingInfo.append_sleb128(entry.addend);
Nick Kledzikf373c772014-11-11 01:31:18 +00001028 lastAddend = entry.addend;
Nick Kledzike34182f2013-11-06 21:36:55 +00001029 }
1030 _bindingInfo.append_byte(BIND_OPCODE_DO_BIND);
1031 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001032 _bindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001033 _bindingInfo.align(_is64 ? 8 : 4);
1034}
1035
1036void MachOFileLayout::buildLazyBindInfo() {
1037 for (const BindLocation& entry : _file.lazyBindingInfo) {
1038 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_TYPE_IMM | entry.kind);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001039 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB
Nick Kledzike34182f2013-11-06 21:36:55 +00001040 | entry.segIndex);
Nick Kledzikf373c772014-11-11 01:31:18 +00001041 _lazyBindingInfo.append_uleb128Fixed(entry.segOffset, 5);
Nick Kledzike34182f2013-11-06 21:36:55 +00001042 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | entry.ordinal);
1043 _lazyBindingInfo.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
1044 _lazyBindingInfo.append_string(entry.symbolName);
1045 _lazyBindingInfo.append_byte(BIND_OPCODE_DO_BIND);
Nick Kledzikf373c772014-11-11 01:31:18 +00001046 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001047 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001048 _lazyBindingInfo.append_byte(BIND_OPCODE_DONE);
Nick Kledzike34182f2013-11-06 21:36:55 +00001049 _lazyBindingInfo.align(_is64 ? 8 : 4);
1050}
1051
Nick Kledzik141330a2014-09-03 19:52:50 +00001052void MachOFileLayout::TrieNode::addSymbol(const Export& entry,
1053 BumpPtrAllocator &allocator,
1054 std::vector<TrieNode*> &allNodes) {
1055 StringRef partialStr = entry.name.drop_front(_cummulativeString.size());
1056 for (TrieEdge &edge : _children) {
1057 StringRef edgeStr = edge._subString;
1058 if (partialStr.startswith(edgeStr)) {
1059 // Already have matching edge, go down that path.
1060 edge._child->addSymbol(entry, allocator, allNodes);
1061 return;
1062 }
1063 // See if string has commmon prefix with existing edge.
1064 for (int n=edgeStr.size()-1; n > 0; --n) {
1065 if (partialStr.substr(0, n).equals(edgeStr.substr(0, n))) {
1066 // Splice in new node: was A -> C, now A -> B -> C
1067 StringRef bNodeStr = edge._child->_cummulativeString;
1068 bNodeStr = bNodeStr.drop_back(edgeStr.size()-n).copy(allocator);
1069 TrieNode* bNode = new (allocator) TrieNode(bNodeStr);
1070 allNodes.push_back(bNode);
1071 TrieNode* cNode = edge._child;
1072 StringRef abEdgeStr = edgeStr.substr(0,n).copy(allocator);
1073 StringRef bcEdgeStr = edgeStr.substr(n).copy(allocator);
1074 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1075 << "splice in TrieNode('" << bNodeStr
1076 << "') between edge '"
1077 << abEdgeStr << "' and edge='"
1078 << bcEdgeStr<< "'\n");
1079 TrieEdge& abEdge = edge;
1080 abEdge._subString = abEdgeStr;
1081 abEdge._child = bNode;
1082 TrieEdge bcEdge(bcEdgeStr, cNode);
1083 bNode->_children.push_back(bcEdge);
1084 bNode->addSymbol(entry, allocator, allNodes);
1085 return;
1086 }
1087 }
1088 }
1089 if (entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1090 assert(entry.otherOffset != 0);
1091 }
1092 if (entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
1093 assert(entry.otherOffset != 0);
1094 }
1095 // No commonality with any existing child, make a new edge.
1096 TrieNode* newNode = new (allocator) TrieNode(entry.name.copy(allocator));
1097 TrieEdge newEdge(partialStr, newNode);
1098 _children.push_back(newEdge);
1099 DEBUG_WITH_TYPE("trie-builder", llvm::dbgs()
1100 << "new TrieNode('" << entry.name << "') with edge '"
1101 << partialStr << "' from node='"
1102 << _cummulativeString << "'\n");
1103 newNode->_address = entry.offset;
1104 newNode->_flags = entry.flags | entry.kind;
1105 newNode->_other = entry.otherOffset;
1106 if ((entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) && !entry.otherName.empty())
1107 newNode->_importedName = entry.otherName.copy(allocator);
1108 newNode->_hasExportInfo = true;
1109 allNodes.push_back(newNode);
1110}
1111
1112bool MachOFileLayout::TrieNode::updateOffset(uint32_t& offset) {
1113 uint32_t nodeSize = 1; // Length when no export info
1114 if (_hasExportInfo) {
1115 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1116 nodeSize = llvm::getULEB128Size(_flags);
1117 nodeSize += llvm::getULEB128Size(_other); // Other contains ordinal.
1118 nodeSize += _importedName.size();
1119 ++nodeSize; // Trailing zero in imported name.
1120 } else {
1121 nodeSize = llvm::getULEB128Size(_flags) + llvm::getULEB128Size(_address);
1122 if (_flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER)
1123 nodeSize += llvm::getULEB128Size(_other);
1124 }
1125 // Overall node size so far is uleb128 of export info + actual export info.
1126 nodeSize += llvm::getULEB128Size(nodeSize);
1127 }
1128 // Compute size of all child edges.
1129 ++nodeSize; // Byte for number of chidren.
1130 for (TrieEdge &edge : _children) {
1131 nodeSize += edge._subString.size() + 1 // String length.
1132 + llvm::getULEB128Size(edge._child->_trieOffset); // Offset len.
1133 }
1134 // On input, 'offset' is new prefered location for this node.
1135 bool result = (_trieOffset != offset);
1136 // Store new location in node object for use by parents.
1137 _trieOffset = offset;
1138 // Update offset for next iteration.
1139 offset += nodeSize;
1140 // Return true if _trieOffset was changed.
1141 return result;
1142}
1143
1144void MachOFileLayout::TrieNode::appendToByteBuffer(ByteBuffer &out) {
1145 if (_hasExportInfo) {
1146 if (_flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
1147 if (!_importedName.empty()) {
1148 // nodes with re-export info: size, flags, ordinal, import-name
1149 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1150 + llvm::getULEB128Size(_other)
1151 + _importedName.size() + 1;
1152 assert(nodeSize < 256);
1153 out.append_byte(nodeSize);
1154 out.append_uleb128(_flags);
1155 out.append_uleb128(_other);
1156 out.append_string(_importedName);
1157 } else {
1158 // nodes without re-export info: size, flags, ordinal, empty-string
1159 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1160 + llvm::getULEB128Size(_other) + 1;
1161 assert(nodeSize < 256);
1162 out.append_byte(nodeSize);
1163 out.append_uleb128(_flags);
1164 out.append_uleb128(_other);
1165 out.append_byte(0);
1166 }
1167 } else if ( _flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) {
1168 // Nodes with export info: size, flags, address, other
1169 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1170 + llvm::getULEB128Size(_address)
1171 + llvm::getULEB128Size(_other);
1172 assert(nodeSize < 256);
1173 out.append_byte(nodeSize);
1174 out.append_uleb128(_flags);
1175 out.append_uleb128(_address);
1176 out.append_uleb128(_other);
1177 } else {
1178 // Nodes with export info: size, flags, address
1179 uint32_t nodeSize = llvm::getULEB128Size(_flags)
1180 + llvm::getULEB128Size(_address);
1181 assert(nodeSize < 256);
1182 out.append_byte(nodeSize);
1183 out.append_uleb128(_flags);
1184 out.append_uleb128(_address);
1185 }
1186 } else {
1187 // Node with no export info.
1188 uint32_t nodeSize = 0;
1189 out.append_byte(nodeSize);
1190 }
1191 // Add number of children.
1192 assert(_children.size() < 256);
1193 out.append_byte(_children.size());
1194 // Append each child edge substring and node offset.
1195 for (TrieEdge &edge : _children) {
1196 out.append_string(edge._subString);
1197 out.append_uleb128(edge._child->_trieOffset);
1198 }
1199}
1200
1201void MachOFileLayout::buildExportTrie() {
1202 if (_file.exportInfo.empty())
1203 return;
1204
1205 // For all temporary strings and objects used building trie.
1206 BumpPtrAllocator allocator;
1207
1208 // Build trie of all exported symbols.
1209 TrieNode* rootNode = new (allocator) TrieNode(StringRef());
1210 std::vector<TrieNode*> allNodes;
1211 allNodes.reserve(_file.exportInfo.size()*2);
1212 allNodes.push_back(rootNode);
1213 for (const Export& entry : _file.exportInfo) {
1214 rootNode->addSymbol(entry, allocator, allNodes);
1215 }
1216
1217 // Assign each node in the vector an offset in the trie stream, iterating
1218 // until all uleb128 sizes have stabilized.
1219 bool more;
1220 do {
1221 uint32_t offset = 0;
1222 more = false;
1223 for (TrieNode* node : allNodes) {
1224 if (node->updateOffset(offset))
1225 more = true;
1226 }
1227 } while (more);
1228
1229 // Serialize trie to ByteBuffer.
1230 for (TrieNode* node : allNodes) {
1231 node->appendToByteBuffer(_exportTrie);
1232 }
1233 _exportTrie.align(_is64 ? 8 : 4);
1234}
1235
1236
Nick Kledzike34182f2013-11-06 21:36:55 +00001237void MachOFileLayout::computeSymbolTableSizes() {
1238 // MachO symbol tables have three ranges: locals, globals, and undefines
1239 const size_t nlistSize = (_is64 ? sizeof(nlist_64) : sizeof(nlist));
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001240 _symbolTableSize = nlistSize * (_file.localSymbols.size()
Nick Kledzike34182f2013-11-06 21:36:55 +00001241 + _file.globalSymbols.size()
1242 + _file.undefinedSymbols.size());
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001243 _symbolStringPoolSize = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +00001244 for (const Symbol &sym : _file.localSymbols) {
1245 _symbolStringPoolSize += (sym.name.size()+1);
1246 }
1247 for (const Symbol &sym : _file.globalSymbols) {
1248 _symbolStringPoolSize += (sym.name.size()+1);
1249 }
1250 for (const Symbol &sym : _file.undefinedSymbols) {
1251 _symbolStringPoolSize += (sym.name.size()+1);
1252 }
1253 _symbolTableLocalsStartIndex = 0;
1254 _symbolTableGlobalsStartIndex = _file.localSymbols.size();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001255 _symbolTableUndefinesStartIndex = _symbolTableGlobalsStartIndex
Nick Kledzike34182f2013-11-06 21:36:55 +00001256 + _file.globalSymbols.size();
1257
1258 _indirectSymbolTableCount = 0;
1259 for (const Section &sect : _file.sections) {
1260 _indirectSymbolTableCount += sect.indirectSymbols.size();
1261 }
1262}
1263
Nick Kledzik21921372014-07-24 23:06:56 +00001264void MachOFileLayout::computeDataInCodeSize() {
1265 _dataInCodeSize = _file.dataInCode.size() * sizeof(data_in_code_entry);
1266}
Nick Kledzike34182f2013-11-06 21:36:55 +00001267
1268void MachOFileLayout::writeLinkEditContent() {
1269 if (_file.fileType == llvm::MachO::MH_OBJECT) {
1270 writeRelocations();
Nick Kledzik21921372014-07-24 23:06:56 +00001271 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001272 writeSymbolTable();
1273 } else {
1274 writeRebaseInfo();
1275 writeBindingInfo();
1276 writeLazyBindingInfo();
1277 // TODO: add weak binding info
Nick Kledzik141330a2014-09-03 19:52:50 +00001278 writeExportInfo();
Nick Kledzik54ce29582014-10-28 22:21:10 +00001279 writeDataInCodeInfo();
Nick Kledzike34182f2013-11-06 21:36:55 +00001280 writeSymbolTable();
1281 }
1282}
1283
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001284std::error_code MachOFileLayout::writeBinary(StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001285 // Check for pending error from constructor.
1286 if (_ec)
1287 return _ec;
1288 // Create FileOutputBuffer with calculated size.
Ahmed Charles13c70b62014-03-13 16:20:38 +00001289 std::unique_ptr<llvm::FileOutputBuffer> fob;
Nick Kledzike34182f2013-11-06 21:36:55 +00001290 unsigned flags = 0;
1291 if (_file.fileType != llvm::MachO::MH_OBJECT)
1292 flags = llvm::FileOutputBuffer::F_executable;
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001293 std::error_code ec;
Nick Kledzike34182f2013-11-06 21:36:55 +00001294 ec = llvm::FileOutputBuffer::create(path, size(), fob, flags);
1295 if (ec)
1296 return ec;
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001297
Nick Kledzike34182f2013-11-06 21:36:55 +00001298 // Write content.
1299 _buffer = fob->getBufferStart();
1300 writeMachHeader();
1301 ec = writeLoadCommands();
1302 if (ec)
1303 return ec;
1304 writeSectionContent();
1305 writeLinkEditContent();
1306 fob->commit();
1307
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001308 return std::error_code();
Nick Kledzike34182f2013-11-06 21:36:55 +00001309}
1310
1311
Nick Kledzike34182f2013-11-06 21:36:55 +00001312/// Takes in-memory normalized view and writes a mach-o object file.
Rafael Espindolab1a4d3a2014-06-12 14:53:47 +00001313std::error_code writeBinary(const NormalizedFile &file, StringRef path) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001314 MachOFileLayout layout(file);
1315 return layout.writeBinary(path);
1316}
1317
1318
1319} // namespace normalized
1320} // namespace mach_o
1321} // namespace lld
1322