blob: 5820a224c527b57f060d3212fc36512de3649079 [file] [log] [blame]
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbarae5abd52010-12-16 16:09:19 +000010#include "llvm/MC/MCMachObjectWriter.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000011#include "llvm/ADT/StringMap.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/MC/MCAssembler.h"
Evan Cheng78c10ee2011-07-25 23:24:55 +000014#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000015#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000016#include "llvm/MC/MCExpr.h"
Craig Topperf1d0f772012-03-26 06:58:25 +000017#include "llvm/MC/MCFixupKindInfo.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000018#include "llvm/MC/MCObjectWriter.h"
19#include "llvm/MC/MCSectionMachO.h"
20#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000021#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000022#include "llvm/MC/MCValue.h"
Daniel Dunbar821ecd72010-11-27 04:19:38 +000023#include "llvm/Object/MachOFormat.h"
Jim Grosbach3e965312012-05-18 19:12:01 +000024#include "llvm/Support/Debug.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000025#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000026
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000027#include <vector>
28using namespace llvm;
Daniel Dunbar821ecd72010-11-27 04:19:38 +000029using namespace llvm::object;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000030
Jim Grosbachba8297e2011-06-24 23:44:37 +000031bool MachObjectWriter::
32doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
Daniel Dunbare9460ec2010-05-10 23:15:13 +000033 // Undefined symbols are always extern.
34 if (SD->Symbol->isUndefined())
35 return true;
36
37 // References to weak definitions require external relocation entries; the
38 // definition may not always be the one in the same object file.
39 if (SD->getFlags() & SF_WeakDefinition)
40 return true;
41
42 // Otherwise, we can use an internal relocation.
43 return false;
44}
45
Jim Grosbachba8297e2011-06-24 23:44:37 +000046bool MachObjectWriter::
47MachSymbolData::operator<(const MachSymbolData &RHS) const {
48 return SymbolData->getSymbol().getName() <
49 RHS.SymbolData->getSymbol().getName();
50}
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000051
Jim Grosbachba8297e2011-06-24 23:44:37 +000052bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
53 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
54 (MCFixupKind) Kind);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000055
Jim Grosbachba8297e2011-06-24 23:44:37 +000056 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
57}
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000058
Jim Grosbachba8297e2011-06-24 23:44:37 +000059uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
60 const MCAsmLayout &Layout) const {
61 return getSectionAddress(Fragment->getParent()) +
62 Layout.getFragmentOffset(Fragment);
63}
Bill Wendlingbbdffa92011-06-22 21:07:27 +000064
65uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
66 const MCAsmLayout &Layout) const {
67 const MCSymbol &S = SD->getSymbol();
68
69 // If this is a variable, then recursively evaluate now.
70 if (S.isVariable()) {
71 MCValue Target;
72 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
73 report_fatal_error("unable to evaluate offset for variable '" +
74 S.getName() + "'");
75
76 // Verify that any used symbols are defined.
77 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
78 report_fatal_error("unable to evaluate offset to undefined symbol '" +
79 Target.getSymA()->getSymbol().getName() + "'");
80 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
81 report_fatal_error("unable to evaluate offset to undefined symbol '" +
82 Target.getSymB()->getSymbol().getName() + "'");
83
84 uint64_t Address = Target.getConstant();
85 if (Target.getSymA())
86 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
87 Target.getSymA()->getSymbol()), Layout);
88 if (Target.getSymB())
89 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
90 Target.getSymB()->getSymbol()), Layout);
91 return Address;
92 }
93
94 return getSectionAddress(SD->getFragment()->getParent()) +
95 Layout.getSymbolOffset(SD);
96}
97
98uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
99 const MCAsmLayout &Layout) const {
100 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
101 unsigned Next = SD->getLayoutOrder() + 1;
102 if (Next >= Layout.getSectionOrder().size())
103 return 0;
104
105 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
106 if (NextSD.getSection().isVirtualSection())
107 return 0;
108 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
109}
110
111void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
112 unsigned LoadCommandsSize,
113 bool SubsectionsViaSymbols) {
114 uint32_t Flags = 0;
115
116 if (SubsectionsViaSymbols)
117 Flags |= macho::HF_SubsectionsViaSymbols;
118
119 // struct mach_header (28 bytes) or
120 // struct mach_header_64 (32 bytes)
121
122 uint64_t Start = OS.tell();
123 (void) Start;
124
125 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
126
127 Write32(TargetObjectWriter->getCPUType());
128 Write32(TargetObjectWriter->getCPUSubtype());
129
130 Write32(macho::HFT_Object);
131 Write32(NumLoadCommands);
132 Write32(LoadCommandsSize);
133 Write32(Flags);
134 if (is64Bit())
135 Write32(0); // reserved
136
137 assert(OS.tell() - Start ==
138 (is64Bit() ? macho::Header64Size : macho::Header32Size));
139}
140
141/// WriteSegmentLoadCommand - Write a segment load command.
142///
143/// \arg NumSections - The number of sections in this segment.
144/// \arg SectionDataSize - The total size of the sections.
145void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
146 uint64_t VMSize,
147 uint64_t SectionDataStartOffset,
148 uint64_t SectionDataSize) {
149 // struct segment_command (56 bytes) or
150 // struct segment_command_64 (72 bytes)
151
152 uint64_t Start = OS.tell();
153 (void) Start;
154
155 unsigned SegmentLoadCommandSize =
156 is64Bit() ? macho::SegmentLoadCommand64Size:
157 macho::SegmentLoadCommand32Size;
158 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
159 Write32(SegmentLoadCommandSize +
160 NumSections * (is64Bit() ? macho::Section64Size :
161 macho::Section32Size));
162
163 WriteBytes("", 16);
164 if (is64Bit()) {
165 Write64(0); // vmaddr
166 Write64(VMSize); // vmsize
167 Write64(SectionDataStartOffset); // file offset
168 Write64(SectionDataSize); // file size
169 } else {
170 Write32(0); // vmaddr
171 Write32(VMSize); // vmsize
172 Write32(SectionDataStartOffset); // file offset
173 Write32(SectionDataSize); // file size
174 }
175 Write32(0x7); // maxprot
176 Write32(0x7); // initprot
177 Write32(NumSections);
178 Write32(0); // flags
179
180 assert(OS.tell() - Start == SegmentLoadCommandSize);
181}
182
183void MachObjectWriter::WriteSection(const MCAssembler &Asm,
184 const MCAsmLayout &Layout,
185 const MCSectionData &SD,
186 uint64_t FileOffset,
187 uint64_t RelocationsStart,
188 unsigned NumRelocations) {
189 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
190
191 // The offset is unused for virtual sections.
192 if (SD.getSection().isVirtualSection()) {
193 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
194 FileOffset = 0;
195 }
196
197 // struct section (68 bytes) or
198 // struct section_64 (80 bytes)
199
200 uint64_t Start = OS.tell();
201 (void) Start;
202
203 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
204 WriteBytes(Section.getSectionName(), 16);
205 WriteBytes(Section.getSegmentName(), 16);
206 if (is64Bit()) {
207 Write64(getSectionAddress(&SD)); // address
208 Write64(SectionSize); // size
209 } else {
210 Write32(getSectionAddress(&SD)); // address
211 Write32(SectionSize); // size
212 }
213 Write32(FileOffset);
214
215 unsigned Flags = Section.getTypeAndAttributes();
216 if (SD.hasInstructions())
217 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
218
219 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
220 Write32(Log2_32(SD.getAlignment()));
221 Write32(NumRelocations ? RelocationsStart : 0);
222 Write32(NumRelocations);
223 Write32(Flags);
224 Write32(IndirectSymBase.lookup(&SD)); // reserved1
225 Write32(Section.getStubSize()); // reserved2
226 if (is64Bit())
227 Write32(0); // reserved3
228
229 assert(OS.tell() - Start == (is64Bit() ? macho::Section64Size :
230 macho::Section32Size));
231}
232
233void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
234 uint32_t NumSymbols,
235 uint32_t StringTableOffset,
236 uint32_t StringTableSize) {
237 // struct symtab_command (24 bytes)
238
239 uint64_t Start = OS.tell();
240 (void) Start;
241
242 Write32(macho::LCT_Symtab);
243 Write32(macho::SymtabLoadCommandSize);
244 Write32(SymbolOffset);
245 Write32(NumSymbols);
246 Write32(StringTableOffset);
247 Write32(StringTableSize);
248
249 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
250}
251
252void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
253 uint32_t NumLocalSymbols,
254 uint32_t FirstExternalSymbol,
255 uint32_t NumExternalSymbols,
256 uint32_t FirstUndefinedSymbol,
257 uint32_t NumUndefinedSymbols,
258 uint32_t IndirectSymbolOffset,
259 uint32_t NumIndirectSymbols) {
260 // struct dysymtab_command (80 bytes)
261
262 uint64_t Start = OS.tell();
263 (void) Start;
264
265 Write32(macho::LCT_Dysymtab);
266 Write32(macho::DysymtabLoadCommandSize);
267 Write32(FirstLocalSymbol);
268 Write32(NumLocalSymbols);
269 Write32(FirstExternalSymbol);
270 Write32(NumExternalSymbols);
271 Write32(FirstUndefinedSymbol);
272 Write32(NumUndefinedSymbols);
273 Write32(0); // tocoff
274 Write32(0); // ntoc
275 Write32(0); // modtaboff
276 Write32(0); // nmodtab
277 Write32(0); // extrefsymoff
278 Write32(0); // nextrefsyms
279 Write32(IndirectSymbolOffset);
280 Write32(NumIndirectSymbols);
281 Write32(0); // extreloff
282 Write32(0); // nextrel
283 Write32(0); // locreloff
284 Write32(0); // nlocrel
285
286 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
287}
288
Bill Wendling3f2ea822011-06-23 00:09:43 +0000289void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
290 const MCAsmLayout &Layout) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000291 MCSymbolData &Data = *MSD.SymbolData;
292 const MCSymbol &Symbol = Data.getSymbol();
293 uint8_t Type = 0;
294 uint16_t Flags = Data.getFlags();
Jim Grosbach739b5572011-08-09 22:12:37 +0000295 uint64_t Address = 0;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000296
297 // Set the N_TYPE bits. See <mach-o/nlist.h>.
298 //
299 // FIXME: Are the prebound or indirect fields possible here?
300 if (Symbol.isUndefined())
301 Type = macho::STT_Undefined;
302 else if (Symbol.isAbsolute())
303 Type = macho::STT_Absolute;
304 else
305 Type = macho::STT_Section;
306
307 // FIXME: Set STAB bits.
308
309 if (Data.isPrivateExtern())
310 Type |= macho::STF_PrivateExtern;
311
312 // Set external bit.
313 if (Data.isExternal() || Symbol.isUndefined())
314 Type |= macho::STF_External;
315
316 // Compute the symbol address.
317 if (Symbol.isDefined()) {
318 if (Symbol.isAbsolute()) {
319 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
320 } else {
321 Address = getSymbolAddress(&Data, Layout);
322 }
323 } else if (Data.isCommon()) {
324 // Common symbols are encoded with the size in the address
325 // field, and their alignment in the flags.
326 Address = Data.getCommonSize();
327
328 // Common alignment is packed into the 'desc' bits.
329 if (unsigned Align = Data.getCommonAlignment()) {
330 unsigned Log2Size = Log2_32(Align);
331 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
332 if (Log2Size > 15)
333 report_fatal_error("invalid 'common' alignment '" +
334 Twine(Align) + "'");
335 // FIXME: Keep this mask with the SymbolFlags enumeration.
336 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
337 }
338 }
339
340 // struct nlist (12 bytes)
341
342 Write32(MSD.StringIndex);
343 Write8(Type);
344 Write8(MSD.SectionIndex);
345
346 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
347 // value.
348 Write16(Flags);
349 if (is64Bit())
350 Write64(Address);
351 else
352 Write32(Address);
353}
354
Jim Grosbach3e965312012-05-18 19:12:01 +0000355void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
356 uint32_t DataOffset,
357 uint32_t DataSize) {
358 uint64_t Start = OS.tell();
359 (void) Start;
360
361 Write32(Type);
362 Write32(macho::LinkeditLoadCommandSize);
363 Write32(DataOffset);
364 Write32(DataSize);
365
366 assert(OS.tell() - Start == macho::LinkeditLoadCommandSize);
367}
368
369
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000370void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
371 const MCAsmLayout &Layout,
372 const MCFragment *Fragment,
373 const MCFixup &Fixup,
374 MCValue Target,
375 uint64_t &FixedValue) {
Jim Grosbachba8297e2011-06-24 23:44:37 +0000376 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
377 Target, FixedValue);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000378}
379
380void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
381 // This is the point where 'as' creates actual symbols for indirect symbols
382 // (in the following two passes). It would be easier for us to do this sooner
383 // when we see the attribute, but that makes getting the order in the symbol
384 // table much more complicated than it is worth.
385 //
386 // FIXME: Revisit this when the dust settles.
387
388 // Bind non lazy symbol pointers first.
389 unsigned IndirectIndex = 0;
390 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
391 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
392 const MCSectionMachO &Section =
393 cast<MCSectionMachO>(it->SectionData->getSection());
394
395 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
396 continue;
397
398 // Initialize the section indirect symbol base, if necessary.
399 if (!IndirectSymBase.count(it->SectionData))
400 IndirectSymBase[it->SectionData] = IndirectIndex;
401
402 Asm.getOrCreateSymbolData(*it->Symbol);
403 }
404
405 // Then lazy symbol pointers and symbol stubs.
406 IndirectIndex = 0;
407 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
408 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
409 const MCSectionMachO &Section =
410 cast<MCSectionMachO>(it->SectionData->getSection());
411
412 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
413 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
414 continue;
415
416 // Initialize the section indirect symbol base, if necessary.
417 if (!IndirectSymBase.count(it->SectionData))
418 IndirectSymBase[it->SectionData] = IndirectIndex;
419
420 // Set the symbol type to undefined lazy, but only on construction.
421 //
422 // FIXME: Do not hardcode.
423 bool Created;
424 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
425 if (Created)
426 Entry.setFlags(Entry.getFlags() | 0x0001);
427 }
428}
429
430/// ComputeSymbolTable - Compute the symbol table data
431///
432/// \param StringTable [out] - The string table data.
433/// \param StringIndexMap [out] - Map from symbol names to offsets in the
434/// string table.
Bill Wendling3f2ea822011-06-23 00:09:43 +0000435void MachObjectWriter::
436ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
437 std::vector<MachSymbolData> &LocalSymbolData,
438 std::vector<MachSymbolData> &ExternalSymbolData,
439 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000440 // Build section lookup table.
441 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
442 unsigned Index = 1;
443 for (MCAssembler::iterator it = Asm.begin(),
444 ie = Asm.end(); it != ie; ++it, ++Index)
445 SectionIndexMap[&it->getSection()] = Index;
446 assert(Index <= 256 && "Too many sections!");
447
448 // Index 0 is always the empty string.
449 StringMap<uint64_t> StringIndexMap;
450 StringTable += '\x00';
451
452 // Build the symbol arrays and the string table, but only for non-local
453 // symbols.
454 //
455 // The particular order that we collect the symbols and create the string
456 // table, then sort the symbols is chosen to match 'as'. Even though it
457 // doesn't matter for correctness, this is important for letting us diff .o
458 // files.
459 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
460 ie = Asm.symbol_end(); it != ie; ++it) {
461 const MCSymbol &Symbol = it->getSymbol();
462
463 // Ignore non-linker visible symbols.
464 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
465 continue;
466
467 if (!it->isExternal() && !Symbol.isUndefined())
468 continue;
469
470 uint64_t &Entry = StringIndexMap[Symbol.getName()];
471 if (!Entry) {
472 Entry = StringTable.size();
473 StringTable += Symbol.getName();
474 StringTable += '\x00';
475 }
476
477 MachSymbolData MSD;
478 MSD.SymbolData = it;
479 MSD.StringIndex = Entry;
480
481 if (Symbol.isUndefined()) {
482 MSD.SectionIndex = 0;
483 UndefinedSymbolData.push_back(MSD);
484 } else if (Symbol.isAbsolute()) {
485 MSD.SectionIndex = 0;
486 ExternalSymbolData.push_back(MSD);
487 } else {
488 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
489 assert(MSD.SectionIndex && "Invalid section index!");
490 ExternalSymbolData.push_back(MSD);
491 }
492 }
493
494 // Now add the data for local symbols.
495 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
496 ie = Asm.symbol_end(); it != ie; ++it) {
497 const MCSymbol &Symbol = it->getSymbol();
498
499 // Ignore non-linker visible symbols.
500 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
501 continue;
502
503 if (it->isExternal() || Symbol.isUndefined())
504 continue;
505
506 uint64_t &Entry = StringIndexMap[Symbol.getName()];
507 if (!Entry) {
508 Entry = StringTable.size();
509 StringTable += Symbol.getName();
510 StringTable += '\x00';
511 }
512
513 MachSymbolData MSD;
514 MSD.SymbolData = it;
515 MSD.StringIndex = Entry;
516
517 if (Symbol.isAbsolute()) {
518 MSD.SectionIndex = 0;
519 LocalSymbolData.push_back(MSD);
520 } else {
521 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
522 assert(MSD.SectionIndex && "Invalid section index!");
523 LocalSymbolData.push_back(MSD);
524 }
525 }
526
527 // External and undefined symbols are required to be in lexicographic order.
528 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
529 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
530
531 // Set the symbol indices.
532 Index = 0;
533 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
534 LocalSymbolData[i].SymbolData->setIndex(Index++);
535 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
536 ExternalSymbolData[i].SymbolData->setIndex(Index++);
537 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
538 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
539
540 // The string table is padded to a multiple of 4.
541 while (StringTable.size() % 4)
542 StringTable += '\x00';
543}
544
545void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
546 const MCAsmLayout &Layout) {
547 uint64_t StartAddress = 0;
548 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
549 for (int i = 0, n = Order.size(); i != n ; ++i) {
550 const MCSectionData *SD = Order[i];
551 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
552 SectionAddress[SD] = StartAddress;
553 StartAddress += Layout.getSectionAddressSize(SD);
554
555 // Explicitly pad the section to match the alignment requirements of the
556 // following one. This is for 'gas' compatibility, it shouldn't
557 /// strictly be necessary.
558 StartAddress += getPaddingSize(SD, Layout);
559 }
560}
561
Bill Wendling3f2ea822011-06-23 00:09:43 +0000562void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
563 const MCAsmLayout &Layout) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000564 computeSectionAddresses(Asm, Layout);
565
566 // Create symbol data for any indirect symbols.
567 BindIndirectSymbols(Asm);
568
569 // Compute symbol table information and bind symbol indices.
570 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
571 UndefinedSymbolData);
572}
573
Bill Wendling3f2ea822011-06-23 00:09:43 +0000574bool MachObjectWriter::
575IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
576 const MCSymbolData &DataA,
577 const MCFragment &FB,
578 bool InSet,
579 bool IsPCRel) const {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000580 if (InSet)
581 return true;
582
583 // The effective address is
584 // addr(atom(A)) + offset(A)
585 // - addr(atom(B)) - offset(B)
586 // and the offsets are not relocatable, so the fixup is fully resolved when
587 // addr(atom(A)) - addr(atom(B)) == 0.
588 const MCSymbolData *A_Base = 0, *B_Base = 0;
589
590 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
591 const MCSection &SecA = SA.getSection();
592 const MCSection &SecB = FB.getParent()->getSection();
593
594 if (IsPCRel) {
595 // The simple (Darwin, except on x86_64) way of dealing with this was to
596 // assume that any reference to a temporary symbol *must* be a temporary
597 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
598 // relocation to a temporary symbol (in the same section) is fully
599 // resolved. This also works in conjunction with absolutized .set, which
600 // requires the compiler to use .set to absolutize the differences between
601 // symbols which the compiler knows to be assembly time constants, so we
602 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbach577b0912011-12-07 19:46:59 +0000603 //
604 // If the file isn't using sub-sections-via-symbols, we can make the
605 // same assumptions about any symbol that we normally make about
606 // assembler locals.
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000607
608 if (!Asm.getBackend().hasReliableSymbolDifference()) {
Jim Grosbach8b9300b2012-01-17 22:14:39 +0000609 if (!SA.isInSection() || &SecA != &SecB ||
Jim Grosbachec4ceb72012-01-18 21:54:12 +0000610 (!SA.isTemporary() &&
Jim Grosbachc389af92012-01-24 21:45:25 +0000611 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
612 Asm.getSubsectionsViaSymbols()))
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000613 return false;
614 return true;
615 }
Kevin Enderby5afc1902011-09-08 20:53:44 +0000616 // For Darwin x86_64, there is one special case when the reference IsPCRel.
617 // If the fragment with the reference does not have a base symbol but meets
618 // the simple way of dealing with this, in that it is a temporary symbol in
619 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopherd1e002a2011-09-08 22:17:40 +0000620 // a relocation entry is not created and so the static linker does not
Kevin Enderby5afc1902011-09-08 20:53:44 +0000621 // mess up the reference later.
622 else if(!FB.getAtom() &&
623 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
624 return true;
625 }
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000626 } else {
627 if (!TargetObjectWriter->useAggressiveSymbolFolding())
628 return false;
629 }
630
Benjamin Kramer0d46ccf2011-08-12 01:51:29 +0000631 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000632
Benjamin Kramer0d46ccf2011-08-12 01:51:29 +0000633 // Bail if the symbol has no fragment.
634 if (!FA)
635 return false;
636
637 A_Base = FA->getAtom();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000638 if (!A_Base)
639 return false;
640
641 B_Base = FB.getAtom();
642 if (!B_Base)
643 return false;
644
645 // If the atoms are the same, they are guaranteed to have the same address.
646 if (A_Base == B_Base)
647 return true;
648
649 // Otherwise, we can't prove this is fully resolved.
650 return false;
651}
652
Eric Christopherd1e002a2011-09-08 22:17:40 +0000653void MachObjectWriter::WriteObject(MCAssembler &Asm,
Jim Grosbachf68a26b2011-12-06 00:13:09 +0000654 const MCAsmLayout &Layout) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000655 unsigned NumSections = Asm.size();
656
657 // The section data starts after the header, the segment load command (and
658 // section headers) and the symbol table.
659 unsigned NumLoadCommands = 1;
660 uint64_t LoadCommandsSize = is64Bit() ?
661 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
662 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
663
664 // Add the symbol table load command sizes, if used.
665 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
666 UndefinedSymbolData.size();
667 if (NumSymbols) {
668 NumLoadCommands += 2;
669 LoadCommandsSize += (macho::SymtabLoadCommandSize +
670 macho::DysymtabLoadCommandSize);
671 }
672
Jim Grosbach3e965312012-05-18 19:12:01 +0000673 // Add the data-in-code load command size, if used.
674 unsigned NumDataRegions = Asm.getDataRegions().size();
675 if (NumDataRegions) {
676 ++NumLoadCommands;
677 LoadCommandsSize += macho::LinkeditLoadCommandSize;
678 }
679
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000680 // Compute the total size of the section data, as well as its file size and vm
681 // size.
682 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
683 macho::Header32Size) + LoadCommandsSize;
684 uint64_t SectionDataSize = 0;
685 uint64_t SectionDataFileSize = 0;
686 uint64_t VMSize = 0;
687 for (MCAssembler::const_iterator it = Asm.begin(),
688 ie = Asm.end(); it != ie; ++it) {
689 const MCSectionData &SD = *it;
690 uint64_t Address = getSectionAddress(&SD);
691 uint64_t Size = Layout.getSectionAddressSize(&SD);
692 uint64_t FileSize = Layout.getSectionFileSize(&SD);
693 FileSize += getPaddingSize(&SD, Layout);
694
695 VMSize = std::max(VMSize, Address + Size);
696
697 if (SD.getSection().isVirtualSection())
698 continue;
699
700 SectionDataSize = std::max(SectionDataSize, Address + Size);
701 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
702 }
703
704 // The section data is padded to 4 bytes.
705 //
706 // FIXME: Is this machine dependent?
707 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
708 SectionDataFileSize += SectionDataPadding;
709
710 // Write the prolog, starting with the header and load command...
711 WriteHeader(NumLoadCommands, LoadCommandsSize,
712 Asm.getSubsectionsViaSymbols());
713 WriteSegmentLoadCommand(NumSections, VMSize,
714 SectionDataStart, SectionDataSize);
715
716 // ... and then the section headers.
717 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
718 for (MCAssembler::const_iterator it = Asm.begin(),
719 ie = Asm.end(); it != ie; ++it) {
720 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
721 unsigned NumRelocs = Relocs.size();
722 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
723 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
724 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
725 }
726
Jim Grosbach3e965312012-05-18 19:12:01 +0000727 // Write the data-in-code load command, if used.
728 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
729 if (NumDataRegions) {
730 uint64_t DataRegionsOffset = RelocTableEnd;
731 uint64_t DataRegionsSize = NumDataRegions * 8;
732 WriteLinkeditLoadCommand(macho::LCT_DataInCode, DataRegionsOffset,
733 DataRegionsSize);
734 }
735
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000736 // Write the symbol table load command, if used.
737 if (NumSymbols) {
738 unsigned FirstLocalSymbol = 0;
739 unsigned NumLocalSymbols = LocalSymbolData.size();
740 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
741 unsigned NumExternalSymbols = ExternalSymbolData.size();
742 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
743 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
744 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
745 unsigned NumSymTabSymbols =
746 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
747 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
748 uint64_t IndirectSymbolOffset = 0;
749
750 // If used, the indirect symbols are written after the section data.
751 if (NumIndirectSymbols)
Jim Grosbach3e965312012-05-18 19:12:01 +0000752 IndirectSymbolOffset = DataInCodeTableEnd;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000753
754 // The symbol table is written after the indirect symbol data.
Jim Grosbach3e965312012-05-18 19:12:01 +0000755 uint64_t SymbolTableOffset = DataInCodeTableEnd + IndirectSymbolSize;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000756
757 // The string table is written after symbol table.
758 uint64_t StringTableOffset =
759 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
760 macho::Nlist32Size);
761 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
762 StringTableOffset, StringTable.size());
763
764 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
765 FirstExternalSymbol, NumExternalSymbols,
766 FirstUndefinedSymbol, NumUndefinedSymbols,
767 IndirectSymbolOffset, NumIndirectSymbols);
768 }
769
770 // Write the actual section data.
771 for (MCAssembler::const_iterator it = Asm.begin(),
772 ie = Asm.end(); it != ie; ++it) {
Jim Grosbachf77d5b12011-12-06 00:03:48 +0000773 Asm.writeSectionData(it, Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000774
775 uint64_t Pad = getPaddingSize(it, Layout);
776 for (unsigned int i = 0; i < Pad; ++i)
777 Write8(0);
778 }
779
780 // Write the extra padding.
781 WriteZeros(SectionDataPadding);
782
783 // Write the relocation entries.
784 for (MCAssembler::const_iterator it = Asm.begin(),
785 ie = Asm.end(); it != ie; ++it) {
786 // Write the section relocation entries, in reverse order to match 'as'
787 // (approximately, the exact algorithm is more complicated than this).
788 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
789 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
790 Write32(Relocs[e - i - 1].Word0);
791 Write32(Relocs[e - i - 1].Word1);
792 }
793 }
794
Jim Grosbach3e965312012-05-18 19:12:01 +0000795 // Write out the data-in-code region payload, if there is one.
796 for (MCAssembler::const_data_region_iterator
797 it = Asm.data_region_begin(), ie = Asm.data_region_end();
798 it != ie; ++it) {
799 const DataRegionData *Data = &(*it);
800 uint64_t Start = getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start), Layout);
801 uint64_t End = getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End), Layout);
802 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
803 << " start: " << Start << "(" << Data->Start->getName() << ")"
804 << " end: " << End << "(" << Data->End->getName() << ")"
805 << " size: " << End - Start
806 << "\n");
807 Write32(Start);
808 Write16(End - Start);
809 Write16(Data->Kind);
810 }
811
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000812 // Write the symbol table data, if used.
813 if (NumSymbols) {
814 // Write the indirect symbol entries.
815 for (MCAssembler::const_indirect_symbol_iterator
816 it = Asm.indirect_symbol_begin(),
817 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
818 // Indirect symbols in the non lazy symbol pointer section have some
819 // special handling.
820 const MCSectionMachO &Section =
821 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
822 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
823 // If this symbol is defined and internal, mark it as such.
824 if (it->Symbol->isDefined() &&
825 !Asm.getSymbolData(*it->Symbol).isExternal()) {
826 uint32_t Flags = macho::ISF_Local;
827 if (it->Symbol->isAbsolute())
828 Flags |= macho::ISF_Absolute;
829 Write32(Flags);
830 continue;
831 }
832 }
833
834 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
835 }
836
837 // FIXME: Check that offsets match computed ones.
838
839 // Write the symbol table entries.
840 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
841 WriteNlist(LocalSymbolData[i], Layout);
842 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
843 WriteNlist(ExternalSymbolData[i], Layout);
844 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
845 WriteNlist(UndefinedSymbolData[i], Layout);
846
847 // Write the string table.
848 OS << StringTable.str();
849 }
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000850}
851
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000852MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000853 raw_ostream &OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000854 bool IsLittleEndian) {
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000855 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000856}