blob: efb9d9c6c8d0baec5c4205d5d6f681cde45fa4dc [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 {
Nick Kledzik2fcbe822014-07-30 00:58:06 +000054 SectionInfo(StringRef seg, StringRef sect, SectionType type,
55 const MachOLinkingContext &ctxt, uint32_t attr=0);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000056
Nick Kledzike34182f2013-11-06 21:36:55 +000057 StringRef segmentName;
58 StringRef sectionName;
59 SectionType type;
60 uint32_t attributes;
61 uint64_t address;
62 uint64_t size;
63 uint32_t alignment;
64 std::vector<AtomInfo> atomsAndOffsets;
65 uint32_t normalizedSectionIndex;
66 uint32_t finalSectionIndex;
67};
68
Nick Kledzik2fcbe822014-07-30 00:58:06 +000069SectionInfo::SectionInfo(StringRef sg, StringRef sct, SectionType t,
70 const MachOLinkingContext &ctxt, uint32_t attrs)
71 : segmentName(sg), sectionName(sct), type(t), attributes(attrs),
Shankar Easwaran3d8de472014-01-27 03:09:26 +000072 address(0), size(0), alignment(0),
Nick Kledzike34182f2013-11-06 21:36:55 +000073 normalizedSectionIndex(0), finalSectionIndex(0) {
Nick Kledzik2fcbe822014-07-30 00:58:06 +000074 uint8_t align;
75 if (ctxt.sectionAligned(segmentName, sectionName, align)) {
76 alignment = align;
77 }
Nick Kledzike34182f2013-11-06 21:36:55 +000078}
79
80struct SegmentInfo {
81 SegmentInfo(StringRef name);
Shankar Easwaran3d8de472014-01-27 03:09:26 +000082
Nick Kledzike34182f2013-11-06 21:36:55 +000083 StringRef name;
84 uint64_t address;
85 uint64_t size;
86 uint32_t access;
87 std::vector<SectionInfo*> sections;
Nick Kledzik2fcbe822014-07-30 00:58:06 +000088 uint32_t normalizedSegmentIndex;
Nick Kledzike34182f2013-11-06 21:36:55 +000089};
90
Shankar Easwaran3d8de472014-01-27 03:09:26 +000091SegmentInfo::SegmentInfo(StringRef n)
Nick Kledzik2fcbe822014-07-30 00:58:06 +000092 : name(n), address(0), size(0), access(0), normalizedSegmentIndex(0) {
Nick Kledzike34182f2013-11-06 21:36:55 +000093}
94
95
96class Util {
97public:
Nick Kledzik2d432352014-07-17 23:16:21 +000098 Util(const MachOLinkingContext &ctxt) : _context(ctxt),
99 _archHandler(ctxt.archHandler()), _entryAtom(nullptr) {}
Nick Kledzike34182f2013-11-06 21:36:55 +0000100
101 void assignAtomsToSections(const lld::File &atomFile);
102 void organizeSections();
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000103 void assignAddressesToSections(const NormalizedFile &file);
Nick Kledzike34182f2013-11-06 21:36:55 +0000104 uint32_t fileFlags();
105 void copySegmentInfo(NormalizedFile &file);
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000106 void copySectionInfo(NormalizedFile &file);
107 void updateSectionInfo(NormalizedFile &file);
Nick Kledzike34182f2013-11-06 21:36:55 +0000108 void buildAtomToAddressMap();
109 void addSymbols(const lld::File &atomFile, NormalizedFile &file);
110 void addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file);
111 void addRebaseAndBindingInfo(const lld::File &, NormalizedFile &file);
112 void addSectionRelocs(const lld::File &, NormalizedFile &file);
Nick Kledzik21921372014-07-24 23:06:56 +0000113 void buildDataInCodeArray(const lld::File &, NormalizedFile &file);
Nick Kledzike34182f2013-11-06 21:36:55 +0000114 void addDependentDylibs(const lld::File &, NormalizedFile &file);
115 void copyEntryPointAddress(NormalizedFile &file);
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000116 void copySectionContent(NormalizedFile &file);
Nick Kledzike34182f2013-11-06 21:36:55 +0000117
118private:
119 typedef std::map<DefinedAtom::ContentType, SectionInfo*> TypeToSection;
120 typedef llvm::DenseMap<const Atom*, uint64_t> AtomToAddress;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000121
Nick Kledzike34182f2013-11-06 21:36:55 +0000122 struct DylibInfo { int ordinal; bool hasWeak; bool hasNonWeak; };
123 typedef llvm::StringMap<DylibInfo> DylibPathToInfo;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000124
Nick Kledzike34182f2013-11-06 21:36:55 +0000125 SectionInfo *sectionForAtom(const DefinedAtom*);
Nick Kledzik936d5202014-06-11 01:30:55 +0000126 SectionInfo *getRelocatableSection(DefinedAtom::ContentType type);
127 SectionInfo *getFinalSection(DefinedAtom::ContentType type);
Nick Kledzike34182f2013-11-06 21:36:55 +0000128 void appendAtom(SectionInfo *sect, const DefinedAtom *atom);
129 SegmentInfo *segmentForName(StringRef segName);
130 void layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr);
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000131 void layoutSectionsInTextSegment(size_t, SegmentInfo *, uint64_t &);
Nick Kledzike34182f2013-11-06 21:36:55 +0000132 void copySectionContent(SectionInfo *si, ContentBytes &content);
133 uint8_t scopeBits(const DefinedAtom* atom);
Nick Kledzik60855392014-06-11 00:24:16 +0000134 uint16_t descBits(const DefinedAtom* atom);
Nick Kledzike34182f2013-11-06 21:36:55 +0000135 int dylibOrdinal(const SharedLibraryAtom *sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000136 void segIndexForSection(const SectionInfo *sect,
Nick Kledzike34182f2013-11-06 21:36:55 +0000137 uint8_t &segmentIndex, uint64_t &segmentStartAddr);
138 const Atom *targetOfLazyPointer(const DefinedAtom *lpAtom);
139 const Atom *targetOfStub(const DefinedAtom *stubAtom);
140 bool belongsInGlobalSymbolsSection(const DefinedAtom* atom);
141 void appendSection(SectionInfo *si, NormalizedFile &file);
Nick Kledzik2d432352014-07-17 23:16:21 +0000142 uint32_t sectionIndexForAtom(const Atom *atom);
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000143
Nick Kledzike34182f2013-11-06 21:36:55 +0000144 static uint64_t alignTo(uint64_t value, uint8_t align2);
145 typedef llvm::DenseMap<const Atom*, uint32_t> AtomToIndex;
146 struct AtomAndIndex { const Atom *atom; uint32_t index; };
Joey Gouly9d263e02013-12-25 19:39:08 +0000147 struct AtomSorter {
148 bool operator()(const AtomAndIndex &left, const AtomAndIndex &right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000149 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000150 struct SegmentSorter {
151 bool operator()(const SegmentInfo *left, const SegmentInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000152 static unsigned weight(const SegmentInfo *);
153 };
Joey Gouly9d263e02013-12-25 19:39:08 +0000154 struct TextSectionSorter {
155 bool operator()(const SectionInfo *left, const SectionInfo *right);
Nick Kledzike34182f2013-11-06 21:36:55 +0000156 static unsigned weight(const SectionInfo *);
157 };
158
159 const MachOLinkingContext &_context;
Nick Kledzik2d432352014-07-17 23:16:21 +0000160 mach_o::ArchHandler &_archHandler;
Nick Kledzike34182f2013-11-06 21:36:55 +0000161 llvm::BumpPtrAllocator _allocator;
162 std::vector<SectionInfo*> _sectionInfos;
163 std::vector<SegmentInfo*> _segmentInfos;
164 TypeToSection _sectionMap;
Nick Kledzikacfad802014-05-30 22:51:04 +0000165 std::vector<SectionInfo*> _customSections;
Nick Kledzike34182f2013-11-06 21:36:55 +0000166 AtomToAddress _atomToAddress;
167 DylibPathToInfo _dylibInfo;
168 const DefinedAtom *_entryAtom;
169 AtomToIndex _atomToSymbolIndex;
170};
171
Nick Kledzikec140832014-06-10 01:50:00 +0000172
Nick Kledzik936d5202014-06-11 01:30:55 +0000173SectionInfo *Util::getRelocatableSection(DefinedAtom::ContentType type) {
Nick Kledzikec140832014-06-10 01:50:00 +0000174 StringRef segmentName;
175 StringRef sectionName;
176 SectionType sectionType;
177 SectionAttr sectionAttrs;
178
179 // Use same table used by when parsing .o files.
180 relocatableSectionInfoForContentType(type, segmentName, sectionName,
181 sectionType, sectionAttrs);
182 // If we already have a SectionInfo with this name, re-use it.
183 // This can happen if two ContentType map to the same mach-o section.
184 for (auto sect : _sectionMap) {
185 if (sect.second->sectionName.equals(sectionName) &&
186 sect.second->segmentName.equals(segmentName)) {
187 return sect.second;
188 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000189 }
Nick Kledzikec140832014-06-10 01:50:00 +0000190 // Otherwise allocate new SectionInfo object.
Nick Kledzik936d5202014-06-11 01:30:55 +0000191 SectionInfo *sect = new (_allocator) SectionInfo(segmentName, sectionName,
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000192 sectionType, _context,
193 sectionAttrs);
Nick Kledzik936d5202014-06-11 01:30:55 +0000194 _sectionInfos.push_back(sect);
195 _sectionMap[type] = sect;
196 return sect;
Nick Kledzikec140832014-06-10 01:50:00 +0000197}
198
199#define ENTRY(seg, sect, type, atomType) \
200 {seg, sect, type, DefinedAtom::atomType }
201
202struct MachOFinalSectionFromAtomType {
203 StringRef segmentName;
204 StringRef sectionName;
205 SectionType sectionType;
206 DefinedAtom::ContentType atomType;
207};
208
209const MachOFinalSectionFromAtomType sectsToAtomType[] = {
210 ENTRY("__TEXT", "__text", S_REGULAR, typeCode),
211 ENTRY("__TEXT", "__cstring", S_CSTRING_LITERALS, typeCString),
212 ENTRY("__TEXT", "__ustring", S_REGULAR, typeUTF16String),
213 ENTRY("__TEXT", "__const", S_REGULAR, typeConstant),
214 ENTRY("__TEXT", "__const", S_4BYTE_LITERALS, typeLiteral4),
215 ENTRY("__TEXT", "__const", S_8BYTE_LITERALS, typeLiteral8),
216 ENTRY("__TEXT", "__const", S_16BYTE_LITERALS, typeLiteral16),
217 ENTRY("__TEXT", "__stubs", S_SYMBOL_STUBS, typeStub),
218 ENTRY("__TEXT", "__stub_helper", S_REGULAR, typeStubHelper),
219 ENTRY("__TEXT", "__gcc_except_tab", S_REGULAR, typeLSDA),
220 ENTRY("__TEXT", "__eh_frame", S_COALESCED, typeCFI),
221 ENTRY("__DATA", "__data", S_REGULAR, typeData),
222 ENTRY("__DATA", "__const", S_REGULAR, typeConstData),
223 ENTRY("__DATA", "__cfstring", S_REGULAR, typeCFString),
224 ENTRY("__DATA", "__la_symbol_ptr", S_LAZY_SYMBOL_POINTERS,
225 typeLazyPointer),
226 ENTRY("__DATA", "__mod_init_func", S_MOD_INIT_FUNC_POINTERS,
227 typeInitializerPtr),
228 ENTRY("__DATA", "__mod_term_func", S_MOD_TERM_FUNC_POINTERS,
229 typeTerminatorPtr),
230 ENTRY("__DATA", "___got", S_NON_LAZY_SYMBOL_POINTERS,
231 typeGOT),
Tim Northover9ee99352014-06-30 09:49:37 +0000232 ENTRY("__DATA", "___bss", S_ZEROFILL, typeZeroFill),
233
234 // FIXME: __compact_unwind actually needs to be processed by a pass and put
235 // into __TEXT,__unwind_info. For now, forwarding it back to
236 // __LD,__compact_unwind is harmless (it's ignored by the unwinder, which then
237 // proceeds to process __TEXT,__eh_frame for its instructions).
238 ENTRY("__LD", "__compact_unwind", S_REGULAR, typeCompactUnwindInfo),
Nick Kledzikec140832014-06-10 01:50:00 +0000239};
240#undef ENTRY
241
242
Nick Kledzik936d5202014-06-11 01:30:55 +0000243SectionInfo *Util::getFinalSection(DefinedAtom::ContentType atomType) {
Tim Northoverb5bf6862014-06-30 10:30:00 +0000244 for (auto &p : sectsToAtomType) {
245 if (p.atomType != atomType)
Nick Kledzikec140832014-06-10 01:50:00 +0000246 continue;
247 SectionAttr sectionAttrs = 0;
248 switch (atomType) {
249 case DefinedAtom::typeCode:
250 case DefinedAtom::typeStub:
251 sectionAttrs = S_ATTR_PURE_INSTRUCTIONS;
252 break;
253 default:
254 break;
255 }
256 // If we already have a SectionInfo with this name, re-use it.
257 // This can happen if two ContentType map to the same mach-o section.
258 for (auto sect : _sectionMap) {
Tim Northoverb5bf6862014-06-30 10:30:00 +0000259 if (sect.second->sectionName.equals(p.sectionName) &&
260 sect.second->segmentName.equals(p.segmentName)) {
Nick Kledzikec140832014-06-10 01:50:00 +0000261 return sect.second;
262 }
263 }
264 // Otherwise allocate new SectionInfo object.
Tim Northoverb5bf6862014-06-30 10:30:00 +0000265 SectionInfo *sect = new (_allocator) SectionInfo(p.segmentName,
266 p.sectionName,
267 p.sectionType,
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000268 _context,
Nick Kledzik936d5202014-06-11 01:30:55 +0000269 sectionAttrs);
270 _sectionInfos.push_back(sect);
271 _sectionMap[atomType] = sect;
272 return sect;
Nick Kledzikec140832014-06-10 01:50:00 +0000273 }
274 llvm_unreachable("content type not yet supported");
Nick Kledzike34182f2013-11-06 21:36:55 +0000275}
276
277
278
279SectionInfo *Util::sectionForAtom(const DefinedAtom *atom) {
Nick Kledzikacfad802014-05-30 22:51:04 +0000280 if (atom->sectionChoice() == DefinedAtom::sectionBasedOnContent) {
281 // Section for this atom is derived from content type.
282 DefinedAtom::ContentType type = atom->contentType();
283 auto pos = _sectionMap.find(type);
284 if ( pos != _sectionMap.end() )
285 return pos->second;
Tim Northoverd30a1f22014-06-20 15:59:00 +0000286 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzik936d5202014-06-11 01:30:55 +0000287 return rMode ? getRelocatableSection(type) : getFinalSection(type);
Nick Kledzikacfad802014-05-30 22:51:04 +0000288 } else {
289 // This atom needs to be in a custom section.
290 StringRef customName = atom->customSectionName();
291 // Look to see if we have already allocated the needed custom section.
292 for(SectionInfo *sect : _customSections) {
293 const DefinedAtom *firstAtom = sect->atomsAndOffsets.front().atom;
294 if (firstAtom->customSectionName().equals(customName)) {
295 return sect;
296 }
297 }
298 // Not found, so need to create a new custom section.
299 size_t seperatorIndex = customName.find('/');
300 assert(seperatorIndex != StringRef::npos);
Tim Northover7b0a1302014-06-30 09:49:33 +0000301 StringRef segName = customName.slice(0, seperatorIndex);
302 StringRef sectName = customName.drop_front(seperatorIndex + 1);
Nick Kledzikacfad802014-05-30 22:51:04 +0000303 SectionInfo *sect = new (_allocator) SectionInfo(segName, sectName,
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000304 S_REGULAR, _context);
Nick Kledzikacfad802014-05-30 22:51:04 +0000305 _customSections.push_back(sect);
Tim Northover7b0a1302014-06-30 09:49:33 +0000306 _sectionInfos.push_back(sect);
Nick Kledzikacfad802014-05-30 22:51:04 +0000307 return sect;
308 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000309}
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000310
Nick Kledzike34182f2013-11-06 21:36:55 +0000311
312void Util::appendAtom(SectionInfo *sect, const DefinedAtom *atom) {
313 // Figure out offset for atom in this section given alignment constraints.
314 uint64_t offset = sect->size;
315 DefinedAtom::Alignment atomAlign = atom->alignment();
316 uint64_t align2 = 1 << atomAlign.powerOf2;
317 uint64_t requiredModulus = atomAlign.modulus;
318 uint64_t currentModulus = (offset % align2);
319 if ( currentModulus != requiredModulus ) {
320 if ( requiredModulus > currentModulus )
321 offset += requiredModulus-currentModulus;
322 else
323 offset += align2+requiredModulus-currentModulus;
324 }
325 // Record max alignment of any atom in this section.
326 if ( atomAlign.powerOf2 > sect->alignment )
327 sect->alignment = atomAlign.powerOf2;
328 // Assign atom to this section with this offset.
329 AtomInfo ai = {atom, offset};
330 sect->atomsAndOffsets.push_back(ai);
331 // Update section size to include this atom.
332 sect->size = offset + atom->size();
333}
334
335void Util::assignAtomsToSections(const lld::File &atomFile) {
336 for (const DefinedAtom *atom : atomFile.defined()) {
337 appendAtom(sectionForAtom(atom), atom);
338 }
339}
340
341SegmentInfo *Util::segmentForName(StringRef segName) {
342 for (SegmentInfo *si : _segmentInfos) {
343 if ( si->name.equals(segName) )
344 return si;
345 }
346 SegmentInfo *info = new (_allocator) SegmentInfo(segName);
347 if (segName.equals("__TEXT"))
348 info->access = VM_PROT_READ | VM_PROT_EXECUTE;
349 else if (segName.equals("__DATA"))
350 info->access = VM_PROT_READ | VM_PROT_WRITE;
351 else if (segName.equals("__PAGEZERO"))
352 info->access = 0;
353 _segmentInfos.push_back(info);
354 return info;
355}
356
357unsigned Util::SegmentSorter::weight(const SegmentInfo *seg) {
358 return llvm::StringSwitch<unsigned>(seg->name)
359 .Case("__PAGEZERO", 1)
360 .Case("__TEXT", 2)
361 .Case("__DATA", 3)
362 .Default(100);
363}
364
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000365bool Util::SegmentSorter::operator()(const SegmentInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000366 const SegmentInfo *right) {
367 return (weight(left) < weight(right));
368}
369
370unsigned Util::TextSectionSorter::weight(const SectionInfo *sect) {
371 return llvm::StringSwitch<unsigned>(sect->sectionName)
372 .Case("__text", 1)
373 .Case("__stubs", 2)
374 .Case("__stub_helper", 3)
375 .Case("__const", 4)
376 .Case("__cstring", 5)
377 .Case("__unwind_info", 98)
378 .Case("__eh_frame", 99)
379 .Default(10);
380}
381
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000382bool Util::TextSectionSorter::operator()(const SectionInfo *left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000383 const SectionInfo *right) {
384 return (weight(left) < weight(right));
385}
386
387
388void Util::organizeSections() {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000389 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000390 // Leave sections ordered as normalized file specified.
391 uint32_t sectionIndex = 1;
392 for (SectionInfo *si : _sectionInfos) {
393 si->finalSectionIndex = sectionIndex++;
394 }
395 } else {
396 // Main executables, need a zero-page segment
Tim Northoverd30a1f22014-06-20 15:59:00 +0000397 if (_context.outputMachOType() == llvm::MachO::MH_EXECUTE)
Nick Kledzike34182f2013-11-06 21:36:55 +0000398 segmentForName("__PAGEZERO");
399 // Group sections into segments.
400 for (SectionInfo *si : _sectionInfos) {
401 SegmentInfo *seg = segmentForName(si->segmentName);
402 seg->sections.push_back(si);
403 }
404 // Sort segments.
405 std::sort(_segmentInfos.begin(), _segmentInfos.end(), SegmentSorter());
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000406
Nick Kledzike34182f2013-11-06 21:36:55 +0000407 // Sort sections within segments.
408 for (SegmentInfo *seg : _segmentInfos) {
409 if (seg->name.equals("__TEXT")) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000410 std::sort(seg->sections.begin(), seg->sections.end(),
Nick Kledzike34182f2013-11-06 21:36:55 +0000411 TextSectionSorter());
412 }
413 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000414
Nick Kledzike34182f2013-11-06 21:36:55 +0000415 // Record final section indexes.
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000416 uint32_t segmentIndex = 0;
Nick Kledzike34182f2013-11-06 21:36:55 +0000417 uint32_t sectionIndex = 1;
418 for (SegmentInfo *seg : _segmentInfos) {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000419 seg->normalizedSegmentIndex = segmentIndex++;
420 for (SectionInfo *sect : seg->sections) {
421 sect->finalSectionIndex = sectionIndex++;
422 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000423 }
424 }
425
426}
427
428uint64_t Util::alignTo(uint64_t value, uint8_t align2) {
429 return llvm::RoundUpToAlignment(value, 1 << align2);
430}
431
432
433void Util::layoutSectionsInSegment(SegmentInfo *seg, uint64_t &addr) {
434 seg->address = addr;
435 for (SectionInfo *sect : seg->sections) {
436 sect->address = alignTo(addr, sect->alignment);
437 addr += sect->size;
438 }
439 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
440}
441
442
443// __TEXT segment lays out backwards so padding is at front after load commands.
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000444void Util::layoutSectionsInTextSegment(size_t hlcSize, SegmentInfo *seg,
445 uint64_t &addr) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000446 seg->address = addr;
447 // Walks sections starting at end to calculate padding for start.
448 int64_t taddr = 0;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000449 for (auto it = seg->sections.rbegin(); it != seg->sections.rend(); ++it) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000450 SectionInfo *sect = *it;
451 taddr -= sect->size;
452 taddr = taddr & (0 - (1 << sect->alignment));
453 }
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000454 int64_t padding = taddr - hlcSize;
Nick Kledzike34182f2013-11-06 21:36:55 +0000455 while (padding < 0)
456 padding += _context.pageSize();
457 // Start assigning section address starting at padded offset.
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000458 addr += (padding + hlcSize);
Nick Kledzike34182f2013-11-06 21:36:55 +0000459 for (SectionInfo *sect : seg->sections) {
460 sect->address = alignTo(addr, sect->alignment);
461 addr = sect->address + sect->size;
462 }
463 seg->size = llvm::RoundUpToAlignment(addr - seg->address,_context.pageSize());
464}
465
466
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000467void Util::assignAddressesToSections(const NormalizedFile &file) {
468 size_t hlcSize = headerAndLoadCommandsSize(file);
Nick Kledzike34182f2013-11-06 21:36:55 +0000469 uint64_t address = 0; // FIXME
Tim Northoverd30a1f22014-06-20 15:59:00 +0000470 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000471 for (SegmentInfo *seg : _segmentInfos) {
472 if (seg->name.equals("__PAGEZERO")) {
473 seg->size = _context.pageZeroSize();
474 address += seg->size;
475 }
476 else if (seg->name.equals("__TEXT"))
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000477 layoutSectionsInTextSegment(hlcSize, seg, address);
Nick Kledzike34182f2013-11-06 21:36:55 +0000478 else
479 layoutSectionsInSegment(seg, address);
Tim Northover7b0a1302014-06-30 09:49:33 +0000480
481 address = llvm::RoundUpToAlignment(address, _context.pageSize());
Nick Kledzike34182f2013-11-06 21:36:55 +0000482 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000483 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000484 llvm::dbgs() << "assignAddressesToSections()\n";
485 for (SegmentInfo *sgi : _segmentInfos) {
486 llvm::dbgs() << " address=" << llvm::format("0x%08llX", sgi->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000487 << ", size=" << llvm::format("0x%08llX", sgi->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000488 << ", segment-name='" << sgi->name
Nick Kledzik020a49c2013-11-06 21:57:52 +0000489 << "'\n";
490 for (SectionInfo *si : sgi->sections) {
491 llvm::dbgs()<< " addr=" << llvm::format("0x%08llX", si->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000492 << ", size=" << llvm::format("0x%08llX", si->size)
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000493 << ", section-name='" << si->sectionName
Nick Kledzik020a49c2013-11-06 21:57:52 +0000494 << "\n";
495 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000496 }
Nick Kledzik020a49c2013-11-06 21:57:52 +0000497 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000498 } else {
499 for (SectionInfo *sect : _sectionInfos) {
500 sect->address = alignTo(address, sect->alignment);
501 address = sect->address + sect->size;
502 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000503 DEBUG_WITH_TYPE("WriterMachO-norm",
Nick Kledzik020a49c2013-11-06 21:57:52 +0000504 llvm::dbgs() << "assignAddressesToSections()\n";
505 for (SectionInfo *si : _sectionInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000506 llvm::dbgs() << " section=" << si->sectionName
Nick Kledzike34182f2013-11-06 21:36:55 +0000507 << " address= " << llvm::format("0x%08X", si->address)
508 << " size= " << llvm::format("0x%08X", si->size)
Nick Kledzik020a49c2013-11-06 21:57:52 +0000509 << "\n";
510 }
511 );
Nick Kledzike34182f2013-11-06 21:36:55 +0000512 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000513}
514
515
516void Util::copySegmentInfo(NormalizedFile &file) {
517 for (SegmentInfo *sgi : _segmentInfos) {
518 Segment seg;
519 seg.name = sgi->name;
520 seg.address = sgi->address;
521 seg.size = sgi->size;
522 seg.access = sgi->access;
523 file.segments.push_back(seg);
524 }
525}
526
527void Util::appendSection(SectionInfo *si, NormalizedFile &file) {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000528 // Add new empty section to end of file.sections.
Nick Kledzike34182f2013-11-06 21:36:55 +0000529 Section temp;
530 file.sections.push_back(std::move(temp));
531 Section* normSect = &file.sections.back();
532 // Copy fields to normalized section.
533 normSect->segmentName = si->segmentName;
534 normSect->sectionName = si->sectionName;
535 normSect->type = si->type;
536 normSect->attributes = si->attributes;
537 normSect->address = si->address;
538 normSect->alignment = si->alignment;
539 // Record where normalized section is.
540 si->normalizedSectionIndex = file.sections.size()-1;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000541}
542
543void Util::copySectionContent(NormalizedFile &file) {
544 const bool r = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
545
546 // Utility function for ArchHandler to find address of atom in output file.
547 auto addrForAtom = [&] (const Atom &atom) -> uint64_t {
548 auto pos = _atomToAddress.find(&atom);
549 assert(pos != _atomToAddress.end());
550 return pos->second;
551 };
552
553 for (SectionInfo *si : _sectionInfos) {
554 if (si->type == llvm::MachO::S_ZEROFILL)
555 continue;
556 // Copy content from atoms to content buffer for section.
557 uint8_t *sectionContent = file.ownedAllocations.Allocate<uint8_t>(si->size);
558 Section *normSect = &file.sections[si->normalizedSectionIndex];
559 normSect->content = llvm::makeArrayRef(sectionContent, si->size);
560 for (AtomInfo &ai : si->atomsAndOffsets) {
561 uint8_t *atomContent = reinterpret_cast<uint8_t*>
Nick Kledzike34182f2013-11-06 21:36:55 +0000562 (&sectionContent[ai.offsetInSection]);
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000563 _archHandler.generateAtomContent(*ai.atom, r, addrForAtom, atomContent);
564 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000565 }
566}
567
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000568
569void Util::copySectionInfo(NormalizedFile &file) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000570 file.sections.reserve(_sectionInfos.size());
571 // For final linked images, write sections grouped by segment.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000572 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000573 for (SegmentInfo *sgi : _segmentInfos) {
574 for (SectionInfo *si : sgi->sections) {
575 appendSection(si, file);
576 }
577 }
578 } else {
579 // Object files write sections in default order.
580 for (SectionInfo *si : _sectionInfos) {
581 appendSection(si, file);
582 }
583 }
584}
585
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000586void Util::updateSectionInfo(NormalizedFile &file) {
587 file.sections.reserve(_sectionInfos.size());
588 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT) {
589 // For final linked images, sections grouped by segment.
590 for (SegmentInfo *sgi : _segmentInfos) {
591 Segment *normSeg = &file.segments[sgi->normalizedSegmentIndex];
592 normSeg->address = sgi->address;
593 normSeg->size = sgi->size;
594 for (SectionInfo *si : sgi->sections) {
595 Section *normSect = &file.sections[si->normalizedSectionIndex];
596 normSect->address = si->address;
597 }
598 }
599 } else {
600 // Object files write sections in default order.
601 for (SectionInfo *si : _sectionInfos) {
602 Section *normSect = &file.sections[si->normalizedSectionIndex];
603 normSect->address = si->address;
604 }
605 }
606}
607
Nick Kledzike34182f2013-11-06 21:36:55 +0000608void Util::copyEntryPointAddress(NormalizedFile &nFile) {
609 if (_context.outputTypeHasEntry()) {
Nick Kledzik54fd4e52014-07-28 23:06:09 +0000610 if (_archHandler.isThumbFunction(*_entryAtom))
611 nFile.entryAddress = (_atomToAddress[_entryAtom] | 1);
612 else
613 nFile.entryAddress = _atomToAddress[_entryAtom];
Nick Kledzike34182f2013-11-06 21:36:55 +0000614 }
615}
616
617void Util::buildAtomToAddressMap() {
618 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
619 << "assign atom addresses:\n");
620 const bool lookForEntry = _context.outputTypeHasEntry();
621 for (SectionInfo *sect : _sectionInfos) {
622 for (const AtomInfo &info : sect->atomsAndOffsets) {
623 _atomToAddress[info.atom] = sect->address + info.offsetInSection;
624 if (lookForEntry && (info.atom->contentType() == DefinedAtom::typeCode) &&
625 (info.atom->size() != 0) &&
626 info.atom->name() == _context.entrySymbolName()) {
627 _entryAtom = info.atom;
628 }
629 DEBUG_WITH_TYPE("WriterMachO-address", llvm::dbgs()
630 << " address="
631 << llvm::format("0x%016X", _atomToAddress[info.atom])
632 << " atom=" << info.atom
633 << " name=" << info.atom->name() << "\n");
634 }
635 }
636}
637
638uint8_t Util::scopeBits(const DefinedAtom* atom) {
639 switch (atom->scope()) {
640 case Atom::scopeTranslationUnit:
641 return 0;
642 case Atom::scopeLinkageUnit:
643 return N_PEXT | N_EXT;
644 case Atom::scopeGlobal:
645 return N_EXT;
646 }
Nick Kledzik020fa7f2013-11-06 22:18:09 +0000647 llvm_unreachable("Unknown scope");
Nick Kledzike34182f2013-11-06 21:36:55 +0000648}
649
Nick Kledzik60855392014-06-11 00:24:16 +0000650uint16_t Util::descBits(const DefinedAtom* atom) {
651 uint16_t desc = 0;
652 switch (atom->merge()) {
653 case lld::DefinedAtom::mergeNo:
654 case lld::DefinedAtom::mergeAsTentative:
655 break;
656 case lld::DefinedAtom::mergeAsWeak:
657 case lld::DefinedAtom::mergeAsWeakAndAddressUsed:
658 desc |= N_WEAK_DEF;
659 break;
660 case lld::DefinedAtom::mergeSameNameAndSize:
661 case lld::DefinedAtom::mergeByLargestSection:
662 case lld::DefinedAtom::mergeByContent:
663 llvm_unreachable("Unsupported DefinedAtom::merge()");
664 break;
665 }
666 if (atom->contentType() == lld::DefinedAtom::typeResolver)
667 desc |= N_SYMBOL_RESOLVER;
Nick Kledzik7e9808f2014-07-23 00:51:37 +0000668 if (_archHandler.isThumbFunction(*atom))
669 desc |= N_ARM_THUMB_DEF;
Nick Kledzik60855392014-06-11 00:24:16 +0000670 return desc;
671}
672
673
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000674bool Util::AtomSorter::operator()(const AtomAndIndex &left,
Nick Kledzike34182f2013-11-06 21:36:55 +0000675 const AtomAndIndex &right) {
676 return (left.atom->name().compare(right.atom->name()) < 0);
677}
678
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000679
Nick Kledzike34182f2013-11-06 21:36:55 +0000680bool Util::belongsInGlobalSymbolsSection(const DefinedAtom* atom) {
Nick Kledzik936d5202014-06-11 01:30:55 +0000681 // ScopeLinkageUnit symbols are in globals area of symbol table
682 // in object files, but in locals area for final linked images.
Tim Northoverd30a1f22014-06-20 15:59:00 +0000683 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzik936d5202014-06-11 01:30:55 +0000684 return (atom->scope() != Atom::scopeTranslationUnit);
685 else
686 return (atom->scope() == Atom::scopeGlobal);
Nick Kledzike34182f2013-11-06 21:36:55 +0000687}
688
689void Util::addSymbols(const lld::File &atomFile, NormalizedFile &file) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000690 bool rMode = (_context.outputMachOType() == llvm::MachO::MH_OBJECT);
Nick Kledzike34182f2013-11-06 21:36:55 +0000691 // Mach-O symbol table has three regions: locals, globals, undefs.
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000692
Nick Kledzike34182f2013-11-06 21:36:55 +0000693 // Add all local (non-global) symbols in address order
694 std::vector<AtomAndIndex> globals;
695 globals.reserve(512);
696 for (SectionInfo *sect : _sectionInfos) {
697 for (const AtomInfo &info : sect->atomsAndOffsets) {
698 const DefinedAtom *atom = info.atom;
699 if (!atom->name().empty()) {
700 if (belongsInGlobalSymbolsSection(atom)) {
701 AtomAndIndex ai = { atom, sect->finalSectionIndex };
702 globals.push_back(ai);
703 } else {
704 Symbol sym;
705 sym.name = atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000706 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000707 sym.scope = scopeBits(atom);
708 sym.sect = sect->finalSectionIndex;
Nick Kledzik7e9808f2014-07-23 00:51:37 +0000709 sym.desc = descBits(atom);
Nick Kledzike34182f2013-11-06 21:36:55 +0000710 sym.value = _atomToAddress[atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000711 _atomToSymbolIndex[atom] = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000712 file.localSymbols.push_back(sym);
713 }
Nick Kledzik2d432352014-07-17 23:16:21 +0000714 } else if (rMode && _archHandler.needsLocalSymbolInRelocatableFile(atom)){
715 // Create 'Lxxx' labels for anonymous atoms if archHandler says so.
716 static unsigned tempNum = 1;
717 char tmpName[16];
718 sprintf(tmpName, "L%04u", tempNum++);
719 StringRef tempRef(tmpName);
720 Symbol sym;
721 sym.name = tempRef.copy(file.ownedAllocations);
722 sym.type = N_SECT;
723 sym.scope = 0;
724 sym.sect = sect->finalSectionIndex;
725 sym.desc = 0;
726 sym.value = _atomToAddress[atom];
727 _atomToSymbolIndex[atom] = file.localSymbols.size();
728 file.localSymbols.push_back(sym);
Nick Kledzike34182f2013-11-06 21:36:55 +0000729 }
730 }
731 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000732
Nick Kledzike34182f2013-11-06 21:36:55 +0000733 // Sort global symbol alphabetically, then add to symbol table.
734 std::sort(globals.begin(), globals.end(), AtomSorter());
Nick Kledzik2d432352014-07-17 23:16:21 +0000735 const uint32_t globalStartIndex = file.localSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000736 for (AtomAndIndex &ai : globals) {
737 Symbol sym;
738 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000739 sym.type = N_SECT;
Nick Kledzike34182f2013-11-06 21:36:55 +0000740 sym.scope = scopeBits(static_cast<const DefinedAtom*>(ai.atom));
741 sym.sect = ai.index;
Nick Kledzik60855392014-06-11 00:24:16 +0000742 sym.desc = descBits(static_cast<const DefinedAtom*>(ai.atom));
Nick Kledzike34182f2013-11-06 21:36:55 +0000743 sym.value = _atomToAddress[ai.atom];
Nick Kledzik2d432352014-07-17 23:16:21 +0000744 _atomToSymbolIndex[ai.atom] = globalStartIndex + file.globalSymbols.size();
Nick Kledzike34182f2013-11-06 21:36:55 +0000745 file.globalSymbols.push_back(sym);
746 }
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000747
748
Nick Kledzike34182f2013-11-06 21:36:55 +0000749 // Sort undefined symbol alphabetically, then add to symbol table.
750 std::vector<AtomAndIndex> undefs;
751 undefs.reserve(128);
752 for (const UndefinedAtom *atom : atomFile.undefined()) {
753 AtomAndIndex ai = { atom, 0 };
754 undefs.push_back(ai);
755 }
756 for (const SharedLibraryAtom *atom : atomFile.sharedLibrary()) {
757 AtomAndIndex ai = { atom, 0 };
758 undefs.push_back(ai);
759 }
760 std::sort(undefs.begin(), undefs.end(), AtomSorter());
761 const uint32_t start = file.globalSymbols.size() + file.localSymbols.size();
762 for (AtomAndIndex &ai : undefs) {
763 Symbol sym;
Nick Kledzikb4768322014-08-13 23:11:42 +0000764 uint16_t desc = 0;
765 if (!rMode) {
766 uint8_t ordinal = dylibOrdinal(dyn_cast<SharedLibraryAtom>(ai.atom));
767 llvm::MachO::SET_LIBRARY_ORDINAL(desc, ordinal);
768 }
Nick Kledzike34182f2013-11-06 21:36:55 +0000769 sym.name = ai.atom->name();
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000770 sym.type = N_UNDF;
Nick Kledzike34182f2013-11-06 21:36:55 +0000771 sym.scope = N_EXT;
772 sym.sect = 0;
Nick Kledzikb4768322014-08-13 23:11:42 +0000773 sym.desc = desc;
Nick Kledzike34182f2013-11-06 21:36:55 +0000774 sym.value = 0;
775 _atomToSymbolIndex[ai.atom] = file.undefinedSymbols.size() + start;
776 file.undefinedSymbols.push_back(sym);
777 }
778}
779
780const Atom *Util::targetOfLazyPointer(const DefinedAtom *lpAtom) {
781 for (const Reference *ref : *lpAtom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000782 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000783 return ref->target();
784 }
785 }
786 return nullptr;
787}
788
789const Atom *Util::targetOfStub(const DefinedAtom *stubAtom) {
790 for (const Reference *ref : *stubAtom) {
791 if (const Atom *ta = ref->target()) {
792 if (const DefinedAtom *lpAtom = dyn_cast<DefinedAtom>(ta)) {
793 const Atom *target = targetOfLazyPointer(lpAtom);
794 if (target)
795 return target;
796 }
797 }
798 }
799 return nullptr;
800}
801
802
803void Util::addIndirectSymbols(const lld::File &atomFile, NormalizedFile &file) {
804 for (SectionInfo *si : _sectionInfos) {
805 Section &normSect = file.sections[si->normalizedSectionIndex];
806 switch (si->type) {
807 case llvm::MachO::S_NON_LAZY_SYMBOL_POINTERS:
808 for (const AtomInfo &info : si->atomsAndOffsets) {
809 bool foundTarget = false;
810 for (const Reference *ref : *info.atom) {
811 const Atom *target = ref->target();
812 if (target) {
813 if (isa<const SharedLibraryAtom>(target)) {
814 uint32_t index = _atomToSymbolIndex[target];
815 normSect.indirectSymbols.push_back(index);
816 foundTarget = true;
817 } else {
818 normSect.indirectSymbols.push_back(
819 llvm::MachO::INDIRECT_SYMBOL_LOCAL);
820 }
821 }
822 }
823 if (!foundTarget) {
824 normSect.indirectSymbols.push_back(
825 llvm::MachO::INDIRECT_SYMBOL_ABS);
826 }
827 }
828 break;
829 case llvm::MachO::S_LAZY_SYMBOL_POINTERS:
830 for (const AtomInfo &info : si->atomsAndOffsets) {
831 const Atom *target = targetOfLazyPointer(info.atom);
832 if (target) {
833 uint32_t index = _atomToSymbolIndex[target];
834 normSect.indirectSymbols.push_back(index);
835 }
836 }
837 break;
838 case llvm::MachO::S_SYMBOL_STUBS:
839 for (const AtomInfo &info : si->atomsAndOffsets) {
840 const Atom *target = targetOfStub(info.atom);
841 if (target) {
842 uint32_t index = _atomToSymbolIndex[target];
843 normSect.indirectSymbols.push_back(index);
844 }
845 }
846 break;
847 default:
848 break;
849 }
850 }
851
852}
853
854void Util::addDependentDylibs(const lld::File &atomFile,NormalizedFile &nFile) {
855 // Scan all imported symbols and build up list of dylibs they are from.
856 int ordinal = 1;
857 for (const SharedLibraryAtom *slAtom : atomFile.sharedLibrary()) {
858 StringRef loadPath = slAtom->loadName();
859 DylibPathToInfo::iterator pos = _dylibInfo.find(loadPath);
860 if (pos == _dylibInfo.end()) {
861 DylibInfo info;
862 info.ordinal = ordinal++;
863 info.hasWeak = slAtom->canBeNullAtRuntime();
864 info.hasNonWeak = !info.hasWeak;
865 _dylibInfo[loadPath] = info;
866 DependentDylib depInfo;
867 depInfo.path = loadPath;
868 depInfo.kind = llvm::MachO::LC_LOAD_DYLIB;
869 nFile.dependentDylibs.push_back(depInfo);
870 } else {
871 if ( slAtom->canBeNullAtRuntime() )
872 pos->second.hasWeak = true;
873 else
874 pos->second.hasNonWeak = true;
875 }
876 }
877 // Automatically weak link dylib in which all symbols are weak (canBeNull).
878 for (DependentDylib &dep : nFile.dependentDylibs) {
879 DylibInfo &info = _dylibInfo[dep.path];
880 if (info.hasWeak && !info.hasNonWeak)
881 dep.kind = llvm::MachO::LC_LOAD_WEAK_DYLIB;
882 }
883}
884
885
886int Util::dylibOrdinal(const SharedLibraryAtom *sa) {
887 return _dylibInfo[sa->loadName()].ordinal;
888}
889
890void Util::segIndexForSection(const SectionInfo *sect, uint8_t &segmentIndex,
891 uint64_t &segmentStartAddr) {
892 segmentIndex = 0;
893 for (const SegmentInfo *seg : _segmentInfos) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000894 if ((seg->address <= sect->address)
Nick Kledzike34182f2013-11-06 21:36:55 +0000895 && (seg->address+seg->size >= sect->address+sect->size)) {
896 segmentStartAddr = seg->address;
897 return;
898 }
899 ++segmentIndex;
900 }
901 llvm_unreachable("section not in any segment");
902}
903
904
Nick Kledzik2d432352014-07-17 23:16:21 +0000905uint32_t Util::sectionIndexForAtom(const Atom *atom) {
906 uint64_t address = _atomToAddress[atom];
907 uint32_t index = 1;
908 for (const SectionInfo *si : _sectionInfos) {
909 if ((si->address <= address) && (address < si->address+si->size))
910 return index;
911 ++index;
912 }
913 llvm_unreachable("atom not in any section");
Nick Kledzike34182f2013-11-06 21:36:55 +0000914}
915
916void Util::addSectionRelocs(const lld::File &, NormalizedFile &file) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000917 if (_context.outputMachOType() != llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000918 return;
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000919
Nick Kledzik2d432352014-07-17 23:16:21 +0000920
921 // Utility function for ArchHandler to find symbol index for an atom.
922 auto symIndexForAtom = [&] (const Atom &atom) -> uint32_t {
923 auto pos = _atomToSymbolIndex.find(&atom);
924 assert(pos != _atomToSymbolIndex.end());
925 return pos->second;
926 };
927
928 // Utility function for ArchHandler to find section index for an atom.
929 auto sectIndexForAtom = [&] (const Atom &atom) -> uint32_t {
930 return sectionIndexForAtom(&atom);
931 };
932
933 // Utility function for ArchHandler to find address of atom in output file.
934 auto addressForAtom = [&] (const Atom &atom) -> uint64_t {
935 auto pos = _atomToAddress.find(&atom);
936 assert(pos != _atomToAddress.end());
937 return pos->second;
938 };
939
Nick Kledzike34182f2013-11-06 21:36:55 +0000940 for (SectionInfo *si : _sectionInfos) {
941 Section &normSect = file.sections[si->normalizedSectionIndex];
942 for (const AtomInfo &info : si->atomsAndOffsets) {
943 const DefinedAtom *atom = info.atom;
944 for (const Reference *ref : *atom) {
Nick Kledzik2d432352014-07-17 23:16:21 +0000945 _archHandler.appendSectionRelocations(*atom, info.offsetInSection, *ref,
946 symIndexForAtom,
947 sectIndexForAtom,
948 addressForAtom,
949 normSect.relocations);
Nick Kledzike34182f2013-11-06 21:36:55 +0000950 }
951 }
952 }
953}
954
Nick Kledzik21921372014-07-24 23:06:56 +0000955void Util::buildDataInCodeArray(const lld::File &, NormalizedFile &file) {
956 for (SectionInfo *si : _sectionInfos) {
957 for (const AtomInfo &info : si->atomsAndOffsets) {
958 // Atoms that contain data-in-code have "transition" references
959 // which mark a point where the embedded data starts of ends.
960 // This needs to be converted to the mach-o format which is an array
961 // of data-in-code ranges.
962 uint32_t startOffset = 0;
963 DataRegionType mode = DataRegionType(0);
964 for (const Reference *ref : *info.atom) {
965 if (ref->kindNamespace() != Reference::KindNamespace::mach_o)
966 continue;
967 if (_archHandler.isDataInCodeTransition(ref->kindValue())) {
968 DataRegionType nextMode = (DataRegionType)ref->addend();
969 if (mode != nextMode) {
970 if (mode != 0) {
971 // Found end data range, so make range entry.
972 DataInCode entry;
973 entry.offset = si->address + info.offsetInSection + startOffset;
974 entry.length = ref->offsetInAtom() - startOffset;
975 entry.kind = mode;
976 file.dataInCode.push_back(entry);
977 }
978 }
979 mode = nextMode;
980 startOffset = ref->offsetInAtom();
981 }
982 }
983 if (mode != 0) {
984 // Function ends with data (no end transition).
985 DataInCode entry;
986 entry.offset = si->address + info.offsetInSection + startOffset;
987 entry.length = info.atom->size() - startOffset;
988 entry.kind = mode;
989 file.dataInCode.push_back(entry);
990 }
991 }
992 }
993}
994
Shankar Easwaran3d8de472014-01-27 03:09:26 +0000995void Util::addRebaseAndBindingInfo(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +0000996 NormalizedFile &nFile) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000997 if (_context.outputMachOType() == llvm::MachO::MH_OBJECT)
Nick Kledzike34182f2013-11-06 21:36:55 +0000998 return;
999
1000 uint8_t segmentIndex;
1001 uint64_t segmentStartAddr;
1002 for (SectionInfo *sect : _sectionInfos) {
1003 segIndexForSection(sect, segmentIndex, segmentStartAddr);
1004 for (const AtomInfo &info : sect->atomsAndOffsets) {
1005 const DefinedAtom *atom = info.atom;
1006 for (const Reference *ref : *atom) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001007 uint64_t segmentOffset = _atomToAddress[atom] + ref->offsetInAtom()
Nick Kledzike34182f2013-11-06 21:36:55 +00001008 - segmentStartAddr;
1009 const Atom* targ = ref->target();
Nick Kledzik2d432352014-07-17 23:16:21 +00001010 if (_archHandler.isPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001011 // A pointer to a DefinedAtom requires rebasing.
1012 if (dyn_cast<DefinedAtom>(targ)) {
1013 RebaseLocation rebase;
1014 rebase.segIndex = segmentIndex;
1015 rebase.segOffset = segmentOffset;
1016 rebase.kind = llvm::MachO::REBASE_TYPE_POINTER;
1017 nFile.rebasingInfo.push_back(rebase);
1018 }
1019 // A pointer to an SharedLibraryAtom requires binding.
1020 if (const SharedLibraryAtom *sa = dyn_cast<SharedLibraryAtom>(targ)) {
1021 BindLocation bind;
1022 bind.segIndex = segmentIndex;
1023 bind.segOffset = segmentOffset;
1024 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
1025 bind.canBeNull = sa->canBeNullAtRuntime();
1026 bind.ordinal = dylibOrdinal(sa);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001027 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +00001028 bind.addend = ref->addend();
1029 nFile.bindingInfo.push_back(bind);
1030 }
1031 }
Nick Kledzik2d432352014-07-17 23:16:21 +00001032 if (_archHandler.isLazyPointer(*ref)) {
Nick Kledzike34182f2013-11-06 21:36:55 +00001033 BindLocation bind;
1034 bind.segIndex = segmentIndex;
1035 bind.segOffset = segmentOffset;
1036 bind.kind = llvm::MachO::BIND_TYPE_POINTER;
1037 bind.canBeNull = false; //sa->canBeNullAtRuntime();
Nick Kledzik2d432352014-07-17 23:16:21 +00001038 bind.ordinal = 1; // FIXME
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001039 bind.symbolName = targ->name();
Nick Kledzike34182f2013-11-06 21:36:55 +00001040 bind.addend = ref->addend();
1041 nFile.lazyBindingInfo.push_back(bind);
1042 }
1043 }
1044 }
1045 }
1046}
1047
1048uint32_t Util::fileFlags() {
Nick Kledzike1aaced2014-07-22 00:49:49 +00001049 // FIXME: these need to determined at runtime.
1050 if (_context.outputMachOType() == MH_OBJECT) {
1051 return MH_SUBSECTIONS_VIA_SYMBOLS;
1052 } else {
1053 return MH_DYLDLINK | MH_NOUNDEFS | MH_TWOLEVEL;
1054 }
Nick Kledzike34182f2013-11-06 21:36:55 +00001055}
1056
1057} // end anonymous namespace
1058
1059
1060namespace lld {
1061namespace mach_o {
1062namespace normalized {
1063
1064/// Convert a set of Atoms into a normalized mach-o file.
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001065ErrorOr<std::unique_ptr<NormalizedFile>>
1066normalizedFromAtoms(const lld::File &atomFile,
Nick Kledzike34182f2013-11-06 21:36:55 +00001067 const MachOLinkingContext &context) {
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001068 // The util object buffers info until the normalized file can be made.
Nick Kledzike34182f2013-11-06 21:36:55 +00001069 Util util(context);
1070 util.assignAtomsToSections(atomFile);
1071 util.organizeSections();
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001072
Nick Kledzike34182f2013-11-06 21:36:55 +00001073 std::unique_ptr<NormalizedFile> f(new NormalizedFile());
1074 NormalizedFile &normFile = *f.get();
Nick Kledzik2fcbe822014-07-30 00:58:06 +00001075 normFile.arch = context.arch();
1076 normFile.fileType = context.outputMachOType();
1077 normFile.flags = util.fileFlags();
1078 normFile.installName = context.installName();
Nick Kledzike34182f2013-11-06 21:36:55 +00001079 util.addDependentDylibs(atomFile, normFile);
Nick Kledzik2fcbe822014-07-30 00:58:06 +00001080 util.copySegmentInfo(normFile);
1081 util.copySectionInfo(normFile);
1082 util.assignAddressesToSections(normFile);
1083 util.buildAtomToAddressMap();
1084 util.updateSectionInfo(normFile);
1085 util.copySectionContent(normFile);
Nick Kledzike34182f2013-11-06 21:36:55 +00001086 util.addSymbols(atomFile, normFile);
1087 util.addIndirectSymbols(atomFile, normFile);
1088 util.addRebaseAndBindingInfo(atomFile, normFile);
1089 util.addSectionRelocs(atomFile, normFile);
Nick Kledzik21921372014-07-24 23:06:56 +00001090 util.buildDataInCodeArray(atomFile, normFile);
Nick Kledzike34182f2013-11-06 21:36:55 +00001091 util.copyEntryPointAddress(normFile);
Shankar Easwaran3d8de472014-01-27 03:09:26 +00001092
Nick Kledzike34182f2013-11-06 21:36:55 +00001093 return std::move(f);
1094}
1095
1096
1097} // namespace normalized
1098} // namespace mach_o
1099} // namespace lld
1100