[clang][Driver] Support simplified triple versions for config files (#111387)
[llvm-project.git] / llvm / lib / ObjCopy / ELF / ELFObject.cpp
blob01c2f24629077ad9196c4ead99c456682468e7ec
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 //===----------------------------------------------------------------------===//
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"
14 #include "llvm/ADT/iterator_range.h"
15 #include "llvm/BinaryFormat/ELF.h"
16 #include "llvm/MC/MCELFExtras.h"
17 #include "llvm/MC/MCTargetOptions.h"
18 #include "llvm/Support/Compression.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/Path.h"
22 #include <algorithm>
23 #include <cstddef>
24 #include <cstdint>
25 #include <iterator>
26 #include <unordered_set>
27 #include <utility>
28 #include <vector>
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::objcopy::elf;
33 using namespace llvm::object;
34 using namespace llvm::support;
36 template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
37 uint8_t *B = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
38 Obj.ProgramHdrSegment.Offset + Seg.Index * sizeof(Elf_Phdr);
39 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
40 Phdr.p_type = Seg.Type;
41 Phdr.p_flags = Seg.Flags;
42 Phdr.p_offset = Seg.Offset;
43 Phdr.p_vaddr = Seg.VAddr;
44 Phdr.p_paddr = Seg.PAddr;
45 Phdr.p_filesz = Seg.FileSize;
46 Phdr.p_memsz = Seg.MemSize;
47 Phdr.p_align = Seg.Align;
50 Error SectionBase::removeSectionReferences(
51 bool, function_ref<bool(const SectionBase *)>) {
52 return Error::success();
55 Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)>) {
56 return Error::success();
59 Error SectionBase::initialize(SectionTableRef) { return Error::success(); }
60 void SectionBase::finalize() {}
61 void SectionBase::markSymbols() {}
62 void SectionBase::replaceSectionReferences(
63 const DenseMap<SectionBase *, SectionBase *> &) {}
64 void SectionBase::onRemove() {}
66 template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
67 uint8_t *B =
68 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Sec.HeaderOffset;
69 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
70 Shdr.sh_name = Sec.NameIndex;
71 Shdr.sh_type = Sec.Type;
72 Shdr.sh_flags = Sec.Flags;
73 Shdr.sh_addr = Sec.Addr;
74 Shdr.sh_offset = Sec.Offset;
75 Shdr.sh_size = Sec.Size;
76 Shdr.sh_link = Sec.Link;
77 Shdr.sh_info = Sec.Info;
78 Shdr.sh_addralign = Sec.Align;
79 Shdr.sh_entsize = Sec.EntrySize;
82 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(Section &) {
83 return Error::success();
86 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(OwnedDataSection &) {
87 return Error::success();
90 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(StringTableSection &) {
91 return Error::success();
94 template <class ELFT>
95 Error ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &) {
96 return Error::success();
99 template <class ELFT>
100 Error ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
101 Sec.EntrySize = sizeof(Elf_Sym);
102 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
103 // Align to the largest field in Elf_Sym.
104 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
105 return Error::success();
108 template <bool Is64>
109 static SmallVector<char, 0> encodeCrel(ArrayRef<Relocation> Relocations) {
110 using uint = std::conditional_t<Is64, uint64_t, uint32_t>;
111 SmallVector<char, 0> Content;
112 raw_svector_ostream OS(Content);
113 ELF::encodeCrel<Is64>(OS, Relocations, [&](const Relocation &R) {
114 uint32_t CurSymIdx = R.RelocSymbol ? R.RelocSymbol->Index : 0;
115 return ELF::Elf_Crel<Is64>{static_cast<uint>(R.Offset), CurSymIdx, R.Type,
116 std::make_signed_t<uint>(R.Addend)};
118 return Content;
121 template <class ELFT>
122 Error ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
123 if (Sec.Type == SHT_CREL) {
124 Sec.Size = encodeCrel<ELFT::Is64Bits>(Sec.Relocations).size();
125 } else {
126 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
127 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
128 // Align to the largest field in Elf_Rel(a).
129 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
131 return Error::success();
134 template <class ELFT>
135 Error ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &) {
136 return Error::success();
139 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {
140 Sec.Size = sizeof(Elf_Word) + Sec.GroupMembers.size() * sizeof(Elf_Word);
141 return Error::success();
144 template <class ELFT>
145 Error ELFSectionSizer<ELFT>::visit(SectionIndexSection &) {
146 return Error::success();
149 template <class ELFT> Error ELFSectionSizer<ELFT>::visit(CompressedSection &) {
150 return Error::success();
153 template <class ELFT>
154 Error ELFSectionSizer<ELFT>::visit(DecompressedSection &) {
155 return Error::success();
158 Error BinarySectionWriter::visit(const SectionIndexSection &Sec) {
159 return createStringError(errc::operation_not_permitted,
160 "cannot write symbol section index table '" +
161 Sec.Name + "' ");
164 Error BinarySectionWriter::visit(const SymbolTableSection &Sec) {
165 return createStringError(errc::operation_not_permitted,
166 "cannot write symbol table '" + Sec.Name +
167 "' out to binary");
170 Error BinarySectionWriter::visit(const RelocationSection &Sec) {
171 return createStringError(errc::operation_not_permitted,
172 "cannot write relocation section '" + Sec.Name +
173 "' out to binary");
176 Error BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
177 return createStringError(errc::operation_not_permitted,
178 "cannot write '" + Sec.Name + "' out to binary");
181 Error BinarySectionWriter::visit(const GroupSection &Sec) {
182 return createStringError(errc::operation_not_permitted,
183 "cannot write '" + Sec.Name + "' out to binary");
186 Error SectionWriter::visit(const Section &Sec) {
187 if (Sec.Type != SHT_NOBITS)
188 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
190 return Error::success();
193 static bool addressOverflows32bit(uint64_t Addr) {
194 // Sign extended 32 bit addresses (e.g 0xFFFFFFFF80000000) are ok
195 return Addr > UINT32_MAX && Addr + 0x80000000 > UINT32_MAX;
198 template <class T> static T checkedGetHex(StringRef S) {
199 T Value;
200 bool Fail = S.getAsInteger(16, Value);
201 assert(!Fail);
202 (void)Fail;
203 return Value;
206 // Fills exactly Len bytes of buffer with hexadecimal characters
207 // representing value 'X'
208 template <class T, class Iterator>
209 static Iterator toHexStr(T X, Iterator It, size_t Len) {
210 // Fill range with '0'
211 std::fill(It, It + Len, '0');
213 for (long I = Len - 1; I >= 0; --I) {
214 unsigned char Mod = static_cast<unsigned char>(X) & 15;
215 *(It + I) = hexdigit(Mod, false);
216 X >>= 4;
218 assert(X == 0);
219 return It + Len;
222 uint8_t IHexRecord::getChecksum(StringRef S) {
223 assert((S.size() & 1) == 0);
224 uint8_t Checksum = 0;
225 while (!S.empty()) {
226 Checksum += checkedGetHex<uint8_t>(S.take_front(2));
227 S = S.drop_front(2);
229 return -Checksum;
232 IHexLineData IHexRecord::getLine(uint8_t Type, uint16_t Addr,
233 ArrayRef<uint8_t> Data) {
234 IHexLineData Line(getLineLength(Data.size()));
235 assert(Line.size());
236 auto Iter = Line.begin();
237 *Iter++ = ':';
238 Iter = toHexStr(Data.size(), Iter, 2);
239 Iter = toHexStr(Addr, Iter, 4);
240 Iter = toHexStr(Type, Iter, 2);
241 for (uint8_t X : Data)
242 Iter = toHexStr(X, Iter, 2);
243 StringRef S(Line.data() + 1, std::distance(Line.begin() + 1, Iter));
244 Iter = toHexStr(getChecksum(S), Iter, 2);
245 *Iter++ = '\r';
246 *Iter++ = '\n';
247 assert(Iter == Line.end());
248 return Line;
251 static Error checkRecord(const IHexRecord &R) {
252 switch (R.Type) {
253 case IHexRecord::Data:
254 if (R.HexData.size() == 0)
255 return createStringError(
256 errc::invalid_argument,
257 "zero data length is not allowed for data records");
258 break;
259 case IHexRecord::EndOfFile:
260 break;
261 case IHexRecord::SegmentAddr:
262 // 20-bit segment address. Data length must be 2 bytes
263 // (4 bytes in hex)
264 if (R.HexData.size() != 4)
265 return createStringError(
266 errc::invalid_argument,
267 "segment address data should be 2 bytes in size");
268 break;
269 case IHexRecord::StartAddr80x86:
270 case IHexRecord::StartAddr:
271 if (R.HexData.size() != 8)
272 return createStringError(errc::invalid_argument,
273 "start address data should be 4 bytes in size");
274 // According to Intel HEX specification '03' record
275 // only specifies the code address within the 20-bit
276 // segmented address space of the 8086/80186. This
277 // means 12 high order bits should be zeroes.
278 if (R.Type == IHexRecord::StartAddr80x86 &&
279 R.HexData.take_front(3) != "000")
280 return createStringError(errc::invalid_argument,
281 "start address exceeds 20 bit for 80x86");
282 break;
283 case IHexRecord::ExtendedAddr:
284 // 16-31 bits of linear base address
285 if (R.HexData.size() != 4)
286 return createStringError(
287 errc::invalid_argument,
288 "extended address data should be 2 bytes in size");
289 break;
290 default:
291 // Unknown record type
292 return createStringError(errc::invalid_argument, "unknown record type: %u",
293 static_cast<unsigned>(R.Type));
295 return Error::success();
298 // Checks that IHEX line contains valid characters.
299 // This allows converting hexadecimal data to integers
300 // without extra verification.
301 static Error checkChars(StringRef Line) {
302 assert(!Line.empty());
303 if (Line[0] != ':')
304 return createStringError(errc::invalid_argument,
305 "missing ':' in the beginning of line.");
307 for (size_t Pos = 1; Pos < Line.size(); ++Pos)
308 if (hexDigitValue(Line[Pos]) == -1U)
309 return createStringError(errc::invalid_argument,
310 "invalid character at position %zu.", Pos + 1);
311 return Error::success();
314 Expected<IHexRecord> IHexRecord::parse(StringRef Line) {
315 assert(!Line.empty());
317 // ':' + Length + Address + Type + Checksum with empty data ':LLAAAATTCC'
318 if (Line.size() < 11)
319 return createStringError(errc::invalid_argument,
320 "line is too short: %zu chars.", Line.size());
322 if (Error E = checkChars(Line))
323 return std::move(E);
325 IHexRecord Rec;
326 size_t DataLen = checkedGetHex<uint8_t>(Line.substr(1, 2));
327 if (Line.size() != getLength(DataLen))
328 return createStringError(errc::invalid_argument,
329 "invalid line length %zu (should be %zu)",
330 Line.size(), getLength(DataLen));
332 Rec.Addr = checkedGetHex<uint16_t>(Line.substr(3, 4));
333 Rec.Type = checkedGetHex<uint8_t>(Line.substr(7, 2));
334 Rec.HexData = Line.substr(9, DataLen * 2);
336 if (getChecksum(Line.drop_front(1)) != 0)
337 return createStringError(errc::invalid_argument, "incorrect checksum.");
338 if (Error E = checkRecord(Rec))
339 return std::move(E);
340 return Rec;
343 static uint64_t sectionPhysicalAddr(const SectionBase *Sec) {
344 Segment *Seg = Sec->ParentSegment;
345 if (Seg && Seg->Type != ELF::PT_LOAD)
346 Seg = nullptr;
347 return Seg ? Seg->PAddr + Sec->OriginalOffset - Seg->OriginalOffset
348 : Sec->Addr;
351 void IHexSectionWriterBase::writeSection(const SectionBase *Sec,
352 ArrayRef<uint8_t> Data) {
353 assert(Data.size() == Sec->Size);
354 const uint32_t ChunkSize = 16;
355 uint32_t Addr = sectionPhysicalAddr(Sec) & 0xFFFFFFFFU;
356 while (!Data.empty()) {
357 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
358 if (Addr > SegmentAddr + BaseAddr + 0xFFFFU) {
359 if (Addr > 0xFFFFFU) {
360 // Write extended address record, zeroing segment address
361 // if needed.
362 if (SegmentAddr != 0)
363 SegmentAddr = writeSegmentAddr(0U);
364 BaseAddr = writeBaseAddr(Addr);
365 } else {
366 // We can still remain 16-bit
367 SegmentAddr = writeSegmentAddr(Addr);
370 uint64_t SegOffset = Addr - BaseAddr - SegmentAddr;
371 assert(SegOffset <= 0xFFFFU);
372 DataSize = std::min(DataSize, 0x10000U - SegOffset);
373 writeData(0, SegOffset, Data.take_front(DataSize));
374 Addr += DataSize;
375 Data = Data.drop_front(DataSize);
379 uint64_t IHexSectionWriterBase::writeSegmentAddr(uint64_t Addr) {
380 assert(Addr <= 0xFFFFFU);
381 uint8_t Data[] = {static_cast<uint8_t>((Addr & 0xF0000U) >> 12), 0};
382 writeData(2, 0, Data);
383 return Addr & 0xF0000U;
386 uint64_t IHexSectionWriterBase::writeBaseAddr(uint64_t Addr) {
387 assert(Addr <= 0xFFFFFFFFU);
388 uint64_t Base = Addr & 0xFFFF0000U;
389 uint8_t Data[] = {static_cast<uint8_t>(Base >> 24),
390 static_cast<uint8_t>((Base >> 16) & 0xFF)};
391 writeData(4, 0, Data);
392 return Base;
395 void IHexSectionWriterBase::writeData(uint8_t, uint16_t,
396 ArrayRef<uint8_t> Data) {
397 Offset += IHexRecord::getLineLength(Data.size());
400 Error IHexSectionWriterBase::visit(const Section &Sec) {
401 writeSection(&Sec, Sec.Contents);
402 return Error::success();
405 Error IHexSectionWriterBase::visit(const OwnedDataSection &Sec) {
406 writeSection(&Sec, Sec.Data);
407 return Error::success();
410 Error IHexSectionWriterBase::visit(const StringTableSection &Sec) {
411 // Check that sizer has already done its work
412 assert(Sec.Size == Sec.StrTabBuilder.getSize());
413 // We are free to pass an invalid pointer to writeSection as long
414 // as we don't actually write any data. The real writer class has
415 // to override this method .
416 writeSection(&Sec, {nullptr, static_cast<size_t>(Sec.Size)});
417 return Error::success();
420 Error IHexSectionWriterBase::visit(const DynamicRelocationSection &Sec) {
421 writeSection(&Sec, Sec.Contents);
422 return Error::success();
425 void IHexSectionWriter::writeData(uint8_t Type, uint16_t Addr,
426 ArrayRef<uint8_t> Data) {
427 IHexLineData HexData = IHexRecord::getLine(Type, Addr, Data);
428 memcpy(Out.getBufferStart() + Offset, HexData.data(), HexData.size());
429 Offset += HexData.size();
432 Error IHexSectionWriter::visit(const StringTableSection &Sec) {
433 assert(Sec.Size == Sec.StrTabBuilder.getSize());
434 std::vector<uint8_t> Data(Sec.Size);
435 Sec.StrTabBuilder.write(Data.data());
436 writeSection(&Sec, Data);
437 return Error::success();
440 Error Section::accept(SectionVisitor &Visitor) const {
441 return Visitor.visit(*this);
444 Error Section::accept(MutableSectionVisitor &Visitor) {
445 return Visitor.visit(*this);
448 void Section::restoreSymTabLink(SymbolTableSection &SymTab) {
449 if (HasSymTabLink) {
450 assert(LinkSection == nullptr);
451 LinkSection = &SymTab;
455 Error SectionWriter::visit(const OwnedDataSection &Sec) {
456 llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
457 return Error::success();
460 template <class ELFT>
461 Error ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
462 ArrayRef<uint8_t> Compressed =
463 Sec.OriginalData.slice(sizeof(Elf_Chdr_Impl<ELFT>));
464 SmallVector<uint8_t, 128> Decompressed;
465 DebugCompressionType Type;
466 switch (Sec.ChType) {
467 case ELFCOMPRESS_ZLIB:
468 Type = DebugCompressionType::Zlib;
469 break;
470 case ELFCOMPRESS_ZSTD:
471 Type = DebugCompressionType::Zstd;
472 break;
473 default:
474 return createStringError(errc::invalid_argument,
475 "--decompress-debug-sections: ch_type (" +
476 Twine(Sec.ChType) + ") of section '" +
477 Sec.Name + "' is unsupported");
479 if (auto *Reason =
480 compression::getReasonIfUnsupported(compression::formatFor(Type)))
481 return createStringError(errc::invalid_argument,
482 "failed to decompress section '" + Sec.Name +
483 "': " + Reason);
484 if (Error E = compression::decompress(Type, Compressed, Decompressed,
485 static_cast<size_t>(Sec.Size)))
486 return createStringError(errc::invalid_argument,
487 "failed to decompress section '" + Sec.Name +
488 "': " + toString(std::move(E)));
490 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
491 std::copy(Decompressed.begin(), Decompressed.end(), Buf);
493 return Error::success();
496 Error BinarySectionWriter::visit(const DecompressedSection &Sec) {
497 return createStringError(errc::operation_not_permitted,
498 "cannot write compressed section '" + Sec.Name +
499 "' ");
502 Error DecompressedSection::accept(SectionVisitor &Visitor) const {
503 return Visitor.visit(*this);
506 Error DecompressedSection::accept(MutableSectionVisitor &Visitor) {
507 return Visitor.visit(*this);
510 Error OwnedDataSection::accept(SectionVisitor &Visitor) const {
511 return Visitor.visit(*this);
514 Error OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
515 return Visitor.visit(*this);
518 void OwnedDataSection::appendHexData(StringRef HexData) {
519 assert((HexData.size() & 1) == 0);
520 while (!HexData.empty()) {
521 Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2)));
522 HexData = HexData.drop_front(2);
524 Size = Data.size();
527 Error BinarySectionWriter::visit(const CompressedSection &Sec) {
528 return createStringError(errc::operation_not_permitted,
529 "cannot write compressed section '" + Sec.Name +
530 "' ");
533 template <class ELFT>
534 Error ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
535 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
536 Elf_Chdr_Impl<ELFT> Chdr = {};
537 switch (Sec.CompressionType) {
538 case DebugCompressionType::None:
539 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
540 return Error::success();
541 case DebugCompressionType::Zlib:
542 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
543 break;
544 case DebugCompressionType::Zstd:
545 Chdr.ch_type = ELF::ELFCOMPRESS_ZSTD;
546 break;
548 Chdr.ch_size = Sec.DecompressedSize;
549 Chdr.ch_addralign = Sec.DecompressedAlign;
550 memcpy(Buf, &Chdr, sizeof(Chdr));
551 Buf += sizeof(Chdr);
553 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
554 return Error::success();
557 CompressedSection::CompressedSection(const SectionBase &Sec,
558 DebugCompressionType CompressionType,
559 bool Is64Bits)
560 : SectionBase(Sec), CompressionType(CompressionType),
561 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
562 compression::compress(compression::Params(CompressionType), OriginalData,
563 CompressedData);
565 Flags |= ELF::SHF_COMPRESSED;
566 OriginalFlags |= ELF::SHF_COMPRESSED;
567 size_t ChdrSize = Is64Bits ? sizeof(object::Elf_Chdr_Impl<object::ELF64LE>)
568 : sizeof(object::Elf_Chdr_Impl<object::ELF32LE>);
569 Size = ChdrSize + CompressedData.size();
570 Align = 8;
573 CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
574 uint32_t ChType, uint64_t DecompressedSize,
575 uint64_t DecompressedAlign)
576 : ChType(ChType), CompressionType(DebugCompressionType::None),
577 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
578 OriginalData = CompressedData;
581 Error CompressedSection::accept(SectionVisitor &Visitor) const {
582 return Visitor.visit(*this);
585 Error CompressedSection::accept(MutableSectionVisitor &Visitor) {
586 return Visitor.visit(*this);
589 void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
591 uint32_t StringTableSection::findIndex(StringRef Name) const {
592 return StrTabBuilder.getOffset(Name);
595 void StringTableSection::prepareForLayout() {
596 StrTabBuilder.finalize();
597 Size = StrTabBuilder.getSize();
600 Error SectionWriter::visit(const StringTableSection &Sec) {
601 Sec.StrTabBuilder.write(reinterpret_cast<uint8_t *>(Out.getBufferStart()) +
602 Sec.Offset);
603 return Error::success();
606 Error StringTableSection::accept(SectionVisitor &Visitor) const {
607 return Visitor.visit(*this);
610 Error StringTableSection::accept(MutableSectionVisitor &Visitor) {
611 return Visitor.visit(*this);
614 template <class ELFT>
615 Error ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
616 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
617 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
618 return Error::success();
621 Error SectionIndexSection::initialize(SectionTableRef SecTable) {
622 Size = 0;
623 Expected<SymbolTableSection *> Sec =
624 SecTable.getSectionOfType<SymbolTableSection>(
625 Link,
626 "Link field value " + Twine(Link) + " in section " + Name +
627 " is invalid",
628 "Link field value " + Twine(Link) + " in section " + Name +
629 " is not a symbol table");
630 if (!Sec)
631 return Sec.takeError();
633 setSymTab(*Sec);
634 Symbols->setShndxTable(this);
635 return Error::success();
638 void SectionIndexSection::finalize() { Link = Symbols->Index; }
640 Error SectionIndexSection::accept(SectionVisitor &Visitor) const {
641 return Visitor.visit(*this);
644 Error SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
645 return Visitor.visit(*this);
648 static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
649 switch (Index) {
650 case SHN_ABS:
651 case SHN_COMMON:
652 return true;
655 if (Machine == EM_AMDGPU) {
656 return Index == SHN_AMDGPU_LDS;
659 if (Machine == EM_MIPS) {
660 switch (Index) {
661 case SHN_MIPS_ACOMMON:
662 case SHN_MIPS_SCOMMON:
663 case SHN_MIPS_SUNDEFINED:
664 return true;
668 if (Machine == EM_HEXAGON) {
669 switch (Index) {
670 case SHN_HEXAGON_SCOMMON:
671 case SHN_HEXAGON_SCOMMON_1:
672 case SHN_HEXAGON_SCOMMON_2:
673 case SHN_HEXAGON_SCOMMON_4:
674 case SHN_HEXAGON_SCOMMON_8:
675 return true;
678 return false;
681 // Large indexes force us to clarify exactly what this function should do. This
682 // function should return the value that will appear in st_shndx when written
683 // out.
684 uint16_t Symbol::getShndx() const {
685 if (DefinedIn != nullptr) {
686 if (DefinedIn->Index >= SHN_LORESERVE)
687 return SHN_XINDEX;
688 return DefinedIn->Index;
691 if (ShndxType == SYMBOL_SIMPLE_INDEX) {
692 // This means that we don't have a defined section but we do need to
693 // output a legitimate section index.
694 return SHN_UNDEF;
697 assert(ShndxType == SYMBOL_ABS || ShndxType == SYMBOL_COMMON ||
698 (ShndxType >= SYMBOL_LOPROC && ShndxType <= SYMBOL_HIPROC) ||
699 (ShndxType >= SYMBOL_LOOS && ShndxType <= SYMBOL_HIOS));
700 return static_cast<uint16_t>(ShndxType);
703 bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
705 void SymbolTableSection::assignIndices() {
706 uint32_t Index = 0;
707 for (auto &Sym : Symbols) {
708 if (Sym->Index != Index)
709 IndicesChanged = true;
710 Sym->Index = Index++;
714 void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
715 SectionBase *DefinedIn, uint64_t Value,
716 uint8_t Visibility, uint16_t Shndx,
717 uint64_t SymbolSize) {
718 Symbol Sym;
719 Sym.Name = Name.str();
720 Sym.Binding = Bind;
721 Sym.Type = Type;
722 Sym.DefinedIn = DefinedIn;
723 if (DefinedIn != nullptr)
724 DefinedIn->HasSymbol = true;
725 if (DefinedIn == nullptr) {
726 if (Shndx >= SHN_LORESERVE)
727 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
728 else
729 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
731 Sym.Value = Value;
732 Sym.Visibility = Visibility;
733 Sym.Size = SymbolSize;
734 Sym.Index = Symbols.size();
735 Symbols.emplace_back(std::make_unique<Symbol>(Sym));
736 Size += this->EntrySize;
739 Error SymbolTableSection::removeSectionReferences(
740 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
741 if (ToRemove(SectionIndexTable))
742 SectionIndexTable = nullptr;
743 if (ToRemove(SymbolNames)) {
744 if (!AllowBrokenLinks)
745 return createStringError(
746 llvm::errc::invalid_argument,
747 "string table '%s' cannot be removed because it is "
748 "referenced by the symbol table '%s'",
749 SymbolNames->Name.data(), this->Name.data());
750 SymbolNames = nullptr;
752 return removeSymbols(
753 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
756 void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
757 for (SymPtr &Sym : llvm::drop_begin(Symbols))
758 Callable(*Sym);
759 std::stable_partition(
760 std::begin(Symbols), std::end(Symbols),
761 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
762 assignIndices();
765 Error SymbolTableSection::removeSymbols(
766 function_ref<bool(const Symbol &)> ToRemove) {
767 Symbols.erase(
768 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
769 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
770 std::end(Symbols));
771 auto PrevSize = Size;
772 Size = Symbols.size() * EntrySize;
773 if (Size < PrevSize)
774 IndicesChanged = true;
775 assignIndices();
776 return Error::success();
779 void SymbolTableSection::replaceSectionReferences(
780 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
781 for (std::unique_ptr<Symbol> &Sym : Symbols)
782 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
783 Sym->DefinedIn = To;
786 Error SymbolTableSection::initialize(SectionTableRef SecTable) {
787 Size = 0;
788 Expected<StringTableSection *> Sec =
789 SecTable.getSectionOfType<StringTableSection>(
790 Link,
791 "Symbol table has link index of " + Twine(Link) +
792 " which is not a valid index",
793 "Symbol table has link index of " + Twine(Link) +
794 " which is not a string table");
795 if (!Sec)
796 return Sec.takeError();
798 setStrTab(*Sec);
799 return Error::success();
802 void SymbolTableSection::finalize() {
803 uint32_t MaxLocalIndex = 0;
804 for (std::unique_ptr<Symbol> &Sym : Symbols) {
805 Sym->NameIndex =
806 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
807 if (Sym->Binding == STB_LOCAL)
808 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
810 // Now we need to set the Link and Info fields.
811 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
812 Info = MaxLocalIndex + 1;
815 void SymbolTableSection::prepareForLayout() {
816 // Reserve proper amount of space in section index table, so we can
817 // layout sections correctly. We will fill the table with correct
818 // indexes later in fillShdnxTable.
819 if (SectionIndexTable)
820 SectionIndexTable->reserve(Symbols.size());
822 // Add all of our strings to SymbolNames so that SymbolNames has the right
823 // size before layout is decided.
824 // If the symbol names section has been removed, don't try to add strings to
825 // the table.
826 if (SymbolNames != nullptr)
827 for (std::unique_ptr<Symbol> &Sym : Symbols)
828 SymbolNames->addString(Sym->Name);
831 void SymbolTableSection::fillShndxTable() {
832 if (SectionIndexTable == nullptr)
833 return;
834 // Fill section index table with real section indexes. This function must
835 // be called after assignOffsets.
836 for (const std::unique_ptr<Symbol> &Sym : Symbols) {
837 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
838 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
839 else
840 SectionIndexTable->addIndex(SHN_UNDEF);
844 Expected<const Symbol *>
845 SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
846 if (Symbols.size() <= Index)
847 return createStringError(errc::invalid_argument,
848 "invalid symbol index: " + Twine(Index));
849 return Symbols[Index].get();
852 Expected<Symbol *> SymbolTableSection::getSymbolByIndex(uint32_t Index) {
853 Expected<const Symbol *> Sym =
854 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index);
855 if (!Sym)
856 return Sym.takeError();
858 return const_cast<Symbol *>(*Sym);
861 template <class ELFT>
862 Error ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
863 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
864 // Loop though symbols setting each entry of the symbol table.
865 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
866 Sym->st_name = Symbol->NameIndex;
867 Sym->st_value = Symbol->Value;
868 Sym->st_size = Symbol->Size;
869 Sym->st_other = Symbol->Visibility;
870 Sym->setBinding(Symbol->Binding);
871 Sym->setType(Symbol->Type);
872 Sym->st_shndx = Symbol->getShndx();
873 ++Sym;
875 return Error::success();
878 Error SymbolTableSection::accept(SectionVisitor &Visitor) const {
879 return Visitor.visit(*this);
882 Error SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
883 return Visitor.visit(*this);
886 StringRef RelocationSectionBase::getNamePrefix() const {
887 switch (Type) {
888 case SHT_REL:
889 return ".rel";
890 case SHT_RELA:
891 return ".rela";
892 case SHT_CREL:
893 return ".crel";
894 default:
895 llvm_unreachable("not a relocation section");
899 Error RelocationSection::removeSectionReferences(
900 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
901 if (ToRemove(Symbols)) {
902 if (!AllowBrokenLinks)
903 return createStringError(
904 llvm::errc::invalid_argument,
905 "symbol table '%s' cannot be removed because it is "
906 "referenced by the relocation section '%s'",
907 Symbols->Name.data(), this->Name.data());
908 Symbols = nullptr;
911 for (const Relocation &R : Relocations) {
912 if (!R.RelocSymbol || !R.RelocSymbol->DefinedIn ||
913 !ToRemove(R.RelocSymbol->DefinedIn))
914 continue;
915 return createStringError(llvm::errc::invalid_argument,
916 "section '%s' cannot be removed: (%s+0x%" PRIx64
917 ") has relocation against symbol '%s'",
918 R.RelocSymbol->DefinedIn->Name.data(),
919 SecToApplyRel->Name.data(), R.Offset,
920 R.RelocSymbol->Name.c_str());
923 return Error::success();
926 template <class SymTabType>
927 Error RelocSectionWithSymtabBase<SymTabType>::initialize(
928 SectionTableRef SecTable) {
929 if (Link != SHN_UNDEF) {
930 Expected<SymTabType *> Sec = SecTable.getSectionOfType<SymTabType>(
931 Link,
932 "Link field value " + Twine(Link) + " in section " + Name +
933 " is invalid",
934 "Link field value " + Twine(Link) + " in section " + Name +
935 " is not a symbol table");
936 if (!Sec)
937 return Sec.takeError();
939 setSymTab(*Sec);
942 if (Info != SHN_UNDEF) {
943 Expected<SectionBase *> Sec =
944 SecTable.getSection(Info, "Info field value " + Twine(Info) +
945 " in section " + Name + " is invalid");
946 if (!Sec)
947 return Sec.takeError();
949 setSection(*Sec);
950 } else
951 setSection(nullptr);
953 return Error::success();
956 template <class SymTabType>
957 void RelocSectionWithSymtabBase<SymTabType>::finalize() {
958 this->Link = Symbols ? Symbols->Index : 0;
960 if (SecToApplyRel != nullptr)
961 this->Info = SecToApplyRel->Index;
964 template <class ELFT>
965 static void setAddend(Elf_Rel_Impl<ELFT, false> &, uint64_t) {}
967 template <class ELFT>
968 static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
969 Rela.r_addend = Addend;
972 template <class RelRange, class T>
973 static void writeRel(const RelRange &Relocations, T *Buf, bool IsMips64EL) {
974 for (const auto &Reloc : Relocations) {
975 Buf->r_offset = Reloc.Offset;
976 setAddend(*Buf, Reloc.Addend);
977 Buf->setSymbolAndType(Reloc.RelocSymbol ? Reloc.RelocSymbol->Index : 0,
978 Reloc.Type, IsMips64EL);
979 ++Buf;
983 template <class ELFT>
984 Error ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
985 uint8_t *Buf = reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
986 if (Sec.Type == SHT_CREL) {
987 auto Content = encodeCrel<ELFT::Is64Bits>(Sec.Relocations);
988 memcpy(Buf, Content.data(), Content.size());
989 } else if (Sec.Type == SHT_REL) {
990 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf),
991 Sec.getObject().IsMips64EL);
992 } else {
993 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf),
994 Sec.getObject().IsMips64EL);
996 return Error::success();
999 Error RelocationSection::accept(SectionVisitor &Visitor) const {
1000 return Visitor.visit(*this);
1003 Error RelocationSection::accept(MutableSectionVisitor &Visitor) {
1004 return Visitor.visit(*this);
1007 Error RelocationSection::removeSymbols(
1008 function_ref<bool(const Symbol &)> ToRemove) {
1009 for (const Relocation &Reloc : Relocations)
1010 if (Reloc.RelocSymbol && ToRemove(*Reloc.RelocSymbol))
1011 return createStringError(
1012 llvm::errc::invalid_argument,
1013 "not stripping symbol '%s' because it is named in a relocation",
1014 Reloc.RelocSymbol->Name.data());
1015 return Error::success();
1018 void RelocationSection::markSymbols() {
1019 for (const Relocation &Reloc : Relocations)
1020 if (Reloc.RelocSymbol)
1021 Reloc.RelocSymbol->Referenced = true;
1024 void RelocationSection::replaceSectionReferences(
1025 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
1026 // Update the target section if it was replaced.
1027 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
1028 SecToApplyRel = To;
1031 Error SectionWriter::visit(const DynamicRelocationSection &Sec) {
1032 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
1033 return Error::success();
1036 Error DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
1037 return Visitor.visit(*this);
1040 Error DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
1041 return Visitor.visit(*this);
1044 Error DynamicRelocationSection::removeSectionReferences(
1045 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1046 if (ToRemove(Symbols)) {
1047 if (!AllowBrokenLinks)
1048 return createStringError(
1049 llvm::errc::invalid_argument,
1050 "symbol table '%s' cannot be removed because it is "
1051 "referenced by the relocation section '%s'",
1052 Symbols->Name.data(), this->Name.data());
1053 Symbols = nullptr;
1056 // SecToApplyRel contains a section referenced by sh_info field. It keeps
1057 // a section to which the relocation section applies. When we remove any
1058 // sections we also remove their relocation sections. Since we do that much
1059 // earlier, this assert should never be triggered.
1060 assert(!SecToApplyRel || !ToRemove(SecToApplyRel));
1061 return Error::success();
1064 Error Section::removeSectionReferences(
1065 bool AllowBrokenDependency,
1066 function_ref<bool(const SectionBase *)> ToRemove) {
1067 if (ToRemove(LinkSection)) {
1068 if (!AllowBrokenDependency)
1069 return createStringError(llvm::errc::invalid_argument,
1070 "section '%s' cannot be removed because it is "
1071 "referenced by the section '%s'",
1072 LinkSection->Name.data(), this->Name.data());
1073 LinkSection = nullptr;
1075 return Error::success();
1078 void GroupSection::finalize() {
1079 this->Info = Sym ? Sym->Index : 0;
1080 this->Link = SymTab ? SymTab->Index : 0;
1081 // Linker deduplication for GRP_COMDAT is based on Sym->Name. The local/global
1082 // status is not part of the equation. If Sym is localized, the intention is
1083 // likely to make the group fully localized. Drop GRP_COMDAT to suppress
1084 // deduplication. See https://groups.google.com/g/generic-abi/c/2X6mR-s2zoc
1085 if ((FlagWord & GRP_COMDAT) && Sym && Sym->Binding == STB_LOCAL)
1086 this->FlagWord &= ~GRP_COMDAT;
1089 Error GroupSection::removeSectionReferences(
1090 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
1091 if (ToRemove(SymTab)) {
1092 if (!AllowBrokenLinks)
1093 return createStringError(
1094 llvm::errc::invalid_argument,
1095 "section '.symtab' cannot be removed because it is "
1096 "referenced by the group section '%s'",
1097 this->Name.data());
1098 SymTab = nullptr;
1099 Sym = nullptr;
1101 llvm::erase_if(GroupMembers, ToRemove);
1102 return Error::success();
1105 Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1106 if (ToRemove(*Sym))
1107 return createStringError(llvm::errc::invalid_argument,
1108 "symbol '%s' cannot be removed because it is "
1109 "referenced by the section '%s[%d]'",
1110 Sym->Name.data(), this->Name.data(), this->Index);
1111 return Error::success();
1114 void GroupSection::markSymbols() {
1115 if (Sym)
1116 Sym->Referenced = true;
1119 void GroupSection::replaceSectionReferences(
1120 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
1121 for (SectionBase *&Sec : GroupMembers)
1122 if (SectionBase *To = FromTo.lookup(Sec))
1123 Sec = To;
1126 void GroupSection::onRemove() {
1127 // As the header section of the group is removed, drop the Group flag in its
1128 // former members.
1129 for (SectionBase *Sec : GroupMembers)
1130 Sec->Flags &= ~SHF_GROUP;
1133 Error Section::initialize(SectionTableRef SecTable) {
1134 if (Link == ELF::SHN_UNDEF)
1135 return Error::success();
1137 Expected<SectionBase *> Sec =
1138 SecTable.getSection(Link, "Link field value " + Twine(Link) +
1139 " in section " + Name + " is invalid");
1140 if (!Sec)
1141 return Sec.takeError();
1143 LinkSection = *Sec;
1145 if (LinkSection->Type == ELF::SHT_SYMTAB) {
1146 HasSymTabLink = true;
1147 LinkSection = nullptr;
1150 return Error::success();
1153 void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
1155 void GnuDebugLinkSection::init(StringRef File) {
1156 FileName = sys::path::filename(File);
1157 // The format for the .gnu_debuglink starts with the file name and is
1158 // followed by a null terminator and then the CRC32 of the file. The CRC32
1159 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
1160 // byte, and then finally push the size to alignment and add 4.
1161 Size = alignTo(FileName.size() + 1, 4) + 4;
1162 // The CRC32 will only be aligned if we align the whole section.
1163 Align = 4;
1164 Type = OriginalType = ELF::SHT_PROGBITS;
1165 Name = ".gnu_debuglink";
1166 // For sections not found in segments, OriginalOffset is only used to
1167 // establish the order that sections should go in. By using the maximum
1168 // possible offset we cause this section to wind up at the end.
1169 OriginalOffset = std::numeric_limits<uint64_t>::max();
1172 GnuDebugLinkSection::GnuDebugLinkSection(StringRef File,
1173 uint32_t PrecomputedCRC)
1174 : FileName(File), CRC32(PrecomputedCRC) {
1175 init(File);
1178 template <class ELFT>
1179 Error ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
1180 unsigned char *Buf =
1181 reinterpret_cast<uint8_t *>(Out.getBufferStart()) + Sec.Offset;
1182 Elf_Word *CRC =
1183 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
1184 *CRC = Sec.CRC32;
1185 llvm::copy(Sec.FileName, Buf);
1186 return Error::success();
1189 Error GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
1190 return Visitor.visit(*this);
1193 Error GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
1194 return Visitor.visit(*this);
1197 template <class ELFT>
1198 Error ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
1199 ELF::Elf32_Word *Buf =
1200 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
1201 endian::write32<ELFT::Endianness>(Buf++, Sec.FlagWord);
1202 for (SectionBase *S : Sec.GroupMembers)
1203 endian::write32<ELFT::Endianness>(Buf++, S->Index);
1204 return Error::success();
1207 Error GroupSection::accept(SectionVisitor &Visitor) const {
1208 return Visitor.visit(*this);
1211 Error GroupSection::accept(MutableSectionVisitor &Visitor) {
1212 return Visitor.visit(*this);
1215 // Returns true IFF a section is wholly inside the range of a segment
1216 static bool sectionWithinSegment(const SectionBase &Sec, const Segment &Seg) {
1217 // If a section is empty it should be treated like it has a size of 1. This is
1218 // to clarify the case when an empty section lies on a boundary between two
1219 // segments and ensures that the section "belongs" to the second segment and
1220 // not the first.
1221 uint64_t SecSize = Sec.Size ? Sec.Size : 1;
1223 // Ignore just added sections.
1224 if (Sec.OriginalOffset == std::numeric_limits<uint64_t>::max())
1225 return false;
1227 if (Sec.Type == SHT_NOBITS) {
1228 if (!(Sec.Flags & SHF_ALLOC))
1229 return false;
1231 bool SectionIsTLS = Sec.Flags & SHF_TLS;
1232 bool SegmentIsTLS = Seg.Type == PT_TLS;
1233 if (SectionIsTLS != SegmentIsTLS)
1234 return false;
1236 return Seg.VAddr <= Sec.Addr &&
1237 Seg.VAddr + Seg.MemSize >= Sec.Addr + SecSize;
1240 return Seg.Offset <= Sec.OriginalOffset &&
1241 Seg.Offset + Seg.FileSize >= Sec.OriginalOffset + SecSize;
1244 // Returns true IFF a segment's original offset is inside of another segment's
1245 // range.
1246 static bool segmentOverlapsSegment(const Segment &Child,
1247 const Segment &Parent) {
1249 return Parent.OriginalOffset <= Child.OriginalOffset &&
1250 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
1253 static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
1254 // Any segment without a parent segment should come before a segment
1255 // that has a parent segment.
1256 if (A->OriginalOffset < B->OriginalOffset)
1257 return true;
1258 if (A->OriginalOffset > B->OriginalOffset)
1259 return false;
1260 // If alignments are different, the one with a smaller alignment cannot be the
1261 // parent; otherwise, layoutSegments will not respect the larger alignment
1262 // requirement. This rule ensures that PT_LOAD/PT_INTERP/PT_GNU_RELRO/PT_TLS
1263 // segments at the same offset will be aligned correctly.
1264 if (A->Align != B->Align)
1265 return A->Align > B->Align;
1266 return A->Index < B->Index;
1269 void BasicELFBuilder::initFileHeader() {
1270 Obj->Flags = 0x0;
1271 Obj->Type = ET_REL;
1272 Obj->OSABI = ELFOSABI_NONE;
1273 Obj->ABIVersion = 0;
1274 Obj->Entry = 0x0;
1275 Obj->Machine = EM_NONE;
1276 Obj->Version = 1;
1279 void BasicELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
1281 StringTableSection *BasicELFBuilder::addStrTab() {
1282 auto &StrTab = Obj->addSection<StringTableSection>();
1283 StrTab.Name = ".strtab";
1285 Obj->SectionNames = &StrTab;
1286 return &StrTab;
1289 SymbolTableSection *BasicELFBuilder::addSymTab(StringTableSection *StrTab) {
1290 auto &SymTab = Obj->addSection<SymbolTableSection>();
1292 SymTab.Name = ".symtab";
1293 SymTab.Link = StrTab->Index;
1295 // The symbol table always needs a null symbol
1296 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
1298 Obj->SymbolTable = &SymTab;
1299 return &SymTab;
1302 Error BasicELFBuilder::initSections() {
1303 for (SectionBase &Sec : Obj->sections())
1304 if (Error Err = Sec.initialize(Obj->sections()))
1305 return Err;
1307 return Error::success();
1310 void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
1311 auto Data = ArrayRef<uint8_t>(
1312 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
1313 MemBuf->getBufferSize());
1314 auto &DataSection = Obj->addSection<Section>(Data);
1315 DataSection.Name = ".data";
1316 DataSection.Type = ELF::SHT_PROGBITS;
1317 DataSection.Size = Data.size();
1318 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1320 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
1321 std::replace_if(
1322 std::begin(SanitizedFilename), std::end(SanitizedFilename),
1323 [](char C) { return !isAlnum(C); }, '_');
1324 Twine Prefix = Twine("_binary_") + SanitizedFilename;
1326 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
1327 /*Value=*/0, NewSymbolVisibility, 0, 0);
1328 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
1329 /*Value=*/DataSection.Size, NewSymbolVisibility, 0, 0);
1330 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
1331 /*Value=*/DataSection.Size, NewSymbolVisibility, SHN_ABS,
1335 Expected<std::unique_ptr<Object>> BinaryELFBuilder::build() {
1336 initFileHeader();
1337 initHeaderSegment();
1339 SymbolTableSection *SymTab = addSymTab(addStrTab());
1340 if (Error Err = initSections())
1341 return std::move(Err);
1342 addData(SymTab);
1344 return std::move(Obj);
1347 // Adds sections from IHEX data file. Data should have been
1348 // fully validated by this time.
1349 void IHexELFBuilder::addDataSections() {
1350 OwnedDataSection *Section = nullptr;
1351 uint64_t SegmentAddr = 0, BaseAddr = 0;
1352 uint32_t SecNo = 1;
1354 for (const IHexRecord &R : Records) {
1355 uint64_t RecAddr;
1356 switch (R.Type) {
1357 case IHexRecord::Data:
1358 // Ignore empty data records
1359 if (R.HexData.empty())
1360 continue;
1361 RecAddr = R.Addr + SegmentAddr + BaseAddr;
1362 if (!Section || Section->Addr + Section->Size != RecAddr) {
1363 // OriginalOffset field is only used to sort sections before layout, so
1364 // instead of keeping track of real offsets in IHEX file, and as
1365 // layoutSections() and layoutSectionsForOnlyKeepDebug() use
1366 // llvm::stable_sort(), we can just set it to a constant (zero).
1367 Section = &Obj->addSection<OwnedDataSection>(
1368 ".sec" + std::to_string(SecNo), RecAddr,
1369 ELF::SHF_ALLOC | ELF::SHF_WRITE, 0);
1370 SecNo++;
1372 Section->appendHexData(R.HexData);
1373 break;
1374 case IHexRecord::EndOfFile:
1375 break;
1376 case IHexRecord::SegmentAddr:
1377 // 20-bit segment address.
1378 SegmentAddr = checkedGetHex<uint16_t>(R.HexData) << 4;
1379 break;
1380 case IHexRecord::StartAddr80x86:
1381 case IHexRecord::StartAddr:
1382 Obj->Entry = checkedGetHex<uint32_t>(R.HexData);
1383 assert(Obj->Entry <= 0xFFFFFU);
1384 break;
1385 case IHexRecord::ExtendedAddr:
1386 // 16-31 bits of linear base address
1387 BaseAddr = checkedGetHex<uint16_t>(R.HexData) << 16;
1388 break;
1389 default:
1390 llvm_unreachable("unknown record type");
1395 Expected<std::unique_ptr<Object>> IHexELFBuilder::build() {
1396 initFileHeader();
1397 initHeaderSegment();
1398 StringTableSection *StrTab = addStrTab();
1399 addSymTab(StrTab);
1400 if (Error Err = initSections())
1401 return std::move(Err);
1402 addDataSections();
1404 return std::move(Obj);
1407 template <class ELFT>
1408 ELFBuilder<ELFT>::ELFBuilder(const ELFObjectFile<ELFT> &ElfObj, Object &Obj,
1409 std::optional<StringRef> ExtractPartition)
1410 : ElfFile(ElfObj.getELFFile()), Obj(Obj),
1411 ExtractPartition(ExtractPartition) {
1412 Obj.IsMips64EL = ElfFile.isMips64EL();
1415 template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
1416 for (Segment &Parent : Obj.segments()) {
1417 // Every segment will overlap with itself but we don't want a segment to
1418 // be its own parent so we avoid that situation.
1419 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
1420 // We want a canonical "most parental" segment but this requires
1421 // inspecting the ParentSegment.
1422 if (compareSegmentsByOffset(&Parent, &Child))
1423 if (Child.ParentSegment == nullptr ||
1424 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
1425 Child.ParentSegment = &Parent;
1431 template <class ELFT> Error ELFBuilder<ELFT>::findEhdrOffset() {
1432 if (!ExtractPartition)
1433 return Error::success();
1435 for (const SectionBase &Sec : Obj.sections()) {
1436 if (Sec.Type == SHT_LLVM_PART_EHDR && Sec.Name == *ExtractPartition) {
1437 EhdrOffset = Sec.Offset;
1438 return Error::success();
1441 return createStringError(errc::invalid_argument,
1442 "could not find partition named '" +
1443 *ExtractPartition + "'");
1446 template <class ELFT>
1447 Error ELFBuilder<ELFT>::readProgramHeaders(const ELFFile<ELFT> &HeadersFile) {
1448 uint32_t Index = 0;
1450 Expected<typename ELFFile<ELFT>::Elf_Phdr_Range> Headers =
1451 HeadersFile.program_headers();
1452 if (!Headers)
1453 return Headers.takeError();
1455 for (const typename ELFFile<ELFT>::Elf_Phdr &Phdr : *Headers) {
1456 if (Phdr.p_offset + Phdr.p_filesz > HeadersFile.getBufSize())
1457 return createStringError(
1458 errc::invalid_argument,
1459 "program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
1460 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
1461 " goes past the end of the file");
1463 ArrayRef<uint8_t> Data{HeadersFile.base() + Phdr.p_offset,
1464 (size_t)Phdr.p_filesz};
1465 Segment &Seg = Obj.addSegment(Data);
1466 Seg.Type = Phdr.p_type;
1467 Seg.Flags = Phdr.p_flags;
1468 Seg.OriginalOffset = Phdr.p_offset + EhdrOffset;
1469 Seg.Offset = Phdr.p_offset + EhdrOffset;
1470 Seg.VAddr = Phdr.p_vaddr;
1471 Seg.PAddr = Phdr.p_paddr;
1472 Seg.FileSize = Phdr.p_filesz;
1473 Seg.MemSize = Phdr.p_memsz;
1474 Seg.Align = Phdr.p_align;
1475 Seg.Index = Index++;
1476 for (SectionBase &Sec : Obj.sections())
1477 if (sectionWithinSegment(Sec, Seg)) {
1478 Seg.addSection(&Sec);
1479 if (!Sec.ParentSegment || Sec.ParentSegment->Offset > Seg.Offset)
1480 Sec.ParentSegment = &Seg;
1484 auto &ElfHdr = Obj.ElfHdrSegment;
1485 ElfHdr.Index = Index++;
1486 ElfHdr.OriginalOffset = ElfHdr.Offset = EhdrOffset;
1488 const typename ELFT::Ehdr &Ehdr = HeadersFile.getHeader();
1489 auto &PrHdr = Obj.ProgramHdrSegment;
1490 PrHdr.Type = PT_PHDR;
1491 PrHdr.Flags = 0;
1492 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
1493 // Whereas this works automatically for ElfHdr, here OriginalOffset is
1494 // always non-zero and to ensure the equation we assign the same value to
1495 // VAddr as well.
1496 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = EhdrOffset + Ehdr.e_phoff;
1497 PrHdr.PAddr = 0;
1498 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
1499 // The spec requires us to naturally align all the fields.
1500 PrHdr.Align = sizeof(Elf_Addr);
1501 PrHdr.Index = Index++;
1503 // Now we do an O(n^2) loop through the segments in order to match up
1504 // segments.
1505 for (Segment &Child : Obj.segments())
1506 setParentSegment(Child);
1507 setParentSegment(ElfHdr);
1508 setParentSegment(PrHdr);
1510 return Error::success();
1513 template <class ELFT>
1514 Error ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
1515 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
1516 return createStringError(errc::invalid_argument,
1517 "invalid alignment " + Twine(GroupSec->Align) +
1518 " of group section '" + GroupSec->Name + "'");
1519 SectionTableRef SecTable = Obj.sections();
1520 if (GroupSec->Link != SHN_UNDEF) {
1521 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1522 GroupSec->Link,
1523 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1524 GroupSec->Name + "' is invalid",
1525 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1526 GroupSec->Name + "' is not a symbol table");
1527 if (!SymTab)
1528 return SymTab.takeError();
1530 Expected<Symbol *> Sym = (*SymTab)->getSymbolByIndex(GroupSec->Info);
1531 if (!Sym)
1532 return createStringError(errc::invalid_argument,
1533 "info field value '" + Twine(GroupSec->Info) +
1534 "' in section '" + GroupSec->Name +
1535 "' is not a valid symbol index");
1536 GroupSec->setSymTab(*SymTab);
1537 GroupSec->setSymbol(*Sym);
1539 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1540 GroupSec->Contents.empty())
1541 return createStringError(errc::invalid_argument,
1542 "the content of the section " + GroupSec->Name +
1543 " is malformed");
1544 const ELF::Elf32_Word *Word =
1545 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1546 const ELF::Elf32_Word *End =
1547 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1548 GroupSec->setFlagWord(endian::read32<ELFT::Endianness>(Word++));
1549 for (; Word != End; ++Word) {
1550 uint32_t Index = support::endian::read32<ELFT::Endianness>(Word);
1551 Expected<SectionBase *> Sec = SecTable.getSection(
1552 Index, "group member index " + Twine(Index) + " in section '" +
1553 GroupSec->Name + "' is invalid");
1554 if (!Sec)
1555 return Sec.takeError();
1557 GroupSec->addMember(*Sec);
1560 return Error::success();
1563 template <class ELFT>
1564 Error ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
1565 Expected<const Elf_Shdr *> Shdr = ElfFile.getSection(SymTab->Index);
1566 if (!Shdr)
1567 return Shdr.takeError();
1569 Expected<StringRef> StrTabData = ElfFile.getStringTableForSymtab(**Shdr);
1570 if (!StrTabData)
1571 return StrTabData.takeError();
1573 ArrayRef<Elf_Word> ShndxData;
1575 Expected<typename ELFFile<ELFT>::Elf_Sym_Range> Symbols =
1576 ElfFile.symbols(*Shdr);
1577 if (!Symbols)
1578 return Symbols.takeError();
1580 for (const typename ELFFile<ELFT>::Elf_Sym &Sym : *Symbols) {
1581 SectionBase *DefSection = nullptr;
1583 Expected<StringRef> Name = Sym.getName(*StrTabData);
1584 if (!Name)
1585 return Name.takeError();
1587 if (Sym.st_shndx == SHN_XINDEX) {
1588 if (SymTab->getShndxTable() == nullptr)
1589 return createStringError(errc::invalid_argument,
1590 "symbol '" + *Name +
1591 "' has index SHN_XINDEX but no "
1592 "SHT_SYMTAB_SHNDX section exists");
1593 if (ShndxData.data() == nullptr) {
1594 Expected<const Elf_Shdr *> ShndxSec =
1595 ElfFile.getSection(SymTab->getShndxTable()->Index);
1596 if (!ShndxSec)
1597 return ShndxSec.takeError();
1599 Expected<ArrayRef<Elf_Word>> Data =
1600 ElfFile.template getSectionContentsAsArray<Elf_Word>(**ShndxSec);
1601 if (!Data)
1602 return Data.takeError();
1604 ShndxData = *Data;
1605 if (ShndxData.size() != Symbols->size())
1606 return createStringError(
1607 errc::invalid_argument,
1608 "symbol section index table does not have the same number of "
1609 "entries as the symbol table");
1611 Elf_Word Index = ShndxData[&Sym - Symbols->begin()];
1612 Expected<SectionBase *> Sec = Obj.sections().getSection(
1613 Index,
1614 "symbol '" + *Name + "' has invalid section index " + Twine(Index));
1615 if (!Sec)
1616 return Sec.takeError();
1618 DefSection = *Sec;
1619 } else if (Sym.st_shndx >= SHN_LORESERVE) {
1620 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
1621 return createStringError(
1622 errc::invalid_argument,
1623 "symbol '" + *Name +
1624 "' has unsupported value greater than or equal "
1625 "to SHN_LORESERVE: " +
1626 Twine(Sym.st_shndx));
1628 } else if (Sym.st_shndx != SHN_UNDEF) {
1629 Expected<SectionBase *> Sec = Obj.sections().getSection(
1630 Sym.st_shndx, "symbol '" + *Name +
1631 "' is defined has invalid section index " +
1632 Twine(Sym.st_shndx));
1633 if (!Sec)
1634 return Sec.takeError();
1636 DefSection = *Sec;
1639 SymTab->addSymbol(*Name, Sym.getBinding(), Sym.getType(), DefSection,
1640 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
1643 return Error::success();
1646 template <class ELFT>
1647 static void getAddend(uint64_t &, const Elf_Rel_Impl<ELFT, false> &) {}
1649 template <class ELFT>
1650 static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1651 ToSet = Rela.r_addend;
1654 template <class T>
1655 static Error initRelocations(RelocationSection *Relocs, T RelRange) {
1656 for (const auto &Rel : RelRange) {
1657 Relocation ToAdd;
1658 ToAdd.Offset = Rel.r_offset;
1659 getAddend(ToAdd.Addend, Rel);
1660 ToAdd.Type = Rel.getType(Relocs->getObject().IsMips64EL);
1662 if (uint32_t Sym = Rel.getSymbol(Relocs->getObject().IsMips64EL)) {
1663 if (!Relocs->getObject().SymbolTable)
1664 return createStringError(
1665 errc::invalid_argument,
1666 "'" + Relocs->Name + "': relocation references symbol with index " +
1667 Twine(Sym) + ", but there is no symbol table");
1668 Expected<Symbol *> SymByIndex =
1669 Relocs->getObject().SymbolTable->getSymbolByIndex(Sym);
1670 if (!SymByIndex)
1671 return SymByIndex.takeError();
1673 ToAdd.RelocSymbol = *SymByIndex;
1676 Relocs->addRelocation(ToAdd);
1679 return Error::success();
1682 Expected<SectionBase *> SectionTableRef::getSection(uint32_t Index,
1683 Twine ErrMsg) {
1684 if (Index == SHN_UNDEF || Index > Sections.size())
1685 return createStringError(errc::invalid_argument, ErrMsg);
1686 return Sections[Index - 1].get();
1689 template <class T>
1690 Expected<T *> SectionTableRef::getSectionOfType(uint32_t Index,
1691 Twine IndexErrMsg,
1692 Twine TypeErrMsg) {
1693 Expected<SectionBase *> BaseSec = getSection(Index, IndexErrMsg);
1694 if (!BaseSec)
1695 return BaseSec.takeError();
1697 if (T *Sec = dyn_cast<T>(*BaseSec))
1698 return Sec;
1700 return createStringError(errc::invalid_argument, TypeErrMsg);
1703 template <class ELFT>
1704 Expected<SectionBase &> ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
1705 switch (Shdr.sh_type) {
1706 case SHT_REL:
1707 case SHT_RELA:
1708 case SHT_CREL:
1709 if (Shdr.sh_flags & SHF_ALLOC) {
1710 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1711 return Obj.addSection<DynamicRelocationSection>(*Data);
1712 else
1713 return Data.takeError();
1715 return Obj.addSection<RelocationSection>(Obj);
1716 case SHT_STRTAB:
1717 // If a string table is allocated we don't want to mess with it. That would
1718 // mean altering the memory image. There are no special link types or
1719 // anything so we can just use a Section.
1720 if (Shdr.sh_flags & SHF_ALLOC) {
1721 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1722 return Obj.addSection<Section>(*Data);
1723 else
1724 return Data.takeError();
1726 return Obj.addSection<StringTableSection>();
1727 case SHT_HASH:
1728 case SHT_GNU_HASH:
1729 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1730 // Because of this we don't need to mess with the hash tables either.
1731 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1732 return Obj.addSection<Section>(*Data);
1733 else
1734 return Data.takeError();
1735 case SHT_GROUP:
1736 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1737 return Obj.addSection<GroupSection>(*Data);
1738 else
1739 return Data.takeError();
1740 case SHT_DYNSYM:
1741 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1742 return Obj.addSection<DynamicSymbolTableSection>(*Data);
1743 else
1744 return Data.takeError();
1745 case SHT_DYNAMIC:
1746 if (Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr))
1747 return Obj.addSection<DynamicSection>(*Data);
1748 else
1749 return Data.takeError();
1750 case SHT_SYMTAB: {
1751 // Multiple SHT_SYMTAB sections are forbidden by the ELF gABI.
1752 if (Obj.SymbolTable != nullptr)
1753 return createStringError(llvm::errc::invalid_argument,
1754 "found multiple SHT_SYMTAB sections");
1755 auto &SymTab = Obj.addSection<SymbolTableSection>();
1756 Obj.SymbolTable = &SymTab;
1757 return SymTab;
1759 case SHT_SYMTAB_SHNDX: {
1760 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1761 Obj.SectionIndexTable = &ShndxSection;
1762 return ShndxSection;
1764 case SHT_NOBITS:
1765 return Obj.addSection<Section>(ArrayRef<uint8_t>());
1766 default: {
1767 Expected<ArrayRef<uint8_t>> Data = ElfFile.getSectionContents(Shdr);
1768 if (!Data)
1769 return Data.takeError();
1771 Expected<StringRef> Name = ElfFile.getSectionName(Shdr);
1772 if (!Name)
1773 return Name.takeError();
1775 if (!(Shdr.sh_flags & ELF::SHF_COMPRESSED))
1776 return Obj.addSection<Section>(*Data);
1777 auto *Chdr = reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data->data());
1778 return Obj.addSection<CompressedSection>(CompressedSection(
1779 *Data, Chdr->ch_type, Chdr->ch_size, Chdr->ch_addralign));
1784 template <class ELFT> Error ELFBuilder<ELFT>::readSectionHeaders() {
1785 uint32_t Index = 0;
1786 Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections =
1787 ElfFile.sections();
1788 if (!Sections)
1789 return Sections.takeError();
1791 for (const typename ELFFile<ELFT>::Elf_Shdr &Shdr : *Sections) {
1792 if (Index == 0) {
1793 ++Index;
1794 continue;
1796 Expected<SectionBase &> Sec = makeSection(Shdr);
1797 if (!Sec)
1798 return Sec.takeError();
1800 Expected<StringRef> SecName = ElfFile.getSectionName(Shdr);
1801 if (!SecName)
1802 return SecName.takeError();
1803 Sec->Name = SecName->str();
1804 Sec->Type = Sec->OriginalType = Shdr.sh_type;
1805 Sec->Flags = Sec->OriginalFlags = Shdr.sh_flags;
1806 Sec->Addr = Shdr.sh_addr;
1807 Sec->Offset = Shdr.sh_offset;
1808 Sec->OriginalOffset = Shdr.sh_offset;
1809 Sec->Size = Shdr.sh_size;
1810 Sec->Link = Shdr.sh_link;
1811 Sec->Info = Shdr.sh_info;
1812 Sec->Align = Shdr.sh_addralign;
1813 Sec->EntrySize = Shdr.sh_entsize;
1814 Sec->Index = Index++;
1815 Sec->OriginalIndex = Sec->Index;
1816 Sec->OriginalData = ArrayRef<uint8_t>(
1817 ElfFile.base() + Shdr.sh_offset,
1818 (Shdr.sh_type == SHT_NOBITS) ? (size_t)0 : Shdr.sh_size);
1821 return Error::success();
1824 template <class ELFT> Error ELFBuilder<ELFT>::readSections(bool EnsureSymtab) {
1825 uint32_t ShstrIndex = ElfFile.getHeader().e_shstrndx;
1826 if (ShstrIndex == SHN_XINDEX) {
1827 Expected<const Elf_Shdr *> Sec = ElfFile.getSection(0);
1828 if (!Sec)
1829 return Sec.takeError();
1831 ShstrIndex = (*Sec)->sh_link;
1834 if (ShstrIndex == SHN_UNDEF)
1835 Obj.HadShdrs = false;
1836 else {
1837 Expected<StringTableSection *> Sec =
1838 Obj.sections().template getSectionOfType<StringTableSection>(
1839 ShstrIndex,
1840 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1841 " is invalid",
1842 "e_shstrndx field value " + Twine(ShstrIndex) + " in elf header " +
1843 " does not reference a string table");
1844 if (!Sec)
1845 return Sec.takeError();
1847 Obj.SectionNames = *Sec;
1850 // If a section index table exists we'll need to initialize it before we
1851 // initialize the symbol table because the symbol table might need to
1852 // reference it.
1853 if (Obj.SectionIndexTable)
1854 if (Error Err = Obj.SectionIndexTable->initialize(Obj.sections()))
1855 return Err;
1857 // Now that all of the sections have been added we can fill out some extra
1858 // details about symbol tables. We need the symbol table filled out before
1859 // any relocations.
1860 if (Obj.SymbolTable) {
1861 if (Error Err = Obj.SymbolTable->initialize(Obj.sections()))
1862 return Err;
1863 if (Error Err = initSymbolTable(Obj.SymbolTable))
1864 return Err;
1865 } else if (EnsureSymtab) {
1866 if (Error Err = Obj.addNewSymbolTable())
1867 return Err;
1870 // Now that all sections and symbols have been added we can add
1871 // relocations that reference symbols and set the link and info fields for
1872 // relocation sections.
1873 for (SectionBase &Sec : Obj.sections()) {
1874 if (&Sec == Obj.SymbolTable)
1875 continue;
1876 if (Error Err = Sec.initialize(Obj.sections()))
1877 return Err;
1878 if (auto RelSec = dyn_cast<RelocationSection>(&Sec)) {
1879 Expected<typename ELFFile<ELFT>::Elf_Shdr_Range> Sections =
1880 ElfFile.sections();
1881 if (!Sections)
1882 return Sections.takeError();
1884 const typename ELFFile<ELFT>::Elf_Shdr *Shdr =
1885 Sections->begin() + RelSec->Index;
1886 if (RelSec->Type == SHT_CREL) {
1887 auto RelsOrRelas = ElfFile.crels(*Shdr);
1888 if (!RelsOrRelas)
1889 return RelsOrRelas.takeError();
1890 if (Error Err = initRelocations(RelSec, RelsOrRelas->first))
1891 return Err;
1892 if (Error Err = initRelocations(RelSec, RelsOrRelas->second))
1893 return Err;
1894 } else if (RelSec->Type == SHT_REL) {
1895 Expected<typename ELFFile<ELFT>::Elf_Rel_Range> Rels =
1896 ElfFile.rels(*Shdr);
1897 if (!Rels)
1898 return Rels.takeError();
1900 if (Error Err = initRelocations(RelSec, *Rels))
1901 return Err;
1902 } else {
1903 Expected<typename ELFFile<ELFT>::Elf_Rela_Range> Relas =
1904 ElfFile.relas(*Shdr);
1905 if (!Relas)
1906 return Relas.takeError();
1908 if (Error Err = initRelocations(RelSec, *Relas))
1909 return Err;
1911 } else if (auto GroupSec = dyn_cast<GroupSection>(&Sec)) {
1912 if (Error Err = initGroupSection(GroupSec))
1913 return Err;
1917 return Error::success();
1920 template <class ELFT> Error ELFBuilder<ELFT>::build(bool EnsureSymtab) {
1921 if (Error E = readSectionHeaders())
1922 return E;
1923 if (Error E = findEhdrOffset())
1924 return E;
1926 // The ELFFile whose ELF headers and program headers are copied into the
1927 // output file. Normally the same as ElfFile, but if we're extracting a
1928 // loadable partition it will point to the partition's headers.
1929 Expected<ELFFile<ELFT>> HeadersFile = ELFFile<ELFT>::create(toStringRef(
1930 {ElfFile.base() + EhdrOffset, ElfFile.getBufSize() - EhdrOffset}));
1931 if (!HeadersFile)
1932 return HeadersFile.takeError();
1934 const typename ELFFile<ELFT>::Elf_Ehdr &Ehdr = HeadersFile->getHeader();
1935 Obj.Is64Bits = Ehdr.e_ident[EI_CLASS] == ELFCLASS64;
1936 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1937 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
1938 Obj.Type = Ehdr.e_type;
1939 Obj.Machine = Ehdr.e_machine;
1940 Obj.Version = Ehdr.e_version;
1941 Obj.Entry = Ehdr.e_entry;
1942 Obj.Flags = Ehdr.e_flags;
1944 if (Error E = readSections(EnsureSymtab))
1945 return E;
1946 return readProgramHeaders(*HeadersFile);
1949 Writer::~Writer() = default;
1951 Reader::~Reader() = default;
1953 Expected<std::unique_ptr<Object>>
1954 BinaryReader::create(bool /*EnsureSymtab*/) const {
1955 return BinaryELFBuilder(MemBuf, NewSymbolVisibility).build();
1958 Expected<std::vector<IHexRecord>> IHexReader::parse() const {
1959 SmallVector<StringRef, 16> Lines;
1960 std::vector<IHexRecord> Records;
1961 bool HasSections = false;
1963 MemBuf->getBuffer().split(Lines, '\n');
1964 Records.reserve(Lines.size());
1965 for (size_t LineNo = 1; LineNo <= Lines.size(); ++LineNo) {
1966 StringRef Line = Lines[LineNo - 1].trim();
1967 if (Line.empty())
1968 continue;
1970 Expected<IHexRecord> R = IHexRecord::parse(Line);
1971 if (!R)
1972 return parseError(LineNo, R.takeError());
1973 if (R->Type == IHexRecord::EndOfFile)
1974 break;
1975 HasSections |= (R->Type == IHexRecord::Data);
1976 Records.push_back(*R);
1978 if (!HasSections)
1979 return parseError(-1U, "no sections");
1981 return std::move(Records);
1984 Expected<std::unique_ptr<Object>>
1985 IHexReader::create(bool /*EnsureSymtab*/) const {
1986 Expected<std::vector<IHexRecord>> Records = parse();
1987 if (!Records)
1988 return Records.takeError();
1990 return IHexELFBuilder(*Records).build();
1993 Expected<std::unique_ptr<Object>> ELFReader::create(bool EnsureSymtab) const {
1994 auto Obj = std::make_unique<Object>();
1995 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1996 ELFBuilder<ELF32LE> Builder(*O, *Obj, ExtractPartition);
1997 if (Error Err = Builder.build(EnsureSymtab))
1998 return std::move(Err);
1999 return std::move(Obj);
2000 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
2001 ELFBuilder<ELF64LE> Builder(*O, *Obj, ExtractPartition);
2002 if (Error Err = Builder.build(EnsureSymtab))
2003 return std::move(Err);
2004 return std::move(Obj);
2005 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
2006 ELFBuilder<ELF32BE> Builder(*O, *Obj, ExtractPartition);
2007 if (Error Err = Builder.build(EnsureSymtab))
2008 return std::move(Err);
2009 return std::move(Obj);
2010 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
2011 ELFBuilder<ELF64BE> Builder(*O, *Obj, ExtractPartition);
2012 if (Error Err = Builder.build(EnsureSymtab))
2013 return std::move(Err);
2014 return std::move(Obj);
2016 return createStringError(errc::invalid_argument, "invalid file type");
2019 template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
2020 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf->getBufferStart());
2021 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
2022 Ehdr.e_ident[EI_MAG0] = 0x7f;
2023 Ehdr.e_ident[EI_MAG1] = 'E';
2024 Ehdr.e_ident[EI_MAG2] = 'L';
2025 Ehdr.e_ident[EI_MAG3] = 'F';
2026 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
2027 Ehdr.e_ident[EI_DATA] =
2028 ELFT::Endianness == llvm::endianness::big ? ELFDATA2MSB : ELFDATA2LSB;
2029 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
2030 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
2031 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
2033 Ehdr.e_type = Obj.Type;
2034 Ehdr.e_machine = Obj.Machine;
2035 Ehdr.e_version = Obj.Version;
2036 Ehdr.e_entry = Obj.Entry;
2037 // We have to use the fully-qualified name llvm::size
2038 // since some compilers complain on ambiguous resolution.
2039 Ehdr.e_phnum = llvm::size(Obj.segments());
2040 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
2041 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
2042 Ehdr.e_flags = Obj.Flags;
2043 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
2044 if (WriteSectionHeaders && Obj.sections().size() != 0) {
2045 Ehdr.e_shentsize = sizeof(Elf_Shdr);
2046 Ehdr.e_shoff = Obj.SHOff;
2047 // """
2048 // If the number of sections is greater than or equal to
2049 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
2050 // number of section header table entries is contained in the sh_size field
2051 // of the section header at index 0.
2052 // """
2053 auto Shnum = Obj.sections().size() + 1;
2054 if (Shnum >= SHN_LORESERVE)
2055 Ehdr.e_shnum = 0;
2056 else
2057 Ehdr.e_shnum = Shnum;
2058 // """
2059 // If the section name string table section index is greater than or equal
2060 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
2061 // and the actual index of the section name string table section is
2062 // contained in the sh_link field of the section header at index 0.
2063 // """
2064 if (Obj.SectionNames->Index >= SHN_LORESERVE)
2065 Ehdr.e_shstrndx = SHN_XINDEX;
2066 else
2067 Ehdr.e_shstrndx = Obj.SectionNames->Index;
2068 } else {
2069 Ehdr.e_shentsize = 0;
2070 Ehdr.e_shoff = 0;
2071 Ehdr.e_shnum = 0;
2072 Ehdr.e_shstrndx = 0;
2076 template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
2077 for (auto &Seg : Obj.segments())
2078 writePhdr(Seg);
2081 template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
2082 // This reference serves to write the dummy section header at the begining
2083 // of the file. It is not used for anything else
2084 Elf_Shdr &Shdr =
2085 *reinterpret_cast<Elf_Shdr *>(Buf->getBufferStart() + Obj.SHOff);
2086 Shdr.sh_name = 0;
2087 Shdr.sh_type = SHT_NULL;
2088 Shdr.sh_flags = 0;
2089 Shdr.sh_addr = 0;
2090 Shdr.sh_offset = 0;
2091 // See writeEhdr for why we do this.
2092 uint64_t Shnum = Obj.sections().size() + 1;
2093 if (Shnum >= SHN_LORESERVE)
2094 Shdr.sh_size = Shnum;
2095 else
2096 Shdr.sh_size = 0;
2097 // See writeEhdr for why we do this.
2098 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
2099 Shdr.sh_link = Obj.SectionNames->Index;
2100 else
2101 Shdr.sh_link = 0;
2102 Shdr.sh_info = 0;
2103 Shdr.sh_addralign = 0;
2104 Shdr.sh_entsize = 0;
2106 for (SectionBase &Sec : Obj.sections())
2107 writeShdr(Sec);
2110 template <class ELFT> Error ELFWriter<ELFT>::writeSectionData() {
2111 for (SectionBase &Sec : Obj.sections())
2112 // Segments are responsible for writing their contents, so only write the
2113 // section data if the section is not in a segment. Note that this renders
2114 // sections in segments effectively immutable.
2115 if (Sec.ParentSegment == nullptr)
2116 if (Error Err = Sec.accept(*SecWriter))
2117 return Err;
2119 return Error::success();
2122 template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
2123 for (Segment &Seg : Obj.segments()) {
2124 size_t Size = std::min<size_t>(Seg.FileSize, Seg.getContents().size());
2125 std::memcpy(Buf->getBufferStart() + Seg.Offset, Seg.getContents().data(),
2126 Size);
2129 for (const auto &it : Obj.getUpdatedSections()) {
2130 SectionBase *Sec = it.first;
2131 ArrayRef<uint8_t> Data = it.second;
2133 auto *Parent = Sec->ParentSegment;
2134 assert(Parent && "This section should've been part of a segment.");
2135 uint64_t Offset =
2136 Sec->OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2137 llvm::copy(Data, Buf->getBufferStart() + Offset);
2140 // Iterate over removed sections and overwrite their old data with zeroes.
2141 for (auto &Sec : Obj.removedSections()) {
2142 Segment *Parent = Sec.ParentSegment;
2143 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
2144 continue;
2145 uint64_t Offset =
2146 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
2147 std::memset(Buf->getBufferStart() + Offset, 0, Sec.Size);
2151 template <class ELFT>
2152 ELFWriter<ELFT>::ELFWriter(Object &Obj, raw_ostream &Buf, bool WSH,
2153 bool OnlyKeepDebug)
2154 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs),
2155 OnlyKeepDebug(OnlyKeepDebug) {}
2157 Error Object::updateSection(StringRef Name, ArrayRef<uint8_t> Data) {
2158 auto It = llvm::find_if(Sections,
2159 [&](const SecPtr &Sec) { return Sec->Name == Name; });
2160 if (It == Sections.end())
2161 return createStringError(errc::invalid_argument, "section '%s' not found",
2162 Name.str().c_str());
2164 auto *OldSec = It->get();
2165 if (!OldSec->hasContents())
2166 return createStringError(
2167 errc::invalid_argument,
2168 "section '%s' cannot be updated because it does not have contents",
2169 Name.str().c_str());
2171 if (Data.size() > OldSec->Size && OldSec->ParentSegment)
2172 return createStringError(errc::invalid_argument,
2173 "cannot fit data of size %zu into section '%s' "
2174 "with size %" PRIu64 " that is part of a segment",
2175 Data.size(), Name.str().c_str(), OldSec->Size);
2177 if (!OldSec->ParentSegment) {
2178 *It = std::make_unique<OwnedDataSection>(*OldSec, Data);
2179 } else {
2180 // The segment writer will be in charge of updating these contents.
2181 OldSec->Size = Data.size();
2182 UpdatedSections[OldSec] = Data;
2185 return Error::success();
2188 Error Object::removeSections(
2189 bool AllowBrokenLinks, std::function<bool(const SectionBase &)> ToRemove) {
2191 auto Iter = std::stable_partition(
2192 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
2193 if (ToRemove(*Sec))
2194 return false;
2195 // TODO: A compressed relocation section may be recognized as
2196 // RelocationSectionBase. We don't want such a section to be removed.
2197 if (isa<CompressedSection>(Sec))
2198 return true;
2199 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
2200 if (auto ToRelSec = RelSec->getSection())
2201 return !ToRemove(*ToRelSec);
2203 // Remove empty group sections.
2204 if (Sec->Type == ELF::SHT_GROUP) {
2205 auto GroupSec = cast<GroupSection>(Sec.get());
2206 return !llvm::all_of(GroupSec->members(), ToRemove);
2208 return true;
2210 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
2211 SymbolTable = nullptr;
2212 if (SectionNames != nullptr && ToRemove(*SectionNames))
2213 SectionNames = nullptr;
2214 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
2215 SectionIndexTable = nullptr;
2216 // Now make sure there are no remaining references to the sections that will
2217 // be removed. Sometimes it is impossible to remove a reference so we emit
2218 // an error here instead.
2219 std::unordered_set<const SectionBase *> RemoveSections;
2220 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
2221 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
2222 for (auto &Segment : Segments)
2223 Segment->removeSection(RemoveSec.get());
2224 RemoveSec->onRemove();
2225 RemoveSections.insert(RemoveSec.get());
2228 // For each section that remains alive, we want to remove the dead references.
2229 // This either might update the content of the section (e.g. remove symbols
2230 // from symbol table that belongs to removed section) or trigger an error if
2231 // a live section critically depends on a section being removed somehow
2232 // (e.g. the removed section is referenced by a relocation).
2233 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
2234 if (Error E = KeepSec->removeSectionReferences(
2235 AllowBrokenLinks, [&RemoveSections](const SectionBase *Sec) {
2236 return RemoveSections.find(Sec) != RemoveSections.end();
2238 return E;
2241 // Transfer removed sections into the Object RemovedSections container for use
2242 // later.
2243 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
2244 // Now finally get rid of them all together.
2245 Sections.erase(Iter, std::end(Sections));
2246 return Error::success();
2249 Error Object::replaceSections(
2250 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
2251 auto SectionIndexLess = [](const SecPtr &Lhs, const SecPtr &Rhs) {
2252 return Lhs->Index < Rhs->Index;
2254 assert(llvm::is_sorted(Sections, SectionIndexLess) &&
2255 "Sections are expected to be sorted by Index");
2256 // Set indices of new sections so that they can be later sorted into positions
2257 // of removed ones.
2258 for (auto &I : FromTo)
2259 I.second->Index = I.first->Index;
2261 // Notify all sections about the replacement.
2262 for (auto &Sec : Sections)
2263 Sec->replaceSectionReferences(FromTo);
2265 if (Error E = removeSections(
2266 /*AllowBrokenLinks=*/false,
2267 [=](const SectionBase &Sec) { return FromTo.count(&Sec) > 0; }))
2268 return E;
2269 llvm::sort(Sections, SectionIndexLess);
2270 return Error::success();
2273 Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
2274 if (SymbolTable)
2275 for (const SecPtr &Sec : Sections)
2276 if (Error E = Sec->removeSymbols(ToRemove))
2277 return E;
2278 return Error::success();
2281 Error Object::addNewSymbolTable() {
2282 assert(!SymbolTable && "Object must not has a SymbolTable.");
2284 // Reuse an existing SHT_STRTAB section if it exists.
2285 StringTableSection *StrTab = nullptr;
2286 for (SectionBase &Sec : sections()) {
2287 if (Sec.Type == ELF::SHT_STRTAB && !(Sec.Flags & SHF_ALLOC)) {
2288 StrTab = static_cast<StringTableSection *>(&Sec);
2290 // Prefer a string table that is not the section header string table, if
2291 // such a table exists.
2292 if (SectionNames != &Sec)
2293 break;
2296 if (!StrTab)
2297 StrTab = &addSection<StringTableSection>();
2299 SymbolTableSection &SymTab = addSection<SymbolTableSection>();
2300 SymTab.Name = ".symtab";
2301 SymTab.Link = StrTab->Index;
2302 if (Error Err = SymTab.initialize(sections()))
2303 return Err;
2304 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
2306 SymbolTable = &SymTab;
2308 return Error::success();
2311 // Orders segments such that if x = y->ParentSegment then y comes before x.
2312 static void orderSegments(std::vector<Segment *> &Segments) {
2313 llvm::stable_sort(Segments, compareSegmentsByOffset);
2316 // This function finds a consistent layout for a list of segments starting from
2317 // an Offset. It assumes that Segments have been sorted by orderSegments and
2318 // returns an Offset one past the end of the last segment.
2319 static uint64_t layoutSegments(std::vector<Segment *> &Segments,
2320 uint64_t Offset) {
2321 assert(llvm::is_sorted(Segments, compareSegmentsByOffset));
2322 // The only way a segment should move is if a section was between two
2323 // segments and that section was removed. If that section isn't in a segment
2324 // then it's acceptable, but not ideal, to simply move it to after the
2325 // segments. So we can simply layout segments one after the other accounting
2326 // for alignment.
2327 for (Segment *Seg : Segments) {
2328 // We assume that segments have been ordered by OriginalOffset and Index
2329 // such that a parent segment will always come before a child segment in
2330 // OrderedSegments. This means that the Offset of the ParentSegment should
2331 // already be set and we can set our offset relative to it.
2332 if (Seg->ParentSegment != nullptr) {
2333 Segment *Parent = Seg->ParentSegment;
2334 Seg->Offset =
2335 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
2336 } else {
2337 Seg->Offset =
2338 alignTo(Offset, std::max<uint64_t>(Seg->Align, 1), Seg->VAddr);
2340 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
2342 return Offset;
2345 // This function finds a consistent layout for a list of sections. It assumes
2346 // that the ->ParentSegment of each section has already been laid out. The
2347 // supplied starting Offset is used for the starting offset of any section that
2348 // does not have a ParentSegment. It returns either the offset given if all
2349 // sections had a ParentSegment or an offset one past the last section if there
2350 // was a section that didn't have a ParentSegment.
2351 template <class Range>
2352 static uint64_t layoutSections(Range Sections, uint64_t Offset) {
2353 // Now the offset of every segment has been set we can assign the offsets
2354 // of each section. For sections that are covered by a segment we should use
2355 // the segment's original offset and the section's original offset to compute
2356 // the offset from the start of the segment. Using the offset from the start
2357 // of the segment we can assign a new offset to the section. For sections not
2358 // covered by segments we can just bump Offset to the next valid location.
2359 // While it is not necessary, layout the sections in the order based on their
2360 // original offsets to resemble the input file as close as possible.
2361 std::vector<SectionBase *> OutOfSegmentSections;
2362 uint32_t Index = 1;
2363 for (auto &Sec : Sections) {
2364 Sec.Index = Index++;
2365 if (Sec.ParentSegment != nullptr) {
2366 const Segment &Segment = *Sec.ParentSegment;
2367 Sec.Offset =
2368 Segment.Offset + (Sec.OriginalOffset - Segment.OriginalOffset);
2369 } else
2370 OutOfSegmentSections.push_back(&Sec);
2373 llvm::stable_sort(OutOfSegmentSections,
2374 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2375 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2377 for (auto *Sec : OutOfSegmentSections) {
2378 Offset = alignTo(Offset, Sec->Align == 0 ? 1 : Sec->Align);
2379 Sec->Offset = Offset;
2380 if (Sec->Type != SHT_NOBITS)
2381 Offset += Sec->Size;
2383 return Offset;
2386 // Rewrite sh_offset after some sections are changed to SHT_NOBITS and thus
2387 // occupy no space in the file.
2388 static uint64_t layoutSectionsForOnlyKeepDebug(Object &Obj, uint64_t Off) {
2389 // The layout algorithm requires the sections to be handled in the order of
2390 // their offsets in the input file, at least inside segments.
2391 std::vector<SectionBase *> Sections;
2392 Sections.reserve(Obj.sections().size());
2393 uint32_t Index = 1;
2394 for (auto &Sec : Obj.sections()) {
2395 Sec.Index = Index++;
2396 Sections.push_back(&Sec);
2398 llvm::stable_sort(Sections,
2399 [](const SectionBase *Lhs, const SectionBase *Rhs) {
2400 return Lhs->OriginalOffset < Rhs->OriginalOffset;
2403 for (auto *Sec : Sections) {
2404 auto *FirstSec = Sec->ParentSegment && Sec->ParentSegment->Type == PT_LOAD
2405 ? Sec->ParentSegment->firstSection()
2406 : nullptr;
2408 // The first section in a PT_LOAD has to have congruent offset and address
2409 // modulo the alignment, which usually equals the maximum page size.
2410 if (FirstSec && FirstSec == Sec)
2411 Off = alignTo(Off, Sec->ParentSegment->Align, Sec->Addr);
2413 // sh_offset is not significant for SHT_NOBITS sections, but the congruence
2414 // rule must be followed if it is the first section in a PT_LOAD. Do not
2415 // advance Off.
2416 if (Sec->Type == SHT_NOBITS) {
2417 Sec->Offset = Off;
2418 continue;
2421 if (!FirstSec) {
2422 // FirstSec being nullptr generally means that Sec does not have the
2423 // SHF_ALLOC flag.
2424 Off = Sec->Align ? alignTo(Off, Sec->Align) : Off;
2425 } else if (FirstSec != Sec) {
2426 // The offset is relative to the first section in the PT_LOAD segment. Use
2427 // sh_offset for non-SHF_ALLOC sections.
2428 Off = Sec->OriginalOffset - FirstSec->OriginalOffset + FirstSec->Offset;
2430 Sec->Offset = Off;
2431 Off += Sec->Size;
2433 return Off;
2436 // Rewrite p_offset and p_filesz of non-PT_PHDR segments after sh_offset values
2437 // have been updated.
2438 static uint64_t layoutSegmentsForOnlyKeepDebug(std::vector<Segment *> &Segments,
2439 uint64_t HdrEnd) {
2440 uint64_t MaxOffset = 0;
2441 for (Segment *Seg : Segments) {
2442 if (Seg->Type == PT_PHDR)
2443 continue;
2445 // The segment offset is generally the offset of the first section.
2447 // For a segment containing no section (see sectionWithinSegment), if it has
2448 // a parent segment, copy the parent segment's offset field. This works for
2449 // empty PT_TLS. If no parent segment, use 0: the segment is not useful for
2450 // debugging anyway.
2451 const SectionBase *FirstSec = Seg->firstSection();
2452 uint64_t Offset =
2453 FirstSec ? FirstSec->Offset
2454 : (Seg->ParentSegment ? Seg->ParentSegment->Offset : 0);
2455 uint64_t FileSize = 0;
2456 for (const SectionBase *Sec : Seg->Sections) {
2457 uint64_t Size = Sec->Type == SHT_NOBITS ? 0 : Sec->Size;
2458 if (Sec->Offset + Size > Offset)
2459 FileSize = std::max(FileSize, Sec->Offset + Size - Offset);
2462 // If the segment includes EHDR and program headers, don't make it smaller
2463 // than the headers.
2464 if (Seg->Offset < HdrEnd && HdrEnd <= Seg->Offset + Seg->FileSize) {
2465 FileSize += Offset - Seg->Offset;
2466 Offset = Seg->Offset;
2467 FileSize = std::max(FileSize, HdrEnd - Offset);
2470 Seg->Offset = Offset;
2471 Seg->FileSize = FileSize;
2472 MaxOffset = std::max(MaxOffset, Offset + FileSize);
2474 return MaxOffset;
2477 template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
2478 Segment &ElfHdr = Obj.ElfHdrSegment;
2479 ElfHdr.Type = PT_PHDR;
2480 ElfHdr.Flags = 0;
2481 ElfHdr.VAddr = 0;
2482 ElfHdr.PAddr = 0;
2483 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
2484 ElfHdr.Align = 0;
2487 template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
2488 // We need a temporary list of segments that has a special order to it
2489 // so that we know that anytime ->ParentSegment is set that segment has
2490 // already had its offset properly set.
2491 std::vector<Segment *> OrderedSegments;
2492 for (Segment &Segment : Obj.segments())
2493 OrderedSegments.push_back(&Segment);
2494 OrderedSegments.push_back(&Obj.ElfHdrSegment);
2495 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
2496 orderSegments(OrderedSegments);
2498 uint64_t Offset;
2499 if (OnlyKeepDebug) {
2500 // For --only-keep-debug, the sections that did not preserve contents were
2501 // changed to SHT_NOBITS. We now rewrite sh_offset fields of sections, and
2502 // then rewrite p_offset/p_filesz of program headers.
2503 uint64_t HdrEnd =
2504 sizeof(Elf_Ehdr) + llvm::size(Obj.segments()) * sizeof(Elf_Phdr);
2505 Offset = layoutSectionsForOnlyKeepDebug(Obj, HdrEnd);
2506 Offset = std::max(Offset,
2507 layoutSegmentsForOnlyKeepDebug(OrderedSegments, HdrEnd));
2508 } else {
2509 // Offset is used as the start offset of the first segment to be laid out.
2510 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
2511 // we start at offset 0.
2512 Offset = layoutSegments(OrderedSegments, 0);
2513 Offset = layoutSections(Obj.sections(), Offset);
2515 // If we need to write the section header table out then we need to align the
2516 // Offset so that SHOffset is valid.
2517 if (WriteSectionHeaders)
2518 Offset = alignTo(Offset, sizeof(Elf_Addr));
2519 Obj.SHOff = Offset;
2522 template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
2523 // We already have the section header offset so we can calculate the total
2524 // size by just adding up the size of each section header.
2525 if (!WriteSectionHeaders)
2526 return Obj.SHOff;
2527 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
2528 return Obj.SHOff + ShdrCount * sizeof(Elf_Shdr);
2531 template <class ELFT> Error ELFWriter<ELFT>::write() {
2532 // Segment data must be written first, so that the ELF header and program
2533 // header tables can overwrite it, if covered by a segment.
2534 writeSegmentData();
2535 writeEhdr();
2536 writePhdrs();
2537 if (Error E = writeSectionData())
2538 return E;
2539 if (WriteSectionHeaders)
2540 writeShdrs();
2542 // TODO: Implement direct writing to the output stream (without intermediate
2543 // memory buffer Buf).
2544 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2545 return Error::success();
2548 static Error removeUnneededSections(Object &Obj) {
2549 // We can remove an empty symbol table from non-relocatable objects.
2550 // Relocatable objects typically have relocation sections whose
2551 // sh_link field points to .symtab, so we can't remove .symtab
2552 // even if it is empty.
2553 if (Obj.isRelocatable() || Obj.SymbolTable == nullptr ||
2554 !Obj.SymbolTable->empty())
2555 return Error::success();
2557 // .strtab can be used for section names. In such a case we shouldn't
2558 // remove it.
2559 auto *StrTab = Obj.SymbolTable->getStrTab() == Obj.SectionNames
2560 ? nullptr
2561 : Obj.SymbolTable->getStrTab();
2562 return Obj.removeSections(false, [&](const SectionBase &Sec) {
2563 return &Sec == Obj.SymbolTable || &Sec == StrTab;
2567 template <class ELFT> Error ELFWriter<ELFT>::finalize() {
2568 // It could happen that SectionNames has been removed and yet the user wants
2569 // a section header table output. We need to throw an error if a user tries
2570 // to do that.
2571 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
2572 return createStringError(llvm::errc::invalid_argument,
2573 "cannot write section header table because "
2574 "section header string table was removed");
2576 if (Error E = removeUnneededSections(Obj))
2577 return E;
2579 // If the .symtab indices have not been changed, restore the sh_link to
2580 // .symtab for sections that were linked to .symtab.
2581 if (Obj.SymbolTable && !Obj.SymbolTable->indicesChanged())
2582 for (SectionBase &Sec : Obj.sections())
2583 Sec.restoreSymTabLink(*Obj.SymbolTable);
2585 // We need to assign indexes before we perform layout because we need to know
2586 // if we need large indexes or not. We can assign indexes first and check as
2587 // we go to see if we will actully need large indexes.
2588 bool NeedsLargeIndexes = false;
2589 if (Obj.sections().size() >= SHN_LORESERVE) {
2590 SectionTableRef Sections = Obj.sections();
2591 // Sections doesn't include the null section header, so account for this
2592 // when skipping the first N sections.
2593 NeedsLargeIndexes =
2594 any_of(drop_begin(Sections, SHN_LORESERVE - 1),
2595 [](const SectionBase &Sec) { return Sec.HasSymbol; });
2596 // TODO: handle case where only one section needs the large index table but
2597 // only needs it because the large index table hasn't been removed yet.
2600 if (NeedsLargeIndexes) {
2601 // This means we definitely need to have a section index table but if we
2602 // already have one then we should use it instead of making a new one.
2603 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
2604 // Addition of a section to the end does not invalidate the indexes of
2605 // other sections and assigns the correct index to the new section.
2606 auto &Shndx = Obj.addSection<SectionIndexSection>();
2607 Obj.SymbolTable->setShndxTable(&Shndx);
2608 Shndx.setSymTab(Obj.SymbolTable);
2610 } else {
2611 // Since we don't need SectionIndexTable we should remove it and all
2612 // references to it.
2613 if (Obj.SectionIndexTable != nullptr) {
2614 // We do not support sections referring to the section index table.
2615 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
2616 [this](const SectionBase &Sec) {
2617 return &Sec == Obj.SectionIndexTable;
2619 return E;
2623 // Make sure we add the names of all the sections. Importantly this must be
2624 // done after we decide to add or remove SectionIndexes.
2625 if (Obj.SectionNames != nullptr)
2626 for (const SectionBase &Sec : Obj.sections())
2627 Obj.SectionNames->addString(Sec.Name);
2629 initEhdrSegment();
2631 // Before we can prepare for layout the indexes need to be finalized.
2632 // Also, the output arch may not be the same as the input arch, so fix up
2633 // size-related fields before doing layout calculations.
2634 uint64_t Index = 0;
2635 auto SecSizer = std::make_unique<ELFSectionSizer<ELFT>>();
2636 for (SectionBase &Sec : Obj.sections()) {
2637 Sec.Index = Index++;
2638 if (Error Err = Sec.accept(*SecSizer))
2639 return Err;
2642 // The symbol table does not update all other sections on update. For
2643 // instance, symbol names are not added as new symbols are added. This means
2644 // that some sections, like .strtab, don't yet have their final size.
2645 if (Obj.SymbolTable != nullptr)
2646 Obj.SymbolTable->prepareForLayout();
2648 // Now that all strings are added we want to finalize string table builders,
2649 // because that affects section sizes which in turn affects section offsets.
2650 for (SectionBase &Sec : Obj.sections())
2651 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
2652 StrTab->prepareForLayout();
2654 assignOffsets();
2656 // layoutSections could have modified section indexes, so we need
2657 // to fill the index table after assignOffsets.
2658 if (Obj.SymbolTable != nullptr)
2659 Obj.SymbolTable->fillShndxTable();
2661 // Finally now that all offsets and indexes have been set we can finalize any
2662 // remaining issues.
2663 uint64_t Offset = Obj.SHOff + sizeof(Elf_Shdr);
2664 for (SectionBase &Sec : Obj.sections()) {
2665 Sec.HeaderOffset = Offset;
2666 Offset += sizeof(Elf_Shdr);
2667 if (WriteSectionHeaders)
2668 Sec.NameIndex = Obj.SectionNames->findIndex(Sec.Name);
2669 Sec.finalize();
2672 size_t TotalSize = totalSize();
2673 Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
2674 if (!Buf)
2675 return createStringError(errc::not_enough_memory,
2676 "failed to allocate memory buffer of " +
2677 Twine::utohexstr(TotalSize) + " bytes");
2679 SecWriter = std::make_unique<ELFSectionWriter<ELFT>>(*Buf);
2680 return Error::success();
2683 Error BinaryWriter::write() {
2684 SmallVector<const SectionBase *, 30> SectionsToWrite;
2685 for (const SectionBase &Sec : Obj.allocSections()) {
2686 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2687 SectionsToWrite.push_back(&Sec);
2690 if (SectionsToWrite.empty())
2691 return Error::success();
2693 llvm::stable_sort(SectionsToWrite,
2694 [](const SectionBase *LHS, const SectionBase *RHS) {
2695 return LHS->Offset < RHS->Offset;
2698 assert(SectionsToWrite.front()->Offset == 0);
2700 for (size_t i = 0; i != SectionsToWrite.size(); ++i) {
2701 const SectionBase &Sec = *SectionsToWrite[i];
2702 if (Error Err = Sec.accept(*SecWriter))
2703 return Err;
2704 if (GapFill == 0)
2705 continue;
2706 uint64_t PadOffset = (i < SectionsToWrite.size() - 1)
2707 ? SectionsToWrite[i + 1]->Offset
2708 : Buf->getBufferSize();
2709 assert(PadOffset <= Buf->getBufferSize());
2710 assert(Sec.Offset + Sec.Size <= PadOffset);
2711 std::fill(Buf->getBufferStart() + Sec.Offset + Sec.Size,
2712 Buf->getBufferStart() + PadOffset, GapFill);
2715 // TODO: Implement direct writing to the output stream (without intermediate
2716 // memory buffer Buf).
2717 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2718 return Error::success();
2721 Error BinaryWriter::finalize() {
2722 // Compute the section LMA based on its sh_offset and the containing segment's
2723 // p_offset and p_paddr. Also compute the minimum LMA of all non-empty
2724 // sections as MinAddr. In the output, the contents between address 0 and
2725 // MinAddr will be skipped.
2726 uint64_t MinAddr = UINT64_MAX;
2727 for (SectionBase &Sec : Obj.allocSections()) {
2728 if (Sec.ParentSegment != nullptr)
2729 Sec.Addr =
2730 Sec.Offset - Sec.ParentSegment->Offset + Sec.ParentSegment->PAddr;
2731 if (Sec.Type != SHT_NOBITS && Sec.Size > 0)
2732 MinAddr = std::min(MinAddr, Sec.Addr);
2735 // Now that every section has been laid out we just need to compute the total
2736 // file size. This might not be the same as the offset returned by
2737 // layoutSections, because we want to truncate the last segment to the end of
2738 // its last non-empty section, to match GNU objcopy's behaviour.
2739 TotalSize = PadTo > MinAddr ? PadTo - MinAddr : 0;
2740 for (SectionBase &Sec : Obj.allocSections())
2741 if (Sec.Type != SHT_NOBITS && Sec.Size > 0) {
2742 Sec.Offset = Sec.Addr - MinAddr;
2743 TotalSize = std::max(TotalSize, Sec.Offset + Sec.Size);
2746 Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
2747 if (!Buf)
2748 return createStringError(errc::not_enough_memory,
2749 "failed to allocate memory buffer of " +
2750 Twine::utohexstr(TotalSize) + " bytes");
2751 SecWriter = std::make_unique<BinarySectionWriter>(*Buf);
2752 return Error::success();
2755 Error ASCIIHexWriter::checkSection(const SectionBase &S) const {
2756 if (addressOverflows32bit(S.Addr) ||
2757 addressOverflows32bit(S.Addr + S.Size - 1))
2758 return createStringError(
2759 errc::invalid_argument,
2760 "section '%s' address range [0x%llx, 0x%llx] is not 32 bit",
2761 S.Name.c_str(), S.Addr, S.Addr + S.Size - 1);
2762 return Error::success();
2765 Error ASCIIHexWriter::finalize() {
2766 // We can't write 64-bit addresses.
2767 if (addressOverflows32bit(Obj.Entry))
2768 return createStringError(errc::invalid_argument,
2769 "entry point address 0x%llx overflows 32 bits",
2770 Obj.Entry);
2772 for (const SectionBase &S : Obj.sections()) {
2773 if ((S.Flags & ELF::SHF_ALLOC) && S.Type != ELF::SHT_NOBITS && S.Size > 0) {
2774 if (Error E = checkSection(S))
2775 return E;
2776 Sections.push_back(&S);
2780 llvm::sort(Sections, [](const SectionBase *A, const SectionBase *B) {
2781 return sectionPhysicalAddr(A) < sectionPhysicalAddr(B);
2784 std::unique_ptr<WritableMemoryBuffer> EmptyBuffer =
2785 WritableMemoryBuffer::getNewMemBuffer(0);
2786 if (!EmptyBuffer)
2787 return createStringError(errc::not_enough_memory,
2788 "failed to allocate memory buffer of 0 bytes");
2790 Expected<size_t> ExpTotalSize = getTotalSize(*EmptyBuffer);
2791 if (!ExpTotalSize)
2792 return ExpTotalSize.takeError();
2793 TotalSize = *ExpTotalSize;
2795 Buf = WritableMemoryBuffer::getNewMemBuffer(TotalSize);
2796 if (!Buf)
2797 return createStringError(errc::not_enough_memory,
2798 "failed to allocate memory buffer of 0x" +
2799 Twine::utohexstr(TotalSize) + " bytes");
2800 return Error::success();
2803 uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
2804 IHexLineData HexData;
2805 uint8_t Data[4] = {};
2806 // We don't write entry point record if entry is zero.
2807 if (Obj.Entry == 0)
2808 return 0;
2810 if (Obj.Entry <= 0xFFFFFU) {
2811 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
2812 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
2813 llvm::endianness::big);
2814 HexData = IHexRecord::getLine(IHexRecord::StartAddr80x86, 0, Data);
2815 } else {
2816 support::endian::write(Data, static_cast<uint32_t>(Obj.Entry),
2817 llvm::endianness::big);
2818 HexData = IHexRecord::getLine(IHexRecord::StartAddr, 0, Data);
2820 memcpy(Buf, HexData.data(), HexData.size());
2821 return HexData.size();
2824 uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
2825 IHexLineData HexData = IHexRecord::getLine(IHexRecord::EndOfFile, 0, {});
2826 memcpy(Buf, HexData.data(), HexData.size());
2827 return HexData.size();
2830 Expected<size_t>
2831 IHexWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
2832 IHexSectionWriterBase LengthCalc(EmptyBuffer);
2833 for (const SectionBase *Sec : Sections)
2834 if (Error Err = Sec->accept(LengthCalc))
2835 return std::move(Err);
2837 // We need space to write section records + StartAddress record
2838 // (if start adress is not zero) + EndOfFile record.
2839 return LengthCalc.getBufferOffset() +
2840 (Obj.Entry ? IHexRecord::getLineLength(4) : 0) +
2841 IHexRecord::getLineLength(0);
2844 Error IHexWriter::write() {
2845 IHexSectionWriter Writer(*Buf);
2846 // Write sections.
2847 for (const SectionBase *Sec : Sections)
2848 if (Error Err = Sec->accept(Writer))
2849 return Err;
2851 uint64_t Offset = Writer.getBufferOffset();
2852 // Write entry point address.
2853 Offset += writeEntryPointRecord(
2854 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2855 // Write EOF.
2856 Offset += writeEndOfFileRecord(
2857 reinterpret_cast<uint8_t *>(Buf->getBufferStart()) + Offset);
2858 assert(Offset == TotalSize);
2860 // TODO: Implement direct writing to the output stream (without intermediate
2861 // memory buffer Buf).
2862 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
2863 return Error::success();
2866 Error SRECSectionWriterBase::visit(const StringTableSection &Sec) {
2867 // Check that the sizer has already done its work.
2868 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2869 "Expected section size to have been finalized");
2870 // We don't need to write anything here because the real writer has already
2871 // done it.
2872 return Error::success();
2875 Error SRECSectionWriterBase::visit(const Section &Sec) {
2876 writeSection(Sec, Sec.Contents);
2877 return Error::success();
2880 Error SRECSectionWriterBase::visit(const OwnedDataSection &Sec) {
2881 writeSection(Sec, Sec.Data);
2882 return Error::success();
2885 Error SRECSectionWriterBase::visit(const DynamicRelocationSection &Sec) {
2886 writeSection(Sec, Sec.Contents);
2887 return Error::success();
2890 void SRECSectionWriter::writeRecord(SRecord &Record, uint64_t Off) {
2891 SRecLineData Data = Record.toString();
2892 memcpy(Out.getBufferStart() + Off, Data.data(), Data.size());
2895 void SRECSectionWriterBase::writeRecords(uint32_t Entry) {
2896 // The ELF header could contain an entry point outside of the sections we have
2897 // seen that does not fit the current record Type.
2898 Type = std::max(Type, SRecord::getType(Entry));
2899 uint64_t Off = HeaderSize;
2900 for (SRecord &Record : Records) {
2901 Record.Type = Type;
2902 writeRecord(Record, Off);
2903 Off += Record.getSize();
2905 Offset = Off;
2908 void SRECSectionWriterBase::writeSection(const SectionBase &S,
2909 ArrayRef<uint8_t> Data) {
2910 const uint32_t ChunkSize = 16;
2911 uint32_t Address = sectionPhysicalAddr(&S);
2912 uint32_t EndAddr = Address + S.Size - 1;
2913 Type = std::max(SRecord::getType(EndAddr), Type);
2914 while (!Data.empty()) {
2915 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
2916 SRecord Record{Type, Address, Data.take_front(DataSize)};
2917 Records.push_back(Record);
2918 Data = Data.drop_front(DataSize);
2919 Address += DataSize;
2923 Error SRECSectionWriter::visit(const StringTableSection &Sec) {
2924 assert(Sec.Size == Sec.StrTabBuilder.getSize() &&
2925 "Section size does not match the section's string table builder size");
2926 std::vector<uint8_t> Data(Sec.Size);
2927 Sec.StrTabBuilder.write(Data.data());
2928 writeSection(Sec, Data);
2929 return Error::success();
2932 SRecLineData SRecord::toString() const {
2933 SRecLineData Line(getSize());
2934 auto *Iter = Line.begin();
2935 *Iter++ = 'S';
2936 *Iter++ = '0' + Type;
2937 // Write 1 byte (2 hex characters) record count.
2938 Iter = toHexStr(getCount(), Iter, 2);
2939 // Write the address field with length depending on record type.
2940 Iter = toHexStr(Address, Iter, getAddressSize());
2941 // Write data byte by byte.
2942 for (uint8_t X : Data)
2943 Iter = toHexStr(X, Iter, 2);
2944 // Write the 1 byte checksum.
2945 Iter = toHexStr(getChecksum(), Iter, 2);
2946 *Iter++ = '\r';
2947 *Iter++ = '\n';
2948 assert(Iter == Line.end());
2949 return Line;
2952 uint8_t SRecord::getChecksum() const {
2953 uint32_t Sum = getCount();
2954 Sum += (Address >> 24) & 0xFF;
2955 Sum += (Address >> 16) & 0xFF;
2956 Sum += (Address >> 8) & 0xFF;
2957 Sum += Address & 0xFF;
2958 for (uint8_t Byte : Data)
2959 Sum += Byte;
2960 return 0xFF - (Sum & 0xFF);
2963 size_t SRecord::getSize() const {
2964 // Type, Count, Checksum, and CRLF are two characters each.
2965 return 2 + 2 + getAddressSize() + Data.size() * 2 + 2 + 2;
2968 uint8_t SRecord::getAddressSize() const {
2969 switch (Type) {
2970 case Type::S2:
2971 return 6;
2972 case Type::S3:
2973 return 8;
2974 case Type::S7:
2975 return 8;
2976 case Type::S8:
2977 return 6;
2978 default:
2979 return 4;
2983 uint8_t SRecord::getCount() const {
2984 uint8_t DataSize = Data.size();
2985 uint8_t ChecksumSize = 1;
2986 return getAddressSize() / 2 + DataSize + ChecksumSize;
2989 uint8_t SRecord::getType(uint32_t Address) {
2990 if (isUInt<16>(Address))
2991 return SRecord::S1;
2992 if (isUInt<24>(Address))
2993 return SRecord::S2;
2994 return SRecord::S3;
2997 SRecord SRecord::getHeader(StringRef FileName) {
2998 // Header is a record with Type S0, Address 0, and Data that is a
2999 // vendor-specific text comment. For the comment we will use the output file
3000 // name truncated to 40 characters to match the behavior of GNU objcopy.
3001 StringRef HeaderContents = FileName.slice(0, 40);
3002 ArrayRef<uint8_t> Data(
3003 reinterpret_cast<const uint8_t *>(HeaderContents.data()),
3004 HeaderContents.size());
3005 return {SRecord::S0, 0, Data};
3008 size_t SRECWriter::writeHeader(uint8_t *Buf) {
3009 SRecLineData Record = SRecord::getHeader(OutputFileName).toString();
3010 memcpy(Buf, Record.data(), Record.size());
3011 return Record.size();
3014 size_t SRECWriter::writeTerminator(uint8_t *Buf, uint8_t Type) {
3015 assert(Type >= SRecord::S7 && Type <= SRecord::S9 &&
3016 "Invalid record type for terminator");
3017 uint32_t Entry = Obj.Entry;
3018 SRecLineData Data = SRecord{Type, Entry, {}}.toString();
3019 memcpy(Buf, Data.data(), Data.size());
3020 return Data.size();
3023 Expected<size_t>
3024 SRECWriter::getTotalSize(WritableMemoryBuffer &EmptyBuffer) const {
3025 SRECSizeCalculator SizeCalc(EmptyBuffer, 0);
3026 for (const SectionBase *Sec : Sections)
3027 if (Error Err = Sec->accept(SizeCalc))
3028 return std::move(Err);
3030 SizeCalc.writeRecords(Obj.Entry);
3031 // We need to add the size of the Header and Terminator records.
3032 SRecord Header = SRecord::getHeader(OutputFileName);
3033 uint8_t TerminatorType = 10 - SizeCalc.getType();
3034 SRecord Terminator = {TerminatorType, static_cast<uint32_t>(Obj.Entry), {}};
3035 return Header.getSize() + SizeCalc.getBufferOffset() + Terminator.getSize();
3038 Error SRECWriter::write() {
3039 uint32_t HeaderSize =
3040 writeHeader(reinterpret_cast<uint8_t *>(Buf->getBufferStart()));
3041 SRECSectionWriter Writer(*Buf, HeaderSize);
3042 for (const SectionBase *S : Sections) {
3043 if (Error E = S->accept(Writer))
3044 return E;
3046 Writer.writeRecords(Obj.Entry);
3047 uint64_t Offset = Writer.getBufferOffset();
3049 // An S1 record terminates with an S9 record, S2 with S8, and S3 with S7.
3050 uint8_t TerminatorType = 10 - Writer.getType();
3051 Offset += writeTerminator(
3052 reinterpret_cast<uint8_t *>(Buf->getBufferStart() + Offset),
3053 TerminatorType);
3054 assert(Offset == TotalSize);
3055 Out.write(Buf->getBufferStart(), Buf->getBufferSize());
3056 return Error::success();
3059 namespace llvm {
3060 namespace objcopy {
3061 namespace elf {
3063 template class ELFBuilder<ELF64LE>;
3064 template class ELFBuilder<ELF64BE>;
3065 template class ELFBuilder<ELF32LE>;
3066 template class ELFBuilder<ELF32BE>;
3068 template class ELFWriter<ELF64LE>;
3069 template class ELFWriter<ELF64BE>;
3070 template class ELFWriter<ELF32LE>;
3071 template class ELFWriter<ELF32BE>;
3073 } // end namespace elf
3074 } // end namespace objcopy
3075 } // end namespace llvm