ELFObjectWriter.cpp 52 KB

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