ELFWriter.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. //===-- ELFWriter.cpp - Target-independent ELF 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 ELF writer. This file writes out
  11. // the ELF file in the following order:
  12. //
  13. // #1. ELF Header
  14. // #2. '.text' section
  15. // #3. '.data' section
  16. // #4. '.bss' section (conceptual position in file)
  17. // ...
  18. // #X. '.shstrtab' section
  19. // #Y. Section Table
  20. //
  21. // The entries in the section table are laid out as:
  22. // #0. Null entry [required]
  23. // #1. ".text" entry - the program code
  24. // #2. ".data" entry - global variables with initializers. [ if needed ]
  25. // #3. ".bss" entry - global variables without initializers. [ if needed ]
  26. // ...
  27. // #N. ".shstrtab" entry - String table for the section names.
  28. //
  29. //===----------------------------------------------------------------------===//
  30. #define DEBUG_TYPE "elfwriter"
  31. #include "ELF.h"
  32. #include "ELFWriter.h"
  33. #include "ELFCodeEmitter.h"
  34. #include "llvm/Constants.h"
  35. #include "llvm/Module.h"
  36. #include "llvm/PassManager.h"
  37. #include "llvm/DerivedTypes.h"
  38. #include "llvm/CodeGen/BinaryObject.h"
  39. #include "llvm/CodeGen/FileWriters.h"
  40. #include "llvm/CodeGen/MachineCodeEmitter.h"
  41. #include "llvm/CodeGen/ObjectCodeEmitter.h"
  42. #include "llvm/CodeGen/MachineCodeEmitter.h"
  43. #include "llvm/CodeGen/MachineConstantPool.h"
  44. #include "llvm/MC/MCContext.h"
  45. #include "llvm/MC/MCSectionELF.h"
  46. #include "llvm/Target/TargetAsmInfo.h"
  47. #include "llvm/Target/TargetData.h"
  48. #include "llvm/Target/TargetELFWriterInfo.h"
  49. #include "llvm/Target/TargetLowering.h"
  50. #include "llvm/Target/TargetLoweringObjectFile.h"
  51. #include "llvm/Target/TargetMachine.h"
  52. #include "llvm/Support/Mangler.h"
  53. #include "llvm/Support/Streams.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Support/Debug.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. using namespace llvm;
  58. char ELFWriter::ID = 0;
  59. /// AddELFWriter - Add the ELF writer to the function pass manager
  60. ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
  61. raw_ostream &O,
  62. TargetMachine &TM) {
  63. ELFWriter *EW = new ELFWriter(O, TM);
  64. PM.add(EW);
  65. return EW->getObjectCodeEmitter();
  66. }
  67. //===----------------------------------------------------------------------===//
  68. // ELFWriter Implementation
  69. //===----------------------------------------------------------------------===//
  70. ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
  71. : MachineFunctionPass(&ID), O(o), TM(tm),
  72. OutContext(*new MCContext()),
  73. TLOF(TM.getTargetLowering()->getObjFileLowering()),
  74. is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
  75. isLittleEndian(TM.getTargetData()->isLittleEndian()),
  76. ElfHdr(isLittleEndian, is64Bit) {
  77. TAI = TM.getTargetAsmInfo();
  78. TEW = TM.getELFWriterInfo();
  79. // Create the object code emitter object for this target.
  80. ElfCE = new ELFCodeEmitter(*this);
  81. // Inital number of sections
  82. NumSections = 0;
  83. }
  84. ELFWriter::~ELFWriter() {
  85. delete ElfCE;
  86. delete &OutContext;
  87. }
  88. // doInitialization - Emit the file header and all of the global variables for
  89. // the module to the ELF file.
  90. bool ELFWriter::doInitialization(Module &M) {
  91. // Initialize TargetLoweringObjectFile.
  92. const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
  93. Mang = new Mangler(M);
  94. // ELF Header
  95. // ----------
  96. // Fields e_shnum e_shstrndx are only known after all section have
  97. // been emitted. They locations in the ouput buffer are recorded so
  98. // to be patched up later.
  99. //
  100. // Note
  101. // ----
  102. // emitWord method behaves differently for ELF32 and ELF64, writing
  103. // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
  104. ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
  105. ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
  106. ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
  107. ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
  108. ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
  109. ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
  110. ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
  111. ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
  112. ElfHdr.emitWord16(ET_REL); // e_type
  113. ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
  114. ElfHdr.emitWord32(EV_CURRENT); // e_version
  115. ElfHdr.emitWord(0); // e_entry, no entry point in .o file
  116. ElfHdr.emitWord(0); // e_phoff, no program header for .o
  117. ELFHdr_e_shoff_Offset = ElfHdr.size();
  118. ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
  119. ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
  120. ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
  121. ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
  122. ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
  123. // e_shentsize = Section header entry size
  124. ElfHdr.emitWord16(TEW->getSHdrSize());
  125. // e_shnum = # of section header ents
  126. ELFHdr_e_shnum_Offset = ElfHdr.size();
  127. ElfHdr.emitWord16(0); // Placeholder
  128. // e_shstrndx = Section # of '.shstrtab'
  129. ELFHdr_e_shstrndx_Offset = ElfHdr.size();
  130. ElfHdr.emitWord16(0); // Placeholder
  131. // Add the null section, which is required to be first in the file.
  132. getNullSection();
  133. // The first entry in the symtab is the null symbol and the second
  134. // is a local symbol containing the module/file name
  135. SymbolList.push_back(new ELFSym());
  136. SymbolList.push_back(ELFSym::getFileSym());
  137. return false;
  138. }
  139. // AddPendingGlobalSymbol - Add a global to be processed and to
  140. // the global symbol lookup, use a zero index because the table
  141. // index will be determined later.
  142. void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV,
  143. bool AddToLookup /* = false */) {
  144. PendingGlobals.insert(GV);
  145. if (AddToLookup)
  146. GblSymLookup[GV] = 0;
  147. }
  148. // AddPendingExternalSymbol - Add the external to be processed
  149. // and to the external symbol lookup, use a zero index because
  150. // the symbol table index will be determined later.
  151. void ELFWriter::AddPendingExternalSymbol(const char *External) {
  152. PendingExternals.insert(External);
  153. ExtSymLookup[External] = 0;
  154. }
  155. ELFSection &ELFWriter::getDataSection() {
  156. const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
  157. return getSection(Data->getSectionName(), Data->getType(),
  158. Data->getFlags(), 4);
  159. }
  160. ELFSection &ELFWriter::getBSSSection() {
  161. const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
  162. return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
  163. }
  164. // getCtorSection - Get the static constructor section
  165. ELFSection &ELFWriter::getCtorSection() {
  166. const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
  167. return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags());
  168. }
  169. // getDtorSection - Get the static destructor section
  170. ELFSection &ELFWriter::getDtorSection() {
  171. const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
  172. return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
  173. }
  174. // getTextSection - Get the text section for the specified function
  175. ELFSection &ELFWriter::getTextSection(Function *F) {
  176. const MCSectionELF *Text =
  177. (const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
  178. return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
  179. }
  180. // getJumpTableSection - Get a read only section for constants when
  181. // emitting jump tables. TODO: add PIC support
  182. ELFSection &ELFWriter::getJumpTableSection() {
  183. const MCSectionELF *JT =
  184. (const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
  185. return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
  186. TM.getTargetData()->getPointerABIAlignment());
  187. }
  188. // getConstantPoolSection - Get a constant pool section based on the machine
  189. // constant pool entry type and relocation info.
  190. ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
  191. SectionKind Kind;
  192. switch (CPE.getRelocationInfo()) {
  193. default: llvm_unreachable("Unknown section kind");
  194. case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
  195. case 1:
  196. Kind = SectionKind::getReadOnlyWithRelLocal();
  197. break;
  198. case 0:
  199. switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
  200. case 4: Kind = SectionKind::getMergeableConst4(); break;
  201. case 8: Kind = SectionKind::getMergeableConst8(); break;
  202. case 16: Kind = SectionKind::getMergeableConst16(); break;
  203. default: Kind = SectionKind::getMergeableConst(); break;
  204. }
  205. }
  206. const MCSectionELF *CPSect =
  207. (const MCSectionELF *)TLOF.getSectionForConstant(Kind);
  208. return getSection(CPSect->getSectionName(), CPSect->getType(),
  209. CPSect->getFlags(), CPE.getAlignment());
  210. }
  211. // getRelocSection - Return the relocation section of section 'S'. 'RelA'
  212. // is true if the relocation section contains entries with addends.
  213. ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
  214. unsigned SectionType = TEW->hasRelocationAddend() ?
  215. ELFSection::SHT_RELA : ELFSection::SHT_REL;
  216. std::string SectionName(".rel");
  217. if (TEW->hasRelocationAddend())
  218. SectionName.append("a");
  219. SectionName.append(S.getName());
  220. return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
  221. }
  222. // getGlobalELFVisibility - Returns the ELF specific visibility type
  223. unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
  224. switch (GV->getVisibility()) {
  225. default:
  226. llvm_unreachable("unknown visibility type");
  227. case GlobalValue::DefaultVisibility:
  228. return ELFSym::STV_DEFAULT;
  229. case GlobalValue::HiddenVisibility:
  230. return ELFSym::STV_HIDDEN;
  231. case GlobalValue::ProtectedVisibility:
  232. return ELFSym::STV_PROTECTED;
  233. }
  234. return 0;
  235. }
  236. // getGlobalELFBinding - Returns the ELF specific binding type
  237. unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
  238. if (GV->hasInternalLinkage())
  239. return ELFSym::STB_LOCAL;
  240. if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
  241. return ELFSym::STB_WEAK;
  242. return ELFSym::STB_GLOBAL;
  243. }
  244. // getGlobalELFType - Returns the ELF specific type for a global
  245. unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
  246. if (GV->isDeclaration())
  247. return ELFSym::STT_NOTYPE;
  248. if (isa<Function>(GV))
  249. return ELFSym::STT_FUNC;
  250. return ELFSym::STT_OBJECT;
  251. }
  252. // IsELFUndefSym - True if the global value must be marked as a symbol
  253. // which points to a SHN_UNDEF section. This means that the symbol has
  254. // no definition on the module.
  255. static bool IsELFUndefSym(const GlobalValue *GV) {
  256. return GV->isDeclaration() || (isa<Function>(GV));
  257. }
  258. // AddToSymbolList - Update the symbol lookup and If the symbol is
  259. // private add it to PrivateSyms list, otherwise to SymbolList.
  260. void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
  261. assert(GblSym->isGlobalValue() && "Symbol must be a global value");
  262. const GlobalValue *GV = GblSym->getGlobalValue();
  263. if (GV->hasPrivateLinkage()) {
  264. // For a private symbols, keep track of the index inside
  265. // the private list since it will never go to the symbol
  266. // table and won't be patched up later.
  267. PrivateSyms.push_back(GblSym);
  268. GblSymLookup[GV] = PrivateSyms.size()-1;
  269. } else {
  270. // Non private symbol are left with zero indices until
  271. // they are patched up during the symbol table emition
  272. // (where the indicies are created).
  273. SymbolList.push_back(GblSym);
  274. GblSymLookup[GV] = 0;
  275. }
  276. }
  277. // EmitGlobal - Choose the right section for global and emit it
  278. void ELFWriter::EmitGlobal(const GlobalValue *GV) {
  279. // Check if the referenced symbol is already emitted
  280. if (GblSymLookup.find(GV) != GblSymLookup.end())
  281. return;
  282. // Handle ELF Bind, Visibility and Type for the current symbol
  283. unsigned SymBind = getGlobalELFBinding(GV);
  284. unsigned SymType = getGlobalELFType(GV);
  285. bool IsUndefSym = IsELFUndefSym(GV);
  286. ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
  287. : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
  288. if (!IsUndefSym) {
  289. assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
  290. const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
  291. // Handle special llvm globals
  292. if (EmitSpecialLLVMGlobal(GVar))
  293. return;
  294. // Get the ELF section where this global belongs from TLOF
  295. const MCSectionELF *S =
  296. (const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
  297. ELFSection &ES =
  298. getSection(S->getSectionName(), S->getType(), S->getFlags());
  299. SectionKind Kind = S->getKind();
  300. // The symbol align should update the section alignment if needed
  301. const TargetData *TD = TM.getTargetData();
  302. unsigned Align = TD->getPreferredAlignment(GVar);
  303. unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
  304. GblSym->Size = Size;
  305. if (S->IsCommon()) { // Symbol must go to a common section
  306. GblSym->SectionIdx = ELFSection::SHN_COMMON;
  307. // A new linkonce section is created for each global in the
  308. // common section, the default alignment is 1 and the symbol
  309. // value contains its alignment.
  310. ES.Align = 1;
  311. GblSym->Value = Align;
  312. } else if (Kind.isBSS() || Kind.isThreadBSS()) { // Symbol goes to BSS.
  313. GblSym->SectionIdx = ES.SectionIdx;
  314. // Update the size with alignment and the next object can
  315. // start in the right offset in the section
  316. if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
  317. ES.Align = std::max(ES.Align, Align);
  318. // GblSym->Value should contain the virtual offset inside the section.
  319. // Virtual because the BSS space is not allocated on ELF objects
  320. GblSym->Value = ES.Size;
  321. ES.Size += Size;
  322. } else { // The symbol must go to some kind of data section
  323. GblSym->SectionIdx = ES.SectionIdx;
  324. // GblSym->Value should contain the symbol offset inside the section,
  325. // and all symbols should start on their required alignment boundary
  326. ES.Align = std::max(ES.Align, Align);
  327. ES.emitAlignment(Align);
  328. GblSym->Value = ES.size();
  329. // Emit the global to the data section 'ES'
  330. EmitGlobalConstant(GVar->getInitializer(), ES);
  331. }
  332. }
  333. AddToSymbolList(GblSym);
  334. }
  335. void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
  336. ELFSection &GblS) {
  337. // Print the fields in successive locations. Pad to align if needed!
  338. const TargetData *TD = TM.getTargetData();
  339. unsigned Size = TD->getTypeAllocSize(CVS->getType());
  340. const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
  341. uint64_t sizeSoFar = 0;
  342. for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
  343. const Constant* field = CVS->getOperand(i);
  344. // Check if padding is needed and insert one or more 0s.
  345. uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
  346. uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
  347. - cvsLayout->getElementOffset(i)) - fieldSize;
  348. sizeSoFar += fieldSize + padSize;
  349. // Now print the actual field value.
  350. EmitGlobalConstant(field, GblS);
  351. // Insert padding - this may include padding to increase the size of the
  352. // current field up to the ABI size (if the struct is not packed) as well
  353. // as padding to ensure that the next field starts at the right offset.
  354. GblS.emitZeros(padSize);
  355. }
  356. assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
  357. "Layout of constant struct may be incorrect!");
  358. }
  359. void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
  360. const TargetData *TD = TM.getTargetData();
  361. unsigned Size = TD->getTypeAllocSize(CV->getType());
  362. if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
  363. for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
  364. EmitGlobalConstant(CVA->getOperand(i), GblS);
  365. return;
  366. } else if (isa<ConstantAggregateZero>(CV)) {
  367. GblS.emitZeros(Size);
  368. return;
  369. } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
  370. EmitGlobalConstantStruct(CVS, GblS);
  371. return;
  372. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  373. APInt Val = CFP->getValueAPF().bitcastToAPInt();
  374. if (CFP->getType() == Type::getDoubleTy(CV->getContext()))
  375. GblS.emitWord64(Val.getZExtValue());
  376. else if (CFP->getType() == Type::getFloatTy(CV->getContext()))
  377. GblS.emitWord32(Val.getZExtValue());
  378. else if (CFP->getType() == Type::getX86_FP80Ty(CV->getContext())) {
  379. unsigned PadSize =
  380. TD->getTypeAllocSize(Type::getX86_FP80Ty(CV->getContext()))-
  381. TD->getTypeStoreSize(Type::getX86_FP80Ty(CV->getContext()));
  382. GblS.emitWordFP80(Val.getRawData(), PadSize);
  383. } else if (CFP->getType() == Type::getPPC_FP128Ty(CV->getContext()))
  384. llvm_unreachable("PPC_FP128Ty global emission not implemented");
  385. return;
  386. } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  387. if (Size == 1)
  388. GblS.emitByte(CI->getZExtValue());
  389. else if (Size == 2)
  390. GblS.emitWord16(CI->getZExtValue());
  391. else if (Size == 4)
  392. GblS.emitWord32(CI->getZExtValue());
  393. else
  394. EmitGlobalConstantLargeInt(CI, GblS);
  395. return;
  396. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
  397. const VectorType *PTy = CP->getType();
  398. for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
  399. EmitGlobalConstant(CP->getOperand(I), GblS);
  400. return;
  401. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
  402. // Resolve a constant expression which returns a (Constant, Offset)
  403. // pair. If 'Res.first' is a GlobalValue, emit a relocation with
  404. // the offset 'Res.second', otherwise emit a global constant like
  405. // it is always done for not contant expression types.
  406. CstExprResTy Res = ResolveConstantExpr(CE);
  407. const Constant *Op = Res.first;
  408. if (isa<GlobalValue>(Op))
  409. EmitGlobalDataRelocation(cast<const GlobalValue>(Op),
  410. TD->getTypeAllocSize(Op->getType()),
  411. GblS, Res.second);
  412. else
  413. EmitGlobalConstant(Op, GblS);
  414. return;
  415. } else if (CV->getType()->getTypeID() == Type::PointerTyID) {
  416. // Fill the data entry with zeros or emit a relocation entry
  417. if (isa<ConstantPointerNull>(CV))
  418. GblS.emitZeros(Size);
  419. else
  420. EmitGlobalDataRelocation(cast<const GlobalValue>(CV),
  421. Size, GblS);
  422. return;
  423. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
  424. // This is a constant address for a global variable or function and
  425. // therefore must be referenced using a relocation entry.
  426. EmitGlobalDataRelocation(GV, Size, GblS);
  427. return;
  428. }
  429. std::string msg;
  430. raw_string_ostream ErrorMsg(msg);
  431. ErrorMsg << "Constant unimp for type: " << *CV->getType();
  432. llvm_report_error(ErrorMsg.str());
  433. }
  434. // ResolveConstantExpr - Resolve the constant expression until it stop
  435. // yielding other constant expressions.
  436. CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
  437. const TargetData *TD = TM.getTargetData();
  438. // There ins't constant expression inside others anymore
  439. if (!isa<ConstantExpr>(CV))
  440. return std::make_pair(CV, 0);
  441. const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
  442. switch (CE->getOpcode()) {
  443. case Instruction::BitCast:
  444. return ResolveConstantExpr(CE->getOperand(0));
  445. case Instruction::GetElementPtr: {
  446. const Constant *ptrVal = CE->getOperand(0);
  447. SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
  448. int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
  449. idxVec.size());
  450. return std::make_pair(ptrVal, Offset);
  451. }
  452. case Instruction::IntToPtr: {
  453. Constant *Op = CE->getOperand(0);
  454. Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
  455. false/*ZExt*/);
  456. return ResolveConstantExpr(Op);
  457. }
  458. case Instruction::PtrToInt: {
  459. Constant *Op = CE->getOperand(0);
  460. const Type *Ty = CE->getType();
  461. // We can emit the pointer value into this slot if the slot is an
  462. // integer slot greater or equal to the size of the pointer.
  463. if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
  464. return ResolveConstantExpr(Op);
  465. llvm_unreachable("Integer size less then pointer size");
  466. }
  467. case Instruction::Add:
  468. case Instruction::Sub: {
  469. // Only handle cases where there's a constant expression with GlobalValue
  470. // as first operand and ConstantInt as second, which are the cases we can
  471. // solve direclty using a relocation entry. GlobalValue=Op0, CstInt=Op1
  472. // 1) Instruction::Add => (global) + CstInt
  473. // 2) Instruction::Sub => (global) + -CstInt
  474. const Constant *Op0 = CE->getOperand(0);
  475. const Constant *Op1 = CE->getOperand(1);
  476. assert(isa<ConstantInt>(Op1) && "Op1 must be a ConstantInt");
  477. CstExprResTy Res = ResolveConstantExpr(Op0);
  478. assert(isa<GlobalValue>(Res.first) && "Op0 must be a GlobalValue");
  479. const APInt &RHS = cast<ConstantInt>(Op1)->getValue();
  480. switch (CE->getOpcode()) {
  481. case Instruction::Add:
  482. return std::make_pair(Res.first, RHS.getSExtValue());
  483. case Instruction::Sub:
  484. return std::make_pair(Res.first, (-RHS).getSExtValue());
  485. }
  486. }
  487. }
  488. std::string msg(CE->getOpcodeName());
  489. raw_string_ostream ErrorMsg(msg);
  490. ErrorMsg << ": Unsupported ConstantExpr type";
  491. llvm_report_error(ErrorMsg.str());
  492. return std::make_pair(CV, 0); // silence warning
  493. }
  494. void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
  495. ELFSection &GblS, int64_t Offset) {
  496. // Create the relocation entry for the global value
  497. MachineRelocation MR =
  498. MachineRelocation::getGV(GblS.getCurrentPCOffset(),
  499. TEW->getAbsoluteLabelMachineRelTy(),
  500. const_cast<GlobalValue*>(GV),
  501. Offset);
  502. // Fill the data entry with zeros
  503. GblS.emitZeros(Size);
  504. // Add the relocation entry for the current data section
  505. GblS.addRelocation(MR);
  506. }
  507. void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
  508. ELFSection &S) {
  509. const TargetData *TD = TM.getTargetData();
  510. unsigned BitWidth = CI->getBitWidth();
  511. assert(isPowerOf2_32(BitWidth) &&
  512. "Non-power-of-2-sized integers not handled!");
  513. const uint64_t *RawData = CI->getValue().getRawData();
  514. uint64_t Val = 0;
  515. for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
  516. Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
  517. S.emitWord64(Val);
  518. }
  519. }
  520. /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
  521. /// special global used by LLVM. If so, emit it and return true, otherwise
  522. /// do nothing and return false.
  523. bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
  524. if (GV->getName() == "llvm.used")
  525. llvm_unreachable("not implemented yet");
  526. // Ignore debug and non-emitted data. This handles llvm.compiler.used.
  527. if (GV->getSection() == "llvm.metadata" ||
  528. GV->hasAvailableExternallyLinkage())
  529. return true;
  530. if (!GV->hasAppendingLinkage()) return false;
  531. assert(GV->hasInitializer() && "Not a special LLVM global!");
  532. const TargetData *TD = TM.getTargetData();
  533. unsigned Align = TD->getPointerPrefAlignment();
  534. if (GV->getName() == "llvm.global_ctors") {
  535. ELFSection &Ctor = getCtorSection();
  536. Ctor.emitAlignment(Align);
  537. EmitXXStructorList(GV->getInitializer(), Ctor);
  538. return true;
  539. }
  540. if (GV->getName() == "llvm.global_dtors") {
  541. ELFSection &Dtor = getDtorSection();
  542. Dtor.emitAlignment(Align);
  543. EmitXXStructorList(GV->getInitializer(), Dtor);
  544. return true;
  545. }
  546. return false;
  547. }
  548. /// EmitXXStructorList - Emit the ctor or dtor list. This just emits out the
  549. /// function pointers, ignoring the init priority.
  550. void ELFWriter::EmitXXStructorList(Constant *List, ELFSection &Xtor) {
  551. // Should be an array of '{ int, void ()* }' structs. The first value is the
  552. // init priority, which we ignore.
  553. if (!isa<ConstantArray>(List)) return;
  554. ConstantArray *InitList = cast<ConstantArray>(List);
  555. for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
  556. if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
  557. if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
  558. if (CS->getOperand(1)->isNullValue())
  559. return; // Found a null terminator, exit printing.
  560. // Emit the function pointer.
  561. EmitGlobalConstant(CS->getOperand(1), Xtor);
  562. }
  563. }
  564. bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
  565. // Nothing to do here, this is all done through the ElfCE object above.
  566. return false;
  567. }
  568. /// doFinalization - Now that the module has been completely processed, emit
  569. /// the ELF file to 'O'.
  570. bool ELFWriter::doFinalization(Module &M) {
  571. // Emit .data section placeholder
  572. getDataSection();
  573. // Emit .bss section placeholder
  574. getBSSSection();
  575. // Build and emit data, bss and "common" sections.
  576. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  577. I != E; ++I)
  578. EmitGlobal(I);
  579. // Emit all pending globals
  580. for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
  581. I != E; ++I)
  582. EmitGlobal(*I);
  583. // Emit all pending externals
  584. for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
  585. I != E; ++I)
  586. SymbolList.push_back(ELFSym::getExtSym(*I));
  587. // Emit non-executable stack note
  588. if (TAI->getNonexecutableStackDirective())
  589. getNonExecStackSection();
  590. // Emit a symbol for each section created until now, skip null section
  591. for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
  592. ELFSection &ES = *SectionList[i];
  593. ELFSym *SectionSym = ELFSym::getSectionSym();
  594. SectionSym->SectionIdx = ES.SectionIdx;
  595. SymbolList.push_back(SectionSym);
  596. ES.Sym = SymbolList.back();
  597. }
  598. // Emit string table
  599. EmitStringTable(M.getModuleIdentifier());
  600. // Emit the symbol table now, if non-empty.
  601. EmitSymbolTable();
  602. // Emit the relocation sections.
  603. EmitRelocations();
  604. // Emit the sections string table.
  605. EmitSectionTableStringTable();
  606. // Dump the sections and section table to the .o file.
  607. OutputSectionsAndSectionTable();
  608. // We are done with the abstract symbols.
  609. SymbolList.clear();
  610. SectionList.clear();
  611. NumSections = 0;
  612. // Release the name mangler object.
  613. delete Mang; Mang = 0;
  614. return false;
  615. }
  616. // RelocateField - Patch relocatable field with 'Offset' in 'BO'
  617. // using a 'Value' of known 'Size'
  618. void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
  619. int64_t Value, unsigned Size) {
  620. if (Size == 32)
  621. BO.fixWord32(Value, Offset);
  622. else if (Size == 64)
  623. BO.fixWord64(Value, Offset);
  624. else
  625. llvm_unreachable("don't know howto patch relocatable field");
  626. }
  627. /// EmitRelocations - Emit relocations
  628. void ELFWriter::EmitRelocations() {
  629. // True if the target uses the relocation entry to hold the addend,
  630. // otherwise the addend is written directly to the relocatable field.
  631. bool HasRelA = TEW->hasRelocationAddend();
  632. // Create Relocation sections for each section which needs it.
  633. for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
  634. ELFSection &S = *SectionList[i];
  635. // This section does not have relocations
  636. if (!S.hasRelocations()) continue;
  637. ELFSection &RelSec = getRelocSection(S);
  638. // 'Link' - Section hdr idx of the associated symbol table
  639. // 'Info' - Section hdr idx of the section to which the relocation applies
  640. ELFSection &SymTab = getSymbolTableSection();
  641. RelSec.Link = SymTab.SectionIdx;
  642. RelSec.Info = S.SectionIdx;
  643. RelSec.EntSize = TEW->getRelocationEntrySize();
  644. // Get the relocations from Section
  645. std::vector<MachineRelocation> Relos = S.getRelocations();
  646. for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
  647. MRE = Relos.end(); MRI != MRE; ++MRI) {
  648. MachineRelocation &MR = *MRI;
  649. // Relocatable field offset from the section start
  650. unsigned RelOffset = MR.getMachineCodeOffset();
  651. // Symbol index in the symbol table
  652. unsigned SymIdx = 0;
  653. // Target specific relocation field type and size
  654. unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
  655. unsigned RelTySize = TEW->getRelocationTySize(RelType);
  656. int64_t Addend = 0;
  657. // There are several machine relocations types, and each one of
  658. // them needs a different approach to retrieve the symbol table index.
  659. if (MR.isGlobalValue()) {
  660. const GlobalValue *G = MR.getGlobalValue();
  661. int64_t GlobalOffset = MR.getConstantVal();
  662. SymIdx = GblSymLookup[G];
  663. if (G->hasPrivateLinkage()) {
  664. // If the target uses a section offset in the relocation:
  665. // SymIdx + Addend = section sym for global + section offset
  666. unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
  667. Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
  668. SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
  669. } else {
  670. Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
  671. }
  672. } else if (MR.isExternalSymbol()) {
  673. const char *ExtSym = MR.getExternalSymbol();
  674. SymIdx = ExtSymLookup[ExtSym];
  675. Addend = TEW->getDefaultAddendForRelTy(RelType);
  676. } else {
  677. // Get the symbol index for the section symbol
  678. unsigned SectionIdx = MR.getConstantVal();
  679. SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
  680. // The symbol offset inside the section
  681. int64_t SymOffset = (int64_t)MR.getResultPointer();
  682. // For pc relative relocations where symbols are defined in the same
  683. // section they are referenced, ignore the relocation entry and patch
  684. // the relocatable field with the symbol offset directly.
  685. if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
  686. int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
  687. RelocateField(S, RelOffset, Value, RelTySize);
  688. continue;
  689. }
  690. Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
  691. }
  692. // The target without addend on the relocation symbol must be
  693. // patched in the relocation place itself to contain the addend
  694. // otherwise write zeros to make sure there is no garbage there
  695. RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
  696. // Get the relocation entry and emit to the relocation section
  697. ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
  698. EmitRelocation(RelSec, Rel, HasRelA);
  699. }
  700. }
  701. }
  702. /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
  703. void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
  704. bool HasRelA) {
  705. RelSec.emitWord(Rel.getOffset());
  706. RelSec.emitWord(Rel.getInfo(is64Bit));
  707. if (HasRelA)
  708. RelSec.emitWord(Rel.getAddend());
  709. }
  710. /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
  711. void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
  712. if (is64Bit) {
  713. SymbolTable.emitWord32(Sym.NameIdx);
  714. SymbolTable.emitByte(Sym.Info);
  715. SymbolTable.emitByte(Sym.Other);
  716. SymbolTable.emitWord16(Sym.SectionIdx);
  717. SymbolTable.emitWord64(Sym.Value);
  718. SymbolTable.emitWord64(Sym.Size);
  719. } else {
  720. SymbolTable.emitWord32(Sym.NameIdx);
  721. SymbolTable.emitWord32(Sym.Value);
  722. SymbolTable.emitWord32(Sym.Size);
  723. SymbolTable.emitByte(Sym.Info);
  724. SymbolTable.emitByte(Sym.Other);
  725. SymbolTable.emitWord16(Sym.SectionIdx);
  726. }
  727. }
  728. /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
  729. /// Section Header Table
  730. void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
  731. const ELFSection &SHdr) {
  732. SHdrTab.emitWord32(SHdr.NameIdx);
  733. SHdrTab.emitWord32(SHdr.Type);
  734. if (is64Bit) {
  735. SHdrTab.emitWord64(SHdr.Flags);
  736. SHdrTab.emitWord(SHdr.Addr);
  737. SHdrTab.emitWord(SHdr.Offset);
  738. SHdrTab.emitWord64(SHdr.Size);
  739. SHdrTab.emitWord32(SHdr.Link);
  740. SHdrTab.emitWord32(SHdr.Info);
  741. SHdrTab.emitWord64(SHdr.Align);
  742. SHdrTab.emitWord64(SHdr.EntSize);
  743. } else {
  744. SHdrTab.emitWord32(SHdr.Flags);
  745. SHdrTab.emitWord(SHdr.Addr);
  746. SHdrTab.emitWord(SHdr.Offset);
  747. SHdrTab.emitWord32(SHdr.Size);
  748. SHdrTab.emitWord32(SHdr.Link);
  749. SHdrTab.emitWord32(SHdr.Info);
  750. SHdrTab.emitWord32(SHdr.Align);
  751. SHdrTab.emitWord32(SHdr.EntSize);
  752. }
  753. }
  754. /// EmitStringTable - If the current symbol table is non-empty, emit the string
  755. /// table for it
  756. void ELFWriter::EmitStringTable(const std::string &ModuleName) {
  757. if (!SymbolList.size()) return; // Empty symbol table.
  758. ELFSection &StrTab = getStringTableSection();
  759. // Set the zero'th symbol to a null byte, as required.
  760. StrTab.emitByte(0);
  761. // Walk on the symbol list and write symbol names into the string table.
  762. unsigned Index = 1;
  763. for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
  764. ELFSym &Sym = *(*I);
  765. std::string Name;
  766. if (Sym.isGlobalValue())
  767. Name.append(Mang->getMangledName(Sym.getGlobalValue()));
  768. else if (Sym.isExternalSym())
  769. Name.append(Sym.getExternalSymbol());
  770. else if (Sym.isFileType())
  771. Name.append(ModuleName);
  772. if (Name.empty()) {
  773. Sym.NameIdx = 0;
  774. } else {
  775. Sym.NameIdx = Index;
  776. StrTab.emitString(Name);
  777. // Keep track of the number of bytes emitted to this section.
  778. Index += Name.size()+1;
  779. }
  780. }
  781. assert(Index == StrTab.size());
  782. StrTab.Size = Index;
  783. }
  784. // SortSymbols - On the symbol table local symbols must come before
  785. // all other symbols with non-local bindings. The return value is
  786. // the position of the first non local symbol.
  787. unsigned ELFWriter::SortSymbols() {
  788. unsigned FirstNonLocalSymbol;
  789. std::vector<ELFSym*> LocalSyms, OtherSyms;
  790. for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
  791. if ((*I)->isLocalBind())
  792. LocalSyms.push_back(*I);
  793. else
  794. OtherSyms.push_back(*I);
  795. }
  796. SymbolList.clear();
  797. FirstNonLocalSymbol = LocalSyms.size();
  798. for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
  799. SymbolList.push_back(LocalSyms[i]);
  800. for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
  801. SymbolList.push_back(*I);
  802. LocalSyms.clear();
  803. OtherSyms.clear();
  804. return FirstNonLocalSymbol;
  805. }
  806. /// EmitSymbolTable - Emit the symbol table itself.
  807. void ELFWriter::EmitSymbolTable() {
  808. if (!SymbolList.size()) return; // Empty symbol table.
  809. // Now that we have emitted the string table and know the offset into the
  810. // string table of each symbol, emit the symbol table itself.
  811. ELFSection &SymTab = getSymbolTableSection();
  812. SymTab.Align = TEW->getPrefELFAlignment();
  813. // Section Index of .strtab.
  814. SymTab.Link = getStringTableSection().SectionIdx;
  815. // Size of each symtab entry.
  816. SymTab.EntSize = TEW->getSymTabEntrySize();
  817. // Reorder the symbol table with local symbols first!
  818. unsigned FirstNonLocalSymbol = SortSymbols();
  819. // Emit all the symbols to the symbol table.
  820. for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
  821. ELFSym &Sym = *SymbolList[i];
  822. // Emit symbol to the symbol table
  823. EmitSymbol(SymTab, Sym);
  824. // Record the symbol table index for each symbol
  825. if (Sym.isGlobalValue())
  826. GblSymLookup[Sym.getGlobalValue()] = i;
  827. else if (Sym.isExternalSym())
  828. ExtSymLookup[Sym.getExternalSymbol()] = i;
  829. // Keep track on the symbol index into the symbol table
  830. Sym.SymTabIdx = i;
  831. }
  832. // One greater than the symbol table index of the last local symbol
  833. SymTab.Info = FirstNonLocalSymbol;
  834. SymTab.Size = SymTab.size();
  835. }
  836. /// EmitSectionTableStringTable - This method adds and emits a section for the
  837. /// ELF Section Table string table: the string table that holds all of the
  838. /// section names.
  839. void ELFWriter::EmitSectionTableStringTable() {
  840. // First step: add the section for the string table to the list of sections:
  841. ELFSection &SHStrTab = getSectionHeaderStringTableSection();
  842. // Now that we know which section number is the .shstrtab section, update the
  843. // e_shstrndx entry in the ELF header.
  844. ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
  845. // Set the NameIdx of each section in the string table and emit the bytes for
  846. // the string table.
  847. unsigned Index = 0;
  848. for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
  849. ELFSection &S = *(*I);
  850. // Set the index into the table. Note if we have lots of entries with
  851. // common suffixes, we could memoize them here if we cared.
  852. S.NameIdx = Index;
  853. SHStrTab.emitString(S.getName());
  854. // Keep track of the number of bytes emitted to this section.
  855. Index += S.getName().size()+1;
  856. }
  857. // Set the size of .shstrtab now that we know what it is.
  858. assert(Index == SHStrTab.size());
  859. SHStrTab.Size = Index;
  860. }
  861. /// OutputSectionsAndSectionTable - Now that we have constructed the file header
  862. /// and all of the sections, emit these to the ostream destination and emit the
  863. /// SectionTable.
  864. void ELFWriter::OutputSectionsAndSectionTable() {
  865. // Pass #1: Compute the file offset for each section.
  866. size_t FileOff = ElfHdr.size(); // File header first.
  867. // Adjust alignment of all section if needed, skip the null section.
  868. for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
  869. ELFSection &ES = *SectionList[i];
  870. if (!ES.size()) {
  871. ES.Offset = FileOff;
  872. continue;
  873. }
  874. // Update Section size
  875. if (!ES.Size)
  876. ES.Size = ES.size();
  877. // Align FileOff to whatever the alignment restrictions of the section are.
  878. if (ES.Align)
  879. FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
  880. ES.Offset = FileOff;
  881. FileOff += ES.Size;
  882. }
  883. // Align Section Header.
  884. unsigned TableAlign = TEW->getPrefELFAlignment();
  885. FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
  886. // Now that we know where all of the sections will be emitted, set the e_shnum
  887. // entry in the ELF header.
  888. ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
  889. // Now that we know the offset in the file of the section table, update the
  890. // e_shoff address in the ELF header.
  891. ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
  892. // Now that we know all of the data in the file header, emit it and all of the
  893. // sections!
  894. O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
  895. FileOff = ElfHdr.size();
  896. // Section Header Table blob
  897. BinaryObject SHdrTable(isLittleEndian, is64Bit);
  898. // Emit all of sections to the file and build the section header table.
  899. for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
  900. ELFSection &S = *(*I);
  901. DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
  902. << ", Size: " << S.Size << ", Offset: " << S.Offset
  903. << ", SectionData Size: " << S.size() << "\n";
  904. // Align FileOff to whatever the alignment restrictions of the section are.
  905. if (S.size()) {
  906. if (S.Align) {
  907. for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
  908. FileOff != NewFileOff; ++FileOff)
  909. O << (char)0xAB;
  910. }
  911. O.write((char *)&S.getData()[0], S.Size);
  912. FileOff += S.Size;
  913. }
  914. EmitSectionHeader(SHdrTable, S);
  915. }
  916. // Align output for the section table.
  917. for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
  918. FileOff != NewFileOff; ++FileOff)
  919. O << (char)0xAB;
  920. // Emit the section table itself.
  921. O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
  922. }