Object.cpp 97 KB

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