ELFObjectWriter.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
  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 ELF object file writer information.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/MC/MCELFObjectWriter.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/MC/MCAsmBackend.h"
  19. #include "llvm/MC/MCAsmInfo.h"
  20. #include "llvm/MC/MCAsmLayout.h"
  21. #include "llvm/MC/MCAssembler.h"
  22. #include "llvm/MC/MCContext.h"
  23. #include "llvm/MC/MCExpr.h"
  24. #include "llvm/MC/MCFixupKindInfo.h"
  25. #include "llvm/MC/MCObjectWriter.h"
  26. #include "llvm/MC/MCSectionELF.h"
  27. #include "llvm/MC/MCSymbolELF.h"
  28. #include "llvm/MC/MCValue.h"
  29. #include "llvm/MC/StringTableBuilder.h"
  30. #include "llvm/Support/Compression.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ELF.h"
  33. #include "llvm/Support/Endian.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include <vector>
  36. using namespace llvm;
  37. #undef DEBUG_TYPE
  38. #define DEBUG_TYPE "reloc-info"
  39. namespace {
  40. typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
  41. class ELFObjectWriter;
  42. class SymbolTableWriter {
  43. ELFObjectWriter &EWriter;
  44. bool Is64Bit;
  45. // indexes we are going to write to .symtab_shndx.
  46. std::vector<uint32_t> ShndxIndexes;
  47. // The numbel of symbols written so far.
  48. unsigned NumWritten;
  49. void createSymtabShndx();
  50. template <typename T> void write(T Value);
  51. public:
  52. SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
  53. void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
  54. uint8_t other, uint32_t shndx, bool Reserved);
  55. ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
  56. };
  57. class ELFObjectWriter : public MCObjectWriter {
  58. static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
  59. static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
  60. static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
  61. bool Used, bool Renamed);
  62. /// Helper struct for containing some precomputed information on symbols.
  63. struct ELFSymbolData {
  64. const MCSymbolELF *Symbol;
  65. uint32_t SectionIndex;
  66. StringRef Name;
  67. // Support lexicographic sorting.
  68. bool operator<(const ELFSymbolData &RHS) const {
  69. unsigned LHSType = Symbol->getType();
  70. unsigned RHSType = RHS.Symbol->getType();
  71. if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
  72. return false;
  73. if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
  74. return true;
  75. if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
  76. return SectionIndex < RHS.SectionIndex;
  77. return Name < RHS.Name;
  78. }
  79. };
  80. /// The target specific ELF writer instance.
  81. std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
  82. DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
  83. llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
  84. Relocations;
  85. /// @}
  86. /// @name Symbol Table Data
  87. /// @{
  88. StringTableBuilder StrTabBuilder;
  89. /// @}
  90. // This holds the symbol table index of the last local symbol.
  91. unsigned LastLocalSymbolIndex;
  92. // This holds the .strtab section index.
  93. unsigned StringTableIndex;
  94. // This holds the .symtab section index.
  95. unsigned SymbolTableIndex;
  96. // Sections in the order they are to be output in the section table.
  97. std::vector<const MCSectionELF *> SectionTable;
  98. unsigned addToSectionTable(const MCSectionELF *Sec);
  99. // TargetObjectWriter wrappers.
  100. bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
  101. bool hasRelocationAddend() const {
  102. return TargetObjectWriter->hasRelocationAddend();
  103. }
  104. unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
  105. bool IsPCRel) const {
  106. return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
  107. }
  108. void align(unsigned Alignment);
  109. public:
  110. ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
  111. bool IsLittleEndian)
  112. : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
  113. void reset() override {
  114. Renames.clear();
  115. Relocations.clear();
  116. StrTabBuilder.clear();
  117. SectionTable.clear();
  118. MCObjectWriter::reset();
  119. }
  120. ~ELFObjectWriter() override;
  121. void WriteWord(uint64_t W) {
  122. if (is64Bit())
  123. write64(W);
  124. else
  125. write32(W);
  126. }
  127. template <typename T> void write(T Val) {
  128. if (IsLittleEndian)
  129. support::endian::Writer<support::little>(OS).write(Val);
  130. else
  131. support::endian::Writer<support::big>(OS).write(Val);
  132. }
  133. void writeHeader(const MCAssembler &Asm);
  134. void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
  135. ELFSymbolData &MSD, const MCAsmLayout &Layout);
  136. // Start and end offset of each section
  137. typedef std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>
  138. SectionOffsetsTy;
  139. bool shouldRelocateWithSymbol(const MCAssembler &Asm,
  140. const MCSymbolRefExpr *RefA,
  141. const MCSymbol *Sym, uint64_t C,
  142. unsigned Type) const;
  143. void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
  144. const MCFragment *Fragment, const MCFixup &Fixup,
  145. MCValue Target, bool &IsPCRel,
  146. uint64_t &FixedValue) override;
  147. // Map from a signature symbol to the group section index
  148. typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
  149. /// Compute the symbol table data
  150. ///
  151. /// \param Asm - The assembler.
  152. /// \param SectionIndexMap - Maps a section to its index.
  153. /// \param RevGroupMap - Maps a signature symbol to the group section.
  154. void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
  155. const SectionIndexMapTy &SectionIndexMap,
  156. const RevGroupMapTy &RevGroupMap,
  157. SectionOffsetsTy &SectionOffsets);
  158. MCSectionELF *createRelocationSection(MCContext &Ctx,
  159. const MCSectionELF &Sec);
  160. const MCSectionELF *createStringTable(MCContext &Ctx);
  161. void executePostLayoutBinding(MCAssembler &Asm,
  162. const MCAsmLayout &Layout) override;
  163. void writeSectionHeader(const MCAsmLayout &Layout,
  164. const SectionIndexMapTy &SectionIndexMap,
  165. const SectionOffsetsTy &SectionOffsets);
  166. void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
  167. const MCAsmLayout &Layout);
  168. void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
  169. uint64_t Address, uint64_t Offset, uint64_t Size,
  170. uint32_t Link, uint32_t Info, uint64_t Alignment,
  171. uint64_t EntrySize);
  172. void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
  173. bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
  174. const MCSymbol &SymA,
  175. const MCFragment &FB,
  176. bool InSet,
  177. bool IsPCRel) const override;
  178. bool isWeak(const MCSymbol &Sym) const override;
  179. void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
  180. void writeSection(const SectionIndexMapTy &SectionIndexMap,
  181. uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
  182. const MCSectionELF &Section);
  183. };
  184. }
  185. void ELFObjectWriter::align(unsigned Alignment) {
  186. uint64_t Padding = OffsetToAlignment(OS.tell(), Alignment);
  187. WriteZeros(Padding);
  188. }
  189. unsigned ELFObjectWriter::addToSectionTable(const MCSectionELF *Sec) {
  190. SectionTable.push_back(Sec);
  191. StrTabBuilder.add(Sec->getSectionName());
  192. return SectionTable.size();
  193. }
  194. void SymbolTableWriter::createSymtabShndx() {
  195. if (!ShndxIndexes.empty())
  196. return;
  197. ShndxIndexes.resize(NumWritten);
  198. }
  199. template <typename T> void SymbolTableWriter::write(T Value) {
  200. EWriter.write(Value);
  201. }
  202. SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
  203. : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
  204. void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
  205. uint64_t size, uint8_t other,
  206. uint32_t shndx, bool Reserved) {
  207. bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
  208. if (LargeIndex)
  209. createSymtabShndx();
  210. if (!ShndxIndexes.empty()) {
  211. if (LargeIndex)
  212. ShndxIndexes.push_back(shndx);
  213. else
  214. ShndxIndexes.push_back(0);
  215. }
  216. uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
  217. if (Is64Bit) {
  218. write(name); // st_name
  219. write(info); // st_info
  220. write(other); // st_other
  221. write(Index); // st_shndx
  222. write(value); // st_value
  223. write(size); // st_size
  224. } else {
  225. write(name); // st_name
  226. write(uint32_t(value)); // st_value
  227. write(uint32_t(size)); // st_size
  228. write(info); // st_info
  229. write(other); // st_other
  230. write(Index); // st_shndx
  231. }
  232. ++NumWritten;
  233. }
  234. bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
  235. const MCFixupKindInfo &FKI =
  236. Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
  237. return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
  238. }
  239. ELFObjectWriter::~ELFObjectWriter()
  240. {}
  241. // Emit the ELF header.
  242. void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
  243. // ELF Header
  244. // ----------
  245. //
  246. // Note
  247. // ----
  248. // emitWord method behaves differently for ELF32 and ELF64, writing
  249. // 4 bytes in the former and 8 in the latter.
  250. writeBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
  251. write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
  252. // e_ident[EI_DATA]
  253. write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
  254. write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
  255. // e_ident[EI_OSABI]
  256. write8(TargetObjectWriter->getOSABI());
  257. write8(0); // e_ident[EI_ABIVERSION]
  258. WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
  259. write16(ELF::ET_REL); // e_type
  260. write16(TargetObjectWriter->getEMachine()); // e_machine = target
  261. write32(ELF::EV_CURRENT); // e_version
  262. WriteWord(0); // e_entry, no entry point in .o file
  263. WriteWord(0); // e_phoff, no program header for .o
  264. WriteWord(0); // e_shoff = sec hdr table off in bytes
  265. // e_flags = whatever the target wants
  266. write32(Asm.getELFHeaderEFlags());
  267. // e_ehsize = ELF header size
  268. write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
  269. write16(0); // e_phentsize = prog header entry size
  270. write16(0); // e_phnum = # prog header entries = 0
  271. // e_shentsize = Section header entry size
  272. write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
  273. // e_shnum = # of section header ents
  274. write16(0);
  275. // e_shstrndx = Section # of '.shstrtab'
  276. assert(StringTableIndex < ELF::SHN_LORESERVE);
  277. write16(StringTableIndex);
  278. }
  279. uint64_t ELFObjectWriter::SymbolValue(const MCSymbol &Sym,
  280. const MCAsmLayout &Layout) {
  281. if (Sym.isCommon() && Sym.isExternal())
  282. return Sym.getCommonAlignment();
  283. uint64_t Res;
  284. if (!Layout.getSymbolOffset(Sym, Res))
  285. return 0;
  286. if (Layout.getAssembler().isThumbFunc(&Sym))
  287. Res |= 1;
  288. return Res;
  289. }
  290. void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
  291. const MCAsmLayout &Layout) {
  292. // The presence of symbol versions causes undefined symbols and
  293. // versions declared with @@@ to be renamed.
  294. for (const MCSymbol &A : Asm.symbols()) {
  295. const auto &Alias = cast<MCSymbolELF>(A);
  296. // Not an alias.
  297. if (!Alias.isVariable())
  298. continue;
  299. auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
  300. if (!Ref)
  301. continue;
  302. const auto &Symbol = cast<MCSymbolELF>(Ref->getSymbol());
  303. StringRef AliasName = Alias.getName();
  304. size_t Pos = AliasName.find('@');
  305. if (Pos == StringRef::npos)
  306. continue;
  307. // Aliases defined with .symvar copy the binding from the symbol they alias.
  308. // This is the first place we are able to copy this information.
  309. Alias.setExternal(Symbol.isExternal());
  310. Alias.setBinding(Symbol.getBinding());
  311. StringRef Rest = AliasName.substr(Pos);
  312. if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
  313. continue;
  314. // FIXME: produce a better error message.
  315. if (Symbol.isUndefined() && Rest.startswith("@@") &&
  316. !Rest.startswith("@@@"))
  317. report_fatal_error("A @@ version cannot be undefined");
  318. Renames.insert(std::make_pair(&Symbol, &Alias));
  319. }
  320. }
  321. static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
  322. uint8_t Type = newType;
  323. // Propagation rules:
  324. // IFUNC > FUNC > OBJECT > NOTYPE
  325. // TLS_OBJECT > OBJECT > NOTYPE
  326. //
  327. // dont let the new type degrade the old type
  328. switch (origType) {
  329. default:
  330. break;
  331. case ELF::STT_GNU_IFUNC:
  332. if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
  333. Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
  334. Type = ELF::STT_GNU_IFUNC;
  335. break;
  336. case ELF::STT_FUNC:
  337. if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
  338. Type == ELF::STT_TLS)
  339. Type = ELF::STT_FUNC;
  340. break;
  341. case ELF::STT_OBJECT:
  342. if (Type == ELF::STT_NOTYPE)
  343. Type = ELF::STT_OBJECT;
  344. break;
  345. case ELF::STT_TLS:
  346. if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
  347. Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
  348. Type = ELF::STT_TLS;
  349. break;
  350. }
  351. return Type;
  352. }
  353. void ELFObjectWriter::writeSymbol(SymbolTableWriter &Writer,
  354. uint32_t StringIndex, ELFSymbolData &MSD,
  355. const MCAsmLayout &Layout) {
  356. const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
  357. assert((!Symbol.getFragment() ||
  358. (Symbol.getFragment()->getParent() == &Symbol.getSection())) &&
  359. "The symbol's section doesn't match the fragment's symbol");
  360. const MCSymbolELF *Base =
  361. cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
  362. // This has to be in sync with when computeSymbolTable uses SHN_ABS or
  363. // SHN_COMMON.
  364. bool IsReserved = !Base || Symbol.isCommon();
  365. // Binding and Type share the same byte as upper and lower nibbles
  366. uint8_t Binding = Symbol.getBinding();
  367. uint8_t Type = Symbol.getType();
  368. if (Base) {
  369. Type = mergeTypeForSet(Type, Base->getType());
  370. }
  371. uint8_t Info = (Binding << 4) | Type;
  372. // Other and Visibility share the same byte with Visibility using the lower
  373. // 2 bits
  374. uint8_t Visibility = Symbol.getVisibility();
  375. uint8_t Other = Symbol.getOther() | Visibility;
  376. uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
  377. uint64_t Size = 0;
  378. const MCExpr *ESize = MSD.Symbol->getSize();
  379. if (!ESize && Base)
  380. ESize = Base->getSize();
  381. if (ESize) {
  382. int64_t Res;
  383. if (!ESize->evaluateKnownAbsolute(Res, Layout))
  384. report_fatal_error("Size expression must be absolute.");
  385. Size = Res;
  386. }
  387. // Write out the symbol table entry
  388. Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
  389. IsReserved);
  390. }
  391. // It is always valid to create a relocation with a symbol. It is preferable
  392. // to use a relocation with a section if that is possible. Using the section
  393. // allows us to omit some local symbols from the symbol table.
  394. bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
  395. const MCSymbolRefExpr *RefA,
  396. const MCSymbol *S, uint64_t C,
  397. unsigned Type) const {
  398. const auto *Sym = cast_or_null<MCSymbolELF>(S);
  399. // A PCRel relocation to an absolute value has no symbol (or section). We
  400. // represent that with a relocation to a null section.
  401. if (!RefA)
  402. return false;
  403. MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
  404. switch (Kind) {
  405. default:
  406. break;
  407. // The .odp creation emits a relocation against the symbol ".TOC." which
  408. // create a R_PPC64_TOC relocation. However the relocation symbol name
  409. // in final object creation should be NULL, since the symbol does not
  410. // really exist, it is just the reference to TOC base for the current
  411. // object file. Since the symbol is undefined, returning false results
  412. // in a relocation with a null section which is the desired result.
  413. case MCSymbolRefExpr::VK_PPC_TOCBASE:
  414. return false;
  415. // These VariantKind cause the relocation to refer to something other than
  416. // the symbol itself, like a linker generated table. Since the address of
  417. // symbol is not relevant, we cannot replace the symbol with the
  418. // section and patch the difference in the addend.
  419. case MCSymbolRefExpr::VK_GOT:
  420. case MCSymbolRefExpr::VK_PLT:
  421. case MCSymbolRefExpr::VK_GOTPCREL:
  422. case MCSymbolRefExpr::VK_Mips_GOT:
  423. case MCSymbolRefExpr::VK_PPC_GOT_LO:
  424. case MCSymbolRefExpr::VK_PPC_GOT_HI:
  425. case MCSymbolRefExpr::VK_PPC_GOT_HA:
  426. return true;
  427. }
  428. // An undefined symbol is not in any section, so the relocation has to point
  429. // to the symbol itself.
  430. assert(Sym && "Expected a symbol");
  431. if (Sym->isUndefined())
  432. return true;
  433. unsigned Binding = Sym->getBinding();
  434. switch(Binding) {
  435. default:
  436. llvm_unreachable("Invalid Binding");
  437. case ELF::STB_LOCAL:
  438. break;
  439. case ELF::STB_WEAK:
  440. // If the symbol is weak, it might be overridden by a symbol in another
  441. // file. The relocation has to point to the symbol so that the linker
  442. // can update it.
  443. return true;
  444. case ELF::STB_GLOBAL:
  445. // Global ELF symbols can be preempted by the dynamic linker. The relocation
  446. // has to point to the symbol for a reason analogous to the STB_WEAK case.
  447. return true;
  448. }
  449. // If a relocation points to a mergeable section, we have to be careful.
  450. // If the offset is zero, a relocation with the section will encode the
  451. // same information. With a non-zero offset, the situation is different.
  452. // For example, a relocation can point 42 bytes past the end of a string.
  453. // If we change such a relocation to use the section, the linker would think
  454. // that it pointed to another string and subtracting 42 at runtime will
  455. // produce the wrong value.
  456. auto &Sec = cast<MCSectionELF>(Sym->getSection());
  457. unsigned Flags = Sec.getFlags();
  458. if (Flags & ELF::SHF_MERGE) {
  459. if (C != 0)
  460. return true;
  461. // It looks like gold has a bug (http://sourceware.org/PR16794) and can
  462. // only handle section relocations to mergeable sections if using RELA.
  463. if (!hasRelocationAddend())
  464. return true;
  465. }
  466. // Most TLS relocations use a got, so they need the symbol. Even those that
  467. // are just an offset (@tpoff), require a symbol in gold versions before
  468. // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
  469. // http://sourceware.org/PR16773.
  470. if (Flags & ELF::SHF_TLS)
  471. return true;
  472. // If the symbol is a thumb function the final relocation must set the lowest
  473. // bit. With a symbol that is done by just having the symbol have that bit
  474. // set, so we would lose the bit if we relocated with the section.
  475. // FIXME: We could use the section but add the bit to the relocation value.
  476. if (Asm.isThumbFunc(Sym))
  477. return true;
  478. if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
  479. return true;
  480. return false;
  481. }
  482. // True if the assembler knows nothing about the final value of the symbol.
  483. // This doesn't cover the comdat issues, since in those cases the assembler
  484. // can at least know that all symbols in the section will move together.
  485. static bool isWeak(const MCSymbolELF &Sym) {
  486. if (Sym.getType() == ELF::STT_GNU_IFUNC)
  487. return true;
  488. switch (Sym.getBinding()) {
  489. default:
  490. llvm_unreachable("Unknown binding");
  491. case ELF::STB_LOCAL:
  492. return false;
  493. case ELF::STB_GLOBAL:
  494. return false;
  495. case ELF::STB_WEAK:
  496. case ELF::STB_GNU_UNIQUE:
  497. return true;
  498. }
  499. }
  500. void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
  501. const MCAsmLayout &Layout,
  502. const MCFragment *Fragment,
  503. const MCFixup &Fixup, MCValue Target,
  504. bool &IsPCRel, uint64_t &FixedValue) {
  505. const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
  506. uint64_t C = Target.getConstant();
  507. uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
  508. if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
  509. assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
  510. "Should not have constructed this");
  511. // Let A, B and C being the components of Target and R be the location of
  512. // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
  513. // If it is pcrel, we want to compute (A - B + C - R).
  514. // In general, ELF has no relocations for -B. It can only represent (A + C)
  515. // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
  516. // replace B to implement it: (A - R - K + C)
  517. if (IsPCRel)
  518. Asm.getContext().reportFatalError(
  519. Fixup.getLoc(),
  520. "No relocation available to represent this relative expression");
  521. const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
  522. if (SymB.isUndefined())
  523. Asm.getContext().reportFatalError(
  524. Fixup.getLoc(),
  525. Twine("symbol '") + SymB.getName() +
  526. "' can not be undefined in a subtraction expression");
  527. assert(!SymB.isAbsolute() && "Should have been folded");
  528. const MCSection &SecB = SymB.getSection();
  529. if (&SecB != &FixupSection)
  530. Asm.getContext().reportFatalError(
  531. Fixup.getLoc(), "Cannot represent a difference across sections");
  532. if (::isWeak(SymB))
  533. Asm.getContext().reportFatalError(
  534. Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
  535. uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
  536. uint64_t K = SymBOffset - FixupOffset;
  537. IsPCRel = true;
  538. C -= K;
  539. }
  540. // We either rejected the fixup or folded B into C at this point.
  541. const MCSymbolRefExpr *RefA = Target.getSymA();
  542. const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
  543. bool ViaWeakRef = false;
  544. if (SymA && SymA->isVariable()) {
  545. const MCExpr *Expr = SymA->getVariableValue();
  546. if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
  547. if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
  548. SymA = cast<MCSymbolELF>(&Inner->getSymbol());
  549. ViaWeakRef = true;
  550. }
  551. }
  552. }
  553. unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
  554. bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
  555. if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
  556. C += Layout.getSymbolOffset(*SymA);
  557. uint64_t Addend = 0;
  558. if (hasRelocationAddend()) {
  559. Addend = C;
  560. C = 0;
  561. }
  562. FixedValue = C;
  563. if (!RelocateWithSymbol) {
  564. const MCSection *SecA =
  565. (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
  566. auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
  567. const auto *SectionSymbol =
  568. ELFSec ? cast<MCSymbolELF>(ELFSec->getBeginSymbol()) : nullptr;
  569. if (SectionSymbol)
  570. SectionSymbol->setUsedInReloc();
  571. ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
  572. Relocations[&FixupSection].push_back(Rec);
  573. return;
  574. }
  575. if (SymA) {
  576. if (const MCSymbolELF *R = Renames.lookup(SymA))
  577. SymA = R;
  578. if (ViaWeakRef)
  579. SymA->setIsWeakrefUsedInReloc();
  580. else
  581. SymA->setUsedInReloc();
  582. }
  583. ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
  584. Relocations[&FixupSection].push_back(Rec);
  585. return;
  586. }
  587. bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
  588. const MCSymbolELF &Symbol, bool Used,
  589. bool Renamed) {
  590. if (Symbol.isVariable()) {
  591. const MCExpr *Expr = Symbol.getVariableValue();
  592. if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
  593. if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
  594. return false;
  595. }
  596. }
  597. if (Used)
  598. return true;
  599. if (Renamed)
  600. return false;
  601. if (Symbol.isVariable() && Symbol.isUndefined()) {
  602. // FIXME: this is here just to diagnose the case of a var = commmon_sym.
  603. Layout.getBaseSymbol(Symbol);
  604. return false;
  605. }
  606. if (Symbol.isUndefined() && !Symbol.isBindingSet())
  607. return false;
  608. if (Symbol.isTemporary())
  609. return false;
  610. if (Symbol.getType() == ELF::STT_SECTION)
  611. return false;
  612. return true;
  613. }
  614. void ELFObjectWriter::computeSymbolTable(
  615. MCAssembler &Asm, const MCAsmLayout &Layout,
  616. const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
  617. SectionOffsetsTy &SectionOffsets) {
  618. MCContext &Ctx = Asm.getContext();
  619. SymbolTableWriter Writer(*this, is64Bit());
  620. // Symbol table
  621. unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
  622. MCSectionELF *SymtabSection =
  623. Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
  624. SymtabSection->setAlignment(is64Bit() ? 8 : 4);
  625. SymbolTableIndex = addToSectionTable(SymtabSection);
  626. align(SymtabSection->getAlignment());
  627. uint64_t SecStart = OS.tell();
  628. // The first entry is the undefined symbol entry.
  629. Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
  630. std::vector<ELFSymbolData> LocalSymbolData;
  631. std::vector<ELFSymbolData> ExternalSymbolData;
  632. // Add the data for the symbols.
  633. bool HasLargeSectionIndex = false;
  634. for (const MCSymbol &S : Asm.symbols()) {
  635. const auto &Symbol = cast<MCSymbolELF>(S);
  636. bool Used = Symbol.isUsedInReloc();
  637. bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
  638. bool isSignature = Symbol.isSignature();
  639. if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
  640. Renames.count(&Symbol)))
  641. continue;
  642. if (Symbol.isTemporary() && Symbol.isUndefined())
  643. Ctx.reportFatalError(SMLoc(), "Undefined temporary");
  644. ELFSymbolData MSD;
  645. MSD.Symbol = cast<MCSymbolELF>(&Symbol);
  646. bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
  647. assert(Local || !Symbol.isTemporary());
  648. if (Symbol.isAbsolute()) {
  649. MSD.SectionIndex = ELF::SHN_ABS;
  650. } else if (Symbol.isCommon()) {
  651. assert(!Local);
  652. MSD.SectionIndex = ELF::SHN_COMMON;
  653. } else if (Symbol.isUndefined()) {
  654. if (isSignature && !Used) {
  655. MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
  656. if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
  657. HasLargeSectionIndex = true;
  658. } else {
  659. MSD.SectionIndex = ELF::SHN_UNDEF;
  660. }
  661. } else {
  662. const MCSectionELF &Section =
  663. static_cast<const MCSectionELF &>(Symbol.getSection());
  664. MSD.SectionIndex = SectionIndexMap.lookup(&Section);
  665. assert(MSD.SectionIndex && "Invalid section index!");
  666. if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
  667. HasLargeSectionIndex = true;
  668. }
  669. // The @@@ in symbol version is replaced with @ in undefined symbols and @@
  670. // in defined ones.
  671. //
  672. // FIXME: All name handling should be done before we get to the writer,
  673. // including dealing with GNU-style version suffixes. Fixing this isn't
  674. // trivial.
  675. //
  676. // We thus have to be careful to not perform the symbol version replacement
  677. // blindly:
  678. //
  679. // The ELF format is used on Windows by the MCJIT engine. Thus, on
  680. // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
  681. // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
  682. // C++ name mangling can legally have "@@@" as a sub-string. In that case,
  683. // the EFLObjectWriter should not interpret the "@@@" sub-string as
  684. // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
  685. // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
  686. // "__imp_?" or "__imp_@?".
  687. //
  688. // It would have been interesting to perform the MS mangling prefix check
  689. // only when the target triple is of the form *-pc-windows-elf. But, it
  690. // seems that this information is not easily accessible from the
  691. // ELFObjectWriter.
  692. StringRef Name = Symbol.getName();
  693. SmallString<32> Buf;
  694. if (!Name.startswith("?") && !Name.startswith("@?") &&
  695. !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
  696. // This symbol isn't following the MSVC C++ name mangling convention. We
  697. // can thus safely interpret the @@@ in symbol names as specifying symbol
  698. // versioning.
  699. size_t Pos = Name.find("@@@");
  700. if (Pos != StringRef::npos) {
  701. Buf += Name.substr(0, Pos);
  702. unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
  703. Buf += Name.substr(Pos + Skip);
  704. Name = Buf;
  705. }
  706. }
  707. // Sections have their own string table
  708. if (Symbol.getType() != ELF::STT_SECTION)
  709. MSD.Name = StrTabBuilder.add(Name);
  710. if (Local)
  711. LocalSymbolData.push_back(MSD);
  712. else
  713. ExternalSymbolData.push_back(MSD);
  714. }
  715. // This holds the .symtab_shndx section index.
  716. unsigned SymtabShndxSectionIndex = 0;
  717. if (HasLargeSectionIndex) {
  718. MCSectionELF *SymtabShndxSection =
  719. Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
  720. SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
  721. SymtabShndxSection->setAlignment(4);
  722. }
  723. ArrayRef<std::string> FileNames = Asm.getFileNames();
  724. for (const std::string &Name : FileNames)
  725. StrTabBuilder.add(Name);
  726. StrTabBuilder.finalize(StringTableBuilder::ELF);
  727. for (const std::string &Name : FileNames)
  728. Writer.writeSymbol(StrTabBuilder.getOffset(Name),
  729. ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
  730. ELF::SHN_ABS, true);
  731. // Symbols are required to be in lexicographic order.
  732. array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
  733. array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
  734. // Set the symbol indices. Local symbols must come before all other
  735. // symbols with non-local bindings.
  736. unsigned Index = FileNames.size() + 1;
  737. for (ELFSymbolData &MSD : LocalSymbolData) {
  738. unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
  739. ? 0
  740. : StrTabBuilder.getOffset(MSD.Name);
  741. MSD.Symbol->setIndex(Index++);
  742. writeSymbol(Writer, StringIndex, MSD, Layout);
  743. }
  744. // Write the symbol table entries.
  745. LastLocalSymbolIndex = Index;
  746. for (ELFSymbolData &MSD : ExternalSymbolData) {
  747. unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
  748. MSD.Symbol->setIndex(Index++);
  749. writeSymbol(Writer, StringIndex, MSD, Layout);
  750. assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
  751. }
  752. uint64_t SecEnd = OS.tell();
  753. SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
  754. ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
  755. if (ShndxIndexes.empty()) {
  756. assert(SymtabShndxSectionIndex == 0);
  757. return;
  758. }
  759. assert(SymtabShndxSectionIndex != 0);
  760. SecStart = OS.tell();
  761. const MCSectionELF *SymtabShndxSection =
  762. SectionTable[SymtabShndxSectionIndex - 1];
  763. for (uint32_t Index : ShndxIndexes)
  764. write(Index);
  765. SecEnd = OS.tell();
  766. SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
  767. }
  768. MCSectionELF *
  769. ELFObjectWriter::createRelocationSection(MCContext &Ctx,
  770. const MCSectionELF &Sec) {
  771. if (Relocations[&Sec].empty())
  772. return nullptr;
  773. const StringRef SectionName = Sec.getSectionName();
  774. std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
  775. RelaSectionName += SectionName;
  776. unsigned EntrySize;
  777. if (hasRelocationAddend())
  778. EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
  779. else
  780. EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
  781. unsigned Flags = 0;
  782. if (Sec.getFlags() & ELF::SHF_GROUP)
  783. Flags = ELF::SHF_GROUP;
  784. MCSectionELF *RelaSection = Ctx.createELFRelSection(
  785. RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
  786. Flags, EntrySize, Sec.getGroup(), &Sec);
  787. RelaSection->setAlignment(is64Bit() ? 8 : 4);
  788. return RelaSection;
  789. }
  790. static SmallVector<char, 128>
  791. getUncompressedData(const MCAsmLayout &Layout,
  792. const MCSection::FragmentListType &Fragments) {
  793. SmallVector<char, 128> UncompressedData;
  794. for (const MCFragment &F : Fragments) {
  795. const SmallVectorImpl<char> *Contents;
  796. switch (F.getKind()) {
  797. case MCFragment::FT_Data:
  798. Contents = &cast<MCDataFragment>(F).getContents();
  799. break;
  800. case MCFragment::FT_Dwarf:
  801. Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
  802. break;
  803. case MCFragment::FT_DwarfFrame:
  804. Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
  805. break;
  806. default:
  807. llvm_unreachable(
  808. "Not expecting any other fragment types in a debug_* section");
  809. }
  810. UncompressedData.append(Contents->begin(), Contents->end());
  811. }
  812. return UncompressedData;
  813. }
  814. // Include the debug info compression header:
  815. // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
  816. // useful for consumers to preallocate a buffer to decompress into.
  817. static bool
  818. prependCompressionHeader(uint64_t Size,
  819. SmallVectorImpl<char> &CompressedContents) {
  820. const StringRef Magic = "ZLIB";
  821. if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
  822. return false;
  823. if (sys::IsLittleEndianHost)
  824. sys::swapByteOrder(Size);
  825. CompressedContents.insert(CompressedContents.begin(),
  826. Magic.size() + sizeof(Size), 0);
  827. std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
  828. std::copy(reinterpret_cast<char *>(&Size),
  829. reinterpret_cast<char *>(&Size + 1),
  830. CompressedContents.begin() + Magic.size());
  831. return true;
  832. }
  833. void ELFObjectWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
  834. const MCAsmLayout &Layout) {
  835. MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
  836. StringRef SectionName = Section.getSectionName();
  837. // Compressing debug_frame requires handling alignment fragments which is
  838. // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
  839. // for writing to arbitrary buffers) for little benefit.
  840. if (!Asm.getContext().getAsmInfo()->compressDebugSections() ||
  841. !SectionName.startswith(".debug_") || SectionName == ".debug_frame") {
  842. Asm.writeSectionData(&Section, Layout);
  843. return;
  844. }
  845. // Gather the uncompressed data from all the fragments.
  846. const MCSection::FragmentListType &Fragments = Section.getFragmentList();
  847. SmallVector<char, 128> UncompressedData =
  848. getUncompressedData(Layout, Fragments);
  849. SmallVector<char, 128> CompressedContents;
  850. zlib::Status Success = zlib::compress(
  851. StringRef(UncompressedData.data(), UncompressedData.size()),
  852. CompressedContents);
  853. if (Success != zlib::StatusOK) {
  854. Asm.writeSectionData(&Section, Layout);
  855. return;
  856. }
  857. if (!prependCompressionHeader(UncompressedData.size(), CompressedContents)) {
  858. Asm.writeSectionData(&Section, Layout);
  859. return;
  860. }
  861. Asm.getContext().renameELFSection(&Section,
  862. (".z" + SectionName.drop_front(1)).str());
  863. OS << CompressedContents;
  864. }
  865. void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
  866. uint64_t Flags, uint64_t Address,
  867. uint64_t Offset, uint64_t Size,
  868. uint32_t Link, uint32_t Info,
  869. uint64_t Alignment,
  870. uint64_t EntrySize) {
  871. write32(Name); // sh_name: index into string table
  872. write32(Type); // sh_type
  873. WriteWord(Flags); // sh_flags
  874. WriteWord(Address); // sh_addr
  875. WriteWord(Offset); // sh_offset
  876. WriteWord(Size); // sh_size
  877. write32(Link); // sh_link
  878. write32(Info); // sh_info
  879. WriteWord(Alignment); // sh_addralign
  880. WriteWord(EntrySize); // sh_entsize
  881. }
  882. void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
  883. const MCSectionELF &Sec) {
  884. std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
  885. // Sort the relocation entries. Most targets just sort by Offset, but some
  886. // (e.g., MIPS) have additional constraints.
  887. TargetObjectWriter->sortRelocs(Asm, Relocs);
  888. for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
  889. const ELFRelocationEntry &Entry = Relocs[e - i - 1];
  890. unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
  891. if (is64Bit()) {
  892. write(Entry.Offset);
  893. if (TargetObjectWriter->isN64()) {
  894. write(uint32_t(Index));
  895. write(TargetObjectWriter->getRSsym(Entry.Type));
  896. write(TargetObjectWriter->getRType3(Entry.Type));
  897. write(TargetObjectWriter->getRType2(Entry.Type));
  898. write(TargetObjectWriter->getRType(Entry.Type));
  899. } else {
  900. struct ELF::Elf64_Rela ERE64;
  901. ERE64.setSymbolAndType(Index, Entry.Type);
  902. write(ERE64.r_info);
  903. }
  904. if (hasRelocationAddend())
  905. write(Entry.Addend);
  906. } else {
  907. write(uint32_t(Entry.Offset));
  908. struct ELF::Elf32_Rela ERE32;
  909. ERE32.setSymbolAndType(Index, Entry.Type);
  910. write(ERE32.r_info);
  911. if (hasRelocationAddend())
  912. write(uint32_t(Entry.Addend));
  913. }
  914. }
  915. }
  916. const MCSectionELF *ELFObjectWriter::createStringTable(MCContext &Ctx) {
  917. const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
  918. OS << StrTabBuilder.data();
  919. return StrtabSection;
  920. }
  921. void ELFObjectWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
  922. uint32_t GroupSymbolIndex, uint64_t Offset,
  923. uint64_t Size, const MCSectionELF &Section) {
  924. uint64_t sh_link = 0;
  925. uint64_t sh_info = 0;
  926. switch(Section.getType()) {
  927. default:
  928. // Nothing to do.
  929. break;
  930. case ELF::SHT_DYNAMIC:
  931. llvm_unreachable("SHT_DYNAMIC in a relocatable object");
  932. case ELF::SHT_REL:
  933. case ELF::SHT_RELA: {
  934. sh_link = SymbolTableIndex;
  935. assert(sh_link && ".symtab not found");
  936. const MCSectionELF *InfoSection = Section.getAssociatedSection();
  937. sh_info = SectionIndexMap.lookup(InfoSection);
  938. break;
  939. }
  940. case ELF::SHT_SYMTAB:
  941. case ELF::SHT_DYNSYM:
  942. sh_link = StringTableIndex;
  943. sh_info = LastLocalSymbolIndex;
  944. break;
  945. case ELF::SHT_SYMTAB_SHNDX:
  946. sh_link = SymbolTableIndex;
  947. break;
  948. case ELF::SHT_GROUP:
  949. sh_link = SymbolTableIndex;
  950. sh_info = GroupSymbolIndex;
  951. break;
  952. }
  953. if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
  954. Section.getType() == ELF::SHT_ARM_EXIDX)
  955. sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
  956. WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getSectionName()),
  957. Section.getType(), Section.getFlags(), 0, Offset, Size,
  958. sh_link, sh_info, Section.getAlignment(),
  959. Section.getEntrySize());
  960. }
  961. void ELFObjectWriter::writeSectionHeader(
  962. const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
  963. const SectionOffsetsTy &SectionOffsets) {
  964. const unsigned NumSections = SectionTable.size();
  965. // Null section first.
  966. uint64_t FirstSectionSize =
  967. (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
  968. WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
  969. for (const MCSectionELF *Section : SectionTable) {
  970. uint32_t GroupSymbolIndex;
  971. unsigned Type = Section->getType();
  972. if (Type != ELF::SHT_GROUP)
  973. GroupSymbolIndex = 0;
  974. else
  975. GroupSymbolIndex = Section->getGroup()->getIndex();
  976. const std::pair<uint64_t, uint64_t> &Offsets =
  977. SectionOffsets.find(Section)->second;
  978. uint64_t Size;
  979. if (Type == ELF::SHT_NOBITS)
  980. Size = Layout.getSectionAddressSize(Section);
  981. else
  982. Size = Offsets.second - Offsets.first;
  983. writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
  984. *Section);
  985. }
  986. }
  987. void ELFObjectWriter::writeObject(MCAssembler &Asm,
  988. const MCAsmLayout &Layout) {
  989. MCContext &Ctx = Asm.getContext();
  990. MCSectionELF *StrtabSection =
  991. Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
  992. StringTableIndex = addToSectionTable(StrtabSection);
  993. RevGroupMapTy RevGroupMap;
  994. SectionIndexMapTy SectionIndexMap;
  995. std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
  996. // Write out the ELF header ...
  997. writeHeader(Asm);
  998. // ... then the sections ...
  999. SectionOffsetsTy SectionOffsets;
  1000. std::vector<MCSectionELF *> Groups;
  1001. std::vector<MCSectionELF *> Relocations;
  1002. for (MCSection &Sec : Asm) {
  1003. MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
  1004. align(Section.getAlignment());
  1005. // Remember the offset into the file for this section.
  1006. uint64_t SecStart = OS.tell();
  1007. const MCSymbolELF *SignatureSymbol = Section.getGroup();
  1008. writeSectionData(Asm, Section, Layout);
  1009. uint64_t SecEnd = OS.tell();
  1010. SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
  1011. MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
  1012. if (SignatureSymbol) {
  1013. Asm.registerSymbol(*SignatureSymbol);
  1014. unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
  1015. if (!GroupIdx) {
  1016. MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
  1017. GroupIdx = addToSectionTable(Group);
  1018. Group->setAlignment(4);
  1019. Groups.push_back(Group);
  1020. }
  1021. std::vector<const MCSectionELF *> &Members =
  1022. GroupMembers[SignatureSymbol];
  1023. Members.push_back(&Section);
  1024. if (RelSection)
  1025. Members.push_back(RelSection);
  1026. }
  1027. SectionIndexMap[&Section] = addToSectionTable(&Section);
  1028. if (RelSection) {
  1029. SectionIndexMap[RelSection] = addToSectionTable(RelSection);
  1030. Relocations.push_back(RelSection);
  1031. }
  1032. }
  1033. for (MCSectionELF *Group : Groups) {
  1034. align(Group->getAlignment());
  1035. // Remember the offset into the file for this section.
  1036. uint64_t SecStart = OS.tell();
  1037. const MCSymbol *SignatureSymbol = Group->getGroup();
  1038. assert(SignatureSymbol);
  1039. write(uint32_t(ELF::GRP_COMDAT));
  1040. for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
  1041. uint32_t SecIndex = SectionIndexMap.lookup(Member);
  1042. write(SecIndex);
  1043. }
  1044. uint64_t SecEnd = OS.tell();
  1045. SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
  1046. }
  1047. // Compute symbol table information.
  1048. computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap, SectionOffsets);
  1049. for (MCSectionELF *RelSection : Relocations) {
  1050. align(RelSection->getAlignment());
  1051. // Remember the offset into the file for this section.
  1052. uint64_t SecStart = OS.tell();
  1053. writeRelocations(Asm, *RelSection->getAssociatedSection());
  1054. uint64_t SecEnd = OS.tell();
  1055. SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
  1056. }
  1057. {
  1058. uint64_t SecStart = OS.tell();
  1059. const MCSectionELF *Sec = createStringTable(Ctx);
  1060. uint64_t SecEnd = OS.tell();
  1061. SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
  1062. }
  1063. uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
  1064. align(NaturalAlignment);
  1065. const unsigned SectionHeaderOffset = OS.tell();
  1066. // ... then the section header table ...
  1067. writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
  1068. uint16_t NumSections = (SectionTable.size() + 1 >= ELF::SHN_LORESERVE)
  1069. ? (uint16_t)ELF::SHN_UNDEF
  1070. : SectionTable.size() + 1;
  1071. if (sys::IsLittleEndianHost != IsLittleEndian)
  1072. sys::swapByteOrder(NumSections);
  1073. unsigned NumSectionsOffset;
  1074. if (is64Bit()) {
  1075. uint64_t Val = SectionHeaderOffset;
  1076. if (sys::IsLittleEndianHost != IsLittleEndian)
  1077. sys::swapByteOrder(Val);
  1078. OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
  1079. offsetof(ELF::Elf64_Ehdr, e_shoff));
  1080. NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
  1081. } else {
  1082. uint32_t Val = SectionHeaderOffset;
  1083. if (sys::IsLittleEndianHost != IsLittleEndian)
  1084. sys::swapByteOrder(Val);
  1085. OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
  1086. offsetof(ELF::Elf32_Ehdr, e_shoff));
  1087. NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
  1088. }
  1089. OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
  1090. NumSectionsOffset);
  1091. }
  1092. bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
  1093. const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
  1094. bool InSet, bool IsPCRel) const {
  1095. const auto &SymA = cast<MCSymbolELF>(SA);
  1096. if (IsPCRel) {
  1097. assert(!InSet);
  1098. if (::isWeak(SymA))
  1099. return false;
  1100. }
  1101. return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
  1102. InSet, IsPCRel);
  1103. }
  1104. bool ELFObjectWriter::isWeak(const MCSymbol &S) const {
  1105. const auto &Sym = cast<MCSymbolELF>(S);
  1106. if (::isWeak(Sym))
  1107. return true;
  1108. // It is invalid to replace a reference to a global in a comdat
  1109. // with a reference to a local since out of comdat references
  1110. // to a local are forbidden.
  1111. // We could try to return false for more cases, like the reference
  1112. // being in the same comdat or Sym being an alias to another global,
  1113. // but it is not clear if it is worth the effort.
  1114. if (Sym.getBinding() != ELF::STB_GLOBAL)
  1115. return false;
  1116. if (!Sym.isInSection())
  1117. return false;
  1118. const auto &Sec = cast<MCSectionELF>(Sym.getSection());
  1119. return Sec.getGroup();
  1120. }
  1121. MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
  1122. raw_pwrite_stream &OS,
  1123. bool IsLittleEndian) {
  1124. return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
  1125. }