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/TargetData.h"
31 #include "llvm/Target/TargetJITInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/Mangler.h"
37 //===----------------------------------------------------------------------===//
38 // MachOCodeEmitter Implementation
39 //===----------------------------------------------------------------------===//
42 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
43 /// for functions to the Mach-O file.
44 class MachOCodeEmitter : public MachineCodeEmitter {
47 /// MOS - The current section we're writing to
48 MachOWriter::MachOSection *MOS;
50 /// Relocations - These are the relocations that the function needs, as
52 std::vector<MachineRelocation> Relocations;
54 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
55 /// It is filled in by the StartMachineBasicBlock callback and queried by
56 /// the getMachineBasicBlockAddress callback.
57 std::vector<intptr_t> MBBLocations;
60 MachOCodeEmitter(MachOWriter &mow) : MOW(mow) {}
62 void startFunction(MachineFunction &F);
63 bool finishFunction(MachineFunction &F);
65 void addRelocation(const MachineRelocation &MR) {
66 Relocations.push_back(MR);
69 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
70 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
71 MBBLocations.resize((MBB->getNumber()+1)*2);
72 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
75 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
76 assert(0 && "CP not implementated yet!");
79 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
80 assert(0 && "JT not implementated yet!");
84 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
85 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
86 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
87 return MBBLocations[MBB->getNumber()];
90 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
91 void startFunctionStub(unsigned StubSize) {
92 assert(0 && "JIT specific function called!");
95 void *finishFunctionStub(const Function *F) {
96 assert(0 && "JIT specific function called!");
103 /// startFunction - This callback is invoked when a new machine function is
104 /// about to be emitted.
105 void MachOCodeEmitter::startFunction(MachineFunction &F) {
106 // Align the output buffer to the appropriate alignment, power of 2.
107 // FIXME: GENERICIZE!!
110 // Get the Mach-O Section that this function belongs in.
111 MOS = &MOW.getTextSection();
113 // FIXME: better memory management
114 MOS->SectionData.reserve(4096);
115 BufferBegin = &(MOS->SectionData[0]);
116 BufferEnd = BufferBegin + MOS->SectionData.capacity();
117 CurBufferPtr = BufferBegin + MOS->size;
119 // Upgrade the section alignment if required.
120 if (MOS->align < Align) MOS->align = Align;
122 // Make sure we only relocate to this function's MBBs.
123 MBBLocations.clear();
126 /// finishFunction - This callback is invoked after the function is completely
128 bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
129 MOS->size += CurBufferPtr - BufferBegin;
131 // Get a symbol for the function to add to the symbol table
132 MachOWriter::MachOSym FnSym(F.getFunction(), MOS->Index);
134 // Figure out the binding (linkage) of the symbol.
135 switch (F.getFunction()->getLinkage()) {
137 // appending linkage is illegal for functions.
138 assert(0 && "Unknown linkage type!");
139 case GlobalValue::ExternalLinkage:
140 FnSym.n_type = MachOWriter::MachOSym::N_SECT | MachOWriter::MachOSym::N_EXT;
142 case GlobalValue::InternalLinkage:
143 FnSym.n_type = MachOWriter::MachOSym::N_SECT;
147 // Resolve the function's relocations either to concrete pointers in the case
148 // of branches from one block to another, or to target relocation entries.
149 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
150 MachineRelocation &MR = Relocations[i];
151 if (MR.isBasicBlock()) {
152 void *MBBAddr = (void *)getMachineBasicBlockAddress(MR.getBasicBlock());
153 MR.setResultPointer(MBBAddr);
154 MOW.TM.getJITInfo()->relocate(BufferBegin, &MR, 1, 0);
155 // FIXME: we basically want the JITInfo relocate() function to rewrite
156 // this guy right now, so we just write the correct displacement
159 // isString | isGV | isCPI | isJTI
160 // FIXME: do something smart here. We won't be able to relocate these
161 // until the sections are all layed out, but we still need to
162 // record them. Maybe emit TargetRelocations and then resolve
163 // those at file writing time?
164 std::cerr << "whee!\n";
169 // Finally, add it to the symtab.
170 MOW.SymbolTable.push_back(FnSym);
174 //===----------------------------------------------------------------------===//
175 // MachOWriter Implementation
176 //===----------------------------------------------------------------------===//
178 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
179 // FIXME: set cpu type and cpu subtype somehow from TM
180 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
181 isLittleEndian = TM.getTargetData()->isLittleEndian();
183 // Create the machine code emitter object for this target.
184 MCE = new MachOCodeEmitter(*this);
187 MachOWriter::~MachOWriter() {
191 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
192 // FIXME: do something smart here.
196 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
197 // Nothing to do here, this is all done through the MCE object.
201 bool MachOWriter::doInitialization(Module &M) {
202 // Set the magic value, now that we know the pointer size and endianness
203 Header.setMagic(isLittleEndian, is64Bit);
206 // FIXME: this only works for object files, we do not support the creation
207 // of dynamic libraries or executables at this time.
208 Header.filetype = MachOHeader::MH_OBJECT;
210 Mang = new Mangler(M);
214 /// doFinalization - Now that the module has been completely processed, emit
215 /// the Mach-O file to 'O'.
216 bool MachOWriter::doFinalization(Module &M) {
217 // Okay, the.text section has been completed, build the .data, .bss, and
218 // "common" sections next.
219 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
223 // Emit the header and load commands.
224 EmitHeaderAndLoadCommands();
226 // Emit the text and data sections.
229 // Emit the relocation entry data for each section.
230 // FIXME: presumably this should be a virtual method, since different targets
231 // have different relocation types.
234 // Emit the symbol table.
235 // FIXME: we don't handle debug info yet, we should probably do that.
238 // Emit the string table for the sections we have.
241 // We are done with the abstract symbols.
244 DynamicSymbolTable.clear();
246 // Release the name mangler object.
247 delete Mang; Mang = 0;
251 void MachOWriter::EmitHeaderAndLoadCommands() {
252 // Step #0: Fill in the segment load command size, since we need it to figure
253 // out the rest of the header fields
254 MachOSegment SEG("", is64Bit);
255 SEG.nsects = SectionList.size();
256 SEG.cmdsize = SEG.cmdSize(is64Bit) +
257 SEG.nsects * SectionList.begin()->cmdSize(is64Bit);
259 // Step #1: calculate the number of load commands. We always have at least
260 // one, for the LC_SEGMENT load command, plus two for the normal
261 // and dynamic symbol tables, if there are any symbols.
262 Header.ncmds = SymbolTable.empty() ? 1 : 3;
264 // Step #2: calculate the size of the load commands
265 Header.sizeofcmds = SEG.cmdsize;
266 if (!SymbolTable.empty())
267 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
269 // Step #3: write the header to the file
270 // Local alias to shortenify coming code.
271 DataBuffer &FH = Header.HeaderData;
272 outword(FH, Header.magic);
273 outword(FH, Header.cputype);
274 outword(FH, Header.cpusubtype);
275 outword(FH, Header.filetype);
276 outword(FH, Header.ncmds);
277 outword(FH, Header.sizeofcmds);
278 outword(FH, Header.flags);
280 outword(FH, Header.reserved);
282 // Step #4: Finish filling in the segment load command and write it out
283 for (std::list<MachOSection>::iterator I = SectionList.begin(),
284 E = SectionList.end(); I != E; ++I)
285 SEG.filesize += I->size;
286 SEG.vmsize = SEG.filesize;
287 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
289 outword(FH, SEG.cmd);
290 outword(FH, SEG.cmdsize);
291 outstring(FH, SEG.segname, 16);
292 outaddr(FH, SEG.vmaddr);
293 outaddr(FH, SEG.vmsize);
294 outaddr(FH, SEG.fileoff);
295 outaddr(FH, SEG.filesize);
296 outword(FH, SEG.maxprot);
297 outword(FH, SEG.initprot);
298 outword(FH, SEG.nsects);
299 outword(FH, SEG.flags);
301 // Step #5: Write out the section commands for each section
302 for (std::list<MachOSection>::iterator I = SectionList.begin(),
303 E = SectionList.end(); I != E; ++I) {
304 I->offset = SEG.fileoff; // FIXME: separate offset
305 outstring(FH, I->sectname, 16);
306 outstring(FH, I->segname, 16);
307 outaddr(FH, I->addr);
308 outaddr(FH, I->size);
309 outword(FH, I->offset);
310 outword(FH, I->align);
311 outword(FH, I->reloff);
312 outword(FH, I->nreloc);
313 outword(FH, I->flags);
314 outword(FH, I->reserved1);
315 outword(FH, I->reserved2);
317 outword(FH, I->reserved3);
320 // Step #6: Emit LC_SYMTAB/LC_DYSYMTAB load commands
321 // FIXME: We'll need to scan over the symbol table and possibly do the sort
322 // here so that we can set the proper indices in the dysymtab load command for
323 // the index and number of external symbols defined in this module.
324 // FIXME: We'll also need to scan over all the symbols so that we can
325 // calculate the size of the string table.
326 // FIXME: add size of relocs
327 SymTab.symoff = SEG.fileoff + SEG.filesize;
328 SymTab.nsyms = SymbolTable.size();
329 SymTab.stroff = SymTab.symoff + SymTab.nsyms * MachOSym::entrySize();
331 outword(FH, SymTab.cmd);
332 outword(FH, SymTab.cmdsize);
333 outword(FH, SymTab.symoff);
334 outword(FH, SymTab.nsyms);
335 outword(FH, SymTab.stroff);
336 outword(FH, SymTab.strsize);
338 // FIXME: set DySymTab fields appropriately
339 outword(FH, DySymTab.cmd);
340 outword(FH, DySymTab.cmdsize);
341 outword(FH, DySymTab.ilocalsym);
342 outword(FH, DySymTab.nlocalsym);
343 outword(FH, DySymTab.iextdefsym);
344 outword(FH, DySymTab.nextdefsym);
345 outword(FH, DySymTab.iundefsym);
346 outword(FH, DySymTab.nundefsym);
347 outword(FH, DySymTab.tocoff);
348 outword(FH, DySymTab.ntoc);
349 outword(FH, DySymTab.modtaboff);
350 outword(FH, DySymTab.nmodtab);
351 outword(FH, DySymTab.extrefsymoff);
352 outword(FH, DySymTab.nextrefsyms);
353 outword(FH, DySymTab.indirectsymoff);
354 outword(FH, DySymTab.nindirectsyms);
355 outword(FH, DySymTab.extreloff);
356 outword(FH, DySymTab.nextrel);
357 outword(FH, DySymTab.locreloff);
358 outword(FH, DySymTab.nlocrel);
360 O.write((char*)&FH[0], FH.size());
363 /// EmitSections - Now that we have constructed the file header and load
364 /// commands, emit the data for each section to the file.
365 void MachOWriter::EmitSections() {
366 for (std::list<MachOSection>::iterator I = SectionList.begin(),
367 E = SectionList.end(); I != E; ++I) {
368 O.write((char*)&I->SectionData[0], I->size);
372 void MachOWriter::EmitRelocations() {
373 // FIXME: this should probably be a pure virtual function, since the
374 // relocation types and layout of the relocations themselves are target
378 /// EmitSymbolTable - Sort the symbols we encountered and assign them each a
379 /// string table index so that they appear in the correct order in the output
381 void MachOWriter::EmitSymbolTable() {
382 // The order of the symbol table is:
384 // defined external symbols (sorted by name)
385 // undefined external symbols (sorted by name)
388 // FIXME: enforce the above ordering, presumably by sorting by name,
389 // then partitioning twice.
390 unsigned stringIndex;
391 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
392 E = SymbolTable.end(); I != E; ++I) {
393 // FIXME: remove when we actually calculate these correctly
395 StringTable.push_back(Mang->getValueName(I->GV));
396 // Emit nlist to buffer
397 outword(ST, I->n_strx);
398 outbyte(ST, I->n_type);
399 outbyte(ST, I->n_sect);
400 outhalf(ST, I->n_desc);
401 outaddr(ST, I->n_value);
404 O.write((char*)&ST[0], ST.size());
407 /// EmitStringTable - This method adds and emits a section for the Mach-O
409 void MachOWriter::EmitStringTable() {
410 // The order of the string table is:
411 // strings for external symbols
412 // strings for local symbols
413 // This is the symbol table, but backwards. This allows us to avoid a sorting
414 // the symbol table again; all we have to do is use a reverse iterator.
417 // Write out a leading zero byte when emitting string table, for n_strx == 0
418 // which means an empty string.
421 for (std::vector<std::string>::iterator I = StringTable.begin(),
422 E = StringTable.end(); I != E; ++I) {
423 // FIXME: do not arbitrarily cap symbols to 16 characters
424 // FIXME: do something more efficient than outstring
425 outstring(ST, *I, 16);
427 O.write((char*)&ST[0], ST.size());