MachOWriter.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
  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. //
  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. #include "MachOWriter.h"
  25. #include "llvm/Constants.h"
  26. #include "llvm/DerivedTypes.h"
  27. #include "llvm/Module.h"
  28. #include "llvm/PassManager.h"
  29. #include "llvm/CodeGen/FileWriters.h"
  30. #include "llvm/CodeGen/MachineCodeEmitter.h"
  31. #include "llvm/CodeGen/MachineConstantPool.h"
  32. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  33. #include "llvm/Target/TargetAsmInfo.h"
  34. #include "llvm/Target/TargetJITInfo.h"
  35. #include "llvm/Support/Mangler.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Support/OutputBuffer.h"
  38. #include "llvm/Support/Streams.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <algorithm>
  41. #include <cstring>
  42. using namespace llvm;
  43. /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
  44. /// pass manager.
  45. MachineCodeEmitter *llvm::AddMachOWriter(PassManagerBase &PM,
  46. raw_ostream &O,
  47. TargetMachine &TM) {
  48. MachOWriter *MOW = new MachOWriter(O, TM);
  49. PM.add(MOW);
  50. return &MOW->getMachineCodeEmitter();
  51. }
  52. //===----------------------------------------------------------------------===//
  53. // MachOCodeEmitter Implementation
  54. //===----------------------------------------------------------------------===//
  55. namespace llvm {
  56. /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
  57. /// for functions to the Mach-O file.
  58. class MachOCodeEmitter : public MachineCodeEmitter {
  59. MachOWriter &MOW;
  60. /// Target machine description.
  61. TargetMachine &TM;
  62. /// is64Bit/isLittleEndian - This information is inferred from the target
  63. /// machine directly, indicating what header values and flags to set.
  64. bool is64Bit, isLittleEndian;
  65. /// Relocations - These are the relocations that the function needs, as
  66. /// emitted.
  67. std::vector<MachineRelocation> Relocations;
  68. /// CPLocations - This is a map of constant pool indices to offsets from the
  69. /// start of the section for that constant pool index.
  70. std::vector<intptr_t> CPLocations;
  71. /// CPSections - This is a map of constant pool indices to the MachOSection
  72. /// containing the constant pool entry for that index.
  73. std::vector<unsigned> CPSections;
  74. /// JTLocations - This is a map of jump table indices to offsets from the
  75. /// start of the section for that jump table index.
  76. std::vector<intptr_t> JTLocations;
  77. /// MBBLocations - This vector is a mapping from MBB ID's to their address.
  78. /// It is filled in by the StartMachineBasicBlock callback and queried by
  79. /// the getMachineBasicBlockAddress callback.
  80. std::vector<intptr_t> MBBLocations;
  81. public:
  82. MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
  83. is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
  84. isLittleEndian = TM.getTargetData()->isLittleEndian();
  85. }
  86. virtual void startFunction(MachineFunction &MF);
  87. virtual bool finishFunction(MachineFunction &MF);
  88. virtual void addRelocation(const MachineRelocation &MR) {
  89. Relocations.push_back(MR);
  90. }
  91. void emitConstantPool(MachineConstantPool *MCP);
  92. void emitJumpTables(MachineJumpTableInfo *MJTI);
  93. virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
  94. assert(CPLocations.size() > Index && "CP not emitted!");
  95. return CPLocations[Index];
  96. }
  97. virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
  98. assert(JTLocations.size() > Index && "JT not emitted!");
  99. return JTLocations[Index];
  100. }
  101. virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
  102. if (MBBLocations.size() <= (unsigned)MBB->getNumber())
  103. MBBLocations.resize((MBB->getNumber()+1)*2);
  104. MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
  105. }
  106. virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
  107. assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
  108. MBBLocations[MBB->getNumber()] && "MBB not emitted!");
  109. return MBBLocations[MBB->getNumber()];
  110. }
  111. virtual intptr_t getLabelAddress(uint64_t Label) const {
  112. assert(0 && "get Label not implemented");
  113. abort();
  114. return 0;
  115. }
  116. virtual void emitLabel(uint64_t LabelID) {
  117. assert(0 && "emit Label not implemented");
  118. abort();
  119. }
  120. virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
  121. /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
  122. virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
  123. unsigned Alignment = 1) {
  124. assert(0 && "JIT specific function called!");
  125. abort();
  126. }
  127. virtual void *finishFunctionStub(const GlobalValue* F) {
  128. assert(0 && "JIT specific function called!");
  129. abort();
  130. return 0;
  131. }
  132. };
  133. }
  134. /// startFunction - This callback is invoked when a new machine function is
  135. /// about to be emitted.
  136. void MachOCodeEmitter::startFunction(MachineFunction &MF) {
  137. const TargetData *TD = TM.getTargetData();
  138. const Function *F = MF.getFunction();
  139. // Align the output buffer to the appropriate alignment, power of 2.
  140. unsigned FnAlign = F->getAlignment();
  141. unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
  142. unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
  143. assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
  144. // Get the Mach-O Section that this function belongs in.
  145. MachOWriter::MachOSection *MOS = MOW.getTextSection();
  146. // FIXME: better memory management
  147. MOS->SectionData.reserve(4096);
  148. BufferBegin = &MOS->SectionData[0];
  149. BufferEnd = BufferBegin + MOS->SectionData.capacity();
  150. // Upgrade the section alignment if required.
  151. if (MOS->align < Align) MOS->align = Align;
  152. // Round the size up to the correct alignment for starting the new function.
  153. if ((MOS->size & ((1 << Align) - 1)) != 0) {
  154. MOS->size += (1 << Align);
  155. MOS->size &= ~((1 << Align) - 1);
  156. }
  157. // FIXME: Using MOS->size directly here instead of calculating it from the
  158. // output buffer size (impossible because the code emitter deals only in raw
  159. // bytes) forces us to manually synchronize size and write padding zero bytes
  160. // to the output buffer for all non-text sections. For text sections, we do
  161. // not synchonize the output buffer, and we just blow up if anyone tries to
  162. // write non-code to it. An assert should probably be added to
  163. // AddSymbolToSection to prevent calling it on the text section.
  164. CurBufferPtr = BufferBegin + MOS->size;
  165. // Clear per-function data structures.
  166. CPLocations.clear();
  167. CPSections.clear();
  168. JTLocations.clear();
  169. MBBLocations.clear();
  170. }
  171. /// finishFunction - This callback is invoked after the function is completely
  172. /// finished.
  173. bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
  174. // Get the Mach-O Section that this function belongs in.
  175. MachOWriter::MachOSection *MOS = MOW.getTextSection();
  176. // Get a symbol for the function to add to the symbol table
  177. // FIXME: it seems like we should call something like AddSymbolToSection
  178. // in startFunction rather than changing the section size and symbol n_value
  179. // here.
  180. const GlobalValue *FuncV = MF.getFunction();
  181. MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
  182. FnSym.n_value = MOS->size;
  183. MOS->size = CurBufferPtr - BufferBegin;
  184. // Emit constant pool to appropriate section(s)
  185. emitConstantPool(MF.getConstantPool());
  186. // Emit jump tables to appropriate section
  187. emitJumpTables(MF.getJumpTableInfo());
  188. // If we have emitted any relocations to function-specific objects such as
  189. // basic blocks, constant pools entries, or jump tables, record their
  190. // addresses now so that we can rewrite them with the correct addresses
  191. // later.
  192. for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
  193. MachineRelocation &MR = Relocations[i];
  194. intptr_t Addr;
  195. if (MR.isBasicBlock()) {
  196. Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
  197. MR.setConstantVal(MOS->Index);
  198. MR.setResultPointer((void*)Addr);
  199. } else if (MR.isJumpTableIndex()) {
  200. Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
  201. MR.setConstantVal(MOW.getJumpTableSection()->Index);
  202. MR.setResultPointer((void*)Addr);
  203. } else if (MR.isConstantPoolIndex()) {
  204. Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
  205. MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
  206. MR.setResultPointer((void*)Addr);
  207. } else if (MR.isGlobalValue()) {
  208. // FIXME: This should be a set or something that uniques
  209. MOW.PendingGlobals.push_back(MR.getGlobalValue());
  210. } else {
  211. assert(0 && "Unhandled relocation type");
  212. }
  213. MOS->Relocations.push_back(MR);
  214. }
  215. Relocations.clear();
  216. // Finally, add it to the symtab.
  217. MOW.SymbolTable.push_back(FnSym);
  218. return false;
  219. }
  220. /// emitConstantPool - For each constant pool entry, figure out which section
  221. /// the constant should live in, allocate space for it, and emit it to the
  222. /// Section data buffer.
  223. void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
  224. const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
  225. if (CP.empty()) return;
  226. // FIXME: handle PIC codegen
  227. bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
  228. assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
  229. // Although there is no strict necessity that I am aware of, we will do what
  230. // gcc for OS X does and put each constant pool entry in a section of constant
  231. // objects of a certain size. That means that float constants go in the
  232. // literal4 section, and double objects go in literal8, etc.
  233. //
  234. // FIXME: revisit this decision if we ever do the "stick everything into one
  235. // "giant object for PIC" optimization.
  236. for (unsigned i = 0, e = CP.size(); i != e; ++i) {
  237. const Type *Ty = CP[i].getType();
  238. unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
  239. MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
  240. OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
  241. CPLocations.push_back(Sec->SectionData.size());
  242. CPSections.push_back(Sec->Index);
  243. // FIXME: remove when we have unified size + output buffer
  244. Sec->size += Size;
  245. // Allocate space in the section for the global.
  246. // FIXME: need alignment?
  247. // FIXME: share between here and AddSymbolToSection?
  248. for (unsigned j = 0; j < Size; ++j)
  249. SecDataOut.outbyte(0);
  250. MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
  251. TM.getTargetData(), Sec->Relocations);
  252. }
  253. }
  254. /// emitJumpTables - Emit all the jump tables for a given jump table info
  255. /// record to the appropriate section.
  256. void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
  257. const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
  258. if (JT.empty()) return;
  259. // FIXME: handle PIC codegen
  260. bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
  261. assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
  262. MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
  263. unsigned TextSecIndex = MOW.getTextSection()->Index;
  264. OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
  265. for (unsigned i = 0, e = JT.size(); i != e; ++i) {
  266. // For each jump table, record its offset from the start of the section,
  267. // reserve space for the relocations to the MBBs, and add the relocations.
  268. const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
  269. JTLocations.push_back(Sec->SectionData.size());
  270. for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
  271. MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
  272. MBBs[mi]));
  273. MR.setResultPointer((void *)JTLocations[i]);
  274. MR.setConstantVal(TextSecIndex);
  275. Sec->Relocations.push_back(MR);
  276. SecDataOut.outaddr(0);
  277. }
  278. }
  279. // FIXME: remove when we have unified size + output buffer
  280. Sec->size = Sec->SectionData.size();
  281. }
  282. //===----------------------------------------------------------------------===//
  283. // MachOWriter Implementation
  284. //===----------------------------------------------------------------------===//
  285. char MachOWriter::ID = 0;
  286. MachOWriter::MachOWriter(raw_ostream &o, TargetMachine &tm)
  287. : MachineFunctionPass((intptr_t)&ID), O(o), TM(tm) {
  288. is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
  289. isLittleEndian = TM.getTargetData()->isLittleEndian();
  290. // Create the machine code emitter object for this target.
  291. MCE = new MachOCodeEmitter(*this);
  292. }
  293. MachOWriter::~MachOWriter() {
  294. delete MCE;
  295. }
  296. void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
  297. const Type *Ty = GV->getType()->getElementType();
  298. unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
  299. unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
  300. // Reserve space in the .bss section for this symbol while maintaining the
  301. // desired section alignment, which must be at least as much as required by
  302. // this symbol.
  303. OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
  304. if (Align) {
  305. uint64_t OrigSize = Sec->size;
  306. Align = Log2_32(Align);
  307. Sec->align = std::max(unsigned(Sec->align), Align);
  308. Sec->size = (Sec->size + Align - 1) & ~(Align-1);
  309. // Add alignment padding to buffer as well.
  310. // FIXME: remove when we have unified size + output buffer
  311. unsigned AlignedSize = Sec->size - OrigSize;
  312. for (unsigned i = 0; i < AlignedSize; ++i)
  313. SecDataOut.outbyte(0);
  314. }
  315. // Globals without external linkage apparently do not go in the symbol table.
  316. if (GV->getLinkage() != GlobalValue::InternalLinkage) {
  317. MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
  318. Sym.n_value = Sec->size;
  319. SymbolTable.push_back(Sym);
  320. }
  321. // Record the offset of the symbol, and then allocate space for it.
  322. // FIXME: remove when we have unified size + output buffer
  323. Sec->size += Size;
  324. // Now that we know what section the GlovalVariable is going to be emitted
  325. // into, update our mappings.
  326. // FIXME: We may also need to update this when outputting non-GlobalVariable
  327. // GlobalValues such as functions.
  328. GVSection[GV] = Sec;
  329. GVOffset[GV] = Sec->SectionData.size();
  330. // Allocate space in the section for the global.
  331. for (unsigned i = 0; i < Size; ++i)
  332. SecDataOut.outbyte(0);
  333. }
  334. void MachOWriter::EmitGlobal(GlobalVariable *GV) {
  335. const Type *Ty = GV->getType()->getElementType();
  336. unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
  337. bool NoInit = !GV->hasInitializer();
  338. // If this global has a zero initializer, it is part of the .bss or common
  339. // section.
  340. if (NoInit || GV->getInitializer()->isNullValue()) {
  341. // If this global is part of the common block, add it now. Variables are
  342. // part of the common block if they are zero initialized and allowed to be
  343. // merged with other symbols.
  344. if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
  345. GV->hasCommonLinkage()) {
  346. MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
  347. // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
  348. // bytes of the symbol.
  349. ExtOrCommonSym.n_value = Size;
  350. SymbolTable.push_back(ExtOrCommonSym);
  351. // Remember that we've seen this symbol
  352. GVOffset[GV] = Size;
  353. return;
  354. }
  355. // Otherwise, this symbol is part of the .bss section.
  356. MachOSection *BSS = getBSSSection();
  357. AddSymbolToSection(BSS, GV);
  358. return;
  359. }
  360. // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
  361. // 16 bytes, or a cstring. Other read only data goes into a regular const
  362. // section. Read-write data goes in the data section.
  363. MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
  364. getDataSection();
  365. AddSymbolToSection(Sec, GV);
  366. InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
  367. TM.getTargetData(), Sec->Relocations);
  368. }
  369. bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
  370. // Nothing to do here, this is all done through the MCE object.
  371. return false;
  372. }
  373. bool MachOWriter::doInitialization(Module &M) {
  374. // Set the magic value, now that we know the pointer size and endianness
  375. Header.setMagic(isLittleEndian, is64Bit);
  376. // Set the file type
  377. // FIXME: this only works for object files, we do not support the creation
  378. // of dynamic libraries or executables at this time.
  379. Header.filetype = MachOHeader::MH_OBJECT;
  380. Mang = new Mangler(M);
  381. return false;
  382. }
  383. /// doFinalization - Now that the module has been completely processed, emit
  384. /// the Mach-O file to 'O'.
  385. bool MachOWriter::doFinalization(Module &M) {
  386. // FIXME: we don't handle debug info yet, we should probably do that.
  387. // Okay, the.text section has been completed, build the .data, .bss, and
  388. // "common" sections next.
  389. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  390. I != E; ++I)
  391. EmitGlobal(I);
  392. // Emit the header and load commands.
  393. EmitHeaderAndLoadCommands();
  394. // Emit the various sections and their relocation info.
  395. EmitSections();
  396. // Write the symbol table and the string table to the end of the file.
  397. O.write((char*)&SymT[0], SymT.size());
  398. O.write((char*)&StrT[0], StrT.size());
  399. // We are done with the abstract symbols.
  400. SectionList.clear();
  401. SymbolTable.clear();
  402. DynamicSymbolTable.clear();
  403. // Release the name mangler object.
  404. delete Mang; Mang = 0;
  405. return false;
  406. }
  407. void MachOWriter::EmitHeaderAndLoadCommands() {
  408. // Step #0: Fill in the segment load command size, since we need it to figure
  409. // out the rest of the header fields
  410. MachOSegment SEG("", is64Bit);
  411. SEG.nsects = SectionList.size();
  412. SEG.cmdsize = SEG.cmdSize(is64Bit) +
  413. SEG.nsects * SectionList[0]->cmdSize(is64Bit);
  414. // Step #1: calculate the number of load commands. We always have at least
  415. // one, for the LC_SEGMENT load command, plus two for the normal
  416. // and dynamic symbol tables, if there are any symbols.
  417. Header.ncmds = SymbolTable.empty() ? 1 : 3;
  418. // Step #2: calculate the size of the load commands
  419. Header.sizeofcmds = SEG.cmdsize;
  420. if (!SymbolTable.empty())
  421. Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
  422. // Step #3: write the header to the file
  423. // Local alias to shortenify coming code.
  424. DataBuffer &FH = Header.HeaderData;
  425. OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
  426. FHOut.outword(Header.magic);
  427. FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
  428. FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
  429. FHOut.outword(Header.filetype);
  430. FHOut.outword(Header.ncmds);
  431. FHOut.outword(Header.sizeofcmds);
  432. FHOut.outword(Header.flags);
  433. if (is64Bit)
  434. FHOut.outword(Header.reserved);
  435. // Step #4: Finish filling in the segment load command and write it out
  436. for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
  437. E = SectionList.end(); I != E; ++I)
  438. SEG.filesize += (*I)->size;
  439. SEG.vmsize = SEG.filesize;
  440. SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
  441. FHOut.outword(SEG.cmd);
  442. FHOut.outword(SEG.cmdsize);
  443. FHOut.outstring(SEG.segname, 16);
  444. FHOut.outaddr(SEG.vmaddr);
  445. FHOut.outaddr(SEG.vmsize);
  446. FHOut.outaddr(SEG.fileoff);
  447. FHOut.outaddr(SEG.filesize);
  448. FHOut.outword(SEG.maxprot);
  449. FHOut.outword(SEG.initprot);
  450. FHOut.outword(SEG.nsects);
  451. FHOut.outword(SEG.flags);
  452. // Step #5: Finish filling in the fields of the MachOSections
  453. uint64_t currentAddr = 0;
  454. for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
  455. E = SectionList.end(); I != E; ++I) {
  456. MachOSection *MOS = *I;
  457. MOS->addr = currentAddr;
  458. MOS->offset = currentAddr + SEG.fileoff;
  459. // FIXME: do we need to do something with alignment here?
  460. currentAddr += MOS->size;
  461. }
  462. // Step #6: Emit the symbol table to temporary buffers, so that we know the
  463. // size of the string table when we write the next load command. This also
  464. // sorts and assigns indices to each of the symbols, which is necessary for
  465. // emitting relocations to externally-defined objects.
  466. BufferSymbolAndStringTable();
  467. // Step #7: Calculate the number of relocations for each section and write out
  468. // the section commands for each section
  469. currentAddr += SEG.fileoff;
  470. for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
  471. E = SectionList.end(); I != E; ++I) {
  472. MachOSection *MOS = *I;
  473. // Convert the relocations to target-specific relocations, and fill in the
  474. // relocation offset for this section.
  475. CalculateRelocations(*MOS);
  476. MOS->reloff = MOS->nreloc ? currentAddr : 0;
  477. currentAddr += MOS->nreloc * 8;
  478. // write the finalized section command to the output buffer
  479. FHOut.outstring(MOS->sectname, 16);
  480. FHOut.outstring(MOS->segname, 16);
  481. FHOut.outaddr(MOS->addr);
  482. FHOut.outaddr(MOS->size);
  483. FHOut.outword(MOS->offset);
  484. FHOut.outword(MOS->align);
  485. FHOut.outword(MOS->reloff);
  486. FHOut.outword(MOS->nreloc);
  487. FHOut.outword(MOS->flags);
  488. FHOut.outword(MOS->reserved1);
  489. FHOut.outword(MOS->reserved2);
  490. if (is64Bit)
  491. FHOut.outword(MOS->reserved3);
  492. }
  493. // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
  494. SymTab.symoff = currentAddr;
  495. SymTab.nsyms = SymbolTable.size();
  496. SymTab.stroff = SymTab.symoff + SymT.size();
  497. SymTab.strsize = StrT.size();
  498. FHOut.outword(SymTab.cmd);
  499. FHOut.outword(SymTab.cmdsize);
  500. FHOut.outword(SymTab.symoff);
  501. FHOut.outword(SymTab.nsyms);
  502. FHOut.outword(SymTab.stroff);
  503. FHOut.outword(SymTab.strsize);
  504. // FIXME: set DySymTab fields appropriately
  505. // We should probably just update these in BufferSymbolAndStringTable since
  506. // thats where we're partitioning up the different kinds of symbols.
  507. FHOut.outword(DySymTab.cmd);
  508. FHOut.outword(DySymTab.cmdsize);
  509. FHOut.outword(DySymTab.ilocalsym);
  510. FHOut.outword(DySymTab.nlocalsym);
  511. FHOut.outword(DySymTab.iextdefsym);
  512. FHOut.outword(DySymTab.nextdefsym);
  513. FHOut.outword(DySymTab.iundefsym);
  514. FHOut.outword(DySymTab.nundefsym);
  515. FHOut.outword(DySymTab.tocoff);
  516. FHOut.outword(DySymTab.ntoc);
  517. FHOut.outword(DySymTab.modtaboff);
  518. FHOut.outword(DySymTab.nmodtab);
  519. FHOut.outword(DySymTab.extrefsymoff);
  520. FHOut.outword(DySymTab.nextrefsyms);
  521. FHOut.outword(DySymTab.indirectsymoff);
  522. FHOut.outword(DySymTab.nindirectsyms);
  523. FHOut.outword(DySymTab.extreloff);
  524. FHOut.outword(DySymTab.nextrel);
  525. FHOut.outword(DySymTab.locreloff);
  526. FHOut.outword(DySymTab.nlocrel);
  527. O.write((char*)&FH[0], FH.size());
  528. }
  529. /// EmitSections - Now that we have constructed the file header and load
  530. /// commands, emit the data for each section to the file.
  531. void MachOWriter::EmitSections() {
  532. for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
  533. E = SectionList.end(); I != E; ++I)
  534. // Emit the contents of each section
  535. O.write((char*)&(*I)->SectionData[0], (*I)->size);
  536. for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
  537. E = SectionList.end(); I != E; ++I)
  538. // Emit the relocation entry data for each section.
  539. O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
  540. }
  541. /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
  542. /// a local symbol rather than an external symbol.
  543. bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
  544. return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
  545. }
  546. /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
  547. /// defined in this module.
  548. bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
  549. // FIXME: Do N_ABS or N_INDR count as defined?
  550. return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
  551. }
  552. /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
  553. /// each a string table index so that they appear in the correct order in the
  554. /// output file.
  555. void MachOWriter::BufferSymbolAndStringTable() {
  556. // The order of the symbol table is:
  557. // 1. local symbols
  558. // 2. defined external symbols (sorted by name)
  559. // 3. undefined external symbols (sorted by name)
  560. // Before sorting the symbols, check the PendingGlobals for any undefined
  561. // globals that need to be put in the symbol table.
  562. for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
  563. E = PendingGlobals.end(); I != E; ++I) {
  564. if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
  565. MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
  566. SymbolTable.push_back(UndfSym);
  567. GVOffset[*I] = -1;
  568. }
  569. }
  570. // Sort the symbols by name, so that when we partition the symbols by scope
  571. // of definition, we won't have to sort by name within each partition.
  572. std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
  573. // Parition the symbol table entries so that all local symbols come before
  574. // all symbols with external linkage. { 1 | 2 3 }
  575. std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
  576. // Advance iterator to beginning of external symbols and partition so that
  577. // all external symbols defined in this module come before all external
  578. // symbols defined elsewhere. { 1 | 2 | 3 }
  579. for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
  580. E = SymbolTable.end(); I != E; ++I) {
  581. if (!PartitionByLocal(*I)) {
  582. std::partition(I, E, PartitionByDefined);
  583. break;
  584. }
  585. }
  586. // Calculate the starting index for each of the local, extern defined, and
  587. // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
  588. // load command.
  589. for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
  590. E = SymbolTable.end(); I != E; ++I) {
  591. if (PartitionByLocal(*I)) {
  592. ++DySymTab.nlocalsym;
  593. ++DySymTab.iextdefsym;
  594. ++DySymTab.iundefsym;
  595. } else if (PartitionByDefined(*I)) {
  596. ++DySymTab.nextdefsym;
  597. ++DySymTab.iundefsym;
  598. } else {
  599. ++DySymTab.nundefsym;
  600. }
  601. }
  602. // Write out a leading zero byte when emitting string table, for n_strx == 0
  603. // which means an empty string.
  604. OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
  605. StrTOut.outbyte(0);
  606. // The order of the string table is:
  607. // 1. strings for external symbols
  608. // 2. strings for local symbols
  609. // Since this is the opposite order from the symbol table, which we have just
  610. // sorted, we can walk the symbol table backwards to output the string table.
  611. for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
  612. E = SymbolTable.rend(); I != E; ++I) {
  613. if (I->GVName == "") {
  614. I->n_strx = 0;
  615. } else {
  616. I->n_strx = StrT.size();
  617. StrTOut.outstring(I->GVName, I->GVName.length()+1);
  618. }
  619. }
  620. OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
  621. unsigned index = 0;
  622. for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
  623. E = SymbolTable.end(); I != E; ++I, ++index) {
  624. // Add the section base address to the section offset in the n_value field
  625. // to calculate the full address.
  626. // FIXME: handle symbols where the n_value field is not the address
  627. GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
  628. if (GV && GVSection[GV])
  629. I->n_value += GVSection[GV]->addr;
  630. if (GV && (GVOffset[GV] == -1))
  631. GVOffset[GV] = index;
  632. // Emit nlist to buffer
  633. SymTOut.outword(I->n_strx);
  634. SymTOut.outbyte(I->n_type);
  635. SymTOut.outbyte(I->n_sect);
  636. SymTOut.outhalf(I->n_desc);
  637. SymTOut.outaddr(I->n_value);
  638. }
  639. }
  640. /// CalculateRelocations - For each MachineRelocation in the current section,
  641. /// calculate the index of the section containing the object to be relocated,
  642. /// and the offset into that section. From this information, create the
  643. /// appropriate target-specific MachORelocation type and add buffer it to be
  644. /// written out after we are finished writing out sections.
  645. void MachOWriter::CalculateRelocations(MachOSection &MOS) {
  646. for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
  647. MachineRelocation &MR = MOS.Relocations[i];
  648. unsigned TargetSection = MR.getConstantVal();
  649. unsigned TargetAddr = 0;
  650. unsigned TargetIndex = 0;
  651. // This is a scattered relocation entry if it points to a global value with
  652. // a non-zero offset.
  653. bool Scattered = false;
  654. bool Extern = false;
  655. // Since we may not have seen the GlobalValue we were interested in yet at
  656. // the time we emitted the relocation for it, fix it up now so that it
  657. // points to the offset into the correct section.
  658. if (MR.isGlobalValue()) {
  659. GlobalValue *GV = MR.getGlobalValue();
  660. MachOSection *MOSPtr = GVSection[GV];
  661. intptr_t Offset = GVOffset[GV];
  662. // If we have never seen the global before, it must be to a symbol
  663. // defined in another module (N_UNDF).
  664. if (!MOSPtr) {
  665. // FIXME: need to append stub suffix
  666. Extern = true;
  667. TargetAddr = 0;
  668. TargetIndex = GVOffset[GV];
  669. } else {
  670. Scattered = TargetSection != 0;
  671. TargetSection = MOSPtr->Index;
  672. }
  673. MR.setResultPointer((void*)Offset);
  674. }
  675. // If the symbol is locally defined, pass in the address of the section and
  676. // the section index to the code which will generate the target relocation.
  677. if (!Extern) {
  678. MachOSection &To = *SectionList[TargetSection - 1];
  679. TargetAddr = To.addr;
  680. TargetIndex = To.Index;
  681. }
  682. OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
  683. OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
  684. MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
  685. RelocOut, SecOut, Scattered, Extern);
  686. }
  687. }
  688. // InitMem - Write the value of a Constant to the specified memory location,
  689. // converting it into bytes and relocations.
  690. void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
  691. const TargetData *TD,
  692. std::vector<MachineRelocation> &MRs) {
  693. typedef std::pair<const Constant*, intptr_t> CPair;
  694. std::vector<CPair> WorkList;
  695. WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
  696. intptr_t ScatteredOffset = 0;
  697. while (!WorkList.empty()) {
  698. const Constant *PC = WorkList.back().first;
  699. intptr_t PA = WorkList.back().second;
  700. WorkList.pop_back();
  701. if (isa<UndefValue>(PC)) {
  702. continue;
  703. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
  704. unsigned ElementSize =
  705. TD->getABITypeSize(CP->getType()->getElementType());
  706. for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
  707. WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
  708. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
  709. //
  710. // FIXME: Handle ConstantExpression. See EE::getConstantValue()
  711. //
  712. switch (CE->getOpcode()) {
  713. case Instruction::GetElementPtr: {
  714. SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
  715. ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
  716. &Indices[0], Indices.size());
  717. WorkList.push_back(CPair(CE->getOperand(0), PA));
  718. break;
  719. }
  720. case Instruction::Add:
  721. default:
  722. cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
  723. abort();
  724. break;
  725. }
  726. } else if (PC->getType()->isSingleValueType()) {
  727. unsigned char *ptr = (unsigned char *)PA;
  728. switch (PC->getType()->getTypeID()) {
  729. case Type::IntegerTyID: {
  730. unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
  731. uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
  732. if (NumBits <= 8)
  733. ptr[0] = val;
  734. else if (NumBits <= 16) {
  735. if (TD->isBigEndian())
  736. val = ByteSwap_16(val);
  737. ptr[0] = val;
  738. ptr[1] = val >> 8;
  739. } else if (NumBits <= 32) {
  740. if (TD->isBigEndian())
  741. val = ByteSwap_32(val);
  742. ptr[0] = val;
  743. ptr[1] = val >> 8;
  744. ptr[2] = val >> 16;
  745. ptr[3] = val >> 24;
  746. } else if (NumBits <= 64) {
  747. if (TD->isBigEndian())
  748. val = ByteSwap_64(val);
  749. ptr[0] = val;
  750. ptr[1] = val >> 8;
  751. ptr[2] = val >> 16;
  752. ptr[3] = val >> 24;
  753. ptr[4] = val >> 32;
  754. ptr[5] = val >> 40;
  755. ptr[6] = val >> 48;
  756. ptr[7] = val >> 56;
  757. } else {
  758. assert(0 && "Not implemented: bit widths > 64");
  759. }
  760. break;
  761. }
  762. case Type::FloatTyID: {
  763. uint32_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
  764. getZExtValue();
  765. if (TD->isBigEndian())
  766. val = ByteSwap_32(val);
  767. ptr[0] = val;
  768. ptr[1] = val >> 8;
  769. ptr[2] = val >> 16;
  770. ptr[3] = val >> 24;
  771. break;
  772. }
  773. case Type::DoubleTyID: {
  774. uint64_t val = cast<ConstantFP>(PC)->getValueAPF().convertToAPInt().
  775. getZExtValue();
  776. if (TD->isBigEndian())
  777. val = ByteSwap_64(val);
  778. ptr[0] = val;
  779. ptr[1] = val >> 8;
  780. ptr[2] = val >> 16;
  781. ptr[3] = val >> 24;
  782. ptr[4] = val >> 32;
  783. ptr[5] = val >> 40;
  784. ptr[6] = val >> 48;
  785. ptr[7] = val >> 56;
  786. break;
  787. }
  788. case Type::PointerTyID:
  789. if (isa<ConstantPointerNull>(PC))
  790. memset(ptr, 0, TD->getPointerSize());
  791. else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
  792. // FIXME: what about function stubs?
  793. MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
  794. MachineRelocation::VANILLA,
  795. const_cast<GlobalValue*>(GV),
  796. ScatteredOffset));
  797. ScatteredOffset = 0;
  798. } else
  799. assert(0 && "Unknown constant pointer type!");
  800. break;
  801. default:
  802. cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
  803. abort();
  804. }
  805. } else if (isa<ConstantAggregateZero>(PC)) {
  806. memset((void*)PA, 0, (size_t)TD->getABITypeSize(PC->getType()));
  807. } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
  808. unsigned ElementSize =
  809. TD->getABITypeSize(CPA->getType()->getElementType());
  810. for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
  811. WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
  812. } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
  813. const StructLayout *SL =
  814. TD->getStructLayout(cast<StructType>(CPS->getType()));
  815. for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
  816. WorkList.push_back(CPair(CPS->getOperand(i),
  817. PA+SL->getElementOffset(i)));
  818. } else {
  819. cerr << "Bad Type: " << *PC->getType() << "\n";
  820. assert(0 && "Unknown constant type to initialize memory with!");
  821. }
  822. }
  823. }
  824. MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
  825. TargetMachine &TM) :
  826. GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
  827. n_desc(0), n_value(0) {
  828. const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
  829. switch (GV->getLinkage()) {
  830. default:
  831. assert(0 && "Unexpected linkage type!");
  832. break;
  833. case GlobalValue::WeakLinkage:
  834. case GlobalValue::LinkOnceLinkage:
  835. case GlobalValue::CommonLinkage:
  836. assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
  837. case GlobalValue::ExternalLinkage:
  838. GVName = TAI->getGlobalPrefix() + name;
  839. n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
  840. break;
  841. case GlobalValue::InternalLinkage:
  842. GVName = TAI->getGlobalPrefix() + name;
  843. break;
  844. }
  845. }