ELFWriter.cpp 39 KB

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