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