LLVM 20.0.0git
ELFObject.cpp
Go to the documentation of this file.
1//===- ELFObject.cpp ------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ELFObject.h"
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/ADT/Twine.h"
16#include "llvm/MC/MCELFExtras.h"
19#include "llvm/Support/Endian.h"
21#include "llvm/Support/Path.h"
22#include <algorithm>
23#include <cstddef>
24#include <cstdint>
25#include <iterator>
26#include <unordered_set>
27#include <utility>
28#include <vector>
29
30using namespace llvm;
31using namespace llvm::ELF;
32using namespace llvm::objcopy::elf;
33using namespace llvm::object;
34using namespace llvm::support;
35
36template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
37 uint8_t *B = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
38 Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
39 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
40 Phdr.p_type = Seg.Type;
41 Phdr.p_flags = Seg.Flags;
42 Phdr.p_offset = Seg.Offset;
43 Phdr.p_vaddr = Seg.VAddr;
44 Phdr.p_paddr = Seg.PAddr;
45 Phdr.p_filesz = Seg.FileSize;
46 Phdr.p_memsz = Seg.MemSize;
47 Phdr.p_align = Seg.Align;
48}
49
51 bool, function_ref<bool(const SectionBase *)>) {
52 return Error::success();
53}
54
56 return Error::success();
57}
58
65
66template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
67 uint8_t *B =
68 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Sec.HeaderOffset;
69 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
70 Shdr.sh_name = Sec.NameIndex;
71 Shdr.sh_type = Sec.Type;
72 Shdr.sh_flags = Sec.Flags;
73 Shdr.sh_addr = Sec.Addr;
74 Shdr.sh_offset = Sec.Offset;
75 Shdr.sh_size = Sec.Size;
76 Shdr.sh_link = Sec.Link;
77 Shdr.sh_info = Sec.Info;
78 Shdr.sh_addralign = Sec.Align;
79 Shdr.sh_entsize = Sec.EntrySize;
80}
81
82template <class ELFT> Error ELFSectionSizer<ELFT>::visit(Section &) {
83 return Error::success();
84}
85
87 return Error::success();
88}
89
91 return Error::success();
92}
93
94template <class ELFT>
96 return Error::success();
97}
98
99template <class ELFT>
101 Sec.EntrySize = sizeof(Elf_Sym);
102 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
103 // Align to the largest field in Elf_Sym.
104 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
105 return Error::success();
106}
107
108template <bool Is64>
110 using uint = std::conditional_t<Is64, uint64_t, uint32_t>;
113 ELF::encodeCrel<Is64>(OS, Relocations, [&](const Relocation &R) {
114 uint32_t CurSymIdx = R.RelocSymbol ? R.RelocSymbol->Index : 0;
115 return ELF::Elf_Crel<Is64>{static_cast<uint>(R.Offset), CurSymIdx, R.Type,
116 std::make_signed_t<uint>(R.Addend)};
117 });
118 return Content;
119}
120
121template <class ELFT>
123 if (Sec.Type == SHT_CREL) {
124 Sec.Size = encodeCrel<ELFT::Is64Bits>(Sec.Relocations).size();
125 } else {
126 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
127 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
128 // Align to the largest field in Elf_Rel(a).
129 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
130 }
131 return Error::success();
132}
133
134template <class ELFT>
136 return Error::success();
137}
138
140 Sec.Size = sizeof(Elf_Word) + Sec.GroupMembers.size() * sizeof(Elf_Word);
141 return Error::success();
142}
143
144template <class ELFT>
146 return Error::success();
147}
148
150 return Error::success();
151}
152
153template <class ELFT>
155 return Error::success();
156}
157
160 "cannot write symbol section index table '" +
161 Sec.Name + "' ");
162}
163
166 "cannot write symbol table '" + Sec.Name +
167 "' out to binary");
168}
169
172 "cannot write relocation section '" + Sec.Name +
173 "' out to binary");
174}
175
178 "cannot write '" + Sec.Name + "' out to binary");
179}
180
183 "cannot write '" + Sec.Name + "' out to binary");
184}
187 if (Sec.Type != SHT_NOBITS)
188 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
192
194 // Sign extended 32 bit addresses (e.g 0xFFFFFFFF80000000) are ok
195 return Addr > UINT32_MAX && Addr + 0x80000000 > UINT32_MAX;
196}
197
198template <class T> static T checkedGetHex(StringRef S) {
199 T Value;
200 bool Fail = S.getAsInteger(16, Value);
201 assert(!Fail);
202 (void)Fail;
203 return Value;
204}
205
206// Fills exactly Len bytes of buffer with hexadecimal characters
207// representing value 'X'
208template <class T, class Iterator>
209static Iterator toHexStr(T X, Iterator It, size_t Len) {
210 // Fill range with '0'
211 std::fill(It, It + Len, '0');
212
213 for (long I = Len - 1; I >= 0; --I) {
214 unsigned char Mod = static_cast<unsigned char>(X) & 15;
215 *(It + I) = hexdigit(Mod, false);
216 X >>= 4;
217 }
218 assert(X == 0);
219 return It + Len;
220}
221
223 assert((S.size() & 1) == 0);
224 uint8_t Checksum = 0;
225 while (!S.empty()) {
226 Checksum += checkedGetHex<uint8_t>(S.take_front(2));
227 S = S.drop_front(2);
228 }
229 return -Checksum;
230}
231
234 IHexLineData Line(getLineLength(Data.size()));
235 assert(Line.size());
236 auto Iter = Line.begin();
237 *Iter++ = ':';
238 Iter = toHexStr(Data.size(), Iter, 2);
239 Iter = toHexStr(Addr, Iter, 4);
240 Iter = toHexStr(Type, Iter, 2);
241 for (uint8_t X : Data)
242 Iter = toHexStr(X, Iter, 2);
243 StringRef S(Line.data() + 1, std::distance(Line.begin() + 1, Iter));
244 Iter = toHexStr(getChecksum(S), Iter, 2);
245 *Iter++ = '\r';
246 *Iter++ = '\n';
247 assert(Iter == Line.end());
248 return Line;
249}
250
251static Error checkRecord(const IHexRecord &R) {
252 switch (R.Type) {
253 case IHexRecord::Data:
254 if (R.HexData.size() == 0)
255 return createStringError(
257 "zero data length is not allowed for data records");
258 break;
260 break;
262 // 20-bit segment address. Data length must be 2 bytes
263 // (4 bytes in hex)
264 if (R.HexData.size() != 4)
265 return createStringError(
267 "segment address data should be 2 bytes in size");
268 break;
271 if (R.HexData.size() != 8)
273 "start address data should be 4 bytes in size");
274 // According to Intel HEX specification '03' record
275 // only specifies the code address within the 20-bit
276 // segmented address space of the 8086/80186. This
277 // means 12 high order bits should be zeroes.
278 if (R.Type == IHexRecord::StartAddr80x86 &&
279 R.HexData.take_front(3) != "000")
281 "start address exceeds 20 bit for 80x86");
282 break;
284 // 16-31 bits of linear base address
285 if (R.HexData.size() != 4)
286 return createStringError(
288 "extended address data should be 2 bytes in size");
289 break;
290 default:
291 // Unknown record type
292 return createStringError(errc::invalid_argument, "unknown record type: %u",
293 static_cast<unsigned>(R.Type));
294 }
295 return Error::success();
296}
297
298// Checks that IHEX line contains valid characters.
299// This allows converting hexadecimal data to integers
300// without extra verification.
302 assert(!Line.empty());
303 if (Line[0] != ':')
305 "missing ':' in the beginning of line.");
306
307 for (size_t Pos = 1; Pos < Line.size(); ++Pos)
308 if (hexDigitValue(Line[Pos]) == -1U)
310 "invalid character at position %zu.", Pos + 1);
311 return Error::success();
312}
313
315 assert(!Line.empty());
316
317 // ':' + Length + Address + Type + Checksum with empty data ':LLAAAATTCC'
318 if (Line.size() < 11)
320 "line is too short: %zu chars.", Line.size());
321
322 if (Error E = checkChars(Line))
323 return std::move(E);
324
325 IHexRecord Rec;
326 size_t DataLen = checkedGetHex<uint8_t>(Line.substr(1, 2));
327 if (Line.size() != getLength(DataLen))
329 "invalid line length %zu (should be %zu)",
330 Line.size(), getLength(DataLen));
331
332 Rec.Addr = checkedGetHex<uint16_t>(Line.substr(3, 4));
333 Rec.Type = checkedGetHex<uint8_t>(Line.substr(7, 2));
334 Rec.HexData = Line.substr(9, DataLen * 2);
335
336 if (getChecksum(Line.drop_front(1)) != 0)
337 return createStringError(errc::invalid_argument, "incorrect checksum.");
338 if (Error E = checkRecord(Rec))
339 return std::move(E);
340 return Rec;
341}
342
344 Segment *Seg = Sec->ParentSegment;
345 if (Seg && Seg->Type != ELF::PT_LOAD)
346 Seg = nullptr;
347 return Seg ? Seg->PAddr + Sec->OriginalOffset - Seg->OriginalOffset
348 : Sec->Addr;
349}
350
353 assert(Data.size() == Sec->Size);
354 const uint32_t ChunkSize = 16;
355 uint32_t Addr = sectionPhysicalAddr(Sec) & 0xFFFFFFFFU;
356 while (!Data.empty()) {
357 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
358 if (Addr > SegmentAddr + BaseAddr + 0xFFFFU) {
359 if (Addr > 0xFFFFFU) {
360 // Write extended address record, zeroing segment address
361 // if needed.
362 if (SegmentAddr != 0)
363 SegmentAddr = writeSegmentAddr(0U);
364 BaseAddr = writeBaseAddr(Addr);
365 } else {
366 // We can still remain 16-bit
367 SegmentAddr = writeSegmentAddr(Addr);
368 }
369 }
370 uint64_t SegOffset = Addr - BaseAddr - SegmentAddr;
371 assert(SegOffset <= 0xFFFFU);
372 DataSize = std::min(DataSize, 0x10000U - SegOffset);
373 writeData(0, SegOffset, Data.take_front(DataSize));
374 Addr += DataSize;
375 Data = Data.drop_front(DataSize);
376 }
377}
378
379uint64_t IHexSectionWriterBase::writeSegmentAddr(uint64_t Addr) {
380 assert(Addr <= 0xFFFFFU);
381 uint8_t Data[] = {static_cast<uint8_t>((Addr & 0xF0000U) >> 12), 0};
382 writeData(2, 0, Data);
383 return Addr & 0xF0000U;
384}
385
386uint64_t IHexSectionWriterBase::writeBaseAddr(uint64_t Addr) {
387 assert(Addr <= 0xFFFFFFFFU);
388 uint64_t Base = Addr & 0xFFFF0000U;
389 uint8_t Data[] = {static_cast<uint8_t>(Base >> 24),
390 static_cast<uint8_t>((Base >> 16) & 0xFF)};
391 writeData(4, 0, Data);
392 return Base;
393}
394
398}
399
401 writeSection(&Sec, Sec.Contents);
402 return Error::success();
403}
404
406 writeSection(&Sec, Sec.Data);
407 return Error::success();
408}
409
411 // Check that sizer has already done its work
412 assert(Sec.Size == Sec.StrTabBuilder.getSize());
413 // We are free to pass an invalid pointer to writeSection as long
414 // as we don't actually write any data. The real writer class has
415 // to override this method .
416 writeSection(&Sec, {nullptr, static_cast<size_t>(Sec.Size)});
417 return Error::success();
418}
419
421 writeSection(&Sec, Sec.Contents);
422 return Error::success();
423}
424
428 memcpy(Out.getBufferStart() + Offset, HexData.data(), HexData.size());
429 Offset += HexData.size();
430}
431
433 assert(Sec.Size == Sec.StrTabBuilder.getSize());
434 std::vector<uint8_t> Data(Sec.Size);
435 Sec.StrTabBuilder.write(Data.data());
436 writeSection(&Sec, Data);
437 return Error::success();
438}
439
441 return Visitor.visit(*this);
442}
443
445 return Visitor.visit(*this);
446}
447
449 if (HasSymTabLink) {
450 assert(LinkSection == nullptr);
451 LinkSection = &SymTab;
452 }
453}
454
456 llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
457 return Error::success();
458}
459
460template <class ELFT>
462 ArrayRef<uint8_t> Compressed =
464 SmallVector<uint8_t, 128> Decompressed;
466 switch (Sec.ChType) {
467 case ELFCOMPRESS_ZLIB:
469 break;
470 case ELFCOMPRESS_ZSTD:
472 break;
473 default:
475 "--decompress-debug-sections: ch_type (" +
476 Twine(Sec.ChType) + ") of section '" +
477 Sec.Name + "' is unsupported");
478 }
479 if (auto *Reason =
482 "failed to decompress section '" + Sec.Name +
483 "': " + Reason);
484 if (Error E = compression::decompress(Type, Compressed, Decompressed,
485 static_cast<size_t>(Sec.Size)))
487 "failed to decompress section '" + Sec.Name +
488 "': " + toString(std::move(E)));
489
490 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
491 std::copy(Decompressed.begin(), Decompressed.end(), Buf);
492
493 return Error::success();
494}
495
498 "cannot write compressed section '" + Sec.Name +
499 "' ");
500}
501
503 return Visitor.visit(*this);
504}
505
507 return Visitor.visit(*this);
508}
509
511 return Visitor.visit(*this);
512}
513
515 return Visitor.visit(*this);
516}
517
519 assert((HexData.size() & 1) == 0);
520 while (!HexData.empty()) {
521 Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2)));
522 HexData = HexData.drop_front(2);
523 }
524 Size = Data.size();
525}
526
529 "cannot write compressed section '" + Sec.Name +
530 "' ");
531}
532
533template <class ELFT>
535 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
536 Elf_Chdr_Impl<ELFT> Chdr = {};
537 switch (Sec.CompressionType) {
539 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
540 return Error::success();
542 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
543 break;
545 Chdr.ch_type = ELF::ELFCOMPRESS_ZSTD;
546 break;
547 }
548 Chdr.ch_size = Sec.DecompressedSize;
549 Chdr.ch_addralign = Sec.DecompressedAlign;
550 memcpy(Buf, &Chdr, sizeof(Chdr));
551 Buf += sizeof(Chdr);
552
553 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
554 return Error::success();
555}
556
558 DebugCompressionType CompressionType,
559 bool Is64Bits)
560 : SectionBase(Sec), CompressionType(CompressionType),
561 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
563 CompressedData);
564
567 size_t ChdrSize = Is64Bits ? sizeof(object::Elf_Chdr_Impl<object::ELF64LE>)
569 Size = ChdrSize + CompressedData.size();
570 Align = 8;
571}
572
574 uint32_t ChType, uint64_t DecompressedSize,
575 uint64_t DecompressedAlign)
576 : ChType(ChType), CompressionType(DebugCompressionType::None),
577 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
578 OriginalData = CompressedData;
579}
580
582 return Visitor.visit(*this);
583}
584
586 return Visitor.visit(*this);
587}
588
590
592 return StrTabBuilder.getOffset(Name);
593}
594
596 StrTabBuilder.finalize();
597 Size = StrTabBuilder.getSize();
598}
599
601 Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) +
602 Sec.Offset);
603 return Error::success();
604}
605
607 return Visitor.visit(*this);
608}
609
611 return Visitor.visit(*this);
612}
613
614template <class ELFT>
616 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
617 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
618 return Error::success();
619}
620
622 Size = 0;
625 Link,
626 "Link field value " + Twine(Link) + " in section " + Name +
627 " is invalid",
628 "Link field value " + Twine(Link) + " in section " + Name +
629 " is not a symbol table");
630 if (!Sec)
631 return Sec.takeError();
632
633 setSymTab(*Sec);
634 Symbols->setShndxTable(this);
635 return Error::success();
636}
637
639
641 return Visitor.visit(*this);
642}
643
645 return Visitor.visit(*this);
646}
647
649 switch (Index) {
650 case SHN_ABS:
651 case SHN_COMMON:
652 return true;
653 }
654
655 if (Machine == EM_AMDGPU) {
656 return Index == SHN_AMDGPU_LDS;
657 }
658
659 if (Machine == EM_MIPS) {
660 switch (Index) {
661 case SHN_MIPS_ACOMMON:
662 case SHN_MIPS_SCOMMON:
664 return true;
665 }
666 }
667
668 if (Machine == EM_HEXAGON) {
669 switch (Index) {
675 return true;
676 }
677 }
678 return false;
679}
680
681// Large indexes force us to clarify exactly what this function should do. This
682// function should return the value that will appear in st_shndx when written
683// out.
685 if (DefinedIn != nullptr) {
687 return SHN_XINDEX;
688 return DefinedIn->Index;
689 }
690
692 // This means that we don't have a defined section but we do need to
693 // output a legitimate section index.
694 return SHN_UNDEF;
695 }
696
700 return static_cast<uint16_t>(ShndxType);
701}
702
703bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
704
705void SymbolTableSection::assignIndices() {
706 uint32_t Index = 0;
707 for (auto &Sym : Symbols) {
708 if (Sym->Index != Index)
709 IndicesChanged = true;
710 Sym->Index = Index++;
711 }
712}
713
715 SectionBase *DefinedIn, uint64_t Value,
716 uint8_t Visibility, uint16_t Shndx,
717 uint64_t SymbolSize) {
718 Symbol Sym;
719 Sym.Name = Name.str();
720 Sym.Binding = Bind;
721 Sym.Type = Type;
722 Sym.DefinedIn = DefinedIn;
723 if (DefinedIn != nullptr)
724 DefinedIn->HasSymbol = true;
725 if (DefinedIn == nullptr) {
726 if (Shndx >= SHN_LORESERVE)
727 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
728 else
729 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
730 }
731 Sym.Value = Value;
732 Sym.Visibility = Visibility;
733 Sym.Size = SymbolSize;
734 Sym.Index = Symbols.size();
735 Symbols.emplace_back(std::make_unique<Symbol>(Sym));
736 Size += this->EntrySize;
737}
738
740 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
742 SectionIndexTable = nullptr;
743 if (ToRemove(SymbolNames)) {
744 if (!AllowBrokenLinks)
745 return createStringError(
747 "string table '%s' cannot be removed because it is "
748 "referenced by the symbol table '%s'",
749 SymbolNames->Name.data(), this->Name.data());
750 SymbolNames = nullptr;
751 }
752 return removeSymbols(
753 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
754}
755
758 Callable(*Sym);
759 std::stable_partition(
760 std::begin(Symbols), std::end(Symbols),
761 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
762 assignIndices();
763}
764
766 function_ref<bool(const Symbol &)> ToRemove) {
767 Symbols.erase(
768 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
769 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
770 std::end(Symbols));
771 auto PrevSize = Size;
772 Size = Symbols.size() * EntrySize;
773 if (Size < PrevSize)
774 IndicesChanged = true;
775 assignIndices();
776 return Error::success();
777}
778
781 for (std::unique_ptr<Symbol> &Sym : Symbols)
782 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
783 Sym->DefinedIn = To;
784}
785
787 Size = 0;
790 Link,
791 "Symbol table has link index of " + Twine(Link) +
792 " which is not a valid index",
793 "Symbol table has link index of " + Twine(Link) +
794 " which is not a string table");
795 if (!Sec)
796 return Sec.takeError();
797
798 setStrTab(*Sec);
799 return Error::success();
800}
801
803 uint32_t MaxLocalIndex = 0;
804 for (std::unique_ptr<Symbol> &Sym : Symbols) {
805 Sym->NameIndex =
806 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
807 if (Sym->Binding == STB_LOCAL)
808 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
809 }
810 // Now we need to set the Link and Info fields.
811 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
812 Info = MaxLocalIndex + 1;
813}
814
816 // Reserve proper amount of space in section index table, so we can
817 // layout sections correctly. We will fill the table with correct
818 // indexes later in fillShdnxTable.
821
822 // Add all of our strings to SymbolNames so that SymbolNames has the right
823 // size before layout is decided.
824 // If the symbol names section has been removed, don't try to add strings to
825 // the table.
826 if (SymbolNames != nullptr)
827 for (std::unique_ptr<Symbol> &Sym : Symbols)
828 SymbolNames->addString(Sym->Name);
829}
830
832 if (SectionIndexTable == nullptr)
833 return;
834 // Fill section index table with real section indexes. This function must
835 // be called after assignOffsets.
836 for (const std::unique_ptr<Symbol> &Sym : Symbols) {
837 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
838 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
839 else
841 }
842}
843
846 if (Symbols.size() <= Index)
848 "invalid symbol index: " + Twine(Index));
849 return Symbols[Index].get();
850}
851
854 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index);
855 if (!Sym)
856 return Sym.takeError();
857
858 return const_cast<Symbol *>(*Sym);
859}
860
861template <class ELFT>
863 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
864 // Loop though symbols setting each entry of the symbol table.
865 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
866 Sym->st_name = Symbol->NameIndex;
867 Sym->st_value = Symbol->Value;
868 Sym->st_size = Symbol->Size;
869 Sym->st_other = Symbol->Visibility;
870 Sym->setBinding(Symbol->Binding);
871 Sym->setType(Symbol->Type);
872 Sym->st_shndx = Symbol->getShndx();
873 ++Sym;
874 }
875 return Error::success();
876}
877
879 return Visitor.visit(*this);
880}
881
883 return Visitor.visit(*this);
884}
885
887 switch (Type) {
888 case SHT_REL:
889 return ".rel";
890 case SHT_RELA:
891 return ".rela";
892 case SHT_CREL:
893 return ".crel";
894 default:
895 llvm_unreachable("not a relocation section");
896 }
897}
898
900 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
902 if (!AllowBrokenLinks)
903 return createStringError(
905 "symbol table '%s' cannot be removed because it is "
906 "referenced by the relocation section '%s'",
907 Symbols->Name.data(), this->Name.data());
908 Symbols = nullptr;
909 }
910
911 for (const Relocation &R : Relocations) {
912 if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn ||
913 !ToRemove(R.RelocSymbol->DefinedIn))
914 continue;
916 "section '%s' cannot be removed: (%s+0x%" PRIx64
917 ") has relocation against symbol '%s'",
918 R.RelocSymbol->DefinedIn->Name.data(),
919 SecToApplyRel->Name.data(), R.Offset,
920 R.RelocSymbol->Name.c_str());
921 }
922
923 return Error::success();
924}
925
926template <class SymTabType>
928 SectionTableRef SecTable) {
929 if (Link != SHN_UNDEF) {
930 Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>(
931 Link,
932 "Link field value " + Twine(Link) + " in section " + Name +
933 " is invalid",
934 "Link field value " + Twine(Link) + " in section " + Name +
935 " is not a symbol table");
936 if (!Sec)
937 return Sec.takeError();
938
939 setSymTab(*Sec);
940 }
941
942 if (Info != SHN_UNDEF) {
944 SecTable.getSection(Info, "Info field value " + Twine(Info) +
945 " in section " + Name + " is invalid");
946 if (!Sec)
947 return Sec.takeError();
948
949 setSection(*Sec);
950 } else
951 setSection(nullptr);
952
953 return Error::success();
954}
955
956template <class SymTabType>
958 this->Link = Symbols ? Symbols->Index : 0;
959
960 if (SecToApplyRel != nullptr)
961 this->Info = SecToApplyRel->Index;
962}
963
964template <class ELFT>
966
967template <class ELFT>
968static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
969 Rela.r_addend = Addend;
970}
971
972template <class RelRange, class T>
973static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) {
974 for (const auto &Reloc : Relocations) {
975 Buf->r_offset = Reloc.Offset;
976 setAddend(*Buf, Reloc.Addend);
977 Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0,
978 Reloc.Type, IsMips64EL);
979 ++Buf;
980 }
981}
982
983template <class ELFT>
985 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
986 if (Sec.Type == SHT_CREL) {
987 auto Content = encodeCrel<ELFT::Is64Bits>(Sec.Relocations);
988 memcpy(Buf, Content.data(), Content.size());
989 } else if (Sec.Type == SHT_REL) {
990 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf),
991 Sec.getObject().IsMips64EL);
992 } else {
993 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf),
994 Sec.getObject().IsMips64EL);
995 }
996 return Error::success();
997}
998
1000 return Visitor.visit(*this);
1001}
1002
1004 return Visitor.visit(*this);
1005}
1006
1008 function_ref<bool(const Symbol &)> ToRemove) {
1009 for (const Relocation &Reloc : Relocations)
1010 if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol))
1011 return createStringError(
1013 "not stripping symbol '%s' because it is named in a relocation",
1014 Reloc.RelocSymbol->Name.data());
1015 return Error::success();
1016}
1017
1019 for (const Relocation &Reloc : Relocations)
1020 if (Reloc.RelocSymbol)
1021 Reloc.RelocSymbol->Referenced = true;
1022}
1023
1026 // Update the target section if it was replaced.
1027 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
1028 SecToApplyRel = To;
1029}
1030
1032 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
1033 return Error::success();
1034}
1035
1037 return Visitor.visit(*this);
1038}
1039
1041 return Visitor.visit(*this);
1042}
1043
1045 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1046 if (ToRemove(Symbols)) {
1047 if (!AllowBrokenLinks)
1048 return createStringError(
1050 "symbol table '%s' cannot be removed because it is "
1051 "referenced by the relocation section '%s'",
1052 Symbols->Name.data(), this->Name.data());
1053 Symbols = nullptr;
1054 }
1055
1056 // SecToApplyRel contains a section referenced by sh_info field. It keeps
1057 // a section to which the relocation section applies. When we remove any
1058 // sections we also remove their relocation sections. Since we do that much
1059 // earlier, this assert should never be triggered.
1061 return Error::success();
1062}
1063
1065 bool AllowBrokenDependency,
1066 function_ref<bool(const SectionBase *)> ToRemove) {
1067 if (ToRemove(LinkSection)) {
1068 if (!AllowBrokenDependency)
1070 "section '%s' cannot be removed because it is "
1071 "referenced by the section '%s'",
1072 LinkSection->Name.data(), this->Name.data());
1073 LinkSection = nullptr;
1074 }
1075 return Error::success();
1076}
1077
1079 this->Info = Sym ? Sym->Index : 0;
1080 this->Link = SymTab ? SymTab->Index : 0;
1081 // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global
1082 // status is not part of the equation. If Sym is localized, the intention is
1083 // likely to make the group fully localized. Drop GRP_COMDAT to suppress
1084 // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc
1085 if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL)
1086 this->FlagWord &= ~GRP_COMDAT;
1087}
1088
1090 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1091 if (ToRemove(SymTab)) {
1092 if (!AllowBrokenLinks)
1093 return createStringError(
1095 "section '.symtab' cannot be removed because it is "
1096 "referenced by the group section '%s'",
1097 this->Name.data());
1098 SymTab = nullptr;
1099 Sym = nullptr;
1100 }
1101 llvm::erase_if(GroupMembers, ToRemove);
1102 return Error::success();
1103}
1104
1106 if (ToRemove(*Sym))
1108 "symbol '%s' cannot be removed because it is "
1109 "referenced by the section '%s[%d]'",
1110 Sym->Name.data(), this->Name.data(), this->Index);
1111 return Error::success();
1112}
1113
1115 if (Sym)
1116 Sym->Referenced = true;
1117}
1118
1121 for (SectionBase *&Sec : GroupMembers)
1122 if (SectionBase *To = FromTo.lookup(Sec))
1123 Sec = To;
1124}
1125
1127 // As the header section of the group is removed, drop the Group flag in its
1128 // former members.
1129 for (SectionBase *Sec : GroupMembers)
1130 Sec->Flags &= ~SHF_GROUP;
1131}
1132
1134 if (Link == ELF::SHN_UNDEF)
1135 return Error::success();
1136
1138 SecTable.getSection(Link, "Link field value " + Twine(Link) +
1139 " in section " + Name + " is invalid");
1140 if (!Sec)
1141 return Sec.takeError();
1142
1143 LinkSection = *Sec;
1144
1145 if (LinkSection->Type == ELF::SHT_SYMTAB) {
1146 HasSymTabLink = true;
1147 LinkSection = nullptr;
1148 }
1149
1150 return Error::success();
1151}
1152
1153void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
1154
1155void GnuDebugLinkSection::init(StringRef File) {
1156 FileName = sys::path::filename(File);
1157 // The format for the .gnu_debuglink starts with the file name and is
1158 // followed by a null terminator and then the CRC32 of the file. The CRC32
1159 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
1160 // byte, and then finally push the size to alignment and add 4.
1161 Size = alignTo(FileName.size() + 1, 4) + 4;
1162 // The CRC32 will only be aligned if we align the whole section.
1163 Align = 4;
1165 Name = ".gnu_debuglink";
1166 // For sections not found in segments, OriginalOffset is only used to
1167 // establish the order that sections should go in. By using the maximum
1168 // possible offset we cause this section to wind up at the end.
1169 OriginalOffset = std::numeric_limits<uint64_t>::max();
1170}
1171
1173 uint32_t PrecomputedCRC)
1174 : FileName(File), CRC32(PrecomputedCRC) {
1175 init(File);
1176}
1177
1178template <class ELFT>
1180 unsigned char *Buf =
1181 reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
1182 Elf_Word *CRC =
1183 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
1184 *CRC = Sec.CRC32;
1185 llvm::copy(Sec.FileName, Buf);
1186 return Error::success();
1187}
1188
1190 return Visitor.visit(*this);
1191}
1192
1194 return Visitor.visit(*this);
1195}
1196
1197template <class ELFT>
1199 ELF::Elf32_Word *Buf =
1200 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
1201 endian::write32<ELFT::Endianness>(Buf++, Sec.FlagWord);
1202 for (SectionBase *S : Sec.GroupMembers)
1203 endian::write32<ELFT::Endianness>(Buf++, S->Index);
1204 return Error::success();
1205}
1206
1208 return Visitor.visit(*this);
1209}
1210
1212 return Visitor.visit(*this);
1213}
1214
1215// Returns true IFF a section is wholly inside the range of a segment
1216static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) {
1217 // If a section is empty it should be treated like it has a size of 1. This is
1218 // to clarify the case when an empty section lies on a boundary between two
1219 // segments and ensures that the section "belongs" to the second segment and
1220 // not the first.
1221 uint64_t SecSize = Sec.Size ? Sec.Size : 1;
1222
1223 // Ignore just added sections.
1224 if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max())
1225 return false;
1226
1227 if (Sec.Type == SHT_NOBITS) {
1228 if (!(Sec.Flags & SHF_ALLOC))
1229 return false;
1230
1231 bool SectionIsTLS = Sec.Flags & SHF_TLS;
1232 bool SegmentIsTLS = Seg.Type == PT_TLS;
1233 if (SectionIsTLS != SegmentIsTLS)
1234 return false;
1235
1236 return Seg.VAddr <= Sec.Addr &&
1237 Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize;
1238 }
1239
1240 return Seg.Offset <= Sec.OriginalOffset &&
1241 Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize;
1242}
1243
1244// Returns true IFF a segment's original offset is inside of another segment's
1245// range.
1246static bool segmentOverlapsSegment(const Segment &Child,
1247 const Segment &Parent) {
1248
1249 return Parent.OriginalOffset <= Child.OriginalOffset &&
1250 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
1251}
1252
1253static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
1254 // Any segment without a parent segment should come before a segment
1255 // that has a parent segment.
1256 if (A->OriginalOffset < B->OriginalOffset)
1257 return true;
1258 if (A->OriginalOffset > B->OriginalOffset)
1259 return false;
1260 // If alignments are different, the one with a smaller alignment cannot be the
1261 // parent; otherwise, layoutSegments will not respect the larger alignment
1262 // requirement. This rule ensures that PT_LOAD/PT_INTERP/PT_GNU_RELRO/PT_TLS
1263 // segments at the same offset will be aligned correctly.
1264 if (A->Align != B->Align)
1265 return A->Align > B->Align;
1266 return A->Index < B->Index;
1267}
1268
1270 Obj->Flags = 0x0;
1271 Obj->Type = ET_REL;
1272 Obj->OSABI = ELFOSABI_NONE;
1273 Obj->ABIVersion = 0;
1274 Obj->Entry = 0x0;
1275 Obj->Machine = EM_NONE;
1276 Obj->Version = 1;
1277}
1278
1279void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
1280
1282 auto &StrTab = Obj->addSection<StringTableSection>();
1283 StrTab.Name = ".strtab";
1284
1285 Obj->SectionNames = &StrTab;
1286 return &StrTab;
1287}
1288
1290 auto &SymTab = Obj->addSection<SymbolTableSection>();
1291
1292 SymTab.Name = ".symtab";
1293 SymTab.Link = StrTab->Index;
1294
1295 // The symbol table always needs a null symbol
1296 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
1297
1298 Obj->SymbolTable = &SymTab;
1299 return &SymTab;
1300}
1301
1303 for (SectionBase &Sec : Obj->sections())
1304 if (Error Err = Sec.initialize(Obj->sections()))
1305 return Err;
1306
1307 return Error::success();
1308}
1309
1310void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
1311 auto Data = ArrayRef<uint8_t>(
1312 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
1313 MemBuf->getBufferSize());
1314 auto &DataSection = Obj->addSection<Section>(Data);
1315 DataSection.Name = ".data";
1316 DataSection.Type = ELF::SHT_PROGBITS;
1317 DataSection.Size = Data.size();
1318 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1319
1320 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
1321 std::replace_if(
1322 std::begin(SanitizedFilename), std::end(SanitizedFilename),
1323 [](char C) { return !isAlnum(C); }, '_');
1324 Twine Prefix = Twine("_binary_") + SanitizedFilename;
1325
1326 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
1327 /*Value=*/0, NewSymbolVisibility, 0, 0);
1328 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
1329 /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
1330 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
1331 /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
1332 0);
1333}
1334
1338
1340 if (Error Err = initSections())
1341 return std::move(Err);
1342 addData(SymTab);
1343
1344 return std::move(Obj);
1345}
1346
1347// Adds sections from IHEX data file. Data should have been
1348// fully validated by this time.
1349void IHexELFBuilder::addDataSections() {
1350 OwnedDataSection *Section = nullptr;
1351 uint64_t SegmentAddr = 0, BaseAddr = 0;
1352 uint32_t SecNo = 1;
1353
1354 for (const IHexRecord &R : Records) {
1355 uint64_t RecAddr;
1356 switch (R.Type) {
1357 case IHexRecord::Data:
1358 // Ignore empty data records
1359 if (R.HexData.empty())
1360 continue;
1361 RecAddr = R.Addr + SegmentAddr + BaseAddr;
1362 if (!Section || Section->Addr + Section->Size != RecAddr) {
1363 // OriginalOffset field is only used to sort sections before layout, so
1364 // instead of keeping track of real offsets in IHEX file, and as
1365 // layoutSections() and layoutSectionsForOnlyKeepDebug() use
1366 // llvm::stable_sort(), we can just set it to a constant (zero).
1367 Section = &Obj->addSection<OwnedDataSection>(
1368 ".sec" + std::to_string(SecNo), RecAddr,
1370 SecNo++;
1371 }
1372 Section->appendHexData(R.HexData);
1373 break;
1375 break;
1377 // 20-bit segment address.
1378 SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
1379 break;
1382 Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
1383 assert(Obj->Entry <= 0xFFFFFU);
1384 break;
1386 // 16-31 bits of linear base address
1387 BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
1388 break;
1389 default:
1390 llvm_unreachable("unknown record type");
1391 }
1392 }
1393}
1394
1398 StringTableSection *StrTab = addStrTab();
1399 addSymTab(StrTab);
1400 if (Error Err = initSections())
1401 return std::move(Err);
1402 addDataSections();
1403
1404 return std::move(Obj);
1405}
1406
1407template <class ELFT>
1409 std::optional<StringRef> ExtractPartition)
1410 : ElfFile(ElfObj.getELFFile()), Obj(Obj),
1411 ExtractPartition(ExtractPartition) {
1412 Obj.IsMips64EL = ElfFile.isMips64EL();
1413}
1414
1415template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
1416 for (Segment &Parent : Obj.segments()) {
1417 // Every segment will overlap with itself but we don't want a segment to
1418 // be its own parent so we avoid that situation.
1419 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
1420 // We want a canonical "most parental" segment but this requires
1421 // inspecting the ParentSegment.
1422 if (compareSegmentsByOffset(&Parent, &Child))
1423 if (Child.ParentSegment == nullptr ||
1424 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
1425 Child.ParentSegment = &Parent;
1426 }
1427 }
1428 }
1429}
1430
1431template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
1432 if (!ExtractPartition)
1433 return Error::success();
1434
1435 for (const SectionBase &Sec : Obj.sections()) {
1436 if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
1437 EhdrOffset = Sec.Offset;
1438 return Error::success();
1439 }
1440 }
1442 "could not find partition named '" +
1443 *ExtractPartition + "'");
1444}
1445
1446template <class ELFT>
1448 uint32_t Index = 0;
1449
1451 HeadersFile.program_headers();
1452 if (!Headers)
1453 return Headers.takeError();
1454
1455 for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
1456 if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
1457 return createStringError(
1459 "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
1460 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
1461 " goes past the end of the file");
1462
1463 ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
1464 (size_t)Phdr.p_filesz};
1465 Segment &Seg = Obj.addSegment(Data);
1466 Seg.Type = Phdr.p_type;
1467 Seg.Flags = Phdr.p_flags;
1468 Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
1469 Seg.Offset = Phdr.p_offset + EhdrOffset;
1470 Seg.VAddr = Phdr.p_vaddr;
1471 Seg.PAddr = Phdr.p_paddr;
1472 Seg.FileSize = Phdr.p_filesz;
1473 Seg.MemSize = Phdr.p_memsz;
1474 Seg.Align = Phdr.p_align;
1475 Seg.Index = Index++;
1476 for (SectionBase &Sec : Obj.sections())
1477 if (sectionWithinSegment(Sec, Seg)) {
1478 Seg.addSection(&Sec);
1479 if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
1480 Sec.ParentSegment = &Seg;
1481 }
1482 }
1483
1484 auto &ElfHdr = Obj.ElfHdrSegment;
1485 ElfHdr.Index = Index++;
1486 ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
1487
1488 const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
1489 auto &PrHdr = Obj.ProgramHdrSegment;
1490 PrHdr.Type = PT_PHDR;
1491 PrHdr.Flags = 0;
1492 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
1493 // Whereas this works automatically for ElfHdr, here OriginalOffset is
1494 // always non-zero and to ensure the equation we assign the same value to
1495 // VAddr as well.
1496 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
1497 PrHdr.PAddr = 0;
1498 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
1499 // The spec requires us to naturally align all the fields.
1500 PrHdr.Align = sizeof(Elf_Addr);
1501 PrHdr.Index = Index++;
1502
1503 // Now we do an O(n^2) loop through the segments in order to match up
1504 // segments.
1505 for (Segment &Child : Obj.segments())
1506 setParentSegment(Child);
1507 setParentSegment(ElfHdr);
1508 setParentSegment(PrHdr);
1509
1510 return Error::success();
1511}
1512
1513template <class ELFT>
1515 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
1517 "invalid alignment " + Twine(GroupSec->Align) +
1518 " of group section '" + GroupSec->Name + "'");
1519 SectionTableRef SecTable = Obj.sections();
1520 if (GroupSec->Link != SHN_UNDEF) {
1521 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1522 GroupSec->Link,
1523 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1524 GroupSec->Name + "' is invalid",
1525 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1526 GroupSec->Name + "' is not a symbol table");
1527 if (!SymTab)
1528 return SymTab.takeError();
1529
1530 Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
1531 if (!Sym)
1533 "info field value '" + Twine(GroupSec->Info) +
1534 "' in section '" + GroupSec->Name +
1535 "' is not a valid symbol index");
1536 GroupSec->setSymTab(*SymTab);
1537 GroupSec->setSymbol(*Sym);
1538 }
1539 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1540 GroupSec->Contents.empty())
1542 "the content of the section " + GroupSec->Name +
1543 " is malformed");
1544 const ELF::Elf32_Word *Word =
1545 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1546 const ELF::Elf32_Word *End =
1547 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1548 GroupSec->setFlagWord(endian::read32<ELFT::Endianness>(Word++));
1549 for (; Word != End; ++Word) {
1550 uint32_t Index = support::endian::read32<ELFT::Endianness>(Word);
1551 Expected<SectionBase *> Sec = SecTable.getSection(
1552 Index, "group member index " + Twine(Index) + " in section '" +
1553 GroupSec->Name + "' is invalid");
1554 if (!Sec)
1555 return Sec.takeError();
1556
1557 GroupSec->addMember(*Sec);
1558 }
1559
1560 return Error::success();
1561}
1562
1563template <class ELFT>
1565 Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
1566 if (!Shdr)
1567 return Shdr.takeError();
1568
1569 Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
1570 if (!StrTabData)
1571 return StrTabData.takeError();
1572
1573 ArrayRef<Elf_Word> ShndxData;
1574
1576 ElfFile.symbols(*Shdr);
1577 if (!Symbols)
1578 return Symbols.takeError();
1579
1580 for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
1581 SectionBase *DefSection = nullptr;
1582
1583 Expected<StringRef> Name = Sym.getName(*StrTabData);
1584 if (!Name)
1585 return Name.takeError();
1586
1587 if (Sym.st_shndx == SHN_XINDEX) {
1588 if (SymTab->getShndxTable() == nullptr)
1590 "symbol '" + *Name +
1591 "' has index SHN_XINDEX but no "
1592 "SHT_SYMTAB_SHNDX section exists");
1593 if (ShndxData.data() == nullptr) {
1595 ElfFile.getSection(SymTab->getShndxTable()->Index);
1596 if (!ShndxSec)
1597 return ShndxSec.takeError();
1598
1600 ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
1601 if (!Data)
1602 return Data.takeError();
1603
1604 ShndxData = *Data;
1605 if (ShndxData.size() != Symbols->size())
1606 return createStringError(
1608 "symbol section index table does not have the same number of "
1609 "entries as the symbol table");
1610 }
1611 Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
1612 Expected<SectionBase *> Sec = Obj.sections().getSection(
1613 Index,
1614 "symbol '" + *Name + "' has invalid section index " + Twine(Index));
1615 if (!Sec)
1616 return Sec.takeError();
1617
1618 DefSection = *Sec;
1619 } else if (Sym.st_shndx >= SHN_LORESERVE) {
1620 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
1621 return createStringError(
1623 "symbol '" + *Name +
1624 "' has unsupported value greater than or equal "
1625 "to SHN_LORESERVE: " +
1626 Twine(Sym.st_shndx));
1627 }
1628 } else if (Sym.st_shndx != SHN_UNDEF) {
1629 Expected<SectionBase *> Sec = Obj.sections().getSection(
1630 Sym.st_shndx, "symbol '" + *Name +
1631 "' is defined has invalid section index " +
1632 Twine(Sym.st_shndx));
1633 if (!Sec)
1634 return Sec.takeError();
1635
1636 DefSection = *Sec;
1637 }
1638
1639 SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
1640 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
1641 }
1642
1643 return Error::success();
1644}
1645
1646template <class ELFT>
1648
1649template <class ELFT>
1650static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1651 ToSet = Rela.r_addend;
1652}
1653
1654template <class T>
1655static Error initRelocations(RelocationSection *Relocs, T RelRange) {
1656 for (const auto &Rel : RelRange) {
1657 Relocation ToAdd;
1658 ToAdd.Offset = Rel.r_offset;
1659 getAddend(ToAdd.Addend, Rel);
1660 ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
1661
1662 if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
1663 if (!Relocs->getObject().SymbolTable)
1664 return createStringError(
1666 "'" + Relocs->Name + "': relocation references symbol with index " +
1667 Twine(Sym) + ", but there is no symbol table");
1668 Expected<Symbol *> SymByIndex =
1670 if (!SymByIndex)
1671 return SymByIndex.takeError();
1672
1673 ToAdd.RelocSymbol = *SymByIndex;
1674 }
1675
1676 Relocs->addRelocation(ToAdd);
1677 }
1678
1679 return Error::success();
1680}
1681
1683 Twine ErrMsg) {
1684 if (Index == SHN_UNDEF || Index > Sections.size())
1686 return Sections[Index - 1].get();
1687}
1688
1689template <class T>
1691 Twine IndexErrMsg,
1692 Twine TypeErrMsg) {
1693 Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
1694 if (!BaseSec)
1695 return BaseSec.takeError();
1696
1697 if (T *Sec = dyn_cast<T>(*BaseSec))
1698 return Sec;
1699
1700 return createStringError(errc::invalid_argument, TypeErrMsg);
1701}
1702
1703template <class ELFT>
1705 switch (Shdr.sh_type) {
1706 case SHT_REL:
1707 case SHT_RELA:
1708 case SHT_CREL:
1709 if (Shdr.sh_flags & SHF_ALLOC) {
1710 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1711 return Obj.addSection<DynamicRelocationSection>(*Data);
1712 else
1713 return Data.takeError();
1714 }
1715 return Obj.addSection<RelocationSection>(Obj);
1716 case SHT_STRTAB:
1717 // If a string table is allocated we don't want to mess with it. That would
1718 // mean altering the memory image. There are no special link types or
1719 // anything so we can just use a Section.
1720 if (Shdr.sh_flags & SHF_ALLOC) {
1721 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1722 return Obj.addSection<Section>(*Data);
1723 else
1724 return Data.takeError();
1725 }
1726 return Obj.addSection<StringTableSection>();
1727 case SHT_HASH:
1728 case SHT_GNU_HASH:
1729 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1730 // Because of this we don't need to mess with the hash tables either.
1731 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1732 return Obj.addSection<Section>(*Data);
1733 else
1734 return Data.takeError();
1735 case SHT_GROUP:
1736 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1737 return Obj.addSection<GroupSection>(*Data);
1738 else
1739 return Data.takeError();
1740 case SHT_DYNSYM:
1741 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1742 return Obj.addSection<DynamicSymbolTableSection>(*Data);
1743 else
1744 return Data.takeError();
1745 case SHT_DYNAMIC:
1746 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1747 return Obj.addSection<DynamicSection>(*Data);
1748 else
1749 return Data.takeError();
1750 case SHT_SYMTAB: {
1751 // Multiple SHT_SYMTAB sections are forbidden by the ELF gABI.
1752 if (Obj.SymbolTable != nullptr)
1754 "found multiple SHT_SYMTAB sections");
1755 auto &SymTab = Obj.addSection<SymbolTableSection>();
1756 Obj.SymbolTable = &SymTab;
1757 return SymTab;
1758 }
1759 case SHT_SYMTAB_SHNDX: {
1760 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1761 Obj.SectionIndexTable = &ShndxSection;
1762 return ShndxSection;
1763 }
1764 case SHT_NOBITS:
1765 return Obj.addSection<Section>(ArrayRef<uint8_t>());
1766 default: {
1767 Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
1768 if (!Data)
1769 return Data.takeError();
1770
1771 Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
1772 if (!Name)
1773 return Name.takeError();
1774
1775 if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
1776 return Obj.addSection<Section>(*Data);
1777 auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
1778 return Obj.addSection<CompressedSection>(CompressedSection(
1779 *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign));
1780 }
1781 }
1782}
1783
1784template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
1785 uint32_t Index = 0;
1787 ElfFile.sections();
1788 if (!Sections)
1789 return Sections.takeError();
1790
1791 for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
1792 if (Index == 0) {
1793 ++Index;
1794 continue;
1795 }
1796 Expected<SectionBase &> Sec = makeSection(Shdr);
1797 if (!Sec)
1798 return Sec.takeError();
1799
1800 Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
1801 if (!SecName)
1802 return SecName.takeError();
1803 Sec->Name = SecName->str();
1804 Sec->Type = Sec->OriginalType = Shdr.sh_type;
1805 Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
1806 Sec->Addr = Shdr.sh_addr;
1807 Sec->Offset = Shdr.sh_offset;
1808 Sec->OriginalOffset = Shdr.sh_offset;
1809 Sec->Size = Shdr.sh_size;
1810 Sec->Link = Shdr.sh_link;
1811 Sec->Info = Shdr.sh_info;
1812 Sec->Align = Shdr.sh_addralign;
1813 Sec->EntrySize = Shdr.sh_entsize;
1814 Sec->Index = Index++;
1815 Sec->OriginalIndex = Sec->Index;
1816 Sec->OriginalData = ArrayRef<uint8_t>(
1817 ElfFile.base() + Shdr.sh_offset,
1818 (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
1819 }
1820
1821 return Error::success();
1822}
1823
1824template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
1825 uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
1826 if (ShstrIndex == SHN_XINDEX) {
1827 Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
1828 if (!Sec)
1829 return Sec.takeError();
1830
1831 ShstrIndex = (*Sec)->sh_link;
1832 }
1833
1834 if (ShstrIndex == SHN_UNDEF)
1835 Obj.HadShdrs = false;
1836 else {
1838 Obj.sections().template getSectionOfType<StringTableSection>(
1839 ShstrIndex,
1840 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1841 " is invalid",
1842 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1843 " does not reference a string table");
1844 if (!Sec)
1845 return Sec.takeError();
1846
1847 Obj.SectionNames = *Sec;
1848 }
1849
1850 // If a section index table exists we'll need to initialize it before we
1851 // initialize the symbol table because the symbol table might need to
1852 // reference it.
1853 if (Obj.SectionIndexTable)
1854 if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
1855 return Err;
1856
1857 // Now that all of the sections have been added we can fill out some extra
1858 // details about symbol tables. We need the symbol table filled out before
1859 // any relocations.
1860 if (Obj.SymbolTable) {
1861 if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
1862 return Err;
1863 if (Error Err = initSymbolTable(Obj.SymbolTable))
1864 return Err;
1865 } else if (EnsureSymtab) {
1866 if (Error Err = Obj.addNewSymbolTable())
1867 return Err;
1868 }
1869
1870 // Now that all sections and symbols have been added we can add
1871 // relocations that reference symbols and set the link and info fields for
1872 // relocation sections.
1873 for (SectionBase &Sec : Obj.sections()) {
1874 if (&Sec == Obj.SymbolTable)
1875 continue;
1876 if (Error Err = Sec.initialize(Obj.sections()))
1877 return Err;
1878 if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
1880 ElfFile.sections();
1881 if (!Sections)
1882 return Sections.takeError();
1883
1884 const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
1885 Sections->begin() + RelSec->Index;
1886 if (RelSec->Type == SHT_CREL) {
1887 auto RelsOrRelas = ElfFile.crels(*Shdr);
1888 if (!RelsOrRelas)
1889 return RelsOrRelas.takeError();
1890 if (Error Err = initRelocations(RelSec, RelsOrRelas->first))
1891 return Err;
1892 if (Error Err = initRelocations(RelSec, RelsOrRelas->second))
1893 return Err;
1894 } else if (RelSec->Type == SHT_REL) {
1896 ElfFile.rels(*Shdr);
1897 if (!Rels)
1898 return Rels.takeError();
1899
1900 if (Error Err = initRelocations(RelSec, *Rels))
1901 return Err;
1902 } else {
1904 ElfFile.relas(*Shdr);
1905 if (!Relas)
1906 return Relas.takeError();
1907
1908 if (Error Err = initRelocations(RelSec, *Relas))
1909 return Err;
1910 }
1911 } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
1912 if (Error Err = initGroupSection(GroupSec))
1913 return Err;
1914 }
1915 }
1916
1917 return Error::success();
1918}
1919
1920template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
1921 if (Error E = readSectionHeaders())
1922 return E;
1923 if (Error E = findEhdrOffset())
1924 return E;
1925
1926 // The ELFFile whose ELF headers and program headers are copied into the
1927 // output file. Normally the same as ElfFile, but if we're extracting a
1928 // loadable partition it will point to the partition's headers.
1929 Expected<ELFFile<ELFT>> HeadersFile = ELFFile<ELFT>::create(toStringRef(
1930 {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
1931 if (!HeadersFile)
1932 return HeadersFile.takeError();
1933
1934 const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
1935 Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64;
1936 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1937 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
1938 Obj.Type = Ehdr.e_type;
1939 Obj.Machine = Ehdr.e_machine;
1940 Obj.Version = Ehdr.e_version;
1941 Obj.Entry = Ehdr.e_entry;
1942 Obj.Flags = Ehdr.e_flags;
1943
1944 if (Error E = readSections(EnsureSymtab))
1945 return E;
1946 return readProgramHeaders(*HeadersFile);
1947}
1948
1949Writer::~Writer() = default;
1950
1951Reader::~Reader() = default;
1952
1954BinaryReader::create(bool /*EnsureSymtab*/) const {
1955 return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
1956}
1957
1958Expected<std::vector<IHexRecord>> IHexReader::parse() const {
1960 std::vector<IHexRecord> Records;
1961 bool HasSections = false;
1962
1963 MemBuf->getBuffer().split(Lines, '\n');
1964 Records.reserve(Lines.size());
1965 for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
1966 StringRef Line = Lines[LineNo - 1].trim();
1967 if (Line.empty())
1968 continue;
1969
1971 if (!R)
1972 return parseError(LineNo, R.takeError());
1973 if (R->Type == IHexRecord::EndOfFile)
1974 break;
1975 HasSections |= (R->Type == IHexRecord::Data);
1976 Records.push_back(*R);
1977 }
1978 if (!HasSections)
1979 return parseError(-1U, "no sections");
1980
1981 return std::move(Records);
1982}
1983
1985IHexReader::create(bool /*EnsureSymtab*/) const {
1987 if (!Records)
1988 return Records.takeError();
1989
1990 return IHexELFBuilder(*Records).build();
1991}
1992
1994 auto Obj = std::make_unique<Object>();
1995 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1996 ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
1997 if (Error Err = Builder.build(EnsureSymtab))
1998 return std::move(Err);
1999 return std::move(Obj);
2000 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
2001 ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
2002 if (Error Err = Builder.build(EnsureSymtab))
2003 return std::move(Err);
2004 return std::move(Obj);
2005 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
2006 ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
2007 if (Error Err = Builder.build(EnsureSymtab))
2008 return std::move(Err);
2009 return std::move(Obj);
2010 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
2011 ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
2012 if (Error Err = Builder.build(EnsureSymtab))
2013 return std::move(Err);
2014 return std::move(Obj);
2015 }
2016 return createStringError(errc::invalid_argument, "invalid file type");
2017}
2018
2019template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
2020 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
2021 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
2022 Ehdr.e_ident[EI_MAG0] = 0x7f;
2023 Ehdr.e_ident[EI_MAG1] = 'E';
2024 Ehdr.e_ident[EI_MAG2] = 'L';
2025 Ehdr.e_ident[EI_MAG3] = 'F';
2026 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
2027 Ehdr.e_ident[EI_DATA] =
2028 ELFT::Endianness == llvm::endianness::big ? ELFDATA2MSB : ELFDATA2LSB;
2029 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
2030 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
2031 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
2032
2033 Ehdr.e_type = Obj.Type;
2034 Ehdr.e_machine = Obj.Machine;
2035 Ehdr.e_version = Obj.Version;
2036 Ehdr.e_entry = Obj.Entry;
2037 // We have to use the fully-qualified name llvm::size
2038 // since some compilers complain on ambiguous resolution.
2039 Ehdr.e_phnum = llvm::size(Obj.segments());
2040 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
2041 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
2042 Ehdr.e_flags = Obj.Flags;
2043 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
2044 if (WriteSectionHeaders && Obj.sections().size() != 0) {
2045 Ehdr.e_shentsize = sizeof(Elf_Shdr);
2046 Ehdr.e_shoff = Obj.SHOff;
2047 // """
2048 // If the number of sections is greater than or equal to
2049 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
2050 // number of section header table entries is contained in the sh_size field
2051 // of the section header at index 0.
2052 // """
2053 auto Shnum = Obj.sections().size() + 1;
2054 if (Shnum >= SHN_LORESERVE)
2055 Ehdr.e_shnum = 0;
2056 else
2057 Ehdr.e_shnum = Shnum;
2058 // """
2059 // If the section name string table section index is greater than or equal
2060 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
2061 // and the actual index of the section name string table section is
2062 // contained in the sh_link field of the section header at index 0.
2063 // """
2064 if (Obj.SectionNames->Index >= SHN_LORESERVE)
2065 Ehdr.e_shstrndx = SHN_XINDEX;
2066 else
2067 Ehdr.e_shstrndx = Obj.SectionNames->Index;
2068 } else {
2069 Ehdr.e_shentsize = 0;
2070 Ehdr.e_shoff = 0;
2071 Ehdr.e_shnum = 0;
2072 Ehdr.e_shstrndx = 0;
2073 }
2074}
2075
2076template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
2077 for (auto &Seg : Obj.segments())
2078 writePhdr(Seg);
2079}
2080
2081template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
2082 // This reference serves to write the dummy section header at the begining
2083 // of the file. It is not used for anything else
2084 Elf_Shdr &Shdr =
2085 *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
2086 Shdr.sh_name = 0;
2087 Shdr.sh_type = SHT_NULL;
2088 Shdr.sh_flags = 0;
2089 Shdr.sh_addr = 0;
2090 Shdr.sh_offset = 0;
2091 // See writeEhdr for why we do this.
2092 uint64_t Shnum = Obj.sections().size() + 1;
2093 if (Shnum >= SHN_LORESERVE)
2094 Shdr.sh_size = Shnum;
2095 else
2096 Shdr.sh_size = 0;
2097 // See writeEhdr for why we do this.
2098 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
2099 Shdr.sh_link = Obj.SectionNames->Index;
2100 else
2101 Shdr.sh_link = 0;
2102 Shdr.sh_info = 0;
2103 Shdr.sh_addralign = 0;
2104 Shdr.sh_entsize = 0;
2105
2106 for (SectionBase &Sec : Obj.sections())
2107 writeShdr(Sec);
2108}
2109
2110template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
2111 for (SectionBase &Sec : Obj.sections())
2112 // Segments are responsible for writing their contents, so only write the
2113 // section data if the section is not in a segment. Note that this renders
2114 // sections in segments effectively immutable.
2115 if (Sec.ParentSegment == nullptr)
2116 if (Error Err = Sec.accept(*SecWriter))
2117 return Err;
2118
2119 return Error::success();
2120}
2121
2122template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
2123 for (Segment &Seg : Obj.segments()) {
2124 size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
2125 std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
2126 Size);
2127 }
2128
2129 for (const auto &it : Obj.getUpdatedSections()) {
2130 SectionBase *Sec = it.first;
2131 ArrayRef<uint8_t> Data = it.second;
2132
2133 auto *Parent = Sec->ParentSegment;
2134 assert(Parent && "This section should've been part of a segment.");
2136 Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2137 llvm::copy(Data, Buf->getBufferStart() + Offset);
2138 }
2139
2140 // Iterate over removed sections and overwrite their old data with zeroes.
2141 for (auto &Sec : Obj.removedSections()) {
2142 Segment *Parent = Sec.ParentSegment;
2143 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
2144 continue;
2146 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2147 std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
2148 }
2149}
2150
2151template <class ELFT>
2153 bool OnlyKeepDebug)
2154 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
2155 OnlyKeepDebug(OnlyKeepDebug) {}
2156
2158 auto It = llvm::find_if(Sections,
2159 [&](const SecPtr &Sec) { return Sec->Name == Name; });
2160 if (It == Sections.end())
2161 return createStringError(errc::invalid_argument, "section '%s' not found",
2162 Name.str().c_str());
2163
2164 auto *OldSec = It->get();
2165 if (!OldSec->hasContents())
2166 return createStringError(
2168 "section '%s' cannot be updated because it does not have contents",
2169 Name.str().c_str());
2170
2171 if (Data.size() > OldSec->Size && OldSec->ParentSegment)
2173 "cannot fit data of size %zu into section '%s' "
2174 "with size %" PRIu64 " that is part of a segment",
2175 Data.size(), Name.str().c_str(), OldSec->Size);
2176
2177 if (!OldSec->ParentSegment) {
2178 *It = std::make_unique<OwnedDataSection>(*OldSec, Data);
2179 } else {
2180 // The segment writer will be in charge of updating these contents.
2181 OldSec->Size = Data.size();
2182 UpdatedSections[OldSec] = Data;
2183 }
2184
2185 return Error::success();
2186}
2187
2189 bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
2190
2191 auto Iter = std::stable_partition(
2192 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
2193 if (ToRemove(*Sec))
2194 return false;
2195 // TODO: A compressed relocation section may be recognized as
2196 // RelocationSectionBase. We don't want such a section to be removed.
2197 if (isa<CompressedSection>(Sec))
2198 return true;
2199 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
2200 if (auto ToRelSec = RelSec->getSection())
2201 return !ToRemove(*ToRelSec);
2202 }
2203 // Remove empty group sections.
2204 if (Sec->Type == ELF::SHT_GROUP) {
2205 auto GroupSec = cast<GroupSection>(Sec.get());
2206 return !llvm::all_of(GroupSec->members(), ToRemove);
2207 }
2208 return true;
2209 });
2210 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
2211 SymbolTable = nullptr;
2212 if (SectionNames != nullptr && ToRemove(*SectionNames))
2213 SectionNames = nullptr;
2214 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
2215 SectionIndexTable = nullptr;
2216 // Now make sure there are no remaining references to the sections that will
2217 // be removed. Sometimes it is impossible to remove a reference so we emit
2218 // an error here instead.
2219 std::unordered_set<const SectionBase *> RemoveSections;
2220 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
2221 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
2222 for (auto &Segment : Segments)
2223 Segment->removeSection(RemoveSec.get());
2224 RemoveSec->onRemove();
2225 RemoveSections.insert(RemoveSec.get());
2226 }
2227
2228 // For each section that remains alive, we want to remove the dead references.
2229 // This either might update the content of the section (e.g. remove symbols
2230 // from symbol table that belongs to removed section) or trigger an error if
2231 // a live section critically depends on a section being removed somehow
2232 // (e.g. the removed section is referenced by a relocation).
2233 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
2234 if (Error E = KeepSec->removeSectionReferences(
2235 AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
2236 return RemoveSections.find(Sec) != RemoveSections.end();
2237 }))
2238 return E;
2239 }
2240
2241 // Transfer removed sections into the Object RemovedSections container for use
2242 // later.
2243 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
2244 // Now finally get rid of them all together.
2245 Sections.erase(Iter, std::end(Sections));
2246 return Error::success();
2247}
2248
2251 auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
2252 return Lhs->Index < Rhs->Index;
2253 };
2254 assert(llvm::is_sorted(Sections, SectionIndexLess) &&
2255 "Sections are expected to be sorted by Index");
2256 // Set indices of new sections so that they can be later sorted into positions
2257 // of removed ones.
2258 for (auto &I : FromTo)
2259 I.second->Index = I.first->Index;
2260
2261 // Notify all sections about the replacement.
2262 for (auto &Sec : Sections)
2263 Sec->replaceSectionReferences(FromTo);
2264
2265 if (Error E = removeSections(
2266 /*AllowBrokenLinks=*/false,
2267 [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
2268 return E;
2269 llvm::sort(Sections, SectionIndexLess);
2270 return Error::success();
2271}
2272
2274 if (SymbolTable)
2275 for (const SecPtr &Sec : Sections)
2276 if (Error E = Sec->removeSymbols(ToRemove))
2277 return E;
2278 return Error::success();
2279}
2280
2282 assert(!SymbolTable && "Object must not has a SymbolTable.");
2283
2284 // Reuse an existing SHT_STRTAB section if it exists.
2285 StringTableSection *StrTab = nullptr;
2286 for (SectionBase &Sec : sections()) {
2287 if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
2288 StrTab = static_cast<StringTableSection *>(&Sec);
2289
2290 // Prefer a string table that is not the section header string table, if
2291 // such a table exists.
2292 if (SectionNames != &Sec)
2293 break;
2294 }
2295 }
2296 if (!StrTab)
2297 StrTab = &addSection<StringTableSection>();
2298
2299 SymbolTableSection &SymTab = addSection<SymbolTableSection>();
2300 SymTab.Name = ".symtab";
2301 SymTab.Link = StrTab->Index;
2302 if (Error Err = SymTab.initialize(sections()))
2303 return Err;
2304 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
2305
2306 SymbolTable = &SymTab;
2307
2308 return Error::success();
2309}
2310
2311// Orders segments such that if x = y->ParentSegment then y comes before x.
2312static void orderSegments(std::vector<Segment *> &Segments) {
2314}
2315
2316// This function finds a consistent layout for a list of segments starting from
2317// an Offset. It assumes that Segments have been sorted by orderSegments and
2318// returns an Offset one past the end of the last segment.
2319static uint64_t layoutSegments(std::vector<Segment *> &Segments,
2320 uint64_t Offset) {
2322 // The only way a segment should move is if a section was between two
2323 // segments and that section was removed. If that section isn't in a segment
2324 // then it's acceptable, but not ideal, to simply move it to after the
2325 // segments. So we can simply layout segments one after the other accounting
2326 // for alignment.
2327 for (Segment *Seg : Segments) {
2328 // We assume that segments have been ordered by OriginalOffset and Index
2329 // such that a parent segment will always come before a child segment in
2330 // OrderedSegments. This means that the Offset of the ParentSegment should
2331 // already be set and we can set our offset relative to it.
2332 if (Seg->ParentSegment != nullptr) {
2333 Segment *Parent = Seg->ParentSegment;
2334 Seg->Offset =
2335 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
2336 } else {
2337 Seg->Offset =
2338 alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
2339 }
2340 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
2341 }
2342 return Offset;
2343}
2344
2345// This function finds a consistent layout for a list of sections. It assumes
2346// that the ->ParentSegment of each section has already been laid out. The
2347// supplied starting Offset is used for the starting offset of any section that
2348// does not have a ParentSegment. It returns either the offset given if all
2349// sections had a ParentSegment or an offset one past the last section if there
2350// was a section that didn't have a ParentSegment.
2351template <class Range>
2353 // Now the offset of every segment has been set we can assign the offsets
2354 // of each section. For sections that are covered by a segment we should use
2355 // the segment's original offset and the section's original offset to compute
2356 // the offset from the start of the segment. Using the offset from the start
2357 // of the segment we can assign a new offset to the section. For sections not
2358 // covered by segments we can just bump Offset to the next valid location.
2359 // While it is not necessary, layout the sections in the order based on their
2360 // original offsets to resemble the input file as close as possible.
2361 std::vector<SectionBase *> OutOfSegmentSections;
2362 uint32_t Index = 1;
2363 for (auto &Sec : Sections) {
2364 Sec.Index = Index++;
2365 if (Sec.ParentSegment != nullptr) {
2366 const Segment &Segment = *Sec.ParentSegment;
2367 Sec.Offset =
2368 Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
2369 } else
2370 OutOfSegmentSections.push_back(&Sec);
2371 }
2372
2373 llvm::stable_sort(OutOfSegmentSections,
2374 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2375 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2376 });
2377 for (auto *Sec : OutOfSegmentSections) {
2378 Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
2379 Sec->Offset = Offset;
2380 if (Sec->Type != SHT_NOBITS)
2381 Offset += Sec->Size;
2382 }
2383 return Offset;
2384}
2385
2386// Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
2387// occupy no space in the file.
2389 // The layout algorithm requires the sections to be handled in the order of
2390 // their offsets in the input file, at least inside segments.
2391 std::vector<SectionBase *> Sections;
2392 Sections.reserve(Obj.sections().size());
2393 uint32_t Index = 1;
2394 for (auto &Sec : Obj.sections()) {
2395 Sec.Index = Index++;
2396 Sections.push_back(&Sec);
2397 }
2398 llvm::stable_sort(Sections,
2399 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2400 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2401 });
2402
2403 for (auto *Sec : Sections) {
2404 auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
2405 ? Sec->ParentSegment->firstSection()
2406 : nullptr;
2407
2408 // The first section in a PT_LOAD has to have congruent offset and address
2409 // modulo the alignment, which usually equals the maximum page size.
2410 if (FirstSec && FirstSec == Sec)
2411 Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
2412
2413 // sh_offset is not significant for SHT_NOBITS sections, but the congruence
2414 // rule must be followed if it is the first section in a PT_LOAD. Do not
2415 // advance Off.
2416 if (Sec->Type == SHT_NOBITS) {
2417 Sec->Offset = Off;
2418 continue;
2419 }
2420
2421 if (!FirstSec) {
2422 // FirstSec being nullptr generally means that Sec does not have the
2423 // SHF_ALLOC flag.
2424 Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
2425 } else if (FirstSec != Sec) {
2426 // The offset is relative to the first section in the PT_LOAD segment. Use
2427 // sh_offset for non-SHF_ALLOC sections.
2428 Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
2429 }
2430 Sec->Offset = Off;
2431 Off += Sec->Size;
2432 }
2433 return Off;
2434}
2435
2436// Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
2437// have been updated.
2438static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
2439 uint64_t HdrEnd) {
2440 uint64_t MaxOffset = 0;
2441 for (Segment *Seg : Segments) {
2442 if (Seg->Type == PT_PHDR)
2443 continue;
2444
2445 // The segment offset is generally the offset of the first section.
2446 //
2447 // For a segment containing no section (see sectionWithinSegment), if it has
2448 // a parent segment, copy the parent segment's offset field. This works for
2449 // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
2450 // debugging anyway.
2451 const SectionBase *FirstSec = Seg->firstSection();
2453 FirstSec ? FirstSec->Offset
2454 : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
2455 uint64_t FileSize = 0;
2456 for (const SectionBase *Sec : Seg->Sections) {
2457 uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
2458 if (Sec->Offset + Size > Offset)
2459 FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
2460 }
2461
2462 // If the segment includes EHDR and program headers, don't make it smaller
2463 // than the headers.
2464 if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
2465 FileSize += Offset - Seg->Offset;
2466 Offset = Seg->Offset;
2467 FileSize = std::max(FileSize, HdrEnd - Offset);
2468 }
2469
2470 Seg->Offset = Offset;
2471 Seg->FileSize = FileSize;
2472 MaxOffset = std::max(MaxOffset, Offset + FileSize);
2473 }
2474 return MaxOffset;
2475}
2476
2477template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
2478 Segment &ElfHdr = Obj.ElfHdrSegment;
2479 ElfHdr.Type = PT_PHDR;
2480 ElfHdr.Flags = 0;
2481 ElfHdr.VAddr = 0;
2482 ElfHdr.PAddr = 0;
2483 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
2484 ElfHdr.Align = 0;
2485}
2486
2487template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
2488 // We need a temporary list of segments that has a special order to it
2489 // so that we know that anytime ->ParentSegment is set that segment has
2490 // already had its offset properly set.
2491 std::vector<Segment *> OrderedSegments;
2492 for (Segment &Segment : Obj.segments())
2493 OrderedSegments.push_back(&Segment);
2494 OrderedSegments.push_back(&Obj.ElfHdrSegment);
2495 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
2496 orderSegments(OrderedSegments);
2497
2499 if (OnlyKeepDebug) {
2500 // For --only-keep-debug, the sections that did not preserve contents were
2501 // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
2502 // then rewrite p_offset/p_filesz of program headers.
2503 uint64_t HdrEnd =
2504 sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
2506 Offset = std::max(Offset,
2507 layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
2508 } else {
2509 // Offset is used as the start offset of the first segment to be laid out.
2510 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
2511 // we start at offset 0.
2512 Offset = layoutSegments(OrderedSegments, 0);
2513 Offset = layoutSections(Obj.sections(), Offset);
2514 }
2515 // If we need to write the section header table out then we need to align the
2516 // Offset so that SHOffset is valid.
2517 if (WriteSectionHeaders)
2518 Offset = alignTo(Offset, sizeof(Elf_Addr));
2519 Obj.SHOff = Offset;
2520}
2521
2522template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
2523 // We already have the section header offset so we can calculate the total
2524 // size by just adding up the size of each section header.
2525 if (!WriteSectionHeaders)
2526 return Obj.SHOff;
2527 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
2528 return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
2529}
2530
2531template <class ELFT> Error ELFWriter<ELFT>::write() {
2532 // Segment data must be written first, so that the ELF header and program
2533 // header tables can overwrite it, if covered by a segment.
2534 writeSegmentData();
2535 writeEhdr();
2536 writePhdrs();
2537 if (Error E = writeSectionData())
2538 return E;
2539 if (WriteSectionHeaders)
2540 writeShdrs();
2541
2542 // TODO: Implement direct writing to the output stream (without intermediate
2543 // memory buffer Buf).
2544 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2545 return Error::success();
2546}
2547
2549 // We can remove an empty symbol table from non-relocatable objects.
2550 // Relocatable objects typically have relocation sections whose
2551 // sh_link field points to .symtab, so we can't remove .symtab
2552 // even if it is empty.
2553 if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
2554 !Obj.SymbolTable->empty())
2555 return Error::success();
2556
2557 // .strtab can be used for section names. In such a case we shouldn't
2558 // remove it.
2559 auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
2560 ? nullptr
2561 : Obj.SymbolTable->getStrTab();
2562 return Obj.removeSections(false, [&](const SectionBase &Sec) {
2563 return &Sec == Obj.SymbolTable || &Sec == StrTab;
2564 });
2565}
2566
2567template <class ELFT> Error ELFWriter<ELFT>::finalize() {
2568 // It could happen that SectionNames has been removed and yet the user wants
2569 // a section header table output. We need to throw an error if a user tries
2570 // to do that.
2571 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
2573 "cannot write section header table because "
2574 "section header string table was removed");
2575
2576 if (Error E = removeUnneededSections(Obj))
2577 return E;
2578
2579 // If the .symtab indices have not been changed, restore the sh_link to
2580 // .symtab for sections that were linked to .symtab.
2581 if (Obj.SymbolTable && !Obj.SymbolTable->indicesChanged())
2582 for (SectionBase &Sec : Obj.sections())
2583 Sec.restoreSymTabLink(*Obj.SymbolTable);
2584
2585 // We need to assign indexes before we perform layout because we need to know
2586 // if we need large indexes or not. We can assign indexes first and check as
2587 // we go to see if we will actully need large indexes.
2588 bool NeedsLargeIndexes = false;
2589 if (Obj.sections().size() >= SHN_LORESERVE) {
2590 SectionTableRef Sections = Obj.sections();
2591 // Sections doesn't include the null section header, so account for this
2592 // when skipping the first N sections.
2593 NeedsLargeIndexes =
2594 any_of(drop_begin(Sections, SHN_LORESERVE - 1),
2595 [](const SectionBase &Sec) { return Sec.HasSymbol; });
2596 // TODO: handle case where only one section needs the large index table but
2597 // only needs it because the large index table hasn't been removed yet.
2598 }
2599
2600 if (NeedsLargeIndexes) {
2601 // This means we definitely need to have a section index table but if we
2602 // already have one then we should use it instead of making a new one.
2603 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
2604 // Addition of a section to the end does not invalidate the indexes of
2605 // other sections and assigns the correct index to the new section.
2606 auto &Shndx = Obj.addSection<SectionIndexSection>();
2607 Obj.SymbolTable->setShndxTable(&Shndx);
2608 Shndx.setSymTab(Obj.SymbolTable);
2609 }
2610 } else {
2611 // Since we don't need SectionIndexTable we should remove it and all
2612 // references to it.
2613 if (Obj.SectionIndexTable != nullptr) {
2614 // We do not support sections referring to the section index table.
2615 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
2616 [this](const SectionBase &Sec) {
2617 return &Sec == Obj.SectionIndexTable;
2618 }))
2619 return E;
2620 }
2621 }
2622
2623 // Make sure we add the names of all the sections. Importantly this must be
2624 // done after we decide to add or remove SectionIndexes.
2625 if (Obj.SectionNames != nullptr)
2626 for (const SectionBase &Sec : Obj.sections())
2627 Obj.SectionNames->addString(Sec.Name);
2628
2629 initEhdrSegment();
2630
2631 // Before we can prepare for layout the indexes need to be finalized.
2632 // Also, the output arch may not be the same as the input arch, so fix up
2633 // size-related fields before doing layout calculations.
2634 uint64_t Index = 0;
2635 auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
2636 for (SectionBase &Sec : Obj.sections()) {
2637 Sec.Index = Index++;
2638 if (Error Err = Sec.accept(*SecSizer))
2639 return Err;
2640 }
2641
2642 // The symbol table does not update all other sections on update. For
2643 // instance, symbol names are not added as new symbols are added. This means
2644 // that some sections, like .strtab, don't yet have their final size.
2645 if (Obj.SymbolTable != nullptr)
2646 Obj.SymbolTable->prepareForLayout();
2647
2648 // Now that all strings are added we want to finalize string table builders,
2649 // because that affects section sizes which in turn affects section offsets.
2650 for (SectionBase &Sec : Obj.sections())
2651 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
2652 StrTab->prepareForLayout();
2653
2654 assignOffsets();
2655
2656 // layoutSections could have modified section indexes, so we need
2657 // to fill the index table after assignOffsets.
2658 if (Obj.SymbolTable != nullptr)
2659 Obj.SymbolTable->fillShndxTable();
2660
2661 // Finally now that all offsets and indexes have been set we can finalize any
2662 // remaining issues.
2663 uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
2664 for (SectionBase &Sec : Obj.sections()) {
2665 Sec.HeaderOffset = Offset;
2666 Offset += sizeof(Elf_Shdr);
2667 if (WriteSectionHeaders)
2668 Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
2669 Sec.finalize();
2670 }
2671
2672 size_t TotalSize = totalSize();
2674 if (!Buf)
2676 "failed to allocate memory buffer of " +
2677 Twine::utohexstr(TotalSize) + " bytes");
2678
2679 SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
2680 return Error::success();
2681}
2682
2685 for (const SectionBase &Sec : Obj.allocSections()) {
2686 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2687 SectionsToWrite.push_back(&Sec);
2688 }
2689
2690 if (SectionsToWrite.empty())
2691 return Error::success();
2692
2693 llvm::stable_sort(SectionsToWrite,
2694 [](const SectionBase *LHS, const SectionBase *RHS) {
2695 return LHS->Offset < RHS->Offset;
2696 });
2697
2698 assert(SectionsToWrite.front()->Offset == 0);
2699
2700 for (size_t i = 0; i != SectionsToWrite.size(); ++i) {
2701 const SectionBase &Sec = *SectionsToWrite[i];
2702 if (Error Err = Sec.accept(*SecWriter))
2703 return Err;
2704 if (GapFill == 0)
2705 continue;
2706 uint64_t PadOffset = (i < SectionsToWrite.size() - 1)
2707 ? SectionsToWrite[i + 1]->Offset
2708 : Buf->getBufferSize();
2709 assert(PadOffset <= Buf->getBufferSize());
2710 assert(Sec.Offset + Sec.Size <= PadOffset);
2711 std::fill(Buf->getBufferStart() + Sec.Offset + Sec.Size,
2712 Buf->getBufferStart() + PadOffset, GapFill);
2713 }
2714
2715 // TODO: Implement direct writing to the output stream (without intermediate
2716 // memory buffer Buf).
2717 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2718 return Error::success();
2719}
2720
2722 // Compute the section LMA based on its sh_offset and the containing segment's
2723 // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
2724 // sections as MinAddr. In the output, the contents between address 0 and
2725 // MinAddr will be skipped.
2726 uint64_t MinAddr = UINT64_MAX;
2727 for (SectionBase &Sec : Obj.allocSections()) {
2728 if (Sec.ParentSegment != nullptr)
2729 Sec.Addr =
2730 Sec.Offset - Sec.ParentSegment->Offset + Sec.ParentSegment->PAddr;
2731 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2732 MinAddr = std::min(MinAddr, Sec.Addr);
2733 }
2734
2735 // Now that every section has been laid out we just need to compute the total
2736 // file size. This might not be the same as the offset returned by
2737 // layoutSections, because we want to truncate the last segment to the end of
2738 // its last non-empty section, to match GNU objcopy's behaviour.
2739 TotalSize = PadTo > MinAddr ? PadTo - MinAddr : 0;
2740 for (SectionBase &Sec : Obj.allocSections())
2741 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
2742 Sec.Offset = Sec.Addr - MinAddr;
2743 TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
2744 }
2745
2747 if (!Buf)
2749 "failed to allocate memory buffer of " +
2750 Twine::utohexstr(TotalSize) + " bytes");
2751 SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
2752 return Error::success();
2753}
2754
2756 if (addressOverflows32bit(S.Addr) ||
2757 addressOverflows32bit(S.Addr + S.Size - 1))
2758 return createStringError(
2760 "section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
2761 S.Name.c_str(), S.Addr, S.Addr + S.Size - 1);
2762 return Error::success();
2763}
2764
2766 // We can't write 64-bit addresses.
2769 "entry point address 0x%llx overflows 32 bits",
2770 Obj.Entry);
2771
2772 for (const SectionBase &S : Obj.sections()) {
2773 if ((S.Flags & ELF::SHF_ALLOC) && S.Type != ELF::SHT_NOBITS && S.Size > 0) {
2774 if (Error E = checkSection(S))
2775 return E;
2776 Sections.push_back(&S);
2777 }
2778 }
2779
2780 llvm::sort(Sections, [](const SectionBase *A, const SectionBase *B) {
2782 });
2783
2784 std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
2786 if (!EmptyBuffer)
2788 "failed to allocate memory buffer of 0 bytes");
2789
2790 Expected<size_t> ExpTotalSize = getTotalSize(*EmptyBuffer);
2791 if (!ExpTotalSize)
2792 return ExpTotalSize.takeError();
2793 TotalSize = *ExpTotalSize;
2794
2796 if (!Buf)
2798 "failed to allocate memory buffer of 0x" +
2799 Twine::utohexstr(TotalSize) + " bytes");
2800 return Error::success();
2801}
2802
2803uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
2804 IHexLineData HexData;
2805 uint8_t Data[4] = {};
2806 // We don't write entry point record if entry is zero.
2807 if (Obj.Entry == 0)
2808 return 0;
2809
2810 if (Obj.Entry <= 0xFFFFFU) {
2811 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
2812 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
2815 } else {
2819 }
2820 memcpy(Buf, HexData.data(), HexData.size());
2821 return HexData.size();
2822}
2823
2824uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
2826 memcpy(Buf, HexData.data(), HexData.size());
2827 return HexData.size();
2828}
2829
2831IHexWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
2832 IHexSectionWriterBase LengthCalc(EmptyBuffer);
2833 for (const SectionBase *Sec : Sections)
2834 if (Error Err = Sec->accept(LengthCalc))
2835 return std::move(Err);
2836
2837 // We need space to write section records + StartAddress record
2838 // (if start adress is not zero) + EndOfFile record.
2839 return LengthCalc.getBufferOffset() +
2841 IHexRecord::getLineLength(0);
2842}
2843
2846 // Write sections.
2847 for (const SectionBase *Sec : Sections)
2848 if (Error Err = Sec->accept(Writer))
2849 return Err;
2850
2851 uint64_t Offset = Writer.getBufferOffset();
2852 // Write entry point address.
2853 Offset += writeEntryPointRecord(
2854 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2855 // Write EOF.
2856 Offset += writeEndOfFileRecord(
2857 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2859
2860 // TODO: Implement direct writing to the output stream (without intermediate
2861 // memory buffer Buf).
2862 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2863 return Error::success();
2864}
2865
2867 // Check that the sizer has already done its work.
2868 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2869 "Expected section size to have been finalized");
2870 // We don't need to write anything here because the real writer has already
2871 // done it.
2872 return Error::success();
2873}
2874
2876 writeSection(Sec, Sec.Contents);
2877 return Error::success();
2878}
2879
2881 writeSection(Sec, Sec.Data);
2882 return Error::success();
2883}
2884
2886 writeSection(Sec, Sec.Contents);
2887 return Error::success();
2888}
2889
2891 SRecLineData Data = Record.toString();
2892 memcpy(Out.getBufferStart() + Off, Data.data(), Data.size());
2893}
2894
2896 // The ELF header could contain an entry point outside of the sections we have
2897 // seen that does not fit the current record Type.
2898 Type = std::max(Type, SRecord::getType(Entry));
2899 uint64_t Off = HeaderSize;
2900 for (SRecord &Record : Records) {
2901 Record.Type = Type;
2902 writeRecord(Record, Off);
2903 Off += Record.getSize();
2904 }
2905 Offset = Off;
2906}
2907
2910 const uint32_t ChunkSize = 16;
2912 uint32_t EndAddr = Address + S.Size - 1;
2913 Type = std::max(SRecord::getType(EndAddr), Type);
2914 while (!Data.empty()) {
2915 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
2916 SRecord Record{Type, Address, Data.take_front(DataSize)};
2917 Records.push_back(Record);
2918 Data = Data.drop_front(DataSize);
2919 Address += DataSize;
2920 }
2921}
2922
2924 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2925 "Section size does not match the section's string table builder size");
2926 std::vector<uint8_t> Data(Sec.Size);
2927 Sec.StrTabBuilder.write(Data.data());
2928 writeSection(Sec, Data);
2929 return Error::success();
2930}
2931
2933 SRecLineData Line(getSize());
2934 auto *Iter = Line.begin();
2935 *Iter++ = 'S';
2936 *Iter++ = '0' + Type;
2937 // Write 1 byte (2 hex characters) record count.
2938 Iter = toHexStr(getCount(), Iter, 2);
2939 // Write the address field with length depending on record type.
2940 Iter = toHexStr(Address, Iter, getAddressSize());
2941 // Write data byte by byte.
2942 for (uint8_t X : Data)
2943 Iter = toHexStr(X, Iter, 2);
2944 // Write the 1 byte checksum.
2945 Iter = toHexStr(getChecksum(), Iter, 2);
2946 *Iter++ = '\r';
2947 *Iter++ = '\n';
2948 assert(Iter == Line.end());
2949 return Line;
2950}
2951
2953 uint32_t Sum = getCount();
2954 Sum += (Address >> 24) & 0xFF;
2955 Sum += (Address >> 16) & 0xFF;
2956 Sum += (Address >> 8) & 0xFF;
2957 Sum += Address & 0xFF;
2958 for (uint8_t Byte : Data)
2959 Sum += Byte;
2960 return 0xFF - (Sum & 0xFF);
2961}
2962
2963size_t SRecord::getSize() const {
2964 // Type, Count, Checksum, and CRLF are two characters each.
2965 return 2 + 2 + getAddressSize() + Data.size() * 2 + 2 + 2;
2966}
2967
2969 switch (Type) {
2970 case Type::S2:
2971 return 6;
2972 case Type::S3:
2973 return 8;
2974 case Type::S7:
2975 return 8;
2976 case Type::S8:
2977 return 6;
2978 default:
2979 return 4;
2980 }
2981}
2982
2984 uint8_t DataSize = Data.size();
2985 uint8_t ChecksumSize = 1;
2986 return getAddressSize() / 2 + DataSize + ChecksumSize;
2987}
2988
2990 if (isUInt<16>(Address))
2991 return SRecord::S1;
2992 if (isUInt<24>(Address))
2993 return SRecord::S2;
2994 return SRecord::S3;
2995}
2996
2998 // Header is a record with Type S0, Address 0, and Data that is a
2999 // vendor-specific text comment. For the comment we will use the output file
3000 // name truncated to 40 characters to match the behavior of GNU objcopy.
3001 StringRef HeaderContents = FileName.slice(0, 40);
3003 reinterpret_cast<const uint8_t *>(HeaderContents.data()),
3004 HeaderContents.size());
3005 return {SRecord::S0, 0, Data};
3006}
3007
3008size_t SRECWriter::writeHeader(uint8_t *Buf) {
3010 memcpy(Buf, Record.data(), Record.size());
3011 return Record.size();
3012}
3013
3014size_t SRECWriter::writeTerminator(uint8_t *Buf, uint8_t Type) {
3016 "Invalid record type for terminator");
3017 uint32_t Entry = Obj.Entry;
3018 SRecLineData Data = SRecord{Type, Entry, {}}.toString();
3019 memcpy(Buf, Data.data(), Data.size());
3020 return Data.size();
3021}
3022
3024SRECWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
3025 SRECSizeCalculator SizeCalc(EmptyBuffer, 0);
3026 for (const SectionBase *Sec : Sections)
3027 if (Error Err = Sec->accept(SizeCalc))
3028 return std::move(Err);
3029
3030 SizeCalc.writeRecords(Obj.Entry);
3031 // We need to add the size of the Header and Terminator records.
3033 uint8_t TerminatorType = 10 - SizeCalc.getType();
3034 SRecord Terminator = {TerminatorType, static_cast<uint32_t>(Obj.Entry), {}};
3035 return Header.getSize() + SizeCalc.getBufferOffset() + Terminator.getSize();
3036}
3037
3039 uint32_t HeaderSize =
3040 writeHeader(reinterpret_cast<uint8_t *>(Buf->getBufferStart()));
3041 SRECSectionWriter Writer(*Buf, HeaderSize);
3042 for (const SectionBase *S : Sections) {
3043 if (Error E = S->accept(Writer))
3044 return E;
3045 }
3046 Writer.writeRecords(Obj.Entry);
3047 uint64_t Offset = Writer.getBufferOffset();
3048
3049 // An S1 record terminates with an S9 record, S2 with S8, and S3 with S7.
3050 uint8_t TerminatorType = 10 - Writer.getType();
3051 Offset += writeTerminator(
3052 reinterpret_cast<uint8_t *>(Buf->getBufferStart() + Offset),
3053 TerminatorType);
3055 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
3056 return Error::success();
3057}
3058
3059namespace llvm {
3060namespace objcopy {
3061namespace elf {
3062
3063template class ELFBuilder<ELF64LE>;
3064template class ELFBuilder<ELF64BE>;
3065template class ELFBuilder<ELF32LE>;
3066template class ELFBuilder<ELF32BE>;
3067
3068template class ELFWriter<ELF64LE>;
3069template class ELFWriter<ELF64BE>;
3070template class ELFWriter<ELF32LE>;
3071template class ELFWriter<ELF32BE>;
3072
3073} // end namespace elf
3074} // end namespace objcopy
3075} // end namespace llvm
#define Fail
ReachingDefAnalysis InstSet & ToRemove
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:390
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
T Content
Elf_Shdr Shdr
uint64_t Addr
std::string Name
uint64_t Size
static bool segmentOverlapsSegment(const Segment &Child, const Segment &Parent)
Definition: ELFObject.cpp:1246
static void setAddend(Elf_Rel_Impl< ELFT, false > &, uint64_t)
Definition: ELFObject.cpp:965
static Error checkChars(StringRef Line)
Definition: ELFObject.cpp:301
static void orderSegments(std::vector< Segment * > &Segments)
Definition: ELFObject.cpp:2312
static uint64_t layoutSegments(std::vector< Segment * > &Segments, uint64_t Offset)
Definition: ELFObject.cpp:2319
static bool compareSegmentsByOffset(const Segment *A, const Segment *B)
Definition: ELFObject.cpp:1253
static uint64_t layoutSections(Range Sections, uint64_t Offset)
Definition: ELFObject.cpp:2352
static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off)
Definition: ELFObject.cpp:2388
static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine)
Definition: ELFObject.cpp:648
static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector< Segment * > &Segments, uint64_t HdrEnd)
Definition: ELFObject.cpp:2438
static void getAddend(uint64_t &, const Elf_Rel_Impl< ELFT, false > &)
Definition: ELFObject.cpp:1647
static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL)
Definition: ELFObject.cpp:973
static bool addressOverflows32bit(uint64_t Addr)
Definition: ELFObject.cpp:193
static T checkedGetHex(StringRef S)
Definition: ELFObject.cpp:198
static uint64_t sectionPhysicalAddr(const SectionBase *Sec)
Definition: ELFObject.cpp:343
static Iterator toHexStr(T X, Iterator It, size_t Len)
Definition: ELFObject.cpp:209
static Error checkRecord(const IHexRecord &R)
Definition: ELFObject.cpp:251
static Error initRelocations(RelocationSection *Relocs, T RelRange)
Definition: ELFObject.cpp:1655
static Error removeUnneededSections(Object &Obj)
Definition: ELFObject.cpp:2548
static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg)
Definition: ELFObject.cpp:1216
bool End
Definition: ELF_riscv.cpp:480
Symbol * Sym
Definition: ELF_riscv.cpp:479
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define I(x, y, z)
Definition: MD5.cpp:58
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
if(PassOpts->AAPipeline)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:157
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
iterator begin() const
Definition: ArrayRef.h:156
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:163
const T * data() const
Definition: ArrayRef.h:165
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:198
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:194
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:76
size_t getBufferSize() const
Definition: MemoryBuffer.h:68
StringRef getBuffer() const
Definition: MemoryBuffer.h:70
const char * getBufferStart() const
Definition: MemoryBuffer.h:66
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
void push_back(const T &Elt)
Definition: SmallVector.h:413
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:286
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:700
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:470
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:229
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:609
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition: StringRef.h:684
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:150
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:144
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition: StringRef.h:580
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
void finalize()
Analyze the strings and build the final table.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:416
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
This class is an extension of MemoryBuffer, which allows copy-on-write access to the underlying conte...
Definition: MemoryBuffer.h:181
static std::unique_ptr< WritableMemoryBuffer > getNewMemBuffer(size_t Size, const Twine &BufferName="")
Allocate a new zero-initialized MemoryBuffer of the specified size.
An efficient, type-erasing, non-owning reference to a callable.
Error checkSection(const SectionBase &S) const
Definition: ELFObject.cpp:2755
std::vector< const SectionBase * > Sections
Definition: ELFObject.h:387
virtual Expected< size_t > getTotalSize(WritableMemoryBuffer &EmptyBuffer) const =0
StringTableSection * addStrTab()
Definition: ELFObject.cpp:1281
SymbolTableSection * addSymTab(StringTableSection *StrTab)
Definition: ELFObject.cpp:1289
std::unique_ptr< Object > Obj
Definition: ELFObject.h:1049
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1335
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1954
Error visit(const SymbolTableSection &Sec) override
Definition: ELFObject.cpp:164
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:581
CompressedSection(const SectionBase &Sec, DebugCompressionType CompressionType, bool Is64Bits)
Definition: ELFObject.cpp:557
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:502
Error accept(SectionVisitor &) const override
Definition: ELFObject.cpp:1036
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1044
ELFBuilder(const ELFObjectFile< ELFT > &ElfObj, Object &Obj, std::optional< StringRef > ExtractPartition)
Definition: ELFObject.cpp:1408
Error build(bool EnsureSymtab)
Definition: ELFObject.cpp:1920
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1993
Error visit(Section &Sec) override
Definition: ELFObject.cpp:82
Error visit(const SymbolTableSection &Sec) override
Definition: ELFObject.cpp:862
ELFWriter(Object &Obj, raw_ostream &Out, bool WSH, bool OnlyKeepDebug)
Definition: ELFObject.cpp:2152
void setSymTab(const SymbolTableSection *SymTabSec)
Definition: ELFObject.h:953
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:1119
Error accept(SectionVisitor &) const override
Definition: ELFObject.cpp:1207
ArrayRef< uint8_t > Contents
Definition: ELFObject.h:949
void addMember(SectionBase *Sec)
Definition: ELFObject.h:956
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1089
void setFlagWord(ELF::Elf32_Word W)
Definition: ELFObject.h:955
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:1105
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1395
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1985
void writeSection(const SectionBase *Sec, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:351
Error visit(const Section &Sec) final
Definition: ELFObject.cpp:400
virtual void writeData(uint8_t Type, uint16_t Addr, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:395
void writeData(uint8_t Type, uint16_t Addr, ArrayRef< uint8_t > Data) override
Definition: ELFObject.cpp:425
Error visit(const StringTableSection &Sec) override
Definition: ELFObject.cpp:432
virtual Error visit(Section &Sec)=0
SectionTableRef sections() const
Definition: ELFObject.h:1199
StringTableSection * SectionNames
Definition: ELFObject.h:1193
bool isRelocatable() const
Definition: ELFObject.h:1237
iterator_range< filter_iterator< pointee_iterator< std::vector< SecPtr >::const_iterator >, decltype(&sectionIsAlloc)> > allocSections() const
Definition: ELFObject.h:1203
Error updateSection(StringRef Name, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2157
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:1195
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:2273
Error removeSections(bool AllowBrokenLinks, std::function< bool(const SectionBase &)> ToRemove)
Definition: ELFObject.cpp:2188
SymbolTableSection * SymbolTable
Definition: ELFObject.h:1194
Error replaceSections(const DenseMap< SectionBase *, SectionBase * > &FromTo)
Definition: ELFObject.cpp:2249
void appendHexData(StringRef HexData)
Definition: ELFObject.cpp:518
Error accept(SectionVisitor &Sec) const override
Definition: ELFObject.cpp:510
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:927
const Object & getObject() const
Definition: ELFObject.h:924
void addRelocation(const Relocation &Rel)
Definition: ELFObject.h:914
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:999
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:1007
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:1024
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:899
virtual void writeRecord(SRecord &Record, uint64_t Off)=0
void writeSection(const SectionBase &S, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2908
Error visit(const Section &S) override
Definition: ELFObject.cpp:2875
Error visit(const StringTableSection &Sec) override
Definition: ELFObject.cpp:2923
void writeRecord(SRecord &Record, uint64_t Off) override
Definition: ELFObject.cpp:2890
ArrayRef< uint8_t > OriginalData
Definition: ELFObject.h:531
virtual Error initialize(SectionTableRef SecTable)
Definition: ELFObject.cpp:59
virtual Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove)
Definition: ELFObject.cpp:50
virtual void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &)
Definition: ELFObject.cpp:62
virtual Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:55
virtual Error accept(SectionVisitor &Visitor) const =0
void setSymTab(SymbolTableSection *SymTab)
Definition: ELFObject.h:793
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:640
void reserve(size_t NumSymbols)
Definition: ELFObject.h:789
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:621
Expected< T * > getSectionOfType(uint32_t Index, Twine IndexErrMsg, Twine TypeErrMsg)
Definition: ELFObject.cpp:1690
Expected< SectionBase * > getSection(uint32_t Index, Twine ErrMsg)
Definition: ELFObject.cpp:1682
virtual Error visit(const Section &Sec)=0
Error visit(const Section &Sec) override
Definition: ELFObject.cpp:186
WritableMemoryBuffer & Out
Definition: ELFObject.h:109
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1064
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:1133
void restoreSymTabLink(SymbolTableSection &SymTab) override
Definition: ELFObject.cpp:448
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:440
void addSection(const SectionBase *Sec)
Definition: ELFObject.h:597
void removeSection(const SectionBase *Sec)
Definition: ELFObject.h:596
const SectionBase * firstSection() const
Definition: ELFObject.h:590
ArrayRef< uint8_t > getContents() const
Definition: ELFObject.h:599
std::set< const SectionBase *, SectionCompare > Sections
Definition: ELFObject.h:585
uint32_t findIndex(StringRef Name) const
Definition: ELFObject.cpp:591
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:606
const SectionBase * getStrTab() const
Definition: ELFObject.h:836
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:739
const SectionIndexSection * getShndxTable() const
Definition: ELFObject.h:834
std::vector< std::unique_ptr< Symbol > > Symbols
Definition: ELFObject.h:814
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:816
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:878
void addSymbol(Twine Name, uint8_t Bind, uint8_t Type, SectionBase *DefinedIn, uint64_t Value, uint8_t Visibility, uint16_t Shndx, uint64_t SymbolSize)
Definition: ELFObject.cpp:714
void updateSymbols(function_ref< void(Symbol &)> Callable)
Definition: ELFObject.cpp:756
Expected< const Symbol * > getSymbolByIndex(uint32_t Index) const
Definition: ELFObject.cpp:845
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:765
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:786
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:779
std::unique_ptr< Symbol > SymPtr
Definition: ELFObject.h:819
void setShndxTable(SectionIndexSection *ShndxTable)
Definition: ELFObject.h:831
StringTableSection * SymbolNames
Definition: ELFObject.h:815
std::unique_ptr< WritableMemoryBuffer > Buf
Definition: ELFObject.h:313
const Elf_Ehdr & getHeader() const
Definition: ELF.h:279
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:888
Expected< Elf_Phdr_Range > program_headers() const
Iterate over program header table.
Definition: ELF.h:376
size_t getBufSize() const
Definition: ELF.h:269
const uint8_t * base() const
Definition: ELF.h:266
Represents a GOFF physical record.
Definition: GOFF.h:31
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition: DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Definition: ELF.h:28
@ ELFOSABI_NONE
Definition: ELF.h:344
@ SHN_XINDEX
Definition: ELF.h:1088
@ SHN_ABS
Definition: ELF.h:1086
@ SHN_COMMON
Definition: ELF.h:1087
@ SHN_UNDEF
Definition: ELF.h:1080
@ SHN_LORESERVE
Definition: ELF.h:1081
void encodeCrel(raw_ostream &OS, RelocsTy Relocs, F ToCrel)
Definition: MCELFExtras.h:25
@ ELFCLASS64
Definition: ELF.h:332
@ ELFCLASS32
Definition: ELF.h:331
@ EI_DATA
Definition: ELF.h:54
@ EI_MAG3
Definition: ELF.h:52
@ EI_MAG1
Definition: ELF.h:50
@ EI_VERSION
Definition: ELF.h:55
@ EI_MAG2
Definition: ELF.h:51
@ EI_ABIVERSION
Definition: ELF.h:57
@ EI_MAG0
Definition: ELF.h:49
@ EI_CLASS
Definition: ELF.h:53
@ EI_OSABI
Definition: ELF.h:56
@ EV_CURRENT
Definition: ELF.h:128
@ EM_NONE
Definition: ELF.h:136
@ EM_HEXAGON
Definition: ELF.h:260
@ EM_MIPS
Definition: ELF.h:144
@ EM_AMDGPU
Definition: ELF.h:319
uint32_t Elf32_Word
Definition: ELF.h:33
@ SHT_STRTAB
Definition: ELF.h:1097
@ SHT_GROUP
Definition: ELF.h:1109
@ SHT_PROGBITS
Definition: ELF.h:1095
@ SHT_REL
Definition: ELF.h:1103
@ SHT_NULL
Definition: ELF.h:1094
@ SHT_NOBITS
Definition: ELF.h:1102
@ SHT_SYMTAB
Definition: ELF.h:1096
@ SHT_LLVM_PART_EHDR
Definition: ELF.h:1129
@ SHT_CREL
Definition: ELF.h:1116
@ SHT_DYNAMIC
Definition: ELF.h:1100
@ SHT_SYMTAB_SHNDX
Definition: ELF.h:1110
@ SHT_GNU_HASH
Definition: ELF.h:1143
@ SHT_RELA
Definition: ELF.h:1098
@ SHT_DYNSYM
Definition: ELF.h:1105
@ SHT_HASH
Definition: ELF.h:1099
@ ELFCOMPRESS_ZSTD
Definition: ELF.h:1980
@ ELFCOMPRESS_ZLIB
Definition: ELF.h:1979
@ SHN_HEXAGON_SCOMMON_2
Definition: ELF.h:662
@ SHN_HEXAGON_SCOMMON_4
Definition: ELF.h:663
@ SHN_HEXAGON_SCOMMON_8
Definition: ELF.h:664
@ SHN_HEXAGON_SCOMMON_1
Definition: ELF.h:661
@ SHN_HEXAGON_SCOMMON
Definition: ELF.h:660
@ SHF_ALLOC
Definition: ELF.h:1193
@ SHF_COMPRESSED
Definition: ELF.h:1221
@ SHF_WRITE
Definition: ELF.h:1190
@ SHF_TLS
Definition: ELF.h:1218
@ STB_GLOBAL
Definition: ELF.h:1347
@ STB_LOCAL
Definition: ELF.h:1346
@ PT_LOAD
Definition: ELF.h:1500
@ PT_TLS
Definition: ELF.h:1506
@ PT_PHDR
Definition: ELF.h:1505
@ ET_REL
Definition: ELF.h:117
@ STT_NOTYPE
Definition: ELF.h:1358
@ ELFDATA2MSB
Definition: ELF.h:339
@ ELFDATA2LSB
Definition: ELF.h:338
@ GRP_COMDAT
Definition: ELF.h:1293
@ SHN_AMDGPU_LDS
Definition: ELF.h:1901
@ SHN_MIPS_SUNDEFINED
Definition: ELF.h:580
@ SHN_MIPS_SCOMMON
Definition: ELF.h:579
@ SHN_MIPS_ACOMMON
Definition: ELF.h:576
const char * getReasonIfUnsupported(Format F)
Definition: Compression.cpp:30
Error decompress(DebugCompressionType T, ArrayRef< uint8_t > Input, uint8_t *Output, size_t UncompressedSize)
Definition: Compression.cpp:58
Format formatFor(DebugCompressionType Type)
Definition: Compression.h:81
void compress(Params P, ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &Output)
Definition: Compression.cpp:46
support::ulittle32_t Word
Definition: IRSymtab.h:52
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:92
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:480
void stable_sort(R &&Range)
Definition: STLExtras.h:2037
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1697
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition: Casting.h:649
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1291
@ operation_not_permitted
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1746
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition: STLExtras.h:1926
@ Mod
The access may modify the value stored in memory.
DebugCompressionType
Definition: Compression.h:27
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1841
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1766
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2099
const char * toString(DWARFSectionKind Kind)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
static IHexLineData getLine(uint8_t Type, uint16_t Addr, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:232
static uint8_t getChecksum(StringRef S)
Definition: ELFObject.cpp:222
static Expected< IHexRecord > parse(StringRef Line)
Definition: ELFObject.cpp:314
static size_t getLength(size_t DataSize)
Definition: ELFObject.h:209
static size_t getLineLength(size_t DataSize)
Definition: ELFObject.h:215
uint8_t getAddressSize() const
Definition: ELFObject.cpp:2968
static SRecord getHeader(StringRef FileName)
Definition: ELFObject.cpp:2997
uint8_t getChecksum() const
Definition: ELFObject.cpp:2952
SRecLineData toString() const
Definition: ELFObject.cpp:2932
static uint8_t getType(uint32_t Address)
Definition: ELFObject.cpp:2989
ArrayRef< uint8_t > Data
Definition: ELFObject.h:424
uint16_t getShndx() const
Definition: ELFObject.cpp:684
SectionBase * DefinedIn
Definition: ELFObject.h:760
SymbolShndxType ShndxType
Definition: ELFObject.h:761
Definition: regcomp.c:192