ELFObject.cpp 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782
  1. //===- ELFObject.cpp ------------------------------------------------------===//
  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. #include "ELFObject.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/ADT/Twine.h"
  13. #include "llvm/ADT/iterator_range.h"
  14. #include "llvm/BinaryFormat/ELF.h"
  15. #include "llvm/MC/MCTargetOptions.h"
  16. #include "llvm/Object/ELF.h"
  17. #include "llvm/Object/ELFObjectFile.h"
  18. #include "llvm/Support/Compression.h"
  19. #include "llvm/Support/Endian.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include "llvm/Support/FileOutputBuffer.h"
  22. #include "llvm/Support/Path.h"
  23. #include <algorithm>
  24. #include <cstddef>
  25. #include <cstdint>
  26. #include <iterator>
  27. #include <unordered_set>
  28. #include <utility>
  29. #include <vector>
  30. using namespace llvm;
  31. using namespace llvm::ELF;
  32. using namespace llvm::objcopy::elf;
  33. using namespace llvm::object;
  34. template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
  35. uint8_t *B = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
  36. Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
  37. Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
  38. Phdr.p_type = Seg.Type;
  39. Phdr.p_flags = Seg.Flags;
  40. Phdr.p_offset = Seg.Offset;
  41. Phdr.p_vaddr = Seg.VAddr;
  42. Phdr.p_paddr = Seg.PAddr;
  43. Phdr.p_filesz = Seg.FileSize;
  44. Phdr.p_memsz = Seg.MemSize;
  45. Phdr.p_align = Seg.Align;
  46. }
  47. Error SectionBase::removeSectionReferences(
  48. bool, function_ref<bool(const SectionBase *)>) {
  49. return Error::success();
  50. }
  51. Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)>) {
  52. return Error::success();
  53. }
  54. Error SectionBase::initialize(SectionTableRef) { return Error::success(); }
  55. void SectionBase::finalize() {}
  56. void SectionBase::markSymbols() {}
  57. void SectionBase::replaceSectionReferences(
  58. const DenseMap<SectionBase *, SectionBase *> &) {}
  59. void SectionBase::onRemove() {}
  60. template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
  61. uint8_t *B =
  62. reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Sec.HeaderOffset;
  63. Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
  64. Shdr.sh_name = Sec.NameIndex;
  65. Shdr.sh_type = Sec.Type;
  66. Shdr.sh_flags = Sec.Flags;
  67. Shdr.sh_addr = Sec.Addr;
  68. Shdr.sh_offset = Sec.Offset;
  69. Shdr.sh_size = Sec.Size;
  70. Shdr.sh_link = Sec.Link;
  71. Shdr.sh_info = Sec.Info;
  72. Shdr.sh_addralign = Sec.Align;
  73. Shdr.sh_entsize = Sec.EntrySize;
  74. }
  75. template <class ELFT> Error ELFSectionSizer<ELFT>::visit(Section &) {
  76. return Error::success();
  77. }
  78. template <class ELFT> Error ELFSectionSizer<ELFT>::visit(OwnedDataSection &) {
  79. return Error::success();
  80. }
  81. template <class ELFT> Error ELFSectionSizer<ELFT>::visit(StringTableSection &) {
  82. return Error::success();
  83. }
  84. template <class ELFT>
  85. Error ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &) {
  86. return Error::success();
  87. }
  88. template <class ELFT>
  89. Error ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
  90. Sec.EntrySize = sizeof(Elf_Sym);
  91. Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
  92. // Align to the largest field in Elf_Sym.
  93. Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
  94. return Error::success();
  95. }
  96. template <class ELFT>
  97. Error ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
  98. Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
  99. Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
  100. // Align to the largest field in Elf_Rel(a).
  101. Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
  102. return Error::success();
  103. }
  104. template <class ELFT>
  105. Error ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &) {
  106. return Error::success();
  107. }
  108. template <class ELFT> Error ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {
  109. Sec.Size = sizeof(Elf_Word) + Sec.GroupMembers.size() * sizeof(Elf_Word);
  110. return Error::success();
  111. }
  112. template <class ELFT>
  113. Error ELFSectionSizer<ELFT>::visit(SectionIndexSection &) {
  114. return Error::success();
  115. }
  116. template <class ELFT> Error ELFSectionSizer<ELFT>::visit(CompressedSection &) {
  117. return Error::success();
  118. }
  119. template <class ELFT>
  120. Error ELFSectionSizer<ELFT>::visit(DecompressedSection &) {
  121. return Error::success();
  122. }
  123. Error BinarySectionWriter::visit(const SectionIndexSection &Sec) {
  124. return createStringError(errc::operation_not_permitted,
  125. "cannot write symbol section index table '" +
  126. Sec.Name + "' ");
  127. }
  128. Error BinarySectionWriter::visit(const SymbolTableSection &Sec) {
  129. return createStringError(errc::operation_not_permitted,
  130. "cannot write symbol table '" + Sec.Name +
  131. "' out to binary");
  132. }
  133. Error BinarySectionWriter::visit(const RelocationSection &Sec) {
  134. return createStringError(errc::operation_not_permitted,
  135. "cannot write relocation section '" + Sec.Name +
  136. "' out to binary");
  137. }
  138. Error BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
  139. return createStringError(errc::operation_not_permitted,
  140. "cannot write '" + Sec.Name + "' out to binary");
  141. }
  142. Error BinarySectionWriter::visit(const GroupSection &Sec) {
  143. return createStringError(errc::operation_not_permitted,
  144. "cannot write '" + Sec.Name + "' out to binary");
  145. }
  146. Error SectionWriter::visit(const Section &Sec) {
  147. if (Sec.Type != SHT_NOBITS)
  148. llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
  149. return Error::success();
  150. }
  151. static bool addressOverflows32bit(uint64_t Addr) {
  152. // Sign extended 32 bit addresses (e.g 0xFFFFFFFF80000000) are ok
  153. return Addr > UINT32_MAX && Addr + 0x80000000 > UINT32_MAX;
  154. }
  155. template <class T> static T checkedGetHex(StringRef S) {
  156. T Value;
  157. bool Fail = S.getAsInteger(16, Value);
  158. assert(!Fail);
  159. (void)Fail;
  160. return Value;
  161. }
  162. // Fills exactly Len bytes of buffer with hexadecimal characters
  163. // representing value 'X'
  164. template <class T, class Iterator>
  165. static Iterator toHexStr(T X, Iterator It, size_t Len) {
  166. // Fill range with '0'
  167. std::fill(It, It + Len, '0');
  168. for (long I = Len - 1; I >= 0; --I) {
  169. unsigned char Mod = static_cast<unsigned char>(X) & 15;
  170. *(It + I) = hexdigit(Mod, false);
  171. X >>= 4;
  172. }
  173. assert(X == 0);
  174. return It + Len;
  175. }
  176. uint8_t IHexRecord::getChecksum(StringRef S) {
  177. assert((S.size() & 1) == 0);
  178. uint8_t Checksum = 0;
  179. while (!S.empty()) {
  180. Checksum += checkedGetHex<uint8_t>(S.take_front(2));
  181. S = S.drop_front(2);
  182. }
  183. return -Checksum;
  184. }
  185. IHexLineData IHexRecord::getLine(uint8_t Type, uint16_t Addr,
  186. ArrayRef<uint8_t> Data) {
  187. IHexLineData Line(getLineLength(Data.size()));
  188. assert(Line.size());
  189. auto Iter = Line.begin();
  190. *Iter++ = ':';
  191. Iter = toHexStr(Data.size(), Iter, 2);
  192. Iter = toHexStr(Addr, Iter, 4);
  193. Iter = toHexStr(Type, Iter, 2);
  194. for (uint8_t X : Data)
  195. Iter = toHexStr(X, Iter, 2);
  196. StringRef S(Line.data() + 1, std::distance(Line.begin() + 1, Iter));
  197. Iter = toHexStr(getChecksum(S), Iter, 2);
  198. *Iter++ = '\r';
  199. *Iter++ = '\n';
  200. assert(Iter == Line.end());
  201. return Line;
  202. }
  203. static Error checkRecord(const IHexRecord &R) {
  204. switch (R.Type) {
  205. case IHexRecord::Data:
  206. if (R.HexData.size() == 0)
  207. return createStringError(
  208. errc::invalid_argument,
  209. "zero data length is not allowed for data records");
  210. break;
  211. case IHexRecord::EndOfFile:
  212. break;
  213. case IHexRecord::SegmentAddr:
  214. // 20-bit segment address. Data length must be 2 bytes
  215. // (4 bytes in hex)
  216. if (R.HexData.size() != 4)
  217. return createStringError(
  218. errc::invalid_argument,
  219. "segment address data should be 2 bytes in size");
  220. break;
  221. case IHexRecord::StartAddr80x86:
  222. case IHexRecord::StartAddr:
  223. if (R.HexData.size() != 8)
  224. return createStringError(errc::invalid_argument,
  225. "start address data should be 4 bytes in size");
  226. // According to Intel HEX specification '03' record
  227. // only specifies the code address within the 20-bit
  228. // segmented address space of the 8086/80186. This
  229. // means 12 high order bits should be zeroes.
  230. if (R.Type == IHexRecord::StartAddr80x86 &&
  231. R.HexData.take_front(3) != "000")
  232. return createStringError(errc::invalid_argument,
  233. "start address exceeds 20 bit for 80x86");
  234. break;
  235. case IHexRecord::ExtendedAddr:
  236. // 16-31 bits of linear base address
  237. if (R.HexData.size() != 4)
  238. return createStringError(
  239. errc::invalid_argument,
  240. "extended address data should be 2 bytes in size");
  241. break;
  242. default:
  243. // Unknown record type
  244. return createStringError(errc::invalid_argument, "unknown record type: %u",
  245. static_cast<unsigned>(R.Type));
  246. }
  247. return Error::success();
  248. }
  249. // Checks that IHEX line contains valid characters.
  250. // This allows converting hexadecimal data to integers
  251. // without extra verification.
  252. static Error checkChars(StringRef Line) {
  253. assert(!Line.empty());
  254. if (Line[0] != ':')
  255. return createStringError(errc::invalid_argument,
  256. "missing ':' in the beginning of line.");
  257. for (size_t Pos = 1; Pos < Line.size(); ++Pos)
  258. if (hexDigitValue(Line[Pos]) == -1U)
  259. return createStringError(errc::invalid_argument,
  260. "invalid character at position %zu.", Pos + 1);
  261. return Error::success();
  262. }
  263. Expected<IHexRecord> IHexRecord::parse(StringRef Line) {
  264. assert(!Line.empty());
  265. // ':' + Length + Address + Type + Checksum with empty data ':LLAAAATTCC'
  266. if (Line.size() < 11)
  267. return createStringError(errc::invalid_argument,
  268. "line is too short: %zu chars.", Line.size());
  269. if (Error E = checkChars(Line))
  270. return std::move(E);
  271. IHexRecord Rec;
  272. size_t DataLen = checkedGetHex<uint8_t>(Line.substr(1, 2));
  273. if (Line.size() != getLength(DataLen))
  274. return createStringError(errc::invalid_argument,
  275. "invalid line length %zu (should be %zu)",
  276. Line.size(), getLength(DataLen));
  277. Rec.Addr = checkedGetHex<uint16_t>(Line.substr(3, 4));
  278. Rec.Type = checkedGetHex<uint8_t>(Line.substr(7, 2));
  279. Rec.HexData = Line.substr(9, DataLen * 2);
  280. if (getChecksum(Line.drop_front(1)) != 0)
  281. return createStringError(errc::invalid_argument, "incorrect checksum.");
  282. if (Error E = checkRecord(Rec))
  283. return std::move(E);
  284. return Rec;
  285. }
  286. static uint64_t sectionPhysicalAddr(const SectionBase *Sec) {
  287. Segment *Seg = Sec->ParentSegment;
  288. if (Seg && Seg->Type != ELF::PT_LOAD)
  289. Seg = nullptr;
  290. return Seg ? Seg->PAddr + Sec->OriginalOffset - Seg->OriginalOffset
  291. : Sec->Addr;
  292. }
  293. void IHexSectionWriterBase::writeSection(const SectionBase *Sec,
  294. ArrayRef<uint8_t> Data) {
  295. assert(Data.size() == Sec->Size);
  296. const uint32_t ChunkSize = 16;
  297. uint32_t Addr = sectionPhysicalAddr(Sec) & 0xFFFFFFFFU;
  298. while (!Data.empty()) {
  299. uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
  300. if (Addr > SegmentAddr + BaseAddr + 0xFFFFU) {
  301. if (Addr > 0xFFFFFU) {
  302. // Write extended address record, zeroing segment address
  303. // if needed.
  304. if (SegmentAddr != 0)
  305. SegmentAddr = writeSegmentAddr(0U);
  306. BaseAddr = writeBaseAddr(Addr);
  307. } else {
  308. // We can still remain 16-bit
  309. SegmentAddr = writeSegmentAddr(Addr);
  310. }
  311. }
  312. uint64_t SegOffset = Addr - BaseAddr - SegmentAddr;
  313. assert(SegOffset <= 0xFFFFU);
  314. DataSize = std::min(DataSize, 0x10000U - SegOffset);
  315. writeData(0, SegOffset, Data.take_front(DataSize));
  316. Addr += DataSize;
  317. Data = Data.drop_front(DataSize);
  318. }
  319. }
  320. uint64_t IHexSectionWriterBase::writeSegmentAddr(uint64_t Addr) {
  321. assert(Addr <= 0xFFFFFU);
  322. uint8_t Data[] = {static_cast<uint8_t>((Addr & 0xF0000U) >> 12), 0};
  323. writeData(2, 0, Data);
  324. return Addr & 0xF0000U;
  325. }
  326. uint64_t IHexSectionWriterBase::writeBaseAddr(uint64_t Addr) {
  327. assert(Addr <= 0xFFFFFFFFU);
  328. uint64_t Base = Addr & 0xFFFF0000U;
  329. uint8_t Data[] = {static_cast<uint8_t>(Base >> 24),
  330. static_cast<uint8_t>((Base >> 16) & 0xFF)};
  331. writeData(4, 0, Data);
  332. return Base;
  333. }
  334. void IHexSectionWriterBase::writeData(uint8_t, uint16_t,
  335. ArrayRef<uint8_t> Data) {
  336. Offset += IHexRecord::getLineLength(Data.size());
  337. }
  338. Error IHexSectionWriterBase::visit(const Section &Sec) {
  339. writeSection(&Sec, Sec.Contents);
  340. return Error::success();
  341. }
  342. Error IHexSectionWriterBase::visit(const OwnedDataSection &Sec) {
  343. writeSection(&Sec, Sec.Data);
  344. return Error::success();
  345. }
  346. Error IHexSectionWriterBase::visit(const StringTableSection &Sec) {
  347. // Check that sizer has already done its work
  348. assert(Sec.Size == Sec.StrTabBuilder.getSize());
  349. // We are free to pass an invalid pointer to writeSection as long
  350. // as we don't actually write any data. The real writer class has
  351. // to override this method .
  352. writeSection(&Sec, {nullptr, static_cast<size_t>(Sec.Size)});
  353. return Error::success();
  354. }
  355. Error IHexSectionWriterBase::visit(const DynamicRelocationSection &Sec) {
  356. writeSection(&Sec, Sec.Contents);
  357. return Error::success();
  358. }
  359. void IHexSectionWriter::writeData(uint8_t Type, uint16_t Addr,
  360. ArrayRef<uint8_t> Data) {
  361. IHexLineData HexData = IHexRecord::getLine(Type, Addr, Data);
  362. memcpy(Out.getBufferStart() + Offset, HexData.data(), HexData.size());
  363. Offset += HexData.size();
  364. }
  365. Error IHexSectionWriter::visit(const StringTableSection &Sec) {
  366. assert(Sec.Size == Sec.StrTabBuilder.getSize());
  367. std::vector<uint8_t> Data(Sec.Size);
  368. Sec.StrTabBuilder.write(Data.data());
  369. writeSection(&Sec, Data);
  370. return Error::success();
  371. }
  372. Error Section::accept(SectionVisitor &Visitor) const {
  373. return Visitor.visit(*this);
  374. }
  375. Error Section::accept(MutableSectionVisitor &Visitor) {
  376. return Visitor.visit(*this);
  377. }
  378. Error SectionWriter::visit(const OwnedDataSection &Sec) {
  379. llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
  380. return Error::success();
  381. }
  382. template <class ELFT>
  383. Error ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
  384. ArrayRef<uint8_t> Compressed =
  385. Sec.OriginalData.slice(sizeof(Elf_Chdr_Impl<ELFT>));
  386. SmallVector<uint8_t, 128> Decompressed;
  387. DebugCompressionType Type;
  388. switch (Sec.ChType) {
  389. case ELFCOMPRESS_ZLIB:
  390. Type = DebugCompressionType::Zlib;
  391. break;
  392. case ELFCOMPRESS_ZSTD:
  393. Type = DebugCompressionType::Zstd;
  394. break;
  395. default:
  396. return createStringError(errc::invalid_argument,
  397. "--decompress-debug-sections: ch_type (" +
  398. Twine(Sec.ChType) + ") of section '" +
  399. Sec.Name + "' is unsupported");
  400. }
  401. if (auto *Reason =
  402. compression::getReasonIfUnsupported(compression::formatFor(Type)))
  403. return createStringError(errc::invalid_argument,
  404. "failed to decompress section '" + Sec.Name +
  405. "': " + Reason);
  406. if (Error E = compression::decompress(Type, Compressed, Decompressed,
  407. static_cast<size_t>(Sec.Size)))
  408. return createStringError(errc::invalid_argument,
  409. "failed to decompress section '" + Sec.Name +
  410. "': " + toString(std::move(E)));
  411. uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
  412. std::copy(Decompressed.begin(), Decompressed.end(), Buf);
  413. return Error::success();
  414. }
  415. Error BinarySectionWriter::visit(const DecompressedSection &Sec) {
  416. return createStringError(errc::operation_not_permitted,
  417. "cannot write compressed section '" + Sec.Name +
  418. "' ");
  419. }
  420. Error DecompressedSection::accept(SectionVisitor &Visitor) const {
  421. return Visitor.visit(*this);
  422. }
  423. Error DecompressedSection::accept(MutableSectionVisitor &Visitor) {
  424. return Visitor.visit(*this);
  425. }
  426. Error OwnedDataSection::accept(SectionVisitor &Visitor) const {
  427. return Visitor.visit(*this);
  428. }
  429. Error OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
  430. return Visitor.visit(*this);
  431. }
  432. void OwnedDataSection::appendHexData(StringRef HexData) {
  433. assert((HexData.size() & 1) == 0);
  434. while (!HexData.empty()) {
  435. Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2)));
  436. HexData = HexData.drop_front(2);
  437. }
  438. Size = Data.size();
  439. }
  440. Error BinarySectionWriter::visit(const CompressedSection &Sec) {
  441. return createStringError(errc::operation_not_permitted,
  442. "cannot write compressed section '" + Sec.Name +
  443. "' ");
  444. }
  445. template <class ELFT>
  446. Error ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
  447. uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
  448. Elf_Chdr_Impl<ELFT> Chdr = {};
  449. switch (Sec.CompressionType) {
  450. case DebugCompressionType::None:
  451. std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
  452. return Error::success();
  453. case DebugCompressionType::Zlib:
  454. Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
  455. break;
  456. case DebugCompressionType::Zstd:
  457. Chdr.ch_type = ELF::ELFCOMPRESS_ZSTD;
  458. break;
  459. }
  460. Chdr.ch_size = Sec.DecompressedSize;
  461. Chdr.ch_addralign = Sec.DecompressedAlign;
  462. memcpy(Buf, &Chdr, sizeof(Chdr));
  463. Buf += sizeof(Chdr);
  464. std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
  465. return Error::success();
  466. }
  467. CompressedSection::CompressedSection(const SectionBase &Sec,
  468. DebugCompressionType CompressionType,
  469. bool Is64Bits)
  470. : SectionBase(Sec), CompressionType(CompressionType),
  471. DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
  472. compression::compress(compression::Params(CompressionType), OriginalData,
  473. CompressedData);
  474. Flags |= ELF::SHF_COMPRESSED;
  475. size_t ChdrSize = Is64Bits ? sizeof(object::Elf_Chdr_Impl<object::ELF64LE>)
  476. : sizeof(object::Elf_Chdr_Impl<object::ELF32LE>);
  477. Size = ChdrSize + CompressedData.size();
  478. Align = 8;
  479. }
  480. CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
  481. uint32_t ChType, uint64_t DecompressedSize,
  482. uint64_t DecompressedAlign)
  483. : ChType(ChType), CompressionType(DebugCompressionType::None),
  484. DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
  485. OriginalData = CompressedData;
  486. }
  487. Error CompressedSection::accept(SectionVisitor &Visitor) const {
  488. return Visitor.visit(*this);
  489. }
  490. Error CompressedSection::accept(MutableSectionVisitor &Visitor) {
  491. return Visitor.visit(*this);
  492. }
  493. void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
  494. uint32_t StringTableSection::findIndex(StringRef Name) const {
  495. return StrTabBuilder.getOffset(Name);
  496. }
  497. void StringTableSection::prepareForLayout() {
  498. StrTabBuilder.finalize();
  499. Size = StrTabBuilder.getSize();
  500. }
  501. Error SectionWriter::visit(const StringTableSection &Sec) {
  502. Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) +
  503. Sec.Offset);
  504. return Error::success();
  505. }
  506. Error StringTableSection::accept(SectionVisitor &Visitor) const {
  507. return Visitor.visit(*this);
  508. }
  509. Error StringTableSection::accept(MutableSectionVisitor &Visitor) {
  510. return Visitor.visit(*this);
  511. }
  512. template <class ELFT>
  513. Error ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
  514. uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
  515. llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
  516. return Error::success();
  517. }
  518. Error SectionIndexSection::initialize(SectionTableRef SecTable) {
  519. Size = 0;
  520. Expected<SymbolTableSection *> Sec =
  521. SecTable.getSectionOfType<SymbolTableSection>(
  522. Link,
  523. "Link field value " + Twine(Link) + " in section " + Name +
  524. " is invalid",
  525. "Link field value " + Twine(Link) + " in section " + Name +
  526. " is not a symbol table");
  527. if (!Sec)
  528. return Sec.takeError();
  529. setSymTab(*Sec);
  530. Symbols->setShndxTable(this);
  531. return Error::success();
  532. }
  533. void SectionIndexSection::finalize() { Link = Symbols->Index; }
  534. Error SectionIndexSection::accept(SectionVisitor &Visitor) const {
  535. return Visitor.visit(*this);
  536. }
  537. Error SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
  538. return Visitor.visit(*this);
  539. }
  540. static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
  541. switch (Index) {
  542. case SHN_ABS:
  543. case SHN_COMMON:
  544. return true;
  545. }
  546. if (Machine == EM_AMDGPU) {
  547. return Index == SHN_AMDGPU_LDS;
  548. }
  549. if (Machine == EM_MIPS) {
  550. switch (Index) {
  551. case SHN_MIPS_ACOMMON:
  552. case SHN_MIPS_SCOMMON:
  553. case SHN_MIPS_SUNDEFINED:
  554. return true;
  555. }
  556. }
  557. if (Machine == EM_HEXAGON) {
  558. switch (Index) {
  559. case SHN_HEXAGON_SCOMMON:
  560. case SHN_HEXAGON_SCOMMON_1:
  561. case SHN_HEXAGON_SCOMMON_2:
  562. case SHN_HEXAGON_SCOMMON_4:
  563. case SHN_HEXAGON_SCOMMON_8:
  564. return true;
  565. }
  566. }
  567. return false;
  568. }
  569. // Large indexes force us to clarify exactly what this function should do. This
  570. // function should return the value that will appear in st_shndx when written
  571. // out.
  572. uint16_t Symbol::getShndx() const {
  573. if (DefinedIn != nullptr) {
  574. if (DefinedIn->Index >= SHN_LORESERVE)
  575. return SHN_XINDEX;
  576. return DefinedIn->Index;
  577. }
  578. if (ShndxType == SYMBOL_SIMPLE_INDEX) {
  579. // This means that we don't have a defined section but we do need to
  580. // output a legitimate section index.
  581. return SHN_UNDEF;
  582. }
  583. assert(ShndxType == SYMBOL_ABS || ShndxType == SYMBOL_COMMON ||
  584. (ShndxType >= SYMBOL_LOPROC && ShndxType <= SYMBOL_HIPROC) ||
  585. (ShndxType >= SYMBOL_LOOS && ShndxType <= SYMBOL_HIOS));
  586. return static_cast<uint16_t>(ShndxType);
  587. }
  588. bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
  589. void SymbolTableSection::assignIndices() {
  590. uint32_t Index = 0;
  591. for (auto &Sym : Symbols)
  592. Sym->Index = Index++;
  593. }
  594. void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
  595. SectionBase *DefinedIn, uint64_t Value,
  596. uint8_t Visibility, uint16_t Shndx,
  597. uint64_t SymbolSize) {
  598. Symbol Sym;
  599. Sym.Name = Name.str();
  600. Sym.Binding = Bind;
  601. Sym.Type = Type;
  602. Sym.DefinedIn = DefinedIn;
  603. if (DefinedIn != nullptr)
  604. DefinedIn->HasSymbol = true;
  605. if (DefinedIn == nullptr) {
  606. if (Shndx >= SHN_LORESERVE)
  607. Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
  608. else
  609. Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
  610. }
  611. Sym.Value = Value;
  612. Sym.Visibility = Visibility;
  613. Sym.Size = SymbolSize;
  614. Sym.Index = Symbols.size();
  615. Symbols.emplace_back(std::make_unique<Symbol>(Sym));
  616. Size += this->EntrySize;
  617. }
  618. Error SymbolTableSection::removeSectionReferences(
  619. bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
  620. if (ToRemove(SectionIndexTable))
  621. SectionIndexTable = nullptr;
  622. if (ToRemove(SymbolNames)) {
  623. if (!AllowBrokenLinks)
  624. return createStringError(
  625. llvm::errc::invalid_argument,
  626. "string table '%s' cannot be removed because it is "
  627. "referenced by the symbol table '%s'",
  628. SymbolNames->Name.data(), this->Name.data());
  629. SymbolNames = nullptr;
  630. }
  631. return removeSymbols(
  632. [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
  633. }
  634. void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
  635. for (SymPtr &Sym : llvm::drop_begin(Symbols))
  636. Callable(*Sym);
  637. std::stable_partition(
  638. std::begin(Symbols), std::end(Symbols),
  639. [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
  640. assignIndices();
  641. }
  642. Error SymbolTableSection::removeSymbols(
  643. function_ref<bool(const Symbol &)> ToRemove) {
  644. Symbols.erase(
  645. std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
  646. [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
  647. std::end(Symbols));
  648. Size = Symbols.size() * EntrySize;
  649. assignIndices();
  650. return Error::success();
  651. }
  652. void SymbolTableSection::replaceSectionReferences(
  653. const DenseMap<SectionBase *, SectionBase *> &FromTo) {
  654. for (std::unique_ptr<Symbol> &Sym : Symbols)
  655. if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
  656. Sym->DefinedIn = To;
  657. }
  658. Error SymbolTableSection::initialize(SectionTableRef SecTable) {
  659. Size = 0;
  660. Expected<StringTableSection *> Sec =
  661. SecTable.getSectionOfType<StringTableSection>(
  662. Link,
  663. "Symbol table has link index of " + Twine(Link) +
  664. " which is not a valid index",
  665. "Symbol table has link index of " + Twine(Link) +
  666. " which is not a string table");
  667. if (!Sec)
  668. return Sec.takeError();
  669. setStrTab(*Sec);
  670. return Error::success();
  671. }
  672. void SymbolTableSection::finalize() {
  673. uint32_t MaxLocalIndex = 0;
  674. for (std::unique_ptr<Symbol> &Sym : Symbols) {
  675. Sym->NameIndex =
  676. SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
  677. if (Sym->Binding == STB_LOCAL)
  678. MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
  679. }
  680. // Now we need to set the Link and Info fields.
  681. Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
  682. Info = MaxLocalIndex + 1;
  683. }
  684. void SymbolTableSection::prepareForLayout() {
  685. // Reserve proper amount of space in section index table, so we can
  686. // layout sections correctly. We will fill the table with correct
  687. // indexes later in fillShdnxTable.
  688. if (SectionIndexTable)
  689. SectionIndexTable->reserve(Symbols.size());
  690. // Add all of our strings to SymbolNames so that SymbolNames has the right
  691. // size before layout is decided.
  692. // If the symbol names section has been removed, don't try to add strings to
  693. // the table.
  694. if (SymbolNames != nullptr)
  695. for (std::unique_ptr<Symbol> &Sym : Symbols)
  696. SymbolNames->addString(Sym->Name);
  697. }
  698. void SymbolTableSection::fillShndxTable() {
  699. if (SectionIndexTable == nullptr)
  700. return;
  701. // Fill section index table with real section indexes. This function must
  702. // be called after assignOffsets.
  703. for (const std::unique_ptr<Symbol> &Sym : Symbols) {
  704. if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
  705. SectionIndexTable->addIndex(Sym->DefinedIn->Index);
  706. else
  707. SectionIndexTable->addIndex(SHN_UNDEF);
  708. }
  709. }
  710. Expected<const Symbol *>
  711. SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
  712. if (Symbols.size() <= Index)
  713. return createStringError(errc::invalid_argument,
  714. "invalid symbol index: " + Twine(Index));
  715. return Symbols[Index].get();
  716. }
  717. Expected<Symbol *> SymbolTableSection::getSymbolByIndex(uint32_t Index) {
  718. Expected<const Symbol *> Sym =
  719. static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index);
  720. if (!Sym)
  721. return Sym.takeError();
  722. return const_cast<Symbol *>(*Sym);
  723. }
  724. template <class ELFT>
  725. Error ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
  726. Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
  727. // Loop though symbols setting each entry of the symbol table.
  728. for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
  729. Sym->st_name = Symbol->NameIndex;
  730. Sym->st_value = Symbol->Value;
  731. Sym->st_size = Symbol->Size;
  732. Sym->st_other = Symbol->Visibility;
  733. Sym->setBinding(Symbol->Binding);
  734. Sym->setType(Symbol->Type);
  735. Sym->st_shndx = Symbol->getShndx();
  736. ++Sym;
  737. }
  738. return Error::success();
  739. }
  740. Error SymbolTableSection::accept(SectionVisitor &Visitor) const {
  741. return Visitor.visit(*this);
  742. }
  743. Error SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
  744. return Visitor.visit(*this);
  745. }
  746. StringRef RelocationSectionBase::getNamePrefix() const {
  747. switch (Type) {
  748. case SHT_REL:
  749. return ".rel";
  750. case SHT_RELA:
  751. return ".rela";
  752. default:
  753. llvm_unreachable("not a relocation section");
  754. }
  755. }
  756. Error RelocationSection::removeSectionReferences(
  757. bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
  758. if (ToRemove(Symbols)) {
  759. if (!AllowBrokenLinks)
  760. return createStringError(
  761. llvm::errc::invalid_argument,
  762. "symbol table '%s' cannot be removed because it is "
  763. "referenced by the relocation section '%s'",
  764. Symbols->Name.data(), this->Name.data());
  765. Symbols = nullptr;
  766. }
  767. for (const Relocation &R : Relocations) {
  768. if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn ||
  769. !ToRemove(R.RelocSymbol->DefinedIn))
  770. continue;
  771. return createStringError(llvm::errc::invalid_argument,
  772. "section '%s' cannot be removed: (%s+0x%" PRIx64
  773. ") has relocation against symbol '%s'",
  774. R.RelocSymbol->DefinedIn->Name.data(),
  775. SecToApplyRel->Name.data(), R.Offset,
  776. R.RelocSymbol->Name.c_str());
  777. }
  778. return Error::success();
  779. }
  780. template <class SymTabType>
  781. Error RelocSectionWithSymtabBase<SymTabType>::initialize(
  782. SectionTableRef SecTable) {
  783. if (Link != SHN_UNDEF) {
  784. Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>(
  785. Link,
  786. "Link field value " + Twine(Link) + " in section " + Name +
  787. " is invalid",
  788. "Link field value " + Twine(Link) + " in section " + Name +
  789. " is not a symbol table");
  790. if (!Sec)
  791. return Sec.takeError();
  792. setSymTab(*Sec);
  793. }
  794. if (Info != SHN_UNDEF) {
  795. Expected<SectionBase *> Sec =
  796. SecTable.getSection(Info, "Info field value " + Twine(Info) +
  797. " in section " + Name + " is invalid");
  798. if (!Sec)
  799. return Sec.takeError();
  800. setSection(*Sec);
  801. } else
  802. setSection(nullptr);
  803. return Error::success();
  804. }
  805. template <class SymTabType>
  806. void RelocSectionWithSymtabBase<SymTabType>::finalize() {
  807. this->Link = Symbols ? Symbols->Index : 0;
  808. if (SecToApplyRel != nullptr)
  809. this->Info = SecToApplyRel->Index;
  810. }
  811. template <class ELFT>
  812. static void setAddend(Elf_Rel_Impl<ELFT, false> &, uint64_t) {}
  813. template <class ELFT>
  814. static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
  815. Rela.r_addend = Addend;
  816. }
  817. template <class RelRange, class T>
  818. static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) {
  819. for (const auto &Reloc : Relocations) {
  820. Buf->r_offset = Reloc.Offset;
  821. setAddend(*Buf, Reloc.Addend);
  822. Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0,
  823. Reloc.Type, IsMips64EL);
  824. ++Buf;
  825. }
  826. }
  827. template <class ELFT>
  828. Error ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
  829. uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
  830. if (Sec.Type == SHT_REL)
  831. writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf),
  832. Sec.getObject().IsMips64EL);
  833. else
  834. writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf),
  835. Sec.getObject().IsMips64EL);
  836. return Error::success();
  837. }
  838. Error RelocationSection::accept(SectionVisitor &Visitor) const {
  839. return Visitor.visit(*this);
  840. }
  841. Error RelocationSection::accept(MutableSectionVisitor &Visitor) {
  842. return Visitor.visit(*this);
  843. }
  844. Error RelocationSection::removeSymbols(
  845. function_ref<bool(const Symbol &)> ToRemove) {
  846. for (const Relocation &Reloc : Relocations)
  847. if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol))
  848. return createStringError(
  849. llvm::errc::invalid_argument,
  850. "not stripping symbol '%s' because it is named in a relocation",
  851. Reloc.RelocSymbol->Name.data());
  852. return Error::success();
  853. }
  854. void RelocationSection::markSymbols() {
  855. for (const Relocation &Reloc : Relocations)
  856. if (Reloc.RelocSymbol)
  857. Reloc.RelocSymbol->Referenced = true;
  858. }
  859. void RelocationSection::replaceSectionReferences(
  860. const DenseMap<SectionBase *, SectionBase *> &FromTo) {
  861. // Update the target section if it was replaced.
  862. if (SectionBase *To = FromTo.lookup(SecToApplyRel))
  863. SecToApplyRel = To;
  864. }
  865. Error SectionWriter::visit(const DynamicRelocationSection &Sec) {
  866. llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
  867. return Error::success();
  868. }
  869. Error DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
  870. return Visitor.visit(*this);
  871. }
  872. Error DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
  873. return Visitor.visit(*this);
  874. }
  875. Error DynamicRelocationSection::removeSectionReferences(
  876. bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
  877. if (ToRemove(Symbols)) {
  878. if (!AllowBrokenLinks)
  879. return createStringError(
  880. llvm::errc::invalid_argument,
  881. "symbol table '%s' cannot be removed because it is "
  882. "referenced by the relocation section '%s'",
  883. Symbols->Name.data(), this->Name.data());
  884. Symbols = nullptr;
  885. }
  886. // SecToApplyRel contains a section referenced by sh_info field. It keeps
  887. // a section to which the relocation section applies. When we remove any
  888. // sections we also remove their relocation sections. Since we do that much
  889. // earlier, this assert should never be triggered.
  890. assert(!SecToApplyRel || !ToRemove(SecToApplyRel));
  891. return Error::success();
  892. }
  893. Error Section::removeSectionReferences(
  894. bool AllowBrokenDependency,
  895. function_ref<bool(const SectionBase *)> ToRemove) {
  896. if (ToRemove(LinkSection)) {
  897. if (!AllowBrokenDependency)
  898. return createStringError(llvm::errc::invalid_argument,
  899. "section '%s' cannot be removed because it is "
  900. "referenced by the section '%s'",
  901. LinkSection->Name.data(), this->Name.data());
  902. LinkSection = nullptr;
  903. }
  904. return Error::success();
  905. }
  906. void GroupSection::finalize() {
  907. this->Info = Sym ? Sym->Index : 0;
  908. this->Link = SymTab ? SymTab->Index : 0;
  909. // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global
  910. // status is not part of the equation. If Sym is localized, the intention is
  911. // likely to make the group fully localized. Drop GRP_COMDAT to suppress
  912. // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc
  913. if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL)
  914. this->FlagWord &= ~GRP_COMDAT;
  915. }
  916. Error GroupSection::removeSectionReferences(
  917. bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
  918. if (ToRemove(SymTab)) {
  919. if (!AllowBrokenLinks)
  920. return createStringError(
  921. llvm::errc::invalid_argument,
  922. "section '.symtab' cannot be removed because it is "
  923. "referenced by the group section '%s'",
  924. this->Name.data());
  925. SymTab = nullptr;
  926. Sym = nullptr;
  927. }
  928. llvm::erase_if(GroupMembers, ToRemove);
  929. return Error::success();
  930. }
  931. Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
  932. if (ToRemove(*Sym))
  933. return createStringError(llvm::errc::invalid_argument,
  934. "symbol '%s' cannot be removed because it is "
  935. "referenced by the section '%s[%d]'",
  936. Sym->Name.data(), this->Name.data(), this->Index);
  937. return Error::success();
  938. }
  939. void GroupSection::markSymbols() {
  940. if (Sym)
  941. Sym->Referenced = true;
  942. }
  943. void GroupSection::replaceSectionReferences(
  944. const DenseMap<SectionBase *, SectionBase *> &FromTo) {
  945. for (SectionBase *&Sec : GroupMembers)
  946. if (SectionBase *To = FromTo.lookup(Sec))
  947. Sec = To;
  948. }
  949. void GroupSection::onRemove() {
  950. // As the header section of the group is removed, drop the Group flag in its
  951. // former members.
  952. for (SectionBase *Sec : GroupMembers)
  953. Sec->Flags &= ~SHF_GROUP;
  954. }
  955. Error Section::initialize(SectionTableRef SecTable) {
  956. if (Link == ELF::SHN_UNDEF)
  957. return Error::success();
  958. Expected<SectionBase *> Sec =
  959. SecTable.getSection(Link, "Link field value " + Twine(Link) +
  960. " in section " + Name + " is invalid");
  961. if (!Sec)
  962. return Sec.takeError();
  963. LinkSection = *Sec;
  964. if (LinkSection->Type == ELF::SHT_SYMTAB)
  965. LinkSection = nullptr;
  966. return Error::success();
  967. }
  968. void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
  969. void GnuDebugLinkSection::init(StringRef File) {
  970. FileName = sys::path::filename(File);
  971. // The format for the .gnu_debuglink starts with the file name and is
  972. // followed by a null terminator and then the CRC32 of the file. The CRC32
  973. // should be 4 byte aligned. So we add the FileName size, a 1 for the null
  974. // byte, and then finally push the size to alignment and add 4.
  975. Size = alignTo(FileName.size() + 1, 4) + 4;
  976. // The CRC32 will only be aligned if we align the whole section.
  977. Align = 4;
  978. Type = OriginalType = ELF::SHT_PROGBITS;
  979. Name = ".gnu_debuglink";
  980. // For sections not found in segments, OriginalOffset is only used to
  981. // establish the order that sections should go in. By using the maximum
  982. // possible offset we cause this section to wind up at the end.
  983. OriginalOffset = std::numeric_limits<uint64_t>::max();
  984. }
  985. GnuDebugLinkSection::GnuDebugLinkSection(StringRef File,
  986. uint32_t PrecomputedCRC)
  987. : FileName(File), CRC32(PrecomputedCRC) {
  988. init(File);
  989. }
  990. template <class ELFT>
  991. Error ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
  992. unsigned char *Buf =
  993. reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
  994. Elf_Word *CRC =
  995. reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
  996. *CRC = Sec.CRC32;
  997. llvm::copy(Sec.FileName, Buf);
  998. return Error::success();
  999. }
  1000. Error GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
  1001. return Visitor.visit(*this);
  1002. }
  1003. Error GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
  1004. return Visitor.visit(*this);
  1005. }
  1006. template <class ELFT>
  1007. Error ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
  1008. ELF::Elf32_Word *Buf =
  1009. reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
  1010. support::endian::write32<ELFT::TargetEndianness>(Buf++, Sec.FlagWord);
  1011. for (SectionBase *S : Sec.GroupMembers)
  1012. support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
  1013. return Error::success();
  1014. }
  1015. Error GroupSection::accept(SectionVisitor &Visitor) const {
  1016. return Visitor.visit(*this);
  1017. }
  1018. Error GroupSection::accept(MutableSectionVisitor &Visitor) {
  1019. return Visitor.visit(*this);
  1020. }
  1021. // Returns true IFF a section is wholly inside the range of a segment
  1022. static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) {
  1023. // If a section is empty it should be treated like it has a size of 1. This is
  1024. // to clarify the case when an empty section lies on a boundary between two
  1025. // segments and ensures that the section "belongs" to the second segment and
  1026. // not the first.
  1027. uint64_t SecSize = Sec.Size ? Sec.Size : 1;
  1028. // Ignore just added sections.
  1029. if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max())
  1030. return false;
  1031. if (Sec.Type == SHT_NOBITS) {
  1032. if (!(Sec.Flags & SHF_ALLOC))
  1033. return false;
  1034. bool SectionIsTLS = Sec.Flags & SHF_TLS;
  1035. bool SegmentIsTLS = Seg.Type == PT_TLS;
  1036. if (SectionIsTLS != SegmentIsTLS)
  1037. return false;
  1038. return Seg.VAddr <= Sec.Addr &&
  1039. Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize;
  1040. }
  1041. return Seg.Offset <= Sec.OriginalOffset &&
  1042. Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize;
  1043. }
  1044. // Returns true IFF a segment's original offset is inside of another segment's
  1045. // range.
  1046. static bool segmentOverlapsSegment(const Segment &Child,
  1047. const Segment &Parent) {
  1048. return Parent.OriginalOffset <= Child.OriginalOffset &&
  1049. Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
  1050. }
  1051. static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
  1052. // Any segment without a parent segment should come before a segment
  1053. // that has a parent segment.
  1054. if (A->OriginalOffset < B->OriginalOffset)
  1055. return true;
  1056. if (A->OriginalOffset > B->OriginalOffset)
  1057. return false;
  1058. return A->Index < B->Index;
  1059. }
  1060. void BasicELFBuilder::initFileHeader() {
  1061. Obj->Flags = 0x0;
  1062. Obj->Type = ET_REL;
  1063. Obj->OSABI = ELFOSABI_NONE;
  1064. Obj->ABIVersion = 0;
  1065. Obj->Entry = 0x0;
  1066. Obj->Machine = EM_NONE;
  1067. Obj->Version = 1;
  1068. }
  1069. void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
  1070. StringTableSection *BasicELFBuilder::addStrTab() {
  1071. auto &StrTab = Obj->addSection<StringTableSection>();
  1072. StrTab.Name = ".strtab";
  1073. Obj->SectionNames = &StrTab;
  1074. return &StrTab;
  1075. }
  1076. SymbolTableSection *BasicELFBuilder::addSymTab(StringTableSection *StrTab) {
  1077. auto &SymTab = Obj->addSection<SymbolTableSection>();
  1078. SymTab.Name = ".symtab";
  1079. SymTab.Link = StrTab->Index;
  1080. // The symbol table always needs a null symbol
  1081. SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
  1082. Obj->SymbolTable = &SymTab;
  1083. return &SymTab;
  1084. }
  1085. Error BasicELFBuilder::initSections() {
  1086. for (SectionBase &Sec : Obj->sections())
  1087. if (Error Err = Sec.initialize(Obj->sections()))
  1088. return Err;
  1089. return Error::success();
  1090. }
  1091. void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
  1092. auto Data = ArrayRef<uint8_t>(
  1093. reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
  1094. MemBuf->getBufferSize());
  1095. auto &DataSection = Obj->addSection<Section>(Data);
  1096. DataSection.Name = ".data";
  1097. DataSection.Type = ELF::SHT_PROGBITS;
  1098. DataSection.Size = Data.size();
  1099. DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  1100. std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
  1101. std::replace_if(
  1102. std::begin(SanitizedFilename), std::end(SanitizedFilename),
  1103. [](char C) { return !isAlnum(C); }, '_');
  1104. Twine Prefix = Twine("_binary_") + SanitizedFilename;
  1105. SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
  1106. /*Value=*/0, NewSymbolVisibility, 0, 0);
  1107. SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
  1108. /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
  1109. SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
  1110. /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
  1111. 0);
  1112. }
  1113. Expected<std::unique_ptr<Object>> BinaryELFBuilder::build() {
  1114. initFileHeader();
  1115. initHeaderSegment();
  1116. SymbolTableSection *SymTab = addSymTab(addStrTab());
  1117. if (Error Err = initSections())
  1118. return std::move(Err);
  1119. addData(SymTab);
  1120. return std::move(Obj);
  1121. }
  1122. // Adds sections from IHEX data file. Data should have been
  1123. // fully validated by this time.
  1124. void IHexELFBuilder::addDataSections() {
  1125. OwnedDataSection *Section = nullptr;
  1126. uint64_t SegmentAddr = 0, BaseAddr = 0;
  1127. uint32_t SecNo = 1;
  1128. for (const IHexRecord &R : Records) {
  1129. uint64_t RecAddr;
  1130. switch (R.Type) {
  1131. case IHexRecord::Data:
  1132. // Ignore empty data records
  1133. if (R.HexData.empty())
  1134. continue;
  1135. RecAddr = R.Addr + SegmentAddr + BaseAddr;
  1136. if (!Section || Section->Addr + Section->Size != RecAddr) {
  1137. // OriginalOffset field is only used to sort sections before layout, so
  1138. // instead of keeping track of real offsets in IHEX file, and as
  1139. // layoutSections() and layoutSectionsForOnlyKeepDebug() use
  1140. // llvm::stable_sort(), we can just set it to a constant (zero).
  1141. Section = &Obj->addSection<OwnedDataSection>(
  1142. ".sec" + std::to_string(SecNo), RecAddr,
  1143. ELF::SHF_ALLOC | ELF::SHF_WRITE, 0);
  1144. SecNo++;
  1145. }
  1146. Section->appendHexData(R.HexData);
  1147. break;
  1148. case IHexRecord::EndOfFile:
  1149. break;
  1150. case IHexRecord::SegmentAddr:
  1151. // 20-bit segment address.
  1152. SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
  1153. break;
  1154. case IHexRecord::StartAddr80x86:
  1155. case IHexRecord::StartAddr:
  1156. Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
  1157. assert(Obj->Entry <= 0xFFFFFU);
  1158. break;
  1159. case IHexRecord::ExtendedAddr:
  1160. // 16-31 bits of linear base address
  1161. BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
  1162. break;
  1163. default:
  1164. llvm_unreachable("unknown record type");
  1165. }
  1166. }
  1167. }
  1168. Expected<std::unique_ptr<Object>> IHexELFBuilder::build() {
  1169. initFileHeader();
  1170. initHeaderSegment();
  1171. StringTableSection *StrTab = addStrTab();
  1172. addSymTab(StrTab);
  1173. if (Error Err = initSections())
  1174. return std::move(Err);
  1175. addDataSections();
  1176. return std::move(Obj);
  1177. }
  1178. template <class ELFT>
  1179. ELFBuilder<ELFT>::ELFBuilder(const ELFObjectFile<ELFT> &ElfObj, Object &Obj,
  1180. std::optional<StringRef> ExtractPartition)
  1181. : ElfFile(ElfObj.getELFFile()), Obj(Obj),
  1182. ExtractPartition(ExtractPartition) {
  1183. Obj.IsMips64EL = ElfFile.isMips64EL();
  1184. }
  1185. template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
  1186. for (Segment &Parent : Obj.segments()) {
  1187. // Every segment will overlap with itself but we don't want a segment to
  1188. // be its own parent so we avoid that situation.
  1189. if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
  1190. // We want a canonical "most parental" segment but this requires
  1191. // inspecting the ParentSegment.
  1192. if (compareSegmentsByOffset(&Parent, &Child))
  1193. if (Child.ParentSegment == nullptr ||
  1194. compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
  1195. Child.ParentSegment = &Parent;
  1196. }
  1197. }
  1198. }
  1199. }
  1200. template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
  1201. if (!ExtractPartition)
  1202. return Error::success();
  1203. for (const SectionBase &Sec : Obj.sections()) {
  1204. if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
  1205. EhdrOffset = Sec.Offset;
  1206. return Error::success();
  1207. }
  1208. }
  1209. return createStringError(errc::invalid_argument,
  1210. "could not find partition named '" +
  1211. *ExtractPartition + "'");
  1212. }
  1213. template <class ELFT>
  1214. Error ELFBuilder<ELFT>::readProgramHeaders(const ELFFile<ELFT> &HeadersFile) {
  1215. uint32_t Index = 0;
  1216. Expected<typename ELFFile<ELFT>::Elf_Phdr_Range> Headers =
  1217. HeadersFile.program_headers();
  1218. if (!Headers)
  1219. return Headers.takeError();
  1220. for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
  1221. if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
  1222. return createStringError(
  1223. errc::invalid_argument,
  1224. "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
  1225. " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
  1226. " goes past the end of the file");
  1227. ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
  1228. (size_t)Phdr.p_filesz};
  1229. Segment &Seg = Obj.addSegment(Data);
  1230. Seg.Type = Phdr.p_type;
  1231. Seg.Flags = Phdr.p_flags;
  1232. Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
  1233. Seg.Offset = Phdr.p_offset + EhdrOffset;
  1234. Seg.VAddr = Phdr.p_vaddr;
  1235. Seg.PAddr = Phdr.p_paddr;
  1236. Seg.FileSize = Phdr.p_filesz;
  1237. Seg.MemSize = Phdr.p_memsz;
  1238. Seg.Align = Phdr.p_align;
  1239. Seg.Index = Index++;
  1240. for (SectionBase &Sec : Obj.sections())
  1241. if (sectionWithinSegment(Sec, Seg)) {
  1242. Seg.addSection(&Sec);
  1243. if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
  1244. Sec.ParentSegment = &Seg;
  1245. }
  1246. }
  1247. auto &ElfHdr = Obj.ElfHdrSegment;
  1248. ElfHdr.Index = Index++;
  1249. ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
  1250. const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
  1251. auto &PrHdr = Obj.ProgramHdrSegment;
  1252. PrHdr.Type = PT_PHDR;
  1253. PrHdr.Flags = 0;
  1254. // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
  1255. // Whereas this works automatically for ElfHdr, here OriginalOffset is
  1256. // always non-zero and to ensure the equation we assign the same value to
  1257. // VAddr as well.
  1258. PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
  1259. PrHdr.PAddr = 0;
  1260. PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
  1261. // The spec requires us to naturally align all the fields.
  1262. PrHdr.Align = sizeof(Elf_Addr);
  1263. PrHdr.Index = Index++;
  1264. // Now we do an O(n^2) loop through the segments in order to match up
  1265. // segments.
  1266. for (Segment &Child : Obj.segments())
  1267. setParentSegment(Child);
  1268. setParentSegment(ElfHdr);
  1269. setParentSegment(PrHdr);
  1270. return Error::success();
  1271. }
  1272. template <class ELFT>
  1273. Error ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
  1274. if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
  1275. return createStringError(errc::invalid_argument,
  1276. "invalid alignment " + Twine(GroupSec->Align) +
  1277. " of group section '" + GroupSec->Name + "'");
  1278. SectionTableRef SecTable = Obj.sections();
  1279. if (GroupSec->Link != SHN_UNDEF) {
  1280. auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
  1281. GroupSec->Link,
  1282. "link field value '" + Twine(GroupSec->Link) + "' in section '" +
  1283. GroupSec->Name + "' is invalid",
  1284. "link field value '" + Twine(GroupSec->Link) + "' in section '" +
  1285. GroupSec->Name + "' is not a symbol table");
  1286. if (!SymTab)
  1287. return SymTab.takeError();
  1288. Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
  1289. if (!Sym)
  1290. return createStringError(errc::invalid_argument,
  1291. "info field value '" + Twine(GroupSec->Info) +
  1292. "' in section '" + GroupSec->Name +
  1293. "' is not a valid symbol index");
  1294. GroupSec->setSymTab(*SymTab);
  1295. GroupSec->setSymbol(*Sym);
  1296. }
  1297. if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
  1298. GroupSec->Contents.empty())
  1299. return createStringError(errc::invalid_argument,
  1300. "the content of the section " + GroupSec->Name +
  1301. " is malformed");
  1302. const ELF::Elf32_Word *Word =
  1303. reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
  1304. const ELF::Elf32_Word *End =
  1305. Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
  1306. GroupSec->setFlagWord(
  1307. support::endian::read32<ELFT::TargetEndianness>(Word++));
  1308. for (; Word != End; ++Word) {
  1309. uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
  1310. Expected<SectionBase *> Sec = SecTable.getSection(
  1311. Index, "group member index " + Twine(Index) + " in section '" +
  1312. GroupSec->Name + "' is invalid");
  1313. if (!Sec)
  1314. return Sec.takeError();
  1315. GroupSec->addMember(*Sec);
  1316. }
  1317. return Error::success();
  1318. }
  1319. template <class ELFT>
  1320. Error ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
  1321. Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
  1322. if (!Shdr)
  1323. return Shdr.takeError();
  1324. Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
  1325. if (!StrTabData)
  1326. return StrTabData.takeError();
  1327. ArrayRef<Elf_Word> ShndxData;
  1328. Expected<typename ELFFile<ELFT>::Elf_Sym_Range> Symbols =
  1329. ElfFile.symbols(*Shdr);
  1330. if (!Symbols)
  1331. return Symbols.takeError();
  1332. for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
  1333. SectionBase *DefSection = nullptr;
  1334. Expected<StringRef> Name = Sym.getName(*StrTabData);
  1335. if (!Name)
  1336. return Name.takeError();
  1337. if (Sym.st_shndx == SHN_XINDEX) {
  1338. if (SymTab->getShndxTable() == nullptr)
  1339. return createStringError(errc::invalid_argument,
  1340. "symbol '" + *Name +
  1341. "' has index SHN_XINDEX but no "
  1342. "SHT_SYMTAB_SHNDX section exists");
  1343. if (ShndxData.data() == nullptr) {
  1344. Expected<const Elf_Shdr *> ShndxSec =
  1345. ElfFile.getSection(SymTab->getShndxTable()->Index);
  1346. if (!ShndxSec)
  1347. return ShndxSec.takeError();
  1348. Expected<ArrayRef<Elf_Word>> Data =
  1349. ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
  1350. if (!Data)
  1351. return Data.takeError();
  1352. ShndxData = *Data;
  1353. if (ShndxData.size() != Symbols->size())
  1354. return createStringError(
  1355. errc::invalid_argument,
  1356. "symbol section index table does not have the same number of "
  1357. "entries as the symbol table");
  1358. }
  1359. Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
  1360. Expected<SectionBase *> Sec = Obj.sections().getSection(
  1361. Index,
  1362. "symbol '" + *Name + "' has invalid section index " + Twine(Index));
  1363. if (!Sec)
  1364. return Sec.takeError();
  1365. DefSection = *Sec;
  1366. } else if (Sym.st_shndx >= SHN_LORESERVE) {
  1367. if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
  1368. return createStringError(
  1369. errc::invalid_argument,
  1370. "symbol '" + *Name +
  1371. "' has unsupported value greater than or equal "
  1372. "to SHN_LORESERVE: " +
  1373. Twine(Sym.st_shndx));
  1374. }
  1375. } else if (Sym.st_shndx != SHN_UNDEF) {
  1376. Expected<SectionBase *> Sec = Obj.sections().getSection(
  1377. Sym.st_shndx, "symbol '" + *Name +
  1378. "' is defined has invalid section index " +
  1379. Twine(Sym.st_shndx));
  1380. if (!Sec)
  1381. return Sec.takeError();
  1382. DefSection = *Sec;
  1383. }
  1384. SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
  1385. Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
  1386. }
  1387. return Error::success();
  1388. }
  1389. template <class ELFT>
  1390. static void getAddend(uint64_t &, const Elf_Rel_Impl<ELFT, false> &) {}
  1391. template <class ELFT>
  1392. static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
  1393. ToSet = Rela.r_addend;
  1394. }
  1395. template <class T>
  1396. static Error initRelocations(RelocationSection *Relocs, T RelRange) {
  1397. for (const auto &Rel : RelRange) {
  1398. Relocation ToAdd;
  1399. ToAdd.Offset = Rel.r_offset;
  1400. getAddend(ToAdd.Addend, Rel);
  1401. ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
  1402. if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
  1403. if (!Relocs->getObject().SymbolTable)
  1404. return createStringError(
  1405. errc::invalid_argument,
  1406. "'" + Relocs->Name + "': relocation references symbol with index " +
  1407. Twine(Sym) + ", but there is no symbol table");
  1408. Expected<Symbol *> SymByIndex =
  1409. Relocs->getObject().SymbolTable->getSymbolByIndex(Sym);
  1410. if (!SymByIndex)
  1411. return SymByIndex.takeError();
  1412. ToAdd.RelocSymbol = *SymByIndex;
  1413. }
  1414. Relocs->addRelocation(ToAdd);
  1415. }
  1416. return Error::success();
  1417. }
  1418. Expected<SectionBase *> SectionTableRef::getSection(uint32_t Index,
  1419. Twine ErrMsg) {
  1420. if (Index == SHN_UNDEF || Index > Sections.size())
  1421. return createStringError(errc::invalid_argument, ErrMsg);
  1422. return Sections[Index - 1].get();
  1423. }
  1424. template <class T>
  1425. Expected<T *> SectionTableRef::getSectionOfType(uint32_t Index,
  1426. Twine IndexErrMsg,
  1427. Twine TypeErrMsg) {
  1428. Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
  1429. if (!BaseSec)
  1430. return BaseSec.takeError();
  1431. if (T *Sec = dyn_cast<T>(*BaseSec))
  1432. return Sec;
  1433. return createStringError(errc::invalid_argument, TypeErrMsg);
  1434. }
  1435. template <class ELFT>
  1436. Expected<SectionBase &> ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
  1437. switch (Shdr.sh_type) {
  1438. case SHT_REL:
  1439. case SHT_RELA:
  1440. if (Shdr.sh_flags & SHF_ALLOC) {
  1441. if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
  1442. return Obj.addSection<DynamicRelocationSection>(*Data);
  1443. else
  1444. return Data.takeError();
  1445. }
  1446. return Obj.addSection<RelocationSection>(Obj);
  1447. case SHT_STRTAB:
  1448. // If a string table is allocated we don't want to mess with it. That would
  1449. // mean altering the memory image. There are no special link types or
  1450. // anything so we can just use a Section.
  1451. if (Shdr.sh_flags & SHF_ALLOC) {
  1452. if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
  1453. return Obj.addSection<Section>(*Data);
  1454. else
  1455. return Data.takeError();
  1456. }
  1457. return Obj.addSection<StringTableSection>();
  1458. case SHT_HASH:
  1459. case SHT_GNU_HASH:
  1460. // Hash tables should refer to SHT_DYNSYM which we're not going to change.
  1461. // Because of this we don't need to mess with the hash tables either.
  1462. if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
  1463. return Obj.addSection<Section>(*Data);
  1464. else
  1465. return Data.takeError();
  1466. case SHT_GROUP:
  1467. if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
  1468. return Obj.addSection<GroupSection>(*Data);
  1469. else
  1470. return Data.takeError();
  1471. case SHT_DYNSYM:
  1472. if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
  1473. return Obj.addSection<DynamicSymbolTableSection>(*Data);
  1474. else
  1475. return Data.takeError();
  1476. case SHT_DYNAMIC:
  1477. if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
  1478. return Obj.addSection<DynamicSection>(*Data);
  1479. else
  1480. return Data.takeError();
  1481. case SHT_SYMTAB: {
  1482. auto &SymTab = Obj.addSection<SymbolTableSection>();
  1483. Obj.SymbolTable = &SymTab;
  1484. return SymTab;
  1485. }
  1486. case SHT_SYMTAB_SHNDX: {
  1487. auto &ShndxSection = Obj.addSection<SectionIndexSection>();
  1488. Obj.SectionIndexTable = &ShndxSection;
  1489. return ShndxSection;
  1490. }
  1491. case SHT_NOBITS:
  1492. return Obj.addSection<Section>(ArrayRef<uint8_t>());
  1493. default: {
  1494. Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
  1495. if (!Data)
  1496. return Data.takeError();
  1497. Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
  1498. if (!Name)
  1499. return Name.takeError();
  1500. if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
  1501. return Obj.addSection<Section>(*Data);
  1502. auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
  1503. return Obj.addSection<CompressedSection>(CompressedSection(
  1504. *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign));
  1505. }
  1506. }
  1507. }
  1508. template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
  1509. uint32_t Index = 0;
  1510. Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections =
  1511. ElfFile.sections();
  1512. if (!Sections)
  1513. return Sections.takeError();
  1514. for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
  1515. if (Index == 0) {
  1516. ++Index;
  1517. continue;
  1518. }
  1519. Expected<SectionBase &> Sec = makeSection(Shdr);
  1520. if (!Sec)
  1521. return Sec.takeError();
  1522. Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
  1523. if (!SecName)
  1524. return SecName.takeError();
  1525. Sec->Name = SecName->str();
  1526. Sec->Type = Sec->OriginalType = Shdr.sh_type;
  1527. Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
  1528. Sec->Addr = Shdr.sh_addr;
  1529. Sec->Offset = Shdr.sh_offset;
  1530. Sec->OriginalOffset = Shdr.sh_offset;
  1531. Sec->Size = Shdr.sh_size;
  1532. Sec->Link = Shdr.sh_link;
  1533. Sec->Info = Shdr.sh_info;
  1534. Sec->Align = Shdr.sh_addralign;
  1535. Sec->EntrySize = Shdr.sh_entsize;
  1536. Sec->Index = Index++;
  1537. Sec->OriginalIndex = Sec->Index;
  1538. Sec->OriginalData = ArrayRef<uint8_t>(
  1539. ElfFile.base() + Shdr.sh_offset,
  1540. (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
  1541. }
  1542. return Error::success();
  1543. }
  1544. template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
  1545. uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
  1546. if (ShstrIndex == SHN_XINDEX) {
  1547. Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
  1548. if (!Sec)
  1549. return Sec.takeError();
  1550. ShstrIndex = (*Sec)->sh_link;
  1551. }
  1552. if (ShstrIndex == SHN_UNDEF)
  1553. Obj.HadShdrs = false;
  1554. else {
  1555. Expected<StringTableSection *> Sec =
  1556. Obj.sections().template getSectionOfType<StringTableSection>(
  1557. ShstrIndex,
  1558. "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
  1559. " is invalid",
  1560. "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
  1561. " does not reference a string table");
  1562. if (!Sec)
  1563. return Sec.takeError();
  1564. Obj.SectionNames = *Sec;
  1565. }
  1566. // If a section index table exists we'll need to initialize it before we
  1567. // initialize the symbol table because the symbol table might need to
  1568. // reference it.
  1569. if (Obj.SectionIndexTable)
  1570. if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
  1571. return Err;
  1572. // Now that all of the sections have been added we can fill out some extra
  1573. // details about symbol tables. We need the symbol table filled out before
  1574. // any relocations.
  1575. if (Obj.SymbolTable) {
  1576. if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
  1577. return Err;
  1578. if (Error Err = initSymbolTable(Obj.SymbolTable))
  1579. return Err;
  1580. } else if (EnsureSymtab) {
  1581. if (Error Err = Obj.addNewSymbolTable())
  1582. return Err;
  1583. }
  1584. // Now that all sections and symbols have been added we can add
  1585. // relocations that reference symbols and set the link and info fields for
  1586. // relocation sections.
  1587. for (SectionBase &Sec : Obj.sections()) {
  1588. if (&Sec == Obj.SymbolTable)
  1589. continue;
  1590. if (Error Err = Sec.initialize(Obj.sections()))
  1591. return Err;
  1592. if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
  1593. Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections =
  1594. ElfFile.sections();
  1595. if (!Sections)
  1596. return Sections.takeError();
  1597. const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
  1598. Sections->begin() + RelSec->Index;
  1599. if (RelSec->Type == SHT_REL) {
  1600. Expected<typename ELFFile<ELFT>::Elf_Rel_Range> Rels =
  1601. ElfFile.rels(*Shdr);
  1602. if (!Rels)
  1603. return Rels.takeError();
  1604. if (Error Err = initRelocations(RelSec, *Rels))
  1605. return Err;
  1606. } else {
  1607. Expected<typename ELFFile<ELFT>::Elf_Rela_Range> Relas =
  1608. ElfFile.relas(*Shdr);
  1609. if (!Relas)
  1610. return Relas.takeError();
  1611. if (Error Err = initRelocations(RelSec, *Relas))
  1612. return Err;
  1613. }
  1614. } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
  1615. if (Error Err = initGroupSection(GroupSec))
  1616. return Err;
  1617. }
  1618. }
  1619. return Error::success();
  1620. }
  1621. template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
  1622. if (Error E = readSectionHeaders())
  1623. return E;
  1624. if (Error E = findEhdrOffset())
  1625. return E;
  1626. // The ELFFile whose ELF headers and program headers are copied into the
  1627. // output file. Normally the same as ElfFile, but if we're extracting a
  1628. // loadable partition it will point to the partition's headers.
  1629. Expected<ELFFile<ELFT>> HeadersFile = ELFFile<ELFT>::create(toStringRef(
  1630. {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
  1631. if (!HeadersFile)
  1632. return HeadersFile.takeError();
  1633. const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
  1634. Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64;
  1635. Obj.OSABI = Ehdr.e_ident[EI_OSABI];
  1636. Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
  1637. Obj.Type = Ehdr.e_type;
  1638. Obj.Machine = Ehdr.e_machine;
  1639. Obj.Version = Ehdr.e_version;
  1640. Obj.Entry = Ehdr.e_entry;
  1641. Obj.Flags = Ehdr.e_flags;
  1642. if (Error E = readSections(EnsureSymtab))
  1643. return E;
  1644. return readProgramHeaders(*HeadersFile);
  1645. }
  1646. Writer::~Writer() = default;
  1647. Reader::~Reader() = default;
  1648. Expected<std::unique_ptr<Object>>
  1649. BinaryReader::create(bool /*EnsureSymtab*/) const {
  1650. return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
  1651. }
  1652. Expected<std::vector<IHexRecord>> IHexReader::parse() const {
  1653. SmallVector<StringRef, 16> Lines;
  1654. std::vector<IHexRecord> Records;
  1655. bool HasSections = false;
  1656. MemBuf->getBuffer().split(Lines, '\n');
  1657. Records.reserve(Lines.size());
  1658. for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
  1659. StringRef Line = Lines[LineNo - 1].trim();
  1660. if (Line.empty())
  1661. continue;
  1662. Expected<IHexRecord> R = IHexRecord::parse(Line);
  1663. if (!R)
  1664. return parseError(LineNo, R.takeError());
  1665. if (R->Type == IHexRecord::EndOfFile)
  1666. break;
  1667. HasSections |= (R->Type == IHexRecord::Data);
  1668. Records.push_back(*R);
  1669. }
  1670. if (!HasSections)
  1671. return parseError(-1U, "no sections");
  1672. return std::move(Records);
  1673. }
  1674. Expected<std::unique_ptr<Object>>
  1675. IHexReader::create(bool /*EnsureSymtab*/) const {
  1676. Expected<std::vector<IHexRecord>> Records = parse();
  1677. if (!Records)
  1678. return Records.takeError();
  1679. return IHexELFBuilder(*Records).build();
  1680. }
  1681. Expected<std::unique_ptr<Object>> ELFReader::create(bool EnsureSymtab) const {
  1682. auto Obj = std::make_unique<Object>();
  1683. if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
  1684. ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
  1685. if (Error Err = Builder.build(EnsureSymtab))
  1686. return std::move(Err);
  1687. return std::move(Obj);
  1688. } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
  1689. ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
  1690. if (Error Err = Builder.build(EnsureSymtab))
  1691. return std::move(Err);
  1692. return std::move(Obj);
  1693. } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
  1694. ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
  1695. if (Error Err = Builder.build(EnsureSymtab))
  1696. return std::move(Err);
  1697. return std::move(Obj);
  1698. } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
  1699. ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
  1700. if (Error Err = Builder.build(EnsureSymtab))
  1701. return std::move(Err);
  1702. return std::move(Obj);
  1703. }
  1704. return createStringError(errc::invalid_argument, "invalid file type");
  1705. }
  1706. template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
  1707. Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
  1708. std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
  1709. Ehdr.e_ident[EI_MAG0] = 0x7f;
  1710. Ehdr.e_ident[EI_MAG1] = 'E';
  1711. Ehdr.e_ident[EI_MAG2] = 'L';
  1712. Ehdr.e_ident[EI_MAG3] = 'F';
  1713. Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
  1714. Ehdr.e_ident[EI_DATA] =
  1715. ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
  1716. Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
  1717. Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
  1718. Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
  1719. Ehdr.e_type = Obj.Type;
  1720. Ehdr.e_machine = Obj.Machine;
  1721. Ehdr.e_version = Obj.Version;
  1722. Ehdr.e_entry = Obj.Entry;
  1723. // We have to use the fully-qualified name llvm::size
  1724. // since some compilers complain on ambiguous resolution.
  1725. Ehdr.e_phnum = llvm::size(Obj.segments());
  1726. Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
  1727. Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
  1728. Ehdr.e_flags = Obj.Flags;
  1729. Ehdr.e_ehsize = sizeof(Elf_Ehdr);
  1730. if (WriteSectionHeaders && Obj.sections().size() != 0) {
  1731. Ehdr.e_shentsize = sizeof(Elf_Shdr);
  1732. Ehdr.e_shoff = Obj.SHOff;
  1733. // """
  1734. // If the number of sections is greater than or equal to
  1735. // SHN_LORESERVE (0xff00), this member has the value zero and the actual
  1736. // number of section header table entries is contained in the sh_size field
  1737. // of the section header at index 0.
  1738. // """
  1739. auto Shnum = Obj.sections().size() + 1;
  1740. if (Shnum >= SHN_LORESERVE)
  1741. Ehdr.e_shnum = 0;
  1742. else
  1743. Ehdr.e_shnum = Shnum;
  1744. // """
  1745. // If the section name string table section index is greater than or equal
  1746. // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
  1747. // and the actual index of the section name string table section is
  1748. // contained in the sh_link field of the section header at index 0.
  1749. // """
  1750. if (Obj.SectionNames->Index >= SHN_LORESERVE)
  1751. Ehdr.e_shstrndx = SHN_XINDEX;
  1752. else
  1753. Ehdr.e_shstrndx = Obj.SectionNames->Index;
  1754. } else {
  1755. Ehdr.e_shentsize = 0;
  1756. Ehdr.e_shoff = 0;
  1757. Ehdr.e_shnum = 0;
  1758. Ehdr.e_shstrndx = 0;
  1759. }
  1760. }
  1761. template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
  1762. for (auto &Seg : Obj.segments())
  1763. writePhdr(Seg);
  1764. }
  1765. template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
  1766. // This reference serves to write the dummy section header at the begining
  1767. // of the file. It is not used for anything else
  1768. Elf_Shdr &Shdr =
  1769. *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
  1770. Shdr.sh_name = 0;
  1771. Shdr.sh_type = SHT_NULL;
  1772. Shdr.sh_flags = 0;
  1773. Shdr.sh_addr = 0;
  1774. Shdr.sh_offset = 0;
  1775. // See writeEhdr for why we do this.
  1776. uint64_t Shnum = Obj.sections().size() + 1;
  1777. if (Shnum >= SHN_LORESERVE)
  1778. Shdr.sh_size = Shnum;
  1779. else
  1780. Shdr.sh_size = 0;
  1781. // See writeEhdr for why we do this.
  1782. if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
  1783. Shdr.sh_link = Obj.SectionNames->Index;
  1784. else
  1785. Shdr.sh_link = 0;
  1786. Shdr.sh_info = 0;
  1787. Shdr.sh_addralign = 0;
  1788. Shdr.sh_entsize = 0;
  1789. for (SectionBase &Sec : Obj.sections())
  1790. writeShdr(Sec);
  1791. }
  1792. template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
  1793. for (SectionBase &Sec : Obj.sections())
  1794. // Segments are responsible for writing their contents, so only write the
  1795. // section data if the section is not in a segment. Note that this renders
  1796. // sections in segments effectively immutable.
  1797. if (Sec.ParentSegment == nullptr)
  1798. if (Error Err = Sec.accept(*SecWriter))
  1799. return Err;
  1800. return Error::success();
  1801. }
  1802. template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
  1803. for (Segment &Seg : Obj.segments()) {
  1804. size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
  1805. std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
  1806. Size);
  1807. }
  1808. for (auto it : Obj.getUpdatedSections()) {
  1809. SectionBase *Sec = it.first;
  1810. ArrayRef<uint8_t> Data = it.second;
  1811. auto *Parent = Sec->ParentSegment;
  1812. assert(Parent && "This section should've been part of a segment.");
  1813. uint64_t Offset =
  1814. Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
  1815. llvm::copy(Data, Buf->getBufferStart() + Offset);
  1816. }
  1817. // Iterate over removed sections and overwrite their old data with zeroes.
  1818. for (auto &Sec : Obj.removedSections()) {
  1819. Segment *Parent = Sec.ParentSegment;
  1820. if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
  1821. continue;
  1822. uint64_t Offset =
  1823. Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
  1824. std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
  1825. }
  1826. }
  1827. template <class ELFT>
  1828. ELFWriter<ELFT>::ELFWriter(Object &Obj, raw_ostream &Buf, bool WSH,
  1829. bool OnlyKeepDebug)
  1830. : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
  1831. OnlyKeepDebug(OnlyKeepDebug) {}
  1832. Error Object::updateSection(StringRef Name, ArrayRef<uint8_t> Data) {
  1833. auto It = llvm::find_if(Sections,
  1834. [&](const SecPtr &Sec) { return Sec->Name == Name; });
  1835. if (It == Sections.end())
  1836. return createStringError(errc::invalid_argument, "section '%s' not found",
  1837. Name.str().c_str());
  1838. auto *OldSec = It->get();
  1839. if (!OldSec->hasContents())
  1840. return createStringError(
  1841. errc::invalid_argument,
  1842. "section '%s' cannot be updated because it does not have contents",
  1843. Name.str().c_str());
  1844. if (Data.size() > OldSec->Size && OldSec->ParentSegment)
  1845. return createStringError(errc::invalid_argument,
  1846. "cannot fit data of size %zu into section '%s' "
  1847. "with size %" PRIu64 " that is part of a segment",
  1848. Data.size(), Name.str().c_str(), OldSec->Size);
  1849. if (!OldSec->ParentSegment) {
  1850. *It = std::make_unique<OwnedDataSection>(*OldSec, Data);
  1851. } else {
  1852. // The segment writer will be in charge of updating these contents.
  1853. OldSec->Size = Data.size();
  1854. UpdatedSections[OldSec] = Data;
  1855. }
  1856. return Error::success();
  1857. }
  1858. Error Object::removeSections(
  1859. bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
  1860. auto Iter = std::stable_partition(
  1861. std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
  1862. if (ToRemove(*Sec))
  1863. return false;
  1864. if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
  1865. if (auto ToRelSec = RelSec->getSection())
  1866. return !ToRemove(*ToRelSec);
  1867. }
  1868. return true;
  1869. });
  1870. if (SymbolTable != nullptr && ToRemove(*SymbolTable))
  1871. SymbolTable = nullptr;
  1872. if (SectionNames != nullptr && ToRemove(*SectionNames))
  1873. SectionNames = nullptr;
  1874. if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
  1875. SectionIndexTable = nullptr;
  1876. // Now make sure there are no remaining references to the sections that will
  1877. // be removed. Sometimes it is impossible to remove a reference so we emit
  1878. // an error here instead.
  1879. std::unordered_set<const SectionBase *> RemoveSections;
  1880. RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
  1881. for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
  1882. for (auto &Segment : Segments)
  1883. Segment->removeSection(RemoveSec.get());
  1884. RemoveSec->onRemove();
  1885. RemoveSections.insert(RemoveSec.get());
  1886. }
  1887. // For each section that remains alive, we want to remove the dead references.
  1888. // This either might update the content of the section (e.g. remove symbols
  1889. // from symbol table that belongs to removed section) or trigger an error if
  1890. // a live section critically depends on a section being removed somehow
  1891. // (e.g. the removed section is referenced by a relocation).
  1892. for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
  1893. if (Error E = KeepSec->removeSectionReferences(
  1894. AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
  1895. return RemoveSections.find(Sec) != RemoveSections.end();
  1896. }))
  1897. return E;
  1898. }
  1899. // Transfer removed sections into the Object RemovedSections container for use
  1900. // later.
  1901. std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
  1902. // Now finally get rid of them all together.
  1903. Sections.erase(Iter, std::end(Sections));
  1904. return Error::success();
  1905. }
  1906. Error Object::replaceSections(
  1907. const DenseMap<SectionBase *, SectionBase *> &FromTo) {
  1908. auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
  1909. return Lhs->Index < Rhs->Index;
  1910. };
  1911. assert(llvm::is_sorted(Sections, SectionIndexLess) &&
  1912. "Sections are expected to be sorted by Index");
  1913. // Set indices of new sections so that they can be later sorted into positions
  1914. // of removed ones.
  1915. for (auto &I : FromTo)
  1916. I.second->Index = I.first->Index;
  1917. // Notify all sections about the replacement.
  1918. for (auto &Sec : Sections)
  1919. Sec->replaceSectionReferences(FromTo);
  1920. if (Error E = removeSections(
  1921. /*AllowBrokenLinks=*/false,
  1922. [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
  1923. return E;
  1924. llvm::sort(Sections, SectionIndexLess);
  1925. return Error::success();
  1926. }
  1927. Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
  1928. if (SymbolTable)
  1929. for (const SecPtr &Sec : Sections)
  1930. if (Error E = Sec->removeSymbols(ToRemove))
  1931. return E;
  1932. return Error::success();
  1933. }
  1934. Error Object::addNewSymbolTable() {
  1935. assert(!SymbolTable && "Object must not has a SymbolTable.");
  1936. // Reuse an existing SHT_STRTAB section if it exists.
  1937. StringTableSection *StrTab = nullptr;
  1938. for (SectionBase &Sec : sections()) {
  1939. if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
  1940. StrTab = static_cast<StringTableSection *>(&Sec);
  1941. // Prefer a string table that is not the section header string table, if
  1942. // such a table exists.
  1943. if (SectionNames != &Sec)
  1944. break;
  1945. }
  1946. }
  1947. if (!StrTab)
  1948. StrTab = &addSection<StringTableSection>();
  1949. SymbolTableSection &SymTab = addSection<SymbolTableSection>();
  1950. SymTab.Name = ".symtab";
  1951. SymTab.Link = StrTab->Index;
  1952. if (Error Err = SymTab.initialize(sections()))
  1953. return Err;
  1954. SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
  1955. SymbolTable = &SymTab;
  1956. return Error::success();
  1957. }
  1958. // Orders segments such that if x = y->ParentSegment then y comes before x.
  1959. static void orderSegments(std::vector<Segment *> &Segments) {
  1960. llvm::stable_sort(Segments, compareSegmentsByOffset);
  1961. }
  1962. // This function finds a consistent layout for a list of segments starting from
  1963. // an Offset. It assumes that Segments have been sorted by orderSegments and
  1964. // returns an Offset one past the end of the last segment.
  1965. static uint64_t layoutSegments(std::vector<Segment *> &Segments,
  1966. uint64_t Offset) {
  1967. assert(llvm::is_sorted(Segments, compareSegmentsByOffset));
  1968. // The only way a segment should move is if a section was between two
  1969. // segments and that section was removed. If that section isn't in a segment
  1970. // then it's acceptable, but not ideal, to simply move it to after the
  1971. // segments. So we can simply layout segments one after the other accounting
  1972. // for alignment.
  1973. for (Segment *Seg : Segments) {
  1974. // We assume that segments have been ordered by OriginalOffset and Index
  1975. // such that a parent segment will always come before a child segment in
  1976. // OrderedSegments. This means that the Offset of the ParentSegment should
  1977. // already be set and we can set our offset relative to it.
  1978. if (Seg->ParentSegment != nullptr) {
  1979. Segment *Parent = Seg->ParentSegment;
  1980. Seg->Offset =
  1981. Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
  1982. } else {
  1983. Seg->Offset =
  1984. alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
  1985. }
  1986. Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
  1987. }
  1988. return Offset;
  1989. }
  1990. // This function finds a consistent layout for a list of sections. It assumes
  1991. // that the ->ParentSegment of each section has already been laid out. The
  1992. // supplied starting Offset is used for the starting offset of any section that
  1993. // does not have a ParentSegment. It returns either the offset given if all
  1994. // sections had a ParentSegment or an offset one past the last section if there
  1995. // was a section that didn't have a ParentSegment.
  1996. template <class Range>
  1997. static uint64_t layoutSections(Range Sections, uint64_t Offset) {
  1998. // Now the offset of every segment has been set we can assign the offsets
  1999. // of each section. For sections that are covered by a segment we should use
  2000. // the segment's original offset and the section's original offset to compute
  2001. // the offset from the start of the segment. Using the offset from the start
  2002. // of the segment we can assign a new offset to the section. For sections not
  2003. // covered by segments we can just bump Offset to the next valid location.
  2004. // While it is not necessary, layout the sections in the order based on their
  2005. // original offsets to resemble the input file as close as possible.
  2006. std::vector<SectionBase *> OutOfSegmentSections;
  2007. uint32_t Index = 1;
  2008. for (auto &Sec : Sections) {
  2009. Sec.Index = Index++;
  2010. if (Sec.ParentSegment != nullptr) {
  2011. auto Segment = *Sec.ParentSegment;
  2012. Sec.Offset =
  2013. Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
  2014. } else
  2015. OutOfSegmentSections.push_back(&Sec);
  2016. }
  2017. llvm::stable_sort(OutOfSegmentSections,
  2018. [](const SectionBase *Lhs, const SectionBase *Rhs) {
  2019. return Lhs->OriginalOffset < Rhs->OriginalOffset;
  2020. });
  2021. for (auto *Sec : OutOfSegmentSections) {
  2022. Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
  2023. Sec->Offset = Offset;
  2024. if (Sec->Type != SHT_NOBITS)
  2025. Offset += Sec->Size;
  2026. }
  2027. return Offset;
  2028. }
  2029. // Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
  2030. // occupy no space in the file.
  2031. static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off) {
  2032. // The layout algorithm requires the sections to be handled in the order of
  2033. // their offsets in the input file, at least inside segments.
  2034. std::vector<SectionBase *> Sections;
  2035. Sections.reserve(Obj.sections().size());
  2036. uint32_t Index = 1;
  2037. for (auto &Sec : Obj.sections()) {
  2038. Sec.Index = Index++;
  2039. Sections.push_back(&Sec);
  2040. }
  2041. llvm::stable_sort(Sections,
  2042. [](const SectionBase *Lhs, const SectionBase *Rhs) {
  2043. return Lhs->OriginalOffset < Rhs->OriginalOffset;
  2044. });
  2045. for (auto *Sec : Sections) {
  2046. auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
  2047. ? Sec->ParentSegment->firstSection()
  2048. : nullptr;
  2049. // The first section in a PT_LOAD has to have congruent offset and address
  2050. // modulo the alignment, which usually equals the maximum page size.
  2051. if (FirstSec && FirstSec == Sec)
  2052. Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
  2053. // sh_offset is not significant for SHT_NOBITS sections, but the congruence
  2054. // rule must be followed if it is the first section in a PT_LOAD. Do not
  2055. // advance Off.
  2056. if (Sec->Type == SHT_NOBITS) {
  2057. Sec->Offset = Off;
  2058. continue;
  2059. }
  2060. if (!FirstSec) {
  2061. // FirstSec being nullptr generally means that Sec does not have the
  2062. // SHF_ALLOC flag.
  2063. Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
  2064. } else if (FirstSec != Sec) {
  2065. // The offset is relative to the first section in the PT_LOAD segment. Use
  2066. // sh_offset for non-SHF_ALLOC sections.
  2067. Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
  2068. }
  2069. Sec->Offset = Off;
  2070. Off += Sec->Size;
  2071. }
  2072. return Off;
  2073. }
  2074. // Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
  2075. // have been updated.
  2076. static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
  2077. uint64_t HdrEnd) {
  2078. uint64_t MaxOffset = 0;
  2079. for (Segment *Seg : Segments) {
  2080. if (Seg->Type == PT_PHDR)
  2081. continue;
  2082. // The segment offset is generally the offset of the first section.
  2083. //
  2084. // For a segment containing no section (see sectionWithinSegment), if it has
  2085. // a parent segment, copy the parent segment's offset field. This works for
  2086. // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
  2087. // debugging anyway.
  2088. const SectionBase *FirstSec = Seg->firstSection();
  2089. uint64_t Offset =
  2090. FirstSec ? FirstSec->Offset
  2091. : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
  2092. uint64_t FileSize = 0;
  2093. for (const SectionBase *Sec : Seg->Sections) {
  2094. uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
  2095. if (Sec->Offset + Size > Offset)
  2096. FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
  2097. }
  2098. // If the segment includes EHDR and program headers, don't make it smaller
  2099. // than the headers.
  2100. if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
  2101. FileSize += Offset - Seg->Offset;
  2102. Offset = Seg->Offset;
  2103. FileSize = std::max(FileSize, HdrEnd - Offset);
  2104. }
  2105. Seg->Offset = Offset;
  2106. Seg->FileSize = FileSize;
  2107. MaxOffset = std::max(MaxOffset, Offset + FileSize);
  2108. }
  2109. return MaxOffset;
  2110. }
  2111. template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
  2112. Segment &ElfHdr = Obj.ElfHdrSegment;
  2113. ElfHdr.Type = PT_PHDR;
  2114. ElfHdr.Flags = 0;
  2115. ElfHdr.VAddr = 0;
  2116. ElfHdr.PAddr = 0;
  2117. ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
  2118. ElfHdr.Align = 0;
  2119. }
  2120. template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
  2121. // We need a temporary list of segments that has a special order to it
  2122. // so that we know that anytime ->ParentSegment is set that segment has
  2123. // already had its offset properly set.
  2124. std::vector<Segment *> OrderedSegments;
  2125. for (Segment &Segment : Obj.segments())
  2126. OrderedSegments.push_back(&Segment);
  2127. OrderedSegments.push_back(&Obj.ElfHdrSegment);
  2128. OrderedSegments.push_back(&Obj.ProgramHdrSegment);
  2129. orderSegments(OrderedSegments);
  2130. uint64_t Offset;
  2131. if (OnlyKeepDebug) {
  2132. // For --only-keep-debug, the sections that did not preserve contents were
  2133. // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
  2134. // then rewrite p_offset/p_filesz of program headers.
  2135. uint64_t HdrEnd =
  2136. sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
  2137. Offset = layoutSectionsForOnlyKeepDebug(Obj, HdrEnd);
  2138. Offset = std::max(Offset,
  2139. layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
  2140. } else {
  2141. // Offset is used as the start offset of the first segment to be laid out.
  2142. // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
  2143. // we start at offset 0.
  2144. Offset = layoutSegments(OrderedSegments, 0);
  2145. Offset = layoutSections(Obj.sections(), Offset);
  2146. }
  2147. // If we need to write the section header table out then we need to align the
  2148. // Offset so that SHOffset is valid.
  2149. if (WriteSectionHeaders)
  2150. Offset = alignTo(Offset, sizeof(Elf_Addr));
  2151. Obj.SHOff = Offset;
  2152. }
  2153. template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
  2154. // We already have the section header offset so we can calculate the total
  2155. // size by just adding up the size of each section header.
  2156. if (!WriteSectionHeaders)
  2157. return Obj.SHOff;
  2158. size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
  2159. return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
  2160. }
  2161. template <class ELFT> Error ELFWriter<ELFT>::write() {
  2162. // Segment data must be written first, so that the ELF header and program
  2163. // header tables can overwrite it, if covered by a segment.
  2164. writeSegmentData();
  2165. writeEhdr();
  2166. writePhdrs();
  2167. if (Error E = writeSectionData())
  2168. return E;
  2169. if (WriteSectionHeaders)
  2170. writeShdrs();
  2171. // TODO: Implement direct writing to the output stream (without intermediate
  2172. // memory buffer Buf).
  2173. Out.write(Buf->getBufferStart(), Buf->getBufferSize());
  2174. return Error::success();
  2175. }
  2176. static Error removeUnneededSections(Object &Obj) {
  2177. // We can remove an empty symbol table from non-relocatable objects.
  2178. // Relocatable objects typically have relocation sections whose
  2179. // sh_link field points to .symtab, so we can't remove .symtab
  2180. // even if it is empty.
  2181. if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
  2182. !Obj.SymbolTable->empty())
  2183. return Error::success();
  2184. // .strtab can be used for section names. In such a case we shouldn't
  2185. // remove it.
  2186. auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
  2187. ? nullptr
  2188. : Obj.SymbolTable->getStrTab();
  2189. return Obj.removeSections(false, [&](const SectionBase &Sec) {
  2190. return &Sec == Obj.SymbolTable || &Sec == StrTab;
  2191. });
  2192. }
  2193. template <class ELFT> Error ELFWriter<ELFT>::finalize() {
  2194. // It could happen that SectionNames has been removed and yet the user wants
  2195. // a section header table output. We need to throw an error if a user tries
  2196. // to do that.
  2197. if (Obj.SectionNames == nullptr && WriteSectionHeaders)
  2198. return createStringError(llvm::errc::invalid_argument,
  2199. "cannot write section header table because "
  2200. "section header string table was removed");
  2201. if (Error E = removeUnneededSections(Obj))
  2202. return E;
  2203. // We need to assign indexes before we perform layout because we need to know
  2204. // if we need large indexes or not. We can assign indexes first and check as
  2205. // we go to see if we will actully need large indexes.
  2206. bool NeedsLargeIndexes = false;
  2207. if (Obj.sections().size() >= SHN_LORESERVE) {
  2208. SectionTableRef Sections = Obj.sections();
  2209. // Sections doesn't include the null section header, so account for this
  2210. // when skipping the first N sections.
  2211. NeedsLargeIndexes =
  2212. any_of(drop_begin(Sections, SHN_LORESERVE - 1),
  2213. [](const SectionBase &Sec) { return Sec.HasSymbol; });
  2214. // TODO: handle case where only one section needs the large index table but
  2215. // only needs it because the large index table hasn't been removed yet.
  2216. }
  2217. if (NeedsLargeIndexes) {
  2218. // This means we definitely need to have a section index table but if we
  2219. // already have one then we should use it instead of making a new one.
  2220. if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
  2221. // Addition of a section to the end does not invalidate the indexes of
  2222. // other sections and assigns the correct index to the new section.
  2223. auto &Shndx = Obj.addSection<SectionIndexSection>();
  2224. Obj.SymbolTable->setShndxTable(&Shndx);
  2225. Shndx.setSymTab(Obj.SymbolTable);
  2226. }
  2227. } else {
  2228. // Since we don't need SectionIndexTable we should remove it and all
  2229. // references to it.
  2230. if (Obj.SectionIndexTable != nullptr) {
  2231. // We do not support sections referring to the section index table.
  2232. if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
  2233. [this](const SectionBase &Sec) {
  2234. return &Sec == Obj.SectionIndexTable;
  2235. }))
  2236. return E;
  2237. }
  2238. }
  2239. // Make sure we add the names of all the sections. Importantly this must be
  2240. // done after we decide to add or remove SectionIndexes.
  2241. if (Obj.SectionNames != nullptr)
  2242. for (const SectionBase &Sec : Obj.sections())
  2243. Obj.SectionNames->addString(Sec.Name);
  2244. initEhdrSegment();
  2245. // Before we can prepare for layout the indexes need to be finalized.
  2246. // Also, the output arch may not be the same as the input arch, so fix up
  2247. // size-related fields before doing layout calculations.
  2248. uint64_t Index = 0;
  2249. auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
  2250. for (SectionBase &Sec : Obj.sections()) {
  2251. Sec.Index = Index++;
  2252. if (Error Err = Sec.accept(*SecSizer))
  2253. return Err;
  2254. }
  2255. // The symbol table does not update all other sections on update. For
  2256. // instance, symbol names are not added as new symbols are added. This means
  2257. // that some sections, like .strtab, don't yet have their final size.
  2258. if (Obj.SymbolTable != nullptr)
  2259. Obj.SymbolTable->prepareForLayout();
  2260. // Now that all strings are added we want to finalize string table builders,
  2261. // because that affects section sizes which in turn affects section offsets.
  2262. for (SectionBase &Sec : Obj.sections())
  2263. if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
  2264. StrTab->prepareForLayout();
  2265. assignOffsets();
  2266. // layoutSections could have modified section indexes, so we need
  2267. // to fill the index table after assignOffsets.
  2268. if (Obj.SymbolTable != nullptr)
  2269. Obj.SymbolTable->fillShndxTable();
  2270. // Finally now that all offsets and indexes have been set we can finalize any
  2271. // remaining issues.
  2272. uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
  2273. for (SectionBase &Sec : Obj.sections()) {
  2274. Sec.HeaderOffset = Offset;
  2275. Offset += sizeof(Elf_Shdr);
  2276. if (WriteSectionHeaders)
  2277. Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
  2278. Sec.finalize();
  2279. }
  2280. size_t TotalSize = totalSize();
  2281. Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
  2282. if (!Buf)
  2283. return createStringError(errc::not_enough_memory,
  2284. "failed to allocate memory buffer of " +
  2285. Twine::utohexstr(TotalSize) + " bytes");
  2286. SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
  2287. return Error::success();
  2288. }
  2289. Error BinaryWriter::write() {
  2290. for (const SectionBase &Sec : Obj.allocSections())
  2291. if (Error Err = Sec.accept(*SecWriter))
  2292. return Err;
  2293. // TODO: Implement direct writing to the output stream (without intermediate
  2294. // memory buffer Buf).
  2295. Out.write(Buf->getBufferStart(), Buf->getBufferSize());
  2296. return Error::success();
  2297. }
  2298. Error BinaryWriter::finalize() {
  2299. // Compute the section LMA based on its sh_offset and the containing segment's
  2300. // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
  2301. // sections as MinAddr. In the output, the contents between address 0 and
  2302. // MinAddr will be skipped.
  2303. uint64_t MinAddr = UINT64_MAX;
  2304. for (SectionBase &Sec : Obj.allocSections()) {
  2305. // If Sec's type is changed from SHT_NOBITS due to --set-section-flags,
  2306. // Offset may not be aligned. Align it to max(Align, 1).
  2307. if (Sec.ParentSegment != nullptr)
  2308. Sec.Addr = alignTo(Sec.Offset - Sec.ParentSegment->Offset +
  2309. Sec.ParentSegment->PAddr,
  2310. std::max(Sec.Align, uint64_t(1)));
  2311. if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
  2312. MinAddr = std::min(MinAddr, Sec.Addr);
  2313. }
  2314. // Now that every section has been laid out we just need to compute the total
  2315. // file size. This might not be the same as the offset returned by
  2316. // layoutSections, because we want to truncate the last segment to the end of
  2317. // its last non-empty section, to match GNU objcopy's behaviour.
  2318. TotalSize = 0;
  2319. for (SectionBase &Sec : Obj.allocSections())
  2320. if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
  2321. Sec.Offset = Sec.Addr - MinAddr;
  2322. TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
  2323. }
  2324. Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
  2325. if (!Buf)
  2326. return createStringError(errc::not_enough_memory,
  2327. "failed to allocate memory buffer of " +
  2328. Twine::utohexstr(TotalSize) + " bytes");
  2329. SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
  2330. return Error::success();
  2331. }
  2332. bool IHexWriter::SectionCompare::operator()(const SectionBase *Lhs,
  2333. const SectionBase *Rhs) const {
  2334. return (sectionPhysicalAddr(Lhs) & 0xFFFFFFFFU) <
  2335. (sectionPhysicalAddr(Rhs) & 0xFFFFFFFFU);
  2336. }
  2337. uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
  2338. IHexLineData HexData;
  2339. uint8_t Data[4] = {};
  2340. // We don't write entry point record if entry is zero.
  2341. if (Obj.Entry == 0)
  2342. return 0;
  2343. if (Obj.Entry <= 0xFFFFFU) {
  2344. Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
  2345. support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
  2346. support::big);
  2347. HexData = IHexRecord::getLine(IHexRecord::StartAddr80x86, 0, Data);
  2348. } else {
  2349. support::endian::write(Data, static_cast<uint32_t>(Obj.Entry),
  2350. support::big);
  2351. HexData = IHexRecord::getLine(IHexRecord::StartAddr, 0, Data);
  2352. }
  2353. memcpy(Buf, HexData.data(), HexData.size());
  2354. return HexData.size();
  2355. }
  2356. uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
  2357. IHexLineData HexData = IHexRecord::getLine(IHexRecord::EndOfFile, 0, {});
  2358. memcpy(Buf, HexData.data(), HexData.size());
  2359. return HexData.size();
  2360. }
  2361. Error IHexWriter::write() {
  2362. IHexSectionWriter Writer(*Buf);
  2363. // Write sections.
  2364. for (const SectionBase *Sec : Sections)
  2365. if (Error Err = Sec->accept(Writer))
  2366. return Err;
  2367. uint64_t Offset = Writer.getBufferOffset();
  2368. // Write entry point address.
  2369. Offset += writeEntryPointRecord(
  2370. reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
  2371. // Write EOF.
  2372. Offset += writeEndOfFileRecord(
  2373. reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
  2374. assert(Offset == TotalSize);
  2375. // TODO: Implement direct writing to the output stream (without intermediate
  2376. // memory buffer Buf).
  2377. Out.write(Buf->getBufferStart(), Buf->getBufferSize());
  2378. return Error::success();
  2379. }
  2380. Error IHexWriter::checkSection(const SectionBase &Sec) {
  2381. uint64_t Addr = sectionPhysicalAddr(&Sec);
  2382. if (addressOverflows32bit(Addr) || addressOverflows32bit(Addr + Sec.Size - 1))
  2383. return createStringError(
  2384. errc::invalid_argument,
  2385. "Section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
  2386. Sec.Name.c_str(), Addr, Addr + Sec.Size - 1);
  2387. return Error::success();
  2388. }
  2389. Error IHexWriter::finalize() {
  2390. // We can't write 64-bit addresses.
  2391. if (addressOverflows32bit(Obj.Entry))
  2392. return createStringError(errc::invalid_argument,
  2393. "Entry point address 0x%llx overflows 32 bits",
  2394. Obj.Entry);
  2395. for (const SectionBase &Sec : Obj.sections())
  2396. if ((Sec.Flags & ELF::SHF_ALLOC) && Sec.Type != ELF::SHT_NOBITS &&
  2397. Sec.Size > 0) {
  2398. if (Error E = checkSection(Sec))
  2399. return E;
  2400. Sections.insert(&Sec);
  2401. }
  2402. std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
  2403. WritableMemoryBuffer::getNewMemBuffer(0);
  2404. if (!EmptyBuffer)
  2405. return createStringError(errc::not_enough_memory,
  2406. "failed to allocate memory buffer of 0 bytes");
  2407. IHexSectionWriterBase LengthCalc(*EmptyBuffer);
  2408. for (const SectionBase *Sec : Sections)
  2409. if (Error Err = Sec->accept(LengthCalc))
  2410. return Err;
  2411. // We need space to write section records + StartAddress record
  2412. // (if start adress is not zero) + EndOfFile record.
  2413. TotalSize = LengthCalc.getBufferOffset() +
  2414. (Obj.Entry ? IHexRecord::getLineLength(4) : 0) +
  2415. IHexRecord::getLineLength(0);
  2416. Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
  2417. if (!Buf)
  2418. return createStringError(errc::not_enough_memory,
  2419. "failed to allocate memory buffer of " +
  2420. Twine::utohexstr(TotalSize) + " bytes");
  2421. return Error::success();
  2422. }
  2423. namespace llvm {
  2424. namespace objcopy {
  2425. namespace elf {
  2426. template class ELFBuilder<ELF64LE>;
  2427. template class ELFBuilder<ELF64BE>;
  2428. template class ELFBuilder<ELF32LE>;
  2429. template class ELFBuilder<ELF32BE>;
  2430. template class ELFWriter<ELF64LE>;
  2431. template class ELFWriter<ELF64BE>;
  2432. template class ELFWriter<ELF32LE>;
  2433. template class ELFWriter<ELF32BE>;
  2434. } // end namespace elf
  2435. } // end namespace objcopy
  2436. } // end namespace llvm