1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the target-independent Mach-O writer. This file writes
11 // out the Mach-O file in the following order:
13 // #1 FatHeader (universal-only)
14 // #2 FatArch (universal-only, 1 per universal arch)
23 //===----------------------------------------------------------------------===//
25 #include "llvm/Module.h"
26 #include "llvm/CodeGen/MachineCodeEmitter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineRelocation.h"
29 #include "llvm/CodeGen/MachOWriter.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/MathExtras.h"
36 //===----------------------------------------------------------------------===//
37 // MachOCodeEmitter Implementation
38 //===----------------------------------------------------------------------===//
41 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
42 /// for functions to the Mach-O file.
43 class MachOCodeEmitter : public MachineCodeEmitter {
46 /// MOS - The current section we're writing to
47 MachOWriter::MachOSection *MOS;
49 /// Relocations - These are the relocations that the function needs, as
51 std::vector<MachineRelocation> Relocations;
53 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
54 /// It is filled in by the StartMachineBasicBlock callback and queried by
55 /// the getMachineBasicBlockAddress callback.
56 std::vector<intptr_t> MBBLocations;
59 MachOCodeEmitter(MachOWriter &mow) : MOW(mow) {}
61 void startFunction(MachineFunction &F);
62 bool finishFunction(MachineFunction &F);
64 void addRelocation(const MachineRelocation &MR) {
65 Relocations.push_back(MR);
68 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
69 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
70 MBBLocations.resize((MBB->getNumber()+1)*2);
71 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
74 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
75 assert(0 && "CP not implementated yet!");
78 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
79 assert(0 && "JT not implementated yet!");
83 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
84 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
85 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
86 return MBBLocations[MBB->getNumber()];
89 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
90 void startFunctionStub(unsigned StubSize) {
91 assert(0 && "JIT specific function called!");
94 void *finishFunctionStub(const Function *F) {
95 assert(0 && "JIT specific function called!");
102 /// startFunction - This callback is invoked when a new machine function is
103 /// about to be emitted.
104 void MachOCodeEmitter::startFunction(MachineFunction &F) {
105 // Align the output buffer to the appropriate alignment, power of 2.
106 // FIXME: GENERICIZE!!
109 // Get the Mach-O Section that this function belongs in.
110 MOS = &MOW.getTextSection();
112 // FIXME: better memory management
113 MOS->SectionData.reserve(4096);
114 BufferBegin = &(MOS->SectionData[0]);
115 BufferEnd = BufferBegin + MOS->SectionData.capacity();
116 CurBufferPtr = BufferBegin + MOS->size;
118 // Upgrade the section alignment if required.
119 if (MOS->align < Align) MOS->align = Align;
121 // Make sure we only relocate to this function's MBBs.
122 MBBLocations.clear();
125 /// finishFunction - This callback is invoked after the function is completely
127 bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
128 MOS->size += CurBufferPtr - BufferBegin;
130 // Get a symbol for the function to add to the symbol table
131 MachOWriter::MachOSym FnSym(F.getFunction(), MOS->Index);
133 // Figure out the binding (linkage) of the symbol.
134 switch (F.getFunction()->getLinkage()) {
136 // appending linkage is illegal for functions.
137 assert(0 && "Unknown linkage type!");
138 case GlobalValue::ExternalLinkage:
139 FnSym.n_type |= MachOWriter::MachOSym::N_EXT;
141 case GlobalValue::InternalLinkage:
145 // Resolve the function's relocations either to concrete pointers in the case
146 // of branches from one block to another, or to target relocation entries.
147 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
148 MachineRelocation &MR = Relocations[i];
149 if (MR.isBasicBlock()) {
150 void *MBBAddr = (void *)getMachineBasicBlockAddress(MR.getBasicBlock());
151 MR.setResultPointer(MBBAddr);
152 MOW.TM.getJITInfo()->relocate(BufferBegin, &MR, 1, 0);
153 // FIXME: we basically want the JITInfo relocate() function to rewrite
154 // this guy right now, so we just write the correct displacement
157 // isString | isGV | isCPI | isJTI
158 // FIXME: do something smart here. We won't be able to relocate these
159 // until the sections are all layed out, but we still need to
160 // record them. Maybe emit TargetRelocations and then resolve
161 // those at file writing time?
162 std::cerr << "whee!\n";
167 // Finally, add it to the symtab.
168 MOW.SymbolTable.push_back(FnSym);
172 //===----------------------------------------------------------------------===//
173 // MachOWriter Implementation
174 //===----------------------------------------------------------------------===//
176 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
177 // FIXME: set cpu type and cpu subtype somehow from TM
178 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
179 isLittleEndian = TM.getTargetData()->isLittleEndian();
181 // Create the machine code emitter object for this target.
182 MCE = new MachOCodeEmitter(*this);
185 MachOWriter::~MachOWriter() {
189 void MachOWriter::AddSymbolToSection(MachOSection &Sec, GlobalVariable *GV) {
190 const Type *Ty = GV->getType()->getElementType();
191 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
192 unsigned Align = Log2_32(TM.getTargetData()->getTypeAlignment(Ty));
194 MachOSym Sym(GV, Sec.Index);
195 // Reserve space in the .bss section for this symbol while maintaining the
196 // desired section alignment, which must be at least as much as required by
199 Sec.align = std::max(Sec.align, Align);
200 Sec.size = (Sec.size + Align - 1) & ~(Align-1);
202 // Record the offset of the symbol, and then allocate space for it.
203 Sym.n_value = Sec.size;
206 switch (GV->getLinkage()) {
207 default: // weak/linkonce handled above
208 assert(0 && "Unexpected linkage type!");
209 case GlobalValue::ExternalLinkage:
210 Sym.n_type |= MachOSym::N_EXT;
212 case GlobalValue::InternalLinkage:
215 SymbolTable.push_back(Sym);
218 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
219 const Type *Ty = GV->getType()->getElementType();
220 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
221 bool NoInit = !GV->hasInitializer();
223 // If this global has a zero initializer, it is part of the .bss or common
225 if (NoInit || GV->getInitializer()->isNullValue()) {
226 // If this global is part of the common block, add it now. Variables are
227 // part of the common block if they are zero initialized and allowed to be
228 // merged with other symbols.
229 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
230 MachOWriter::MachOSym ExtOrCommonSym(GV, MachOSym::NO_SECT);
231 ExtOrCommonSym.n_type |= MachOSym::N_EXT;
232 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
233 // bytes of the symbol.
234 ExtOrCommonSym.n_value = Size;
235 // If the symbol is external, we'll put it on a list of symbols whose
236 // addition to the symbol table is being pended until we find a reference
238 PendingSyms.push_back(ExtOrCommonSym);
240 SymbolTable.push_back(ExtOrCommonSym);
243 // Otherwise, this symbol is part of the .bss section.
244 MachOSection &BSS = getBSSSection();
245 AddSymbolToSection(BSS, GV);
249 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
250 // 16 bytes, or a cstring. Other read only data goes into a regular const
251 // section. Read-write data goes in the data section.
252 MachOSection &Sec = GV->isConstant() ? getConstSection(Ty) : getDataSection();
253 AddSymbolToSection(Sec, GV);
255 // FIXME: actually write out the initializer to the section. This will
256 // require ExecutionEngine's InitializeMemory() function, which will need to
257 // be enhanced to support relocations.
261 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
262 // Nothing to do here, this is all done through the MCE object.
266 bool MachOWriter::doInitialization(Module &M) {
267 // Set the magic value, now that we know the pointer size and endianness
268 Header.setMagic(isLittleEndian, is64Bit);
271 // FIXME: this only works for object files, we do not support the creation
272 // of dynamic libraries or executables at this time.
273 Header.filetype = MachOHeader::MH_OBJECT;
275 Mang = new Mangler(M);
279 /// doFinalization - Now that the module has been completely processed, emit
280 /// the Mach-O file to 'O'.
281 bool MachOWriter::doFinalization(Module &M) {
282 // Okay, the.text section has been completed, build the .data, .bss, and
283 // "common" sections next.
284 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
288 // Emit the header and load commands.
289 EmitHeaderAndLoadCommands();
291 // Emit the text and data sections.
294 // Emit the relocation entry data for each section.
295 // FIXME: presumably this should be a virtual method, since different targets
296 // have different relocation types.
299 // Emit the symbol table.
300 // FIXME: we don't handle debug info yet, we should probably do that.
303 // Emit the string table for the sections we have.
306 // We are done with the abstract symbols.
309 DynamicSymbolTable.clear();
311 // Release the name mangler object.
312 delete Mang; Mang = 0;
316 void MachOWriter::EmitHeaderAndLoadCommands() {
317 // Step #0: Fill in the segment load command size, since we need it to figure
318 // out the rest of the header fields
319 MachOSegment SEG("", is64Bit);
320 SEG.nsects = SectionList.size();
321 SEG.cmdsize = SEG.cmdSize(is64Bit) +
322 SEG.nsects * SectionList.begin()->cmdSize(is64Bit);
324 // Step #1: calculate the number of load commands. We always have at least
325 // one, for the LC_SEGMENT load command, plus two for the normal
326 // and dynamic symbol tables, if there are any symbols.
327 Header.ncmds = SymbolTable.empty() ? 1 : 3;
329 // Step #2: calculate the size of the load commands
330 Header.sizeofcmds = SEG.cmdsize;
331 if (!SymbolTable.empty())
332 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
334 // Step #3: write the header to the file
335 // Local alias to shortenify coming code.
336 DataBuffer &FH = Header.HeaderData;
337 outword(FH, Header.magic);
338 outword(FH, Header.cputype);
339 outword(FH, Header.cpusubtype);
340 outword(FH, Header.filetype);
341 outword(FH, Header.ncmds);
342 outword(FH, Header.sizeofcmds);
343 outword(FH, Header.flags);
345 outword(FH, Header.reserved);
347 // Step #4: Finish filling in the segment load command and write it out
348 for (std::list<MachOSection>::iterator I = SectionList.begin(),
349 E = SectionList.end(); I != E; ++I)
350 SEG.filesize += I->size;
351 SEG.vmsize = SEG.filesize;
352 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
354 outword(FH, SEG.cmd);
355 outword(FH, SEG.cmdsize);
356 outstring(FH, SEG.segname, 16);
357 outaddr(FH, SEG.vmaddr);
358 outaddr(FH, SEG.vmsize);
359 outaddr(FH, SEG.fileoff);
360 outaddr(FH, SEG.filesize);
361 outword(FH, SEG.maxprot);
362 outword(FH, SEG.initprot);
363 outword(FH, SEG.nsects);
364 outword(FH, SEG.flags);
366 // Step #5: Write out the section commands for each section
367 for (std::list<MachOSection>::iterator I = SectionList.begin(),
368 E = SectionList.end(); I != E; ++I) {
369 I->offset = SEG.fileoff; // FIXME: separate offset
370 outstring(FH, I->sectname, 16);
371 outstring(FH, I->segname, 16);
372 outaddr(FH, I->addr);
373 outaddr(FH, I->size);
374 outword(FH, I->offset);
375 outword(FH, I->align);
376 outword(FH, I->reloff);
377 outword(FH, I->nreloc);
378 outword(FH, I->flags);
379 outword(FH, I->reserved1);
380 outword(FH, I->reserved2);
382 outword(FH, I->reserved3);
385 // Step #6: Emit LC_SYMTAB/LC_DYSYMTAB load commands
386 // FIXME: We'll need to scan over the symbol table and possibly do the sort
387 // here so that we can set the proper indices in the dysymtab load command for
388 // the index and number of external symbols defined in this module.
389 // FIXME: We'll also need to scan over all the symbols so that we can
390 // calculate the size of the string table.
391 // FIXME: add size of relocs
392 SymTab.symoff = SEG.fileoff + SEG.filesize;
393 SymTab.nsyms = SymbolTable.size();
394 SymTab.stroff = SymTab.symoff + SymTab.nsyms * MachOSym::entrySize();
396 outword(FH, SymTab.cmd);
397 outword(FH, SymTab.cmdsize);
398 outword(FH, SymTab.symoff);
399 outword(FH, SymTab.nsyms);
400 outword(FH, SymTab.stroff);
401 outword(FH, SymTab.strsize);
403 // FIXME: set DySymTab fields appropriately
404 outword(FH, DySymTab.cmd);
405 outword(FH, DySymTab.cmdsize);
406 outword(FH, DySymTab.ilocalsym);
407 outword(FH, DySymTab.nlocalsym);
408 outword(FH, DySymTab.iextdefsym);
409 outword(FH, DySymTab.nextdefsym);
410 outword(FH, DySymTab.iundefsym);
411 outword(FH, DySymTab.nundefsym);
412 outword(FH, DySymTab.tocoff);
413 outword(FH, DySymTab.ntoc);
414 outword(FH, DySymTab.modtaboff);
415 outword(FH, DySymTab.nmodtab);
416 outword(FH, DySymTab.extrefsymoff);
417 outword(FH, DySymTab.nextrefsyms);
418 outword(FH, DySymTab.indirectsymoff);
419 outword(FH, DySymTab.nindirectsyms);
420 outword(FH, DySymTab.extreloff);
421 outword(FH, DySymTab.nextrel);
422 outword(FH, DySymTab.locreloff);
423 outword(FH, DySymTab.nlocrel);
425 O.write((char*)&FH[0], FH.size());
428 /// EmitSections - Now that we have constructed the file header and load
429 /// commands, emit the data for each section to the file.
430 void MachOWriter::EmitSections() {
431 for (std::list<MachOSection>::iterator I = SectionList.begin(),
432 E = SectionList.end(); I != E; ++I) {
433 O.write((char*)&I->SectionData[0], I->size);
437 void MachOWriter::EmitRelocations() {
438 // FIXME: this should probably be a pure virtual function, since the
439 // relocation types and layout of the relocations themselves are target
443 /// EmitSymbolTable - Sort the symbols we encountered and assign them each a
444 /// string table index so that they appear in the correct order in the output
446 void MachOWriter::EmitSymbolTable() {
447 // The order of the symbol table is:
449 // defined external symbols (sorted by name)
450 // undefined external symbols (sorted by name)
453 // FIXME: enforce the above ordering, presumably by sorting by name,
454 // then partitioning twice.
455 unsigned stringIndex;
456 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
457 E = SymbolTable.end(); I != E; ++I) {
458 // FIXME: remove when we actually calculate these correctly
460 StringTable.push_back(Mang->getValueName(I->GV));
461 // Emit nlist to buffer
462 outword(ST, I->n_strx);
463 outbyte(ST, I->n_type);
464 outbyte(ST, I->n_sect);
465 outhalf(ST, I->n_desc);
466 outaddr(ST, I->n_value);
469 O.write((char*)&ST[0], ST.size());
472 /// EmitStringTable - This method adds and emits a section for the Mach-O
474 void MachOWriter::EmitStringTable() {
475 // The order of the string table is:
476 // strings for external symbols
477 // strings for local symbols
478 // This is the symbol table, but backwards. This allows us to avoid a sorting
479 // the symbol table again; all we have to do is use a reverse iterator.
482 // Write out a leading zero byte when emitting string table, for n_strx == 0
483 // which means an empty string.
486 for (std::vector<std::string>::iterator I = StringTable.begin(),
487 E = StringTable.end(); I != E; ++I) {
488 // FIXME: do not arbitrarily cap symbols to 16 characters
489 // FIXME: do something more efficient than outstring
490 outstring(ST, *I, 16);
492 O.write((char*)&ST[0], ST.size());