LLVM 18.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 if (HasSymTabLink) {
434 assert(LinkSection == nullptr);
435 LinkSection = &SymTab;
436 }
437}
438
440 llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
441 return Error::success();
442}
443
444template <class ELFT>
446 ArrayRef<uint8_t> Compressed =
448 SmallVector<uint8_t, 128> Decompressed;
450 switch (Sec.ChType) {
451 case ELFCOMPRESS_ZLIB:
453 break;
454 case ELFCOMPRESS_ZSTD:
456 break;
457 default:
459 "--decompress-debug-sections: ch_type (" +
460 Twine(Sec.ChType) + ") of section '" +
461 Sec.Name + "' is unsupported");
462 }
463 if (auto *Reason =
466 "failed to decompress section '" + Sec.Name +
467 "': " + Reason);
468 if (Error E = compression::decompress(Type, Compressed, Decompressed,
469 static_cast<size_t>(Sec.Size)))
471 "failed to decompress section '" + Sec.Name +
472 "': " + toString(std::move(E)));
473
474 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
475 std::copy(Decompressed.begin(), Decompressed.end(), Buf);
476
477 return Error::success();
478}
479
482 "cannot write compressed section '" + Sec.Name +
483 "' ");
484}
485
487 return Visitor.visit(*this);
488}
489
491 return Visitor.visit(*this);
492}
493
495 return Visitor.visit(*this);
496}
497
499 return Visitor.visit(*this);
500}
501
503 assert((HexData.size() & 1) == 0);
504 while (!HexData.empty()) {
505 Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2)));
506 HexData = HexData.drop_front(2);
507 }
508 Size = Data.size();
509}
510
513 "cannot write compressed section '" + Sec.Name +
514 "' ");
515}
516
517template <class ELFT>
519 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
520 Elf_Chdr_Impl<ELFT> Chdr = {};
521 switch (Sec.CompressionType) {
523 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
524 return Error::success();
526 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
527 break;
529 Chdr.ch_type = ELF::ELFCOMPRESS_ZSTD;
530 break;
531 }
532 Chdr.ch_size = Sec.DecompressedSize;
533 Chdr.ch_addralign = Sec.DecompressedAlign;
534 memcpy(Buf, &Chdr, sizeof(Chdr));
535 Buf += sizeof(Chdr);
536
537 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
538 return Error::success();
539}
540
542 DebugCompressionType CompressionType,
543 bool Is64Bits)
544 : SectionBase(Sec), CompressionType(CompressionType),
545 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
547 CompressedData);
548
550 size_t ChdrSize = Is64Bits ? sizeof(object::Elf_Chdr_Impl<object::ELF64LE>)
552 Size = ChdrSize + CompressedData.size();
553 Align = 8;
554}
555
557 uint32_t ChType, uint64_t DecompressedSize,
558 uint64_t DecompressedAlign)
559 : ChType(ChType), CompressionType(DebugCompressionType::None),
560 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
561 OriginalData = CompressedData;
562}
563
565 return Visitor.visit(*this);
566}
567
569 return Visitor.visit(*this);
570}
571
573
575 return StrTabBuilder.getOffset(Name);
576}
577
579 StrTabBuilder.finalize();
580 Size = StrTabBuilder.getSize();
581}
582
584 Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) +
585 Sec.Offset);
586 return Error::success();
587}
588
590 return Visitor.visit(*this);
591}
592
594 return Visitor.visit(*this);
595}
596
597template <class ELFT>
599 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
600 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
601 return Error::success();
602}
603
605 Size = 0;
608 Link,
609 "Link field value " + Twine(Link) + " in section " + Name +
610 " is invalid",
611 "Link field value " + Twine(Link) + " in section " + Name +
612 " is not a symbol table");
613 if (!Sec)
614 return Sec.takeError();
615
616 setSymTab(*Sec);
617 Symbols->setShndxTable(this);
618 return Error::success();
619}
620
622
624 return Visitor.visit(*this);
625}
626
628 return Visitor.visit(*this);
629}
630
632 switch (Index) {
633 case SHN_ABS:
634 case SHN_COMMON:
635 return true;
636 }
637
638 if (Machine == EM_AMDGPU) {
639 return Index == SHN_AMDGPU_LDS;
640 }
641
642 if (Machine == EM_MIPS) {
643 switch (Index) {
644 case SHN_MIPS_ACOMMON:
645 case SHN_MIPS_SCOMMON:
647 return true;
648 }
649 }
650
651 if (Machine == EM_HEXAGON) {
652 switch (Index) {
658 return true;
659 }
660 }
661 return false;
662}
663
664// Large indexes force us to clarify exactly what this function should do. This
665// function should return the value that will appear in st_shndx when written
666// out.
668 if (DefinedIn != nullptr) {
670 return SHN_XINDEX;
671 return DefinedIn->Index;
672 }
673
675 // This means that we don't have a defined section but we do need to
676 // output a legitimate section index.
677 return SHN_UNDEF;
678 }
679
683 return static_cast<uint16_t>(ShndxType);
684}
685
686bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
687
688void SymbolTableSection::assignIndices() {
689 uint32_t Index = 0;
690 for (auto &Sym : Symbols) {
691 if (Sym->Index != Index)
692 IndicesChanged = true;
693 Sym->Index = Index++;
694 }
695}
696
697void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
698 SectionBase *DefinedIn, uint64_t Value,
699 uint8_t Visibility, uint16_t Shndx,
700 uint64_t SymbolSize) {
701 Symbol Sym;
702 Sym.Name = Name.str();
703 Sym.Binding = Bind;
704 Sym.Type = Type;
705 Sym.DefinedIn = DefinedIn;
706 if (DefinedIn != nullptr)
707 DefinedIn->HasSymbol = true;
708 if (DefinedIn == nullptr) {
709 if (Shndx >= SHN_LORESERVE)
710 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
711 else
712 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
713 }
714 Sym.Value = Value;
715 Sym.Visibility = Visibility;
716 Sym.Size = SymbolSize;
717 Sym.Index = Symbols.size();
718 Symbols.emplace_back(std::make_unique<Symbol>(Sym));
719 Size += this->EntrySize;
720}
721
723 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
725 SectionIndexTable = nullptr;
726 if (ToRemove(SymbolNames)) {
727 if (!AllowBrokenLinks)
728 return createStringError(
730 "string table '%s' cannot be removed because it is "
731 "referenced by the symbol table '%s'",
732 SymbolNames->Name.data(), this->Name.data());
733 SymbolNames = nullptr;
734 }
735 return removeSymbols(
736 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
737}
738
741 Callable(*Sym);
742 std::stable_partition(
743 std::begin(Symbols), std::end(Symbols),
744 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
745 assignIndices();
746}
747
749 function_ref<bool(const Symbol &)> ToRemove) {
750 Symbols.erase(
751 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
752 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
753 std::end(Symbols));
754 auto PrevSize = Size;
755 Size = Symbols.size() * EntrySize;
756 if (Size < PrevSize)
757 IndicesChanged = true;
758 assignIndices();
759 return Error::success();
760}
761
764 for (std::unique_ptr<Symbol> &Sym : Symbols)
765 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
766 Sym->DefinedIn = To;
767}
768
770 Size = 0;
773 Link,
774 "Symbol table has link index of " + Twine(Link) +
775 " which is not a valid index",
776 "Symbol table has link index of " + Twine(Link) +
777 " which is not a string table");
778 if (!Sec)
779 return Sec.takeError();
780
781 setStrTab(*Sec);
783}
784
786 uint32_t MaxLocalIndex = 0;
787 for (std::unique_ptr<Symbol> &Sym : Symbols) {
788 Sym->NameIndex =
789 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
790 if (Sym->Binding == STB_LOCAL)
791 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
792 }
793 // Now we need to set the Link and Info fields.
794 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
795 Info = MaxLocalIndex + 1;
796}
797
799 // Reserve proper amount of space in section index table, so we can
800 // layout sections correctly. We will fill the table with correct
801 // indexes later in fillShdnxTable.
804
805 // Add all of our strings to SymbolNames so that SymbolNames has the right
806 // size before layout is decided.
807 // If the symbol names section has been removed, don't try to add strings to
808 // the table.
809 if (SymbolNames != nullptr)
810 for (std::unique_ptr<Symbol> &Sym : Symbols)
811 SymbolNames->addString(Sym->Name);
812}
813
815 if (SectionIndexTable == nullptr)
816 return;
817 // Fill section index table with real section indexes. This function must
818 // be called after assignOffsets.
819 for (const std::unique_ptr<Symbol> &Sym : Symbols) {
820 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
821 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
822 else
824 }
825}
826
829 if (Symbols.size() <= Index)
831 "invalid symbol index: " + Twine(Index));
832 return Symbols[Index].get();
833}
834
837 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index);
838 if (!Sym)
839 return Sym.takeError();
840
841 return const_cast<Symbol *>(*Sym);
842}
843
844template <class ELFT>
846 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
847 // Loop though symbols setting each entry of the symbol table.
848 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
849 Sym->st_name = Symbol->NameIndex;
850 Sym->st_value = Symbol->Value;
851 Sym->st_size = Symbol->Size;
852 Sym->st_other = Symbol->Visibility;
853 Sym->setBinding(Symbol->Binding);
854 Sym->setType(Symbol->Type);
855 Sym->st_shndx = Symbol->getShndx();
856 ++Sym;
857 }
858 return Error::success();
859}
860
862 return Visitor.visit(*this);
863}
864
866 return Visitor.visit(*this);
867}
868
870 switch (Type) {
871 case SHT_REL:
872 return ".rel";
873 case SHT_RELA:
874 return ".rela";
875 default:
876 llvm_unreachable("not a relocation section");
877 }
878}
879
881 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
882 if (ToRemove(Symbols)) {
883 if (!AllowBrokenLinks)
884 return createStringError(
886 "symbol table '%s' cannot be removed because it is "
887 "referenced by the relocation section '%s'",
888 Symbols->Name.data(), this->Name.data());
889 Symbols = nullptr;
890 }
891
892 for (const Relocation &R : Relocations) {
893 if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn ||
894 !ToRemove(R.RelocSymbol->DefinedIn))
895 continue;
897 "section '%s' cannot be removed: (%s+0x%" PRIx64
898 ") has relocation against symbol '%s'",
899 R.RelocSymbol->DefinedIn->Name.data(),
900 SecToApplyRel->Name.data(), R.Offset,
901 R.RelocSymbol->Name.c_str());
902 }
903
904 return Error::success();
905}
906
907template <class SymTabType>
909 SectionTableRef SecTable) {
910 if (Link != SHN_UNDEF) {
911 Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>(
912 Link,
913 "Link field value " + Twine(Link) + " in section " + Name +
914 " is invalid",
915 "Link field value " + Twine(Link) + " in section " + Name +
916 " is not a symbol table");
917 if (!Sec)
918 return Sec.takeError();
919
920 setSymTab(*Sec);
921 }
922
923 if (Info != SHN_UNDEF) {
925 SecTable.getSection(Info, "Info field value " + Twine(Info) +
926 " in section " + Name + " is invalid");
927 if (!Sec)
928 return Sec.takeError();
929
930 setSection(*Sec);
931 } else
932 setSection(nullptr);
933
934 return Error::success();
935}
936
937template <class SymTabType>
939 this->Link = Symbols ? Symbols->Index : 0;
940
941 if (SecToApplyRel != nullptr)
942 this->Info = SecToApplyRel->Index;
943}
944
945template <class ELFT>
947
948template <class ELFT>
949static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
950 Rela.r_addend = Addend;
951}
952
953template <class RelRange, class T>
954static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) {
955 for (const auto &Reloc : Relocations) {
956 Buf->r_offset = Reloc.Offset;
957 setAddend(*Buf, Reloc.Addend);
958 Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0,
959 Reloc.Type, IsMips64EL);
960 ++Buf;
961 }
962}
963
964template <class ELFT>
966 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
967 if (Sec.Type == SHT_REL)
968 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf),
969 Sec.getObject().IsMips64EL);
970 else
971 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf),
972 Sec.getObject().IsMips64EL);
973 return Error::success();
974}
975
977 return Visitor.visit(*this);
978}
979
981 return Visitor.visit(*this);
982}
983
985 function_ref<bool(const Symbol &)> ToRemove) {
986 for (const Relocation &Reloc : Relocations)
987 if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol))
988 return createStringError(
990 "not stripping symbol '%s' because it is named in a relocation",
991 Reloc.RelocSymbol->Name.data());
992 return Error::success();
993}
994
996 for (const Relocation &Reloc : Relocations)
997 if (Reloc.RelocSymbol)
998 Reloc.RelocSymbol->Referenced = true;
999}
1000
1003 // Update the target section if it was replaced.
1004 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
1005 SecToApplyRel = To;
1006}
1007
1009 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
1010 return Error::success();
1011}
1012
1014 return Visitor.visit(*this);
1015}
1016
1018 return Visitor.visit(*this);
1019}
1020
1022 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1023 if (ToRemove(Symbols)) {
1024 if (!AllowBrokenLinks)
1025 return createStringError(
1027 "symbol table '%s' cannot be removed because it is "
1028 "referenced by the relocation section '%s'",
1029 Symbols->Name.data(), this->Name.data());
1030 Symbols = nullptr;
1031 }
1032
1033 // SecToApplyRel contains a section referenced by sh_info field. It keeps
1034 // a section to which the relocation section applies. When we remove any
1035 // sections we also remove their relocation sections. Since we do that much
1036 // earlier, this assert should never be triggered.
1038 return Error::success();
1039}
1040
1042 bool AllowBrokenDependency,
1043 function_ref<bool(const SectionBase *)> ToRemove) {
1044 if (ToRemove(LinkSection)) {
1045 if (!AllowBrokenDependency)
1047 "section '%s' cannot be removed because it is "
1048 "referenced by the section '%s'",
1049 LinkSection->Name.data(), this->Name.data());
1050 LinkSection = nullptr;
1051 }
1052 return Error::success();
1053}
1054
1056 this->Info = Sym ? Sym->Index : 0;
1057 this->Link = SymTab ? SymTab->Index : 0;
1058 // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global
1059 // status is not part of the equation. If Sym is localized, the intention is
1060 // likely to make the group fully localized. Drop GRP_COMDAT to suppress
1061 // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc
1062 if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL)
1063 this->FlagWord &= ~GRP_COMDAT;
1064}
1065
1067 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1068 if (ToRemove(SymTab)) {
1069 if (!AllowBrokenLinks)
1070 return createStringError(
1072 "section '.symtab' cannot be removed because it is "
1073 "referenced by the group section '%s'",
1074 this->Name.data());
1075 SymTab = nullptr;
1076 Sym = nullptr;
1077 }
1078 llvm::erase_if(GroupMembers, ToRemove);
1079 return Error::success();
1080}
1081
1083 if (ToRemove(*Sym))
1085 "symbol '%s' cannot be removed because it is "
1086 "referenced by the section '%s[%d]'",
1087 Sym->Name.data(), this->Name.data(), this->Index);
1088 return Error::success();
1089}
1090
1092 if (Sym)
1093 Sym->Referenced = true;
1094}
1095
1098 for (SectionBase *&Sec : GroupMembers)
1099 if (SectionBase *To = FromTo.lookup(Sec))
1100 Sec = To;
1101}
1102
1104 // As the header section of the group is removed, drop the Group flag in its
1105 // former members.
1106 for (SectionBase *Sec : GroupMembers)
1107 Sec->Flags &= ~SHF_GROUP;
1108}
1109
1111 if (Link == ELF::SHN_UNDEF)
1112 return Error::success();
1113
1115 SecTable.getSection(Link, "Link field value " + Twine(Link) +
1116 " in section " + Name + " is invalid");
1117 if (!Sec)
1118 return Sec.takeError();
1119
1120 LinkSection = *Sec;
1121
1122 if (LinkSection->Type == ELF::SHT_SYMTAB) {
1123 HasSymTabLink = true;
1124 LinkSection = nullptr;
1125 }
1126
1127 return Error::success();
1128}
1129
1130void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
1131
1132void GnuDebugLinkSection::init(StringRef File) {
1133 FileName = sys::path::filename(File);
1134 // The format for the .gnu_debuglink starts with the file name and is
1135 // followed by a null terminator and then the CRC32 of the file. The CRC32
1136 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
1137 // byte, and then finally push the size to alignment and add 4.
1138 Size = alignTo(FileName.size() + 1, 4) + 4;
1139 // The CRC32 will only be aligned if we align the whole section.
1140 Align = 4;
1142 Name = ".gnu_debuglink";
1143 // For sections not found in segments, OriginalOffset is only used to
1144 // establish the order that sections should go in. By using the maximum
1145 // possible offset we cause this section to wind up at the end.
1146 OriginalOffset = std::numeric_limits<uint64_t>::max();
1147}
1148
1150 uint32_t PrecomputedCRC)
1151 : FileName(File), CRC32(PrecomputedCRC) {
1152 init(File);
1153}
1154
1155template <class ELFT>
1157 unsigned char *Buf =
1158 reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
1159 Elf_Word *CRC =
1160 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
1161 *CRC = Sec.CRC32;
1162 llvm::copy(Sec.FileName, Buf);
1163 return Error::success();
1164}
1165
1167 return Visitor.visit(*this);
1168}
1169
1171 return Visitor.visit(*this);
1172}
1173
1174template <class ELFT>
1176 ELF::Elf32_Word *Buf =
1177 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
1178 support::endian::write32<ELFT::TargetEndianness>(Buf++, Sec.FlagWord);
1179 for (SectionBase *S : Sec.GroupMembers)
1180 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
1181 return Error::success();
1182}
1183
1185 return Visitor.visit(*this);
1186}
1187
1189 return Visitor.visit(*this);
1190}
1191
1192// Returns true IFF a section is wholly inside the range of a segment
1193static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) {
1194 // If a section is empty it should be treated like it has a size of 1. This is
1195 // to clarify the case when an empty section lies on a boundary between two
1196 // segments and ensures that the section "belongs" to the second segment and
1197 // not the first.
1198 uint64_t SecSize = Sec.Size ? Sec.Size : 1;
1199
1200 // Ignore just added sections.
1201 if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max())
1202 return false;
1203
1204 if (Sec.Type == SHT_NOBITS) {
1205 if (!(Sec.Flags & SHF_ALLOC))
1206 return false;
1207
1208 bool SectionIsTLS = Sec.Flags & SHF_TLS;
1209 bool SegmentIsTLS = Seg.Type == PT_TLS;
1210 if (SectionIsTLS != SegmentIsTLS)
1211 return false;
1212
1213 return Seg.VAddr <= Sec.Addr &&
1214 Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize;
1215 }
1216
1217 return Seg.Offset <= Sec.OriginalOffset &&
1218 Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize;
1219}
1220
1221// Returns true IFF a segment's original offset is inside of another segment's
1222// range.
1223static bool segmentOverlapsSegment(const Segment &Child,
1224 const Segment &Parent) {
1225
1226 return Parent.OriginalOffset <= Child.OriginalOffset &&
1227 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
1228}
1229
1230static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
1231 // Any segment without a parent segment should come before a segment
1232 // that has a parent segment.
1233 if (A->OriginalOffset < B->OriginalOffset)
1234 return true;
1235 if (A->OriginalOffset > B->OriginalOffset)
1236 return false;
1237 return A->Index < B->Index;
1238}
1239
1241 Obj->Flags = 0x0;
1242 Obj->Type = ET_REL;
1243 Obj->OSABI = ELFOSABI_NONE;
1244 Obj->ABIVersion = 0;
1245 Obj->Entry = 0x0;
1246 Obj->Machine = EM_NONE;
1247 Obj->Version = 1;
1248}
1249
1250void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
1251
1253 auto &StrTab = Obj->addSection<StringTableSection>();
1254 StrTab.Name = ".strtab";
1255
1256 Obj->SectionNames = &StrTab;
1257 return &StrTab;
1258}
1259
1261 auto &SymTab = Obj->addSection<SymbolTableSection>();
1262
1263 SymTab.Name = ".symtab";
1264 SymTab.Link = StrTab->Index;
1265
1266 // The symbol table always needs a null symbol
1267 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
1268
1269 Obj->SymbolTable = &SymTab;
1270 return &SymTab;
1271}
1272
1274 for (SectionBase &Sec : Obj->sections())
1275 if (Error Err = Sec.initialize(Obj->sections()))
1276 return Err;
1277
1278 return Error::success();
1279}
1280
1281void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
1282 auto Data = ArrayRef<uint8_t>(
1283 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
1284 MemBuf->getBufferSize());
1285 auto &DataSection = Obj->addSection<Section>(Data);
1286 DataSection.Name = ".data";
1287 DataSection.Type = ELF::SHT_PROGBITS;
1288 DataSection.Size = Data.size();
1289 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1290
1291 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
1292 std::replace_if(
1293 std::begin(SanitizedFilename), std::end(SanitizedFilename),
1294 [](char C) { return !isAlnum(C); }, '_');
1295 Twine Prefix = Twine("_binary_") + SanitizedFilename;
1296
1297 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
1298 /*Value=*/0, NewSymbolVisibility, 0, 0);
1299 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
1300 /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
1301 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
1302 /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
1303 0);
1304}
1305
1309
1311 if (Error Err = initSections())
1312 return std::move(Err);
1313 addData(SymTab);
1314
1315 return std::move(Obj);
1316}
1317
1318// Adds sections from IHEX data file. Data should have been
1319// fully validated by this time.
1320void IHexELFBuilder::addDataSections() {
1321 OwnedDataSection *Section = nullptr;
1322 uint64_t SegmentAddr = 0, BaseAddr = 0;
1323 uint32_t SecNo = 1;
1324
1325 for (const IHexRecord &R : Records) {
1326 uint64_t RecAddr;
1327 switch (R.Type) {
1328 case IHexRecord::Data:
1329 // Ignore empty data records
1330 if (R.HexData.empty())
1331 continue;
1332 RecAddr = R.Addr + SegmentAddr + BaseAddr;
1333 if (!Section || Section->Addr + Section->Size != RecAddr) {
1334 // OriginalOffset field is only used to sort sections before layout, so
1335 // instead of keeping track of real offsets in IHEX file, and as
1336 // layoutSections() and layoutSectionsForOnlyKeepDebug() use
1337 // llvm::stable_sort(), we can just set it to a constant (zero).
1338 Section = &Obj->addSection<OwnedDataSection>(
1339 ".sec" + std::to_string(SecNo), RecAddr,
1341 SecNo++;
1342 }
1343 Section->appendHexData(R.HexData);
1344 break;
1346 break;
1348 // 20-bit segment address.
1349 SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
1350 break;
1353 Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
1354 assert(Obj->Entry <= 0xFFFFFU);
1355 break;
1357 // 16-31 bits of linear base address
1358 BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
1359 break;
1360 default:
1361 llvm_unreachable("unknown record type");
1362 }
1363 }
1364}
1365
1369 StringTableSection *StrTab = addStrTab();
1370 addSymTab(StrTab);
1371 if (Error Err = initSections())
1372 return std::move(Err);
1373 addDataSections();
1374
1375 return std::move(Obj);
1376}
1377
1378template <class ELFT>
1380 std::optional<StringRef> ExtractPartition)
1381 : ElfFile(ElfObj.getELFFile()), Obj(Obj),
1382 ExtractPartition(ExtractPartition) {
1383 Obj.IsMips64EL = ElfFile.isMips64EL();
1384}
1385
1386template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
1387 for (Segment &Parent : Obj.segments()) {
1388 // Every segment will overlap with itself but we don't want a segment to
1389 // be its own parent so we avoid that situation.
1390 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
1391 // We want a canonical "most parental" segment but this requires
1392 // inspecting the ParentSegment.
1393 if (compareSegmentsByOffset(&Parent, &Child))
1394 if (Child.ParentSegment == nullptr ||
1395 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
1396 Child.ParentSegment = &Parent;
1397 }
1398 }
1399 }
1400}
1401
1402template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
1403 if (!ExtractPartition)
1404 return Error::success();
1405
1406 for (const SectionBase &Sec : Obj.sections()) {
1407 if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
1408 EhdrOffset = Sec.Offset;
1409 return Error::success();
1410 }
1411 }
1413 "could not find partition named '" +
1414 *ExtractPartition + "'");
1415}
1416
1417template <class ELFT>
1419 uint32_t Index = 0;
1420
1422 HeadersFile.program_headers();
1423 if (!Headers)
1424 return Headers.takeError();
1425
1426 for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
1427 if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
1428 return createStringError(
1430 "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
1431 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
1432 " goes past the end of the file");
1433
1434 ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
1435 (size_t)Phdr.p_filesz};
1436 Segment &Seg = Obj.addSegment(Data);
1437 Seg.Type = Phdr.p_type;
1438 Seg.Flags = Phdr.p_flags;
1439 Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
1440 Seg.Offset = Phdr.p_offset + EhdrOffset;
1441 Seg.VAddr = Phdr.p_vaddr;
1442 Seg.PAddr = Phdr.p_paddr;
1443 Seg.FileSize = Phdr.p_filesz;
1444 Seg.MemSize = Phdr.p_memsz;
1445 Seg.Align = Phdr.p_align;
1446 Seg.Index = Index++;
1447 for (SectionBase &Sec : Obj.sections())
1448 if (sectionWithinSegment(Sec, Seg)) {
1449 Seg.addSection(&Sec);
1450 if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
1451 Sec.ParentSegment = &Seg;
1452 }
1453 }
1454
1455 auto &ElfHdr = Obj.ElfHdrSegment;
1456 ElfHdr.Index = Index++;
1457 ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
1458
1459 const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
1460 auto &PrHdr = Obj.ProgramHdrSegment;
1461 PrHdr.Type = PT_PHDR;
1462 PrHdr.Flags = 0;
1463 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
1464 // Whereas this works automatically for ElfHdr, here OriginalOffset is
1465 // always non-zero and to ensure the equation we assign the same value to
1466 // VAddr as well.
1467 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
1468 PrHdr.PAddr = 0;
1469 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
1470 // The spec requires us to naturally align all the fields.
1471 PrHdr.Align = sizeof(Elf_Addr);
1472 PrHdr.Index = Index++;
1473
1474 // Now we do an O(n^2) loop through the segments in order to match up
1475 // segments.
1476 for (Segment &Child : Obj.segments())
1477 setParentSegment(Child);
1478 setParentSegment(ElfHdr);
1479 setParentSegment(PrHdr);
1480
1481 return Error::success();
1482}
1483
1484template <class ELFT>
1486 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
1488 "invalid alignment " + Twine(GroupSec->Align) +
1489 " of group section '" + GroupSec->Name + "'");
1490 SectionTableRef SecTable = Obj.sections();
1491 if (GroupSec->Link != SHN_UNDEF) {
1492 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1493 GroupSec->Link,
1494 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1495 GroupSec->Name + "' is invalid",
1496 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1497 GroupSec->Name + "' is not a symbol table");
1498 if (!SymTab)
1499 return SymTab.takeError();
1500
1501 Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
1502 if (!Sym)
1504 "info field value '" + Twine(GroupSec->Info) +
1505 "' in section '" + GroupSec->Name +
1506 "' is not a valid symbol index");
1507 GroupSec->setSymTab(*SymTab);
1508 GroupSec->setSymbol(*Sym);
1509 }
1510 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1511 GroupSec->Contents.empty())
1513 "the content of the section " + GroupSec->Name +
1514 " is malformed");
1515 const ELF::Elf32_Word *Word =
1516 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1517 const ELF::Elf32_Word *End =
1518 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1519 GroupSec->setFlagWord(
1520 support::endian::read32<ELFT::TargetEndianness>(Word++));
1521 for (; Word != End; ++Word) {
1522 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
1523 Expected<SectionBase *> Sec = SecTable.getSection(
1524 Index, "group member index " + Twine(Index) + " in section '" +
1525 GroupSec->Name + "' is invalid");
1526 if (!Sec)
1527 return Sec.takeError();
1528
1529 GroupSec->addMember(*Sec);
1530 }
1531
1532 return Error::success();
1533}
1534
1535template <class ELFT>
1537 Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
1538 if (!Shdr)
1539 return Shdr.takeError();
1540
1541 Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
1542 if (!StrTabData)
1543 return StrTabData.takeError();
1544
1545 ArrayRef<Elf_Word> ShndxData;
1546
1548 ElfFile.symbols(*Shdr);
1549 if (!Symbols)
1550 return Symbols.takeError();
1551
1552 for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
1553 SectionBase *DefSection = nullptr;
1554
1555 Expected<StringRef> Name = Sym.getName(*StrTabData);
1556 if (!Name)
1557 return Name.takeError();
1558
1559 if (Sym.st_shndx == SHN_XINDEX) {
1560 if (SymTab->getShndxTable() == nullptr)
1562 "symbol '" + *Name +
1563 "' has index SHN_XINDEX but no "
1564 "SHT_SYMTAB_SHNDX section exists");
1565 if (ShndxData.data() == nullptr) {
1567 ElfFile.getSection(SymTab->getShndxTable()->Index);
1568 if (!ShndxSec)
1569 return ShndxSec.takeError();
1570
1572 ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
1573 if (!Data)
1574 return Data.takeError();
1575
1576 ShndxData = *Data;
1577 if (ShndxData.size() != Symbols->size())
1578 return createStringError(
1580 "symbol section index table does not have the same number of "
1581 "entries as the symbol table");
1582 }
1583 Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
1584 Expected<SectionBase *> Sec = Obj.sections().getSection(
1585 Index,
1586 "symbol '" + *Name + "' has invalid section index " + Twine(Index));
1587 if (!Sec)
1588 return Sec.takeError();
1589
1590 DefSection = *Sec;
1591 } else if (Sym.st_shndx >= SHN_LORESERVE) {
1592 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
1593 return createStringError(
1595 "symbol '" + *Name +
1596 "' has unsupported value greater than or equal "
1597 "to SHN_LORESERVE: " +
1598 Twine(Sym.st_shndx));
1599 }
1600 } else if (Sym.st_shndx != SHN_UNDEF) {
1601 Expected<SectionBase *> Sec = Obj.sections().getSection(
1602 Sym.st_shndx, "symbol '" + *Name +
1603 "' is defined has invalid section index " +
1604 Twine(Sym.st_shndx));
1605 if (!Sec)
1606 return Sec.takeError();
1607
1608 DefSection = *Sec;
1609 }
1610
1611 SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
1612 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
1613 }
1614
1615 return Error::success();
1616}
1617
1618template <class ELFT>
1620
1621template <class ELFT>
1622static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1623 ToSet = Rela.r_addend;
1624}
1625
1626template <class T>
1627static Error initRelocations(RelocationSection *Relocs, T RelRange) {
1628 for (const auto &Rel : RelRange) {
1629 Relocation ToAdd;
1630 ToAdd.Offset = Rel.r_offset;
1631 getAddend(ToAdd.Addend, Rel);
1632 ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
1633
1634 if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
1635 if (!Relocs->getObject().SymbolTable)
1636 return createStringError(
1638 "'" + Relocs->Name + "': relocation references symbol with index " +
1639 Twine(Sym) + ", but there is no symbol table");
1640 Expected<Symbol *> SymByIndex =
1642 if (!SymByIndex)
1643 return SymByIndex.takeError();
1644
1645 ToAdd.RelocSymbol = *SymByIndex;
1646 }
1647
1648 Relocs->addRelocation(ToAdd);
1649 }
1650
1651 return Error::success();
1652}
1653
1655 Twine ErrMsg) {
1656 if (Index == SHN_UNDEF || Index > Sections.size())
1658 return Sections[Index - 1].get();
1659}
1660
1661template <class T>
1663 Twine IndexErrMsg,
1664 Twine TypeErrMsg) {
1665 Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
1666 if (!BaseSec)
1667 return BaseSec.takeError();
1668
1669 if (T *Sec = dyn_cast<T>(*BaseSec))
1670 return Sec;
1671
1672 return createStringError(errc::invalid_argument, TypeErrMsg);
1673}
1674
1675template <class ELFT>
1677 switch (Shdr.sh_type) {
1678 case SHT_REL:
1679 case SHT_RELA:
1680 if (Shdr.sh_flags & SHF_ALLOC) {
1681 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1682 return Obj.addSection<DynamicRelocationSection>(*Data);
1683 else
1684 return Data.takeError();
1685 }
1686 return Obj.addSection<RelocationSection>(Obj);
1687 case SHT_STRTAB:
1688 // If a string table is allocated we don't want to mess with it. That would
1689 // mean altering the memory image. There are no special link types or
1690 // anything so we can just use a Section.
1691 if (Shdr.sh_flags & SHF_ALLOC) {
1692 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1693 return Obj.addSection<Section>(*Data);
1694 else
1695 return Data.takeError();
1696 }
1697 return Obj.addSection<StringTableSection>();
1698 case SHT_HASH:
1699 case SHT_GNU_HASH:
1700 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1701 // Because of this we don't need to mess with the hash tables either.
1702 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1703 return Obj.addSection<Section>(*Data);
1704 else
1705 return Data.takeError();
1706 case SHT_GROUP:
1707 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1708 return Obj.addSection<GroupSection>(*Data);
1709 else
1710 return Data.takeError();
1711 case SHT_DYNSYM:
1712 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1713 return Obj.addSection<DynamicSymbolTableSection>(*Data);
1714 else
1715 return Data.takeError();
1716 case SHT_DYNAMIC:
1717 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1718 return Obj.addSection<DynamicSection>(*Data);
1719 else
1720 return Data.takeError();
1721 case SHT_SYMTAB: {
1722 // Multiple SHT_SYMTAB sections are forbidden by the ELF gABI.
1723 if (Obj.SymbolTable != nullptr)
1725 "found multiple SHT_SYMTAB sections");
1726 auto &SymTab = Obj.addSection<SymbolTableSection>();
1727 Obj.SymbolTable = &SymTab;
1728 return SymTab;
1729 }
1730 case SHT_SYMTAB_SHNDX: {
1731 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1732 Obj.SectionIndexTable = &ShndxSection;
1733 return ShndxSection;
1734 }
1735 case SHT_NOBITS:
1736 return Obj.addSection<Section>(ArrayRef<uint8_t>());
1737 default: {
1738 Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
1739 if (!Data)
1740 return Data.takeError();
1741
1742 Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
1743 if (!Name)
1744 return Name.takeError();
1745
1746 if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
1747 return Obj.addSection<Section>(*Data);
1748 auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
1749 return Obj.addSection<CompressedSection>(CompressedSection(
1750 *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign));
1751 }
1752 }
1753}
1754
1755template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
1756 uint32_t Index = 0;
1758 ElfFile.sections();
1759 if (!Sections)
1760 return Sections.takeError();
1761
1762 for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
1763 if (Index == 0) {
1764 ++Index;
1765 continue;
1766 }
1767 Expected<SectionBase &> Sec = makeSection(Shdr);
1768 if (!Sec)
1769 return Sec.takeError();
1770
1771 Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
1772 if (!SecName)
1773 return SecName.takeError();
1774 Sec->Name = SecName->str();
1775 Sec->Type = Sec->OriginalType = Shdr.sh_type;
1776 Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
1777 Sec->Addr = Shdr.sh_addr;
1778 Sec->Offset = Shdr.sh_offset;
1779 Sec->OriginalOffset = Shdr.sh_offset;
1780 Sec->Size = Shdr.sh_size;
1781 Sec->Link = Shdr.sh_link;
1782 Sec->Info = Shdr.sh_info;
1783 Sec->Align = Shdr.sh_addralign;
1784 Sec->EntrySize = Shdr.sh_entsize;
1785 Sec->Index = Index++;
1786 Sec->OriginalIndex = Sec->Index;
1787 Sec->OriginalData = ArrayRef<uint8_t>(
1788 ElfFile.base() + Shdr.sh_offset,
1789 (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
1790 }
1791
1792 return Error::success();
1793}
1794
1795template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
1796 uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
1797 if (ShstrIndex == SHN_XINDEX) {
1798 Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
1799 if (!Sec)
1800 return Sec.takeError();
1801
1802 ShstrIndex = (*Sec)->sh_link;
1803 }
1804
1805 if (ShstrIndex == SHN_UNDEF)
1806 Obj.HadShdrs = false;
1807 else {
1809 Obj.sections().template getSectionOfType<StringTableSection>(
1810 ShstrIndex,
1811 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1812 " is invalid",
1813 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1814 " does not reference a string table");
1815 if (!Sec)
1816 return Sec.takeError();
1817
1818 Obj.SectionNames = *Sec;
1819 }
1820
1821 // If a section index table exists we'll need to initialize it before we
1822 // initialize the symbol table because the symbol table might need to
1823 // reference it.
1824 if (Obj.SectionIndexTable)
1825 if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
1826 return Err;
1827
1828 // Now that all of the sections have been added we can fill out some extra
1829 // details about symbol tables. We need the symbol table filled out before
1830 // any relocations.
1831 if (Obj.SymbolTable) {
1832 if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
1833 return Err;
1834 if (Error Err = initSymbolTable(Obj.SymbolTable))
1835 return Err;
1836 } else if (EnsureSymtab) {
1837 if (Error Err = Obj.addNewSymbolTable())
1838 return Err;
1839 }
1840
1841 // Now that all sections and symbols have been added we can add
1842 // relocations that reference symbols and set the link and info fields for
1843 // relocation sections.
1844 for (SectionBase &Sec : Obj.sections()) {
1845 if (&Sec == Obj.SymbolTable)
1846 continue;
1847 if (Error Err = Sec.initialize(Obj.sections()))
1848 return Err;
1849 if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
1851 ElfFile.sections();
1852 if (!Sections)
1853 return Sections.takeError();
1854
1855 const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
1856 Sections->begin() + RelSec->Index;
1857 if (RelSec->Type == SHT_REL) {
1859 ElfFile.rels(*Shdr);
1860 if (!Rels)
1861 return Rels.takeError();
1862
1863 if (Error Err = initRelocations(RelSec, *Rels))
1864 return Err;
1865 } else {
1867 ElfFile.relas(*Shdr);
1868 if (!Relas)
1869 return Relas.takeError();
1870
1871 if (Error Err = initRelocations(RelSec, *Relas))
1872 return Err;
1873 }
1874 } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
1875 if (Error Err = initGroupSection(GroupSec))
1876 return Err;
1877 }
1878 }
1879
1880 return Error::success();
1881}
1882
1883template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
1884 if (Error E = readSectionHeaders())
1885 return E;
1886 if (Error E = findEhdrOffset())
1887 return E;
1888
1889 // The ELFFile whose ELF headers and program headers are copied into the
1890 // output file. Normally the same as ElfFile, but if we're extracting a
1891 // loadable partition it will point to the partition's headers.
1893 {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
1894 if (!HeadersFile)
1895 return HeadersFile.takeError();
1896
1897 const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
1898 Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64;
1899 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1900 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
1901 Obj.Type = Ehdr.e_type;
1902 Obj.Machine = Ehdr.e_machine;
1903 Obj.Version = Ehdr.e_version;
1904 Obj.Entry = Ehdr.e_entry;
1905 Obj.Flags = Ehdr.e_flags;
1906
1907 if (Error E = readSections(EnsureSymtab))
1908 return E;
1909 return readProgramHeaders(*HeadersFile);
1910}
1911
1912Writer::~Writer() = default;
1913
1914Reader::~Reader() = default;
1915
1917BinaryReader::create(bool /*EnsureSymtab*/) const {
1918 return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
1919}
1920
1921Expected<std::vector<IHexRecord>> IHexReader::parse() const {
1923 std::vector<IHexRecord> Records;
1924 bool HasSections = false;
1925
1926 MemBuf->getBuffer().split(Lines, '\n');
1927 Records.reserve(Lines.size());
1928 for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
1929 StringRef Line = Lines[LineNo - 1].trim();
1930 if (Line.empty())
1931 continue;
1932
1934 if (!R)
1935 return parseError(LineNo, R.takeError());
1936 if (R->Type == IHexRecord::EndOfFile)
1937 break;
1938 HasSections |= (R->Type == IHexRecord::Data);
1939 Records.push_back(*R);
1940 }
1941 if (!HasSections)
1942 return parseError(-1U, "no sections");
1943
1944 return std::move(Records);
1945}
1946
1948IHexReader::create(bool /*EnsureSymtab*/) const {
1950 if (!Records)
1951 return Records.takeError();
1952
1953 return IHexELFBuilder(*Records).build();
1954}
1955
1957 auto Obj = std::make_unique<Object>();
1958 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1959 ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
1960 if (Error Err = Builder.build(EnsureSymtab))
1961 return std::move(Err);
1962 return std::move(Obj);
1963 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1964 ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
1965 if (Error Err = Builder.build(EnsureSymtab))
1966 return std::move(Err);
1967 return std::move(Obj);
1968 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1969 ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
1970 if (Error Err = Builder.build(EnsureSymtab))
1971 return std::move(Err);
1972 return std::move(Obj);
1973 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1974 ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
1975 if (Error Err = Builder.build(EnsureSymtab))
1976 return std::move(Err);
1977 return std::move(Obj);
1978 }
1979 return createStringError(errc::invalid_argument, "invalid file type");
1980}
1981
1982template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
1983 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
1984 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1985 Ehdr.e_ident[EI_MAG0] = 0x7f;
1986 Ehdr.e_ident[EI_MAG1] = 'E';
1987 Ehdr.e_ident[EI_MAG2] = 'L';
1988 Ehdr.e_ident[EI_MAG3] = 'F';
1989 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1990 Ehdr.e_ident[EI_DATA] =
1991 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1992 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
1993 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1994 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
1995
1996 Ehdr.e_type = Obj.Type;
1997 Ehdr.e_machine = Obj.Machine;
1998 Ehdr.e_version = Obj.Version;
1999 Ehdr.e_entry = Obj.Entry;
2000 // We have to use the fully-qualified name llvm::size
2001 // since some compilers complain on ambiguous resolution.
2002 Ehdr.e_phnum = llvm::size(Obj.segments());
2003 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
2004 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
2005 Ehdr.e_flags = Obj.Flags;
2006 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
2007 if (WriteSectionHeaders && Obj.sections().size() != 0) {
2008 Ehdr.e_shentsize = sizeof(Elf_Shdr);
2009 Ehdr.e_shoff = Obj.SHOff;
2010 // """
2011 // If the number of sections is greater than or equal to
2012 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
2013 // number of section header table entries is contained in the sh_size field
2014 // of the section header at index 0.
2015 // """
2016 auto Shnum = Obj.sections().size() + 1;
2017 if (Shnum >= SHN_LORESERVE)
2018 Ehdr.e_shnum = 0;
2019 else
2020 Ehdr.e_shnum = Shnum;
2021 // """
2022 // If the section name string table section index is greater than or equal
2023 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
2024 // and the actual index of the section name string table section is
2025 // contained in the sh_link field of the section header at index 0.
2026 // """
2027 if (Obj.SectionNames->Index >= SHN_LORESERVE)
2028 Ehdr.e_shstrndx = SHN_XINDEX;
2029 else
2030 Ehdr.e_shstrndx = Obj.SectionNames->Index;
2031 } else {
2032 Ehdr.e_shentsize = 0;
2033 Ehdr.e_shoff = 0;
2034 Ehdr.e_shnum = 0;
2035 Ehdr.e_shstrndx = 0;
2036 }
2037}
2038
2039template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
2040 for (auto &Seg : Obj.segments())
2041 writePhdr(Seg);
2042}
2043
2044template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
2045 // This reference serves to write the dummy section header at the begining
2046 // of the file. It is not used for anything else
2047 Elf_Shdr &Shdr =
2048 *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
2049 Shdr.sh_name = 0;
2050 Shdr.sh_type = SHT_NULL;
2051 Shdr.sh_flags = 0;
2052 Shdr.sh_addr = 0;
2053 Shdr.sh_offset = 0;
2054 // See writeEhdr for why we do this.
2055 uint64_t Shnum = Obj.sections().size() + 1;
2056 if (Shnum >= SHN_LORESERVE)
2057 Shdr.sh_size = Shnum;
2058 else
2059 Shdr.sh_size = 0;
2060 // See writeEhdr for why we do this.
2061 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
2062 Shdr.sh_link = Obj.SectionNames->Index;
2063 else
2064 Shdr.sh_link = 0;
2065 Shdr.sh_info = 0;
2066 Shdr.sh_addralign = 0;
2067 Shdr.sh_entsize = 0;
2068
2069 for (SectionBase &Sec : Obj.sections())
2070 writeShdr(Sec);
2071}
2072
2073template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
2074 for (SectionBase &Sec : Obj.sections())
2075 // Segments are responsible for writing their contents, so only write the
2076 // section data if the section is not in a segment. Note that this renders
2077 // sections in segments effectively immutable.
2078 if (Sec.ParentSegment == nullptr)
2079 if (Error Err = Sec.accept(*SecWriter))
2080 return Err;
2081
2082 return Error::success();
2083}
2084
2085template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
2086 for (Segment &Seg : Obj.segments()) {
2087 size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
2088 std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
2089 Size);
2090 }
2091
2092 for (const auto &it : Obj.getUpdatedSections()) {
2093 SectionBase *Sec = it.first;
2094 ArrayRef<uint8_t> Data = it.second;
2095
2096 auto *Parent = Sec->ParentSegment;
2097 assert(Parent && "This section should've been part of a segment.");
2099 Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2100 llvm::copy(Data, Buf->getBufferStart() + Offset);
2101 }
2102
2103 // Iterate over removed sections and overwrite their old data with zeroes.
2104 for (auto &Sec : Obj.removedSections()) {
2105 Segment *Parent = Sec.ParentSegment;
2106 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
2107 continue;
2109 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2110 std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
2111 }
2112}
2113
2114template <class ELFT>
2116 bool OnlyKeepDebug)
2117 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
2118 OnlyKeepDebug(OnlyKeepDebug) {}
2119
2121 auto It = llvm::find_if(Sections,
2122 [&](const SecPtr &Sec) { return Sec->Name == Name; });
2123 if (It == Sections.end())
2124 return createStringError(errc::invalid_argument, "section '%s' not found",
2125 Name.str().c_str());
2126
2127 auto *OldSec = It->get();
2128 if (!OldSec->hasContents())
2129 return createStringError(
2131 "section '%s' cannot be updated because it does not have contents",
2132 Name.str().c_str());
2133
2134 if (Data.size() > OldSec->Size && OldSec->ParentSegment)
2136 "cannot fit data of size %zu into section '%s' "
2137 "with size %" PRIu64 " that is part of a segment",
2138 Data.size(), Name.str().c_str(), OldSec->Size);
2139
2140 if (!OldSec->ParentSegment) {
2141 *It = std::make_unique<OwnedDataSection>(*OldSec, Data);
2142 } else {
2143 // The segment writer will be in charge of updating these contents.
2144 OldSec->Size = Data.size();
2145 UpdatedSections[OldSec] = Data;
2146 }
2147
2148 return Error::success();
2149}
2150
2152 bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
2153
2154 auto Iter = std::stable_partition(
2155 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
2156 if (ToRemove(*Sec))
2157 return false;
2158 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
2159 if (auto ToRelSec = RelSec->getSection())
2160 return !ToRemove(*ToRelSec);
2161 }
2162 return true;
2163 });
2164 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
2165 SymbolTable = nullptr;
2166 if (SectionNames != nullptr && ToRemove(*SectionNames))
2167 SectionNames = nullptr;
2168 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
2169 SectionIndexTable = nullptr;
2170 // Now make sure there are no remaining references to the sections that will
2171 // be removed. Sometimes it is impossible to remove a reference so we emit
2172 // an error here instead.
2173 std::unordered_set<const SectionBase *> RemoveSections;
2174 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
2175 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
2176 for (auto &Segment : Segments)
2177 Segment->removeSection(RemoveSec.get());
2178 RemoveSec->onRemove();
2179 RemoveSections.insert(RemoveSec.get());
2180 }
2181
2182 // For each section that remains alive, we want to remove the dead references.
2183 // This either might update the content of the section (e.g. remove symbols
2184 // from symbol table that belongs to removed section) or trigger an error if
2185 // a live section critically depends on a section being removed somehow
2186 // (e.g. the removed section is referenced by a relocation).
2187 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
2188 if (Error E = KeepSec->removeSectionReferences(
2189 AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
2190 return RemoveSections.find(Sec) != RemoveSections.end();
2191 }))
2192 return E;
2193 }
2194
2195 // Transfer removed sections into the Object RemovedSections container for use
2196 // later.
2197 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
2198 // Now finally get rid of them all together.
2199 Sections.erase(Iter, std::end(Sections));
2200 return Error::success();
2201}
2202
2205 auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
2206 return Lhs->Index < Rhs->Index;
2207 };
2208 assert(llvm::is_sorted(Sections, SectionIndexLess) &&
2209 "Sections are expected to be sorted by Index");
2210 // Set indices of new sections so that they can be later sorted into positions
2211 // of removed ones.
2212 for (auto &I : FromTo)
2213 I.second->Index = I.first->Index;
2214
2215 // Notify all sections about the replacement.
2216 for (auto &Sec : Sections)
2217 Sec->replaceSectionReferences(FromTo);
2218
2219 if (Error E = removeSections(
2220 /*AllowBrokenLinks=*/false,
2221 [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
2222 return E;
2223 llvm::sort(Sections, SectionIndexLess);
2224 return Error::success();
2225}
2226
2228 if (SymbolTable)
2229 for (const SecPtr &Sec : Sections)
2230 if (Error E = Sec->removeSymbols(ToRemove))
2231 return E;
2232 return Error::success();
2233}
2234
2236 assert(!SymbolTable && "Object must not has a SymbolTable.");
2237
2238 // Reuse an existing SHT_STRTAB section if it exists.
2239 StringTableSection *StrTab = nullptr;
2240 for (SectionBase &Sec : sections()) {
2241 if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
2242 StrTab = static_cast<StringTableSection *>(&Sec);
2243
2244 // Prefer a string table that is not the section header string table, if
2245 // such a table exists.
2246 if (SectionNames != &Sec)
2247 break;
2248 }
2249 }
2250 if (!StrTab)
2251 StrTab = &addSection<StringTableSection>();
2252
2253 SymbolTableSection &SymTab = addSection<SymbolTableSection>();
2254 SymTab.Name = ".symtab";
2255 SymTab.Link = StrTab->Index;
2256 if (Error Err = SymTab.initialize(sections()))
2257 return Err;
2258 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
2259
2260 SymbolTable = &SymTab;
2261
2262 return Error::success();
2263}
2264
2265// Orders segments such that if x = y->ParentSegment then y comes before x.
2266static void orderSegments(std::vector<Segment *> &Segments) {
2268}
2269
2270// This function finds a consistent layout for a list of segments starting from
2271// an Offset. It assumes that Segments have been sorted by orderSegments and
2272// returns an Offset one past the end of the last segment.
2273static uint64_t layoutSegments(std::vector<Segment *> &Segments,
2274 uint64_t Offset) {
2276 // The only way a segment should move is if a section was between two
2277 // segments and that section was removed. If that section isn't in a segment
2278 // then it's acceptable, but not ideal, to simply move it to after the
2279 // segments. So we can simply layout segments one after the other accounting
2280 // for alignment.
2281 for (Segment *Seg : Segments) {
2282 // We assume that segments have been ordered by OriginalOffset and Index
2283 // such that a parent segment will always come before a child segment in
2284 // OrderedSegments. This means that the Offset of the ParentSegment should
2285 // already be set and we can set our offset relative to it.
2286 if (Seg->ParentSegment != nullptr) {
2287 Segment *Parent = Seg->ParentSegment;
2288 Seg->Offset =
2289 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
2290 } else {
2291 Seg->Offset =
2292 alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
2293 }
2294 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
2295 }
2296 return Offset;
2297}
2298
2299// This function finds a consistent layout for a list of sections. It assumes
2300// that the ->ParentSegment of each section has already been laid out. The
2301// supplied starting Offset is used for the starting offset of any section that
2302// does not have a ParentSegment. It returns either the offset given if all
2303// sections had a ParentSegment or an offset one past the last section if there
2304// was a section that didn't have a ParentSegment.
2305template <class Range>
2306static uint64_t layoutSections(Range Sections, uint64_t Offset) {
2307 // Now the offset of every segment has been set we can assign the offsets
2308 // of each section. For sections that are covered by a segment we should use
2309 // the segment's original offset and the section's original offset to compute
2310 // the offset from the start of the segment. Using the offset from the start
2311 // of the segment we can assign a new offset to the section. For sections not
2312 // covered by segments we can just bump Offset to the next valid location.
2313 // While it is not necessary, layout the sections in the order based on their
2314 // original offsets to resemble the input file as close as possible.
2315 std::vector<SectionBase *> OutOfSegmentSections;
2316 uint32_t Index = 1;
2317 for (auto &Sec : Sections) {
2318 Sec.Index = Index++;
2319 if (Sec.ParentSegment != nullptr) {
2320 const Segment &Segment = *Sec.ParentSegment;
2321 Sec.Offset =
2322 Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
2323 } else
2324 OutOfSegmentSections.push_back(&Sec);
2325 }
2326
2327 llvm::stable_sort(OutOfSegmentSections,
2328 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2329 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2330 });
2331 for (auto *Sec : OutOfSegmentSections) {
2332 Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
2333 Sec->Offset = Offset;
2334 if (Sec->Type != SHT_NOBITS)
2335 Offset += Sec->Size;
2336 }
2337 return Offset;
2338}
2339
2340// Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
2341// occupy no space in the file.
2343 // The layout algorithm requires the sections to be handled in the order of
2344 // their offsets in the input file, at least inside segments.
2345 std::vector<SectionBase *> Sections;
2346 Sections.reserve(Obj.sections().size());
2347 uint32_t Index = 1;
2348 for (auto &Sec : Obj.sections()) {
2349 Sec.Index = Index++;
2350 Sections.push_back(&Sec);
2351 }
2352 llvm::stable_sort(Sections,
2353 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2354 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2355 });
2356
2357 for (auto *Sec : Sections) {
2358 auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
2359 ? Sec->ParentSegment->firstSection()
2360 : nullptr;
2361
2362 // The first section in a PT_LOAD has to have congruent offset and address
2363 // modulo the alignment, which usually equals the maximum page size.
2364 if (FirstSec && FirstSec == Sec)
2365 Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
2366
2367 // sh_offset is not significant for SHT_NOBITS sections, but the congruence
2368 // rule must be followed if it is the first section in a PT_LOAD. Do not
2369 // advance Off.
2370 if (Sec->Type == SHT_NOBITS) {
2371 Sec->Offset = Off;
2372 continue;
2373 }
2374
2375 if (!FirstSec) {
2376 // FirstSec being nullptr generally means that Sec does not have the
2377 // SHF_ALLOC flag.
2378 Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
2379 } else if (FirstSec != Sec) {
2380 // The offset is relative to the first section in the PT_LOAD segment. Use
2381 // sh_offset for non-SHF_ALLOC sections.
2382 Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
2383 }
2384 Sec->Offset = Off;
2385 Off += Sec->Size;
2386 }
2387 return Off;
2388}
2389
2390// Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
2391// have been updated.
2392static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
2393 uint64_t HdrEnd) {
2394 uint64_t MaxOffset = 0;
2395 for (Segment *Seg : Segments) {
2396 if (Seg->Type == PT_PHDR)
2397 continue;
2398
2399 // The segment offset is generally the offset of the first section.
2400 //
2401 // For a segment containing no section (see sectionWithinSegment), if it has
2402 // a parent segment, copy the parent segment's offset field. This works for
2403 // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
2404 // debugging anyway.
2405 const SectionBase *FirstSec = Seg->firstSection();
2407 FirstSec ? FirstSec->Offset
2408 : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
2409 uint64_t FileSize = 0;
2410 for (const SectionBase *Sec : Seg->Sections) {
2411 uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
2412 if (Sec->Offset + Size > Offset)
2413 FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
2414 }
2415
2416 // If the segment includes EHDR and program headers, don't make it smaller
2417 // than the headers.
2418 if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
2419 FileSize += Offset - Seg->Offset;
2420 Offset = Seg->Offset;
2421 FileSize = std::max(FileSize, HdrEnd - Offset);
2422 }
2423
2424 Seg->Offset = Offset;
2425 Seg->FileSize = FileSize;
2426 MaxOffset = std::max(MaxOffset, Offset + FileSize);
2427 }
2428 return MaxOffset;
2429}
2430
2431template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
2432 Segment &ElfHdr = Obj.ElfHdrSegment;
2433 ElfHdr.Type = PT_PHDR;
2434 ElfHdr.Flags = 0;
2435 ElfHdr.VAddr = 0;
2436 ElfHdr.PAddr = 0;
2437 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
2438 ElfHdr.Align = 0;
2439}
2440
2441template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
2442 // We need a temporary list of segments that has a special order to it
2443 // so that we know that anytime ->ParentSegment is set that segment has
2444 // already had its offset properly set.
2445 std::vector<Segment *> OrderedSegments;
2446 for (Segment &Segment : Obj.segments())
2447 OrderedSegments.push_back(&Segment);
2448 OrderedSegments.push_back(&Obj.ElfHdrSegment);
2449 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
2450 orderSegments(OrderedSegments);
2451
2453 if (OnlyKeepDebug) {
2454 // For --only-keep-debug, the sections that did not preserve contents were
2455 // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
2456 // then rewrite p_offset/p_filesz of program headers.
2457 uint64_t HdrEnd =
2458 sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
2460 Offset = std::max(Offset,
2461 layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
2462 } else {
2463 // Offset is used as the start offset of the first segment to be laid out.
2464 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
2465 // we start at offset 0.
2466 Offset = layoutSegments(OrderedSegments, 0);
2467 Offset = layoutSections(Obj.sections(), Offset);
2468 }
2469 // If we need to write the section header table out then we need to align the
2470 // Offset so that SHOffset is valid.
2471 if (WriteSectionHeaders)
2472 Offset = alignTo(Offset, sizeof(Elf_Addr));
2473 Obj.SHOff = Offset;
2474}
2475
2476template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
2477 // We already have the section header offset so we can calculate the total
2478 // size by just adding up the size of each section header.
2479 if (!WriteSectionHeaders)
2480 return Obj.SHOff;
2481 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
2482 return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
2483}
2484
2485template <class ELFT> Error ELFWriter<ELFT>::write() {
2486 // Segment data must be written first, so that the ELF header and program
2487 // header tables can overwrite it, if covered by a segment.
2488 writeSegmentData();
2489 writeEhdr();
2490 writePhdrs();
2491 if (Error E = writeSectionData())
2492 return E;
2493 if (WriteSectionHeaders)
2494 writeShdrs();
2495
2496 // TODO: Implement direct writing to the output stream (without intermediate
2497 // memory buffer Buf).
2498 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2499 return Error::success();
2500}
2501
2503 // We can remove an empty symbol table from non-relocatable objects.
2504 // Relocatable objects typically have relocation sections whose
2505 // sh_link field points to .symtab, so we can't remove .symtab
2506 // even if it is empty.
2507 if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
2508 !Obj.SymbolTable->empty())
2509 return Error::success();
2510
2511 // .strtab can be used for section names. In such a case we shouldn't
2512 // remove it.
2513 auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
2514 ? nullptr
2515 : Obj.SymbolTable->getStrTab();
2516 return Obj.removeSections(false, [&](const SectionBase &Sec) {
2517 return &Sec == Obj.SymbolTable || &Sec == StrTab;
2518 });
2519}
2520
2521template <class ELFT> Error ELFWriter<ELFT>::finalize() {
2522 // It could happen that SectionNames has been removed and yet the user wants
2523 // a section header table output. We need to throw an error if a user tries
2524 // to do that.
2525 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
2527 "cannot write section header table because "
2528 "section header string table was removed");
2529
2530 if (Error E = removeUnneededSections(Obj))
2531 return E;
2532
2533 // If the .symtab indices have not been changed, restore the sh_link to
2534 // .symtab for sections that were linked to .symtab.
2535 if (Obj.SymbolTable && !Obj.SymbolTable->indicesChanged())
2536 for (SectionBase &Sec : Obj.sections())
2537 Sec.restoreSymTabLink(*Obj.SymbolTable);
2538
2539 // We need to assign indexes before we perform layout because we need to know
2540 // if we need large indexes or not. We can assign indexes first and check as
2541 // we go to see if we will actully need large indexes.
2542 bool NeedsLargeIndexes = false;
2543 if (Obj.sections().size() >= SHN_LORESERVE) {
2544 SectionTableRef Sections = Obj.sections();
2545 // Sections doesn't include the null section header, so account for this
2546 // when skipping the first N sections.
2547 NeedsLargeIndexes =
2548 any_of(drop_begin(Sections, SHN_LORESERVE - 1),
2549 [](const SectionBase &Sec) { return Sec.HasSymbol; });
2550 // TODO: handle case where only one section needs the large index table but
2551 // only needs it because the large index table hasn't been removed yet.
2552 }
2553
2554 if (NeedsLargeIndexes) {
2555 // This means we definitely need to have a section index table but if we
2556 // already have one then we should use it instead of making a new one.
2557 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
2558 // Addition of a section to the end does not invalidate the indexes of
2559 // other sections and assigns the correct index to the new section.
2560 auto &Shndx = Obj.addSection<SectionIndexSection>();
2561 Obj.SymbolTable->setShndxTable(&Shndx);
2562 Shndx.setSymTab(Obj.SymbolTable);
2563 }
2564 } else {
2565 // Since we don't need SectionIndexTable we should remove it and all
2566 // references to it.
2567 if (Obj.SectionIndexTable != nullptr) {
2568 // We do not support sections referring to the section index table.
2569 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
2570 [this](const SectionBase &Sec) {
2571 return &Sec == Obj.SectionIndexTable;
2572 }))
2573 return E;
2574 }
2575 }
2576
2577 // Make sure we add the names of all the sections. Importantly this must be
2578 // done after we decide to add or remove SectionIndexes.
2579 if (Obj.SectionNames != nullptr)
2580 for (const SectionBase &Sec : Obj.sections())
2581 Obj.SectionNames->addString(Sec.Name);
2582
2583 initEhdrSegment();
2584
2585 // Before we can prepare for layout the indexes need to be finalized.
2586 // Also, the output arch may not be the same as the input arch, so fix up
2587 // size-related fields before doing layout calculations.
2588 uint64_t Index = 0;
2589 auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
2590 for (SectionBase &Sec : Obj.sections()) {
2591 Sec.Index = Index++;
2592 if (Error Err = Sec.accept(*SecSizer))
2593 return Err;
2594 }
2595
2596 // The symbol table does not update all other sections on update. For
2597 // instance, symbol names are not added as new symbols are added. This means
2598 // that some sections, like .strtab, don't yet have their final size.
2599 if (Obj.SymbolTable != nullptr)
2600 Obj.SymbolTable->prepareForLayout();
2601
2602 // Now that all strings are added we want to finalize string table builders,
2603 // because that affects section sizes which in turn affects section offsets.
2604 for (SectionBase &Sec : Obj.sections())
2605 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
2606 StrTab->prepareForLayout();
2607
2608 assignOffsets();
2609
2610 // layoutSections could have modified section indexes, so we need
2611 // to fill the index table after assignOffsets.
2612 if (Obj.SymbolTable != nullptr)
2613 Obj.SymbolTable->fillShndxTable();
2614
2615 // Finally now that all offsets and indexes have been set we can finalize any
2616 // remaining issues.
2617 uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
2618 for (SectionBase &Sec : Obj.sections()) {
2619 Sec.HeaderOffset = Offset;
2620 Offset += sizeof(Elf_Shdr);
2621 if (WriteSectionHeaders)
2622 Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
2623 Sec.finalize();
2624 }
2625
2626 size_t TotalSize = totalSize();
2628 if (!Buf)
2630 "failed to allocate memory buffer of " +
2631 Twine::utohexstr(TotalSize) + " bytes");
2632
2633 SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
2634 return Error::success();
2635}
2636
2638 for (const SectionBase &Sec : Obj.allocSections())
2639 if (Error Err = Sec.accept(*SecWriter))
2640 return Err;
2641
2642 // TODO: Implement direct writing to the output stream (without intermediate
2643 // memory buffer Buf).
2644 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2645 return Error::success();
2646}
2647
2649 // Compute the section LMA based on its sh_offset and the containing segment's
2650 // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
2651 // sections as MinAddr. In the output, the contents between address 0 and
2652 // MinAddr will be skipped.
2653 uint64_t MinAddr = UINT64_MAX;
2654 for (SectionBase &Sec : Obj.allocSections()) {
2655 if (Sec.ParentSegment != nullptr)
2656 Sec.Addr =
2657 Sec.Offset - Sec.ParentSegment->Offset + Sec.ParentSegment->PAddr;
2658 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2659 MinAddr = std::min(MinAddr, Sec.Addr);
2660 }
2661
2662 // Now that every section has been laid out we just need to compute the total
2663 // file size. This might not be the same as the offset returned by
2664 // layoutSections, because we want to truncate the last segment to the end of
2665 // its last non-empty section, to match GNU objcopy's behaviour.
2666 TotalSize = 0;
2667 for (SectionBase &Sec : Obj.allocSections())
2668 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
2669 Sec.Offset = Sec.Addr - MinAddr;
2670 TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
2671 }
2672
2674 if (!Buf)
2676 "failed to allocate memory buffer of " +
2677 Twine::utohexstr(TotalSize) + " bytes");
2678 SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
2679 return Error::success();
2680}
2681
2682bool IHexWriter::SectionCompare::operator()(const SectionBase *Lhs,
2683 const SectionBase *Rhs) const {
2684 return (sectionPhysicalAddr(Lhs) & 0xFFFFFFFFU) <
2685 (sectionPhysicalAddr(Rhs) & 0xFFFFFFFFU);
2686}
2687
2688uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
2689 IHexLineData HexData;
2690 uint8_t Data[4] = {};
2691 // We don't write entry point record if entry is zero.
2692 if (Obj.Entry == 0)
2693 return 0;
2694
2695 if (Obj.Entry <= 0xFFFFFU) {
2696 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
2697 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
2698 support::big);
2700 } else {
2702 support::big);
2704 }
2705 memcpy(Buf, HexData.data(), HexData.size());
2706 return HexData.size();
2707}
2708
2709uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
2711 memcpy(Buf, HexData.data(), HexData.size());
2712 return HexData.size();
2713}
2714
2717 // Write sections.
2718 for (const SectionBase *Sec : Sections)
2719 if (Error Err = Sec->accept(Writer))
2720 return Err;
2721
2722 uint64_t Offset = Writer.getBufferOffset();
2723 // Write entry point address.
2724 Offset += writeEntryPointRecord(
2725 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2726 // Write EOF.
2727 Offset += writeEndOfFileRecord(
2728 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2729 assert(Offset == TotalSize);
2730
2731 // TODO: Implement direct writing to the output stream (without intermediate
2732 // memory buffer Buf).
2733 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2734 return Error::success();
2735}
2736
2737Error IHexWriter::checkSection(const SectionBase &Sec) {
2740 return createStringError(
2742 "Section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
2743 Sec.Name.c_str(), Addr, Addr + Sec.Size - 1);
2744 return Error::success();
2745}
2746
2748 // We can't write 64-bit addresses.
2751 "Entry point address 0x%llx overflows 32 bits",
2752 Obj.Entry);
2753
2754 for (const SectionBase &Sec : Obj.sections())
2755 if ((Sec.Flags & ELF::SHF_ALLOC) && Sec.Type != ELF::SHT_NOBITS &&
2756 Sec.Size > 0) {
2757 if (Error E = checkSection(Sec))
2758 return E;
2759 Sections.insert(&Sec);
2760 }
2761
2762 std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
2764 if (!EmptyBuffer)
2766 "failed to allocate memory buffer of 0 bytes");
2767
2768 IHexSectionWriterBase LengthCalc(*EmptyBuffer);
2769 for (const SectionBase *Sec : Sections)
2770 if (Error Err = Sec->accept(LengthCalc))
2771 return Err;
2772
2773 // We need space to write section records + StartAddress record
2774 // (if start adress is not zero) + EndOfFile record.
2775 TotalSize = LengthCalc.getBufferOffset() +
2778
2780 if (!Buf)
2782 "failed to allocate memory buffer of " +
2783 Twine::utohexstr(TotalSize) + " bytes");
2784
2785 return Error::success();
2786}
2787
2788namespace llvm {
2789namespace objcopy {
2790namespace elf {
2791
2792template class ELFBuilder<ELF64LE>;
2793template class ELFBuilder<ELF64BE>;
2794template class ELFBuilder<ELF32LE>;
2795template class ELFBuilder<ELF32BE>;
2796
2797template class ELFWriter<ELF64LE>;
2798template class ELFWriter<ELF64BE>;
2799template class ELFWriter<ELF32LE>;
2800template class ELFWriter<ELF32BE>;
2801
2802} // end namespace elf
2803} // end namespace objcopy
2804} // 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:1223
static void setAddend(Elf_Rel_Impl< ELFT, false > &, uint64_t)
Definition: ELFObject.cpp:946
static Error checkChars(StringRef Line)
Definition: ELFObject.cpp:285
static void orderSegments(std::vector< Segment * > &Segments)
Definition: ELFObject.cpp:2266
static uint64_t layoutSegments(std::vector< Segment * > &Segments, uint64_t Offset)
Definition: ELFObject.cpp:2273
static bool compareSegmentsByOffset(const Segment *A, const Segment *B)
Definition: ELFObject.cpp:1230
static uint64_t layoutSections(Range Sections, uint64_t Offset)
Definition: ELFObject.cpp:2306
static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off)
Definition: ELFObject.cpp:2342
static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine)
Definition: ELFObject.cpp:631
static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector< Segment * > &Segments, uint64_t HdrEnd)
Definition: ELFObject.cpp:2392
static void getAddend(uint64_t &, const Elf_Rel_Impl< ELFT, false > &)
Definition: ELFObject.cpp:1619
static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL)
Definition: ELFObject.cpp:954
static bool addressOverflows32bit(uint64_t Addr)
Definition: ELFObject.cpp:177
static T checkedGetHex(StringRef S)
Definition: ELFObject.cpp:182
static uint64_t sectionPhysicalAddr(const SectionBase *Sec)
Definition: ELFObject.cpp:327
static Iterator toHexStr(T X, Iterator It, size_t Len)
Definition: ELFObject.cpp:193
static Error checkRecord(const IHexRecord &R)
Definition: ELFObject.cpp:235
static Error initRelocations(RelocationSection *Relocs, T RelRange)
Definition: ELFObject.cpp:1627
static Error removeUnneededSections(Object &Obj)
Definition: ELFObject.cpp:2502
static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg)
Definition: ELFObject.cpp:1193
bool End
Definition: ELF_riscv.cpp:469
Symbol * Sym
Definition: ELF_riscv.cpp:468
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define I(x, y, z)
Definition: MD5.cpp:58
if(VerifyEach)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
iterator begin() const
Definition: ArrayRef.h:153
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:160
const T * data() const
Definition: ArrayRef.h:162
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:195
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
Error takeError()
Take ownership of the stored error.
Definition: Error.h:601
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
Definition: MemoryBuffer.h:76
size_t getBufferSize() const
Definition: MemoryBuffer.h:68
StringRef getBuffer() const
Definition: MemoryBuffer.h:70
const char * getBufferStart() const
Definition: MemoryBuffer.h:66
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:704
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:474
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:613
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:584
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
void finalize()
Analyze the strings and build the final table.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:416
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
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:1252
SymbolTableSection * addSymTab(StringTableSection *StrTab)
Definition: ELFObject.cpp:1260
std::unique_ptr< Object > Obj
Definition: ELFObject.h:922
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1306
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1917
Error visit(const SymbolTableSection &Sec) override
Definition: ELFObject.cpp:148
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:564
CompressedSection(const SectionBase &Sec, DebugCompressionType CompressionType, bool Is64Bits)
Definition: ELFObject.cpp:541
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:486
Error accept(SectionVisitor &) const override
Definition: ELFObject.cpp:1013
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1021
ELFBuilder(const ELFObjectFile< ELFT > &ElfObj, Object &Obj, std::optional< StringRef > ExtractPartition)
Definition: ELFObject.cpp:1379
Error build(bool EnsureSymtab)
Definition: ELFObject.cpp:1883
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1956
Error visit(Section &Sec) override
Definition: ELFObject.cpp:83
Error visit(const SymbolTableSection &Sec) override
Definition: ELFObject.cpp:845
ELFWriter(Object &Obj, raw_ostream &Out, bool WSH, bool OnlyKeepDebug)
Definition: ELFObject.cpp:2115
void setSymTab(const SymbolTableSection *SymTabSec)
Definition: ELFObject.h:830
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:1096
Error accept(SectionVisitor &) const override
Definition: ELFObject.cpp:1184
ArrayRef< uint8_t > Contents
Definition: ELFObject.h:826
void addMember(SectionBase *Sec)
Definition: ELFObject.h:833
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1066
void setFlagWord(ELF::Elf32_Word W)
Definition: ELFObject.h:832
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:1082
Expected< std::unique_ptr< Object > > build()
Definition: ELFObject.cpp:1366
Expected< std::unique_ptr< Object > > create(bool EnsureSymtab) const override
Definition: ELFObject.cpp:1948
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:1072
StringTableSection * SectionNames
Definition: ELFObject.h:1066
bool isRelocatable() const
Definition: ELFObject.h:1109
iterator_range< filter_iterator< pointee_iterator< std::vector< SecPtr >::const_iterator >, decltype(&sectionIsAlloc)> > allocSections() const
Definition: ELFObject.h:1076
Error updateSection(StringRef Name, ArrayRef< uint8_t > Data)
Definition: ELFObject.cpp:2120
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:1068
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove)
Definition: ELFObject.cpp:2227
Error removeSections(bool AllowBrokenLinks, std::function< bool(const SectionBase &)> ToRemove)
Definition: ELFObject.cpp:2151
SymbolTableSection * SymbolTable
Definition: ELFObject.h:1067
Error replaceSections(const DenseMap< SectionBase *, SectionBase * > &FromTo)
Definition: ELFObject.cpp:2203
void appendHexData(StringRef HexData)
Definition: ELFObject.cpp:502
Error accept(SectionVisitor &Sec) const override
Definition: ELFObject.cpp:494
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:908
void addRelocation(Relocation Rel)
Definition: ELFObject.h:794
const Object & getObject() const
Definition: ELFObject.h:804
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:976
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:984
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:1001
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:880
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:674
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:623
void reserve(size_t NumSymbols)
Definition: ELFObject.h:670
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:604
Expected< T * > getSectionOfType(uint32_t Index, Twine IndexErrMsg, Twine TypeErrMsg)
Definition: ELFObject.cpp:1662
Expected< SectionBase * > getSection(uint32_t Index, Twine ErrMsg)
Definition: ELFObject.cpp:1654
virtual Error visit(const Section &Sec)=0
Error visit(const Section &Sec) override
Definition: ELFObject.cpp:170
WritableMemoryBuffer & Out
Definition: ELFObject.h:109
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:1041
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:1110
void restoreSymTabLink(SymbolTableSection &SymTab) override
Definition: ELFObject.cpp:432
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:424
void addSection(const SectionBase *Sec)
Definition: ELFObject.h:478
void removeSection(const SectionBase *Sec)
Definition: ELFObject.h:477
const SectionBase * firstSection() const
Definition: ELFObject.h:471
ArrayRef< uint8_t > getContents() const
Definition: ELFObject.h:480
std::set< const SectionBase *, SectionCompare > Sections
Definition: ELFObject.h:466
uint32_t findIndex(StringRef Name) const
Definition: ELFObject.cpp:574
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:589
const SectionBase * getStrTab() const
Definition: ELFObject.h:717
Error removeSectionReferences(bool AllowBrokenLinks, function_ref< bool(const SectionBase *)> ToRemove) override
Definition: ELFObject.cpp:722
const SectionIndexSection * getShndxTable() const
Definition: ELFObject.h:715
std::vector< std::unique_ptr< Symbol > > Symbols
Definition: ELFObject.h:695
SectionIndexSection * SectionIndexTable
Definition: ELFObject.h:697
Error accept(SectionVisitor &Visitor) const override
Definition: ELFObject.cpp:861
void addSymbol(Twine Name, uint8_t Bind, uint8_t Type, SectionBase *DefinedIn, uint64_t Value, uint8_t Visibility, uint16_t Shndx, uint64_t SymbolSize)
Definition: ELFObject.cpp:697
void updateSymbols(function_ref< void(Symbol &)> Callable)
Definition: ELFObject.cpp:739
Expected< const Symbol * > getSymbolByIndex(uint32_t Index) const
Definition: ELFObject.cpp:828
Error removeSymbols(function_ref< bool(const Symbol &)> ToRemove) override
Definition: ELFObject.cpp:748
Error initialize(SectionTableRef SecTable) override
Definition: ELFObject.cpp:769
void replaceSectionReferences(const DenseMap< SectionBase *, SectionBase * > &FromTo) override
Definition: ELFObject.cpp:762
std::unique_ptr< Symbol > SymPtr
Definition: ELFObject.h:700
void setShndxTable(SectionIndexSection *ShndxTable)
Definition: ELFObject.h:712
StringTableSection * SymbolNames
Definition: ELFObject.h:696
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:792
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
@ EI_DATA
Definition: ELF.h:53
@ EI_MAG3
Definition: ELF.h:51
@ EI_MAG1
Definition: ELF.h:49
@ EI_VERSION
Definition: ELF.h:54
@ EI_MAG2
Definition: ELF.h:50
@ EI_ABIVERSION
Definition: ELF.h:56
@ EI_MAG0
Definition: ELF.h:48
@ EI_CLASS
Definition: ELF.h:52
@ EI_OSABI
Definition: ELF.h:55
@ STB_GLOBAL
Definition: ELF.h:1243
@ STB_LOCAL
Definition: ELF.h:1242
@ 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
@ EV_CURRENT
Definition: ELF.h:127
@ ET_REL
Definition: ELF.h:116
@ 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
@ ELFOSABI_NONE
Definition: ELF.h:341
uint32_t Elf32_Word
Definition: ELF.h:32
@ SHT_STRTAB
Definition: ELF.h:1002
@ SHT_GROUP
Definition: ELF.h:1014
@ SHT_PROGBITS
Definition: ELF.h:1000
@ SHT_REL
Definition: ELF.h:1008
@ SHT_NULL
Definition: ELF.h:999
@ SHT_NOBITS
Definition: ELF.h:1007
@ SHT_SYMTAB
Definition: ELF.h:1001
@ SHT_LLVM_PART_EHDR
Definition: ELF.h:1031
@ SHT_DYNAMIC
Definition: ELF.h:1005
@ SHT_SYMTAB_SHNDX
Definition: ELF.h:1015
@ SHT_GNU_HASH
Definition: ELF.h:1044
@ SHT_RELA
Definition: ELF.h:1003
@ SHT_DYNSYM
Definition: ELF.h:1010
@ SHT_HASH
Definition: ELF.h:1004
@ SHN_XINDEX
Definition: ELF.h:993
@ SHN_ABS
Definition: ELF.h:991
@ SHN_COMMON
Definition: ELF.h:992
@ SHN_UNDEF
Definition: ELF.h:985
@ SHN_LORESERVE
Definition: ELF.h:986
@ PT_LOAD
Definition: ELF.h:1388
@ PT_TLS
Definition: ELF.h:1394
@ PT_PHDR
Definition: ELF.h:1393
@ ELFCOMPRESS_ZSTD
Definition: ELF.h:1837
@ ELFCOMPRESS_ZLIB
Definition: ELF.h:1836
@ ELFCLASS64
Definition: ELF.h:329
@ ELFCLASS32
Definition: ELF.h:328
@ SHN_AMDGPU_LDS
Definition: ELF.h:1758
@ SHF_ALLOC
Definition: ELF.h:1089
@ SHF_COMPRESSED
Definition: ELF.h:1117
@ SHF_WRITE
Definition: ELF.h:1086
@ SHF_TLS
Definition: ELF.h:1114
@ SHN_MIPS_SUNDEFINED
Definition: ELF.h:574
@ SHN_MIPS_SCOMMON
Definition: ELF.h:573
@ SHN_MIPS_ACOMMON
Definition: ELF.h:570
@ STT_NOTYPE
Definition: ELF.h:1254
@ GRP_COMDAT
Definition: ELF.h:1189
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:96
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:579
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:330
@ Offset
Definition: DWP.cpp:440
void stable_sort(R &&Range)
Definition: STLExtras.h:1971
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1685
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition: Casting.h:649
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1244
@ operation_not_permitted
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1734
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1652
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:1907
@ 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:1829
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:1754
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:2021
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:667
SectionBase * DefinedIn
Definition: ELFObject.h:641
SymbolShndxType ShndxType
Definition: ELFObject.h:642
Definition: regcomp.c:192