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