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
552 size_t ChdrSize = Is64Bits ? sizeof(object::Elf_Chdr_Impl<object::ELF64LE>)
554 Size = ChdrSize + CompressedData.size();
555 Align = 8;
556}
557
559 uint32_t ChType, uint64_t DecompressedSize,
560 uint64_t DecompressedAlign)
561 : ChType(ChType), CompressionType(DebugCompressionType::None),
562 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
563 OriginalData = CompressedData;
564}
565
567 return Visitor.visit(*this);
568}
569
571 return Visitor.visit(*this);
572}
573
575
577 return StrTabBuilder.getOffset(Name);
578}
579
581 StrTabBuilder.finalize();
582 Size = StrTabBuilder.getSize();
583}
584
586 Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) +
587 Sec.Offset);
588 return Error::success();
589}
590
592 return Visitor.visit(*this);
593}
594
596 return Visitor.visit(*this);
597}
598
599template <class ELFT>
601 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
602 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
603 return Error::success();
604}
605
607 Size = 0;
610 Link,
611 "Link field value " + Twine(Link) + " in section " + Name +
612 " is invalid",
613 "Link field value " + Twine(Link) + " in section " + Name +
614 " is not a symbol table");
615 if (!Sec)
616 return Sec.takeError();
617
618 setSymTab(*Sec);
619 Symbols->setShndxTable(this);
620 return Error::success();
621}
622
624
626 return Visitor.visit(*this);
627}
628
630 return Visitor.visit(*this);
631}
632
634 switch (Index) {
635 case SHN_ABS:
636 case SHN_COMMON:
637 return true;
638 }
639
640 if (Machine == EM_AMDGPU) {
641 return Index == SHN_AMDGPU_LDS;
642 }
643
644 if (Machine == EM_MIPS) {
645 switch (Index) {
646 case SHN_MIPS_ACOMMON:
647 case SHN_MIPS_SCOMMON:
649 return true;
650 }
651 }
652
653 if (Machine == EM_HEXAGON) {
654 switch (Index) {
660 return true;
661 }
662 }
663 return false;
664}
665
666// Large indexes force us to clarify exactly what this function should do. This
667// function should return the value that will appear in st_shndx when written
668// out.
670 if (DefinedIn != nullptr) {
672 return SHN_XINDEX;
673 return DefinedIn->Index;
674 }
675
677 // This means that we don't have a defined section but we do need to
678 // output a legitimate section index.
679 return SHN_UNDEF;
680 }
681
685 return static_cast<uint16_t>(ShndxType);
686}
687
688bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
689
690void SymbolTableSection::assignIndices() {
691 uint32_t Index = 0;
692 for (auto &Sym : Symbols) {
693 if (Sym->Index != Index)
694 IndicesChanged = true;
695 Sym->Index = Index++;
696 }
697}
698
699void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
700 SectionBase *DefinedIn, uint64_t Value,
701 uint8_t Visibility, uint16_t Shndx,
702 uint64_t SymbolSize) {
703 Symbol Sym;
704 Sym.Name = Name.str();
705 Sym.Binding = Bind;
706 Sym.Type = Type;
707 Sym.DefinedIn = DefinedIn;
708 if (DefinedIn != nullptr)
709 DefinedIn->HasSymbol = true;
710 if (DefinedIn == nullptr) {
711 if (Shndx >= SHN_LORESERVE)
712 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
713 else
714 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
715 }
716 Sym.Value = Value;
717 Sym.Visibility = Visibility;
718 Sym.Size = SymbolSize;
719 Sym.Index = Symbols.size();
720 Symbols.emplace_back(std::make_unique<Symbol>(Sym));
721 Size += this->EntrySize;
722}
723
725 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
727 SectionIndexTable = nullptr;
728 if (ToRemove(SymbolNames)) {
729 if (!AllowBrokenLinks)
730 return createStringError(
732 "string table '%s' cannot be removed because it is "
733 "referenced by the symbol table '%s'",
734 SymbolNames->Name.data(), this->Name.data());
735 SymbolNames = nullptr;
736 }
737 return removeSymbols(
738 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
739}
740
743 Callable(*Sym);
744 std::stable_partition(
745 std::begin(Symbols), std::end(Symbols),
746 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
747 assignIndices();
748}
749
751 function_ref<bool(const Symbol &)> ToRemove) {
752 Symbols.erase(
753 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
754 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
755 std::end(Symbols));
756 auto PrevSize = Size;
757 Size = Symbols.size() * EntrySize;
758 if (Size < PrevSize)
759 IndicesChanged = true;
760 assignIndices();
761 return Error::success();
762}
763
766 for (std::unique_ptr<Symbol> &Sym : Symbols)
767 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
768 Sym->DefinedIn = To;
769}
770
772 Size = 0;
775 Link,
776 "Symbol table has link index of " + Twine(Link) +
777 " which is not a valid index",
778 "Symbol table has link index of " + Twine(Link) +
779 " which is not a string table");
780 if (!Sec)
781 return Sec.takeError();
782
783 setStrTab(*Sec);
784 return Error::success();
785}
786
788 uint32_t MaxLocalIndex = 0;
789 for (std::unique_ptr<Symbol> &Sym : Symbols) {
790 Sym->NameIndex =
791 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
792 if (Sym->Binding == STB_LOCAL)
793 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
794 }
795 // Now we need to set the Link and Info fields.
796 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
797 Info = MaxLocalIndex + 1;
798}
799
801 // Reserve proper amount of space in section index table, so we can
802 // layout sections correctly. We will fill the table with correct
803 // indexes later in fillShdnxTable.
806
807 // Add all of our strings to SymbolNames so that SymbolNames has the right
808 // size before layout is decided.
809 // If the symbol names section has been removed, don't try to add strings to
810 // the table.
811 if (SymbolNames != nullptr)
812 for (std::unique_ptr<Symbol> &Sym : Symbols)
813 SymbolNames->addString(Sym->Name);
814}
815
817 if (SectionIndexTable == nullptr)
818 return;
819 // Fill section index table with real section indexes. This function must
820 // be called after assignOffsets.
821 for (const std::unique_ptr<Symbol> &Sym : Symbols) {
822 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
823 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
824 else
826 }
827}
828
831 if (Symbols.size() <= Index)
833 "invalid symbol index: " + Twine(Index));
834 return Symbols[Index].get();
835}
836
839 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index);
840 if (!Sym)
841 return Sym.takeError();
842
843 return const_cast<Symbol *>(*Sym);
844}
845
846template <class ELFT>
848 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
849 // Loop though symbols setting each entry of the symbol table.
850 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
851 Sym->st_name = Symbol->NameIndex;
852 Sym->st_value = Symbol->Value;
853 Sym->st_size = Symbol->Size;
854 Sym->st_other = Symbol->Visibility;
855 Sym->setBinding(Symbol->Binding);
856 Sym->setType(Symbol->Type);
857 Sym->st_shndx = Symbol->getShndx();
858 ++Sym;
859 }
860 return Error::success();
861}
862
864 return Visitor.visit(*this);
865}
866
868 return Visitor.visit(*this);
869}
870
872 switch (Type) {
873 case SHT_REL:
874 return ".rel";
875 case SHT_RELA:
876 return ".rela";
877 default:
878 llvm_unreachable("not a relocation section");
879 }
880}
881
883 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
884 if (ToRemove(Symbols)) {
885 if (!AllowBrokenLinks)
886 return createStringError(
888 "symbol table '%s' cannot be removed because it is "
889 "referenced by the relocation section '%s'",
890 Symbols->Name.data(), this->Name.data());
891 Symbols = nullptr;
892 }
893
894 for (const Relocation &R : Relocations) {
895 if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn ||
896 !ToRemove(R.RelocSymbol->DefinedIn))
897 continue;
899 "section '%s' cannot be removed: (%s+0x%" PRIx64
900 ") has relocation against symbol '%s'",
901 R.RelocSymbol->DefinedIn->Name.data(),
902 SecToApplyRel->Name.data(), R.Offset,
903 R.RelocSymbol->Name.c_str());
904 }
905
906 return Error::success();
907}
908
909template <class SymTabType>
911 SectionTableRef SecTable) {
912 if (Link != SHN_UNDEF) {
913 Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>(
914 Link,
915 "Link field value " + Twine(Link) + " in section " + Name +
916 " is invalid",
917 "Link field value " + Twine(Link) + " in section " + Name +
918 " is not a symbol table");
919 if (!Sec)
920 return Sec.takeError();
921
922 setSymTab(*Sec);
923 }
924
925 if (Info != SHN_UNDEF) {
927 SecTable.getSection(Info, "Info field value " + Twine(Info) +
928 " in section " + Name + " is invalid");
929 if (!Sec)
930 return Sec.takeError();
931
932 setSection(*Sec);
933 } else
934 setSection(nullptr);
935
936 return Error::success();
937}
938
939template <class SymTabType>
941 this->Link = Symbols ? Symbols->Index : 0;
942
943 if (SecToApplyRel != nullptr)
944 this->Info = SecToApplyRel->Index;
945}
946
947template <class ELFT>
949
950template <class ELFT>
951static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
952 Rela.r_addend = Addend;
953}
954
955template <class RelRange, class T>
956static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) {
957 for (const auto &Reloc : Relocations) {
958 Buf->r_offset = Reloc.Offset;
959 setAddend(*Buf, Reloc.Addend);
960 Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0,
961 Reloc.Type, IsMips64EL);
962 ++Buf;
963 }
964}
965
966template <class ELFT>
968 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
969 if (Sec.Type == SHT_REL)
970 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf),
971 Sec.getObject().IsMips64EL);
972 else
973 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf),
974 Sec.getObject().IsMips64EL);
975 return Error::success();
976}
977
979 return Visitor.visit(*this);
980}
981
983 return Visitor.visit(*this);
984}
985
987 function_ref<bool(const Symbol &)> ToRemove) {
988 for (const Relocation &Reloc : Relocations)
989 if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol))
990 return createStringError(
992 "not stripping symbol '%s' because it is named in a relocation",
993 Reloc.RelocSymbol->Name.data());
994 return Error::success();
995}
996
998 for (const Relocation &Reloc : Relocations)
999 if (Reloc.RelocSymbol)
1000 Reloc.RelocSymbol->Referenced = true;
1001}
1002
1005 // Update the target section if it was replaced.
1006 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
1007 SecToApplyRel = To;
1008}
1009
1011 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
1012 return Error::success();
1013}
1014
1016 return Visitor.visit(*this);
1017}
1018
1020 return Visitor.visit(*this);
1021}
1022
1024 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1025 if (ToRemove(Symbols)) {
1026 if (!AllowBrokenLinks)
1027 return createStringError(
1029 "symbol table '%s' cannot be removed because it is "
1030 "referenced by the relocation section '%s'",
1031 Symbols->Name.data(), this->Name.data());
1032 Symbols = nullptr;
1033 }
1034
1035 // SecToApplyRel contains a section referenced by sh_info field. It keeps
1036 // a section to which the relocation section applies. When we remove any
1037 // sections we also remove their relocation sections. Since we do that much
1038 // earlier, this assert should never be triggered.
1040 return Error::success();
1041}
1042
1044 bool AllowBrokenDependency,
1045 function_ref<bool(const SectionBase *)> ToRemove) {
1046 if (ToRemove(LinkSection)) {
1047 if (!AllowBrokenDependency)
1049 "section '%s' cannot be removed because it is "
1050 "referenced by the section '%s'",
1051 LinkSection->Name.data(), this->Name.data());
1052 LinkSection = nullptr;
1053 }
1054 return Error::success();
1055}
1056
1058 this->Info = Sym ? Sym->Index : 0;
1059 this->Link = SymTab ? SymTab->Index : 0;
1060 // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global
1061 // status is not part of the equation. If Sym is localized, the intention is
1062 // likely to make the group fully localized. Drop GRP_COMDAT to suppress
1063 // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc
1064 if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL)
1065 this->FlagWord &= ~GRP_COMDAT;
1066}
1067
1069 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1070 if (ToRemove(SymTab)) {
1071 if (!AllowBrokenLinks)
1072 return createStringError(
1074 "section '.symtab' cannot be removed because it is "
1075 "referenced by the group section '%s'",
1076 this->Name.data());
1077 SymTab = nullptr;
1078 Sym = nullptr;
1079 }
1080 llvm::erase_if(GroupMembers, ToRemove);
1081 return Error::success();
1082}
1083
1085 if (ToRemove(*Sym))
1087 "symbol '%s' cannot be removed because it is "
1088 "referenced by the section '%s[%d]'",
1089 Sym->Name.data(), this->Name.data(), this->Index);
1090 return Error::success();
1091}
1092
1094 if (Sym)
1095 Sym->Referenced = true;
1096}
1097
1100 for (SectionBase *&Sec : GroupMembers)
1101 if (SectionBase *To = FromTo.lookup(Sec))
1102 Sec = To;
1103}
1104
1106 // As the header section of the group is removed, drop the Group flag in its
1107 // former members.
1108 for (SectionBase *Sec : GroupMembers)
1109 Sec->Flags &= ~SHF_GROUP;
1110}
1111
1113 if (Link == ELF::SHN_UNDEF)
1114 return Error::success();
1115
1117 SecTable.getSection(Link, "Link field value " + Twine(Link) +
1118 " in section " + Name + " is invalid");
1119 if (!Sec)
1120 return Sec.takeError();
1121
1122 LinkSection = *Sec;
1123
1124 if (LinkSection->Type == ELF::SHT_SYMTAB) {
1125 HasSymTabLink = true;
1126 LinkSection = nullptr;
1127 }
1128
1129 return Error::success();
1130}
1131
1132void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
1133
1134void GnuDebugLinkSection::init(StringRef File) {
1135 FileName = sys::path::filename(File);
1136 // The format for the .gnu_debuglink starts with the file name and is
1137 // followed by a null terminator and then the CRC32 of the file. The CRC32
1138 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
1139 // byte, and then finally push the size to alignment and add 4.
1140 Size = alignTo(FileName.size() + 1, 4) + 4;
1141 // The CRC32 will only be aligned if we align the whole section.
1142 Align = 4;
1144 Name = ".gnu_debuglink";
1145 // For sections not found in segments, OriginalOffset is only used to
1146 // establish the order that sections should go in. By using the maximum
1147 // possible offset we cause this section to wind up at the end.
1148 OriginalOffset = std::numeric_limits<uint64_t>::max();
1149}
1150
1152 uint32_t PrecomputedCRC)
1153 : FileName(File), CRC32(PrecomputedCRC) {
1154 init(File);
1155}
1156
1157template <class ELFT>
1159 unsigned char *Buf =
1160 reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
1161 Elf_Word *CRC =
1162 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
1163 *CRC = Sec.CRC32;
1164 llvm::copy(Sec.FileName, Buf);
1165 return Error::success();
1166}
1167
1169 return Visitor.visit(*this);
1170}
1171
1173 return Visitor.visit(*this);
1174}
1175
1176template <class ELFT>
1178 ELF::Elf32_Word *Buf =
1179 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
1180 endian::write32<ELFT::Endianness>(Buf++, Sec.FlagWord);
1181 for (SectionBase *S : Sec.GroupMembers)
1182 endian::write32<ELFT::Endianness>(Buf++, S->Index);
1183 return Error::success();
1184}
1185
1187 return Visitor.visit(*this);
1188}
1189
1191 return Visitor.visit(*this);
1192}
1193
1194// Returns true IFF a section is wholly inside the range of a segment
1195static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) {
1196 // If a section is empty it should be treated like it has a size of 1. This is
1197 // to clarify the case when an empty section lies on a boundary between two
1198 // segments and ensures that the section "belongs" to the second segment and
1199 // not the first.
1200 uint64_t SecSize = Sec.Size ? Sec.Size : 1;
1201
1202 // Ignore just added sections.
1203 if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max())
1204 return false;
1205
1206 if (Sec.Type == SHT_NOBITS) {
1207 if (!(Sec.Flags & SHF_ALLOC))
1208 return false;
1209
1210 bool SectionIsTLS = Sec.Flags & SHF_TLS;
1211 bool SegmentIsTLS = Seg.Type == PT_TLS;
1212 if (SectionIsTLS != SegmentIsTLS)
1213 return false;
1214
1215 return Seg.VAddr <= Sec.Addr &&
1216 Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize;
1217 }
1218
1219 return Seg.Offset <= Sec.OriginalOffset &&
1220 Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize;
1221}
1222
1223// Returns true IFF a segment's original offset is inside of another segment's
1224// range.
1225static bool segmentOverlapsSegment(const Segment &Child,
1226 const Segment &Parent) {
1227
1228 return Parent.OriginalOffset <= Child.OriginalOffset &&
1229 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
1230}
1231
1232static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
1233 // Any segment without a parent segment should come before a segment
1234 // that has a parent segment.
1235 if (A->OriginalOffset < B->OriginalOffset)
1236 return true;
1237 if (A->OriginalOffset > B->OriginalOffset)
1238 return false;
1239 // If alignments are different, the one with a smaller alignment cannot be the
1240 // parent; otherwise, layoutSegments will not respect the larger alignment
1241 // requirement. This rule ensures that PT_LOAD/PT_INTERP/PT_GNU_RELRO/PT_TLS
1242 // segments at the same offset will be aligned correctly.
1243 if (A->Align != B->Align)
1244 return A->Align > B->Align;
1245 return A->Index < B->Index;
1246}
1247
1249 Obj->Flags = 0x0;
1250 Obj->Type = ET_REL;
1251 Obj->OSABI = ELFOSABI_NONE;
1252 Obj->ABIVersion = 0;
1253 Obj->Entry = 0x0;
1254 Obj->Machine = EM_NONE;
1255 Obj->Version = 1;
1256}
1257
1258void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
1259
1261 auto &StrTab = Obj->addSection<StringTableSection>();
1262 StrTab.Name = ".strtab";
1263
1264 Obj->SectionNames = &StrTab;
1265 return &StrTab;
1266}
1267
1269 auto &SymTab = Obj->addSection<SymbolTableSection>();
1270
1271 SymTab.Name = ".symtab";
1272 SymTab.Link = StrTab->Index;
1273
1274 // The symbol table always needs a null symbol
1275 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
1276
1277 Obj->SymbolTable = &SymTab;
1278 return &SymTab;
1279}
1280
1282 for (SectionBase &Sec : Obj->sections())
1283 if (Error Err = Sec.initialize(Obj->sections()))
1284 return Err;
1285
1286 return Error::success();
1287}
1288
1289void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
1290 auto Data = ArrayRef<uint8_t>(
1291 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
1292 MemBuf->getBufferSize());
1293 auto &DataSection = Obj->addSection<Section>(Data);
1294 DataSection.Name = ".data";
1295 DataSection.Type = ELF::SHT_PROGBITS;
1296 DataSection.Size = Data.size();
1297 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1298
1299 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
1300 std::replace_if(
1301 std::begin(SanitizedFilename), std::end(SanitizedFilename),
1302 [](char C) { return !isAlnum(C); }, '_');
1303 Twine Prefix = Twine("_binary_") + SanitizedFilename;
1304
1305 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
1306 /*Value=*/0, NewSymbolVisibility, 0, 0);
1307 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
1308 /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
1309 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
1310 /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
1311 0);
1312}
1313
1317
1319 if (Error Err = initSections())
1320 return std::move(Err);
1321 addData(SymTab);
1322
1323 return std::move(Obj);
1324}
1325
1326// Adds sections from IHEX data file. Data should have been
1327// fully validated by this time.
1328void IHexELFBuilder::addDataSections() {
1329 OwnedDataSection *Section = nullptr;
1330 uint64_t SegmentAddr = 0, BaseAddr = 0;
1331 uint32_t SecNo = 1;
1332
1333 for (const IHexRecord &R : Records) {
1334 uint64_t RecAddr;
1335 switch (R.Type) {
1336 case IHexRecord::Data:
1337 // Ignore empty data records
1338 if (R.HexData.empty())
1339 continue;
1340 RecAddr = R.Addr + SegmentAddr + BaseAddr;
1341 if (!Section || Section->Addr + Section->Size != RecAddr) {
1342 // OriginalOffset field is only used to sort sections before layout, so
1343 // instead of keeping track of real offsets in IHEX file, and as
1344 // layoutSections() and layoutSectionsForOnlyKeepDebug() use
1345 // llvm::stable_sort(), we can just set it to a constant (zero).
1346 Section = &Obj->addSection<OwnedDataSection>(
1347 ".sec" + std::to_string(SecNo), RecAddr,
1349 SecNo++;
1350 }
1351 Section->appendHexData(R.HexData);
1352 break;
1354 break;
1356 // 20-bit segment address.
1357 SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
1358 break;
1361 Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
1362 assert(Obj->Entry <= 0xFFFFFU);
1363 break;
1365 // 16-31 bits of linear base address
1366 BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
1367 break;
1368 default:
1369 llvm_unreachable("unknown record type");
1370 }
1371 }
1372}
1373
1377 StringTableSection *StrTab = addStrTab();
1378 addSymTab(StrTab);
1379 if (Error Err = initSections())
1380 return std::move(Err);
1381 addDataSections();
1382
1383 return std::move(Obj);
1384}
1385
1386template <class ELFT>
1388 std::optional<StringRef> ExtractPartition)
1389 : ElfFile(ElfObj.getELFFile()), Obj(Obj),
1390 ExtractPartition(ExtractPartition) {
1391 Obj.IsMips64EL = ElfFile.isMips64EL();
1392}
1393
1394template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
1395 for (Segment &Parent : Obj.segments()) {
1396 // Every segment will overlap with itself but we don't want a segment to
1397 // be its own parent so we avoid that situation.
1398 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
1399 // We want a canonical "most parental" segment but this requires
1400 // inspecting the ParentSegment.
1401 if (compareSegmentsByOffset(&Parent, &Child))
1402 if (Child.ParentSegment == nullptr ||
1403 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
1404 Child.ParentSegment = &Parent;
1405 }
1406 }
1407 }
1408}
1409
1410template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
1411 if (!ExtractPartition)
1412 return Error::success();
1413
1414 for (const SectionBase &Sec : Obj.sections()) {
1415 if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
1416 EhdrOffset = Sec.Offset;
1417 return Error::success();
1418 }
1419 }
1421 "could not find partition named '" +
1422 *ExtractPartition + "'");
1423}
1424
1425template <class ELFT>
1427 uint32_t Index = 0;
1428
1430 HeadersFile.program_headers();
1431 if (!Headers)
1432 return Headers.takeError();
1433
1434 for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
1435 if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
1436 return createStringError(
1438 "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
1439 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
1440 " goes past the end of the file");
1441
1442 ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
1443 (size_t)Phdr.p_filesz};
1444 Segment &Seg = Obj.addSegment(Data);
1445 Seg.Type = Phdr.p_type;
1446 Seg.Flags = Phdr.p_flags;
1447 Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
1448 Seg.Offset = Phdr.p_offset + EhdrOffset;
1449 Seg.VAddr = Phdr.p_vaddr;
1450 Seg.PAddr = Phdr.p_paddr;
1451 Seg.FileSize = Phdr.p_filesz;
1452 Seg.MemSize = Phdr.p_memsz;
1453 Seg.Align = Phdr.p_align;
1454 Seg.Index = Index++;
1455 for (SectionBase &Sec : Obj.sections())
1456 if (sectionWithinSegment(Sec, Seg)) {
1457 Seg.addSection(&Sec);
1458 if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
1459 Sec.ParentSegment = &Seg;
1460 }
1461 }
1462
1463 auto &ElfHdr = Obj.ElfHdrSegment;
1464 ElfHdr.Index = Index++;
1465 ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
1466
1467 const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
1468 auto &PrHdr = Obj.ProgramHdrSegment;
1469 PrHdr.Type = PT_PHDR;
1470 PrHdr.Flags = 0;
1471 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
1472 // Whereas this works automatically for ElfHdr, here OriginalOffset is
1473 // always non-zero and to ensure the equation we assign the same value to
1474 // VAddr as well.
1475 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
1476 PrHdr.PAddr = 0;
1477 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
1478 // The spec requires us to naturally align all the fields.
1479 PrHdr.Align = sizeof(Elf_Addr);
1480 PrHdr.Index = Index++;
1481
1482 // Now we do an O(n^2) loop through the segments in order to match up
1483 // segments.
1484 for (Segment &Child : Obj.segments())
1485 setParentSegment(Child);
1486 setParentSegment(ElfHdr);
1487 setParentSegment(PrHdr);
1488
1489 return Error::success();
1490}
1491
1492template <class ELFT>
1494 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
1496 "invalid alignment " + Twine(GroupSec->Align) +
1497 " of group section '" + GroupSec->Name + "'");
1498 SectionTableRef SecTable = Obj.sections();
1499 if (GroupSec->Link != SHN_UNDEF) {
1500 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1501 GroupSec->Link,
1502 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1503 GroupSec->Name + "' is invalid",
1504 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1505 GroupSec->Name + "' is not a symbol table");
1506 if (!SymTab)
1507 return SymTab.takeError();
1508
1509 Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
1510 if (!Sym)
1512 "info field value '" + Twine(GroupSec->Info) +
1513 "' in section '" + GroupSec->Name +
1514 "' is not a valid symbol index");
1515 GroupSec->setSymTab(*SymTab);
1516 GroupSec->setSymbol(*Sym);
1517 }
1518 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1519 GroupSec->Contents.empty())
1521 "the content of the section " + GroupSec->Name +
1522 " is malformed");
1523 const ELF::Elf32_Word *Word =
1524 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1525 const ELF::Elf32_Word *End =
1526 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1527 GroupSec->setFlagWord(endian::read32<ELFT::Endianness>(Word++));
1528 for (; Word != End; ++Word) {
1529 uint32_t Index = support::endian::read32<ELFT::Endianness>(Word);
1530 Expected<SectionBase *> Sec = SecTable.getSection(
1531 Index, "group member index " + Twine(Index) + " in section '" +
1532 GroupSec->Name + "' is invalid");
1533 if (!Sec)
1534 return Sec.takeError();
1535
1536 GroupSec->addMember(*Sec);
1537 }
1538
1539 return Error::success();
1540}
1541
1542template <class ELFT>
1544 Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
1545 if (!Shdr)
1546 return Shdr.takeError();
1547
1548 Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
1549 if (!StrTabData)
1550 return StrTabData.takeError();
1551
1552 ArrayRef<Elf_Word> ShndxData;
1553
1555 ElfFile.symbols(*Shdr);
1556 if (!Symbols)
1557 return Symbols.takeError();
1558
1559 for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
1560 SectionBase *DefSection = nullptr;
1561
1562 Expected<StringRef> Name = Sym.getName(*StrTabData);
1563 if (!Name)
1564 return Name.takeError();
1565
1566 if (Sym.st_shndx == SHN_XINDEX) {
1567 if (SymTab->getShndxTable() == nullptr)
1569 "symbol '" + *Name +
1570 "' has index SHN_XINDEX but no "
1571 "SHT_SYMTAB_SHNDX section exists");
1572 if (ShndxData.data() == nullptr) {
1574 ElfFile.getSection(SymTab->getShndxTable()->Index);
1575 if (!ShndxSec)
1576 return ShndxSec.takeError();
1577
1579 ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
1580 if (!Data)
1581 return Data.takeError();
1582
1583 ShndxData = *Data;
1584 if (ShndxData.size() != Symbols->size())
1585 return createStringError(
1587 "symbol section index table does not have the same number of "
1588 "entries as the symbol table");
1589 }
1590 Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
1591 Expected<SectionBase *> Sec = Obj.sections().getSection(
1592 Index,
1593 "symbol '" + *Name + "' has invalid section index " + Twine(Index));
1594 if (!Sec)
1595 return Sec.takeError();
1596
1597 DefSection = *Sec;
1598 } else if (Sym.st_shndx >= SHN_LORESERVE) {
1599 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
1600 return createStringError(
1602 "symbol '" + *Name +
1603 "' has unsupported value greater than or equal "
1604 "to SHN_LORESERVE: " +
1605 Twine(Sym.st_shndx));
1606 }
1607 } else if (Sym.st_shndx != SHN_UNDEF) {
1608 Expected<SectionBase *> Sec = Obj.sections().getSection(
1609 Sym.st_shndx, "symbol '" + *Name +
1610 "' is defined has invalid section index " +
1611 Twine(Sym.st_shndx));
1612 if (!Sec)
1613 return Sec.takeError();
1614
1615 DefSection = *Sec;
1616 }
1617
1618 SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
1619 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
1620 }
1621
1622 return Error::success();
1623}
1624
1625template <class ELFT>
1627
1628template <class ELFT>
1629static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1630 ToSet = Rela.r_addend;
1631}
1632
1633template <class T>
1634static Error initRelocations(RelocationSection *Relocs, T RelRange) {
1635 for (const auto &Rel : RelRange) {
1636 Relocation ToAdd;
1637 ToAdd.Offset = Rel.r_offset;
1638 getAddend(ToAdd.Addend, Rel);
1639 ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
1640
1641 if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
1642 if (!Relocs->getObject().SymbolTable)
1643 return createStringError(
1645 "'" + Relocs->Name + "': relocation references symbol with index " +
1646 Twine(Sym) + ", but there is no symbol table");
1647 Expected<Symbol *> SymByIndex =
1649 if (!SymByIndex)
1650 return SymByIndex.takeError();
1651
1652 ToAdd.RelocSymbol = *SymByIndex;
1653 }
1654
1655 Relocs->addRelocation(ToAdd);
1656 }
1657
1658 return Error::success();
1659}
1660
1662 Twine ErrMsg) {
1663 if (Index == SHN_UNDEF || Index > Sections.size())
1665 return Sections[Index - 1].get();
1666}
1667
1668template <class T>
1670 Twine IndexErrMsg,
1671 Twine TypeErrMsg) {
1672 Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
1673 if (!BaseSec)
1674 return BaseSec.takeError();
1675
1676 if (T *Sec = dyn_cast<T>(*BaseSec))
1677 return Sec;
1678
1679 return createStringError(errc::invalid_argument, TypeErrMsg);
1680}
1681
1682template <class ELFT>
1684 switch (Shdr.sh_type) {
1685 case SHT_REL:
1686 case SHT_RELA:
1687 if (Shdr.sh_flags & SHF_ALLOC) {
1688 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1689 return Obj.addSection<DynamicRelocationSection>(*Data);
1690 else
1691 return Data.takeError();
1692 }
1693 return Obj.addSection<RelocationSection>(Obj);
1694 case SHT_STRTAB:
1695 // If a string table is allocated we don't want to mess with it. That would
1696 // mean altering the memory image. There are no special link types or
1697 // anything so we can just use a Section.
1698 if (Shdr.sh_flags & SHF_ALLOC) {
1699 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1700 return Obj.addSection<Section>(*Data);
1701 else
1702 return Data.takeError();
1703 }
1704 return Obj.addSection<StringTableSection>();
1705 case SHT_HASH:
1706 case SHT_GNU_HASH:
1707 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1708 // Because of this we don't need to mess with the hash tables either.
1709 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1710 return Obj.addSection<Section>(*Data);
1711 else
1712 return Data.takeError();
1713 case SHT_GROUP:
1714 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1715 return Obj.addSection<GroupSection>(*Data);
1716 else
1717 return Data.takeError();
1718 case SHT_DYNSYM:
1719 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1720 return Obj.addSection<DynamicSymbolTableSection>(*Data);
1721 else
1722 return Data.takeError();
1723 case SHT_DYNAMIC:
1724 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1725 return Obj.addSection<DynamicSection>(*Data);
1726 else
1727 return Data.takeError();
1728 case SHT_SYMTAB: {
1729 // Multiple SHT_SYMTAB sections are forbidden by the ELF gABI.
1730 if (Obj.SymbolTable != nullptr)
1732 "found multiple SHT_SYMTAB sections");
1733 auto &SymTab = Obj.addSection<SymbolTableSection>();
1734 Obj.SymbolTable = &SymTab;
1735 return SymTab;
1736 }
1737 case SHT_SYMTAB_SHNDX: {
1738 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1739 Obj.SectionIndexTable = &ShndxSection;
1740 return ShndxSection;
1741 }
1742 case SHT_NOBITS:
1743 return Obj.addSection<Section>(ArrayRef<uint8_t>());
1744 default: {
1745 Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
1746 if (!Data)
1747 return Data.takeError();
1748
1749 Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
1750 if (!Name)
1751 return Name.takeError();
1752
1753 if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
1754 return Obj.addSection<Section>(*Data);
1755 auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
1756 return Obj.addSection<CompressedSection>(CompressedSection(
1757 *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign));
1758 }
1759 }
1760}
1761
1762template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
1763 uint32_t Index = 0;
1765 ElfFile.sections();
1766 if (!Sections)
1767 return Sections.takeError();
1768
1769 for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
1770 if (Index == 0) {
1771 ++Index;
1772 continue;
1773 }
1774 Expected<SectionBase &> Sec = makeSection(Shdr);
1775 if (!Sec)
1776 return Sec.takeError();
1777
1778 Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
1779 if (!SecName)
1780 return SecName.takeError();
1781 Sec->Name = SecName->str();
1782 Sec->Type = Sec->OriginalType = Shdr.sh_type;
1783 Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
1784 Sec->Addr = Shdr.sh_addr;
1785 Sec->Offset = Shdr.sh_offset;
1786 Sec->OriginalOffset = Shdr.sh_offset;
1787 Sec->Size = Shdr.sh_size;
1788 Sec->Link = Shdr.sh_link;
1789 Sec->Info = Shdr.sh_info;
1790 Sec->Align = Shdr.sh_addralign;
1791 Sec->EntrySize = Shdr.sh_entsize;
1792 Sec->Index = Index++;
1793 Sec->OriginalIndex = Sec->Index;
1794 Sec->OriginalData = ArrayRef<uint8_t>(
1795 ElfFile.base() + Shdr.sh_offset,
1796 (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
1797 }
1798
1799 return Error::success();
1800}
1801
1802template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
1803 uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
1804 if (ShstrIndex == SHN_XINDEX) {
1805 Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
1806 if (!Sec)
1807 return Sec.takeError();
1808
1809 ShstrIndex = (*Sec)->sh_link;
1810 }
1811
1812 if (ShstrIndex == SHN_UNDEF)
1813 Obj.HadShdrs = false;
1814 else {
1816 Obj.sections().template getSectionOfType<StringTableSection>(
1817 ShstrIndex,
1818 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1819 " is invalid",
1820 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1821 " does not reference a string table");
1822 if (!Sec)
1823 return Sec.takeError();
1824
1825 Obj.SectionNames = *Sec;
1826 }
1827
1828 // If a section index table exists we'll need to initialize it before we
1829 // initialize the symbol table because the symbol table might need to
1830 // reference it.
1831 if (Obj.SectionIndexTable)
1832 if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
1833 return Err;
1834
1835 // Now that all of the sections have been added we can fill out some extra
1836 // details about symbol tables. We need the symbol table filled out before
1837 // any relocations.
1838 if (Obj.SymbolTable) {
1839 if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
1840 return Err;
1841 if (Error Err = initSymbolTable(Obj.SymbolTable))
1842 return Err;
1843 } else if (EnsureSymtab) {
1844 if (Error Err = Obj.addNewSymbolTable())
1845 return Err;
1846 }
1847
1848 // Now that all sections and symbols have been added we can add
1849 // relocations that reference symbols and set the link and info fields for
1850 // relocation sections.
1851 for (SectionBase &Sec : Obj.sections()) {
1852 if (&Sec == Obj.SymbolTable)
1853 continue;
1854 if (Error Err = Sec.initialize(Obj.sections()))
1855 return Err;
1856 if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
1858 ElfFile.sections();
1859 if (!Sections)
1860 return Sections.takeError();
1861
1862 const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
1863 Sections->begin() + RelSec->Index;
1864 if (RelSec->Type == SHT_REL) {
1866 ElfFile.rels(*Shdr);
1867 if (!Rels)
1868 return Rels.takeError();
1869
1870 if (Error Err = initRelocations(RelSec, *Rels))
1871 return Err;
1872 } else {
1874 ElfFile.relas(*Shdr);
1875 if (!Relas)
1876 return Relas.takeError();
1877
1878 if (Error Err = initRelocations(RelSec, *Relas))
1879 return Err;
1880 }
1881 } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
1882 if (Error Err = initGroupSection(GroupSec))
1883 return Err;
1884 }
1885 }
1886
1887 return Error::success();
1888}
1889
1890template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
1891 if (Error E = readSectionHeaders())
1892 return E;
1893 if (Error E = findEhdrOffset())
1894 return E;
1895
1896 // The ELFFile whose ELF headers and program headers are copied into the
1897 // output file. Normally the same as ElfFile, but if we're extracting a
1898 // loadable partition it will point to the partition's headers.
1900 {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
1901 if (!HeadersFile)
1902 return HeadersFile.takeError();
1903
1904 const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
1905 Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64;
1906 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1907 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
1908 Obj.Type = Ehdr.e_type;
1909 Obj.Machine = Ehdr.e_machine;
1910 Obj.Version = Ehdr.e_version;
1911 Obj.Entry = Ehdr.e_entry;
1912 Obj.Flags = Ehdr.e_flags;
1913
1914 if (Error E = readSections(EnsureSymtab))
1915 return E;
1916 return readProgramHeaders(*HeadersFile);
1917}
1918
1919Writer::~Writer() = default;
1920
1921Reader::~Reader() = default;
1922
1924BinaryReader::create(bool /*EnsureSymtab*/) const {
1925 return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
1926}
1927
1928Expected<std::vector<IHexRecord>> IHexReader::parse() const {
1930 std::vector<IHexRecord> Records;
1931 bool HasSections = false;
1932
1933 MemBuf->getBuffer().split(Lines, '\n');
1934 Records.reserve(Lines.size());
1935 for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
1936 StringRef Line = Lines[LineNo - 1].trim();
1937 if (Line.empty())
1938 continue;
1939
1941 if (!R)
1942 return parseError(LineNo, R.takeError());
1943 if (R->Type == IHexRecord::EndOfFile)
1944 break;
1945 HasSections |= (R->Type == IHexRecord::Data);
1946 Records.push_back(*R);
1947 }
1948 if (!HasSections)
1949 return parseError(-1U, "no sections");
1950
1951 return std::move(Records);
1952}
1953
1955IHexReader::create(bool /*EnsureSymtab*/) const {
1957 if (!Records)
1958 return Records.takeError();
1959
1960 return IHexELFBuilder(*Records).build();
1961}
1962
1964 auto Obj = std::make_unique<Object>();
1965 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1966 ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
1967 if (Error Err = Builder.build(EnsureSymtab))
1968 return std::move(Err);
1969 return std::move(Obj);
1970 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1971 ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
1972 if (Error Err = Builder.build(EnsureSymtab))
1973 return std::move(Err);
1974 return std::move(Obj);
1975 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1976 ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
1977 if (Error Err = Builder.build(EnsureSymtab))
1978 return std::move(Err);
1979 return std::move(Obj);
1980 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1981 ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
1982 if (Error Err = Builder.build(EnsureSymtab))
1983 return std::move(Err);
1984 return std::move(Obj);
1985 }
1986 return createStringError(errc::invalid_argument, "invalid file type");
1987}
1988
1989template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
1990 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
1991 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1992 Ehdr.e_ident[EI_MAG0] = 0x7f;
1993 Ehdr.e_ident[EI_MAG1] = 'E';
1994 Ehdr.e_ident[EI_MAG2] = 'L';
1995 Ehdr.e_ident[EI_MAG3] = 'F';
1996 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1997 Ehdr.e_ident[EI_DATA] =
1998 ELFT::Endianness == llvm::endianness::big ? ELFDATA2MSB : ELFDATA2LSB;
1999 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
2000 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
2001 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
2002
2003 Ehdr.e_type = Obj.Type;
2004 Ehdr.e_machine = Obj.Machine;
2005 Ehdr.e_version = Obj.Version;
2006 Ehdr.e_entry = Obj.Entry;
2007 // We have to use the fully-qualified name llvm::size
2008 // since some compilers complain on ambiguous resolution.
2009 Ehdr.e_phnum = llvm::size(Obj.segments());
2010 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
2011 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
2012 Ehdr.e_flags = Obj.Flags;
2013 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
2014 if (WriteSectionHeaders && Obj.sections().size() != 0) {
2015 Ehdr.e_shentsize = sizeof(Elf_Shdr);
2016 Ehdr.e_shoff = Obj.SHOff;
2017 // """
2018 // If the number of sections is greater than or equal to
2019 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
2020 // number of section header table entries is contained in the sh_size field
2021 // of the section header at index 0.
2022 // """
2023 auto Shnum = Obj.sections().size() + 1;
2024 if (Shnum >= SHN_LORESERVE)
2025 Ehdr.e_shnum = 0;
2026 else
2027 Ehdr.e_shnum = Shnum;
2028 // """
2029 // If the section name string table section index is greater than or equal
2030 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
2031 // and the actual index of the section name string table section is
2032 // contained in the sh_link field of the section header at index 0.
2033 // """
2034 if (Obj.SectionNames->Index >= SHN_LORESERVE)
2035 Ehdr.e_shstrndx = SHN_XINDEX;
2036 else
2037 Ehdr.e_shstrndx = Obj.SectionNames->Index;
2038 } else {
2039 Ehdr.e_shentsize = 0;
2040 Ehdr.e_shoff = 0;
2041 Ehdr.e_shnum = 0;
2042 Ehdr.e_shstrndx = 0;
2043 }
2044}
2045
2046template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
2047 for (auto &Seg : Obj.segments())
2048 writePhdr(Seg);
2049}
2050
2051template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
2052 // This reference serves to write the dummy section header at the begining
2053 // of the file. It is not used for anything else
2054 Elf_Shdr &Shdr =
2055 *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
2056 Shdr.sh_name = 0;
2057 Shdr.sh_type = SHT_NULL;
2058 Shdr.sh_flags = 0;
2059 Shdr.sh_addr = 0;
2060 Shdr.sh_offset = 0;
2061 // See writeEhdr for why we do this.
2062 uint64_t Shnum = Obj.sections().size() + 1;
2063 if (Shnum >= SHN_LORESERVE)
2064 Shdr.sh_size = Shnum;
2065 else
2066 Shdr.sh_size = 0;
2067 // See writeEhdr for why we do this.
2068 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
2069 Shdr.sh_link = Obj.SectionNames->Index;
2070 else
2071 Shdr.sh_link = 0;
2072 Shdr.sh_info = 0;
2073 Shdr.sh_addralign = 0;
2074 Shdr.sh_entsize = 0;
2075
2076 for (SectionBase &Sec : Obj.sections())
2077 writeShdr(Sec);
2078}
2079
2080template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
2081 for (SectionBase &Sec : Obj.sections())
2082 // Segments are responsible for writing their contents, so only write the
2083 // section data if the section is not in a segment. Note that this renders
2084 // sections in segments effectively immutable.
2085 if (Sec.ParentSegment == nullptr)
2086 if (Error Err = Sec.accept(*SecWriter))
2087 return Err;
2088
2089 return Error::success();
2090}
2091
2092template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
2093 for (Segment &Seg : Obj.segments()) {
2094 size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
2095 std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
2096 Size);
2097 }
2098
2099 for (const auto &it : Obj.getUpdatedSections()) {
2100 SectionBase *Sec = it.first;
2101 ArrayRef<uint8_t> Data = it.second;
2102
2103 auto *Parent = Sec->ParentSegment;
2104 assert(Parent && "This section should've been part of a segment.");
2106 Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2107 llvm::copy(Data, Buf->getBufferStart() + Offset);
2108 }
2109
2110 // Iterate over removed sections and overwrite their old data with zeroes.
2111 for (auto &Sec : Obj.removedSections()) {
2112 Segment *Parent = Sec.ParentSegment;
2113 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
2114 continue;
2116 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2117 std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
2118 }
2119}
2120
2121template <class ELFT>
2123 bool OnlyKeepDebug)
2124 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
2125 OnlyKeepDebug(OnlyKeepDebug) {}
2126
2128 auto It = llvm::find_if(Sections,
2129 [&](const SecPtr &Sec) { return Sec->Name == Name; });
2130 if (It == Sections.end())
2131 return createStringError(errc::invalid_argument, "section '%s' not found",
2132 Name.str().c_str());
2133
2134 auto *OldSec = It->get();
2135 if (!OldSec->hasContents())
2136 return createStringError(
2138 "section '%s' cannot be updated because it does not have contents",
2139 Name.str().c_str());
2140
2141 if (Data.size() > OldSec->Size && OldSec->ParentSegment)
2143 "cannot fit data of size %zu into section '%s' "
2144 "with size %" PRIu64 " that is part of a segment",
2145 Data.size(), Name.str().c_str(), OldSec->Size);
2146
2147 if (!OldSec->ParentSegment) {
2148 *It = std::make_unique<OwnedDataSection>(*OldSec, Data);
2149 } else {
2150 // The segment writer will be in charge of updating these contents.
2151 OldSec->Size = Data.size();
2152 UpdatedSections[OldSec] = Data;
2153 }
2154
2155 return Error::success();
2156}
2157
2159 bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
2160
2161 auto Iter = std::stable_partition(
2162 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
2163 if (ToRemove(*Sec))
2164 return false;
2165 // TODO: A compressed relocation section may be recognized as
2166 // RelocationSectionBase. We don't want such a section to be removed.
2167 if (isa<CompressedSection>(Sec))
2168 return true;
2169 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
2170 if (auto ToRelSec = RelSec->getSection())
2171 return !ToRemove(*ToRelSec);
2172 }
2173 return true;
2174 });
2175 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
2176 SymbolTable = nullptr;
2177 if (SectionNames != nullptr && ToRemove(*SectionNames))
2178 SectionNames = nullptr;
2179 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
2180 SectionIndexTable = nullptr;
2181 // Now make sure there are no remaining references to the sections that will
2182 // be removed. Sometimes it is impossible to remove a reference so we emit
2183 // an error here instead.
2184 std::unordered_set<const SectionBase *> RemoveSections;
2185 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
2186 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
2187 for (auto &Segment : Segments)
2188 Segment->removeSection(RemoveSec.get());
2189 RemoveSec->onRemove();
2190 RemoveSections.insert(RemoveSec.get());
2191 }
2192
2193 // For each section that remains alive, we want to remove the dead references.
2194 // This either might update the content of the section (e.g. remove symbols
2195 // from symbol table that belongs to removed section) or trigger an error if
2196 // a live section critically depends on a section being removed somehow
2197 // (e.g. the removed section is referenced by a relocation).
2198 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
2199 if (Error E = KeepSec->removeSectionReferences(
2200 AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
2201 return RemoveSections.find(Sec) != RemoveSections.end();
2202 }))
2203 return E;
2204 }
2205
2206 // Transfer removed sections into the Object RemovedSections container for use
2207 // later.
2208 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
2209 // Now finally get rid of them all together.
2210 Sections.erase(Iter, std::end(Sections));
2211 return Error::success();
2212}
2213
2216 auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
2217 return Lhs->Index < Rhs->Index;
2218 };
2219 assert(llvm::is_sorted(Sections, SectionIndexLess) &&
2220 "Sections are expected to be sorted by Index");
2221 // Set indices of new sections so that they can be later sorted into positions
2222 // of removed ones.
2223 for (auto &I : FromTo)
2224 I.second->Index = I.first->Index;
2225
2226 // Notify all sections about the replacement.
2227 for (auto &Sec : Sections)
2228 Sec->replaceSectionReferences(FromTo);
2229
2230 if (Error E = removeSections(
2231 /*AllowBrokenLinks=*/false,
2232 [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
2233 return E;
2234 llvm::sort(Sections, SectionIndexLess);
2235 return Error::success();
2236}
2237
2239 if (SymbolTable)
2240 for (const SecPtr &Sec : Sections)
2241 if (Error E = Sec->removeSymbols(ToRemove))
2242 return E;
2243 return Error::success();
2244}
2245
2247 assert(!SymbolTable && "Object must not has a SymbolTable.");
2248
2249 // Reuse an existing SHT_STRTAB section if it exists.
2250 StringTableSection *StrTab = nullptr;
2251 for (SectionBase &Sec : sections()) {
2252 if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
2253 StrTab = static_cast<StringTableSection *>(&Sec);
2254
2255 // Prefer a string table that is not the section header string table, if
2256 // such a table exists.
2257 if (SectionNames != &Sec)
2258 break;
2259 }
2260 }
2261 if (!StrTab)
2262 StrTab = &addSection<StringTableSection>();
2263
2264 SymbolTableSection &SymTab = addSection<SymbolTableSection>();
2265 SymTab.Name = ".symtab";
2266 SymTab.Link = StrTab->Index;
2267 if (Error Err = SymTab.initialize(sections()))
2268 return Err;
2269 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
2270
2271 SymbolTable = &SymTab;
2272
2273 return Error::success();
2274}
2275
2276// Orders segments such that if x = y->ParentSegment then y comes before x.
2277static void orderSegments(std::vector<Segment *> &Segments) {
2279}
2280
2281// This function finds a consistent layout for a list of segments starting from
2282// an Offset. It assumes that Segments have been sorted by orderSegments and
2283// returns an Offset one past the end of the last segment.
2284static uint64_t layoutSegments(std::vector<Segment *> &Segments,
2285 uint64_t Offset) {
2287 // The only way a segment should move is if a section was between two
2288 // segments and that section was removed. If that section isn't in a segment
2289 // then it's acceptable, but not ideal, to simply move it to after the
2290 // segments. So we can simply layout segments one after the other accounting
2291 // for alignment.
2292 for (Segment *Seg : Segments) {
2293 // We assume that segments have been ordered by OriginalOffset and Index
2294 // such that a parent segment will always come before a child segment in
2295 // OrderedSegments. This means that the Offset of the ParentSegment should
2296 // already be set and we can set our offset relative to it.
2297 if (Seg->ParentSegment != nullptr) {
2298 Segment *Parent = Seg->ParentSegment;
2299 Seg->Offset =
2300 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
2301 } else {
2302 Seg->Offset =
2303 alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
2304 }
2305 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
2306 }
2307 return Offset;
2308}
2309
2310// This function finds a consistent layout for a list of sections. It assumes
2311// that the ->ParentSegment of each section has already been laid out. The
2312// supplied starting Offset is used for the starting offset of any section that
2313// does not have a ParentSegment. It returns either the offset given if all
2314// sections had a ParentSegment or an offset one past the last section if there
2315// was a section that didn't have a ParentSegment.
2316template <class Range>
2317static uint64_t layoutSections(Range Sections, uint64_t Offset) {
2318 // Now the offset of every segment has been set we can assign the offsets
2319 // of each section. For sections that are covered by a segment we should use
2320 // the segment's original offset and the section's original offset to compute
2321 // the offset from the start of the segment. Using the offset from the start
2322 // of the segment we can assign a new offset to the section. For sections not
2323 // covered by segments we can just bump Offset to the next valid location.
2324 // While it is not necessary, layout the sections in the order based on their
2325 // original offsets to resemble the input file as close as possible.
2326 std::vector<SectionBase *> OutOfSegmentSections;
2327 uint32_t Index = 1;
2328 for (auto &Sec : Sections) {
2329 Sec.Index = Index++;
2330 if (Sec.ParentSegment != nullptr) {
2331 const Segment &Segment = *Sec.ParentSegment;
2332 Sec.Offset =
2333 Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
2334 } else
2335 OutOfSegmentSections.push_back(&Sec);
2336 }
2337
2338 llvm::stable_sort(OutOfSegmentSections,
2339 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2340 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2341 });
2342 for (auto *Sec : OutOfSegmentSections) {
2343 Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
2344 Sec->Offset = Offset;
2345 if (Sec->Type != SHT_NOBITS)
2346 Offset += Sec->Size;
2347 }
2348 return Offset;
2349}
2350
2351// Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
2352// occupy no space in the file.
2354 // The layout algorithm requires the sections to be handled in the order of
2355 // their offsets in the input file, at least inside segments.
2356 std::vector<SectionBase *> Sections;
2357 Sections.reserve(Obj.sections().size());
2358 uint32_t Index = 1;
2359 for (auto &Sec : Obj.sections()) {
2360 Sec.Index = Index++;
2361 Sections.push_back(&Sec);
2362 }
2363 llvm::stable_sort(Sections,
2364 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2365 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2366 });
2367
2368 for (auto *Sec : Sections) {
2369 auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
2370 ? Sec->ParentSegment->firstSection()
2371 : nullptr;
2372
2373 // The first section in a PT_LOAD has to have congruent offset and address
2374 // modulo the alignment, which usually equals the maximum page size.
2375 if (FirstSec && FirstSec == Sec)
2376 Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
2377
2378 // sh_offset is not significant for SHT_NOBITS sections, but the congruence
2379 // rule must be followed if it is the first section in a PT_LOAD. Do not
2380 // advance Off.
2381 if (Sec->Type == SHT_NOBITS) {
2382 Sec->Offset = Off;
2383 continue;
2384 }
2385
2386 if (!FirstSec) {
2387 // FirstSec being nullptr generally means that Sec does not have the
2388 // SHF_ALLOC flag.
2389 Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
2390 } else if (FirstSec != Sec) {
2391 // The offset is relative to the first section in the PT_LOAD segment. Use
2392 // sh_offset for non-SHF_ALLOC sections.
2393 Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
2394 }
2395 Sec->Offset = Off;
2396 Off += Sec->Size;
2397 }
2398 return Off;
2399}
2400
2401// Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
2402// have been updated.
2403static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
2404 uint64_t HdrEnd) {
2405 uint64_t MaxOffset = 0;
2406 for (Segment *Seg : Segments) {
2407 if (Seg->Type == PT_PHDR)
2408 continue;
2409
2410 // The segment offset is generally the offset of the first section.
2411 //
2412 // For a segment containing no section (see sectionWithinSegment), if it has
2413 // a parent segment, copy the parent segment's offset field. This works for
2414 // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
2415 // debugging anyway.
2416 const SectionBase *FirstSec = Seg->firstSection();
2418 FirstSec ? FirstSec->Offset
2419 : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
2420 uint64_t FileSize = 0;
2421 for (const SectionBase *Sec : Seg->Sections) {
2422 uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
2423 if (Sec->Offset + Size > Offset)
2424 FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
2425 }
2426
2427 // If the segment includes EHDR and program headers, don't make it smaller
2428 // than the headers.
2429 if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
2430 FileSize += Offset - Seg->Offset;
2431 Offset = Seg->Offset;
2432 FileSize = std::max(FileSize, HdrEnd - Offset);
2433 }
2434
2435 Seg->Offset = Offset;
2436 Seg->FileSize = FileSize;
2437 MaxOffset = std::max(MaxOffset, Offset + FileSize);
2438 }
2439 return MaxOffset;
2440}
2441
2442template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
2443 Segment &ElfHdr = Obj.ElfHdrSegment;
2444 ElfHdr.Type = PT_PHDR;
2445 ElfHdr.Flags = 0;
2446 ElfHdr.VAddr = 0;
2447 ElfHdr.PAddr = 0;
2448 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
2449 ElfHdr.Align = 0;
2450}
2451
2452template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
2453 // We need a temporary list of segments that has a special order to it
2454 // so that we know that anytime ->ParentSegment is set that segment has
2455 // already had its offset properly set.
2456 std::vector<Segment *> OrderedSegments;
2457 for (Segment &Segment : Obj.segments())
2458 OrderedSegments.push_back(&Segment);
2459 OrderedSegments.push_back(&Obj.ElfHdrSegment);
2460 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
2461 orderSegments(OrderedSegments);
2462
2464 if (OnlyKeepDebug) {
2465 // For --only-keep-debug, the sections that did not preserve contents were
2466 // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
2467 // then rewrite p_offset/p_filesz of program headers.
2468 uint64_t HdrEnd =
2469 sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
2471 Offset = std::max(Offset,
2472 layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
2473 } else {
2474 // Offset is used as the start offset of the first segment to be laid out.
2475 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
2476 // we start at offset 0.
2477 Offset = layoutSegments(OrderedSegments, 0);
2478 Offset = layoutSections(Obj.sections(), Offset);
2479 }
2480 // If we need to write the section header table out then we need to align the
2481 // Offset so that SHOffset is valid.
2482 if (WriteSectionHeaders)
2483 Offset = alignTo(Offset, sizeof(Elf_Addr));
2484 Obj.SHOff = Offset;
2485}
2486
2487template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
2488 // We already have the section header offset so we can calculate the total
2489 // size by just adding up the size of each section header.
2490 if (!WriteSectionHeaders)
2491 return Obj.SHOff;
2492 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
2493 return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
2494}
2495
2496template <class ELFT> Error ELFWriter<ELFT>::write() {
2497 // Segment data must be written first, so that the ELF header and program
2498 // header tables can overwrite it, if covered by a segment.
2499 writeSegmentData();
2500 writeEhdr();
2501 writePhdrs();
2502 if (Error E = writeSectionData())
2503 return E;
2504 if (WriteSectionHeaders)
2505 writeShdrs();
2506
2507 // TODO: Implement direct writing to the output stream (without intermediate
2508 // memory buffer Buf).
2509 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2510 return Error::success();
2511}
2512
2514 // We can remove an empty symbol table from non-relocatable objects.
2515 // Relocatable objects typically have relocation sections whose
2516 // sh_link field points to .symtab, so we can't remove .symtab
2517 // even if it is empty.
2518 if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
2519 !Obj.SymbolTable->empty())
2520 return Error::success();
2521
2522 // .strtab can be used for section names. In such a case we shouldn't
2523 // remove it.
2524 auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
2525 ? nullptr
2526 : Obj.SymbolTable->getStrTab();
2527 return Obj.removeSections(false, [&](const SectionBase &Sec) {
2528 return &Sec == Obj.SymbolTable || &Sec == StrTab;
2529 });
2530}
2531
2532template <class ELFT> Error ELFWriter<ELFT>::finalize() {
2533 // It could happen that SectionNames has been removed and yet the user wants
2534 // a section header table output. We need to throw an error if a user tries
2535 // to do that.
2536 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
2538 "cannot write section header table because "
2539 "section header string table was removed");
2540
2541 if (Error E = removeUnneededSections(Obj))
2542 return E;
2543
2544 // If the .symtab indices have not been changed, restore the sh_link to
2545 // .symtab for sections that were linked to .symtab.
2546 if (Obj.SymbolTable && !Obj.SymbolTable->indicesChanged())
2547 for (SectionBase &Sec : Obj.sections())
2548 Sec.restoreSymTabLink(*Obj.SymbolTable);
2549
2550 // We need to assign indexes before we perform layout because we need to know
2551 // if we need large indexes or not. We can assign indexes first and check as
2552 // we go to see if we will actully need large indexes.
2553 bool NeedsLargeIndexes = false;
2554 if (Obj.sections().size() >= SHN_LORESERVE) {
2555 SectionTableRef Sections = Obj.sections();
2556 // Sections doesn't include the null section header, so account for this
2557 // when skipping the first N sections.
2558 NeedsLargeIndexes =
2559 any_of(drop_begin(Sections, SHN_LORESERVE - 1),
2560 [](const SectionBase &Sec) { return Sec.HasSymbol; });
2561 // TODO: handle case where only one section needs the large index table but
2562 // only needs it because the large index table hasn't been removed yet.
2563 }
2564
2565 if (NeedsLargeIndexes) {
2566 // This means we definitely need to have a section index table but if we
2567 // already have one then we should use it instead of making a new one.
2568 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
2569 // Addition of a section to the end does not invalidate the indexes of
2570 // other sections and assigns the correct index to the new section.
2571 auto &Shndx = Obj.addSection<SectionIndexSection>();
2572 Obj.SymbolTable->setShndxTable(&Shndx);
2573 Shndx.setSymTab(Obj.SymbolTable);
2574 }
2575 } else {
2576 // Since we don't need SectionIndexTable we should remove it and all
2577 // references to it.
2578 if (Obj.SectionIndexTable != nullptr) {
2579 // We do not support sections referring to the section index table.
2580 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
2581 [this](const SectionBase &Sec) {
2582 return &Sec == Obj.SectionIndexTable;
2583 }))
2584 return E;
2585 }
2586 }
2587
2588 // Make sure we add the names of all the sections. Importantly this must be
2589 // done after we decide to add or remove SectionIndexes.
2590 if (Obj.SectionNames != nullptr)
2591 for (const SectionBase &Sec : Obj.sections())
2592 Obj.SectionNames->addString(Sec.Name);
2593
2594 initEhdrSegment();
2595
2596 // Before we can prepare for layout the indexes need to be finalized.
2597 // Also, the output arch may not be the same as the input arch, so fix up
2598 // size-related fields before doing layout calculations.
2599 uint64_t Index = 0;
2600 auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
2601 for (SectionBase &Sec : Obj.sections()) {
2602 Sec.Index = Index++;
2603 if (Error Err = Sec.accept(*SecSizer))
2604 return Err;
2605 }
2606
2607 // The symbol table does not update all other sections on update. For
2608 // instance, symbol names are not added as new symbols are added. This means
2609 // that some sections, like .strtab, don't yet have their final size.
2610 if (Obj.SymbolTable != nullptr)
2611 Obj.SymbolTable->prepareForLayout();
2612
2613 // Now that all strings are added we want to finalize string table builders,
2614 // because that affects section sizes which in turn affects section offsets.
2615 for (SectionBase &Sec : Obj.sections())
2616 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
2617 StrTab->prepareForLayout();
2618
2619 assignOffsets();
2620
2621 // layoutSections could have modified section indexes, so we need
2622 // to fill the index table after assignOffsets.
2623 if (Obj.SymbolTable != nullptr)
2624 Obj.SymbolTable->fillShndxTable();
2625
2626 // Finally now that all offsets and indexes have been set we can finalize any
2627 // remaining issues.
2628 uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
2629 for (SectionBase &Sec : Obj.sections()) {
2630 Sec.HeaderOffset = Offset;
2631 Offset += sizeof(Elf_Shdr);
2632 if (WriteSectionHeaders)
2633 Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
2634 Sec.finalize();
2635 }
2636
2637 size_t TotalSize = totalSize();
2639 if (!Buf)
2641 "failed to allocate memory buffer of " +
2642 Twine::utohexstr(TotalSize) + " bytes");
2643
2644 SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
2645 return Error::success();
2646}
2647
2650 for (const SectionBase &Sec : Obj.allocSections()) {
2651 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2652 SectionsToWrite.push_back(&Sec);
2653 }
2654
2655 if (SectionsToWrite.empty())
2656 return Error::success();
2657
2658 llvm::stable_sort(SectionsToWrite,
2659 [](const SectionBase *LHS, const SectionBase *RHS) {
2660 return LHS->Offset < RHS->Offset;
2661 });
2662
2663 assert(SectionsToWrite.front()->Offset == 0);
2664
2665 for (size_t i = 0; i != SectionsToWrite.size(); ++i) {
2666 const SectionBase &Sec = *SectionsToWrite[i];
2667 if (Error Err = Sec.accept(*SecWriter))
2668 return Err;
2669 if (GapFill == 0)
2670 continue;
2671 uint64_t PadOffset = (i < SectionsToWrite.size() - 1)
2672 ? SectionsToWrite[i + 1]->Offset
2673 : Buf->getBufferSize();
2674 assert(PadOffset <= Buf->getBufferSize());
2675 assert(Sec.Offset + Sec.Size <= PadOffset);
2676 std::fill(Buf->getBufferStart() + Sec.Offset + Sec.Size,
2677 Buf->getBufferStart() + PadOffset, GapFill);
2678 }
2679
2680 // TODO: Implement direct writing to the output stream (without intermediate
2681 // memory buffer Buf).
2682 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2683 return Error::success();
2684}
2685
2687 // Compute the section LMA based on its sh_offset and the containing segment's
2688 // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
2689 // sections as MinAddr. In the output, the contents between address 0 and
2690 // MinAddr will be skipped.
2691 uint64_t MinAddr = UINT64_MAX;
2692 for (SectionBase &Sec : Obj.allocSections()) {
2693 if (Sec.ParentSegment != nullptr)
2694 Sec.Addr =
2695 Sec.Offset - Sec.ParentSegment->Offset + Sec.ParentSegment->PAddr;
2696 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2697 MinAddr = std::min(MinAddr, Sec.Addr);
2698 }
2699
2700 // Now that every section has been laid out we just need to compute the total
2701 // file size. This might not be the same as the offset returned by
2702 // layoutSections, because we want to truncate the last segment to the end of
2703 // its last non-empty section, to match GNU objcopy's behaviour.
2704 TotalSize = PadTo > MinAddr ? PadTo - MinAddr : 0;
2705 for (SectionBase &Sec : Obj.allocSections())
2706 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
2707 Sec.Offset = Sec.Addr - MinAddr;
2708 TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
2709 }
2710
2712 if (!Buf)
2714 "failed to allocate memory buffer of " +
2715 Twine::utohexstr(TotalSize) + " bytes");
2716 SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
2717 return Error::success();
2718}
2719
2721 if (addressOverflows32bit(S.Addr) ||
2722 addressOverflows32bit(S.Addr + S.Size - 1))
2723 return createStringError(
2725 "section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
2726 S.Name.c_str(), S.Addr, S.Addr + S.Size - 1);
2727 return Error::success();
2728}
2729
2731 // We can't write 64-bit addresses.
2734 "entry point address 0x%llx overflows 32 bits",
2735 Obj.Entry);
2736
2737 for (const SectionBase &S : Obj.sections()) {
2738 if ((S.Flags & ELF::SHF_ALLOC) && S.Type != ELF::SHT_NOBITS && S.Size > 0) {
2739 if (Error E = checkSection(S))
2740 return E;
2741 Sections.push_back(&S);
2742 }
2743 }
2744
2745 llvm::sort(Sections, [](const SectionBase *A, const SectionBase *B) {
2747 });
2748
2749 std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
2751 if (!EmptyBuffer)
2753 "failed to allocate memory buffer of 0 bytes");
2754
2755 Expected<size_t> ExpTotalSize = getTotalSize(*EmptyBuffer);
2756 if (!ExpTotalSize)
2757 return ExpTotalSize.takeError();
2758 TotalSize = *ExpTotalSize;
2759
2761 if (!Buf)
2763 "failed to allocate memory buffer of 0x" +
2764 Twine::utohexstr(TotalSize) + " bytes");
2765 return Error::success();
2766}
2767
2768uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
2769 IHexLineData HexData;
2770 uint8_t Data[4] = {};
2771 // We don't write entry point record if entry is zero.
2772 if (Obj.Entry == 0)
2773 return 0;
2774
2775 if (Obj.Entry <= 0xFFFFFU) {
2776 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
2777 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
2780 } else {
2784 }
2785 memcpy(Buf, HexData.data(), HexData.size());
2786 return HexData.size();
2787}
2788
2789uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
2791 memcpy(Buf, HexData.data(), HexData.size());
2792 return HexData.size();
2793}
2794
2796IHexWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
2797 IHexSectionWriterBase LengthCalc(EmptyBuffer);
2798 for (const SectionBase *Sec : Sections)
2799 if (Error Err = Sec->accept(LengthCalc))
2800 return std::move(Err);
2801
2802 // We need space to write section records + StartAddress record
2803 // (if start adress is not zero) + EndOfFile record.
2804 return LengthCalc.getBufferOffset() +
2806 IHexRecord::getLineLength(0);
2807}
2808
2811 // Write sections.
2812 for (const SectionBase *Sec : Sections)
2813 if (Error Err = Sec->accept(Writer))
2814 return Err;
2815
2816 uint64_t Offset = Writer.getBufferOffset();
2817 // Write entry point address.
2818 Offset += writeEntryPointRecord(
2819 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2820 // Write EOF.
2821 Offset += writeEndOfFileRecord(
2822 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2824
2825 // TODO: Implement direct writing to the output stream (without intermediate
2826 // memory buffer Buf).
2827 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2828 return Error::success();
2829}
2830
2832 // Check that the sizer has already done its work.
2833 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2834 "Expected section size to have been finalized");
2835 // We don't need to write anything here because the real writer has already
2836 // done it.
2837 return Error::success();
2838}
2839
2841 writeSection(Sec, Sec.Contents);
2842 return Error::success();
2843}
2844
2846 writeSection(Sec, Sec.Data);
2847 return Error::success();
2848}
2849
2851 writeSection(Sec, Sec.Contents);
2852 return Error::success();
2853}
2854
2856 SRecLineData Data = Record.toString();
2857 memcpy(Out.getBufferStart() + Off, Data.data(), Data.size());
2858}
2859
2861 // The ELF header could contain an entry point outside of the sections we have
2862 // seen that does not fit the current record Type.
2863 Type = std::max(Type, SRecord::getType(Entry));
2864 uint64_t Off = HeaderSize;
2865 for (SRecord &Record : Records) {
2866 Record.Type = Type;
2867 writeRecord(Record, Off);
2868 Off += Record.getSize();
2869 }
2870 Offset = Off;
2871}
2872
2875 const uint32_t ChunkSize = 16;
2877 uint32_t EndAddr = Address + S.Size - 1;
2878 Type = std::max(SRecord::getType(EndAddr), Type);
2879 while (!Data.empty()) {
2880 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
2881 SRecord Record{Type, Address, Data.take_front(DataSize)};
2882 Records.push_back(Record);
2883 Data = Data.drop_front(DataSize);
2884 Address += DataSize;
2885 }
2886}
2887
2889 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2890 "Section size does not match the section's string table builder size");
2891 std::vector<uint8_t> Data(Sec.Size);
2892 Sec.StrTabBuilder.write(Data.data());
2893 writeSection(Sec, Data);
2894 return Error::success();
2895}
2896
2898 SRecLineData Line(getSize());
2899 auto *Iter = Line.begin();
2900 *Iter++ = 'S';
2901 *Iter++ = '0' + Type;
2902 // Write 1 byte (2 hex characters) record count.
2903 Iter = toHexStr(getCount(), Iter, 2);
2904 // Write the address field with length depending on record type.
2905 Iter = toHexStr(Address, Iter, getAddressSize());
2906 // Write data byte by byte.
2907 for (uint8_t X : Data)
2908 Iter = toHexStr(X, Iter, 2);
2909 // Write the 1 byte checksum.
2910 Iter = toHexStr(getChecksum(), Iter, 2);
2911 *Iter++ = '\r';
2912 *Iter++ = '\n';
2913 assert(Iter == Line.end());
2914 return Line;
2915}
2916
2917uint8_t SRecord::getChecksum() const {
2918 uint32_t Sum = getCount();
2919 Sum += (Address >> 24) & 0xFF;
2920 Sum += (Address >> 16) & 0xFF;
2921 Sum += (Address >> 8) & 0xFF;
2922 Sum += Address & 0xFF;
2923 for (uint8_t Byte : Data)
2924 Sum += Byte;
2925 return 0xFF - (Sum & 0xFF);
2926}
2927
2928size_t SRecord::getSize() const {
2929 // Type, Count, Checksum, and CRLF are two characters each.
2930 return 2 + 2 + getAddressSize() + Data.size() * 2 + 2 + 2;
2931}
2932
2934 switch (Type) {
2935 case Type::S2:
2936 return 6;
2937 case Type::S3:
2938 return 8;
2939 case Type::S7:
2940 return 8;
2941 case Type::S8:
2942 return 6;
2943 default:
2944 return 4;
2945 }
2946}
2947
2948uint8_t SRecord::getCount() const {
2949 uint8_t DataSize = Data.size();
2950 uint8_t ChecksumSize = 1;
2951 return getAddressSize() / 2 + DataSize + ChecksumSize;
2952}
2953
2955 if (isUInt<16>(Address))
2956 return SRecord::S1;
2957 if (isUInt<24>(Address))
2958 return SRecord::S2;
2959 return SRecord::S3;
2960}
2961
2963 // Header is a record with Type S0, Address 0, and Data that is a
2964 // vendor-specific text comment. For the comment we will use the output file
2965 // name truncated to 40 characters to match the behavior of GNU objcopy.
2966 StringRef HeaderContents = FileName.slice(0, 40);
2968 reinterpret_cast<const uint8_t *>(HeaderContents.data()),
2969 HeaderContents.size());
2970 return {SRecord::S0, 0, Data};
2971}
2972
2973size_t SRECWriter::writeHeader(uint8_t *Buf) {
2975 memcpy(Buf, Record.data(), Record.size());
2976 return Record.size();
2977}
2978
2979size_t SRECWriter::writeTerminator(uint8_t *Buf, uint8_t Type) {
2981 "Invalid record type for terminator");
2982 uint32_t Entry = Obj.Entry;
2983 SRecLineData Data = SRecord{Type, Entry, {}}.toString();
2984 memcpy(Buf, Data.data(), Data.size());
2985 return Data.size();
2986}
2987
2989SRECWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
2990 SRECSizeCalculator SizeCalc(EmptyBuffer, 0);
2991 for (const SectionBase *Sec : Sections)
2992 if (Error Err = Sec->accept(SizeCalc))
2993 return std::move(Err);
2994
2995 SizeCalc.writeRecords(Obj.Entry);
2996 // We need to add the size of the Header and Terminator records.
2998 uint8_t TerminatorType = 10 - SizeCalc.getType();
2999 SRecord Terminator = {TerminatorType, static_cast<uint32_t>(Obj.Entry), {}};
3000 return Header.getSize() + SizeCalc.getBufferOffset() + Terminator.getSize();
3001}
3002
3004 uint32_t HeaderSize =
3005 writeHeader(reinterpret_cast<uint8_t *>(Buf->getBufferStart()));
3006 SRECSectionWriter Writer(*Buf, HeaderSize);
3007 for (const SectionBase *S : Sections) {
3008 if (Error E = S->accept(Writer))
3009 return E;
3010 }
3011 Writer.writeRecords(Obj.Entry);
3012 uint64_t Offset = Writer.getBufferOffset();
3013
3014 // An S1 record terminates with an S9 record, S2 with S8, and S3 with S7.
3015 uint8_t TerminatorType = 10 - Writer.getType();
3016 Offset += writeTerminator(
3017 reinterpret_cast<uint8_t *>(Buf->getBufferStart() + Offset),
3018 TerminatorType);
3020 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
3021 return Error::success();
3022}
3023
3024namespace llvm {
3025namespace objcopy {
3026namespace elf {
3027
3028template class ELFBuilder<ELF64LE>;
3029template class ELFBuilder<ELF64BE>;
3030template class ELFBuilder<ELF32LE>;
3031template class ELFBuilder<ELF32BE>;
3032
3033template class ELFWriter<ELF64LE>;
3034template class ELFWriter<ELF64BE>;
3035template class ELFWriter<ELF32LE>;
3036template class ELFWriter<ELF32BE>;
3037
3038} // end namespace elf
3039} // end namespace objcopy
3040} // 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:1225
static void setAddend(Elf_Rel_Impl< ELFT, false > &, uint64_t)
Definition: ELFObject.cpp:948
static Error checkChars(StringRef Line)
Definition: ELFObject.cpp:286
static void orderSegments(std::vector< Segment * > &Segments)
Definition: ELFObject.cpp:2277
static uint64_t layoutSegments(std::vector< Segment * > &Segments, uint64_t Offset)
Definition: ELFObject.cpp:2284
static bool compareSegmentsByOffset(const Segment *A, const Segment *B)
Definition: ELFObject.cpp:1232
static uint64_t layoutSections(Range Sections, uint64_t Offset)
Definition: ELFObject.cpp:2317
static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off)
Definition: ELFObject.cpp:2353
static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine)
Definition: ELFObject.cpp:633
static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector< Segment * > &Segments, uint64_t HdrEnd)
Definition: ELFObject.cpp:2403
static void getAddend(uint64_t &, const Elf_Rel_Impl< ELFT, false > &)
Definition: ELFObject.cpp:1626
static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL)
Definition: ELFObject.cpp:956
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:1634
static Error removeUnneededSections(Object &Obj)
Definition: ELFObject.cpp:2513
static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg)
Definition: ELFObject.cpp:1195
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:2720
std::vector< const SectionBase * > Sections
Definition: ELFObject.h:387
virtual Expected< size_t > getTotalSize(WritableMemoryBuffer &EmptyBuffer) const =0
StringTableSection * addStrTab()
Definition: ELFObject.cpp:1260
SymbolTableSection * addSymTab(StringTableSection *StrTab)
Definition: ELFObject.cpp:1268
std::unique_ptr< Object > Obj
Definition: ELFObject.h:1041
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1314
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1924
Error visit(const SymbolTableSection &Sec) override
Definition: ELFObject.cpp:149
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:566
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:1015
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1023
ELFBuilder(const ELFObjectFile< ELFT > &ElfObj, Object &Obj, std::optional< StringRef > ExtractPartition)
Definition: ELFObject.cpp:1387
Error build(bool EnsureSymtab)
Definition: ELFObject.cpp:1890
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1963
Error visit(Section &Sec) override
Definition: ELFObject.cpp:84
Error visit(const SymbolTableSection &Sec) override
Definition: ELFObject.cpp:847
ELFWriter(Object &Obj, raw_ostream &Out, bool WSH, bool OnlyKeepDebug)
Definition: ELFObject.cpp:2122
void setSymTab(const SymbolTableSection *SymTabSec)
Definition: ELFObject.h:949
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:1098
Error accept(SectionVisitor &) const override
Definition: ELFObject.cpp:1186
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:1068
void setFlagWord(ELF::Elf32_Word W)
Definition: ELFObject.h:951
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:1084
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1374
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1955
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:2127
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:1187
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:2238
Error removeSections(bool AllowBrokenLinks, std::function< bool(const SectionBase &)> ToRemove)
Definition: ELFObject.cpp:2158
SymbolTableSection * SymbolTable
Definition: ELFObject.h:1186
Error replaceSections(const DenseMap< SectionBase *, SectionBase * > &FromTo)
Definition: ELFObject.cpp:2214
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:910
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:978
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:986
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:1003
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:882
virtual void writeRecord(SRecord &Record, uint64_t Off)=0
void writeSection(const SectionBase &S, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2873
Error visit(const Section &S) override
Definition: ELFObject.cpp:2840
Error visit(const StringTableSection &Sec) override
Definition: ELFObject.cpp:2888
void writeRecord(SRecord &Record, uint64_t Off) override
Definition: ELFObject.cpp:2855
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:625
void reserve(size_t NumSymbols)
Definition: ELFObject.h:789
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:606
Expected< T * > getSectionOfType(uint32_t Index, Twine IndexErrMsg, Twine TypeErrMsg)
Definition: ELFObject.cpp:1669
Expected< SectionBase * > getSection(uint32_t Index, Twine ErrMsg)
Definition: ELFObject.cpp:1661
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:1043
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:1112
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:576
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:591
const SectionBase * getStrTab() const
Definition: ELFObject.h:836
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:724
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:863
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:699
void updateSymbols(function_ref< void(Symbol &)> Callable)
Definition: ELFObject.cpp:741
Expected< const Symbol * > getSymbolByIndex(uint32_t Index) const
Definition: ELFObject.cpp:830
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:750
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:771
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:764
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:2933
static SRecord getHeader(StringRef FileName)
Definition: ELFObject.cpp:2962
uint8_t getChecksum() const
Definition: ELFObject.cpp:2917
SRecLineData toString() const
Definition: ELFObject.cpp:2897
static uint8_t getType(uint32_t Address)
Definition: ELFObject.cpp:2954
ArrayRef< uint8_t > Data
Definition: ELFObject.h:424
uint16_t getShndx() const
Definition: ELFObject.cpp:669
SectionBase * DefinedIn
Definition: ELFObject.h:760
SymbolShndxType ShndxType
Definition: ELFObject.h:761
Definition: regcomp.c:192