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