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