ELFWriter.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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/Target/TargetAsmInfo.h"
  45. #include "llvm/Target/TargetData.h"
  46. #include "llvm/Target/TargetELFWriterInfo.h"
  47. #include "llvm/Target/TargetMachine.h"
  48. #include "llvm/Support/Mangler.h"
  49. #include "llvm/Support/Streams.h"
  50. #include "llvm/Support/raw_ostream.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/ErrorHandling.h"
  53. using namespace llvm;
  54. char ELFWriter::ID = 0;
  55. /// AddELFWriter - Add the ELF writer to the function pass manager
  56. ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
  57. raw_ostream &O,
  58. TargetMachine &TM) {
  59. ELFWriter *EW = new ELFWriter(O, TM);
  60. PM.add(EW);
  61. return EW->getObjectCodeEmitter();
  62. }
  63. //===----------------------------------------------------------------------===//
  64. // ELFWriter Implementation
  65. //===----------------------------------------------------------------------===//
  66. ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
  67. : MachineFunctionPass(&ID), O(o), TM(tm),
  68. is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
  69. isLittleEndian(TM.getTargetData()->isLittleEndian()),
  70. ElfHdr(isLittleEndian, is64Bit) {
  71. TAI = TM.getTargetAsmInfo();
  72. TEW = TM.getELFWriterInfo();
  73. // Create the object code emitter object for this target.
  74. ElfCE = new ELFCodeEmitter(*this);
  75. // Inital number of sections
  76. NumSections = 0;
  77. }
  78. ELFWriter::~ELFWriter() {
  79. delete ElfCE;
  80. }
  81. // doInitialization - Emit the file header and all of the global variables for
  82. // the module to the ELF file.
  83. bool ELFWriter::doInitialization(Module &M) {
  84. Mang = new Mangler(M);
  85. // ELF Header
  86. // ----------
  87. // Fields e_shnum e_shstrndx are only known after all section have
  88. // been emitted. They locations in the ouput buffer are recorded so
  89. // to be patched up later.
  90. //
  91. // Note
  92. // ----
  93. // emitWord method behaves differently for ELF32 and ELF64, writing
  94. // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
  95. ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
  96. ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
  97. ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
  98. ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
  99. ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
  100. ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
  101. ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
  102. ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
  103. ElfHdr.emitWord16(ET_REL); // e_type
  104. ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
  105. ElfHdr.emitWord32(EV_CURRENT); // e_version
  106. ElfHdr.emitWord(0); // e_entry, no entry point in .o file
  107. ElfHdr.emitWord(0); // e_phoff, no program header for .o
  108. ELFHdr_e_shoff_Offset = ElfHdr.size();
  109. ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
  110. ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
  111. ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
  112. ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
  113. ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
  114. // e_shentsize = Section header entry size
  115. ElfHdr.emitWord16(TEW->getSHdrSize());
  116. // e_shnum = # of section header ents
  117. ELFHdr_e_shnum_Offset = ElfHdr.size();
  118. ElfHdr.emitWord16(0); // Placeholder
  119. // e_shstrndx = Section # of '.shstrtab'
  120. ELFHdr_e_shstrndx_Offset = ElfHdr.size();
  121. ElfHdr.emitWord16(0); // Placeholder
  122. // Add the null section, which is required to be first in the file.
  123. getNullSection();
  124. return false;
  125. }
  126. unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
  127. switch (GV->getVisibility()) {
  128. default:
  129. LLVM_UNREACHABLE("unknown visibility type");
  130. case GlobalValue::DefaultVisibility:
  131. return ELFSym::STV_DEFAULT;
  132. case GlobalValue::HiddenVisibility:
  133. return ELFSym::STV_HIDDEN;
  134. case GlobalValue::ProtectedVisibility:
  135. return ELFSym::STV_PROTECTED;
  136. }
  137. return 0;
  138. }
  139. unsigned ELFWriter::getGlobalELFLinkage(const GlobalValue *GV) {
  140. if (GV->hasInternalLinkage())
  141. return ELFSym::STB_LOCAL;
  142. if (GV->hasWeakLinkage())
  143. return ELFSym::STB_WEAK;
  144. return ELFSym::STB_GLOBAL;
  145. }
  146. // getElfSectionFlags - Get the ELF Section Header based on the
  147. // flags defined in ELFTargetAsmInfo.
  148. unsigned ELFWriter::getElfSectionFlags(unsigned Flags) {
  149. unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
  150. if (Flags & SectionFlags::Code)
  151. ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
  152. if (Flags & SectionFlags::Writeable)
  153. ElfSectionFlags |= ELFSection::SHF_WRITE;
  154. if (Flags & SectionFlags::Mergeable)
  155. ElfSectionFlags |= ELFSection::SHF_MERGE;
  156. if (Flags & SectionFlags::TLS)
  157. ElfSectionFlags |= ELFSection::SHF_TLS;
  158. if (Flags & SectionFlags::Strings)
  159. ElfSectionFlags |= ELFSection::SHF_STRINGS;
  160. return ElfSectionFlags;
  161. }
  162. // For global symbols without a section, return the Null section as a
  163. // placeholder
  164. ELFSection &ELFWriter::getGlobalSymELFSection(const GlobalVariable *GV,
  165. ELFSym &Sym) {
  166. // If this is a declaration, the symbol does not have a section.
  167. if (!GV->hasInitializer()) {
  168. Sym.SectionIdx = ELFSection::SHN_UNDEF;
  169. return getNullSection();
  170. }
  171. // Get the name and flags of the section for the global
  172. const Section *S = TAI->SectionForGlobal(GV);
  173. unsigned SectionType = ELFSection::SHT_PROGBITS;
  174. unsigned SectionFlags = getElfSectionFlags(S->getFlags());
  175. DOUT << "Section " << S->getName() << " for global " << GV->getName() << "\n";
  176. const TargetData *TD = TM.getTargetData();
  177. unsigned Align = TD->getPreferredAlignment(GV);
  178. Constant *CV = GV->getInitializer();
  179. // If this global has a zero initializer, go to .bss or common section.
  180. // Variables are part of the common block if they are zero initialized
  181. // and allowed to be merged with other symbols.
  182. if (CV->isNullValue() || isa<UndefValue>(CV)) {
  183. SectionType = ELFSection::SHT_NOBITS;
  184. ELFSection &ElfS = getSection(S->getName(), SectionType, SectionFlags);
  185. if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
  186. GV->hasCommonLinkage()) {
  187. Sym.SectionIdx = ELFSection::SHN_COMMON;
  188. Sym.IsCommon = true;
  189. ElfS.Align = 1;
  190. return ElfS;
  191. }
  192. Sym.IsBss = true;
  193. Sym.SectionIdx = ElfS.SectionIdx;
  194. if (Align) ElfS.Size = (ElfS.Size + Align-1) & ~(Align-1);
  195. ElfS.Align = std::max(ElfS.Align, Align);
  196. return ElfS;
  197. }
  198. Sym.IsConstant = true;
  199. ELFSection &ElfS = getSection(S->getName(), SectionType, SectionFlags);
  200. Sym.SectionIdx = ElfS.SectionIdx;
  201. ElfS.Align = std::max(ElfS.Align, Align);
  202. return ElfS;
  203. }
  204. void ELFWriter::EmitFunctionDeclaration(const Function *F) {
  205. ELFSym GblSym(F);
  206. GblSym.setBind(ELFSym::STB_GLOBAL);
  207. GblSym.setType(ELFSym::STT_NOTYPE);
  208. GblSym.setVisibility(ELFSym::STV_DEFAULT);
  209. GblSym.SectionIdx = ELFSection::SHN_UNDEF;
  210. SymbolList.push_back(GblSym);
  211. }
  212. void ELFWriter::EmitGlobalVar(const GlobalVariable *GV) {
  213. unsigned SymBind = getGlobalELFLinkage(GV);
  214. unsigned Align=0, Size=0;
  215. ELFSym GblSym(GV);
  216. GblSym.setBind(SymBind);
  217. GblSym.setVisibility(getGlobalELFVisibility(GV));
  218. if (GV->hasInitializer()) {
  219. GblSym.setType(ELFSym::STT_OBJECT);
  220. const TargetData *TD = TM.getTargetData();
  221. Align = TD->getPreferredAlignment(GV);
  222. Size = TD->getTypeAllocSize(GV->getInitializer()->getType());
  223. GblSym.Size = Size;
  224. } else {
  225. GblSym.setType(ELFSym::STT_NOTYPE);
  226. }
  227. ELFSection &GblSection = getGlobalSymELFSection(GV, GblSym);
  228. if (GblSym.IsCommon) {
  229. GblSym.Value = Align;
  230. } else if (GblSym.IsBss) {
  231. GblSym.Value = GblSection.Size;
  232. GblSection.Size += Size;
  233. } else if (GblSym.IsConstant){
  234. // GblSym.Value should contain the symbol index inside the section,
  235. // and all symbols should start on their required alignment boundary
  236. GblSym.Value = (GblSection.size() + (Align-1)) & (-Align);
  237. GblSection.emitAlignment(Align);
  238. EmitGlobalConstant(GV->getInitializer(), GblSection);
  239. }
  240. // Local symbols should come first on the symbol table.
  241. if (!GV->hasPrivateLinkage()) {
  242. if (SymBind == ELFSym::STB_LOCAL)
  243. SymbolList.push_front(GblSym);
  244. else
  245. SymbolList.push_back(GblSym);
  246. }
  247. }
  248. void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
  249. ELFSection &GblS) {
  250. // Print the fields in successive locations. Pad to align if needed!
  251. const TargetData *TD = TM.getTargetData();
  252. unsigned Size = TD->getTypeAllocSize(CVS->getType());
  253. const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
  254. uint64_t sizeSoFar = 0;
  255. for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
  256. const Constant* field = CVS->getOperand(i);
  257. // Check if padding is needed and insert one or more 0s.
  258. uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
  259. uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
  260. - cvsLayout->getElementOffset(i)) - fieldSize;
  261. sizeSoFar += fieldSize + padSize;
  262. // Now print the actual field value.
  263. EmitGlobalConstant(field, GblS);
  264. // Insert padding - this may include padding to increase the size of the
  265. // current field up to the ABI size (if the struct is not packed) as well
  266. // as padding to ensure that the next field starts at the right offset.
  267. for (unsigned p=0; p < padSize; p++)
  268. GblS.emitByte(0);
  269. }
  270. assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
  271. "Layout of constant struct may be incorrect!");
  272. }
  273. void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
  274. const TargetData *TD = TM.getTargetData();
  275. unsigned Size = TD->getTypeAllocSize(CV->getType());
  276. if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
  277. if (CVA->isString()) {
  278. std::string GblStr = CVA->getAsString();
  279. GblStr.resize(GblStr.size()-1);
  280. GblS.emitString(GblStr);
  281. } else { // Not a string. Print the values in successive locations
  282. for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
  283. EmitGlobalConstant(CVA->getOperand(i), GblS);
  284. }
  285. return;
  286. } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
  287. EmitGlobalConstantStruct(CVS, GblS);
  288. return;
  289. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
  290. uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
  291. if (CFP->getType() == Type::DoubleTy)
  292. GblS.emitWord64(Val);
  293. else if (CFP->getType() == Type::FloatTy)
  294. GblS.emitWord32(Val);
  295. else if (CFP->getType() == Type::X86_FP80Ty) {
  296. LLVM_UNREACHABLE("X86_FP80Ty global emission not implemented");
  297. } else if (CFP->getType() == Type::PPC_FP128Ty)
  298. LLVM_UNREACHABLE("PPC_FP128Ty global emission not implemented");
  299. return;
  300. } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
  301. if (Size == 4)
  302. GblS.emitWord32(CI->getZExtValue());
  303. else if (Size == 8)
  304. GblS.emitWord64(CI->getZExtValue());
  305. else
  306. LLVM_UNREACHABLE("LargeInt global emission not implemented");
  307. return;
  308. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
  309. const VectorType *PTy = CP->getType();
  310. for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
  311. EmitGlobalConstant(CP->getOperand(I), GblS);
  312. return;
  313. }
  314. LLVM_UNREACHABLE("unknown global constant");
  315. }
  316. bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
  317. // Nothing to do here, this is all done through the ElfCE object above.
  318. return false;
  319. }
  320. /// doFinalization - Now that the module has been completely processed, emit
  321. /// the ELF file to 'O'.
  322. bool ELFWriter::doFinalization(Module &M) {
  323. // Emit .data section placeholder
  324. getDataSection();
  325. // Emit .bss section placeholder
  326. getBSSSection();
  327. // Build and emit data, bss and "common" sections.
  328. for (Module::global_iterator I = M.global_begin(), E = M.global_end();
  329. I != E; ++I) {
  330. EmitGlobalVar(I);
  331. GblSymLookup[I] = 0;
  332. }
  333. // Emit all pending globals
  334. // TODO: this should be done only for referenced symbols
  335. for (SetVector<GlobalValue*>::const_iterator I = PendingGlobals.begin(),
  336. E = PendingGlobals.end(); I != E; ++I) {
  337. // No need to emit the symbol again
  338. if (GblSymLookup.find(*I) != GblSymLookup.end())
  339. continue;
  340. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
  341. EmitGlobalVar(GV);
  342. } else if (Function *F = dyn_cast<Function>(*I)) {
  343. // If function is not in GblSymLookup, it doesn't have a body,
  344. // so emit the symbol as a function declaration (no section associated)
  345. EmitFunctionDeclaration(F);
  346. } else {
  347. assert("unknown howto handle pending global");
  348. }
  349. GblSymLookup[*I] = 0;
  350. }
  351. // Emit non-executable stack note
  352. if (TAI->getNonexecutableStackDirective())
  353. getNonExecStackSection();
  354. // Emit a symbol for each section created until now
  355. for (std::map<std::string, ELFSection*>::iterator I = SectionLookup.begin(),
  356. E = SectionLookup.end(); I != E; ++I) {
  357. ELFSection *ES = I->second;
  358. // Skip null section
  359. if (ES->SectionIdx == 0) continue;
  360. ELFSym SectionSym(0);
  361. SectionSym.SectionIdx = ES->SectionIdx;
  362. SectionSym.Size = 0;
  363. SectionSym.setBind(ELFSym::STB_LOCAL);
  364. SectionSym.setType(ELFSym::STT_SECTION);
  365. SectionSym.setVisibility(ELFSym::STV_DEFAULT);
  366. // Local symbols go in the list front
  367. SymbolList.push_front(SectionSym);
  368. }
  369. // Emit string table
  370. EmitStringTable();
  371. // Emit the symbol table now, if non-empty.
  372. EmitSymbolTable();
  373. // Emit the relocation sections.
  374. EmitRelocations();
  375. // Emit the sections string table.
  376. EmitSectionTableStringTable();
  377. // Dump the sections and section table to the .o file.
  378. OutputSectionsAndSectionTable();
  379. // We are done with the abstract symbols.
  380. SectionList.clear();
  381. NumSections = 0;
  382. // Release the name mangler object.
  383. delete Mang; Mang = 0;
  384. return false;
  385. }
  386. /// EmitRelocations - Emit relocations
  387. void ELFWriter::EmitRelocations() {
  388. // Create Relocation sections for each section which needs it.
  389. for (std::list<ELFSection>::iterator I = SectionList.begin(),
  390. E = SectionList.end(); I != E; ++I) {
  391. // This section does not have relocations
  392. if (!I->hasRelocations()) continue;
  393. // Get the relocation section for section 'I'
  394. bool HasRelA = TEW->hasRelocationAddend();
  395. ELFSection &RelSec = getRelocSection(I->getName(), HasRelA,
  396. TEW->getPrefELFAlignment());
  397. // 'Link' - Section hdr idx of the associated symbol table
  398. // 'Info' - Section hdr idx of the section to which the relocation applies
  399. ELFSection &SymTab = getSymbolTableSection();
  400. RelSec.Link = SymTab.SectionIdx;
  401. RelSec.Info = I->SectionIdx;
  402. RelSec.EntSize = TEW->getRelocationEntrySize();
  403. // Get the relocations from Section
  404. std::vector<MachineRelocation> Relos = I->getRelocations();
  405. for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
  406. MRE = Relos.end(); MRI != MRE; ++MRI) {
  407. MachineRelocation &MR = *MRI;
  408. // Offset from the start of the section containing the symbol
  409. unsigned Offset = MR.getMachineCodeOffset();
  410. // Symbol index in the symbol table
  411. unsigned SymIdx = 0;
  412. // Target specific ELF relocation type
  413. unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
  414. // Constant addend used to compute the value to be stored
  415. // into the relocatable field
  416. int64_t Addend = 0;
  417. // There are several machine relocations types, and each one of
  418. // them needs a different approach to retrieve the symbol table index.
  419. if (MR.isGlobalValue()) {
  420. const GlobalValue *G = MR.getGlobalValue();
  421. SymIdx = GblSymLookup[G];
  422. Addend = TEW->getAddendForRelTy(RelType);
  423. } else {
  424. unsigned SectionIdx = MR.getConstantVal();
  425. // TODO: use a map for this.
  426. for (std::list<ELFSym>::iterator I = SymbolList.begin(),
  427. E = SymbolList.end(); I != E; ++I)
  428. if ((SectionIdx == I->SectionIdx) &&
  429. (I->getType() == ELFSym::STT_SECTION)) {
  430. SymIdx = I->SymTabIdx;
  431. break;
  432. }
  433. Addend = (uint64_t)MR.getResultPointer();
  434. }
  435. // Get the relocation entry and emit to the relocation section
  436. ELFRelocation Rel(Offset, SymIdx, RelType, HasRelA, Addend);
  437. EmitRelocation(RelSec, Rel, HasRelA);
  438. }
  439. }
  440. }
  441. /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
  442. void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
  443. bool HasRelA) {
  444. RelSec.emitWord(Rel.getOffset());
  445. RelSec.emitWord(Rel.getInfo(is64Bit));
  446. if (HasRelA)
  447. RelSec.emitWord(Rel.getAddend());
  448. }
  449. /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
  450. void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
  451. if (is64Bit) {
  452. SymbolTable.emitWord32(Sym.NameIdx);
  453. SymbolTable.emitByte(Sym.Info);
  454. SymbolTable.emitByte(Sym.Other);
  455. SymbolTable.emitWord16(Sym.SectionIdx);
  456. SymbolTable.emitWord64(Sym.Value);
  457. SymbolTable.emitWord64(Sym.Size);
  458. } else {
  459. SymbolTable.emitWord32(Sym.NameIdx);
  460. SymbolTable.emitWord32(Sym.Value);
  461. SymbolTable.emitWord32(Sym.Size);
  462. SymbolTable.emitByte(Sym.Info);
  463. SymbolTable.emitByte(Sym.Other);
  464. SymbolTable.emitWord16(Sym.SectionIdx);
  465. }
  466. }
  467. /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
  468. /// Section Header Table
  469. void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
  470. const ELFSection &SHdr) {
  471. SHdrTab.emitWord32(SHdr.NameIdx);
  472. SHdrTab.emitWord32(SHdr.Type);
  473. if (is64Bit) {
  474. SHdrTab.emitWord64(SHdr.Flags);
  475. SHdrTab.emitWord(SHdr.Addr);
  476. SHdrTab.emitWord(SHdr.Offset);
  477. SHdrTab.emitWord64(SHdr.Size);
  478. SHdrTab.emitWord32(SHdr.Link);
  479. SHdrTab.emitWord32(SHdr.Info);
  480. SHdrTab.emitWord64(SHdr.Align);
  481. SHdrTab.emitWord64(SHdr.EntSize);
  482. } else {
  483. SHdrTab.emitWord32(SHdr.Flags);
  484. SHdrTab.emitWord(SHdr.Addr);
  485. SHdrTab.emitWord(SHdr.Offset);
  486. SHdrTab.emitWord32(SHdr.Size);
  487. SHdrTab.emitWord32(SHdr.Link);
  488. SHdrTab.emitWord32(SHdr.Info);
  489. SHdrTab.emitWord32(SHdr.Align);
  490. SHdrTab.emitWord32(SHdr.EntSize);
  491. }
  492. }
  493. /// EmitStringTable - If the current symbol table is non-empty, emit the string
  494. /// table for it
  495. void ELFWriter::EmitStringTable() {
  496. if (!SymbolList.size()) return; // Empty symbol table.
  497. ELFSection &StrTab = getStringTableSection();
  498. // Set the zero'th symbol to a null byte, as required.
  499. StrTab.emitByte(0);
  500. // Walk on the symbol list and write symbol names into the
  501. // string table.
  502. unsigned Index = 1;
  503. for (std::list<ELFSym>::iterator I = SymbolList.begin(),
  504. E = SymbolList.end(); I != E; ++I) {
  505. // Use the name mangler to uniquify the LLVM symbol.
  506. std::string Name;
  507. if (I->GV) Name.append(Mang->getValueName(I->GV));
  508. if (Name.empty()) {
  509. I->NameIdx = 0;
  510. } else {
  511. I->NameIdx = Index;
  512. StrTab.emitString(Name);
  513. // Keep track of the number of bytes emitted to this section.
  514. Index += Name.size()+1;
  515. }
  516. }
  517. assert(Index == StrTab.size());
  518. StrTab.Size = Index;
  519. }
  520. /// EmitSymbolTable - Emit the symbol table itself.
  521. void ELFWriter::EmitSymbolTable() {
  522. if (!SymbolList.size()) return; // Empty symbol table.
  523. unsigned FirstNonLocalSymbol = 1;
  524. // Now that we have emitted the string table and know the offset into the
  525. // string table of each symbol, emit the symbol table itself.
  526. ELFSection &SymTab = getSymbolTableSection();
  527. SymTab.Align = TEW->getPrefELFAlignment();
  528. // Section Index of .strtab.
  529. SymTab.Link = getStringTableSection().SectionIdx;
  530. // Size of each symtab entry.
  531. SymTab.EntSize = TEW->getSymTabEntrySize();
  532. // The first entry in the symtab is the null symbol
  533. ELFSym NullSym = ELFSym(0);
  534. EmitSymbol(SymTab, NullSym);
  535. // Emit all the symbols to the symbol table. Skip the null
  536. // symbol, cause it's emitted already
  537. unsigned Index = 1;
  538. for (std::list<ELFSym>::iterator I = SymbolList.begin(),
  539. E = SymbolList.end(); I != E; ++I, ++Index) {
  540. // Keep track of the first non-local symbol
  541. if (I->getBind() == ELFSym::STB_LOCAL)
  542. FirstNonLocalSymbol++;
  543. // Emit symbol to the symbol table
  544. EmitSymbol(SymTab, *I);
  545. // Record the symbol table index for each global value
  546. if (I->GV)
  547. GblSymLookup[I->GV] = Index;
  548. // Keep track on the symbol index into the symbol table
  549. I->SymTabIdx = Index;
  550. }
  551. SymTab.Info = FirstNonLocalSymbol;
  552. SymTab.Size = SymTab.size();
  553. }
  554. /// EmitSectionTableStringTable - This method adds and emits a section for the
  555. /// ELF Section Table string table: the string table that holds all of the
  556. /// section names.
  557. void ELFWriter::EmitSectionTableStringTable() {
  558. // First step: add the section for the string table to the list of sections:
  559. ELFSection &SHStrTab = getSectionHeaderStringTableSection();
  560. // Now that we know which section number is the .shstrtab section, update the
  561. // e_shstrndx entry in the ELF header.
  562. ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
  563. // Set the NameIdx of each section in the string table and emit the bytes for
  564. // the string table.
  565. unsigned Index = 0;
  566. for (std::list<ELFSection>::iterator I = SectionList.begin(),
  567. E = SectionList.end(); I != E; ++I) {
  568. // Set the index into the table. Note if we have lots of entries with
  569. // common suffixes, we could memoize them here if we cared.
  570. I->NameIdx = Index;
  571. SHStrTab.emitString(I->getName());
  572. // Keep track of the number of bytes emitted to this section.
  573. Index += I->getName().size()+1;
  574. }
  575. // Set the size of .shstrtab now that we know what it is.
  576. assert(Index == SHStrTab.size());
  577. SHStrTab.Size = Index;
  578. }
  579. /// OutputSectionsAndSectionTable - Now that we have constructed the file header
  580. /// and all of the sections, emit these to the ostream destination and emit the
  581. /// SectionTable.
  582. void ELFWriter::OutputSectionsAndSectionTable() {
  583. // Pass #1: Compute the file offset for each section.
  584. size_t FileOff = ElfHdr.size(); // File header first.
  585. // Adjust alignment of all section if needed.
  586. for (std::list<ELFSection>::iterator I = SectionList.begin(),
  587. E = SectionList.end(); I != E; ++I) {
  588. // Section idx 0 has 0 offset
  589. if (!I->SectionIdx)
  590. continue;
  591. if (!I->size()) {
  592. I->Offset = FileOff;
  593. continue;
  594. }
  595. // Update Section size
  596. if (!I->Size)
  597. I->Size = I->size();
  598. // Align FileOff to whatever the alignment restrictions of the section are.
  599. if (I->Align)
  600. FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
  601. I->Offset = FileOff;
  602. FileOff += I->Size;
  603. }
  604. // Align Section Header.
  605. unsigned TableAlign = TEW->getPrefELFAlignment();
  606. FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
  607. // Now that we know where all of the sections will be emitted, set the e_shnum
  608. // entry in the ELF header.
  609. ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
  610. // Now that we know the offset in the file of the section table, update the
  611. // e_shoff address in the ELF header.
  612. ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
  613. // Now that we know all of the data in the file header, emit it and all of the
  614. // sections!
  615. O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
  616. FileOff = ElfHdr.size();
  617. // Section Header Table blob
  618. BinaryObject SHdrTable(isLittleEndian, is64Bit);
  619. // Emit all of sections to the file and build the section header table.
  620. while (!SectionList.empty()) {
  621. ELFSection &S = *SectionList.begin();
  622. DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
  623. << ", Size: " << S.Size << ", Offset: " << S.Offset
  624. << ", SectionData Size: " << S.size() << "\n";
  625. // Align FileOff to whatever the alignment restrictions of the section are.
  626. if (S.size()) {
  627. if (S.Align) {
  628. for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
  629. FileOff != NewFileOff; ++FileOff)
  630. O << (char)0xAB;
  631. }
  632. O.write((char *)&S.getData()[0], S.Size);
  633. FileOff += S.Size;
  634. }
  635. EmitSectionHeader(SHdrTable, S);
  636. SectionList.pop_front();
  637. }
  638. // Align output for the section table.
  639. for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
  640. FileOff != NewFileOff; ++FileOff)
  641. O << (char)0xAB;
  642. // Emit the section table itself.
  643. O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
  644. }