blob: adda9b723d77f432920046de965be38010645575 [file] [log] [blame]
Nick Kledzike34182f2013-11-06 21:36:55 +00001//===- lib/ReaderWriter/MachO/MachONormalizedFileFromAtoms.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///
11/// \file Converts from in-memory Atoms to in-memory normalized mach-o.
12///
13/// +------------+
14/// | normalized |
15/// +------------+
16/// ^
17/// |
18/// |
Shankar Easwaran3d8de472014-01-27 03:09:26 +000019/// +-------+
Nick Kledzike34182f2013-11-06 21:36:55 +000020/// | Atoms |
Shankar Easwaran3d8de472014-01-27 03:09:26 +000021/// +-------+
Nick Kledzike34182f2013-11-06 21:36:55 +000022
23#include "MachONormalizedFile.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000024
25#include "ArchHandler.h"
Nick Kledzikec140832014-06-10 01:50:00 +000026#include "MachONormalizedFileBinaryUtils.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000027
Nick Kledzike34182f2013-11-06 21:36:55 +000028#include "lld/Core/Error.h"
29#include "lld/Core/LLVM.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000030#include "llvm/ADT/StringRef.h"
31#include "llvm/ADT/StringSwitch.h"
32#include "llvm/Support/Casting.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/Format.h"
36#include "llvm/Support/MachO.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000037#include <map>
Rafael Espindola54427cc2014-06-12 17:15:58 +000038#include <system_error>
Nick Kledzike34182f2013-11-06 21:36:55 +000039
40using llvm::StringRef;
Nick Kledzike34182f2013-11-06 21:36:55 +000041using llvm::isa;
42using namespace llvm::MachO;
43using namespace lld::mach_o::normalized;
44using namespace lld;
45
46namespace {
47
48struct AtomInfo {
49 const DefinedAtom *atom;
50 uint64_t offsetInSection;
51};
52
53struct SectionInfo {
54 SectionInfo(StringRef seg, StringRef sect, SectionType type, uint32_t attr=0);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000055
Nick Kledzike34182f2013-11-06 21:36:55 +000056 StringRef segmentName;
57 StringRef sectionName;
58 SectionType type;
59 uint32_t attributes;
60 uint64_t address;
61 uint64_t size;
62 uint32_t alignment;
63 std::vector<AtomInfo> atomsAndOffsets;
64 uint32_t normalizedSectionIndex;
65 uint32_t finalSectionIndex;
66};
67
Shankar Easwaran3d8de472014-01-27 03:09:26 +000068SectionInfo::SectionInfo(StringRef sg, StringRef sct, SectionType t, uint32_t a)
69 : segmentName(sg), sectionName(sct), type(t), attributes(a),
70 address(0), size(0), alignment(0),
Nick Kledzike34182f2013-11-06 21:36:55 +000071 normalizedSectionIndex(0), finalSectionIndex(0) {
72}
73
74struct SegmentInfo {
75 SegmentInfo(StringRef name);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000076
Nick Kledzike34182f2013-11-06 21:36:55 +000077 StringRef name;
78 uint64_t address;
79 uint64_t size;
80 uint32_t access;
81 std::vector<SectionInfo*> sections;
82};
83
Shankar Easwaran3d8de472014-01-27 03:09:26 +000084SegmentInfo::SegmentInfo(StringRef n)
Nick Kledzike34182f2013-11-06 21:36:55 +000085 : name(n), address(0), size(0), access(0) {
86}
87
88
89class Util {
90public:
Nick Kledzik2d432352014-07-17 23:16:21 +000091 Util(const MachOLinkingContext &ctxt) : _context(ctxt),
92 _archHandler(ctxt.archHandler()), _entryAtom(nullptr) {}
Nick Kledzike34182f2013-11-06 21:36:55 +000093
94 void assignAtomsToSections(const lld::File &atomFile);
95 void organizeSections();
96 void assignAddressesToSections();
97 uint32_t fileFlags();
98 void copySegmentInfo(NormalizedFile &file);
99 void copySections(NormalizedFile &file);
100 void buildAtomToAddressMap();
101 void addSymbols(const lld::File &atomFile, NormalizedFile &file);
102 void addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file);
103 void addRebaseAndBindingInfo(const lld::File &, NormalizedFile &file);
104 void addSectionRelocs(const lld::File &, NormalizedFile &file);
Nick Kledzik21921372014-07-24 23:06:56 +0000105 void buildDataInCodeArray(const lld::File &, NormalizedFile &file);
Nick Kledzike34182f2013-11-06 21:36:55 +0000106 void addDependentDylibs(const lld::File &, NormalizedFile &file);
107 void copyEntryPointAddress(NormalizedFile &file);
108
109private:
110 typedef std::map<DefinedAtom::ContentType, SectionInfo*> TypeToSection;
111 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000112
Nick Kledzike34182f2013-11-06 21:36:55 +0000113 struct DylibInfo { int ordinal; bool hasWeak; bool hasNonWeak; };
114 typedef llvm::StringMap<DylibInfo> DylibPathToInfo;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000115
Nick Kledzike34182f2013-11-06 21:36:55 +0000116 SectionInfo *sectionForAtom(const DefinedAtom*);
Nick Kledzik936d5202014-06-11 01:30:55 +0000117 SectionInfo *getRelocatableSection(DefinedAtom::ContentType type);
118 SectionInfo *getFinalSection(DefinedAtom::ContentType type);
Nick Kledzike34182f2013-11-06 21:36:55 +0000119 void appendAtom(SectionInfo *sect, const DefinedAtom *atom);
120 SegmentInfo *segmentForName(StringRef segName);
121 void layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr);
122 void layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr);
123 void copySectionContent(SectionInfo *si, ContentBytes &content);
124 uint8_t scopeBits(const DefinedAtom* atom);
Nick Kledzik60855392014-06-11 00:24:16 +0000125 uint16_t descBits(const DefinedAtom* atom);
Nick Kledzike34182f2013-11-06 21:36:55 +0000126 int dylibOrdinal(const SharedLibraryAtom *sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000127 void segIndexForSection(const SectionInfo *sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000128 uint8_t &segmentIndex, uint64_t &segmentStartAddr);
129 const Atom *targetOfLazyPointer(const DefinedAtom *lpAtom);
130 const Atom *targetOfStub(const DefinedAtom *stubAtom);
131 bool belongsInGlobalSymbolsSection(const DefinedAtom* atom);
132 void appendSection(SectionInfo *si, NormalizedFile &file);
Nick Kledzik2d432352014-07-17 23:16:21 +0000133 uint32_t sectionIndexForAtom(const Atom *atom);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000134
Nick Kledzike34182f2013-11-06 21:36:55 +0000135 static uint64_t alignTo(uint64_t value, uint8_t align2);
136 typedef llvm::DenseMap<const Atom*, uint32_t> AtomToIndex;
137 struct AtomAndIndex { const Atom *atom; uint32_t index; };
Joey Gouly9d263e02013-12-25 19:39:08 +0000138 struct AtomSorter {
139 bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000140 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000141 struct SegmentSorter {
142 bool operator()(const SegmentInfo *left, const SegmentInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000143 static unsigned weight(const SegmentInfo *);
144 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000145 struct TextSectionSorter {
146 bool operator()(const SectionInfo *left, const SectionInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000147 static unsigned weight(const SectionInfo *);
148 };
149
150 const MachOLinkingContext &_context;
Nick Kledzik2d432352014-07-17 23:16:21 +0000151 mach_o::ArchHandler &_archHandler;
Nick Kledzike34182f2013-11-06 21:36:55 +0000152 llvm::BumpPtrAllocator _allocator;
153 std::vector<SectionInfo*> _sectionInfos;
154 std::vector<SegmentInfo*> _segmentInfos;
155 TypeToSection _sectionMap;
Nick Kledzikacfad802014-05-30 22:51:04 +0000156 std::vector<SectionInfo*> _customSections;
Nick Kledzike34182f2013-11-06 21:36:55 +0000157 AtomToAddress _atomToAddress;
158 DylibPathToInfo _dylibInfo;
159 const DefinedAtom *_entryAtom;
160 AtomToIndex _atomToSymbolIndex;
161};
162
Nick Kledzikec140832014-06-10 01:50:00 +0000163
Nick Kledzik936d5202014-06-11 01:30:55 +0000164SectionInfo *Util::getRelocatableSection(DefinedAtom::ContentType type) {
Nick Kledzikec140832014-06-10 01:50:00 +0000165 StringRef segmentName;
166 StringRef sectionName;
167 SectionType sectionType;
168 SectionAttr sectionAttrs;
169
170 // Use same table used by when parsing .o files.
171 relocatableSectionInfoForContentType(type, segmentName, sectionName,
172 sectionType, sectionAttrs);
173 // If we already have a SectionInfo with this name, re-use it.
174 // This can happen if two ContentType map to the same mach-o section.
175 for (auto sect : _sectionMap) {
176 if (sect.second->sectionName.equals(sectionName) &&
177 sect.second->segmentName.equals(segmentName)) {
178 return sect.second;
179 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000180 }
Nick Kledzikec140832014-06-10 01:50:00 +0000181 // Otherwise allocate new SectionInfo object.
Nick Kledzik936d5202014-06-11 01:30:55 +0000182 SectionInfo *sect = new (_allocator) SectionInfo(segmentName, sectionName,
183 sectionType, sectionAttrs);
184 _sectionInfos.push_back(sect);
185 _sectionMap[type] = sect;
186 return sect;
Nick Kledzikec140832014-06-10 01:50:00 +0000187}
188
189#define ENTRY(seg, sect, type, atomType) \
190 {seg, sect, type, DefinedAtom::atomType }
191
192struct MachOFinalSectionFromAtomType {
193 StringRef segmentName;
194 StringRef sectionName;
195 SectionType sectionType;
196 DefinedAtom::ContentType atomType;
197};
198
199const MachOFinalSectionFromAtomType sectsToAtomType[] = {
200 ENTRY("__TEXT", "__text", S_REGULAR, typeCode),
201 ENTRY("__TEXT", "__cstring", S_CSTRING_LITERALS, typeCString),
202 ENTRY("__TEXT", "__ustring", S_REGULAR, typeUTF16String),
203 ENTRY("__TEXT", "__const", S_REGULAR, typeConstant),
204 ENTRY("__TEXT", "__const", S_4BYTE_LITERALS, typeLiteral4),
205 ENTRY("__TEXT", "__const", S_8BYTE_LITERALS, typeLiteral8),
206 ENTRY("__TEXT", "__const", S_16BYTE_LITERALS, typeLiteral16),
207 ENTRY("__TEXT", "__stubs", S_SYMBOL_STUBS, typeStub),
208 ENTRY("__TEXT", "__stub_helper", S_REGULAR, typeStubHelper),
209 ENTRY("__TEXT", "__gcc_except_tab", S_REGULAR, typeLSDA),
210 ENTRY("__TEXT", "__eh_frame", S_COALESCED, typeCFI),
211 ENTRY("__DATA", "__data", S_REGULAR, typeData),
212 ENTRY("__DATA", "__const", S_REGULAR, typeConstData),
213 ENTRY("__DATA", "__cfstring", S_REGULAR, typeCFString),
214 ENTRY("__DATA", "__la_symbol_ptr", S_LAZY_SYMBOL_POINTERS,
215 typeLazyPointer),
216 ENTRY("__DATA", "__mod_init_func", S_MOD_INIT_FUNC_POINTERS,
217 typeInitializerPtr),
218 ENTRY("__DATA", "__mod_term_func", S_MOD_TERM_FUNC_POINTERS,
219 typeTerminatorPtr),
220 ENTRY("__DATA", "___got", S_NON_LAZY_SYMBOL_POINTERS,
221 typeGOT),
Tim Northover9ee99352014-06-30 09:49:37 +0000222 ENTRY("__DATA", "___bss", S_ZEROFILL, typeZeroFill),
223
224 // FIXME: __compact_unwind actually needs to be processed by a pass and put
225 // into __TEXT,__unwind_info. For now, forwarding it back to
226 // __LD,__compact_unwind is harmless (it's ignored by the unwinder, which then
227 // proceeds to process __TEXT,__eh_frame for its instructions).
228 ENTRY("__LD", "__compact_unwind", S_REGULAR, typeCompactUnwindInfo),
Nick Kledzikec140832014-06-10 01:50:00 +0000229};
230#undef ENTRY
231
232
Nick Kledzik936d5202014-06-11 01:30:55 +0000233SectionInfo *Util::getFinalSection(DefinedAtom::ContentType atomType) {
Tim Northoverb5bf6862014-06-30 10:30:00 +0000234 for (auto &p : sectsToAtomType) {
235 if (p.atomType != atomType)
Nick Kledzikec140832014-06-10 01:50:00 +0000236 continue;
237 SectionAttr sectionAttrs = 0;
238 switch (atomType) {
239 case DefinedAtom::typeCode:
240 case DefinedAtom::typeStub:
241 sectionAttrs = S_ATTR_PURE_INSTRUCTIONS;
242 break;
243 default:
244 break;
245 }
246 // If we already have a SectionInfo with this name, re-use it.
247 // This can happen if two ContentType map to the same mach-o section.
248 for (auto sect : _sectionMap) {
Tim Northoverb5bf6862014-06-30 10:30:00 +0000249 if (sect.second->sectionName.equals(p.sectionName) &&
250 sect.second->segmentName.equals(p.segmentName)) {
Nick Kledzikec140832014-06-10 01:50:00 +0000251 return sect.second;
252 }
253 }
254 // Otherwise allocate new SectionInfo object.
Tim Northoverb5bf6862014-06-30 10:30:00 +0000255 SectionInfo *sect = new (_allocator) SectionInfo(p.segmentName,
256 p.sectionName,
257 p.sectionType,
Nick Kledzik936d5202014-06-11 01:30:55 +0000258 sectionAttrs);
259 _sectionInfos.push_back(sect);
260 _sectionMap[atomType] = sect;
261 return sect;
Nick Kledzikec140832014-06-10 01:50:00 +0000262 }
263 llvm_unreachable("content type not yet supported");
Nick Kledzike34182f2013-11-06 21:36:55 +0000264}
265
266
267
268SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
Nick Kledzikacfad802014-05-30 22:51:04 +0000269 if (atom->sectionChoice() == DefinedAtom::sectionBasedOnContent) {
270 // Section for this atom is derived from content type.
271 DefinedAtom::ContentType type = atom->contentType();
272 auto pos = _sectionMap.find(type);
273 if ( pos != _sectionMap.end() )
274 return pos->second;
Tim Northoverd30a1f22014-06-20 15:59:00 +0000275 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzik936d5202014-06-11 01:30:55 +0000276 return rMode ? getRelocatableSection(type) : getFinalSection(type);
Nick Kledzikacfad802014-05-30 22:51:04 +0000277 } else {
278 // This atom needs to be in a custom section.
279 StringRef customName = atom->customSectionName();
280 // Look to see if we have already allocated the needed custom section.
281 for(SectionInfo *sect : _customSections) {
282 const DefinedAtom *firstAtom = sect->atomsAndOffsets.front().atom;
283 if (firstAtom->customSectionName().equals(customName)) {
284 return sect;
285 }
286 }
287 // Not found, so need to create a new custom section.
288 size_t seperatorIndex = customName.find('/');
289 assert(seperatorIndex != StringRef::npos);
Tim Northover7b0a1302014-06-30 09:49:33 +0000290 StringRef segName = customName.slice(0, seperatorIndex);
291 StringRef sectName = customName.drop_front(seperatorIndex + 1);
Nick Kledzikacfad802014-05-30 22:51:04 +0000292 SectionInfo *sect = new (_allocator) SectionInfo(segName, sectName,
293 S_REGULAR);
294 _customSections.push_back(sect);
Tim Northover7b0a1302014-06-30 09:49:33 +0000295 _sectionInfos.push_back(sect);
Nick Kledzikacfad802014-05-30 22:51:04 +0000296 return sect;
297 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000298}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000299
Nick Kledzike34182f2013-11-06 21:36:55 +0000300
301void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
302 // Figure out offset for atom in this section given alignment constraints.
303 uint64_t offset = sect->size;
304 DefinedAtom::Alignment atomAlign = atom->alignment();
305 uint64_t align2 = 1 << atomAlign.powerOf2;
306 uint64_t requiredModulus = atomAlign.modulus;
307 uint64_t currentModulus = (offset % align2);
308 if ( currentModulus != requiredModulus ) {
309 if ( requiredModulus > currentModulus )
310 offset += requiredModulus-currentModulus;
311 else
312 offset += align2+requiredModulus-currentModulus;
313 }
314 // Record max alignment of any atom in this section.
315 if ( atomAlign.powerOf2 > sect->alignment )
316 sect->alignment = atomAlign.powerOf2;
317 // Assign atom to this section with this offset.
318 AtomInfo ai = {atom, offset};
319 sect->atomsAndOffsets.push_back(ai);
320 // Update section size to include this atom.
321 sect->size = offset + atom->size();
322}
323
324void Util::assignAtomsToSections(const lld::File &atomFile) {
325 for (const DefinedAtom *atom : atomFile.defined()) {
326 appendAtom(sectionForAtom(atom), atom);
327 }
328}
329
330SegmentInfo *Util::segmentForName(StringRef segName) {
331 for (SegmentInfo *si : _segmentInfos) {
332 if ( si->name.equals(segName) )
333 return si;
334 }
335 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
336 if (segName.equals("__TEXT"))
337 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
338 else if (segName.equals("__DATA"))
339 info->access = VM_PROT_READ | VM_PROT_WRITE;
340 else if (segName.equals("__PAGEZERO"))
341 info->access = 0;
342 _segmentInfos.push_back(info);
343 return info;
344}
345
346unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
347 return llvm::StringSwitch<unsigned>(seg->name)
348 .Case("__PAGEZERO", 1)
349 .Case("__TEXT", 2)
350 .Case("__DATA", 3)
351 .Default(100);
352}
353
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000354bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000355 const SegmentInfo *right) {
356 return (weight(left) < weight(right));
357}
358
359unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
360 return llvm::StringSwitch<unsigned>(sect->sectionName)
361 .Case("__text", 1)
362 .Case("__stubs", 2)
363 .Case("__stub_helper", 3)
364 .Case("__const", 4)
365 .Case("__cstring", 5)
366 .Case("__unwind_info", 98)
367 .Case("__eh_frame", 99)
368 .Default(10);
369}
370
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000371bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000372 const SectionInfo *right) {
373 return (weight(left) < weight(right));
374}
375
376
377void Util::organizeSections() {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000378 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000379 // Leave sections ordered as normalized file specified.
380 uint32_t sectionIndex = 1;
381 for (SectionInfo *si : _sectionInfos) {
382 si->finalSectionIndex = sectionIndex++;
383 }
384 } else {
385 // Main executables, need a zero-page segment
Tim Northoverd30a1f22014-06-20 15:59:00 +0000386 if (_context.outputMachOType() == llvm::MachO::MH_EXECUTE)
Nick Kledzike34182f2013-11-06 21:36:55 +0000387 segmentForName("__PAGEZERO");
388 // Group sections into segments.
389 for (SectionInfo *si : _sectionInfos) {
390 SegmentInfo *seg = segmentForName(si->segmentName);
391 seg->sections.push_back(si);
392 }
393 // Sort segments.
394 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000395
Nick Kledzike34182f2013-11-06 21:36:55 +0000396 // Sort sections within segments.
397 for (SegmentInfo *seg : _segmentInfos) {
398 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000399 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000400 TextSectionSorter());
401 }
402 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000403
Nick Kledzike34182f2013-11-06 21:36:55 +0000404 // Record final section indexes.
405 uint32_t sectionIndex = 1;
406 for (SegmentInfo *seg : _segmentInfos) {
407 for (SectionInfo *sect : seg->sections) {
408 sect->finalSectionIndex = sectionIndex++;
409 }
410 }
411 }
412
413}
414
415uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
416 return llvm::RoundUpToAlignment(value, 1 << align2);
417}
418
419
420void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
421 seg->address = addr;
422 for (SectionInfo *sect : seg->sections) {
423 sect->address = alignTo(addr, sect->alignment);
424 addr += sect->size;
425 }
426 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
427}
428
429
430// __TEXT segment lays out backwards so padding is at front after load commands.
431void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
432 seg->address = addr;
433 // Walks sections starting at end to calculate padding for start.
434 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000435 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000436 SectionInfo *sect = *it;
437 taddr -= sect->size;
438 taddr = taddr & (0 - (1 << sect->alignment));
439 }
440 int64_t padding = taddr;
441 while (padding < 0)
442 padding += _context.pageSize();
443 // Start assigning section address starting at padded offset.
444 addr += padding;
445 for (SectionInfo *sect : seg->sections) {
446 sect->address = alignTo(addr, sect->alignment);
447 addr = sect->address + sect->size;
448 }
449 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
450}
451
452
453void Util::assignAddressesToSections() {
454 uint64_t address = 0; // FIXME
Tim Northoverd30a1f22014-06-20 15:59:00 +0000455 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000456 for (SegmentInfo *seg : _segmentInfos) {
457 if (seg->name.equals("__PAGEZERO")) {
458 seg->size = _context.pageZeroSize();
459 address += seg->size;
460 }
461 else if (seg->name.equals("__TEXT"))
462 layoutSectionsInTextSegment(seg, address);
463 else
464 layoutSectionsInSegment(seg, address);
Tim Northover7b0a1302014-06-30 09:49:33 +0000465
466 address = llvm::RoundUpToAlignment(address, _context.pageSize());
Nick Kledzike34182f2013-11-06 21:36:55 +0000467 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000468 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000469 llvm::dbgs() << "assignAddressesToSections()\n";
470 for (SegmentInfo *sgi : _segmentInfos) {
471 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000472 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000473 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000474 << "'\n";
475 for (SectionInfo *si : sgi->sections) {
476 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000477 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000478 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000479 << "\n";
480 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000481 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000482 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000483 } else {
484 for (SectionInfo *sect : _sectionInfos) {
485 sect->address = alignTo(address, sect->alignment);
486 address = sect->address + sect->size;
487 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000488 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000489 llvm::dbgs() << "assignAddressesToSections()\n";
490 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000491 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000492 << " address= " << llvm::format("0x%08X", si->address)
493 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000494 << "\n";
495 }
496 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000497 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000498}
499
500
501void Util::copySegmentInfo(NormalizedFile &file) {
502 for (SegmentInfo *sgi : _segmentInfos) {
503 Segment seg;
504 seg.name = sgi->name;
505 seg.address = sgi->address;
506 seg.size = sgi->size;
507 seg.access = sgi->access;
508 file.segments.push_back(seg);
509 }
510}
511
512void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
Nick Kledzik3f690762014-06-27 18:25:01 +0000513 const bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzik2d432352014-07-17 23:16:21 +0000514
515 // Utility function for ArchHandler to find address of atom in output file.
516 auto addrForAtom = [&] (const Atom &atom) -> uint64_t {
517 auto pos = _atomToAddress.find(&atom);
518 assert(pos != _atomToAddress.end());
519 return pos->second;
520 };
521
Nick Kledzike34182f2013-11-06 21:36:55 +0000522 // Add new empty section to end of file.sections.
523 Section temp;
524 file.sections.push_back(std::move(temp));
525 Section* normSect = &file.sections.back();
526 // Copy fields to normalized section.
527 normSect->segmentName = si->segmentName;
528 normSect->sectionName = si->sectionName;
529 normSect->type = si->type;
530 normSect->attributes = si->attributes;
531 normSect->address = si->address;
532 normSect->alignment = si->alignment;
533 // Record where normalized section is.
534 si->normalizedSectionIndex = file.sections.size()-1;
535 // Copy content from atoms to content buffer for section.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000536 if (si->type == llvm::MachO::S_ZEROFILL)
537 return;
Nick Kledzik6edd7222014-01-11 01:07:43 +0000538 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
539 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000540 for (AtomInfo &ai : si->atomsAndOffsets) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000541 uint8_t *atomContent = reinterpret_cast<uint8_t*>
542 (&sectionContent[ai.offsetInSection]);
Nick Kledzik2d432352014-07-17 23:16:21 +0000543 _archHandler.generateAtomContent(*ai.atom, rMode, addrForAtom, atomContent);
Nick Kledzike34182f2013-11-06 21:36:55 +0000544 }
545}
546
547void Util::copySections(NormalizedFile &file) {
548 file.sections.reserve(_sectionInfos.size());
549 // For final linked images, write sections grouped by segment.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000550 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000551 for (SegmentInfo *sgi : _segmentInfos) {
552 for (SectionInfo *si : sgi->sections) {
553 appendSection(si, file);
554 }
555 }
556 } else {
557 // Object files write sections in default order.
558 for (SectionInfo *si : _sectionInfos) {
559 appendSection(si, file);
560 }
561 }
562}
563
564void Util::copyEntryPointAddress(NormalizedFile &nFile) {
565 if (_context.outputTypeHasEntry()) {
566 nFile.entryAddress = _atomToAddress[_entryAtom];
567 }
568}
569
570void Util::buildAtomToAddressMap() {
571 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
572 << "assign atom addresses:\n");
573 const bool lookForEntry = _context.outputTypeHasEntry();
574 for (SectionInfo *sect : _sectionInfos) {
575 for (const AtomInfo &info : sect->atomsAndOffsets) {
576 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
577 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
578 (info.atom->size() != 0) &&
579 info.atom->name() == _context.entrySymbolName()) {
580 _entryAtom = info.atom;
581 }
582 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
583 << " address="
584 << llvm::format("0x%016X", _atomToAddress[info.atom])
585 << " atom=" << info.atom
586 << " name=" << info.atom->name() << "\n");
587 }
588 }
589}
590
591uint8_t Util::scopeBits(const DefinedAtom* atom) {
592 switch (atom->scope()) {
593 case Atom::scopeTranslationUnit:
594 return 0;
595 case Atom::scopeLinkageUnit:
596 return N_PEXT | N_EXT;
597 case Atom::scopeGlobal:
598 return N_EXT;
599 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000600 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000601}
602
Nick Kledzik60855392014-06-11 00:24:16 +0000603uint16_t Util::descBits(const DefinedAtom* atom) {
604 uint16_t desc = 0;
605 switch (atom->merge()) {
606 case lld::DefinedAtom::mergeNo:
607 case lld::DefinedAtom::mergeAsTentative:
608 break;
609 case lld::DefinedAtom::mergeAsWeak:
610 case lld::DefinedAtom::mergeAsWeakAndAddressUsed:
611 desc |= N_WEAK_DEF;
612 break;
613 case lld::DefinedAtom::mergeSameNameAndSize:
614 case lld::DefinedAtom::mergeByLargestSection:
615 case lld::DefinedAtom::mergeByContent:
616 llvm_unreachable("Unsupported DefinedAtom::merge()");
617 break;
618 }
619 if (atom->contentType() == lld::DefinedAtom::typeResolver)
620 desc |= N_SYMBOL_RESOLVER;
Nick Kledzik7e9808f2014-07-23 00:51:37 +0000621 if (_archHandler.isThumbFunction(*atom))
622 desc |= N_ARM_THUMB_DEF;
Nick Kledzik60855392014-06-11 00:24:16 +0000623 return desc;
624}
625
626
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000627bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000628 const AtomAndIndex &right) {
629 return (left.atom->name().compare(right.atom->name()) < 0);
630}
631
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000632
Nick Kledzike34182f2013-11-06 21:36:55 +0000633bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
Nick Kledzik936d5202014-06-11 01:30:55 +0000634 // ScopeLinkageUnit symbols are in globals area of symbol table
635 // in object files, but in locals area for final linked images.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000636 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzik936d5202014-06-11 01:30:55 +0000637 return (atom->scope() != Atom::scopeTranslationUnit);
638 else
639 return (atom->scope() == Atom::scopeGlobal);
Nick Kledzike34182f2013-11-06 21:36:55 +0000640}
641
642void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000643 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzike34182f2013-11-06 21:36:55 +0000644 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000645
Nick Kledzike34182f2013-11-06 21:36:55 +0000646 // Add all local (non-global) symbols in address order
647 std::vector<AtomAndIndex> globals;
648 globals.reserve(512);
649 for (SectionInfo *sect : _sectionInfos) {
650 for (const AtomInfo &info : sect->atomsAndOffsets) {
651 const DefinedAtom *atom = info.atom;
652 if (!atom->name().empty()) {
653 if (belongsInGlobalSymbolsSection(atom)) {
654 AtomAndIndex ai = { atom, sect->finalSectionIndex };
655 globals.push_back(ai);
656 } else {
657 Symbol sym;
658 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000659 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000660 sym.scope = scopeBits(atom);
661 sym.sect = sect->finalSectionIndex;
Nick Kledzik7e9808f2014-07-23 00:51:37 +0000662 sym.desc = descBits(atom);
Nick Kledzike34182f2013-11-06 21:36:55 +0000663 sym.value = _atomToAddress[atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000664 _atomToSymbolIndex[atom] = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000665 file.localSymbols.push_back(sym);
666 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000667 } else if (rMode && _archHandler.needsLocalSymbolInRelocatableFile(atom)){
668 // Create 'Lxxx' labels for anonymous atoms if archHandler says so.
669 static unsigned tempNum = 1;
670 char tmpName[16];
671 sprintf(tmpName, "L%04u", tempNum++);
672 StringRef tempRef(tmpName);
673 Symbol sym;
674 sym.name = tempRef.copy(file.ownedAllocations);
675 sym.type = N_SECT;
676 sym.scope = 0;
677 sym.sect = sect->finalSectionIndex;
678 sym.desc = 0;
679 sym.value = _atomToAddress[atom];
680 _atomToSymbolIndex[atom] = file.localSymbols.size();
681 file.localSymbols.push_back(sym);
Nick Kledzike34182f2013-11-06 21:36:55 +0000682 }
683 }
684 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000685
Nick Kledzike34182f2013-11-06 21:36:55 +0000686 // Sort global symbol alphabetically, then add to symbol table.
687 std::sort(globals.begin(), globals.end(), AtomSorter());
Nick Kledzik2d432352014-07-17 23:16:21 +0000688 const uint32_t globalStartIndex = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000689 for (AtomAndIndex &ai : globals) {
690 Symbol sym;
691 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000692 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000693 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
694 sym.sect = ai.index;
Nick Kledzik60855392014-06-11 00:24:16 +0000695 sym.desc = descBits(static_cast<const DefinedAtom*>(ai.atom));
Nick Kledzike34182f2013-11-06 21:36:55 +0000696 sym.value = _atomToAddress[ai.atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000697 _atomToSymbolIndex[ai.atom] = globalStartIndex + file.globalSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000698 file.globalSymbols.push_back(sym);
699 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000700
701
Nick Kledzike34182f2013-11-06 21:36:55 +0000702 // Sort undefined symbol alphabetically, then add to symbol table.
703 std::vector<AtomAndIndex> undefs;
704 undefs.reserve(128);
705 for (const UndefinedAtom *atom : atomFile.undefined()) {
706 AtomAndIndex ai = { atom, 0 };
707 undefs.push_back(ai);
708 }
709 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
710 AtomAndIndex ai = { atom, 0 };
711 undefs.push_back(ai);
712 }
713 std::sort(undefs.begin(), undefs.end(), AtomSorter());
714 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
715 for (AtomAndIndex &ai : undefs) {
716 Symbol sym;
717 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000718 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000719 sym.scope = N_EXT;
720 sym.sect = 0;
721 sym.desc = 0;
722 sym.value = 0;
723 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
724 file.undefinedSymbols.push_back(sym);
725 }
726}
727
728const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
729 for (const Reference *ref : *lpAtom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000730 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000731 return ref->target();
732 }
733 }
734 return nullptr;
735}
736
737const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
738 for (const Reference *ref : *stubAtom) {
739 if (const Atom *ta = ref->target()) {
740 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
741 const Atom *target = targetOfLazyPointer(lpAtom);
742 if (target)
743 return target;
744 }
745 }
746 }
747 return nullptr;
748}
749
750
751void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
752 for (SectionInfo *si : _sectionInfos) {
753 Section &normSect = file.sections[si->normalizedSectionIndex];
754 switch (si->type) {
755 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
756 for (const AtomInfo &info : si->atomsAndOffsets) {
757 bool foundTarget = false;
758 for (const Reference *ref : *info.atom) {
759 const Atom *target = ref->target();
760 if (target) {
761 if (isa<const SharedLibraryAtom>(target)) {
762 uint32_t index = _atomToSymbolIndex[target];
763 normSect.indirectSymbols.push_back(index);
764 foundTarget = true;
765 } else {
766 normSect.indirectSymbols.push_back(
767 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
768 }
769 }
770 }
771 if (!foundTarget) {
772 normSect.indirectSymbols.push_back(
773 llvm::MachO::INDIRECT_SYMBOL_ABS);
774 }
775 }
776 break;
777 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
778 for (const AtomInfo &info : si->atomsAndOffsets) {
779 const Atom *target = targetOfLazyPointer(info.atom);
780 if (target) {
781 uint32_t index = _atomToSymbolIndex[target];
782 normSect.indirectSymbols.push_back(index);
783 }
784 }
785 break;
786 case llvm::MachO::S_SYMBOL_STUBS:
787 for (const AtomInfo &info : si->atomsAndOffsets) {
788 const Atom *target = targetOfStub(info.atom);
789 if (target) {
790 uint32_t index = _atomToSymbolIndex[target];
791 normSect.indirectSymbols.push_back(index);
792 }
793 }
794 break;
795 default:
796 break;
797 }
798 }
799
800}
801
802void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
803 // Scan all imported symbols and build up list of dylibs they are from.
804 int ordinal = 1;
805 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
806 StringRef loadPath = slAtom->loadName();
807 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
808 if (pos == _dylibInfo.end()) {
809 DylibInfo info;
810 info.ordinal = ordinal++;
811 info.hasWeak = slAtom->canBeNullAtRuntime();
812 info.hasNonWeak = !info.hasWeak;
813 _dylibInfo[loadPath] = info;
814 DependentDylib depInfo;
815 depInfo.path = loadPath;
816 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
817 nFile.dependentDylibs.push_back(depInfo);
818 } else {
819 if ( slAtom->canBeNullAtRuntime() )
820 pos->second.hasWeak = true;
821 else
822 pos->second.hasNonWeak = true;
823 }
824 }
825 // Automatically weak link dylib in which all symbols are weak (canBeNull).
826 for (DependentDylib &dep : nFile.dependentDylibs) {
827 DylibInfo &info = _dylibInfo[dep.path];
828 if (info.hasWeak && !info.hasNonWeak)
829 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
830 }
831}
832
833
834int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
835 return _dylibInfo[sa->loadName()].ordinal;
836}
837
838void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
839 uint64_t &segmentStartAddr) {
840 segmentIndex = 0;
841 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000842 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000843 && (seg->address+seg->size >= sect->address+sect->size)) {
844 segmentStartAddr = seg->address;
845 return;
846 }
847 ++segmentIndex;
848 }
849 llvm_unreachable("section not in any segment");
850}
851
852
Nick Kledzik2d432352014-07-17 23:16:21 +0000853uint32_t Util::sectionIndexForAtom(const Atom *atom) {
854 uint64_t address = _atomToAddress[atom];
855 uint32_t index = 1;
856 for (const SectionInfo *si : _sectionInfos) {
857 if ((si->address <= address) && (address < si->address+si->size))
858 return index;
859 ++index;
860 }
861 llvm_unreachable("atom not in any section");
Nick Kledzike34182f2013-11-06 21:36:55 +0000862}
863
864void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000865 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000866 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000867
Nick Kledzik2d432352014-07-17 23:16:21 +0000868
869 // Utility function for ArchHandler to find symbol index for an atom.
870 auto symIndexForAtom = [&] (const Atom &atom) -> uint32_t {
871 auto pos = _atomToSymbolIndex.find(&atom);
872 assert(pos != _atomToSymbolIndex.end());
873 return pos->second;
874 };
875
876 // Utility function for ArchHandler to find section index for an atom.
877 auto sectIndexForAtom = [&] (const Atom &atom) -> uint32_t {
878 return sectionIndexForAtom(&atom);
879 };
880
881 // Utility function for ArchHandler to find address of atom in output file.
882 auto addressForAtom = [&] (const Atom &atom) -> uint64_t {
883 auto pos = _atomToAddress.find(&atom);
884 assert(pos != _atomToAddress.end());
885 return pos->second;
886 };
887
Nick Kledzike34182f2013-11-06 21:36:55 +0000888 for (SectionInfo *si : _sectionInfos) {
889 Section &normSect = file.sections[si->normalizedSectionIndex];
890 for (const AtomInfo &info : si->atomsAndOffsets) {
891 const DefinedAtom *atom = info.atom;
892 for (const Reference *ref : *atom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000893 _archHandler.appendSectionRelocations(*atom, info.offsetInSection, *ref,
894 symIndexForAtom,
895 sectIndexForAtom,
896 addressForAtom,
897 normSect.relocations);
Nick Kledzike34182f2013-11-06 21:36:55 +0000898 }
899 }
900 }
901}
902
Nick Kledzik21921372014-07-24 23:06:56 +0000903void Util::buildDataInCodeArray(const lld::File &, NormalizedFile &file) {
904 for (SectionInfo *si : _sectionInfos) {
905 for (const AtomInfo &info : si->atomsAndOffsets) {
906 // Atoms that contain data-in-code have "transition" references
907 // which mark a point where the embedded data starts of ends.
908 // This needs to be converted to the mach-o format which is an array
909 // of data-in-code ranges.
910 uint32_t startOffset = 0;
911 DataRegionType mode = DataRegionType(0);
912 for (const Reference *ref : *info.atom) {
913 if (ref->kindNamespace() != Reference::KindNamespace::mach_o)
914 continue;
915 if (_archHandler.isDataInCodeTransition(ref->kindValue())) {
916 DataRegionType nextMode = (DataRegionType)ref->addend();
917 if (mode != nextMode) {
918 if (mode != 0) {
919 // Found end data range, so make range entry.
920 DataInCode entry;
921 entry.offset = si->address + info.offsetInSection + startOffset;
922 entry.length = ref->offsetInAtom() - startOffset;
923 entry.kind = mode;
924 file.dataInCode.push_back(entry);
925 }
926 }
927 mode = nextMode;
928 startOffset = ref->offsetInAtom();
929 }
930 }
931 if (mode != 0) {
932 // Function ends with data (no end transition).
933 DataInCode entry;
934 entry.offset = si->address + info.offsetInSection + startOffset;
935 entry.length = info.atom->size() - startOffset;
936 entry.kind = mode;
937 file.dataInCode.push_back(entry);
938 }
939 }
940 }
941}
942
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000943void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000944 NormalizedFile &nFile) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000945 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000946 return;
947
948 uint8_t segmentIndex;
949 uint64_t segmentStartAddr;
950 for (SectionInfo *sect : _sectionInfos) {
951 segIndexForSection(sect, segmentIndex, segmentStartAddr);
952 for (const AtomInfo &info : sect->atomsAndOffsets) {
953 const DefinedAtom *atom = info.atom;
954 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000955 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000956 - segmentStartAddr;
957 const Atom* targ = ref->target();
Nick Kledzik2d432352014-07-17 23:16:21 +0000958 if (_archHandler.isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000959 // A pointer to a DefinedAtom requires rebasing.
960 if (dyn_cast<DefinedAtom>(targ)) {
961 RebaseLocation rebase;
962 rebase.segIndex = segmentIndex;
963 rebase.segOffset = segmentOffset;
964 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
965 nFile.rebasingInfo.push_back(rebase);
966 }
967 // A pointer to an SharedLibraryAtom requires binding.
968 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
969 BindLocation bind;
970 bind.segIndex = segmentIndex;
971 bind.segOffset = segmentOffset;
972 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
973 bind.canBeNull = sa->canBeNullAtRuntime();
974 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000975 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000976 bind.addend = ref->addend();
977 nFile.bindingInfo.push_back(bind);
978 }
979 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000980 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000981 BindLocation bind;
982 bind.segIndex = segmentIndex;
983 bind.segOffset = segmentOffset;
984 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
985 bind.canBeNull = false; //sa->canBeNullAtRuntime();
Nick Kledzik2d432352014-07-17 23:16:21 +0000986 bind.ordinal = 1; // FIXME
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000987 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000988 bind.addend = ref->addend();
989 nFile.lazyBindingInfo.push_back(bind);
990 }
991 }
992 }
993 }
994}
995
996uint32_t Util::fileFlags() {
Nick Kledzike1aaced2014-07-22 00:49:49 +0000997 // FIXME: these need to determined at runtime.
998 if (_context.outputMachOType() == MH_OBJECT) {
999 return MH_SUBSECTIONS_VIA_SYMBOLS;
1000 } else {
1001 return MH_DYLDLINK | MH_NOUNDEFS | MH_TWOLEVEL;
1002 }
Nick Kledzike34182f2013-11-06 21:36:55 +00001003}
1004
1005} // end anonymous namespace
1006
1007
1008namespace lld {
1009namespace mach_o {
1010namespace normalized {
1011
1012/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001013ErrorOr<std::unique_ptr<NormalizedFile>>
1014normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +00001015 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001016 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +00001017 Util util(context);
1018 util.assignAtomsToSections(atomFile);
1019 util.organizeSections();
1020 util.assignAddressesToSections();
1021 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001022
Nick Kledzike34182f2013-11-06 21:36:55 +00001023 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
1024 NormalizedFile &normFile = *f.get();
1025 f->arch = context.arch();
Tim Northoverd30a1f22014-06-20 15:59:00 +00001026 f->fileType = context.outputMachOType();
Nick Kledzike34182f2013-11-06 21:36:55 +00001027 f->flags = util.fileFlags();
Tim Northover301c4e62014-07-01 08:15:41 +00001028 f->installName = context.installName();
Nick Kledzike34182f2013-11-06 21:36:55 +00001029 util.copySegmentInfo(normFile);
1030 util.copySections(normFile);
1031 util.addDependentDylibs(atomFile, normFile);
1032 util.addSymbols(atomFile, normFile);
1033 util.addIndirectSymbols(atomFile, normFile);
1034 util.addRebaseAndBindingInfo(atomFile, normFile);
1035 util.addSectionRelocs(atomFile, normFile);
Nick Kledzik21921372014-07-24 23:06:56 +00001036 util.buildDataInCodeArray(atomFile, normFile);
Nick Kledzike34182f2013-11-06 21:36:55 +00001037 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001038
Nick Kledzike34182f2013-11-06 21:36:55 +00001039 return std::move(f);
1040}
1041
1042
1043} // namespace normalized
1044} // namespace mach_o
1045} // namespace lld
1046