ELFObjectWriter.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. //===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements ELF object file writer information.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/ArrayRef.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/Twine.h"
  19. #include "llvm/BinaryFormat/ELF.h"
  20. #include "llvm/MC/MCAsmBackend.h"
  21. #include "llvm/MC/MCAsmInfo.h"
  22. #include "llvm/MC/MCAsmLayout.h"
  23. #include "llvm/MC/MCAssembler.h"
  24. #include "llvm/MC/MCContext.h"
  25. #include "llvm/MC/MCELFObjectWriter.h"
  26. #include "llvm/MC/MCExpr.h"
  27. #include "llvm/MC/MCFixup.h"
  28. #include "llvm/MC/MCFixupKindInfo.h"
  29. #include "llvm/MC/MCFragment.h"
  30. #include "llvm/MC/MCObjectFileInfo.h"
  31. #include "llvm/MC/MCObjectWriter.h"
  32. #include "llvm/MC/MCSection.h"
  33. #include "llvm/MC/MCSectionELF.h"
  34. #include "llvm/MC/MCSymbol.h"
  35. #include "llvm/MC/MCSymbolELF.h"
  36. #include "llvm/MC/MCValue.h"
  37. #include "llvm/MC/StringTableBuilder.h"
  38. #include "llvm/Support/Alignment.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/Compression.h"
  42. #include "llvm/Support/EndianStream.h"
  43. #include "llvm/Support/Error.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/Host.h"
  46. #include "llvm/Support/LEB128.h"
  47. #include "llvm/Support/MathExtras.h"
  48. #include "llvm/Support/SMLoc.h"
  49. #include "llvm/Support/StringSaver.h"
  50. #include "llvm/Support/SwapByteOrder.h"
  51. #include "llvm/Support/raw_ostream.h"
  52. #include <algorithm>
  53. #include <cassert>
  54. #include <cstddef>
  55. #include <cstdint>
  56. #include <map>
  57. #include <memory>
  58. #include <string>
  59. #include <utility>
  60. #include <vector>
  61. using namespace llvm;
  62. #undef DEBUG_TYPE
  63. #define DEBUG_TYPE "reloc-info"
  64. namespace {
  65. using SectionIndexMapTy = DenseMap<const MCSectionELF *, uint32_t>;
  66. class ELFObjectWriter;
  67. struct ELFWriter;
  68. bool isDwoSection(const MCSectionELF &Sec) {
  69. return Sec.getName().endswith(".dwo");
  70. }
  71. class SymbolTableWriter {
  72. ELFWriter &EWriter;
  73. bool Is64Bit;
  74. // indexes we are going to write to .symtab_shndx.
  75. std::vector<uint32_t> ShndxIndexes;
  76. // The numbel of symbols written so far.
  77. unsigned NumWritten;
  78. void createSymtabShndx();
  79. template <typename T> void write(T Value);
  80. public:
  81. SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit);
  82. void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
  83. uint8_t other, uint32_t shndx, bool Reserved);
  84. ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
  85. };
  86. struct ELFWriter {
  87. ELFObjectWriter &OWriter;
  88. support::endian::Writer W;
  89. enum DwoMode {
  90. AllSections,
  91. NonDwoOnly,
  92. DwoOnly,
  93. } Mode;
  94. static uint64_t SymbolValue(const MCSymbol &Sym, const MCAsmLayout &Layout);
  95. static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
  96. bool Used, bool Renamed);
  97. /// Helper struct for containing some precomputed information on symbols.
  98. struct ELFSymbolData {
  99. const MCSymbolELF *Symbol;
  100. uint32_t SectionIndex;
  101. StringRef Name;
  102. // Support lexicographic sorting.
  103. bool operator<(const ELFSymbolData &RHS) const {
  104. unsigned LHSType = Symbol->getType();
  105. unsigned RHSType = RHS.Symbol->getType();
  106. if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
  107. return false;
  108. if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
  109. return true;
  110. if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
  111. return SectionIndex < RHS.SectionIndex;
  112. return Name < RHS.Name;
  113. }
  114. };
  115. /// @}
  116. /// @name Symbol Table Data
  117. /// @{
  118. StringTableBuilder StrTabBuilder{StringTableBuilder::ELF};
  119. /// @}
  120. // This holds the symbol table index of the last local symbol.
  121. unsigned LastLocalSymbolIndex;
  122. // This holds the .strtab section index.
  123. unsigned StringTableIndex;
  124. // This holds the .symtab section index.
  125. unsigned SymbolTableIndex;
  126. // Sections in the order they are to be output in the section table.
  127. std::vector<const MCSectionELF *> SectionTable;
  128. unsigned addToSectionTable(const MCSectionELF *Sec);
  129. // TargetObjectWriter wrappers.
  130. bool is64Bit() const;
  131. bool hasRelocationAddend() const;
  132. void align(unsigned Alignment);
  133. bool maybeWriteCompression(uint64_t Size,
  134. SmallVectorImpl<char> &CompressedContents,
  135. bool ZLibStyle, unsigned Alignment);
  136. public:
  137. ELFWriter(ELFObjectWriter &OWriter, raw_pwrite_stream &OS,
  138. bool IsLittleEndian, DwoMode Mode)
  139. : OWriter(OWriter),
  140. W(OS, IsLittleEndian ? support::little : support::big), Mode(Mode) {}
  141. void WriteWord(uint64_t Word) {
  142. if (is64Bit())
  143. W.write<uint64_t>(Word);
  144. else
  145. W.write<uint32_t>(Word);
  146. }
  147. template <typename T> void write(T Val) {
  148. W.write(Val);
  149. }
  150. void writeHeader(const MCAssembler &Asm);
  151. void writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
  152. ELFSymbolData &MSD, const MCAsmLayout &Layout);
  153. // Start and end offset of each section
  154. using SectionOffsetsTy =
  155. std::map<const MCSectionELF *, std::pair<uint64_t, uint64_t>>;
  156. // Map from a signature symbol to the group section index
  157. using RevGroupMapTy = DenseMap<const MCSymbol *, unsigned>;
  158. /// Compute the symbol table data
  159. ///
  160. /// \param Asm - The assembler.
  161. /// \param SectionIndexMap - Maps a section to its index.
  162. /// \param RevGroupMap - Maps a signature symbol to the group section.
  163. void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
  164. const SectionIndexMapTy &SectionIndexMap,
  165. const RevGroupMapTy &RevGroupMap,
  166. SectionOffsetsTy &SectionOffsets);
  167. void writeAddrsigSection();
  168. MCSectionELF *createRelocationSection(MCContext &Ctx,
  169. const MCSectionELF &Sec);
  170. const MCSectionELF *createStringTable(MCContext &Ctx);
  171. void writeSectionHeader(const MCAsmLayout &Layout,
  172. const SectionIndexMapTy &SectionIndexMap,
  173. const SectionOffsetsTy &SectionOffsets);
  174. void writeSectionData(const MCAssembler &Asm, MCSection &Sec,
  175. const MCAsmLayout &Layout);
  176. void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
  177. uint64_t Address, uint64_t Offset, uint64_t Size,
  178. uint32_t Link, uint32_t Info, uint64_t Alignment,
  179. uint64_t EntrySize);
  180. void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
  181. uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout);
  182. void writeSection(const SectionIndexMapTy &SectionIndexMap,
  183. uint32_t GroupSymbolIndex, uint64_t Offset, uint64_t Size,
  184. const MCSectionELF &Section);
  185. };
  186. class ELFObjectWriter : public MCObjectWriter {
  187. /// The target specific ELF writer instance.
  188. std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
  189. DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>> Relocations;
  190. DenseMap<const MCSymbolELF *, const MCSymbolELF *> Renames;
  191. bool EmitAddrsigSection = false;
  192. std::vector<const MCSymbol *> AddrsigSyms;
  193. bool hasRelocationAddend() const;
  194. bool shouldRelocateWithSymbol(const MCAssembler &Asm,
  195. const MCSymbolRefExpr *RefA,
  196. const MCSymbolELF *Sym, uint64_t C,
  197. unsigned Type) const;
  198. public:
  199. ELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW)
  200. : TargetObjectWriter(std::move(MOTW)) {}
  201. void reset() override {
  202. Relocations.clear();
  203. Renames.clear();
  204. MCObjectWriter::reset();
  205. }
  206. bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
  207. const MCSymbol &SymA,
  208. const MCFragment &FB, bool InSet,
  209. bool IsPCRel) const override;
  210. virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
  211. const MCSectionELF *From,
  212. const MCSectionELF *To) {
  213. return true;
  214. }
  215. void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
  216. const MCFragment *Fragment, const MCFixup &Fixup,
  217. MCValue Target, uint64_t &FixedValue) override;
  218. void executePostLayoutBinding(MCAssembler &Asm,
  219. const MCAsmLayout &Layout) override;
  220. void emitAddrsigSection() override { EmitAddrsigSection = true; }
  221. void addAddrsigSymbol(const MCSymbol *Sym) override {
  222. AddrsigSyms.push_back(Sym);
  223. }
  224. friend struct ELFWriter;
  225. };
  226. class ELFSingleObjectWriter : public ELFObjectWriter {
  227. raw_pwrite_stream &OS;
  228. bool IsLittleEndian;
  229. public:
  230. ELFSingleObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
  231. raw_pwrite_stream &OS, bool IsLittleEndian)
  232. : ELFObjectWriter(std::move(MOTW)), OS(OS),
  233. IsLittleEndian(IsLittleEndian) {}
  234. uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
  235. return ELFWriter(*this, OS, IsLittleEndian, ELFWriter::AllSections)
  236. .writeObject(Asm, Layout);
  237. }
  238. friend struct ELFWriter;
  239. };
  240. class ELFDwoObjectWriter : public ELFObjectWriter {
  241. raw_pwrite_stream &OS, &DwoOS;
  242. bool IsLittleEndian;
  243. public:
  244. ELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
  245. raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
  246. bool IsLittleEndian)
  247. : ELFObjectWriter(std::move(MOTW)), OS(OS), DwoOS(DwoOS),
  248. IsLittleEndian(IsLittleEndian) {}
  249. virtual bool checkRelocation(MCContext &Ctx, SMLoc Loc,
  250. const MCSectionELF *From,
  251. const MCSectionELF *To) override {
  252. if (isDwoSection(*From)) {
  253. Ctx.reportError(Loc, "A dwo section may not contain relocations");
  254. return false;
  255. }
  256. if (To && isDwoSection(*To)) {
  257. Ctx.reportError(Loc, "A relocation may not refer to a dwo section");
  258. return false;
  259. }
  260. return true;
  261. }
  262. uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override {
  263. uint64_t Size = ELFWriter(*this, OS, IsLittleEndian, ELFWriter::NonDwoOnly)
  264. .writeObject(Asm, Layout);
  265. Size += ELFWriter(*this, DwoOS, IsLittleEndian, ELFWriter::DwoOnly)
  266. .writeObject(Asm, Layout);
  267. return Size;
  268. }
  269. };
  270. } // end anonymous namespace
  271. void ELFWriter::align(unsigned Alignment) {
  272. uint64_t Padding = offsetToAlignment(W.OS.tell(), Align(Alignment));
  273. W.OS.write_zeros(Padding);
  274. }
  275. unsigned ELFWriter::addToSectionTable(const MCSectionELF *Sec) {
  276. SectionTable.push_back(Sec);
  277. StrTabBuilder.add(Sec->getName());
  278. return SectionTable.size();
  279. }
  280. void SymbolTableWriter::createSymtabShndx() {
  281. if (!ShndxIndexes.empty())
  282. return;
  283. ShndxIndexes.resize(NumWritten);
  284. }
  285. template <typename T> void SymbolTableWriter::write(T Value) {
  286. EWriter.write(Value);
  287. }
  288. SymbolTableWriter::SymbolTableWriter(ELFWriter &EWriter, bool Is64Bit)
  289. : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
  290. void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
  291. uint64_t size, uint8_t other,
  292. uint32_t shndx, bool Reserved) {
  293. bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
  294. if (LargeIndex)
  295. createSymtabShndx();
  296. if (!ShndxIndexes.empty()) {
  297. if (LargeIndex)
  298. ShndxIndexes.push_back(shndx);
  299. else
  300. ShndxIndexes.push_back(0);
  301. }
  302. uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
  303. if (Is64Bit) {
  304. write(name); // st_name
  305. write(info); // st_info
  306. write(other); // st_other
  307. write(Index); // st_shndx
  308. write(value); // st_value
  309. write(size); // st_size
  310. } else {
  311. write(name); // st_name
  312. write(uint32_t(value)); // st_value
  313. write(uint32_t(size)); // st_size
  314. write(info); // st_info
  315. write(other); // st_other
  316. write(Index); // st_shndx
  317. }
  318. ++NumWritten;
  319. }
  320. bool ELFWriter::is64Bit() const {
  321. return OWriter.TargetObjectWriter->is64Bit();
  322. }
  323. bool ELFWriter::hasRelocationAddend() const {
  324. return OWriter.hasRelocationAddend();
  325. }
  326. // Emit the ELF header.
  327. void ELFWriter::writeHeader(const MCAssembler &Asm) {
  328. // ELF Header
  329. // ----------
  330. //
  331. // Note
  332. // ----
  333. // emitWord method behaves differently for ELF32 and ELF64, writing
  334. // 4 bytes in the former and 8 in the latter.
  335. W.OS << ELF::ElfMagic; // e_ident[EI_MAG0] to e_ident[EI_MAG3]
  336. W.OS << char(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
  337. // e_ident[EI_DATA]
  338. W.OS << char(W.Endian == support::little ? ELF::ELFDATA2LSB
  339. : ELF::ELFDATA2MSB);
  340. W.OS << char(ELF::EV_CURRENT); // e_ident[EI_VERSION]
  341. // e_ident[EI_OSABI]
  342. W.OS << char(OWriter.TargetObjectWriter->getOSABI());
  343. // e_ident[EI_ABIVERSION]
  344. W.OS << char(OWriter.TargetObjectWriter->getABIVersion());
  345. W.OS.write_zeros(ELF::EI_NIDENT - ELF::EI_PAD);
  346. W.write<uint16_t>(ELF::ET_REL); // e_type
  347. W.write<uint16_t>(OWriter.TargetObjectWriter->getEMachine()); // e_machine = target
  348. W.write<uint32_t>(ELF::EV_CURRENT); // e_version
  349. WriteWord(0); // e_entry, no entry point in .o file
  350. WriteWord(0); // e_phoff, no program header for .o
  351. WriteWord(0); // e_shoff = sec hdr table off in bytes
  352. // e_flags = whatever the target wants
  353. W.write<uint32_t>(Asm.getELFHeaderEFlags());
  354. // e_ehsize = ELF header size
  355. W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Ehdr)
  356. : sizeof(ELF::Elf32_Ehdr));
  357. W.write<uint16_t>(0); // e_phentsize = prog header entry size
  358. W.write<uint16_t>(0); // e_phnum = # prog header entries = 0
  359. // e_shentsize = Section header entry size
  360. W.write<uint16_t>(is64Bit() ? sizeof(ELF::Elf64_Shdr)
  361. : sizeof(ELF::Elf32_Shdr));
  362. // e_shnum = # of section header ents
  363. W.write<uint16_t>(0);
  364. // e_shstrndx = Section # of '.shstrtab'
  365. assert(StringTableIndex < ELF::SHN_LORESERVE);
  366. W.write<uint16_t>(StringTableIndex);
  367. }
  368. uint64_t ELFWriter::SymbolValue(const MCSymbol &Sym,
  369. const MCAsmLayout &Layout) {
  370. if (Sym.isCommon())
  371. return Sym.getCommonAlignment();
  372. uint64_t Res;
  373. if (!Layout.getSymbolOffset(Sym, Res))
  374. return 0;
  375. if (Layout.getAssembler().isThumbFunc(&Sym))
  376. Res |= 1;
  377. return Res;
  378. }
  379. static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
  380. uint8_t Type = newType;
  381. // Propagation rules:
  382. // IFUNC > FUNC > OBJECT > NOTYPE
  383. // TLS_OBJECT > OBJECT > NOTYPE
  384. //
  385. // dont let the new type degrade the old type
  386. switch (origType) {
  387. default:
  388. break;
  389. case ELF::STT_GNU_IFUNC:
  390. if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
  391. Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
  392. Type = ELF::STT_GNU_IFUNC;
  393. break;
  394. case ELF::STT_FUNC:
  395. if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
  396. Type == ELF::STT_TLS)
  397. Type = ELF::STT_FUNC;
  398. break;
  399. case ELF::STT_OBJECT:
  400. if (Type == ELF::STT_NOTYPE)
  401. Type = ELF::STT_OBJECT;
  402. break;
  403. case ELF::STT_TLS:
  404. if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
  405. Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
  406. Type = ELF::STT_TLS;
  407. break;
  408. }
  409. return Type;
  410. }
  411. static bool isIFunc(const MCSymbolELF *Symbol) {
  412. while (Symbol->getType() != ELF::STT_GNU_IFUNC) {
  413. const MCSymbolRefExpr *Value;
  414. if (!Symbol->isVariable() ||
  415. !(Value = dyn_cast<MCSymbolRefExpr>(Symbol->getVariableValue())) ||
  416. Value->getKind() != MCSymbolRefExpr::VK_None ||
  417. mergeTypeForSet(Symbol->getType(), ELF::STT_GNU_IFUNC) != ELF::STT_GNU_IFUNC)
  418. return false;
  419. Symbol = &cast<MCSymbolELF>(Value->getSymbol());
  420. }
  421. return true;
  422. }
  423. void ELFWriter::writeSymbol(SymbolTableWriter &Writer, uint32_t StringIndex,
  424. ELFSymbolData &MSD, const MCAsmLayout &Layout) {
  425. const auto &Symbol = cast<MCSymbolELF>(*MSD.Symbol);
  426. const MCSymbolELF *Base =
  427. cast_or_null<MCSymbolELF>(Layout.getBaseSymbol(Symbol));
  428. // This has to be in sync with when computeSymbolTable uses SHN_ABS or
  429. // SHN_COMMON.
  430. bool IsReserved = !Base || Symbol.isCommon();
  431. // Binding and Type share the same byte as upper and lower nibbles
  432. uint8_t Binding = Symbol.getBinding();
  433. uint8_t Type = Symbol.getType();
  434. if (isIFunc(&Symbol))
  435. Type = ELF::STT_GNU_IFUNC;
  436. if (Base) {
  437. Type = mergeTypeForSet(Type, Base->getType());
  438. }
  439. uint8_t Info = (Binding << 4) | Type;
  440. // Other and Visibility share the same byte with Visibility using the lower
  441. // 2 bits
  442. uint8_t Visibility = Symbol.getVisibility();
  443. uint8_t Other = Symbol.getOther() | Visibility;
  444. uint64_t Value = SymbolValue(*MSD.Symbol, Layout);
  445. uint64_t Size = 0;
  446. const MCExpr *ESize = MSD.Symbol->getSize();
  447. if (!ESize && Base)
  448. ESize = Base->getSize();
  449. if (ESize) {
  450. int64_t Res;
  451. if (!ESize->evaluateKnownAbsolute(Res, Layout))
  452. report_fatal_error("Size expression must be absolute.");
  453. Size = Res;
  454. }
  455. // Write out the symbol table entry
  456. Writer.writeSymbol(StringIndex, Info, Value, Size, Other, MSD.SectionIndex,
  457. IsReserved);
  458. }
  459. bool ELFWriter::isInSymtab(const MCAsmLayout &Layout, const MCSymbolELF &Symbol,
  460. bool Used, bool Renamed) {
  461. if (Symbol.isVariable()) {
  462. const MCExpr *Expr = Symbol.getVariableValue();
  463. // Target Expressions that are always inlined do not appear in the symtab
  464. if (const auto *T = dyn_cast<MCTargetExpr>(Expr))
  465. if (T->inlineAssignedExpr())
  466. return false;
  467. if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
  468. if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
  469. return false;
  470. }
  471. }
  472. if (Used)
  473. return true;
  474. if (Renamed)
  475. return false;
  476. if (Symbol.isVariable() && Symbol.isUndefined()) {
  477. // FIXME: this is here just to diagnose the case of a var = commmon_sym.
  478. Layout.getBaseSymbol(Symbol);
  479. return false;
  480. }
  481. if (Symbol.isTemporary())
  482. return false;
  483. if (Symbol.getType() == ELF::STT_SECTION)
  484. return false;
  485. return true;
  486. }
  487. void ELFWriter::computeSymbolTable(
  488. MCAssembler &Asm, const MCAsmLayout &Layout,
  489. const SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap,
  490. SectionOffsetsTy &SectionOffsets) {
  491. MCContext &Ctx = Asm.getContext();
  492. SymbolTableWriter Writer(*this, is64Bit());
  493. // Symbol table
  494. unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
  495. MCSectionELF *SymtabSection =
  496. Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
  497. SymtabSection->setAlignment(is64Bit() ? Align(8) : Align(4));
  498. SymbolTableIndex = addToSectionTable(SymtabSection);
  499. align(SymtabSection->getAlignment());
  500. uint64_t SecStart = W.OS.tell();
  501. // The first entry is the undefined symbol entry.
  502. Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
  503. std::vector<ELFSymbolData> LocalSymbolData;
  504. std::vector<ELFSymbolData> ExternalSymbolData;
  505. // Add the data for the symbols.
  506. bool HasLargeSectionIndex = false;
  507. for (const MCSymbol &S : Asm.symbols()) {
  508. const auto &Symbol = cast<MCSymbolELF>(S);
  509. bool Used = Symbol.isUsedInReloc();
  510. bool WeakrefUsed = Symbol.isWeakrefUsedInReloc();
  511. bool isSignature = Symbol.isSignature();
  512. if (!isInSymtab(Layout, Symbol, Used || WeakrefUsed || isSignature,
  513. OWriter.Renames.count(&Symbol)))
  514. continue;
  515. if (Symbol.isTemporary() && Symbol.isUndefined()) {
  516. Ctx.reportError(SMLoc(), "Undefined temporary symbol " + Symbol.getName());
  517. continue;
  518. }
  519. ELFSymbolData MSD;
  520. MSD.Symbol = cast<MCSymbolELF>(&Symbol);
  521. bool Local = Symbol.getBinding() == ELF::STB_LOCAL;
  522. assert(Local || !Symbol.isTemporary());
  523. if (Symbol.isAbsolute()) {
  524. MSD.SectionIndex = ELF::SHN_ABS;
  525. } else if (Symbol.isCommon()) {
  526. if (Symbol.isTargetCommon()) {
  527. MSD.SectionIndex = Symbol.getIndex();
  528. } else {
  529. assert(!Local);
  530. MSD.SectionIndex = ELF::SHN_COMMON;
  531. }
  532. } else if (Symbol.isUndefined()) {
  533. if (isSignature && !Used) {
  534. MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
  535. if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
  536. HasLargeSectionIndex = true;
  537. } else {
  538. MSD.SectionIndex = ELF::SHN_UNDEF;
  539. }
  540. } else {
  541. const MCSectionELF &Section =
  542. static_cast<const MCSectionELF &>(Symbol.getSection());
  543. // We may end up with a situation when section symbol is technically
  544. // defined, but should not be. That happens because we explicitly
  545. // pre-create few .debug_* sections to have accessors.
  546. // And if these sections were not really defined in the code, but were
  547. // referenced, we simply error out.
  548. if (!Section.isRegistered()) {
  549. assert(static_cast<const MCSymbolELF &>(Symbol).getType() ==
  550. ELF::STT_SECTION);
  551. Ctx.reportError(SMLoc(),
  552. "Undefined section reference: " + Symbol.getName());
  553. continue;
  554. }
  555. if (Mode == NonDwoOnly && isDwoSection(Section))
  556. continue;
  557. MSD.SectionIndex = SectionIndexMap.lookup(&Section);
  558. assert(MSD.SectionIndex && "Invalid section index!");
  559. if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
  560. HasLargeSectionIndex = true;
  561. }
  562. StringRef Name = Symbol.getName();
  563. // Sections have their own string table
  564. if (Symbol.getType() != ELF::STT_SECTION) {
  565. MSD.Name = Name;
  566. StrTabBuilder.add(Name);
  567. }
  568. if (Local)
  569. LocalSymbolData.push_back(MSD);
  570. else
  571. ExternalSymbolData.push_back(MSD);
  572. }
  573. // This holds the .symtab_shndx section index.
  574. unsigned SymtabShndxSectionIndex = 0;
  575. if (HasLargeSectionIndex) {
  576. MCSectionELF *SymtabShndxSection =
  577. Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
  578. SymtabShndxSectionIndex = addToSectionTable(SymtabShndxSection);
  579. SymtabShndxSection->setAlignment(Align(4));
  580. }
  581. ArrayRef<std::string> FileNames = Asm.getFileNames();
  582. for (const std::string &Name : FileNames)
  583. StrTabBuilder.add(Name);
  584. StrTabBuilder.finalize();
  585. // File symbols are emitted first and handled separately from normal symbols,
  586. // i.e. a non-STT_FILE symbol with the same name may appear.
  587. for (const std::string &Name : FileNames)
  588. Writer.writeSymbol(StrTabBuilder.getOffset(Name),
  589. ELF::STT_FILE | ELF::STB_LOCAL, 0, 0, ELF::STV_DEFAULT,
  590. ELF::SHN_ABS, true);
  591. // Symbols are required to be in lexicographic order.
  592. array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
  593. array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
  594. // Set the symbol indices. Local symbols must come before all other
  595. // symbols with non-local bindings.
  596. unsigned Index = FileNames.size() + 1;
  597. for (ELFSymbolData &MSD : LocalSymbolData) {
  598. unsigned StringIndex = MSD.Symbol->getType() == ELF::STT_SECTION
  599. ? 0
  600. : StrTabBuilder.getOffset(MSD.Name);
  601. MSD.Symbol->setIndex(Index++);
  602. writeSymbol(Writer, StringIndex, MSD, Layout);
  603. }
  604. // Write the symbol table entries.
  605. LastLocalSymbolIndex = Index;
  606. for (ELFSymbolData &MSD : ExternalSymbolData) {
  607. unsigned StringIndex = StrTabBuilder.getOffset(MSD.Name);
  608. MSD.Symbol->setIndex(Index++);
  609. writeSymbol(Writer, StringIndex, MSD, Layout);
  610. assert(MSD.Symbol->getBinding() != ELF::STB_LOCAL);
  611. }
  612. uint64_t SecEnd = W.OS.tell();
  613. SectionOffsets[SymtabSection] = std::make_pair(SecStart, SecEnd);
  614. ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
  615. if (ShndxIndexes.empty()) {
  616. assert(SymtabShndxSectionIndex == 0);
  617. return;
  618. }
  619. assert(SymtabShndxSectionIndex != 0);
  620. SecStart = W.OS.tell();
  621. const MCSectionELF *SymtabShndxSection =
  622. SectionTable[SymtabShndxSectionIndex - 1];
  623. for (uint32_t Index : ShndxIndexes)
  624. write(Index);
  625. SecEnd = W.OS.tell();
  626. SectionOffsets[SymtabShndxSection] = std::make_pair(SecStart, SecEnd);
  627. }
  628. void ELFWriter::writeAddrsigSection() {
  629. for (const MCSymbol *Sym : OWriter.AddrsigSyms)
  630. encodeULEB128(Sym->getIndex(), W.OS);
  631. }
  632. MCSectionELF *ELFWriter::createRelocationSection(MCContext &Ctx,
  633. const MCSectionELF &Sec) {
  634. if (OWriter.Relocations[&Sec].empty())
  635. return nullptr;
  636. const StringRef SectionName = Sec.getName();
  637. std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
  638. RelaSectionName += SectionName;
  639. unsigned EntrySize;
  640. if (hasRelocationAddend())
  641. EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
  642. else
  643. EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
  644. unsigned Flags = 0;
  645. if (Sec.getFlags() & ELF::SHF_GROUP)
  646. Flags = ELF::SHF_GROUP;
  647. MCSectionELF *RelaSection = Ctx.createELFRelSection(
  648. RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
  649. Flags, EntrySize, Sec.getGroup(), &Sec);
  650. RelaSection->setAlignment(is64Bit() ? Align(8) : Align(4));
  651. return RelaSection;
  652. }
  653. // Include the debug info compression header.
  654. bool ELFWriter::maybeWriteCompression(
  655. uint64_t Size, SmallVectorImpl<char> &CompressedContents, bool ZLibStyle,
  656. unsigned Alignment) {
  657. if (ZLibStyle) {
  658. uint64_t HdrSize =
  659. is64Bit() ? sizeof(ELF::Elf32_Chdr) : sizeof(ELF::Elf64_Chdr);
  660. if (Size <= HdrSize + CompressedContents.size())
  661. return false;
  662. // Platform specific header is followed by compressed data.
  663. if (is64Bit()) {
  664. // Write Elf64_Chdr header.
  665. write(static_cast<ELF::Elf64_Word>(ELF::ELFCOMPRESS_ZLIB));
  666. write(static_cast<ELF::Elf64_Word>(0)); // ch_reserved field.
  667. write(static_cast<ELF::Elf64_Xword>(Size));
  668. write(static_cast<ELF::Elf64_Xword>(Alignment));
  669. } else {
  670. // Write Elf32_Chdr header otherwise.
  671. write(static_cast<ELF::Elf32_Word>(ELF::ELFCOMPRESS_ZLIB));
  672. write(static_cast<ELF::Elf32_Word>(Size));
  673. write(static_cast<ELF::Elf32_Word>(Alignment));
  674. }
  675. return true;
  676. }
  677. // "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
  678. // useful for consumers to preallocate a buffer to decompress into.
  679. const StringRef Magic = "ZLIB";
  680. if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
  681. return false;
  682. W.OS << Magic;
  683. support::endian::write(W.OS, Size, support::big);
  684. return true;
  685. }
  686. void ELFWriter::writeSectionData(const MCAssembler &Asm, MCSection &Sec,
  687. const MCAsmLayout &Layout) {
  688. MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
  689. StringRef SectionName = Section.getName();
  690. auto &MC = Asm.getContext();
  691. const auto &MAI = MC.getAsmInfo();
  692. // Compressing debug_frame requires handling alignment fragments which is
  693. // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
  694. // for writing to arbitrary buffers) for little benefit.
  695. bool CompressionEnabled =
  696. MAI->compressDebugSections() != DebugCompressionType::None;
  697. if (!CompressionEnabled || !SectionName.startswith(".debug_") ||
  698. SectionName == ".debug_frame") {
  699. Asm.writeSectionData(W.OS, &Section, Layout);
  700. return;
  701. }
  702. assert((MAI->compressDebugSections() == DebugCompressionType::Z ||
  703. MAI->compressDebugSections() == DebugCompressionType::GNU) &&
  704. "expected zlib or zlib-gnu style compression");
  705. SmallVector<char, 128> UncompressedData;
  706. raw_svector_ostream VecOS(UncompressedData);
  707. Asm.writeSectionData(VecOS, &Section, Layout);
  708. SmallVector<char, 128> CompressedContents;
  709. if (Error E = zlib::compress(
  710. StringRef(UncompressedData.data(), UncompressedData.size()),
  711. CompressedContents)) {
  712. consumeError(std::move(E));
  713. W.OS << UncompressedData;
  714. return;
  715. }
  716. bool ZlibStyle = MAI->compressDebugSections() == DebugCompressionType::Z;
  717. if (!maybeWriteCompression(UncompressedData.size(), CompressedContents,
  718. ZlibStyle, Sec.getAlignment())) {
  719. W.OS << UncompressedData;
  720. return;
  721. }
  722. if (ZlibStyle) {
  723. // Set the compressed flag. That is zlib style.
  724. Section.setFlags(Section.getFlags() | ELF::SHF_COMPRESSED);
  725. // Alignment field should reflect the requirements of
  726. // the compressed section header.
  727. Section.setAlignment(is64Bit() ? Align(8) : Align(4));
  728. } else {
  729. // Add "z" prefix to section name. This is zlib-gnu style.
  730. MC.renameELFSection(&Section, (".z" + SectionName.drop_front(1)).str());
  731. }
  732. W.OS << CompressedContents;
  733. }
  734. void ELFWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
  735. uint64_t Address, uint64_t Offset,
  736. uint64_t Size, uint32_t Link, uint32_t Info,
  737. uint64_t Alignment, uint64_t EntrySize) {
  738. W.write<uint32_t>(Name); // sh_name: index into string table
  739. W.write<uint32_t>(Type); // sh_type
  740. WriteWord(Flags); // sh_flags
  741. WriteWord(Address); // sh_addr
  742. WriteWord(Offset); // sh_offset
  743. WriteWord(Size); // sh_size
  744. W.write<uint32_t>(Link); // sh_link
  745. W.write<uint32_t>(Info); // sh_info
  746. WriteWord(Alignment); // sh_addralign
  747. WriteWord(EntrySize); // sh_entsize
  748. }
  749. void ELFWriter::writeRelocations(const MCAssembler &Asm,
  750. const MCSectionELF &Sec) {
  751. std::vector<ELFRelocationEntry> &Relocs = OWriter.Relocations[&Sec];
  752. // We record relocations by pushing to the end of a vector. Reverse the vector
  753. // to get the relocations in the order they were created.
  754. // In most cases that is not important, but it can be for special sections
  755. // (.eh_frame) or specific relocations (TLS optimizations on SystemZ).
  756. std::reverse(Relocs.begin(), Relocs.end());
  757. // Sort the relocation entries. MIPS needs this.
  758. OWriter.TargetObjectWriter->sortRelocs(Asm, Relocs);
  759. for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
  760. const ELFRelocationEntry &Entry = Relocs[e - i - 1];
  761. unsigned Index = Entry.Symbol ? Entry.Symbol->getIndex() : 0;
  762. if (is64Bit()) {
  763. write(Entry.Offset);
  764. if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
  765. write(uint32_t(Index));
  766. write(OWriter.TargetObjectWriter->getRSsym(Entry.Type));
  767. write(OWriter.TargetObjectWriter->getRType3(Entry.Type));
  768. write(OWriter.TargetObjectWriter->getRType2(Entry.Type));
  769. write(OWriter.TargetObjectWriter->getRType(Entry.Type));
  770. } else {
  771. struct ELF::Elf64_Rela ERE64;
  772. ERE64.setSymbolAndType(Index, Entry.Type);
  773. write(ERE64.r_info);
  774. }
  775. if (hasRelocationAddend())
  776. write(Entry.Addend);
  777. } else {
  778. write(uint32_t(Entry.Offset));
  779. struct ELF::Elf32_Rela ERE32;
  780. ERE32.setSymbolAndType(Index, Entry.Type);
  781. write(ERE32.r_info);
  782. if (hasRelocationAddend())
  783. write(uint32_t(Entry.Addend));
  784. if (OWriter.TargetObjectWriter->getEMachine() == ELF::EM_MIPS) {
  785. if (uint32_t RType =
  786. OWriter.TargetObjectWriter->getRType2(Entry.Type)) {
  787. write(uint32_t(Entry.Offset));
  788. ERE32.setSymbolAndType(0, RType);
  789. write(ERE32.r_info);
  790. write(uint32_t(0));
  791. }
  792. if (uint32_t RType =
  793. OWriter.TargetObjectWriter->getRType3(Entry.Type)) {
  794. write(uint32_t(Entry.Offset));
  795. ERE32.setSymbolAndType(0, RType);
  796. write(ERE32.r_info);
  797. write(uint32_t(0));
  798. }
  799. }
  800. }
  801. }
  802. }
  803. const MCSectionELF *ELFWriter::createStringTable(MCContext &Ctx) {
  804. const MCSectionELF *StrtabSection = SectionTable[StringTableIndex - 1];
  805. StrTabBuilder.write(W.OS);
  806. return StrtabSection;
  807. }
  808. void ELFWriter::writeSection(const SectionIndexMapTy &SectionIndexMap,
  809. uint32_t GroupSymbolIndex, uint64_t Offset,
  810. uint64_t Size, const MCSectionELF &Section) {
  811. uint64_t sh_link = 0;
  812. uint64_t sh_info = 0;
  813. switch(Section.getType()) {
  814. default:
  815. // Nothing to do.
  816. break;
  817. case ELF::SHT_DYNAMIC:
  818. llvm_unreachable("SHT_DYNAMIC in a relocatable object");
  819. case ELF::SHT_REL:
  820. case ELF::SHT_RELA: {
  821. sh_link = SymbolTableIndex;
  822. assert(sh_link && ".symtab not found");
  823. const MCSection *InfoSection = Section.getLinkedToSection();
  824. sh_info = SectionIndexMap.lookup(cast<MCSectionELF>(InfoSection));
  825. break;
  826. }
  827. case ELF::SHT_SYMTAB:
  828. sh_link = StringTableIndex;
  829. sh_info = LastLocalSymbolIndex;
  830. break;
  831. case ELF::SHT_SYMTAB_SHNDX:
  832. case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
  833. case ELF::SHT_LLVM_ADDRSIG:
  834. sh_link = SymbolTableIndex;
  835. break;
  836. case ELF::SHT_GROUP:
  837. sh_link = SymbolTableIndex;
  838. sh_info = GroupSymbolIndex;
  839. break;
  840. }
  841. if (Section.getFlags() & ELF::SHF_LINK_ORDER) {
  842. // If the value in the associated metadata is not a definition, Sym will be
  843. // undefined. Represent this with sh_link=0.
  844. const MCSymbol *Sym = Section.getLinkedToSymbol();
  845. if (Sym && Sym->isInSection()) {
  846. const MCSectionELF *Sec = cast<MCSectionELF>(&Sym->getSection());
  847. sh_link = SectionIndexMap.lookup(Sec);
  848. }
  849. }
  850. WriteSecHdrEntry(StrTabBuilder.getOffset(Section.getName()),
  851. Section.getType(), Section.getFlags(), 0, Offset, Size,
  852. sh_link, sh_info, Section.getAlignment(),
  853. Section.getEntrySize());
  854. }
  855. void ELFWriter::writeSectionHeader(
  856. const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
  857. const SectionOffsetsTy &SectionOffsets) {
  858. const unsigned NumSections = SectionTable.size();
  859. // Null section first.
  860. uint64_t FirstSectionSize =
  861. (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
  862. WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
  863. for (const MCSectionELF *Section : SectionTable) {
  864. uint32_t GroupSymbolIndex;
  865. unsigned Type = Section->getType();
  866. if (Type != ELF::SHT_GROUP)
  867. GroupSymbolIndex = 0;
  868. else
  869. GroupSymbolIndex = Section->getGroup()->getIndex();
  870. const std::pair<uint64_t, uint64_t> &Offsets =
  871. SectionOffsets.find(Section)->second;
  872. uint64_t Size;
  873. if (Type == ELF::SHT_NOBITS)
  874. Size = Layout.getSectionAddressSize(Section);
  875. else
  876. Size = Offsets.second - Offsets.first;
  877. writeSection(SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
  878. *Section);
  879. }
  880. }
  881. uint64_t ELFWriter::writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
  882. uint64_t StartOffset = W.OS.tell();
  883. MCContext &Ctx = Asm.getContext();
  884. MCSectionELF *StrtabSection =
  885. Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
  886. StringTableIndex = addToSectionTable(StrtabSection);
  887. RevGroupMapTy RevGroupMap;
  888. SectionIndexMapTy SectionIndexMap;
  889. std::map<const MCSymbol *, std::vector<const MCSectionELF *>> GroupMembers;
  890. // Write out the ELF header ...
  891. writeHeader(Asm);
  892. // ... then the sections ...
  893. SectionOffsetsTy SectionOffsets;
  894. std::vector<MCSectionELF *> Groups;
  895. std::vector<MCSectionELF *> Relocations;
  896. for (MCSection &Sec : Asm) {
  897. MCSectionELF &Section = static_cast<MCSectionELF &>(Sec);
  898. if (Mode == NonDwoOnly && isDwoSection(Section))
  899. continue;
  900. if (Mode == DwoOnly && !isDwoSection(Section))
  901. continue;
  902. align(Section.getAlignment());
  903. // Remember the offset into the file for this section.
  904. uint64_t SecStart = W.OS.tell();
  905. const MCSymbolELF *SignatureSymbol = Section.getGroup();
  906. writeSectionData(Asm, Section, Layout);
  907. uint64_t SecEnd = W.OS.tell();
  908. SectionOffsets[&Section] = std::make_pair(SecStart, SecEnd);
  909. MCSectionELF *RelSection = createRelocationSection(Ctx, Section);
  910. if (SignatureSymbol) {
  911. Asm.registerSymbol(*SignatureSymbol);
  912. unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
  913. if (!GroupIdx) {
  914. MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
  915. GroupIdx = addToSectionTable(Group);
  916. Group->setAlignment(Align(4));
  917. Groups.push_back(Group);
  918. }
  919. std::vector<const MCSectionELF *> &Members =
  920. GroupMembers[SignatureSymbol];
  921. Members.push_back(&Section);
  922. if (RelSection)
  923. Members.push_back(RelSection);
  924. }
  925. SectionIndexMap[&Section] = addToSectionTable(&Section);
  926. if (RelSection) {
  927. SectionIndexMap[RelSection] = addToSectionTable(RelSection);
  928. Relocations.push_back(RelSection);
  929. }
  930. OWriter.TargetObjectWriter->addTargetSectionFlags(Ctx, Section);
  931. }
  932. MCSectionELF *CGProfileSection = nullptr;
  933. if (!Asm.CGProfile.empty()) {
  934. CGProfileSection = Ctx.getELFSection(".llvm.call-graph-profile",
  935. ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
  936. ELF::SHF_EXCLUDE, 16, "");
  937. SectionIndexMap[CGProfileSection] = addToSectionTable(CGProfileSection);
  938. }
  939. for (MCSectionELF *Group : Groups) {
  940. align(Group->getAlignment());
  941. // Remember the offset into the file for this section.
  942. uint64_t SecStart = W.OS.tell();
  943. const MCSymbol *SignatureSymbol = Group->getGroup();
  944. assert(SignatureSymbol);
  945. write(uint32_t(ELF::GRP_COMDAT));
  946. for (const MCSectionELF *Member : GroupMembers[SignatureSymbol]) {
  947. uint32_t SecIndex = SectionIndexMap.lookup(Member);
  948. write(SecIndex);
  949. }
  950. uint64_t SecEnd = W.OS.tell();
  951. SectionOffsets[Group] = std::make_pair(SecStart, SecEnd);
  952. }
  953. if (Mode == DwoOnly) {
  954. // dwo files don't have symbol tables or relocations, but they do have
  955. // string tables.
  956. StrTabBuilder.finalize();
  957. } else {
  958. MCSectionELF *AddrsigSection;
  959. if (OWriter.EmitAddrsigSection) {
  960. AddrsigSection = Ctx.getELFSection(".llvm_addrsig", ELF::SHT_LLVM_ADDRSIG,
  961. ELF::SHF_EXCLUDE);
  962. addToSectionTable(AddrsigSection);
  963. }
  964. // Compute symbol table information.
  965. computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
  966. SectionOffsets);
  967. for (MCSectionELF *RelSection : Relocations) {
  968. align(RelSection->getAlignment());
  969. // Remember the offset into the file for this section.
  970. uint64_t SecStart = W.OS.tell();
  971. writeRelocations(Asm,
  972. cast<MCSectionELF>(*RelSection->getLinkedToSection()));
  973. uint64_t SecEnd = W.OS.tell();
  974. SectionOffsets[RelSection] = std::make_pair(SecStart, SecEnd);
  975. }
  976. if (OWriter.EmitAddrsigSection) {
  977. uint64_t SecStart = W.OS.tell();
  978. writeAddrsigSection();
  979. uint64_t SecEnd = W.OS.tell();
  980. SectionOffsets[AddrsigSection] = std::make_pair(SecStart, SecEnd);
  981. }
  982. }
  983. if (CGProfileSection) {
  984. uint64_t SecStart = W.OS.tell();
  985. for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
  986. W.write<uint32_t>(CGPE.From->getSymbol().getIndex());
  987. W.write<uint32_t>(CGPE.To->getSymbol().getIndex());
  988. W.write<uint64_t>(CGPE.Count);
  989. }
  990. uint64_t SecEnd = W.OS.tell();
  991. SectionOffsets[CGProfileSection] = std::make_pair(SecStart, SecEnd);
  992. }
  993. {
  994. uint64_t SecStart = W.OS.tell();
  995. const MCSectionELF *Sec = createStringTable(Ctx);
  996. uint64_t SecEnd = W.OS.tell();
  997. SectionOffsets[Sec] = std::make_pair(SecStart, SecEnd);
  998. }
  999. uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
  1000. align(NaturalAlignment);
  1001. const uint64_t SectionHeaderOffset = W.OS.tell();
  1002. // ... then the section header table ...
  1003. writeSectionHeader(Layout, SectionIndexMap, SectionOffsets);
  1004. uint16_t NumSections = support::endian::byte_swap<uint16_t>(
  1005. (SectionTable.size() + 1 >= ELF::SHN_LORESERVE) ? (uint16_t)ELF::SHN_UNDEF
  1006. : SectionTable.size() + 1,
  1007. W.Endian);
  1008. unsigned NumSectionsOffset;
  1009. auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
  1010. if (is64Bit()) {
  1011. uint64_t Val =
  1012. support::endian::byte_swap<uint64_t>(SectionHeaderOffset, W.Endian);
  1013. Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
  1014. offsetof(ELF::Elf64_Ehdr, e_shoff));
  1015. NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
  1016. } else {
  1017. uint32_t Val =
  1018. support::endian::byte_swap<uint32_t>(SectionHeaderOffset, W.Endian);
  1019. Stream.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
  1020. offsetof(ELF::Elf32_Ehdr, e_shoff));
  1021. NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
  1022. }
  1023. Stream.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
  1024. NumSectionsOffset);
  1025. return W.OS.tell() - StartOffset;
  1026. }
  1027. bool ELFObjectWriter::hasRelocationAddend() const {
  1028. return TargetObjectWriter->hasRelocationAddend();
  1029. }
  1030. void ELFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
  1031. const MCAsmLayout &Layout) {
  1032. // The presence of symbol versions causes undefined symbols and
  1033. // versions declared with @@@ to be renamed.
  1034. for (const MCAssembler::Symver &S : Asm.Symvers) {
  1035. StringRef AliasName = S.Name;
  1036. const auto &Symbol = cast<MCSymbolELF>(*S.Sym);
  1037. size_t Pos = AliasName.find('@');
  1038. assert(Pos != StringRef::npos);
  1039. StringRef Prefix = AliasName.substr(0, Pos);
  1040. StringRef Rest = AliasName.substr(Pos);
  1041. StringRef Tail = Rest;
  1042. if (Rest.startswith("@@@"))
  1043. Tail = Rest.substr(Symbol.isUndefined() ? 2 : 1);
  1044. auto *Alias =
  1045. cast<MCSymbolELF>(Asm.getContext().getOrCreateSymbol(Prefix + Tail));
  1046. Asm.registerSymbol(*Alias);
  1047. const MCExpr *Value = MCSymbolRefExpr::create(&Symbol, Asm.getContext());
  1048. Alias->setVariableValue(Value);
  1049. // Aliases defined with .symvar copy the binding from the symbol they alias.
  1050. // This is the first place we are able to copy this information.
  1051. Alias->setBinding(Symbol.getBinding());
  1052. Alias->setVisibility(Symbol.getVisibility());
  1053. Alias->setOther(Symbol.getOther());
  1054. if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
  1055. continue;
  1056. if (Symbol.isUndefined() && Rest.startswith("@@") &&
  1057. !Rest.startswith("@@@")) {
  1058. Asm.getContext().reportError(S.Loc, "default version symbol " +
  1059. AliasName + " must be defined");
  1060. continue;
  1061. }
  1062. if (Renames.count(&Symbol) && Renames[&Symbol] != Alias) {
  1063. Asm.getContext().reportError(S.Loc, Twine("multiple versions for ") +
  1064. Symbol.getName());
  1065. continue;
  1066. }
  1067. Renames.insert(std::make_pair(&Symbol, Alias));
  1068. }
  1069. for (const MCSymbol *&Sym : AddrsigSyms) {
  1070. if (const MCSymbol *R = Renames.lookup(cast<MCSymbolELF>(Sym)))
  1071. Sym = R;
  1072. if (Sym->isInSection() && Sym->getName().startswith(".L"))
  1073. Sym = Sym->getSection().getBeginSymbol();
  1074. Sym->setUsedInReloc();
  1075. }
  1076. }
  1077. // It is always valid to create a relocation with a symbol. It is preferable
  1078. // to use a relocation with a section if that is possible. Using the section
  1079. // allows us to omit some local symbols from the symbol table.
  1080. bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
  1081. const MCSymbolRefExpr *RefA,
  1082. const MCSymbolELF *Sym,
  1083. uint64_t C,
  1084. unsigned Type) const {
  1085. // A PCRel relocation to an absolute value has no symbol (or section). We
  1086. // represent that with a relocation to a null section.
  1087. if (!RefA)
  1088. return false;
  1089. MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
  1090. switch (Kind) {
  1091. default:
  1092. break;
  1093. // The .odp creation emits a relocation against the symbol ".TOC." which
  1094. // create a R_PPC64_TOC relocation. However the relocation symbol name
  1095. // in final object creation should be NULL, since the symbol does not
  1096. // really exist, it is just the reference to TOC base for the current
  1097. // object file. Since the symbol is undefined, returning false results
  1098. // in a relocation with a null section which is the desired result.
  1099. case MCSymbolRefExpr::VK_PPC_TOCBASE:
  1100. return false;
  1101. // These VariantKind cause the relocation to refer to something other than
  1102. // the symbol itself, like a linker generated table. Since the address of
  1103. // symbol is not relevant, we cannot replace the symbol with the
  1104. // section and patch the difference in the addend.
  1105. case MCSymbolRefExpr::VK_GOT:
  1106. case MCSymbolRefExpr::VK_PLT:
  1107. case MCSymbolRefExpr::VK_GOTPCREL:
  1108. case MCSymbolRefExpr::VK_PPC_GOT_LO:
  1109. case MCSymbolRefExpr::VK_PPC_GOT_HI:
  1110. case MCSymbolRefExpr::VK_PPC_GOT_HA:
  1111. return true;
  1112. }
  1113. // An undefined symbol is not in any section, so the relocation has to point
  1114. // to the symbol itself.
  1115. assert(Sym && "Expected a symbol");
  1116. if (Sym->isUndefined())
  1117. return true;
  1118. unsigned Binding = Sym->getBinding();
  1119. switch(Binding) {
  1120. default:
  1121. llvm_unreachable("Invalid Binding");
  1122. case ELF::STB_LOCAL:
  1123. break;
  1124. case ELF::STB_WEAK:
  1125. // If the symbol is weak, it might be overridden by a symbol in another
  1126. // file. The relocation has to point to the symbol so that the linker
  1127. // can update it.
  1128. return true;
  1129. case ELF::STB_GLOBAL:
  1130. // Global ELF symbols can be preempted by the dynamic linker. The relocation
  1131. // has to point to the symbol for a reason analogous to the STB_WEAK case.
  1132. return true;
  1133. }
  1134. // Keep symbol type for a local ifunc because it may result in an IRELATIVE
  1135. // reloc that the dynamic loader will use to resolve the address at startup
  1136. // time.
  1137. if (Sym->getType() == ELF::STT_GNU_IFUNC)
  1138. return true;
  1139. // If a relocation points to a mergeable section, we have to be careful.
  1140. // If the offset is zero, a relocation with the section will encode the
  1141. // same information. With a non-zero offset, the situation is different.
  1142. // For example, a relocation can point 42 bytes past the end of a string.
  1143. // If we change such a relocation to use the section, the linker would think
  1144. // that it pointed to another string and subtracting 42 at runtime will
  1145. // produce the wrong value.
  1146. if (Sym->isInSection()) {
  1147. auto &Sec = cast<MCSectionELF>(Sym->getSection());
  1148. unsigned Flags = Sec.getFlags();
  1149. if (Flags & ELF::SHF_MERGE) {
  1150. if (C != 0)
  1151. return true;
  1152. // gold<2.34 incorrectly ignored the addend for R_386_GOTOFF (9)
  1153. // (http://sourceware.org/PR16794).
  1154. if (TargetObjectWriter->getEMachine() == ELF::EM_386 &&
  1155. Type == ELF::R_386_GOTOFF)
  1156. return true;
  1157. // ld.lld handles R_MIPS_HI16/R_MIPS_LO16 separately, not as a whole, so
  1158. // it doesn't know that an R_MIPS_HI16 with implicit addend 1 and an
  1159. // R_MIPS_LO16 with implicit addend -32768 represents 32768, which is in
  1160. // range of a MergeInputSection. We could introduce a new RelExpr member
  1161. // (like R_RISCV_PC_INDIRECT for R_RISCV_PCREL_HI20 / R_RISCV_PCREL_LO12)
  1162. // but the complexity is unnecessary given that GNU as keeps the original
  1163. // symbol for this case as well.
  1164. if (TargetObjectWriter->getEMachine() == ELF::EM_MIPS &&
  1165. !hasRelocationAddend())
  1166. return true;
  1167. }
  1168. // Most TLS relocations use a got, so they need the symbol. Even those that
  1169. // are just an offset (@tpoff), require a symbol in gold versions before
  1170. // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
  1171. // http://sourceware.org/PR16773.
  1172. if (Flags & ELF::SHF_TLS)
  1173. return true;
  1174. }
  1175. // If the symbol is a thumb function the final relocation must set the lowest
  1176. // bit. With a symbol that is done by just having the symbol have that bit
  1177. // set, so we would lose the bit if we relocated with the section.
  1178. // FIXME: We could use the section but add the bit to the relocation value.
  1179. if (Asm.isThumbFunc(Sym))
  1180. return true;
  1181. if (TargetObjectWriter->needsRelocateWithSymbol(*Sym, Type))
  1182. return true;
  1183. return false;
  1184. }
  1185. void ELFObjectWriter::recordRelocation(MCAssembler &Asm,
  1186. const MCAsmLayout &Layout,
  1187. const MCFragment *Fragment,
  1188. const MCFixup &Fixup, MCValue Target,
  1189. uint64_t &FixedValue) {
  1190. MCAsmBackend &Backend = Asm.getBackend();
  1191. bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
  1192. MCFixupKindInfo::FKF_IsPCRel;
  1193. const MCSectionELF &FixupSection = cast<MCSectionELF>(*Fragment->getParent());
  1194. uint64_t C = Target.getConstant();
  1195. uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
  1196. MCContext &Ctx = Asm.getContext();
  1197. if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
  1198. const auto &SymB = cast<MCSymbolELF>(RefB->getSymbol());
  1199. if (SymB.isUndefined()) {
  1200. Ctx.reportError(Fixup.getLoc(),
  1201. Twine("symbol '") + SymB.getName() +
  1202. "' can not be undefined in a subtraction expression");
  1203. return;
  1204. }
  1205. assert(!SymB.isAbsolute() && "Should have been folded");
  1206. const MCSection &SecB = SymB.getSection();
  1207. if (&SecB != &FixupSection) {
  1208. Ctx.reportError(Fixup.getLoc(),
  1209. "Cannot represent a difference across sections");
  1210. return;
  1211. }
  1212. assert(!IsPCRel && "should have been folded");
  1213. IsPCRel = true;
  1214. C += FixupOffset - Layout.getSymbolOffset(SymB);
  1215. }
  1216. // We either rejected the fixup or folded B into C at this point.
  1217. const MCSymbolRefExpr *RefA = Target.getSymA();
  1218. const auto *SymA = RefA ? cast<MCSymbolELF>(&RefA->getSymbol()) : nullptr;
  1219. bool ViaWeakRef = false;
  1220. if (SymA && SymA->isVariable()) {
  1221. const MCExpr *Expr = SymA->getVariableValue();
  1222. if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) {
  1223. if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) {
  1224. SymA = cast<MCSymbolELF>(&Inner->getSymbol());
  1225. ViaWeakRef = true;
  1226. }
  1227. }
  1228. }
  1229. const MCSectionELF *SecA = (SymA && SymA->isInSection())
  1230. ? cast<MCSectionELF>(&SymA->getSection())
  1231. : nullptr;
  1232. if (!checkRelocation(Ctx, Fixup.getLoc(), &FixupSection, SecA))
  1233. return;
  1234. unsigned Type = TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel);
  1235. bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymA, C, Type);
  1236. uint64_t Addend = 0;
  1237. FixedValue = !RelocateWithSymbol && SymA && !SymA->isUndefined()
  1238. ? C + Layout.getSymbolOffset(*SymA)
  1239. : C;
  1240. if (hasRelocationAddend()) {
  1241. Addend = FixedValue;
  1242. FixedValue = 0;
  1243. }
  1244. if (!RelocateWithSymbol) {
  1245. const auto *SectionSymbol =
  1246. SecA ? cast<MCSymbolELF>(SecA->getBeginSymbol()) : nullptr;
  1247. if (SectionSymbol)
  1248. SectionSymbol->setUsedInReloc();
  1249. ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend, SymA, C);
  1250. Relocations[&FixupSection].push_back(Rec);
  1251. return;
  1252. }
  1253. const MCSymbolELF *RenamedSymA = SymA;
  1254. if (SymA) {
  1255. if (const MCSymbolELF *R = Renames.lookup(SymA))
  1256. RenamedSymA = R;
  1257. if (ViaWeakRef)
  1258. RenamedSymA->setIsWeakrefUsedInReloc();
  1259. else
  1260. RenamedSymA->setUsedInReloc();
  1261. }
  1262. ELFRelocationEntry Rec(FixupOffset, RenamedSymA, Type, Addend, SymA, C);
  1263. Relocations[&FixupSection].push_back(Rec);
  1264. }
  1265. bool ELFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
  1266. const MCAssembler &Asm, const MCSymbol &SA, const MCFragment &FB,
  1267. bool InSet, bool IsPCRel) const {
  1268. const auto &SymA = cast<MCSymbolELF>(SA);
  1269. if (IsPCRel) {
  1270. assert(!InSet);
  1271. if (SymA.getBinding() != ELF::STB_LOCAL ||
  1272. SymA.getType() == ELF::STT_GNU_IFUNC)
  1273. return false;
  1274. }
  1275. return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
  1276. InSet, IsPCRel);
  1277. }
  1278. std::unique_ptr<MCObjectWriter>
  1279. llvm::createELFObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
  1280. raw_pwrite_stream &OS, bool IsLittleEndian) {
  1281. return std::make_unique<ELFSingleObjectWriter>(std::move(MOTW), OS,
  1282. IsLittleEndian);
  1283. }
  1284. std::unique_ptr<MCObjectWriter>
  1285. llvm::createELFDwoObjectWriter(std::unique_ptr<MCELFObjectTargetWriter> MOTW,
  1286. raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS,
  1287. bool IsLittleEndian) {
  1288. return std::make_unique<ELFDwoObjectWriter>(std::move(MOTW), OS, DwoOS,
  1289. IsLittleEndian);
  1290. }