blob: e181a212de343df33c8220961d019b4b63767fcf [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()) {
Nick Kledzik54fd4e52014-07-28 23:06:09 +0000566 if (_archHandler.isThumbFunction(*_entryAtom))
567 nFile.entryAddress = (_atomToAddress[_entryAtom] | 1);
568 else
569 nFile.entryAddress = _atomToAddress[_entryAtom];
Nick Kledzike34182f2013-11-06 21:36:55 +0000570 }
571}
572
573void Util::buildAtomToAddressMap() {
574 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
575 << "assign atom addresses:\n");
576 const bool lookForEntry = _context.outputTypeHasEntry();
577 for (SectionInfo *sect : _sectionInfos) {
578 for (const AtomInfo &info : sect->atomsAndOffsets) {
579 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
580 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
581 (info.atom->size() != 0) &&
582 info.atom->name() == _context.entrySymbolName()) {
583 _entryAtom = info.atom;
584 }
585 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
586 << " address="
587 << llvm::format("0x%016X", _atomToAddress[info.atom])
588 << " atom=" << info.atom
589 << " name=" << info.atom->name() << "\n");
590 }
591 }
592}
593
594uint8_t Util::scopeBits(const DefinedAtom* atom) {
595 switch (atom->scope()) {
596 case Atom::scopeTranslationUnit:
597 return 0;
598 case Atom::scopeLinkageUnit:
599 return N_PEXT | N_EXT;
600 case Atom::scopeGlobal:
601 return N_EXT;
602 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000603 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000604}
605
Nick Kledzik60855392014-06-11 00:24:16 +0000606uint16_t Util::descBits(const DefinedAtom* atom) {
607 uint16_t desc = 0;
608 switch (atom->merge()) {
609 case lld::DefinedAtom::mergeNo:
610 case lld::DefinedAtom::mergeAsTentative:
611 break;
612 case lld::DefinedAtom::mergeAsWeak:
613 case lld::DefinedAtom::mergeAsWeakAndAddressUsed:
614 desc |= N_WEAK_DEF;
615 break;
616 case lld::DefinedAtom::mergeSameNameAndSize:
617 case lld::DefinedAtom::mergeByLargestSection:
618 case lld::DefinedAtom::mergeByContent:
619 llvm_unreachable("Unsupported DefinedAtom::merge()");
620 break;
621 }
622 if (atom->contentType() == lld::DefinedAtom::typeResolver)
623 desc |= N_SYMBOL_RESOLVER;
Nick Kledzik7e9808f2014-07-23 00:51:37 +0000624 if (_archHandler.isThumbFunction(*atom))
625 desc |= N_ARM_THUMB_DEF;
Nick Kledzik60855392014-06-11 00:24:16 +0000626 return desc;
627}
628
629
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000630bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000631 const AtomAndIndex &right) {
632 return (left.atom->name().compare(right.atom->name()) < 0);
633}
634
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000635
Nick Kledzike34182f2013-11-06 21:36:55 +0000636bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
Nick Kledzik936d5202014-06-11 01:30:55 +0000637 // ScopeLinkageUnit symbols are in globals area of symbol table
638 // in object files, but in locals area for final linked images.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000639 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzik936d5202014-06-11 01:30:55 +0000640 return (atom->scope() != Atom::scopeTranslationUnit);
641 else
642 return (atom->scope() == Atom::scopeGlobal);
Nick Kledzike34182f2013-11-06 21:36:55 +0000643}
644
645void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000646 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzike34182f2013-11-06 21:36:55 +0000647 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000648
Nick Kledzike34182f2013-11-06 21:36:55 +0000649 // Add all local (non-global) symbols in address order
650 std::vector<AtomAndIndex> globals;
651 globals.reserve(512);
652 for (SectionInfo *sect : _sectionInfos) {
653 for (const AtomInfo &info : sect->atomsAndOffsets) {
654 const DefinedAtom *atom = info.atom;
655 if (!atom->name().empty()) {
656 if (belongsInGlobalSymbolsSection(atom)) {
657 AtomAndIndex ai = { atom, sect->finalSectionIndex };
658 globals.push_back(ai);
659 } else {
660 Symbol sym;
661 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000662 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000663 sym.scope = scopeBits(atom);
664 sym.sect = sect->finalSectionIndex;
Nick Kledzik7e9808f2014-07-23 00:51:37 +0000665 sym.desc = descBits(atom);
Nick Kledzike34182f2013-11-06 21:36:55 +0000666 sym.value = _atomToAddress[atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000667 _atomToSymbolIndex[atom] = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000668 file.localSymbols.push_back(sym);
669 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000670 } else if (rMode && _archHandler.needsLocalSymbolInRelocatableFile(atom)){
671 // Create 'Lxxx' labels for anonymous atoms if archHandler says so.
672 static unsigned tempNum = 1;
673 char tmpName[16];
674 sprintf(tmpName, "L%04u", tempNum++);
675 StringRef tempRef(tmpName);
676 Symbol sym;
677 sym.name = tempRef.copy(file.ownedAllocations);
678 sym.type = N_SECT;
679 sym.scope = 0;
680 sym.sect = sect->finalSectionIndex;
681 sym.desc = 0;
682 sym.value = _atomToAddress[atom];
683 _atomToSymbolIndex[atom] = file.localSymbols.size();
684 file.localSymbols.push_back(sym);
Nick Kledzike34182f2013-11-06 21:36:55 +0000685 }
686 }
687 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000688
Nick Kledzike34182f2013-11-06 21:36:55 +0000689 // Sort global symbol alphabetically, then add to symbol table.
690 std::sort(globals.begin(), globals.end(), AtomSorter());
Nick Kledzik2d432352014-07-17 23:16:21 +0000691 const uint32_t globalStartIndex = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000692 for (AtomAndIndex &ai : globals) {
693 Symbol sym;
694 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000695 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000696 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
697 sym.sect = ai.index;
Nick Kledzik60855392014-06-11 00:24:16 +0000698 sym.desc = descBits(static_cast<const DefinedAtom*>(ai.atom));
Nick Kledzike34182f2013-11-06 21:36:55 +0000699 sym.value = _atomToAddress[ai.atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000700 _atomToSymbolIndex[ai.atom] = globalStartIndex + file.globalSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000701 file.globalSymbols.push_back(sym);
702 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000703
704
Nick Kledzike34182f2013-11-06 21:36:55 +0000705 // Sort undefined symbol alphabetically, then add to symbol table.
706 std::vector<AtomAndIndex> undefs;
707 undefs.reserve(128);
708 for (const UndefinedAtom *atom : atomFile.undefined()) {
709 AtomAndIndex ai = { atom, 0 };
710 undefs.push_back(ai);
711 }
712 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
713 AtomAndIndex ai = { atom, 0 };
714 undefs.push_back(ai);
715 }
716 std::sort(undefs.begin(), undefs.end(), AtomSorter());
717 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
718 for (AtomAndIndex &ai : undefs) {
719 Symbol sym;
720 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000721 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000722 sym.scope = N_EXT;
723 sym.sect = 0;
724 sym.desc = 0;
725 sym.value = 0;
726 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
727 file.undefinedSymbols.push_back(sym);
728 }
729}
730
731const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
732 for (const Reference *ref : *lpAtom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000733 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000734 return ref->target();
735 }
736 }
737 return nullptr;
738}
739
740const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
741 for (const Reference *ref : *stubAtom) {
742 if (const Atom *ta = ref->target()) {
743 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
744 const Atom *target = targetOfLazyPointer(lpAtom);
745 if (target)
746 return target;
747 }
748 }
749 }
750 return nullptr;
751}
752
753
754void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
755 for (SectionInfo *si : _sectionInfos) {
756 Section &normSect = file.sections[si->normalizedSectionIndex];
757 switch (si->type) {
758 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
759 for (const AtomInfo &info : si->atomsAndOffsets) {
760 bool foundTarget = false;
761 for (const Reference *ref : *info.atom) {
762 const Atom *target = ref->target();
763 if (target) {
764 if (isa<const SharedLibraryAtom>(target)) {
765 uint32_t index = _atomToSymbolIndex[target];
766 normSect.indirectSymbols.push_back(index);
767 foundTarget = true;
768 } else {
769 normSect.indirectSymbols.push_back(
770 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
771 }
772 }
773 }
774 if (!foundTarget) {
775 normSect.indirectSymbols.push_back(
776 llvm::MachO::INDIRECT_SYMBOL_ABS);
777 }
778 }
779 break;
780 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
781 for (const AtomInfo &info : si->atomsAndOffsets) {
782 const Atom *target = targetOfLazyPointer(info.atom);
783 if (target) {
784 uint32_t index = _atomToSymbolIndex[target];
785 normSect.indirectSymbols.push_back(index);
786 }
787 }
788 break;
789 case llvm::MachO::S_SYMBOL_STUBS:
790 for (const AtomInfo &info : si->atomsAndOffsets) {
791 const Atom *target = targetOfStub(info.atom);
792 if (target) {
793 uint32_t index = _atomToSymbolIndex[target];
794 normSect.indirectSymbols.push_back(index);
795 }
796 }
797 break;
798 default:
799 break;
800 }
801 }
802
803}
804
805void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
806 // Scan all imported symbols and build up list of dylibs they are from.
807 int ordinal = 1;
808 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
809 StringRef loadPath = slAtom->loadName();
810 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
811 if (pos == _dylibInfo.end()) {
812 DylibInfo info;
813 info.ordinal = ordinal++;
814 info.hasWeak = slAtom->canBeNullAtRuntime();
815 info.hasNonWeak = !info.hasWeak;
816 _dylibInfo[loadPath] = info;
817 DependentDylib depInfo;
818 depInfo.path = loadPath;
819 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
820 nFile.dependentDylibs.push_back(depInfo);
821 } else {
822 if ( slAtom->canBeNullAtRuntime() )
823 pos->second.hasWeak = true;
824 else
825 pos->second.hasNonWeak = true;
826 }
827 }
828 // Automatically weak link dylib in which all symbols are weak (canBeNull).
829 for (DependentDylib &dep : nFile.dependentDylibs) {
830 DylibInfo &info = _dylibInfo[dep.path];
831 if (info.hasWeak && !info.hasNonWeak)
832 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
833 }
834}
835
836
837int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
838 return _dylibInfo[sa->loadName()].ordinal;
839}
840
841void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
842 uint64_t &segmentStartAddr) {
843 segmentIndex = 0;
844 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000845 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000846 && (seg->address+seg->size >= sect->address+sect->size)) {
847 segmentStartAddr = seg->address;
848 return;
849 }
850 ++segmentIndex;
851 }
852 llvm_unreachable("section not in any segment");
853}
854
855
Nick Kledzik2d432352014-07-17 23:16:21 +0000856uint32_t Util::sectionIndexForAtom(const Atom *atom) {
857 uint64_t address = _atomToAddress[atom];
858 uint32_t index = 1;
859 for (const SectionInfo *si : _sectionInfos) {
860 if ((si->address <= address) && (address < si->address+si->size))
861 return index;
862 ++index;
863 }
864 llvm_unreachable("atom not in any section");
Nick Kledzike34182f2013-11-06 21:36:55 +0000865}
866
867void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000868 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000869 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000870
Nick Kledzik2d432352014-07-17 23:16:21 +0000871
872 // Utility function for ArchHandler to find symbol index for an atom.
873 auto symIndexForAtom = [&] (const Atom &atom) -> uint32_t {
874 auto pos = _atomToSymbolIndex.find(&atom);
875 assert(pos != _atomToSymbolIndex.end());
876 return pos->second;
877 };
878
879 // Utility function for ArchHandler to find section index for an atom.
880 auto sectIndexForAtom = [&] (const Atom &atom) -> uint32_t {
881 return sectionIndexForAtom(&atom);
882 };
883
884 // Utility function for ArchHandler to find address of atom in output file.
885 auto addressForAtom = [&] (const Atom &atom) -> uint64_t {
886 auto pos = _atomToAddress.find(&atom);
887 assert(pos != _atomToAddress.end());
888 return pos->second;
889 };
890
Nick Kledzike34182f2013-11-06 21:36:55 +0000891 for (SectionInfo *si : _sectionInfos) {
892 Section &normSect = file.sections[si->normalizedSectionIndex];
893 for (const AtomInfo &info : si->atomsAndOffsets) {
894 const DefinedAtom *atom = info.atom;
895 for (const Reference *ref : *atom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000896 _archHandler.appendSectionRelocations(*atom, info.offsetInSection, *ref,
897 symIndexForAtom,
898 sectIndexForAtom,
899 addressForAtom,
900 normSect.relocations);
Nick Kledzike34182f2013-11-06 21:36:55 +0000901 }
902 }
903 }
904}
905
Nick Kledzik21921372014-07-24 23:06:56 +0000906void Util::buildDataInCodeArray(const lld::File &, NormalizedFile &file) {
907 for (SectionInfo *si : _sectionInfos) {
908 for (const AtomInfo &info : si->atomsAndOffsets) {
909 // Atoms that contain data-in-code have "transition" references
910 // which mark a point where the embedded data starts of ends.
911 // This needs to be converted to the mach-o format which is an array
912 // of data-in-code ranges.
913 uint32_t startOffset = 0;
914 DataRegionType mode = DataRegionType(0);
915 for (const Reference *ref : *info.atom) {
916 if (ref->kindNamespace() != Reference::KindNamespace::mach_o)
917 continue;
918 if (_archHandler.isDataInCodeTransition(ref->kindValue())) {
919 DataRegionType nextMode = (DataRegionType)ref->addend();
920 if (mode != nextMode) {
921 if (mode != 0) {
922 // Found end data range, so make range entry.
923 DataInCode entry;
924 entry.offset = si->address + info.offsetInSection + startOffset;
925 entry.length = ref->offsetInAtom() - startOffset;
926 entry.kind = mode;
927 file.dataInCode.push_back(entry);
928 }
929 }
930 mode = nextMode;
931 startOffset = ref->offsetInAtom();
932 }
933 }
934 if (mode != 0) {
935 // Function ends with data (no end transition).
936 DataInCode entry;
937 entry.offset = si->address + info.offsetInSection + startOffset;
938 entry.length = info.atom->size() - startOffset;
939 entry.kind = mode;
940 file.dataInCode.push_back(entry);
941 }
942 }
943 }
944}
945
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000946void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000947 NormalizedFile &nFile) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000948 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000949 return;
950
951 uint8_t segmentIndex;
952 uint64_t segmentStartAddr;
953 for (SectionInfo *sect : _sectionInfos) {
954 segIndexForSection(sect, segmentIndex, segmentStartAddr);
955 for (const AtomInfo &info : sect->atomsAndOffsets) {
956 const DefinedAtom *atom = info.atom;
957 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000958 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +0000959 - segmentStartAddr;
960 const Atom* targ = ref->target();
Nick Kledzik2d432352014-07-17 23:16:21 +0000961 if (_archHandler.isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000962 // A pointer to a DefinedAtom requires rebasing.
963 if (dyn_cast<DefinedAtom>(targ)) {
964 RebaseLocation rebase;
965 rebase.segIndex = segmentIndex;
966 rebase.segOffset = segmentOffset;
967 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
968 nFile.rebasingInfo.push_back(rebase);
969 }
970 // A pointer to an SharedLibraryAtom requires binding.
971 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
972 BindLocation bind;
973 bind.segIndex = segmentIndex;
974 bind.segOffset = segmentOffset;
975 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
976 bind.canBeNull = sa->canBeNullAtRuntime();
977 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000978 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000979 bind.addend = ref->addend();
980 nFile.bindingInfo.push_back(bind);
981 }
982 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000983 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000984 BindLocation bind;
985 bind.segIndex = segmentIndex;
986 bind.segOffset = segmentOffset;
987 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
988 bind.canBeNull = false; //sa->canBeNullAtRuntime();
Nick Kledzik2d432352014-07-17 23:16:21 +0000989 bind.ordinal = 1; // FIXME
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000990 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +0000991 bind.addend = ref->addend();
992 nFile.lazyBindingInfo.push_back(bind);
993 }
994 }
995 }
996 }
997}
998
999uint32_t Util::fileFlags() {
Nick Kledzike1aaced2014-07-22 00:49:49 +00001000 // FIXME: these need to determined at runtime.
1001 if (_context.outputMachOType() == MH_OBJECT) {
1002 return MH_SUBSECTIONS_VIA_SYMBOLS;
1003 } else {
1004 return MH_DYLDLINK | MH_NOUNDEFS | MH_TWOLEVEL;
1005 }
Nick Kledzike34182f2013-11-06 21:36:55 +00001006}
1007
1008} // end anonymous namespace
1009
1010
1011namespace lld {
1012namespace mach_o {
1013namespace normalized {
1014
1015/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001016ErrorOr<std::unique_ptr<NormalizedFile>>
1017normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +00001018 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001019 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +00001020 Util util(context);
1021 util.assignAtomsToSections(atomFile);
1022 util.organizeSections();
1023 util.assignAddressesToSections();
1024 util.buildAtomToAddressMap();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001025
Nick Kledzike34182f2013-11-06 21:36:55 +00001026 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
1027 NormalizedFile &normFile = *f.get();
1028 f->arch = context.arch();
Tim Northoverd30a1f22014-06-20 15:59:00 +00001029 f->fileType = context.outputMachOType();
Nick Kledzike34182f2013-11-06 21:36:55 +00001030 f->flags = util.fileFlags();
Tim Northover301c4e62014-07-01 08:15:41 +00001031 f->installName = context.installName();
Nick Kledzike34182f2013-11-06 21:36:55 +00001032 util.copySegmentInfo(normFile);
1033 util.copySections(normFile);
1034 util.addDependentDylibs(atomFile, normFile);
1035 util.addSymbols(atomFile, normFile);
1036 util.addIndirectSymbols(atomFile, normFile);
1037 util.addRebaseAndBindingInfo(atomFile, normFile);
1038 util.addSectionRelocs(atomFile, normFile);
Nick Kledzik21921372014-07-24 23:06:56 +00001039 util.buildDataInCodeArray(atomFile, normFile);
Nick Kledzike34182f2013-11-06 21:36:55 +00001040 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001041
Nick Kledzike34182f2013-11-06 21:36:55 +00001042 return std::move(f);
1043}
1044
1045
1046} // namespace normalized
1047} // namespace mach_o
1048} // namespace lld
1049