LLVM 22.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 llvm::copy(Decompressed, 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) {
901 if (ToRemove(Symbols)) {
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
1312
1313void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
1314 auto Data = ArrayRef<uint8_t>(
1315 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
1316 MemBuf->getBufferSize());
1317 auto &DataSection = Obj->addSection<Section>(Data);
1318 DataSection.Name = ".data";
1319 DataSection.Type = ELF::SHT_PROGBITS;
1320 DataSection.Size = Data.size();
1321 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1322
1323 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
1324 std::replace_if(
1325 std::begin(SanitizedFilename), std::end(SanitizedFilename),
1326 [](char C) { return !isAlnum(C); }, '_');
1327 Twine Prefix = Twine("_binary_") + SanitizedFilename;
1328
1329 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
1330 /*Value=*/0, NewSymbolVisibility, 0, 0);
1331 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
1332 /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
1333 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
1334 /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
1335 0);
1336}
1337
1341
1343 if (Error Err = initSections())
1344 return std::move(Err);
1345 addData(SymTab);
1346
1347 return std::move(Obj);
1348}
1349
1350// Adds sections from IHEX data file. Data should have been
1351// fully validated by this time.
1352void IHexELFBuilder::addDataSections() {
1353 OwnedDataSection *Section = nullptr;
1354 uint64_t SegmentAddr = 0, BaseAddr = 0;
1355 uint32_t SecNo = 1;
1356
1357 for (const IHexRecord &R : Records) {
1358 uint64_t RecAddr;
1359 switch (R.Type) {
1360 case IHexRecord::Data:
1361 // Ignore empty data records
1362 if (R.HexData.empty())
1363 continue;
1364 RecAddr = R.Addr + SegmentAddr + BaseAddr;
1365 if (!Section || Section->Addr + Section->Size != RecAddr) {
1366 // OriginalOffset field is only used to sort sections before layout, so
1367 // instead of keeping track of real offsets in IHEX file, and as
1368 // layoutSections() and layoutSectionsForOnlyKeepDebug() use
1369 // llvm::stable_sort(), we can just set it to a constant (zero).
1370 Section = &Obj->addSection<OwnedDataSection>(
1371 ".sec" + std::to_string(SecNo), RecAddr,
1373 SecNo++;
1374 }
1375 Section->appendHexData(R.HexData);
1376 break;
1378 break;
1380 // 20-bit segment address.
1381 SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
1382 break;
1385 Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
1386 assert(Obj->Entry <= 0xFFFFFU);
1387 break;
1389 // 16-31 bits of linear base address
1390 BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
1391 break;
1392 default:
1393 llvm_unreachable("unknown record type");
1394 }
1395 }
1396}
1397
1401 StringTableSection *StrTab = addStrTab();
1402 addSymTab(StrTab);
1403 if (Error Err = initSections())
1404 return std::move(Err);
1405 addDataSections();
1406
1407 return std::move(Obj);
1408}
1409
1410template <class ELFT>
1412 std::optional<StringRef> ExtractPartition)
1413 : ElfFile(ElfObj.getELFFile()), Obj(Obj),
1414 ExtractPartition(ExtractPartition) {
1415 Obj.IsMips64EL = ElfFile.isMips64EL();
1416}
1417
1418template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
1419 for (Segment &Parent : Obj.segments()) {
1420 // Every segment will overlap with itself but we don't want a segment to
1421 // be its own parent so we avoid that situation.
1422 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
1423 // We want a canonical "most parental" segment but this requires
1424 // inspecting the ParentSegment.
1425 if (compareSegmentsByOffset(&Parent, &Child))
1426 if (Child.ParentSegment == nullptr ||
1427 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
1428 Child.ParentSegment = &Parent;
1429 }
1430 }
1431 }
1432}
1433
1434template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
1435 if (!ExtractPartition)
1436 return Error::success();
1437
1438 for (const SectionBase &Sec : Obj.sections()) {
1439 if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
1440 EhdrOffset = Sec.Offset;
1441 return Error::success();
1442 }
1443 }
1445 "could not find partition named '" +
1446 *ExtractPartition + "'");
1447}
1448
1449template <class ELFT>
1451 uint32_t Index = 0;
1452
1454 HeadersFile.program_headers();
1455 if (!Headers)
1456 return Headers.takeError();
1457
1458 for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
1459 if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
1460 return createStringError(
1462 "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
1463 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
1464 " goes past the end of the file");
1465
1466 ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
1467 (size_t)Phdr.p_filesz};
1468 Segment &Seg = Obj.addSegment(Data);
1469 Seg.Type = Phdr.p_type;
1470 Seg.Flags = Phdr.p_flags;
1471 Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
1472 Seg.Offset = Phdr.p_offset + EhdrOffset;
1473 Seg.VAddr = Phdr.p_vaddr;
1474 Seg.PAddr = Phdr.p_paddr;
1475 Seg.FileSize = Phdr.p_filesz;
1476 Seg.MemSize = Phdr.p_memsz;
1477 Seg.Align = Phdr.p_align;
1478 Seg.Index = Index++;
1479 for (SectionBase &Sec : Obj.sections())
1480 if (sectionWithinSegment(Sec, Seg)) {
1481 Seg.addSection(&Sec);
1482 if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
1483 Sec.ParentSegment = &Seg;
1484 }
1485 }
1486
1487 auto &ElfHdr = Obj.ElfHdrSegment;
1488 ElfHdr.Index = Index++;
1489 ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
1490
1491 const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
1492 auto &PrHdr = Obj.ProgramHdrSegment;
1493 PrHdr.Type = PT_PHDR;
1494 PrHdr.Flags = 0;
1495 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
1496 // Whereas this works automatically for ElfHdr, here OriginalOffset is
1497 // always non-zero and to ensure the equation we assign the same value to
1498 // VAddr as well.
1499 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
1500 PrHdr.PAddr = 0;
1501 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
1502 // The spec requires us to naturally align all the fields.
1503 PrHdr.Align = sizeof(Elf_Addr);
1504 PrHdr.Index = Index++;
1505
1506 // Now we do an O(n^2) loop through the segments in order to match up
1507 // segments.
1508 for (Segment &Child : Obj.segments())
1509 setParentSegment(Child);
1510 setParentSegment(ElfHdr);
1511 setParentSegment(PrHdr);
1512
1513 return Error::success();
1514}
1515
1516template <class ELFT>
1518 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
1520 "invalid alignment " + Twine(GroupSec->Align) +
1521 " of group section '" + GroupSec->Name + "'");
1522 SectionTableRef SecTable = Obj.sections();
1523 if (GroupSec->Link != SHN_UNDEF) {
1524 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1525 GroupSec->Link,
1526 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1527 GroupSec->Name + "' is invalid",
1528 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1529 GroupSec->Name + "' is not a symbol table");
1530 if (!SymTab)
1531 return SymTab.takeError();
1532
1533 Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
1534 if (!Sym)
1536 "info field value '" + Twine(GroupSec->Info) +
1537 "' in section '" + GroupSec->Name +
1538 "' is not a valid symbol index");
1539 GroupSec->setSymTab(*SymTab);
1540 GroupSec->setSymbol(*Sym);
1541 }
1542 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1543 GroupSec->Contents.empty())
1545 "the content of the section " + GroupSec->Name +
1546 " is malformed");
1547 const ELF::Elf32_Word *Word =
1548 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1549 const ELF::Elf32_Word *End =
1550 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1551 GroupSec->setFlagWord(endian::read32<ELFT::Endianness>(Word++));
1552 for (; Word != End; ++Word) {
1553 uint32_t Index = support::endian::read32<ELFT::Endianness>(Word);
1554 Expected<SectionBase *> Sec = SecTable.getSection(
1555 Index, "group member index " + Twine(Index) + " in section '" +
1556 GroupSec->Name + "' is invalid");
1557 if (!Sec)
1558 return Sec.takeError();
1559
1560 GroupSec->addMember(*Sec);
1561 }
1562
1563 return Error::success();
1564}
1565
1566template <class ELFT>
1568 Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
1569 if (!Shdr)
1570 return Shdr.takeError();
1571
1572 Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
1573 if (!StrTabData)
1574 return StrTabData.takeError();
1575
1576 ArrayRef<Elf_Word> ShndxData;
1577
1579 ElfFile.symbols(*Shdr);
1580 if (!Symbols)
1581 return Symbols.takeError();
1582
1583 for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
1584 SectionBase *DefSection = nullptr;
1585
1586 Expected<StringRef> Name = Sym.getName(*StrTabData);
1587 if (!Name)
1588 return Name.takeError();
1589
1590 if (Sym.st_shndx == SHN_XINDEX) {
1591 if (SymTab->getShndxTable() == nullptr)
1593 "symbol '" + *Name +
1594 "' has index SHN_XINDEX but no "
1595 "SHT_SYMTAB_SHNDX section exists");
1596 if (ShndxData.data() == nullptr) {
1598 ElfFile.getSection(SymTab->getShndxTable()->Index);
1599 if (!ShndxSec)
1600 return ShndxSec.takeError();
1601
1603 ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
1604 if (!Data)
1605 return Data.takeError();
1606
1607 ShndxData = *Data;
1608 if (ShndxData.size() != Symbols->size())
1609 return createStringError(
1611 "symbol section index table does not have the same number of "
1612 "entries as the symbol table");
1613 }
1614 Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
1615 Expected<SectionBase *> Sec = Obj.sections().getSection(
1616 Index,
1617 "symbol '" + *Name + "' has invalid section index " + Twine(Index));
1618 if (!Sec)
1619 return Sec.takeError();
1620
1621 DefSection = *Sec;
1622 } else if (Sym.st_shndx >= SHN_LORESERVE) {
1623 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
1624 return createStringError(
1626 "symbol '" + *Name +
1627 "' has unsupported value greater than or equal "
1628 "to SHN_LORESERVE: " +
1629 Twine(Sym.st_shndx));
1630 }
1631 } else if (Sym.st_shndx != SHN_UNDEF) {
1632 Expected<SectionBase *> Sec = Obj.sections().getSection(
1633 Sym.st_shndx, "symbol '" + *Name +
1634 "' is defined has invalid section index " +
1635 Twine(Sym.st_shndx));
1636 if (!Sec)
1637 return Sec.takeError();
1638
1639 DefSection = *Sec;
1640 }
1641
1642 SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
1643 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
1644 }
1645
1646 return Error::success();
1647}
1648
1649template <class ELFT>
1651
1652template <class ELFT>
1653static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1654 ToSet = Rela.r_addend;
1655}
1656
1657template <class T>
1658static Error initRelocations(RelocationSection *Relocs, T RelRange) {
1659 for (const auto &Rel : RelRange) {
1660 Relocation ToAdd;
1661 ToAdd.Offset = Rel.r_offset;
1662 getAddend(ToAdd.Addend, Rel);
1663 ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
1664
1665 if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
1666 if (!Relocs->getObject().SymbolTable)
1667 return createStringError(
1669 "'" + Relocs->Name + "': relocation references symbol with index " +
1670 Twine(Sym) + ", but there is no symbol table");
1671 Expected<Symbol *> SymByIndex =
1673 if (!SymByIndex)
1674 return SymByIndex.takeError();
1675
1676 ToAdd.RelocSymbol = *SymByIndex;
1677 }
1678
1679 Relocs->addRelocation(ToAdd);
1680 }
1681
1682 return Error::success();
1683}
1684
1686 Twine ErrMsg) {
1687 if (Index == SHN_UNDEF || Index > Sections.size())
1689 return Sections[Index - 1].get();
1690}
1691
1692template <class T>
1694 Twine IndexErrMsg,
1695 Twine TypeErrMsg) {
1696 Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
1697 if (!BaseSec)
1698 return BaseSec.takeError();
1699
1700 if (T *Sec = dyn_cast<T>(*BaseSec))
1701 return Sec;
1702
1703 return createStringError(errc::invalid_argument, TypeErrMsg);
1704}
1705
1706template <class ELFT>
1708 switch (Shdr.sh_type) {
1709 case SHT_REL:
1710 case SHT_RELA:
1711 case SHT_CREL:
1712 if (Shdr.sh_flags & SHF_ALLOC) {
1713 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1714 return Obj.addSection<DynamicRelocationSection>(*Data);
1715 else
1716 return Data.takeError();
1717 }
1718 return Obj.addSection<RelocationSection>(Obj);
1719 case SHT_STRTAB:
1720 // If a string table is allocated we don't want to mess with it. That would
1721 // mean altering the memory image. There are no special link types or
1722 // anything so we can just use a Section.
1723 if (Shdr.sh_flags & SHF_ALLOC) {
1724 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1725 return Obj.addSection<Section>(*Data);
1726 else
1727 return Data.takeError();
1728 }
1729 return Obj.addSection<StringTableSection>();
1730 case SHT_HASH:
1731 case SHT_GNU_HASH:
1732 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1733 // Because of this we don't need to mess with the hash tables either.
1734 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1735 return Obj.addSection<Section>(*Data);
1736 else
1737 return Data.takeError();
1738 case SHT_GROUP:
1739 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1740 return Obj.addSection<GroupSection>(*Data);
1741 else
1742 return Data.takeError();
1743 case SHT_DYNSYM:
1744 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1745 return Obj.addSection<DynamicSymbolTableSection>(*Data);
1746 else
1747 return Data.takeError();
1748 case SHT_DYNAMIC:
1749 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1750 return Obj.addSection<DynamicSection>(*Data);
1751 else
1752 return Data.takeError();
1753 case SHT_SYMTAB: {
1754 // Multiple SHT_SYMTAB sections are forbidden by the ELF gABI.
1755 if (Obj.SymbolTable != nullptr)
1757 "found multiple SHT_SYMTAB sections");
1758 auto &SymTab = Obj.addSection<SymbolTableSection>();
1759 Obj.SymbolTable = &SymTab;
1760 return SymTab;
1761 }
1762 case SHT_SYMTAB_SHNDX: {
1763 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1764 Obj.SectionIndexTable = &ShndxSection;
1765 return ShndxSection;
1766 }
1767 case SHT_NOBITS:
1768 return Obj.addSection<Section>(ArrayRef<uint8_t>());
1769 default: {
1770 Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
1771 if (!Data)
1772 return Data.takeError();
1773
1774 Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
1775 if (!Name)
1776 return Name.takeError();
1777
1778 if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
1779 return Obj.addSection<Section>(*Data);
1780 auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
1781 return Obj.addSection<CompressedSection>(CompressedSection(
1782 *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign));
1783 }
1784 }
1785}
1786
1787template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
1788 uint32_t Index = 0;
1790 ElfFile.sections();
1791 if (!Sections)
1792 return Sections.takeError();
1793
1794 for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
1795 if (Index == 0) {
1796 ++Index;
1797 continue;
1798 }
1799 Expected<SectionBase &> Sec = makeSection(Shdr);
1800 if (!Sec)
1801 return Sec.takeError();
1802
1803 Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
1804 if (!SecName)
1805 return SecName.takeError();
1806 Sec->Name = SecName->str();
1807 Sec->Type = Sec->OriginalType = Shdr.sh_type;
1808 Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
1809 Sec->Addr = Shdr.sh_addr;
1810 Sec->Offset = Shdr.sh_offset;
1811 Sec->OriginalOffset = Shdr.sh_offset;
1812 Sec->Size = Shdr.sh_size;
1813 Sec->Link = Shdr.sh_link;
1814 Sec->Info = Shdr.sh_info;
1815 Sec->Align = Shdr.sh_addralign;
1816 Sec->EntrySize = Shdr.sh_entsize;
1817 Sec->Index = Index++;
1818 Sec->OriginalIndex = Sec->Index;
1819 Sec->OriginalData = ArrayRef<uint8_t>(
1820 ElfFile.base() + Shdr.sh_offset,
1821 (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
1822 }
1823
1824 return Error::success();
1825}
1826
1827template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
1828 uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
1829 if (ShstrIndex == SHN_XINDEX) {
1830 Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
1831 if (!Sec)
1832 return Sec.takeError();
1833
1834 ShstrIndex = (*Sec)->sh_link;
1835 }
1836
1837 if (ShstrIndex == SHN_UNDEF)
1838 Obj.HadShdrs = false;
1839 else {
1841 Obj.sections().template getSectionOfType<StringTableSection>(
1842 ShstrIndex,
1843 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1844 " is invalid",
1845 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1846 " does not reference a string table");
1847 if (!Sec)
1848 return Sec.takeError();
1849
1850 Obj.SectionNames = *Sec;
1851 }
1852
1853 // If a section index table exists we'll need to initialize it before we
1854 // initialize the symbol table because the symbol table might need to
1855 // reference it.
1856 if (Obj.SectionIndexTable)
1857 if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
1858 return Err;
1859
1860 // Now that all of the sections have been added we can fill out some extra
1861 // details about symbol tables. We need the symbol table filled out before
1862 // any relocations.
1863 if (Obj.SymbolTable) {
1864 if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
1865 return Err;
1866 if (Error Err = initSymbolTable(Obj.SymbolTable))
1867 return Err;
1868 } else if (EnsureSymtab) {
1869 if (Error Err = Obj.addNewSymbolTable())
1870 return Err;
1871 }
1872
1873 // Now that all sections and symbols have been added we can add
1874 // relocations that reference symbols and set the link and info fields for
1875 // relocation sections.
1876 for (SectionBase &Sec : Obj.sections()) {
1877 if (&Sec == Obj.SymbolTable)
1878 continue;
1879 if (Error Err = Sec.initialize(Obj.sections()))
1880 return Err;
1881 if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
1883 ElfFile.sections();
1884 if (!Sections)
1885 return Sections.takeError();
1886
1887 const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
1888 Sections->begin() + RelSec->Index;
1889 if (RelSec->Type == SHT_CREL) {
1890 auto RelsOrRelas = ElfFile.crels(*Shdr);
1891 if (!RelsOrRelas)
1892 return RelsOrRelas.takeError();
1893 if (Error Err = initRelocations(RelSec, RelsOrRelas->first))
1894 return Err;
1895 if (Error Err = initRelocations(RelSec, RelsOrRelas->second))
1896 return Err;
1897 } else if (RelSec->Type == SHT_REL) {
1899 ElfFile.rels(*Shdr);
1900 if (!Rels)
1901 return Rels.takeError();
1902
1903 if (Error Err = initRelocations(RelSec, *Rels))
1904 return Err;
1905 } else {
1907 ElfFile.relas(*Shdr);
1908 if (!Relas)
1909 return Relas.takeError();
1910
1911 if (Error Err = initRelocations(RelSec, *Relas))
1912 return Err;
1913 }
1914 } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
1915 if (Error Err = initGroupSection(GroupSec))
1916 return Err;
1917 }
1918 }
1919
1920 return Error::success();
1921}
1922
1923template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
1924 if (Error E = readSectionHeaders())
1925 return E;
1926 if (Error E = findEhdrOffset())
1927 return E;
1928
1929 // The ELFFile whose ELF headers and program headers are copied into the
1930 // output file. Normally the same as ElfFile, but if we're extracting a
1931 // loadable partition it will point to the partition's headers.
1932 Expected<ELFFile<ELFT>> HeadersFile = ELFFile<ELFT>::create(toStringRef(
1933 {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
1934 if (!HeadersFile)
1935 return HeadersFile.takeError();
1936
1937 const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
1938 Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64;
1939 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1940 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
1941 Obj.Type = Ehdr.e_type;
1942 Obj.Machine = Ehdr.e_machine;
1943 Obj.Version = Ehdr.e_version;
1944 Obj.Entry = Ehdr.e_entry;
1945 Obj.Flags = Ehdr.e_flags;
1946
1947 if (Error E = readSections(EnsureSymtab))
1948 return E;
1949 return readProgramHeaders(*HeadersFile);
1950}
1951
1952Writer::~Writer() = default;
1953
1954Reader::~Reader() = default;
1955
1957BinaryReader::create(bool /*EnsureSymtab*/) const {
1958 return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
1959}
1960
1961Expected<std::vector<IHexRecord>> IHexReader::parse() const {
1963 std::vector<IHexRecord> Records;
1964 bool HasSections = false;
1965
1966 MemBuf->getBuffer().split(Lines, '\n');
1967 Records.reserve(Lines.size());
1968 for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
1969 StringRef Line = Lines[LineNo - 1].trim();
1970 if (Line.empty())
1971 continue;
1972
1974 if (!R)
1975 return parseError(LineNo, R.takeError());
1976 if (R->Type == IHexRecord::EndOfFile)
1977 break;
1978 HasSections |= (R->Type == IHexRecord::Data);
1979 Records.push_back(*R);
1980 }
1981 if (!HasSections)
1982 return parseError(-1U, "no sections");
1983
1984 return std::move(Records);
1985}
1986
1988IHexReader::create(bool /*EnsureSymtab*/) const {
1990 if (!Records)
1991 return Records.takeError();
1992
1993 return IHexELFBuilder(*Records).build();
1994}
1995
1997 auto Obj = std::make_unique<Object>();
1998 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1999 ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
2000 if (Error Err = Builder.build(EnsureSymtab))
2001 return std::move(Err);
2002 return std::move(Obj);
2003 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
2004 ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
2005 if (Error Err = Builder.build(EnsureSymtab))
2006 return std::move(Err);
2007 return std::move(Obj);
2008 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
2009 ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
2010 if (Error Err = Builder.build(EnsureSymtab))
2011 return std::move(Err);
2012 return std::move(Obj);
2013 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
2014 ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
2015 if (Error Err = Builder.build(EnsureSymtab))
2016 return std::move(Err);
2017 return std::move(Obj);
2018 }
2019 return createStringError(errc::invalid_argument, "invalid file type");
2020}
2021
2022template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
2023 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
2024 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
2025 Ehdr.e_ident[EI_MAG0] = 0x7f;
2026 Ehdr.e_ident[EI_MAG1] = 'E';
2027 Ehdr.e_ident[EI_MAG2] = 'L';
2028 Ehdr.e_ident[EI_MAG3] = 'F';
2029 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
2030 Ehdr.e_ident[EI_DATA] =
2031 ELFT::Endianness == llvm::endianness::big ? ELFDATA2MSB : ELFDATA2LSB;
2032 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
2033 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
2034 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
2035
2036 Ehdr.e_type = Obj.Type;
2037 Ehdr.e_machine = Obj.Machine;
2038 Ehdr.e_version = Obj.Version;
2039 Ehdr.e_entry = Obj.Entry;
2040 // We have to use the fully-qualified name llvm::size
2041 // since some compilers complain on ambiguous resolution.
2042 Ehdr.e_phnum = llvm::size(Obj.segments());
2043 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
2044 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
2045 Ehdr.e_flags = Obj.Flags;
2046 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
2047 if (WriteSectionHeaders && Obj.sections().size() != 0) {
2048 Ehdr.e_shentsize = sizeof(Elf_Shdr);
2049 Ehdr.e_shoff = Obj.SHOff;
2050 // """
2051 // If the number of sections is greater than or equal to
2052 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
2053 // number of section header table entries is contained in the sh_size field
2054 // of the section header at index 0.
2055 // """
2056 auto Shnum = Obj.sections().size() + 1;
2057 if (Shnum >= SHN_LORESERVE)
2058 Ehdr.e_shnum = 0;
2059 else
2060 Ehdr.e_shnum = Shnum;
2061 // """
2062 // If the section name string table section index is greater than or equal
2063 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
2064 // and the actual index of the section name string table section is
2065 // contained in the sh_link field of the section header at index 0.
2066 // """
2067 if (Obj.SectionNames->Index >= SHN_LORESERVE)
2068 Ehdr.e_shstrndx = SHN_XINDEX;
2069 else
2070 Ehdr.e_shstrndx = Obj.SectionNames->Index;
2071 } else {
2072 Ehdr.e_shentsize = 0;
2073 Ehdr.e_shoff = 0;
2074 Ehdr.e_shnum = 0;
2075 Ehdr.e_shstrndx = 0;
2076 }
2077}
2078
2079template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
2080 for (auto &Seg : Obj.segments())
2081 writePhdr(Seg);
2082}
2083
2084template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
2085 // This reference serves to write the dummy section header at the begining
2086 // of the file. It is not used for anything else
2087 Elf_Shdr &Shdr =
2088 *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
2089 Shdr.sh_name = 0;
2090 Shdr.sh_type = SHT_NULL;
2091 Shdr.sh_flags = 0;
2092 Shdr.sh_addr = 0;
2093 Shdr.sh_offset = 0;
2094 // See writeEhdr for why we do this.
2095 uint64_t Shnum = Obj.sections().size() + 1;
2096 if (Shnum >= SHN_LORESERVE)
2097 Shdr.sh_size = Shnum;
2098 else
2099 Shdr.sh_size = 0;
2100 // See writeEhdr for why we do this.
2101 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
2102 Shdr.sh_link = Obj.SectionNames->Index;
2103 else
2104 Shdr.sh_link = 0;
2105 Shdr.sh_info = 0;
2106 Shdr.sh_addralign = 0;
2107 Shdr.sh_entsize = 0;
2108
2109 for (SectionBase &Sec : Obj.sections())
2110 writeShdr(Sec);
2111}
2112
2113template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
2114 for (SectionBase &Sec : Obj.sections())
2115 // Segments are responsible for writing their contents, so only write the
2116 // section data if the section is not in a segment. Note that this renders
2117 // sections in segments effectively immutable.
2118 if (Sec.ParentSegment == nullptr)
2119 if (Error Err = Sec.accept(*SecWriter))
2120 return Err;
2121
2122 return Error::success();
2123}
2124
2125template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
2126 for (Segment &Seg : Obj.segments()) {
2127 size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
2128 std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
2129 Size);
2130 }
2131
2132 for (const auto &it : Obj.getUpdatedSections()) {
2133 SectionBase *Sec = it.first;
2134 ArrayRef<uint8_t> Data = it.second;
2135
2136 auto *Parent = Sec->ParentSegment;
2137 assert(Parent && "This section should've been part of a segment.");
2139 Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2140 llvm::copy(Data, Buf->getBufferStart() + Offset);
2141 }
2142
2143 // Iterate over removed sections and overwrite their old data with zeroes.
2144 for (auto &Sec : Obj.removedSections()) {
2145 Segment *Parent = Sec.ParentSegment;
2146 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
2147 continue;
2149 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2150 std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
2151 }
2152}
2153
2154template <class ELFT>
2156 bool OnlyKeepDebug)
2157 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
2158 OnlyKeepDebug(OnlyKeepDebug) {}
2159
2160Error Object::updateSectionData(SecPtr &Sec, ArrayRef<uint8_t> Data) {
2161 if (!Sec->hasContents())
2162 return createStringError(
2164 "section '%s' cannot be updated because it does not have contents",
2165 Sec->Name.c_str());
2166
2167 if (Data.size() > Sec->Size && Sec->ParentSegment)
2169 "cannot fit data of size %zu into section '%s' "
2170 "with size %" PRIu64 " that is part of a segment",
2171 Data.size(), Sec->Name.c_str(), Sec->Size);
2172
2173 if (!Sec->ParentSegment) {
2174 Sec = std::make_unique<OwnedDataSection>(*Sec, Data);
2175 } else {
2176 // The segment writer will be in charge of updating these contents.
2177 Sec->Size = Data.size();
2178 UpdatedSections[Sec.get()] = Data;
2179 }
2180
2181 return Error::success();
2182}
2183
2185 auto It = llvm::find_if(Sections,
2186 [&](const SecPtr &Sec) { return Sec->Name == Name; });
2187 if (It == Sections.end())
2188 return createStringError(errc::invalid_argument, "section '%s' not found",
2189 Name.str().c_str());
2190 return updateSectionData(*It, Data);
2191}
2192
2193Error Object::updateSectionData(SectionBase &S, ArrayRef<uint8_t> Data) {
2194 auto It = llvm::find_if(Sections,
2195 [&](const SecPtr &Sec) { return Sec.get() == &S; });
2196 assert(It != Sections.end() && "The section should belong to the object");
2197 return updateSectionData(*It, Data);
2198}
2199
2201 bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
2202
2203 auto Iter = std::stable_partition(
2204 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
2205 if (ToRemove(*Sec))
2206 return false;
2207 // TODO: A compressed relocation section may be recognized as
2208 // RelocationSectionBase. We don't want such a section to be removed.
2209 if (isa<CompressedSection>(Sec))
2210 return true;
2211 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
2212 if (auto ToRelSec = RelSec->getSection())
2213 return !ToRemove(*ToRelSec);
2214 }
2215 // Remove empty group sections.
2216 if (Sec->Type == ELF::SHT_GROUP) {
2217 auto GroupSec = cast<GroupSection>(Sec.get());
2218 return !llvm::all_of(GroupSec->members(), ToRemove);
2219 }
2220 return true;
2221 });
2222 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
2223 SymbolTable = nullptr;
2224 if (SectionNames != nullptr && ToRemove(*SectionNames))
2225 SectionNames = nullptr;
2226 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
2227 SectionIndexTable = nullptr;
2228 // Now make sure there are no remaining references to the sections that will
2229 // be removed. Sometimes it is impossible to remove a reference so we emit
2230 // an error here instead.
2231 std::unordered_set<const SectionBase *> RemoveSections;
2232 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
2233 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
2234 for (auto &Segment : Segments)
2235 Segment->removeSection(RemoveSec.get());
2236 RemoveSec->onRemove();
2237 RemoveSections.insert(RemoveSec.get());
2238 }
2239
2240 // For each section that remains alive, we want to remove the dead references.
2241 // This either might update the content of the section (e.g. remove symbols
2242 // from symbol table that belongs to removed section) or trigger an error if
2243 // a live section critically depends on a section being removed somehow
2244 // (e.g. the removed section is referenced by a relocation).
2245 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
2246 if (Error E = KeepSec->removeSectionReferences(
2247 AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
2248 return RemoveSections.find(Sec) != RemoveSections.end();
2249 }))
2250 return E;
2251 }
2252
2253 // Transfer removed sections into the Object RemovedSections container for use
2254 // later.
2255 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
2256 // Now finally get rid of them all together.
2257 Sections.erase(Iter, std::end(Sections));
2258 return Error::success();
2259}
2260
2263 auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
2264 return Lhs->Index < Rhs->Index;
2265 };
2266 assert(llvm::is_sorted(Sections, SectionIndexLess) &&
2267 "Sections are expected to be sorted by Index");
2268 // Set indices of new sections so that they can be later sorted into positions
2269 // of removed ones.
2270 for (auto &I : FromTo)
2271 I.second->Index = I.first->Index;
2272
2273 // Notify all sections about the replacement.
2274 for (auto &Sec : Sections)
2275 Sec->replaceSectionReferences(FromTo);
2276
2277 if (Error E = removeSections(
2278 /*AllowBrokenLinks=*/false,
2279 [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
2280 return E;
2281 llvm::sort(Sections, SectionIndexLess);
2282 return Error::success();
2283}
2284
2286 if (SymbolTable)
2287 for (const SecPtr &Sec : Sections)
2288 if (Error E = Sec->removeSymbols(ToRemove))
2289 return E;
2290 return Error::success();
2291}
2292
2294 assert(!SymbolTable && "Object must not has a SymbolTable.");
2295
2296 // Reuse an existing SHT_STRTAB section if it exists.
2297 StringTableSection *StrTab = nullptr;
2298 for (SectionBase &Sec : sections()) {
2299 if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
2300 StrTab = static_cast<StringTableSection *>(&Sec);
2301
2302 // Prefer a string table that is not the section header string table, if
2303 // such a table exists.
2304 if (SectionNames != &Sec)
2305 break;
2306 }
2307 }
2308 if (!StrTab)
2309 StrTab = &addSection<StringTableSection>();
2310
2311 SymbolTableSection &SymTab = addSection<SymbolTableSection>();
2312 SymTab.Name = ".symtab";
2313 SymTab.Link = StrTab->Index;
2314 if (Error Err = SymTab.initialize(sections()))
2315 return Err;
2316 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
2317
2318 SymbolTable = &SymTab;
2319
2320 return Error::success();
2321}
2322
2323// Orders segments such that if x = y->ParentSegment then y comes before x.
2324static void orderSegments(std::vector<Segment *> &Segments) {
2326}
2327
2328// This function finds a consistent layout for a list of segments starting from
2329// an Offset. It assumes that Segments have been sorted by orderSegments and
2330// returns an Offset one past the end of the last segment.
2331static uint64_t layoutSegments(std::vector<Segment *> &Segments,
2332 uint64_t Offset) {
2334 // The only way a segment should move is if a section was between two
2335 // segments and that section was removed. If that section isn't in a segment
2336 // then it's acceptable, but not ideal, to simply move it to after the
2337 // segments. So we can simply layout segments one after the other accounting
2338 // for alignment.
2339 for (Segment *Seg : Segments) {
2340 // We assume that segments have been ordered by OriginalOffset and Index
2341 // such that a parent segment will always come before a child segment in
2342 // OrderedSegments. This means that the Offset of the ParentSegment should
2343 // already be set and we can set our offset relative to it.
2344 if (Seg->ParentSegment != nullptr) {
2345 Segment *Parent = Seg->ParentSegment;
2346 Seg->Offset =
2347 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
2348 } else {
2349 Seg->Offset =
2350 alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
2351 }
2352 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
2353 }
2354 return Offset;
2355}
2356
2357// This function finds a consistent layout for a list of sections. It assumes
2358// that the ->ParentSegment of each section has already been laid out. The
2359// supplied starting Offset is used for the starting offset of any section that
2360// does not have a ParentSegment. It returns either the offset given if all
2361// sections had a ParentSegment or an offset one past the last section if there
2362// was a section that didn't have a ParentSegment.
2363template <class Range>
2365 // Now the offset of every segment has been set we can assign the offsets
2366 // of each section. For sections that are covered by a segment we should use
2367 // the segment's original offset and the section's original offset to compute
2368 // the offset from the start of the segment. Using the offset from the start
2369 // of the segment we can assign a new offset to the section. For sections not
2370 // covered by segments we can just bump Offset to the next valid location.
2371 // While it is not necessary, layout the sections in the order based on their
2372 // original offsets to resemble the input file as close as possible.
2373 std::vector<SectionBase *> OutOfSegmentSections;
2374 uint32_t Index = 1;
2375 for (auto &Sec : Sections) {
2376 Sec.Index = Index++;
2377 if (Sec.ParentSegment != nullptr) {
2378 const Segment &Segment = *Sec.ParentSegment;
2379 Sec.Offset =
2380 Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
2381 } else
2382 OutOfSegmentSections.push_back(&Sec);
2383 }
2384
2385 llvm::stable_sort(OutOfSegmentSections,
2386 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2387 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2388 });
2389 for (auto *Sec : OutOfSegmentSections) {
2390 Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
2391 Sec->Offset = Offset;
2392 if (Sec->Type != SHT_NOBITS)
2393 Offset += Sec->Size;
2394 }
2395 return Offset;
2396}
2397
2398// Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
2399// occupy no space in the file.
2401 // The layout algorithm requires the sections to be handled in the order of
2402 // their offsets in the input file, at least inside segments.
2403 std::vector<SectionBase *> Sections;
2404 Sections.reserve(Obj.sections().size());
2405 uint32_t Index = 1;
2406 for (auto &Sec : Obj.sections()) {
2407 Sec.Index = Index++;
2408 Sections.push_back(&Sec);
2409 }
2410 llvm::stable_sort(Sections,
2411 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2412 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2413 });
2414
2415 for (auto *Sec : Sections) {
2416 auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
2417 ? Sec->ParentSegment->firstSection()
2418 : nullptr;
2419
2420 // The first section in a PT_LOAD has to have congruent offset and address
2421 // modulo the alignment, which usually equals the maximum page size.
2422 if (FirstSec && FirstSec == Sec)
2423 Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
2424
2425 // sh_offset is not significant for SHT_NOBITS sections, but the congruence
2426 // rule must be followed if it is the first section in a PT_LOAD. Do not
2427 // advance Off.
2428 if (Sec->Type == SHT_NOBITS) {
2429 Sec->Offset = Off;
2430 continue;
2431 }
2432
2433 if (!FirstSec) {
2434 // FirstSec being nullptr generally means that Sec does not have the
2435 // SHF_ALLOC flag.
2436 Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
2437 } else if (FirstSec != Sec) {
2438 // The offset is relative to the first section in the PT_LOAD segment. Use
2439 // sh_offset for non-SHF_ALLOC sections.
2440 Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
2441 }
2442 Sec->Offset = Off;
2443 Off += Sec->Size;
2444 }
2445 return Off;
2446}
2447
2448// Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
2449// have been updated.
2450static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
2451 uint64_t HdrEnd) {
2452 uint64_t MaxOffset = 0;
2453 for (Segment *Seg : Segments) {
2454 if (Seg->Type == PT_PHDR)
2455 continue;
2456
2457 // The segment offset is generally the offset of the first section.
2458 //
2459 // For a segment containing no section (see sectionWithinSegment), if it has
2460 // a parent segment, copy the parent segment's offset field. This works for
2461 // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
2462 // debugging anyway.
2463 const SectionBase *FirstSec = Seg->firstSection();
2465 FirstSec ? FirstSec->Offset
2466 : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
2467 uint64_t FileSize = 0;
2468 for (const SectionBase *Sec : Seg->Sections) {
2469 uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
2470 if (Sec->Offset + Size > Offset)
2471 FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
2472 }
2473
2474 // If the segment includes EHDR and program headers, don't make it smaller
2475 // than the headers.
2476 if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
2477 FileSize += Offset - Seg->Offset;
2478 Offset = Seg->Offset;
2479 FileSize = std::max(FileSize, HdrEnd - Offset);
2480 }
2481
2482 Seg->Offset = Offset;
2483 Seg->FileSize = FileSize;
2484 MaxOffset = std::max(MaxOffset, Offset + FileSize);
2485 }
2486 return MaxOffset;
2487}
2488
2489template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
2490 Segment &ElfHdr = Obj.ElfHdrSegment;
2491 ElfHdr.Type = PT_PHDR;
2492 ElfHdr.Flags = 0;
2493 ElfHdr.VAddr = 0;
2494 ElfHdr.PAddr = 0;
2495 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
2496 ElfHdr.Align = 0;
2497}
2498
2499template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
2500 // We need a temporary list of segments that has a special order to it
2501 // so that we know that anytime ->ParentSegment is set that segment has
2502 // already had its offset properly set.
2503 std::vector<Segment *> OrderedSegments;
2504 for (Segment &Segment : Obj.segments())
2505 OrderedSegments.push_back(&Segment);
2506 OrderedSegments.push_back(&Obj.ElfHdrSegment);
2507 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
2508 orderSegments(OrderedSegments);
2509
2511 if (OnlyKeepDebug) {
2512 // For --only-keep-debug, the sections that did not preserve contents were
2513 // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
2514 // then rewrite p_offset/p_filesz of program headers.
2515 uint64_t HdrEnd =
2516 sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
2518 Offset = std::max(Offset,
2519 layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
2520 } else {
2521 // Offset is used as the start offset of the first segment to be laid out.
2522 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
2523 // we start at offset 0.
2524 Offset = layoutSegments(OrderedSegments, 0);
2525 Offset = layoutSections(Obj.sections(), Offset);
2526 }
2527 // If we need to write the section header table out then we need to align the
2528 // Offset so that SHOffset is valid.
2529 if (WriteSectionHeaders)
2530 Offset = alignTo(Offset, sizeof(Elf_Addr));
2531 Obj.SHOff = Offset;
2532}
2533
2534template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
2535 // We already have the section header offset so we can calculate the total
2536 // size by just adding up the size of each section header.
2537 if (!WriteSectionHeaders)
2538 return Obj.SHOff;
2539 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
2540 return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
2541}
2542
2543template <class ELFT> Error ELFWriter<ELFT>::write() {
2544 // Segment data must be written first, so that the ELF header and program
2545 // header tables can overwrite it, if covered by a segment.
2546 writeSegmentData();
2547 writeEhdr();
2548 writePhdrs();
2549 if (Error E = writeSectionData())
2550 return E;
2551 if (WriteSectionHeaders)
2552 writeShdrs();
2553
2554 // TODO: Implement direct writing to the output stream (without intermediate
2555 // memory buffer Buf).
2556 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2557 return Error::success();
2558}
2559
2561 // We can remove an empty symbol table from non-relocatable objects.
2562 // Relocatable objects typically have relocation sections whose
2563 // sh_link field points to .symtab, so we can't remove .symtab
2564 // even if it is empty.
2565 if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
2566 !Obj.SymbolTable->empty())
2567 return Error::success();
2568
2569 // .strtab can be used for section names. In such a case we shouldn't
2570 // remove it.
2571 auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
2572 ? nullptr
2573 : Obj.SymbolTable->getStrTab();
2574 return Obj.removeSections(false, [&](const SectionBase &Sec) {
2575 return &Sec == Obj.SymbolTable || &Sec == StrTab;
2576 });
2577}
2578
2579template <class ELFT> Error ELFWriter<ELFT>::finalize() {
2580 // It could happen that SectionNames has been removed and yet the user wants
2581 // a section header table output. We need to throw an error if a user tries
2582 // to do that.
2583 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
2585 "cannot write section header table because "
2586 "section header string table was removed");
2587
2588 if (Error E = removeUnneededSections(Obj))
2589 return E;
2590
2591 // If the .symtab indices have not been changed, restore the sh_link to
2592 // .symtab for sections that were linked to .symtab.
2593 if (Obj.SymbolTable && !Obj.SymbolTable->indicesChanged())
2594 for (SectionBase &Sec : Obj.sections())
2595 Sec.restoreSymTabLink(*Obj.SymbolTable);
2596
2597 // We need to assign indexes before we perform layout because we need to know
2598 // if we need large indexes or not. We can assign indexes first and check as
2599 // we go to see if we will actully need large indexes.
2600 bool NeedsLargeIndexes = false;
2601 if (Obj.sections().size() >= SHN_LORESERVE) {
2602 SectionTableRef Sections = Obj.sections();
2603 // Sections doesn't include the null section header, so account for this
2604 // when skipping the first N sections.
2605 NeedsLargeIndexes =
2606 any_of(drop_begin(Sections, SHN_LORESERVE - 1),
2607 [](const SectionBase &Sec) { return Sec.HasSymbol; });
2608 // TODO: handle case where only one section needs the large index table but
2609 // only needs it because the large index table hasn't been removed yet.
2610 }
2611
2612 if (NeedsLargeIndexes) {
2613 // This means we definitely need to have a section index table but if we
2614 // already have one then we should use it instead of making a new one.
2615 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
2616 // Addition of a section to the end does not invalidate the indexes of
2617 // other sections and assigns the correct index to the new section.
2618 auto &Shndx = Obj.addSection<SectionIndexSection>();
2619 Obj.SymbolTable->setShndxTable(&Shndx);
2620 Shndx.setSymTab(Obj.SymbolTable);
2621 }
2622 } else {
2623 // Since we don't need SectionIndexTable we should remove it and all
2624 // references to it.
2625 if (Obj.SectionIndexTable != nullptr) {
2626 // We do not support sections referring to the section index table.
2627 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
2628 [this](const SectionBase &Sec) {
2629 return &Sec == Obj.SectionIndexTable;
2630 }))
2631 return E;
2632 }
2633 }
2634
2635 // Make sure we add the names of all the sections. Importantly this must be
2636 // done after we decide to add or remove SectionIndexes.
2637 if (Obj.SectionNames != nullptr)
2638 for (const SectionBase &Sec : Obj.sections())
2639 Obj.SectionNames->addString(Sec.Name);
2640
2641 initEhdrSegment();
2642
2643 // Before we can prepare for layout the indexes need to be finalized.
2644 // Also, the output arch may not be the same as the input arch, so fix up
2645 // size-related fields before doing layout calculations.
2646 uint64_t Index = 0;
2647 auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
2648 for (SectionBase &Sec : Obj.sections()) {
2649 Sec.Index = Index++;
2650 if (Error Err = Sec.accept(*SecSizer))
2651 return Err;
2652 }
2653
2654 // The symbol table does not update all other sections on update. For
2655 // instance, symbol names are not added as new symbols are added. This means
2656 // that some sections, like .strtab, don't yet have their final size.
2657 if (Obj.SymbolTable != nullptr)
2658 Obj.SymbolTable->prepareForLayout();
2659
2660 // Now that all strings are added we want to finalize string table builders,
2661 // because that affects section sizes which in turn affects section offsets.
2662 for (SectionBase &Sec : Obj.sections())
2663 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
2664 StrTab->prepareForLayout();
2665
2666 assignOffsets();
2667
2668 // layoutSections could have modified section indexes, so we need
2669 // to fill the index table after assignOffsets.
2670 if (Obj.SymbolTable != nullptr)
2671 Obj.SymbolTable->fillShndxTable();
2672
2673 // Finally now that all offsets and indexes have been set we can finalize any
2674 // remaining issues.
2675 uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
2676 for (SectionBase &Sec : Obj.sections()) {
2677 Sec.HeaderOffset = Offset;
2678 Offset += sizeof(Elf_Shdr);
2679 if (WriteSectionHeaders)
2680 Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
2681 Sec.finalize();
2682 }
2683
2684 size_t TotalSize = totalSize();
2686 if (!Buf)
2688 "failed to allocate memory buffer of " +
2689 Twine::utohexstr(TotalSize) + " bytes");
2690
2691 SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
2692 return Error::success();
2693}
2694
2697 for (const SectionBase &Sec : Obj.allocSections()) {
2698 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2699 SectionsToWrite.push_back(&Sec);
2700 }
2701
2702 if (SectionsToWrite.empty())
2703 return Error::success();
2704
2705 llvm::stable_sort(SectionsToWrite,
2706 [](const SectionBase *LHS, const SectionBase *RHS) {
2707 return LHS->Offset < RHS->Offset;
2708 });
2709
2710 assert(SectionsToWrite.front()->Offset == 0);
2711
2712 for (size_t i = 0; i != SectionsToWrite.size(); ++i) {
2713 const SectionBase &Sec = *SectionsToWrite[i];
2714 if (Error Err = Sec.accept(*SecWriter))
2715 return Err;
2716 if (GapFill == 0)
2717 continue;
2718 uint64_t PadOffset = (i < SectionsToWrite.size() - 1)
2719 ? SectionsToWrite[i + 1]->Offset
2720 : Buf->getBufferSize();
2721 assert(PadOffset <= Buf->getBufferSize());
2722 assert(Sec.Offset + Sec.Size <= PadOffset);
2723 std::fill(Buf->getBufferStart() + Sec.Offset + Sec.Size,
2724 Buf->getBufferStart() + PadOffset, GapFill);
2725 }
2726
2727 // TODO: Implement direct writing to the output stream (without intermediate
2728 // memory buffer Buf).
2729 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2730 return Error::success();
2731}
2732
2734 // Compute the section LMA based on its sh_offset and the containing segment's
2735 // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
2736 // sections as MinAddr. In the output, the contents between address 0 and
2737 // MinAddr will be skipped.
2738 uint64_t MinAddr = UINT64_MAX;
2739 for (SectionBase &Sec : Obj.allocSections()) {
2740 if (Sec.ParentSegment != nullptr)
2741 Sec.Addr =
2742 Sec.Offset - Sec.ParentSegment->Offset + Sec.ParentSegment->PAddr;
2743 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2744 MinAddr = std::min(MinAddr, Sec.Addr);
2745 }
2746
2747 // Now that every section has been laid out we just need to compute the total
2748 // file size. This might not be the same as the offset returned by
2749 // layoutSections, because we want to truncate the last segment to the end of
2750 // its last non-empty section, to match GNU objcopy's behaviour.
2751 TotalSize = PadTo > MinAddr ? PadTo - MinAddr : 0;
2752 for (SectionBase &Sec : Obj.allocSections())
2753 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
2754 Sec.Offset = Sec.Addr - MinAddr;
2755 TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
2756 }
2757
2759 if (!Buf)
2761 "failed to allocate memory buffer of " +
2762 Twine::utohexstr(TotalSize) + " bytes");
2763 SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
2764 return Error::success();
2765}
2766
2768 if (addressOverflows32bit(S.Addr) ||
2769 addressOverflows32bit(S.Addr + S.Size - 1))
2770 return createStringError(
2772 "section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
2773 S.Name.c_str(), S.Addr, S.Addr + S.Size - 1);
2774 return Error::success();
2775}
2776
2778 // We can't write 64-bit addresses.
2781 "entry point address 0x%llx overflows 32 bits",
2782 Obj.Entry);
2783
2784 for (const SectionBase &S : Obj.sections()) {
2785 if ((S.Flags & ELF::SHF_ALLOC) && S.Type != ELF::SHT_NOBITS && S.Size > 0) {
2786 if (Error E = checkSection(S))
2787 return E;
2788 Sections.push_back(&S);
2789 }
2790 }
2791
2792 llvm::sort(Sections, [](const SectionBase *A, const SectionBase *B) {
2794 });
2795
2796 std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
2798 if (!EmptyBuffer)
2800 "failed to allocate memory buffer of 0 bytes");
2801
2802 Expected<size_t> ExpTotalSize = getTotalSize(*EmptyBuffer);
2803 if (!ExpTotalSize)
2804 return ExpTotalSize.takeError();
2805 TotalSize = *ExpTotalSize;
2806
2808 if (!Buf)
2810 "failed to allocate memory buffer of 0x" +
2811 Twine::utohexstr(TotalSize) + " bytes");
2812 return Error::success();
2813}
2814
2815uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
2816 IHexLineData HexData;
2817 uint8_t Data[4] = {};
2818 // We don't write entry point record if entry is zero.
2819 if (Obj.Entry == 0)
2820 return 0;
2821
2822 if (Obj.Entry <= 0xFFFFFU) {
2823 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
2824 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
2827 } else {
2831 }
2832 memcpy(Buf, HexData.data(), HexData.size());
2833 return HexData.size();
2834}
2835
2836uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
2838 memcpy(Buf, HexData.data(), HexData.size());
2839 return HexData.size();
2840}
2841
2843IHexWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
2844 IHexSectionWriterBase LengthCalc(EmptyBuffer);
2845 for (const SectionBase *Sec : Sections)
2846 if (Error Err = Sec->accept(LengthCalc))
2847 return std::move(Err);
2848
2849 // We need space to write section records + StartAddress record
2850 // (if start adress is not zero) + EndOfFile record.
2851 return LengthCalc.getBufferOffset() +
2853 IHexRecord::getLineLength(0);
2854}
2855
2858 // Write sections.
2859 for (const SectionBase *Sec : Sections)
2860 if (Error Err = Sec->accept(Writer))
2861 return Err;
2862
2863 uint64_t Offset = Writer.getBufferOffset();
2864 // Write entry point address.
2865 Offset += writeEntryPointRecord(
2866 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2867 // Write EOF.
2868 Offset += writeEndOfFileRecord(
2869 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2871
2872 // TODO: Implement direct writing to the output stream (without intermediate
2873 // memory buffer Buf).
2874 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2875 return Error::success();
2876}
2877
2879 // Check that the sizer has already done its work.
2880 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2881 "Expected section size to have been finalized");
2882 // We don't need to write anything here because the real writer has already
2883 // done it.
2884 return Error::success();
2885}
2886
2888 writeSection(Sec, Sec.Contents);
2889 return Error::success();
2890}
2891
2893 writeSection(Sec, Sec.Data);
2894 return Error::success();
2895}
2896
2898 writeSection(Sec, Sec.Contents);
2899 return Error::success();
2900}
2901
2903 SRecLineData Data = Record.toString();
2904 memcpy(Out.getBufferStart() + Off, Data.data(), Data.size());
2905}
2906
2908 // The ELF header could contain an entry point outside of the sections we have
2909 // seen that does not fit the current record Type.
2910 Type = std::max(Type, SRecord::getType(Entry));
2911 uint64_t Off = HeaderSize;
2912 for (SRecord &Record : Records) {
2913 Record.Type = Type;
2914 writeRecord(Record, Off);
2915 Off += Record.getSize();
2916 }
2917 Offset = Off;
2918}
2919
2922 const uint32_t ChunkSize = 16;
2924 uint32_t EndAddr = Address + S.Size - 1;
2925 Type = std::max(SRecord::getType(EndAddr), Type);
2926 while (!Data.empty()) {
2927 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
2928 SRecord Record{Type, Address, Data.take_front(DataSize)};
2929 Records.push_back(Record);
2930 Data = Data.drop_front(DataSize);
2931 Address += DataSize;
2932 }
2933}
2934
2936 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2937 "Section size does not match the section's string table builder size");
2938 std::vector<uint8_t> Data(Sec.Size);
2939 Sec.StrTabBuilder.write(Data.data());
2940 writeSection(Sec, Data);
2941 return Error::success();
2942}
2943
2945 SRecLineData Line(getSize());
2946 auto *Iter = Line.begin();
2947 *Iter++ = 'S';
2948 *Iter++ = '0' + Type;
2949 // Write 1 byte (2 hex characters) record count.
2950 Iter = toHexStr(getCount(), Iter, 2);
2951 // Write the address field with length depending on record type.
2952 Iter = toHexStr(Address, Iter, getAddressSize());
2953 // Write data byte by byte.
2954 for (uint8_t X : Data)
2955 Iter = toHexStr(X, Iter, 2);
2956 // Write the 1 byte checksum.
2957 Iter = toHexStr(getChecksum(), Iter, 2);
2958 *Iter++ = '\r';
2959 *Iter++ = '\n';
2960 assert(Iter == Line.end());
2961 return Line;
2962}
2963
2965 uint32_t Sum = getCount();
2966 Sum += (Address >> 24) & 0xFF;
2967 Sum += (Address >> 16) & 0xFF;
2968 Sum += (Address >> 8) & 0xFF;
2969 Sum += Address & 0xFF;
2970 for (uint8_t Byte : Data)
2971 Sum += Byte;
2972 return 0xFF - (Sum & 0xFF);
2973}
2974
2975size_t SRecord::getSize() const {
2976 // Type, Count, Checksum, and CRLF are two characters each.
2977 return 2 + 2 + getAddressSize() + Data.size() * 2 + 2 + 2;
2978}
2979
2981 switch (Type) {
2982 case Type::S2:
2983 return 6;
2984 case Type::S3:
2985 return 8;
2986 case Type::S7:
2987 return 8;
2988 case Type::S8:
2989 return 6;
2990 default:
2991 return 4;
2992 }
2993}
2994
2996 uint8_t DataSize = Data.size();
2997 uint8_t ChecksumSize = 1;
2998 return getAddressSize() / 2 + DataSize + ChecksumSize;
2999}
3000
3002 if (isUInt<16>(Address))
3003 return SRecord::S1;
3004 if (isUInt<24>(Address))
3005 return SRecord::S2;
3006 return SRecord::S3;
3007}
3008
3010 // Header is a record with Type S0, Address 0, and Data that is a
3011 // vendor-specific text comment. For the comment we will use the output file
3012 // name truncated to 40 characters to match the behavior of GNU objcopy.
3013 StringRef HeaderContents = FileName.slice(0, 40);
3015 reinterpret_cast<const uint8_t *>(HeaderContents.data()),
3016 HeaderContents.size());
3017 return {SRecord::S0, 0, Data};
3018}
3019
3020size_t SRECWriter::writeHeader(uint8_t *Buf) {
3022 memcpy(Buf, Record.data(), Record.size());
3023 return Record.size();
3024}
3025
3026size_t SRECWriter::writeTerminator(uint8_t *Buf, uint8_t Type) {
3028 "Invalid record type for terminator");
3029 uint32_t Entry = Obj.Entry;
3030 SRecLineData Data = SRecord{Type, Entry, {}}.toString();
3031 memcpy(Buf, Data.data(), Data.size());
3032 return Data.size();
3033}
3034
3036SRECWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
3037 SRECSizeCalculator SizeCalc(EmptyBuffer, 0);
3038 for (const SectionBase *Sec : Sections)
3039 if (Error Err = Sec->accept(SizeCalc))
3040 return std::move(Err);
3041
3042 SizeCalc.writeRecords(Obj.Entry);
3043 // We need to add the size of the Header and Terminator records.
3045 uint8_t TerminatorType = 10 - SizeCalc.getType();
3046 SRecord Terminator = {TerminatorType, static_cast<uint32_t>(Obj.Entry), {}};
3047 return Header.getSize() + SizeCalc.getBufferOffset() + Terminator.getSize();
3048}
3049
3051 uint32_t HeaderSize =
3052 writeHeader(reinterpret_cast<uint8_t *>(Buf->getBufferStart()));
3053 SRECSectionWriter Writer(*Buf, HeaderSize);
3054 for (const SectionBase *S : Sections) {
3055 if (Error E = S->accept(Writer))
3056 return E;
3057 }
3058 Writer.writeRecords(Obj.Entry);
3059 uint64_t Offset = Writer.getBufferOffset();
3060
3061 // An S1 record terminates with an S9 record, S2 with S8, and S3 with S7.
3062 uint8_t TerminatorType = 10 - Writer.getType();
3063 Offset += writeTerminator(
3064 reinterpret_cast<uint8_t *>(Buf->getBufferStart() + Offset),
3065 TerminatorType);
3067 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
3068 return Error::success();
3069}
3070
3071namespace llvm {
3072namespace objcopy {
3073namespace elf {
3074
3075template class ELFBuilder<ELF64LE>;
3076template class ELFBuilder<ELF64BE>;
3077template class ELFBuilder<ELF32LE>;
3078template class ELFBuilder<ELF32BE>;
3079
3080template class ELFWriter<ELF64LE>;
3081template class ELFWriter<ELF64BE>;
3082template class ELFWriter<ELF32LE>;
3083template class ELFWriter<ELF32BE>;
3084
3085} // end namespace elf
3086} // end namespace objcopy
3087} // end namespace llvm
#define Fail
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:2324
static uint64_t layoutSegments(std::vector< Segment * > &Segments, uint64_t Offset)
Definition: ELFObject.cpp:2331
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:2364
static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off)
Definition: ELFObject.cpp:2400
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:2450
static void getAddend(uint64_t &, const Elf_Rel_Impl< ELFT, false > &)
Definition: ELFObject.cpp:1650
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:1658
static Error removeUnneededSections(Object &Obj)
Definition: ELFObject.cpp:2560
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)
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:136
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
iterator begin() const
Definition: ArrayRef.h:135
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:142
const T * data() const
Definition: ArrayRef.h:144
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:191
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:203
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:173
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
Error takeError()
Take ownership of the stored error.
Definition: Error.h:612
reference get()
Returns a reference to the stored T value.
Definition: Error.h:582
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:77
size_t getBufferSize() const
Definition: MemoryBuffer.h:69
StringRef getBuffer() const
Definition: MemoryBuffer.h:71
const char * getBufferStart() const
Definition: MemoryBuffer.h:67
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
void push_back(const T &Elt)
Definition: SmallVector.h:414
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:287
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:710
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:480
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:233
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:619
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition: StringRef.h:694
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:148
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:590
LLVM_ABI size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
LLVM_ABI size_t add(CachedHashStringRef S, uint8_t Priority=0)
Add a string to the builder.
LLVM_ABI void write(raw_ostream &OS) const
LLVM_ABI 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:82
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:418
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:75
This class is an extension of MemoryBuffer, which allows copy-on-write access to the underlying conte...
Definition: MemoryBuffer.h:182
static LLVM_ABI 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:2767
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:1053
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1338
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1957
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:1411
Error build(bool EnsureSymtab)
Definition: ELFObject.cpp:1923
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1996
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:2155
void setSymTab(const SymbolTableSection *SymTabSec)
Definition: ELFObject.h:957
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:953
void addMember(SectionBase *Sec)
Definition: ELFObject.h:960
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1089
void setFlagWord(ELF::Elf32_Word W)
Definition: ELFObject.h:959
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:1105
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1398
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1988
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:1206
StringTableSection * SectionNames
Definition: ELFObject.h:1200
bool isRelocatable() const
Definition: ELFObject.h:1245
iterator_range< filter_iterator< pointee_iterator< std::vector< SecPtr >::const_iterator >, decltype(&sectionIsAlloc)> > allocSections() const
Definition: ELFObject.h:1210
Error updateSection(StringRef Name, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2184
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:1202
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:2285
Error removeSections(bool AllowBrokenLinks, std::function< bool(const SectionBase &)> ToRemove)
Definition: ELFObject.cpp:2200
SymbolTableSection * SymbolTable
Definition: ELFObject.h:1201
Error replaceSections(const DenseMap< SectionBase *, SectionBase * > &FromTo)
Definition: ELFObject.cpp:2261
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:928
void addRelocation(const Relocation &Rel)
Definition: ELFObject.h:918
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:2920
Error visit(const Section &S) override
Definition: ELFObject.cpp:2887
Error visit(const StringTableSection &Sec) override
Definition: ELFObject.cpp:2935
void writeRecord(SRecord &Record, uint64_t Off) override
Definition: ELFObject.cpp:2902
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:797
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:640
void reserve(size_t NumSymbols)
Definition: ELFObject.h:793
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:621
Expected< T * > getSectionOfType(uint32_t Index, Twine IndexErrMsg, Twine TypeErrMsg)
Definition: ELFObject.cpp:1693
Expected< SectionBase * > getSection(uint32_t Index, Twine ErrMsg)
Definition: ELFObject.cpp:1685
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:598
void removeSection(const SectionBase *Sec)
Definition: ELFObject.h:597
const SectionBase * firstSection() const
Definition: ELFObject.h:591
ArrayRef< uint8_t > getContents() const
Definition: ELFObject.h:600
std::set< const SectionBase *, SectionCompare > Sections
Definition: ELFObject.h:586
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:840
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:739
const SectionIndexSection * getShndxTable() const
Definition: ELFObject.h:838
std::vector< std::unique_ptr< Symbol > > Symbols
Definition: ELFObject.h:818
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:820
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:823
void setShndxTable(SectionIndexSection *ShndxTable)
Definition: ELFObject.h:835
StringTableSection * SymbolNames
Definition: ELFObject.h:819
std::unique_ptr< WritableMemoryBuffer > Buf
Definition: ELFObject.h:313
const Elf_Ehdr & getHeader() const
Definition: ELF.h:284
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:893
Expected< Elf_Phdr_Range > program_headers() const
Iterate over program header table.
Definition: ELF.h:381
size_t getBufSize() const
Definition: ELF.h:274
const uint8_t * base() const
Definition: ELF.h:271
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:692
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:30
@ ELFOSABI_NONE
Definition: ELF.h:346
@ SHN_MIPS_SUNDEFINED
Definition: ELF.h:589
@ SHN_MIPS_SCOMMON
Definition: ELF.h:588
@ SHN_MIPS_ACOMMON
Definition: ELF.h:585
@ GRP_COMDAT
Definition: ELF.h:1343
void encodeCrel(raw_ostream &OS, RelocsTy Relocs, F ToCrel)
Definition: MCELFExtras.h:25
@ ELFCLASS64
Definition: ELF.h:334
@ ELFCLASS32
Definition: ELF.h:333
@ EI_DATA
Definition: ELF.h:56
@ EI_MAG3
Definition: ELF.h:54
@ EI_MAG1
Definition: ELF.h:52
@ EI_VERSION
Definition: ELF.h:57
@ EI_MAG2
Definition: ELF.h:53
@ EI_ABIVERSION
Definition: ELF.h:59
@ EI_MAG0
Definition: ELF.h:51
@ EI_CLASS
Definition: ELF.h:55
@ EI_OSABI
Definition: ELF.h:58
@ EV_CURRENT
Definition: ELF.h:130
@ EM_NONE
Definition: ELF.h:138
@ EM_HEXAGON
Definition: ELF.h:262
@ EM_MIPS
Definition: ELF.h:146
@ EM_AMDGPU
Definition: ELF.h:321
uint32_t Elf32_Word
Definition: ELF.h:35
@ SHT_STRTAB
Definition: ELF.h:1142
@ SHT_GROUP
Definition: ELF.h:1154
@ SHT_PROGBITS
Definition: ELF.h:1140
@ SHT_REL
Definition: ELF.h:1148
@ SHT_NULL
Definition: ELF.h:1139
@ SHT_NOBITS
Definition: ELF.h:1147
@ SHT_SYMTAB
Definition: ELF.h:1141
@ SHT_LLVM_PART_EHDR
Definition: ELF.h:1174
@ SHT_CREL
Definition: ELF.h:1161
@ SHT_DYNAMIC
Definition: ELF.h:1145
@ SHT_SYMTAB_SHNDX
Definition: ELF.h:1155
@ SHT_GNU_HASH
Definition: ELF.h:1188
@ SHT_RELA
Definition: ELF.h:1143
@ SHT_DYNSYM
Definition: ELF.h:1150
@ SHT_HASH
Definition: ELF.h:1144
@ ELFCOMPRESS_ZSTD
Definition: ELF.h:2038
@ ELFCOMPRESS_ZLIB
Definition: ELF.h:2037
@ SHN_AMDGPU_LDS
Definition: ELF.h:1960
@ SHN_HEXAGON_SCOMMON_2
Definition: ELF.h:691
@ SHN_HEXAGON_SCOMMON_4
Definition: ELF.h:692
@ SHN_HEXAGON_SCOMMON_8
Definition: ELF.h:693
@ SHN_HEXAGON_SCOMMON_1
Definition: ELF.h:690
@ SHN_HEXAGON_SCOMMON
Definition: ELF.h:689
@ ET_REL
Definition: ELF.h:119
@ STB_GLOBAL
Definition: ELF.h:1397
@ STB_LOCAL
Definition: ELF.h:1396
@ ELFDATA2MSB
Definition: ELF.h:341
@ ELFDATA2LSB
Definition: ELF.h:340
@ SHN_XINDEX
Definition: ELF.h:1133
@ SHN_ABS
Definition: ELF.h:1131
@ SHN_COMMON
Definition: ELF.h:1132
@ SHN_UNDEF
Definition: ELF.h:1125
@ SHN_LORESERVE
Definition: ELF.h:1126
@ SHF_ALLOC
Definition: ELF.h:1240
@ SHF_COMPRESSED
Definition: ELF.h:1268
@ SHF_WRITE
Definition: ELF.h:1237
@ SHF_TLS
Definition: ELF.h:1265
@ STT_NOTYPE
Definition: ELF.h:1408
@ PT_LOAD
Definition: ELF.h:1550
@ PT_TLS
Definition: ELF.h:1556
@ PT_PHDR
Definition: ELF.h:1555
LLVM_ABI const char * getReasonIfUnsupported(Format F)
Definition: Compression.cpp:30
LLVM_ABI 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:84
LLVM_ABI void compress(Params P, ArrayRef< uint8_t > Input, SmallVectorImpl< uint8_t > &Output)
Definition: Compression.cpp:46
support::ulittle32_t Word
Definition: IRSymtab.h:53
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:92
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, 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:338
@ Offset
Definition: DWP.cpp:477
void stable_sort(R &&Range)
Definition: STLExtras.h:2077
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:1702
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:1305
@ 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:1751
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
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:1939
@ Mod
The access may modify the value stored in memory.
DebugCompressionType
Definition: Compression.h:28
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:1854
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:1777
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:2139
const char * toString(DWARFSectionKind Kind)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
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:2980
static SRecord getHeader(StringRef FileName)
Definition: ELFObject.cpp:3009
uint8_t getChecksum() const
Definition: ELFObject.cpp:2964
SRecLineData toString() const
Definition: ELFObject.cpp:2944
static uint8_t getType(uint32_t Address)
Definition: ELFObject.cpp:3001
ArrayRef< uint8_t > Data
Definition: ELFObject.h:424
uint16_t getShndx() const
Definition: ELFObject.cpp:684
SectionBase * DefinedIn
Definition: ELFObject.h:764
SymbolShndxType ShndxType
Definition: ELFObject.h:765
Definition: regcomp.c:186