blob: d4addf2a382856b308f38ca2c3eb8617310543c7 [file] [log] [blame]
Nate Begemaneb883af2006-08-23 21:08:52 +00001//===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the target-independent Mach-O writer. This file writes
11// out the Mach-O file in the following order:
12//
13// #1 FatHeader (universal-only)
14// #2 FatArch (universal-only, 1 per universal arch)
15// Per arch:
16// #3 Header
17// #4 Load Commands
18// #5 Sections
19// #6 Relocations
20// #7 Symbols
21// #8 Strings
22//
23//===----------------------------------------------------------------------===//
24
Nate Begemanbfaaaa62006-12-11 02:20:45 +000025#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000027#include "llvm/Module.h"
28#include "llvm/CodeGen/MachineCodeEmitter.h"
29#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman019f8512006-09-10 23:03:44 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000031#include "llvm/CodeGen/MachOWriter.h"
Nate Begeman94be2482006-09-08 22:42:09 +000032#include "llvm/ExecutionEngine/ExecutionEngine.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000033#include "llvm/Target/TargetAsmInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000034#include "llvm/Target/TargetJITInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000035#include "llvm/Support/Mangler.h"
Nate Begemanf8f2c5a2006-08-25 06:36:58 +000036#include "llvm/Support/MathExtras.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000037#include "llvm/Support/Streams.h"
Nate Begemand2030e62006-08-26 15:46:34 +000038#include <algorithm>
Nate Begemanbfaaaa62006-12-11 02:20:45 +000039
Nate Begemaneb883af2006-08-23 21:08:52 +000040using namespace llvm;
41
42//===----------------------------------------------------------------------===//
43// MachOCodeEmitter Implementation
44//===----------------------------------------------------------------------===//
45
46namespace llvm {
47 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
48 /// for functions to the Mach-O file.
49 class MachOCodeEmitter : public MachineCodeEmitter {
50 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000051
52 /// Relocations - These are the relocations that the function needs, as
53 /// emitted.
54 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000055
56 /// CPLocations - This is a map of constant pool indices to offsets from the
57 /// start of the section for that constant pool index.
58 std::vector<intptr_t> CPLocations;
59
Nate Begemanbfaaaa62006-12-11 02:20:45 +000060 /// CPSections - This is a map of constant pool indices to the MachOSection
61 /// containing the constant pool entry for that index.
62 std::vector<unsigned> CPSections;
63
Nate Begeman019f8512006-09-10 23:03:44 +000064 /// JTLocations - This is a map of jump table indices to offsets from the
65 /// start of the section for that jump table index.
66 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000067
68 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
69 /// It is filled in by the StartMachineBasicBlock callback and queried by
70 /// the getMachineBasicBlockAddress callback.
71 std::vector<intptr_t> MBBLocations;
72
73 public:
74 MachOCodeEmitter(MachOWriter &mow) : MOW(mow) {}
75
Nate Begemanbfaaaa62006-12-11 02:20:45 +000076 virtual void startFunction(MachineFunction &F);
77 virtual bool finishFunction(MachineFunction &F);
Nate Begemaneb883af2006-08-23 21:08:52 +000078
Nate Begemanbfaaaa62006-12-11 02:20:45 +000079 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +000080 Relocations.push_back(MR);
81 }
82
Nate Begeman019f8512006-09-10 23:03:44 +000083 void emitConstantPool(MachineConstantPool *MCP);
84 void emitJumpTables(MachineJumpTableInfo *MJTI);
85
Nate Begemaneb883af2006-08-23 21:08:52 +000086 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +000087 assert(CPLocations.size() > Index && "CP not emitted!");
88 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +000089 }
90 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +000091 assert(JTLocations.size() > Index && "JT not emitted!");
92 return JTLocations[Index];
93 }
94
95 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
96 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
97 MBBLocations.resize((MBB->getNumber()+1)*2);
98 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +000099 }
100
101 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
102 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
103 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
104 return MBBLocations[MBB->getNumber()];
105 }
106
107 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000108 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000109 assert(0 && "JIT specific function called!");
110 abort();
111 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000112 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000113 assert(0 && "JIT specific function called!");
114 abort();
115 return 0;
116 }
117 };
118}
119
120/// startFunction - This callback is invoked when a new machine function is
121/// about to be emitted.
122void MachOCodeEmitter::startFunction(MachineFunction &F) {
123 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000124 // FIXME: MachineFunction or TargetData should probably carry an alignment
125 // field for functions that we can query here instead of hard coding 4 in both
126 // the object writer and asm printer.
Nate Begemaneb883af2006-08-23 21:08:52 +0000127 unsigned Align = 4;
128
129 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000130 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000131
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000132 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000133 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000134 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000135 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000136
137 // FIXME: Using MOS->size directly here instead of calculating it from the
138 // output buffer size (impossible because the code emitter deals only in raw
139 // bytes) forces us to manually synchronize size and write padding zero bytes
140 // to the output buffer for all non-text sections. For text sections, we do
141 // not synchonize the output buffer, and we just blow up if anyone tries to
142 // write non-code to it. An assert should probably be added to
143 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000144 CurBufferPtr = BufferBegin + MOS->size;
145
146 // Upgrade the section alignment if required.
147 if (MOS->align < Align) MOS->align = Align;
148
Nate Begeman019f8512006-09-10 23:03:44 +0000149 // Clear per-function data structures.
150 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000151 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000152 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000153 MBBLocations.clear();
154}
155
156/// finishFunction - This callback is invoked after the function is completely
157/// finished.
158bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000159 // Get the Mach-O Section that this function belongs in.
160 MachOWriter::MachOSection *MOS = MOW.getTextSection();
161
Nate Begemaneb883af2006-08-23 21:08:52 +0000162 MOS->size += CurBufferPtr - BufferBegin;
163
164 // Get a symbol for the function to add to the symbol table
Nate Begemand2030e62006-08-26 15:46:34 +0000165 const GlobalValue *FuncV = F.getFunction();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000166 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, MOW.TM);
Nate Begeman94be2482006-09-08 22:42:09 +0000167
Nate Begeman019f8512006-09-10 23:03:44 +0000168 // Emit constant pool to appropriate section(s)
169 emitConstantPool(F.getConstantPool());
170
171 // Emit jump tables to appropriate section
172 emitJumpTables(F.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000173
Nate Begeman019f8512006-09-10 23:03:44 +0000174 // If we have emitted any relocations to function-specific objects such as
175 // basic blocks, constant pools entries, or jump tables, record their
176 // addresses now so that we can rewrite them with the correct addresses
177 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000178 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
179 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000180 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000181
Nate Begemaneb883af2006-08-23 21:08:52 +0000182 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000183 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000184 MR.setConstantVal(MOS->Index);
185 MR.setResultPointer((void*)Addr);
186 } else if (MR.isJumpTableIndex()) {
187 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
188 MR.setConstantVal(MOW.getJumpTableSection()->Index);
189 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000190 } else if (MR.isConstantPoolIndex()) {
191 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000192 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
193 MR.setResultPointer((void*)Addr);
194 } else if (!MR.isGlobalValue()) {
195 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000196 }
Nate Begeman019f8512006-09-10 23:03:44 +0000197 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000198 }
199 Relocations.clear();
200
201 // Finally, add it to the symtab.
202 MOW.SymbolTable.push_back(FnSym);
203 return false;
204}
205
Nate Begeman019f8512006-09-10 23:03:44 +0000206/// emitConstantPool - For each constant pool entry, figure out which section
207/// the constant should live in, allocate space for it, and emit it to the
208/// Section data buffer.
209void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000210 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
211 if (CP.empty()) return;
212
213 // FIXME: handle PIC codegen
214 bool isPIC = MOW.TM.getRelocationModel() == Reloc::PIC_;
215 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
216
217 // Although there is no strict necessity that I am aware of, we will do what
218 // gcc for OS X does and put each constant pool entry in a section of constant
219 // objects of a certain size. That means that float constants go in the
220 // literal4 section, and double objects go in literal8, etc.
221 //
222 // FIXME: revisit this decision if we ever do the "stick everything into one
223 // "giant object for PIC" optimization.
224 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
225 const Type *Ty = CP[i].getType();
226 unsigned Size = MOW.TM.getTargetData()->getTypeSize(Ty);
227
228 MachOWriter::MachOSection *Sec = MOW.getConstSection(Ty);
229 CPLocations.push_back(Sec->SectionData.size());
230 CPSections.push_back(Sec->Index);
231
232 // FIXME: remove when we have unified size + output buffer
233 Sec->size += Size;
234
235 // Allocate space in the section for the global.
236 // FIXME: need alignment?
237 // FIXME: share between here and AddSymbolToSection?
238 for (unsigned j = 0; j < Size; ++j)
239 MOW.outbyte(Sec->SectionData, 0);
240
241 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
242 MOW.TM.getTargetData(), Sec->Relocations);
243 }
Nate Begeman019f8512006-09-10 23:03:44 +0000244}
245
246/// emitJumpTables - Emit all the jump tables for a given jump table info
247/// record to the appropriate section.
248void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
249 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
250 if (JT.empty()) return;
251
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000252 // FIXME: handle PIC codegen
Nate Begeman019f8512006-09-10 23:03:44 +0000253 bool isPIC = MOW.TM.getRelocationModel() == Reloc::PIC_;
254 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
255
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000256 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
257 unsigned TextSecIndex = MOW.getTextSection()->Index;
Nate Begeman019f8512006-09-10 23:03:44 +0000258
259 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
260 // For each jump table, record its offset from the start of the section,
261 // reserve space for the relocations to the MBBs, and add the relocations.
262 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000263 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000264 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000265 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000266 MBBs[mi]));
267 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000268 MR.setConstantVal(TextSecIndex);
269 Sec->Relocations.push_back(MR);
270 MOW.outaddr(Sec->SectionData, 0);
Nate Begeman019f8512006-09-10 23:03:44 +0000271 }
272 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000273 // FIXME: remove when we have unified size + output buffer
274 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000275}
276
Nate Begemaneb883af2006-08-23 21:08:52 +0000277//===----------------------------------------------------------------------===//
278// MachOWriter Implementation
279//===----------------------------------------------------------------------===//
280
281MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000282 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
283 isLittleEndian = TM.getTargetData()->isLittleEndian();
284
285 // Create the machine code emitter object for this target.
286 MCE = new MachOCodeEmitter(*this);
287}
288
289MachOWriter::~MachOWriter() {
290 delete MCE;
291}
292
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000293void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000294 const Type *Ty = GV->getType()->getElementType();
295 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000296 unsigned Align = GV->getAlignment();
297 if (Align == 0)
298 Align = TM.getTargetData()->getTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000299
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000300 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
301
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000302 // Reserve space in the .bss section for this symbol while maintaining the
303 // desired section alignment, which must be at least as much as required by
304 // this symbol.
305 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000306 uint64_t OrigSize = Sec->size;
307 Align = Log2_32(Align);
308 Sec->align = std::max(unsigned(Sec->align), Align);
309 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
310
311 // Add alignment padding to buffer as well.
312 // FIXME: remove when we have unified size + output buffer
313 unsigned AlignedSize = Sec->size - OrigSize;
314 for (unsigned i = 0; i < AlignedSize; ++i)
315 outbyte(Sec->SectionData, 0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000316 }
317 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000318 // FIXME: remove when we have unified size + output buffer
319 Sym.n_value = Sec->size;
320 Sec->size += Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000321 SymbolTable.push_back(Sym);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000322
323 // Now that we know what section the GlovalVariable is going to be emitted
324 // into, update our mappings.
325 // FIXME: We may also need to update this when outputting non-GlobalVariable
326 // GlobalValues such as functions.
327 GVSection[GV] = Sec;
328 GVOffset[GV] = Sec->SectionData.size();
329
330 // Allocate space in the section for the global.
331 for (unsigned i = 0; i < Size; ++i)
332 outbyte(Sec->SectionData, 0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000333}
334
Nate Begemaneb883af2006-08-23 21:08:52 +0000335void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000336 const Type *Ty = GV->getType()->getElementType();
337 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
338 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000339
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000340 // If this global has a zero initializer, it is part of the .bss or common
341 // section.
342 if (NoInit || GV->getInitializer()->isNullValue()) {
343 // If this global is part of the common block, add it now. Variables are
344 // part of the common block if they are zero initialized and allowed to be
345 // merged with other symbols.
346 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000347 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000348 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
349 // bytes of the symbol.
350 ExtOrCommonSym.n_value = Size;
351 // If the symbol is external, we'll put it on a list of symbols whose
352 // addition to the symbol table is being pended until we find a reference
353 if (NoInit)
354 PendingSyms.push_back(ExtOrCommonSym);
355 else
356 SymbolTable.push_back(ExtOrCommonSym);
357 return;
358 }
359 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000360 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000361 AddSymbolToSection(BSS, GV);
362 return;
363 }
364
365 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
366 // 16 bytes, or a cstring. Other read only data goes into a regular const
367 // section. Read-write data goes in the data section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000368 MachOSection *Sec = GV->isConstant() ? getConstSection(Ty) : getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000369 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000370 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
371 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000372}
373
374
375bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
376 // Nothing to do here, this is all done through the MCE object.
377 return false;
378}
379
380bool MachOWriter::doInitialization(Module &M) {
381 // Set the magic value, now that we know the pointer size and endianness
382 Header.setMagic(isLittleEndian, is64Bit);
383
384 // Set the file type
385 // FIXME: this only works for object files, we do not support the creation
386 // of dynamic libraries or executables at this time.
387 Header.filetype = MachOHeader::MH_OBJECT;
388
389 Mang = new Mangler(M);
390 return false;
391}
392
393/// doFinalization - Now that the module has been completely processed, emit
394/// the Mach-O file to 'O'.
395bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000396 // FIXME: we don't handle debug info yet, we should probably do that.
397
Nate Begemaneb883af2006-08-23 21:08:52 +0000398 // Okay, the.text section has been completed, build the .data, .bss, and
399 // "common" sections next.
400 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
401 I != E; ++I)
402 EmitGlobal(I);
403
404 // Emit the header and load commands.
405 EmitHeaderAndLoadCommands();
406
Nate Begeman019f8512006-09-10 23:03:44 +0000407 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000408 EmitSections();
409
Nate Begemand2030e62006-08-26 15:46:34 +0000410 // Write the symbol table and the string table to the end of the file.
411 O.write((char*)&SymT[0], SymT.size());
412 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000413
414 // We are done with the abstract symbols.
415 SectionList.clear();
416 SymbolTable.clear();
417 DynamicSymbolTable.clear();
418
419 // Release the name mangler object.
420 delete Mang; Mang = 0;
421 return false;
422}
423
424void MachOWriter::EmitHeaderAndLoadCommands() {
425 // Step #0: Fill in the segment load command size, since we need it to figure
426 // out the rest of the header fields
427 MachOSegment SEG("", is64Bit);
428 SEG.nsects = SectionList.size();
429 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000430 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000431
432 // Step #1: calculate the number of load commands. We always have at least
433 // one, for the LC_SEGMENT load command, plus two for the normal
434 // and dynamic symbol tables, if there are any symbols.
435 Header.ncmds = SymbolTable.empty() ? 1 : 3;
436
437 // Step #2: calculate the size of the load commands
438 Header.sizeofcmds = SEG.cmdsize;
439 if (!SymbolTable.empty())
440 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
441
442 // Step #3: write the header to the file
443 // Local alias to shortenify coming code.
444 DataBuffer &FH = Header.HeaderData;
445 outword(FH, Header.magic);
446 outword(FH, Header.cputype);
447 outword(FH, Header.cpusubtype);
448 outword(FH, Header.filetype);
449 outword(FH, Header.ncmds);
450 outword(FH, Header.sizeofcmds);
451 outword(FH, Header.flags);
452 if (is64Bit)
453 outword(FH, Header.reserved);
454
455 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000456 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000457 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000458 SEG.filesize += (*I)->size;
459
Nate Begemaneb883af2006-08-23 21:08:52 +0000460 SEG.vmsize = SEG.filesize;
461 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
462
463 outword(FH, SEG.cmd);
464 outword(FH, SEG.cmdsize);
465 outstring(FH, SEG.segname, 16);
466 outaddr(FH, SEG.vmaddr);
467 outaddr(FH, SEG.vmsize);
468 outaddr(FH, SEG.fileoff);
469 outaddr(FH, SEG.filesize);
470 outword(FH, SEG.maxprot);
471 outword(FH, SEG.initprot);
472 outword(FH, SEG.nsects);
473 outword(FH, SEG.flags);
474
Nate Begeman94be2482006-09-08 22:42:09 +0000475 // Step #5: Finish filling in the fields of the MachOSections
476 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000477 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000478 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000479 MachOSection *MOS = *I;
480 MOS->addr = currentAddr;
481 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000482
Nate Begeman94be2482006-09-08 22:42:09 +0000483 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000484 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000485 }
486
487 // Step #6: Calculate the number of relocations for each section and write out
488 // the section commands for each section
489 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000490 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000491 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000492 MachOSection *MOS = *I;
493 // Convert the relocations to target-specific relocations, and fill in the
494 // relocation offset for this section.
495 CalculateRelocations(*MOS);
496 MOS->reloff = MOS->nreloc ? currentAddr : 0;
497 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000498
499 // write the finalized section command to the output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000500 outstring(FH, MOS->sectname, 16);
501 outstring(FH, MOS->segname, 16);
502 outaddr(FH, MOS->addr);
503 outaddr(FH, MOS->size);
504 outword(FH, MOS->offset);
505 outword(FH, MOS->align);
506 outword(FH, MOS->reloff);
507 outword(FH, MOS->nreloc);
508 outword(FH, MOS->flags);
509 outword(FH, MOS->reserved1);
510 outword(FH, MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000511 if (is64Bit)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000512 outword(FH, MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000513 }
514
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000515 // Step #7: Emit the symbol table to temporary buffers, so that we know the
516 // size of the string table when we write the next load command.
517 BufferSymbolAndStringTable();
518
519 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000520 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000521 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000522 SymTab.stroff = SymTab.symoff + SymT.size();
523 SymTab.strsize = StrT.size();
Nate Begemaneb883af2006-08-23 21:08:52 +0000524 outword(FH, SymTab.cmd);
525 outword(FH, SymTab.cmdsize);
526 outword(FH, SymTab.symoff);
527 outword(FH, SymTab.nsyms);
528 outword(FH, SymTab.stroff);
529 outword(FH, SymTab.strsize);
530
531 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000532 // We should probably just update these in BufferSymbolAndStringTable since
533 // thats where we're partitioning up the different kinds of symbols.
Nate Begemaneb883af2006-08-23 21:08:52 +0000534 outword(FH, DySymTab.cmd);
535 outword(FH, DySymTab.cmdsize);
536 outword(FH, DySymTab.ilocalsym);
537 outword(FH, DySymTab.nlocalsym);
538 outword(FH, DySymTab.iextdefsym);
539 outword(FH, DySymTab.nextdefsym);
540 outword(FH, DySymTab.iundefsym);
541 outword(FH, DySymTab.nundefsym);
542 outword(FH, DySymTab.tocoff);
543 outword(FH, DySymTab.ntoc);
544 outword(FH, DySymTab.modtaboff);
545 outword(FH, DySymTab.nmodtab);
546 outword(FH, DySymTab.extrefsymoff);
547 outword(FH, DySymTab.nextrefsyms);
548 outword(FH, DySymTab.indirectsymoff);
549 outword(FH, DySymTab.nindirectsyms);
550 outword(FH, DySymTab.extreloff);
551 outword(FH, DySymTab.nextrel);
552 outword(FH, DySymTab.locreloff);
553 outword(FH, DySymTab.nlocrel);
554
555 O.write((char*)&FH[0], FH.size());
556}
557
558/// EmitSections - Now that we have constructed the file header and load
559/// commands, emit the data for each section to the file.
560void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000561 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000562 E = SectionList.end(); I != E; ++I)
563 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000564 O.write((char*)&(*I)->SectionData[0], (*I)->size);
565 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000566 E = SectionList.end(); I != E; ++I)
567 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000568 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000569}
570
Nate Begemand2030e62006-08-26 15:46:34 +0000571/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
572/// a local symbol rather than an external symbol.
573bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000574 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000575}
576
Nate Begemand2030e62006-08-26 15:46:34 +0000577/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
578/// defined in this module.
579bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
580 // FIXME: Do N_ABS or N_INDR count as defined?
581 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
582}
Nate Begemaneb883af2006-08-23 21:08:52 +0000583
Nate Begemand2030e62006-08-26 15:46:34 +0000584/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
585/// each a string table index so that they appear in the correct order in the
586/// output file.
587void MachOWriter::BufferSymbolAndStringTable() {
588 // The order of the symbol table is:
589 // 1. local symbols
590 // 2. defined external symbols (sorted by name)
591 // 3. undefined external symbols (sorted by name)
592
593 // Sort the symbols by name, so that when we partition the symbols by scope
594 // of definition, we won't have to sort by name within each partition.
595 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
596
597 // Parition the symbol table entries so that all local symbols come before
598 // all symbols with external linkage. { 1 | 2 3 }
599 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
600
601 // Advance iterator to beginning of external symbols and partition so that
602 // all external symbols defined in this module come before all external
603 // symbols defined elsewhere. { 1 | 2 | 3 }
604 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
605 E = SymbolTable.end(); I != E; ++I) {
606 if (!PartitionByLocal(*I)) {
607 std::partition(I, E, PartitionByDefined);
608 break;
609 }
610 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000611
612 // Calculate the starting index for each of the local, extern defined, and
613 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
614 // load command.
615 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
616 E = SymbolTable.end(); I != E; ++I) {
617 if (PartitionByLocal(*I)) {
618 ++DySymTab.nlocalsym;
619 ++DySymTab.iextdefsym;
620 } else if (PartitionByDefined(*I)) {
621 ++DySymTab.nextdefsym;
622 ++DySymTab.iundefsym;
623 } else {
624 ++DySymTab.nundefsym;
625 }
626 }
Nate Begemand2030e62006-08-26 15:46:34 +0000627
Nate Begemaneb883af2006-08-23 21:08:52 +0000628 // Write out a leading zero byte when emitting string table, for n_strx == 0
629 // which means an empty string.
Nate Begemand2030e62006-08-26 15:46:34 +0000630 outbyte(StrT, 0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000631
Nate Begemand2030e62006-08-26 15:46:34 +0000632 // The order of the string table is:
633 // 1. strings for external symbols
634 // 2. strings for local symbols
635 // Since this is the opposite order from the symbol table, which we have just
636 // sorted, we can walk the symbol table backwards to output the string table.
637 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
638 E = SymbolTable.rend(); I != E; ++I) {
639 if (I->GVName == "") {
640 I->n_strx = 0;
641 } else {
642 I->n_strx = StrT.size();
643 outstring(StrT, I->GVName, I->GVName.length()+1);
644 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000645 }
Nate Begemand2030e62006-08-26 15:46:34 +0000646
647 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
648 E = SymbolTable.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000649 // Add the section base address to the section offset in the n_value field
650 // to calculate the full address.
651 // FIXME: handle symbols where the n_value field is not the address
652 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
653 if (GV && GVSection[GV])
654 I->n_value += GVSection[GV]->addr;
655
Nate Begemand2030e62006-08-26 15:46:34 +0000656 // Emit nlist to buffer
657 outword(SymT, I->n_strx);
658 outbyte(SymT, I->n_type);
659 outbyte(SymT, I->n_sect);
660 outhalf(SymT, I->n_desc);
661 outaddr(SymT, I->n_value);
662 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000663}
Nate Begeman94be2482006-09-08 22:42:09 +0000664
Nate Begeman019f8512006-09-10 23:03:44 +0000665/// CalculateRelocations - For each MachineRelocation in the current section,
666/// calculate the index of the section containing the object to be relocated,
667/// and the offset into that section. From this information, create the
668/// appropriate target-specific MachORelocation type and add buffer it to be
669/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000670void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000671 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000672 MachineRelocation &MR = MOS.Relocations[i];
673 unsigned TargetSection = MR.getConstantVal();
674
675 // Since we may not have seen the GlobalValue we were interested in yet at
676 // the time we emitted the relocation for it, fix it up now so that it
677 // points to the offset into the correct section.
678 if (MR.isGlobalValue()) {
679 GlobalValue *GV = MR.getGlobalValue();
680 MachOSection *MOSPtr = GVSection[GV];
681 intptr_t offset = GVOffset[GV];
682
683 assert(MOSPtr && "Trying to relocate unknown global!");
684
685 TargetSection = MOSPtr->Index;
686 MR.setResultPointer((void*)offset);
687 }
688
689 GetTargetRelocation(MR, MOS, *SectionList[TargetSection-1]);
Nate Begeman019f8512006-09-10 23:03:44 +0000690 }
Nate Begeman019f8512006-09-10 23:03:44 +0000691}
692
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000693// InitMem - Write the value of a Constant to the specified memory location,
694// converting it into bytes and relocations.
695void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
696 const TargetData *TD,
697 std::vector<MachineRelocation> &MRs) {
698 typedef std::pair<const Constant*, intptr_t> CPair;
699 std::vector<CPair> WorkList;
700
701 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
702
703 while (!WorkList.empty()) {
704 const Constant *PC = WorkList.back().first;
705 intptr_t PA = WorkList.back().second;
706 WorkList.pop_back();
707
708 if (isa<UndefValue>(PC)) {
709 continue;
710 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
711 unsigned ElementSize =
712 CP->getType()->getElementType()->getPrimitiveSize();
713 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
714 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
715 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
716 //
717 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
718 //
719 switch (CE->getOpcode()) {
720 case Instruction::GetElementPtr:
721 case Instruction::Add:
722 default:
723 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
724 abort();
725 break;
726 }
727 } else if (PC->getType()->isFirstClassType()) {
728 unsigned char *ptr = (unsigned char *)PA;
729 uint64_t val;
730
731 switch (PC->getType()->getTypeID()) {
732 case Type::BoolTyID:
Reid Spencer47857812006-12-31 05:55:36 +0000733 case Type::Int8TyID:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000734 ptr[0] = cast<ConstantInt>(PC)->getZExtValue();
735 break;
Reid Spencer47857812006-12-31 05:55:36 +0000736 case Type::Int16TyID:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000737 val = cast<ConstantInt>(PC)->getZExtValue();
738 if (TD->isBigEndian())
739 val = ByteSwap_16(val);
740 ptr[0] = val;
741 ptr[1] = val >> 8;
742 break;
Reid Spencer47857812006-12-31 05:55:36 +0000743 case Type::Int32TyID:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000744 case Type::FloatTyID:
745 if (PC->getType()->getTypeID() == Type::FloatTyID) {
746 val = FloatToBits(cast<ConstantFP>(PC)->getValue());
747 } else {
748 val = cast<ConstantInt>(PC)->getZExtValue();
749 }
750 if (TD->isBigEndian())
751 val = ByteSwap_32(val);
752 ptr[0] = val;
753 ptr[1] = val >> 8;
754 ptr[2] = val >> 16;
755 ptr[3] = val >> 24;
756 break;
757 case Type::DoubleTyID:
Reid Spencer47857812006-12-31 05:55:36 +0000758 case Type::Int64TyID:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000759 if (PC->getType()->getTypeID() == Type::DoubleTyID) {
760 val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
761 } else {
762 val = cast<ConstantInt>(PC)->getZExtValue();
763 }
764 if (TD->isBigEndian())
765 val = ByteSwap_64(val);
766 ptr[0] = val;
767 ptr[1] = val >> 8;
768 ptr[2] = val >> 16;
769 ptr[3] = val >> 24;
770 ptr[4] = val >> 32;
771 ptr[5] = val >> 40;
772 ptr[6] = val >> 48;
773 ptr[7] = val >> 56;
774 break;
775 case Type::PointerTyID:
776 if (isa<ConstantPointerNull>(C))
777 memset(ptr, 0, TD->getPointerSize());
778 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(C))
779 // FIXME: what about function stubs?
780 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
781 MachineRelocation::VANILLA,
782 const_cast<GlobalValue*>(GV)));
783 else
784 assert(0 && "Unknown constant pointer type!");
785 break;
786 default:
787 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
788 abort();
789 }
790 } else if (isa<ConstantAggregateZero>(PC)) {
791 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
792 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
793 unsigned ElementSize =
794 CPA->getType()->getElementType()->getPrimitiveSize();
795 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
796 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
797 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
798 const StructLayout *SL =
799 TD->getStructLayout(cast<StructType>(CPS->getType()));
800 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
801 WorkList.push_back(CPair(CPS->getOperand(i), PA+SL->MemberOffsets[i]));
802 } else {
803 cerr << "Bad Type: " << *PC->getType() << "\n";
804 assert(0 && "Unknown constant type to initialize memory with!");
805 }
806 }
807}
808
809MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
810 TargetMachine &TM) :
811 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
812 n_desc(0), n_value(0) {
813
814 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
815
Nate Begeman94be2482006-09-08 22:42:09 +0000816 switch (GV->getLinkage()) {
817 default:
818 assert(0 && "Unexpected linkage type!");
819 break;
820 case GlobalValue::WeakLinkage:
821 case GlobalValue::LinkOnceLinkage:
822 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
823 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000824 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000825 n_type |= N_EXT;
826 break;
827 case GlobalValue::InternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000828 GVName = TAI->getPrivateGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000829 break;
830 }
831}