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