blob: 17dc4701ca14a5fc92a4bc9f6d643c0050421c31 [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);
105 void addDependentDylibs(const lld::File &, NormalizedFile &file);
106 void copyEntryPointAddress(NormalizedFile &file);
107
108private:
109 typedef std::map<DefinedAtom::ContentType, SectionInfo*> TypeToSection;
110 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000111
Nick Kledzike34182f2013-11-06 21:36:55 +0000112 struct DylibInfo { int ordinal; bool hasWeak; bool hasNonWeak; };
113 typedef llvm::StringMap<DylibInfo> DylibPathToInfo;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000114
Nick Kledzike34182f2013-11-06 21:36:55 +0000115 SectionInfo *sectionForAtom(const DefinedAtom*);
Nick Kledzik936d5202014-06-11 01:30:55 +0000116 SectionInfo *getRelocatableSection(DefinedAtom::ContentType type);
117 SectionInfo *getFinalSection(DefinedAtom::ContentType type);
Nick Kledzike34182f2013-11-06 21:36:55 +0000118 void appendAtom(SectionInfo *sect, const DefinedAtom *atom);
119 SegmentInfo *segmentForName(StringRef segName);
120 void layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr);
121 void layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr);
122 void copySectionContent(SectionInfo *si, ContentBytes &content);
123 uint8_t scopeBits(const DefinedAtom* atom);
Nick Kledzik60855392014-06-11 00:24:16 +0000124 uint16_t descBits(const DefinedAtom* atom);
Nick Kledzike34182f2013-11-06 21:36:55 +0000125 int dylibOrdinal(const SharedLibraryAtom *sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000126 void segIndexForSection(const SectionInfo *sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000127 uint8_t &segmentIndex, uint64_t &segmentStartAddr);
128 const Atom *targetOfLazyPointer(const DefinedAtom *lpAtom);
129 const Atom *targetOfStub(const DefinedAtom *stubAtom);
130 bool belongsInGlobalSymbolsSection(const DefinedAtom* atom);
131 void appendSection(SectionInfo *si, NormalizedFile &file);
Nick Kledzik2d432352014-07-17 23:16:21 +0000132 uint32_t sectionIndexForAtom(const Atom *atom);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000133
Nick Kledzike34182f2013-11-06 21:36:55 +0000134 static uint64_t alignTo(uint64_t value, uint8_t align2);
135 typedef llvm::DenseMap<const Atom*, uint32_t> AtomToIndex;
136 struct AtomAndIndex { const Atom *atom; uint32_t index; };
Joey Gouly9d263e02013-12-25 19:39:08 +0000137 struct AtomSorter {
138 bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000139 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000140 struct SegmentSorter {
141 bool operator()(const SegmentInfo *left, const SegmentInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000142 static unsigned weight(const SegmentInfo *);
143 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000144 struct TextSectionSorter {
145 bool operator()(const SectionInfo *left, const SectionInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000146 static unsigned weight(const SectionInfo *);
147 };
148
149 const MachOLinkingContext &_context;
Nick Kledzik2d432352014-07-17 23:16:21 +0000150 mach_o::ArchHandler &_archHandler;
Nick Kledzike34182f2013-11-06 21:36:55 +0000151 llvm::BumpPtrAllocator _allocator;
152 std::vector<SectionInfo*> _sectionInfos;
153 std::vector<SegmentInfo*> _segmentInfos;
154 TypeToSection _sectionMap;
Nick Kledzikacfad802014-05-30 22:51:04 +0000155 std::vector<SectionInfo*> _customSections;
Nick Kledzike34182f2013-11-06 21:36:55 +0000156 AtomToAddress _atomToAddress;
157 DylibPathToInfo _dylibInfo;
158 const DefinedAtom *_entryAtom;
159 AtomToIndex _atomToSymbolIndex;
160};
161
Nick Kledzikec140832014-06-10 01:50:00 +0000162
Nick Kledzik936d5202014-06-11 01:30:55 +0000163SectionInfo *Util::getRelocatableSection(DefinedAtom::ContentType type) {
Nick Kledzikec140832014-06-10 01:50:00 +0000164 StringRef segmentName;
165 StringRef sectionName;
166 SectionType sectionType;
167 SectionAttr sectionAttrs;
168
169 // Use same table used by when parsing .o files.
170 relocatableSectionInfoForContentType(type, segmentName, sectionName,
171 sectionType, sectionAttrs);
172 // If we already have a SectionInfo with this name, re-use it.
173 // This can happen if two ContentType map to the same mach-o section.
174 for (auto sect : _sectionMap) {
175 if (sect.second->sectionName.equals(sectionName) &&
176 sect.second->segmentName.equals(segmentName)) {
177 return sect.second;
178 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000179 }
Nick Kledzikec140832014-06-10 01:50:00 +0000180 // Otherwise allocate new SectionInfo object.
Nick Kledzik936d5202014-06-11 01:30:55 +0000181 SectionInfo *sect = new (_allocator) SectionInfo(segmentName, sectionName,
182 sectionType, sectionAttrs);
183 _sectionInfos.push_back(sect);
184 _sectionMap[type] = sect;
185 return sect;
Nick Kledzikec140832014-06-10 01:50:00 +0000186}
187
188#define ENTRY(seg, sect, type, atomType) \
189 {seg, sect, type, DefinedAtom::atomType }
190
191struct MachOFinalSectionFromAtomType {
192 StringRef segmentName;
193 StringRef sectionName;
194 SectionType sectionType;
195 DefinedAtom::ContentType atomType;
196};
197
198const MachOFinalSectionFromAtomType sectsToAtomType[] = {
199 ENTRY("__TEXT", "__text", S_REGULAR, typeCode),
200 ENTRY("__TEXT", "__cstring", S_CSTRING_LITERALS, typeCString),
201 ENTRY("__TEXT", "__ustring", S_REGULAR, typeUTF16String),
202 ENTRY("__TEXT", "__const", S_REGULAR, typeConstant),
203 ENTRY("__TEXT", "__const", S_4BYTE_LITERALS, typeLiteral4),
204 ENTRY("__TEXT", "__const", S_8BYTE_LITERALS, typeLiteral8),
205 ENTRY("__TEXT", "__const", S_16BYTE_LITERALS, typeLiteral16),
206 ENTRY("__TEXT", "__stubs", S_SYMBOL_STUBS, typeStub),
207 ENTRY("__TEXT", "__stub_helper", S_REGULAR, typeStubHelper),
208 ENTRY("__TEXT", "__gcc_except_tab", S_REGULAR, typeLSDA),
209 ENTRY("__TEXT", "__eh_frame", S_COALESCED, typeCFI),
210 ENTRY("__DATA", "__data", S_REGULAR, typeData),
211 ENTRY("__DATA", "__const", S_REGULAR, typeConstData),
212 ENTRY("__DATA", "__cfstring", S_REGULAR, typeCFString),
213 ENTRY("__DATA", "__la_symbol_ptr", S_LAZY_SYMBOL_POINTERS,
214 typeLazyPointer),
215 ENTRY("__DATA", "__mod_init_func", S_MOD_INIT_FUNC_POINTERS,
216 typeInitializerPtr),
217 ENTRY("__DATA", "__mod_term_func", S_MOD_TERM_FUNC_POINTERS,
218 typeTerminatorPtr),
219 ENTRY("__DATA", "___got", S_NON_LAZY_SYMBOL_POINTERS,
220 typeGOT),
Tim Northover9ee99352014-06-30 09:49:37 +0000221 ENTRY("__DATA", "___bss", S_ZEROFILL, typeZeroFill),
222
223 // FIXME: __compact_unwind actually needs to be processed by a pass and put
224 // into __TEXT,__unwind_info. For now, forwarding it back to
225 // __LD,__compact_unwind is harmless (it's ignored by the unwinder, which then
226 // proceeds to process __TEXT,__eh_frame for its instructions).
227 ENTRY("__LD", "__compact_unwind", S_REGULAR, typeCompactUnwindInfo),
Nick Kledzikec140832014-06-10 01:50:00 +0000228};
229#undef ENTRY
230
231
Nick Kledzik936d5202014-06-11 01:30:55 +0000232SectionInfo *Util::getFinalSection(DefinedAtom::ContentType atomType) {
Tim Northoverb5bf6862014-06-30 10:30:00 +0000233 for (auto &p : sectsToAtomType) {
234 if (p.atomType != atomType)
Nick Kledzikec140832014-06-10 01:50:00 +0000235 continue;
236 SectionAttr sectionAttrs = 0;
237 switch (atomType) {
238 case DefinedAtom::typeCode:
239 case DefinedAtom::typeStub:
240 sectionAttrs = S_ATTR_PURE_INSTRUCTIONS;
241 break;
242 default:
243 break;
244 }
245 // If we already have a SectionInfo with this name, re-use it.
246 // This can happen if two ContentType map to the same mach-o section.
247 for (auto sect : _sectionMap) {
Tim Northoverb5bf6862014-06-30 10:30:00 +0000248 if (sect.second->sectionName.equals(p.sectionName) &&
249 sect.second->segmentName.equals(p.segmentName)) {
Nick Kledzikec140832014-06-10 01:50:00 +0000250 return sect.second;
251 }
252 }
253 // Otherwise allocate new SectionInfo object.
Tim Northoverb5bf6862014-06-30 10:30:00 +0000254 SectionInfo *sect = new (_allocator) SectionInfo(p.segmentName,
255 p.sectionName,
256 p.sectionType,
Nick Kledzik936d5202014-06-11 01:30:55 +0000257 sectionAttrs);
258 _sectionInfos.push_back(sect);
259 _sectionMap[atomType] = sect;
260 return sect;
Nick Kledzikec140832014-06-10 01:50:00 +0000261 }
262 llvm_unreachable("content type not yet supported");
Nick Kledzike34182f2013-11-06 21:36:55 +0000263}
264
265
266
267SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
Nick Kledzikacfad802014-05-30 22:51:04 +0000268 if (atom->sectionChoice() == DefinedAtom::sectionBasedOnContent) {
269 // Section for this atom is derived from content type.
270 DefinedAtom::ContentType type = atom->contentType();
271 auto pos = _sectionMap.find(type);
272 if ( pos != _sectionMap.end() )
273 return pos->second;
Tim Northoverd30a1f22014-06-20 15:59:00 +0000274 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzik936d5202014-06-11 01:30:55 +0000275 return rMode ? getRelocatableSection(type) : getFinalSection(type);
Nick Kledzikacfad802014-05-30 22:51:04 +0000276 } else {
277 // This atom needs to be in a custom section.
278 StringRef customName = atom->customSectionName();
279 // Look to see if we have already allocated the needed custom section.
280 for(SectionInfo *sect : _customSections) {
281 const DefinedAtom *firstAtom = sect->atomsAndOffsets.front().atom;
282 if (firstAtom->customSectionName().equals(customName)) {
283 return sect;
284 }
285 }
286 // Not found, so need to create a new custom section.
287 size_t seperatorIndex = customName.find('/');
288 assert(seperatorIndex != StringRef::npos);
Tim Northover7b0a1302014-06-30 09:49:33 +0000289 StringRef segName = customName.slice(0, seperatorIndex);
290 StringRef sectName = customName.drop_front(seperatorIndex + 1);
Nick Kledzikacfad802014-05-30 22:51:04 +0000291 SectionInfo *sect = new (_allocator) SectionInfo(segName, sectName,
292 S_REGULAR);
293 _customSections.push_back(sect);
Tim Northover7b0a1302014-06-30 09:49:33 +0000294 _sectionInfos.push_back(sect);
Nick Kledzikacfad802014-05-30 22:51:04 +0000295 return sect;
296 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000297}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000298
Nick Kledzike34182f2013-11-06 21:36:55 +0000299
300void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
301 // Figure out offset for atom in this section given alignment constraints.
302 uint64_t offset = sect->size;
303 DefinedAtom::Alignment atomAlign = atom->alignment();
304 uint64_t align2 = 1 << atomAlign.powerOf2;
305 uint64_t requiredModulus = atomAlign.modulus;
306 uint64_t currentModulus = (offset % align2);
307 if ( currentModulus != requiredModulus ) {
308 if ( requiredModulus > currentModulus )
309 offset += requiredModulus-currentModulus;
310 else
311 offset += align2+requiredModulus-currentModulus;
312 }
313 // Record max alignment of any atom in this section.
314 if ( atomAlign.powerOf2 > sect->alignment )
315 sect->alignment = atomAlign.powerOf2;
316 // Assign atom to this section with this offset.
317 AtomInfo ai = {atom, offset};
318 sect->atomsAndOffsets.push_back(ai);
319 // Update section size to include this atom.
320 sect->size = offset + atom->size();
321}
322
323void Util::assignAtomsToSections(const lld::File &atomFile) {
324 for (const DefinedAtom *atom : atomFile.defined()) {
325 appendAtom(sectionForAtom(atom), atom);
326 }
327}
328
329SegmentInfo *Util::segmentForName(StringRef segName) {
330 for (SegmentInfo *si : _segmentInfos) {
331 if ( si->name.equals(segName) )
332 return si;
333 }
334 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
335 if (segName.equals("__TEXT"))
336 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
337 else if (segName.equals("__DATA"))
338 info->access = VM_PROT_READ | VM_PROT_WRITE;
339 else if (segName.equals("__PAGEZERO"))
340 info->access = 0;
341 _segmentInfos.push_back(info);
342 return info;
343}
344
345unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
346 return llvm::StringSwitch<unsigned>(seg->name)
347 .Case("__PAGEZERO", 1)
348 .Case("__TEXT", 2)
349 .Case("__DATA", 3)
350 .Default(100);
351}
352
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000353bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000354 const SegmentInfo *right) {
355 return (weight(left) < weight(right));
356}
357
358unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
359 return llvm::StringSwitch<unsigned>(sect->sectionName)
360 .Case("__text", 1)
361 .Case("__stubs", 2)
362 .Case("__stub_helper", 3)
363 .Case("__const", 4)
364 .Case("__cstring", 5)
365 .Case("__unwind_info", 98)
366 .Case("__eh_frame", 99)
367 .Default(10);
368}
369
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000370bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000371 const SectionInfo *right) {
372 return (weight(left) < weight(right));
373}
374
375
376void Util::organizeSections() {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000377 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000378 // Leave sections ordered as normalized file specified.
379 uint32_t sectionIndex = 1;
380 for (SectionInfo *si : _sectionInfos) {
381 si->finalSectionIndex = sectionIndex++;
382 }
383 } else {
384 // Main executables, need a zero-page segment
Tim Northoverd30a1f22014-06-20 15:59:00 +0000385 if (_context.outputMachOType() == llvm::MachO::MH_EXECUTE)
Nick Kledzike34182f2013-11-06 21:36:55 +0000386 segmentForName("__PAGEZERO");
387 // Group sections into segments.
388 for (SectionInfo *si : _sectionInfos) {
389 SegmentInfo *seg = segmentForName(si->segmentName);
390 seg->sections.push_back(si);
391 }
392 // Sort segments.
393 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000394
Nick Kledzike34182f2013-11-06 21:36:55 +0000395 // Sort sections within segments.
396 for (SegmentInfo *seg : _segmentInfos) {
397 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000398 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000399 TextSectionSorter());
400 }
401 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000402
Nick Kledzike34182f2013-11-06 21:36:55 +0000403 // Record final section indexes.
404 uint32_t sectionIndex = 1;
405 for (SegmentInfo *seg : _segmentInfos) {
406 for (SectionInfo *sect : seg->sections) {
407 sect->finalSectionIndex = sectionIndex++;
408 }
409 }
410 }
411
412}
413
414uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
415 return llvm::RoundUpToAlignment(value, 1 << align2);
416}
417
418
419void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
420 seg->address = addr;
421 for (SectionInfo *sect : seg->sections) {
422 sect->address = alignTo(addr, sect->alignment);
423 addr += sect->size;
424 }
425 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
426}
427
428
429// __TEXT segment lays out backwards so padding is at front after load commands.
430void Util::layoutSectionsInTextSegment(SegmentInfo *seg, uint64_t &addr) {
431 seg->address = addr;
432 // Walks sections starting at end to calculate padding for start.
433 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000434 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000435 SectionInfo *sect = *it;
436 taddr -= sect->size;
437 taddr = taddr & (0 - (1 << sect->alignment));
438 }
439 int64_t padding = taddr;
440 while (padding < 0)
441 padding += _context.pageSize();
442 // Start assigning section address starting at padded offset.
443 addr += padding;
444 for (SectionInfo *sect : seg->sections) {
445 sect->address = alignTo(addr, sect->alignment);
446 addr = sect->address + sect->size;
447 }
448 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
449}
450
451
452void Util::assignAddressesToSections() {
453 uint64_t address = 0; // FIXME
Tim Northoverd30a1f22014-06-20 15:59:00 +0000454 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000455 for (SegmentInfo *seg : _segmentInfos) {
456 if (seg->name.equals("__PAGEZERO")) {
457 seg->size = _context.pageZeroSize();
458 address += seg->size;
459 }
460 else if (seg->name.equals("__TEXT"))
461 layoutSectionsInTextSegment(seg, address);
462 else
463 layoutSectionsInSegment(seg, address);
Tim Northover7b0a1302014-06-30 09:49:33 +0000464
465 address = llvm::RoundUpToAlignment(address, _context.pageSize());
Nick Kledzike34182f2013-11-06 21:36:55 +0000466 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000467 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000468 llvm::dbgs() << "assignAddressesToSections()\n";
469 for (SegmentInfo *sgi : _segmentInfos) {
470 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000471 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000472 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000473 << "'\n";
474 for (SectionInfo *si : sgi->sections) {
475 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000476 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000477 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000478 << "\n";
479 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000480 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000481 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000482 } else {
483 for (SectionInfo *sect : _sectionInfos) {
484 sect->address = alignTo(address, sect->alignment);
485 address = sect->address + sect->size;
486 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000487 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000488 llvm::dbgs() << "assignAddressesToSections()\n";
489 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000490 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000491 << " address= " << llvm::format("0x%08X", si->address)
492 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000493 << "\n";
494 }
495 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000496 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000497}
498
499
500void Util::copySegmentInfo(NormalizedFile &file) {
501 for (SegmentInfo *sgi : _segmentInfos) {
502 Segment seg;
503 seg.name = sgi->name;
504 seg.address = sgi->address;
505 seg.size = sgi->size;
506 seg.access = sgi->access;
507 file.segments.push_back(seg);
508 }
509}
510
511void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
Nick Kledzik3f690762014-06-27 18:25:01 +0000512 const bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzik2d432352014-07-17 23:16:21 +0000513
514 // Utility function for ArchHandler to find address of atom in output file.
515 auto addrForAtom = [&] (const Atom &atom) -> uint64_t {
516 auto pos = _atomToAddress.find(&atom);
517 assert(pos != _atomToAddress.end());
518 return pos->second;
519 };
520
Nick Kledzike34182f2013-11-06 21:36:55 +0000521 // Add new empty section to end of file.sections.
522 Section temp;
523 file.sections.push_back(std::move(temp));
524 Section* normSect = &file.sections.back();
525 // Copy fields to normalized section.
526 normSect->segmentName = si->segmentName;
527 normSect->sectionName = si->sectionName;
528 normSect->type = si->type;
529 normSect->attributes = si->attributes;
530 normSect->address = si->address;
531 normSect->alignment = si->alignment;
532 // Record where normalized section is.
533 si->normalizedSectionIndex = file.sections.size()-1;
534 // Copy content from atoms to content buffer for section.
Nick Kledzik61fdef62014-05-15 20:59:23 +0000535 if (si->type == llvm::MachO::S_ZEROFILL)
536 return;
Nick Kledzik6edd7222014-01-11 01:07:43 +0000537 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
538 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
Nick Kledzike34182f2013-11-06 21:36:55 +0000539 for (AtomInfo &ai : si->atomsAndOffsets) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000540 uint8_t *atomContent = reinterpret_cast<uint8_t*>
541 (&sectionContent[ai.offsetInSection]);
Nick Kledzik2d432352014-07-17 23:16:21 +0000542 _archHandler.generateAtomContent(*ai.atom, rMode, addrForAtom, atomContent);
Nick Kledzike34182f2013-11-06 21:36:55 +0000543 }
544}
545
546void Util::copySections(NormalizedFile &file) {
547 file.sections.reserve(_sectionInfos.size());
548 // For final linked images, write sections grouped by segment.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000549 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000550 for (SegmentInfo *sgi : _segmentInfos) {
551 for (SectionInfo *si : sgi->sections) {
552 appendSection(si, file);
553 }
554 }
555 } else {
556 // Object files write sections in default order.
557 for (SectionInfo *si : _sectionInfos) {
558 appendSection(si, file);
559 }
560 }
561}
562
563void Util::copyEntryPointAddress(NormalizedFile &nFile) {
564 if (_context.outputTypeHasEntry()) {
565 nFile.entryAddress = _atomToAddress[_entryAtom];
566 }
567}
568
569void Util::buildAtomToAddressMap() {
570 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
571 << "assign atom addresses:\n");
572 const bool lookForEntry = _context.outputTypeHasEntry();
573 for (SectionInfo *sect : _sectionInfos) {
574 for (const AtomInfo &info : sect->atomsAndOffsets) {
575 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
576 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
577 (info.atom->size() != 0) &&
578 info.atom->name() == _context.entrySymbolName()) {
579 _entryAtom = info.atom;
580 }
581 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
582 << " address="
583 << llvm::format("0x%016X", _atomToAddress[info.atom])
584 << " atom=" << info.atom
585 << " name=" << info.atom->name() << "\n");
586 }
587 }
588}
589
590uint8_t Util::scopeBits(const DefinedAtom* atom) {
591 switch (atom->scope()) {
592 case Atom::scopeTranslationUnit:
593 return 0;
594 case Atom::scopeLinkageUnit:
595 return N_PEXT | N_EXT;
596 case Atom::scopeGlobal:
597 return N_EXT;
598 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000599 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000600}
601
Nick Kledzik60855392014-06-11 00:24:16 +0000602uint16_t Util::descBits(const DefinedAtom* atom) {
603 uint16_t desc = 0;
604 switch (atom->merge()) {
605 case lld::DefinedAtom::mergeNo:
606 case lld::DefinedAtom::mergeAsTentative:
607 break;
608 case lld::DefinedAtom::mergeAsWeak:
609 case lld::DefinedAtom::mergeAsWeakAndAddressUsed:
610 desc |= N_WEAK_DEF;
611 break;
612 case lld::DefinedAtom::mergeSameNameAndSize:
613 case lld::DefinedAtom::mergeByLargestSection:
614 case lld::DefinedAtom::mergeByContent:
615 llvm_unreachable("Unsupported DefinedAtom::merge()");
616 break;
617 }
618 if (atom->contentType() == lld::DefinedAtom::typeResolver)
619 desc |= N_SYMBOL_RESOLVER;
620 return desc;
621}
622
623
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000624bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000625 const AtomAndIndex &right) {
626 return (left.atom->name().compare(right.atom->name()) < 0);
627}
628
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000629
Nick Kledzike34182f2013-11-06 21:36:55 +0000630bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
Nick Kledzik936d5202014-06-11 01:30:55 +0000631 // ScopeLinkageUnit symbols are in globals area of symbol table
632 // in object files, but in locals area for final linked images.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000633 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzik936d5202014-06-11 01:30:55 +0000634 return (atom->scope() != Atom::scopeTranslationUnit);
635 else
636 return (atom->scope() == Atom::scopeGlobal);
Nick Kledzike34182f2013-11-06 21:36:55 +0000637}
638
639void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000640 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzike34182f2013-11-06 21:36:55 +0000641 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000642
Nick Kledzike34182f2013-11-06 21:36:55 +0000643 // Add all local (non-global) symbols in address order
644 std::vector<AtomAndIndex> globals;
645 globals.reserve(512);
646 for (SectionInfo *sect : _sectionInfos) {
647 for (const AtomInfo &info : sect->atomsAndOffsets) {
648 const DefinedAtom *atom = info.atom;
649 if (!atom->name().empty()) {
650 if (belongsInGlobalSymbolsSection(atom)) {
651 AtomAndIndex ai = { atom, sect->finalSectionIndex };
652 globals.push_back(ai);
653 } else {
654 Symbol sym;
655 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000656 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000657 sym.scope = scopeBits(atom);
658 sym.sect = sect->finalSectionIndex;
659 sym.desc = 0;
660 sym.value = _atomToAddress[atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000661 _atomToSymbolIndex[atom] = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000662 file.localSymbols.push_back(sym);
663 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000664 } else if (rMode && _archHandler.needsLocalSymbolInRelocatableFile(atom)){
665 // Create 'Lxxx' labels for anonymous atoms if archHandler says so.
666 static unsigned tempNum = 1;
667 char tmpName[16];
668 sprintf(tmpName, "L%04u", tempNum++);
669 StringRef tempRef(tmpName);
670 Symbol sym;
671 sym.name = tempRef.copy(file.ownedAllocations);
672 sym.type = N_SECT;
673 sym.scope = 0;
674 sym.sect = sect->finalSectionIndex;
675 sym.desc = 0;
676 sym.value = _atomToAddress[atom];
677 _atomToSymbolIndex[atom] = file.localSymbols.size();
678 file.localSymbols.push_back(sym);
Nick Kledzike34182f2013-11-06 21:36:55 +0000679 }
680 }
681 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000682
Nick Kledzike34182f2013-11-06 21:36:55 +0000683 // Sort global symbol alphabetically, then add to symbol table.
684 std::sort(globals.begin(), globals.end(), AtomSorter());
Nick Kledzik2d432352014-07-17 23:16:21 +0000685 const uint32_t globalStartIndex = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000686 for (AtomAndIndex &ai : globals) {
687 Symbol sym;
688 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000689 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000690 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
691 sym.sect = ai.index;
Nick Kledzik60855392014-06-11 00:24:16 +0000692 sym.desc = descBits(static_cast<const DefinedAtom*>(ai.atom));
Nick Kledzike34182f2013-11-06 21:36:55 +0000693 sym.value = _atomToAddress[ai.atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000694 _atomToSymbolIndex[ai.atom] = globalStartIndex + file.globalSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000695 file.globalSymbols.push_back(sym);
696 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000697
698
Nick Kledzike34182f2013-11-06 21:36:55 +0000699 // Sort undefined symbol alphabetically, then add to symbol table.
700 std::vector<AtomAndIndex> undefs;
701 undefs.reserve(128);
702 for (const UndefinedAtom *atom : atomFile.undefined()) {
703 AtomAndIndex ai = { atom, 0 };
704 undefs.push_back(ai);
705 }
706 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
707 AtomAndIndex ai = { atom, 0 };
708 undefs.push_back(ai);
709 }
710 std::sort(undefs.begin(), undefs.end(), AtomSorter());
711 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
712 for (AtomAndIndex &ai : undefs) {
713 Symbol sym;
714 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000715 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000716 sym.scope = N_EXT;
717 sym.sect = 0;
718 sym.desc = 0;
719 sym.value = 0;
720 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
721 file.undefinedSymbols.push_back(sym);
722 }
723}
724
725const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
726 for (const Reference *ref : *lpAtom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000727 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000728 return ref->target();
729 }
730 }
731 return nullptr;
732}
733
734const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
735 for (const Reference *ref : *stubAtom) {
736 if (const Atom *ta = ref->target()) {
737 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
738 const Atom *target = targetOfLazyPointer(lpAtom);
739 if (target)
740 return target;
741 }
742 }
743 }
744 return nullptr;
745}
746
747
748void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
749 for (SectionInfo *si : _sectionInfos) {
750 Section &normSect = file.sections[si->normalizedSectionIndex];
751 switch (si->type) {
752 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
753 for (const AtomInfo &info : si->atomsAndOffsets) {
754 bool foundTarget = false;
755 for (const Reference *ref : *info.atom) {
756 const Atom *target = ref->target();
757 if (target) {
758 if (isa<const SharedLibraryAtom>(target)) {
759 uint32_t index = _atomToSymbolIndex[target];
760 normSect.indirectSymbols.push_back(index);
761 foundTarget = true;
762 } else {
763 normSect.indirectSymbols.push_back(
764 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
765 }
766 }
767 }
768 if (!foundTarget) {
769 normSect.indirectSymbols.push_back(
770 llvm::MachO::INDIRECT_SYMBOL_ABS);
771 }
772 }
773 break;
774 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
775 for (const AtomInfo &info : si->atomsAndOffsets) {
776 const Atom *target = targetOfLazyPointer(info.atom);
777 if (target) {
778 uint32_t index = _atomToSymbolIndex[target];
779 normSect.indirectSymbols.push_back(index);
780 }
781 }
782 break;
783 case llvm::MachO::S_SYMBOL_STUBS:
784 for (const AtomInfo &info : si->atomsAndOffsets) {
785 const Atom *target = targetOfStub(info.atom);
786 if (target) {
787 uint32_t index = _atomToSymbolIndex[target];
788 normSect.indirectSymbols.push_back(index);
789 }
790 }
791 break;
792 default:
793 break;
794 }
795 }
796
797}
798
799void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
800 // Scan all imported symbols and build up list of dylibs they are from.
801 int ordinal = 1;
802 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
803 StringRef loadPath = slAtom->loadName();
804 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
805 if (pos == _dylibInfo.end()) {
806 DylibInfo info;
807 info.ordinal = ordinal++;
808 info.hasWeak = slAtom->canBeNullAtRuntime();
809 info.hasNonWeak = !info.hasWeak;
810 _dylibInfo[loadPath] = info;
811 DependentDylib depInfo;
812 depInfo.path = loadPath;
813 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
814 nFile.dependentDylibs.push_back(depInfo);
815 } else {
816 if ( slAtom->canBeNullAtRuntime() )
817 pos->second.hasWeak = true;
818 else
819 pos->second.hasNonWeak = true;
820 }
821 }
822 // Automatically weak link dylib in which all symbols are weak (canBeNull).
823 for (DependentDylib &dep : nFile.dependentDylibs) {
824 DylibInfo &info = _dylibInfo[dep.path];
825 if (info.hasWeak && !info.hasNonWeak)
826 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
827 }
828}
829
830
831int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
832 return _dylibInfo[sa->loadName()].ordinal;
833}
834
835void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
836 uint64_t &segmentStartAddr) {
837 segmentIndex = 0;
838 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000839 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000840 && (seg->address+seg->size >= sect->address+sect->size)) {
841 segmentStartAddr = seg->address;
842 return;
843 }
844 ++segmentIndex;
845 }
846 llvm_unreachable("section not in any segment");
847}
848
849
Nick Kledzik2d432352014-07-17 23:16:21 +0000850uint32_t Util::sectionIndexForAtom(const Atom *atom) {
851 uint64_t address = _atomToAddress[atom];
852 uint32_t index = 1;
853 for (const SectionInfo *si : _sectionInfos) {
854 if ((si->address <= address) && (address < si->address+si->size))
855 return index;
856 ++index;
857 }
858 llvm_unreachable("atom not in any section");
Nick Kledzike34182f2013-11-06 21:36:55 +0000859}
860
861void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000862 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000863 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000864
Nick Kledzik2d432352014-07-17 23:16:21 +0000865
866 // Utility function for ArchHandler to find symbol index for an atom.
867 auto symIndexForAtom = [&] (const Atom &atom) -> uint32_t {
868 auto pos = _atomToSymbolIndex.find(&atom);
869 assert(pos != _atomToSymbolIndex.end());
870 return pos->second;
871 };
872
873 // Utility function for ArchHandler to find section index for an atom.
874 auto sectIndexForAtom = [&] (const Atom &atom) -> uint32_t {
875 return sectionIndexForAtom(&atom);
876 };
877
878 // Utility function for ArchHandler to find address of atom in output file.
879 auto addressForAtom = [&] (const Atom &atom) -> uint64_t {
880 auto pos = _atomToAddress.find(&atom);
881 assert(pos != _atomToAddress.end());
882 return pos->second;
883 };
884
Nick Kledzike34182f2013-11-06 21:36:55 +0000885 for (SectionInfo *si : _sectionInfos) {
886 Section &normSect = file.sections[si->normalizedSectionIndex];
887 for (const AtomInfo &info : si->atomsAndOffsets) {
888 const DefinedAtom *atom = info.atom;
889 for (const Reference *ref : *atom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000890 _archHandler.appendSectionRelocations(*atom, info.offsetInSection, *ref,
891 symIndexForAtom,
892 sectIndexForAtom,
893 addressForAtom,
894 normSect.relocations);
Nick Kledzike34182f2013-11-06 21:36:55 +0000895 }
896 }
897 }
898}
899
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000900void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000901 NormalizedFile &nFile) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000902 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000903 return;
904
905 uint8_t segmentIndex;
906 uint64_t segmentStartAddr;
907 for (SectionInfo *sect : _sectionInfos) {
908 segIndexForSection(sect, segmentIndex, segmentStartAddr);
909 for (const AtomInfo &info : sect->atomsAndOffsets) {
910 const DefinedAtom *atom = info.atom;
911 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000912 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000913 - segmentStartAddr;
914 const Atom* targ = ref->target();
Nick Kledzik2d432352014-07-17 23:16:21 +0000915 if (_archHandler.isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000916 // A pointer to a DefinedAtom requires rebasing.
917 if (dyn_cast<DefinedAtom>(targ)) {
918 RebaseLocation rebase;
919 rebase.segIndex = segmentIndex;
920 rebase.segOffset = segmentOffset;
921 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
922 nFile.rebasingInfo.push_back(rebase);
923 }
924 // A pointer to an SharedLibraryAtom requires binding.
925 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
926 BindLocation bind;
927 bind.segIndex = segmentIndex;
928 bind.segOffset = segmentOffset;
929 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
930 bind.canBeNull = sa->canBeNullAtRuntime();
931 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000932 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000933 bind.addend = ref->addend();
934 nFile.bindingInfo.push_back(bind);
935 }
936 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000937 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000938 BindLocation bind;
939 bind.segIndex = segmentIndex;
940 bind.segOffset = segmentOffset;
941 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
942 bind.canBeNull = false; //sa->canBeNullAtRuntime();
Nick Kledzik2d432352014-07-17 23:16:21 +0000943 bind.ordinal = 1; // FIXME
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000944 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000945 bind.addend = ref->addend();
946 nFile.lazyBindingInfo.push_back(bind);
947 }
948 }
949 }
950 }
951}
952
953uint32_t Util::fileFlags() {
954 return 0; //FIX ME
955}
956
957} // end anonymous namespace
958
959
960namespace lld {
961namespace mach_o {
962namespace normalized {
963
964/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000965ErrorOr<std::unique_ptr<NormalizedFile>>
966normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000967 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000968 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +0000969 Util util(context);
970 util.assignAtomsToSections(atomFile);
971 util.organizeSections();
972 util.assignAddressesToSections();
973 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000974
Nick Kledzike34182f2013-11-06 21:36:55 +0000975 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
976 NormalizedFile &normFile = *f.get();
977 f->arch = context.arch();
Tim Northoverd30a1f22014-06-20 15:59:00 +0000978 f->fileType = context.outputMachOType();
Nick Kledzike34182f2013-11-06 21:36:55 +0000979 f->flags = util.fileFlags();
Tim Northover301c4e62014-07-01 08:15:41 +0000980 f->installName = context.installName();
Nick Kledzike34182f2013-11-06 21:36:55 +0000981 util.copySegmentInfo(normFile);
982 util.copySections(normFile);
983 util.addDependentDylibs(atomFile, normFile);
984 util.addSymbols(atomFile, normFile);
985 util.addIndirectSymbols(atomFile, normFile);
986 util.addRebaseAndBindingInfo(atomFile, normFile);
987 util.addSectionRelocs(atomFile, normFile);
988 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000989
Nick Kledzike34182f2013-11-06 21:36:55 +0000990 return std::move(f);
991}
992
993
994} // namespace normalized
995} // namespace mach_o
996} // namespace lld
997