blob: b654305474f23a84f3efcaf3253027967a80405d [file] [log] [blame]
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001//===- Object.cpp ---------------------------------------------------------===//
Petr Hosek05a04cb2017-08-01 00:33:58 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Petr Hosek05a04cb2017-08-01 00:33:58 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00008
Petr Hosek05a04cb2017-08-01 00:33:58 +00009#include "Object.h"
10#include "llvm-objcopy.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/ADT/iterator_range.h"
16#include "llvm/BinaryFormat/ELF.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000017#include "llvm/MC/MCTargetOptions.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000018#include "llvm/Object/ELFObjectFile.h"
Puyan Lotfi99124cc2018-09-07 08:10:22 +000019#include "llvm/Support/Compression.h"
Eugene Levianta6fb1832019-05-29 11:37:16 +000020#include "llvm/Support/Endian.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000021#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/FileOutputBuffer.h"
Jake Ehrlichea07d3c2018-01-25 22:15:14 +000023#include "llvm/Support/Path.h"
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000024#include <algorithm>
25#include <cstddef>
26#include <cstdint>
27#include <iterator>
Jordan Rupprecht52d57812019-02-21 16:45:42 +000028#include <unordered_set>
Eugene Zelenko0ad18f82017-11-01 21:16:06 +000029#include <utility>
30#include <vector>
Petr Hosek05a04cb2017-08-01 00:33:58 +000031
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +000032namespace llvm {
33namespace objcopy {
34namespace elf {
35
Petr Hosek05a04cb2017-08-01 00:33:58 +000036using namespace object;
37using namespace ELF;
38
Jake Ehrlich76e91102018-01-25 22:46:17 +000039template <class ELFT> void ELFWriter<ELFT>::writePhdr(const Segment &Seg) {
George Rimare98a8f72019-05-23 09:18:57 +000040 uint8_t *B = Buf.getBufferStart() + Obj.ProgramHdrSegment.Offset +
41 Seg.Index * sizeof(Elf_Phdr);
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +000042 Elf_Phdr &Phdr = *reinterpret_cast<Elf_Phdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000043 Phdr.p_type = Seg.Type;
44 Phdr.p_flags = Seg.Flags;
45 Phdr.p_offset = Seg.Offset;
46 Phdr.p_vaddr = Seg.VAddr;
47 Phdr.p_paddr = Seg.PAddr;
48 Phdr.p_filesz = Seg.FileSize;
49 Phdr.p_memsz = Seg.MemSize;
50 Phdr.p_align = Seg.Align;
Petr Hosekc4df10e2017-08-04 21:09:26 +000051}
52
Jordan Rupprecht52d57812019-02-21 16:45:42 +000053Error SectionBase::removeSectionReferences(
James Henderson66a9d0f2019-04-18 09:13:30 +000054 bool AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +000055 function_ref<bool(const SectionBase *)> ToRemove) {
Jordan Rupprecht971d47622019-02-01 15:20:36 +000056 return Error::success();
57}
58
59Error SectionBase::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
60 return Error::success();
61}
62
Jake Ehrlichf5a43772017-09-25 20:37:28 +000063void SectionBase::initialize(SectionTableRef SecTable) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000064void SectionBase::finalize() {}
Paul Semel99dda0b2018-05-25 11:01:25 +000065void SectionBase::markSymbols() {}
George Rimard8a5c6c2019-03-11 11:01:24 +000066void SectionBase::replaceSectionReferences(
67 const DenseMap<SectionBase *, SectionBase *> &) {}
Petr Hosek05a04cb2017-08-01 00:33:58 +000068
Jake Ehrlich76e91102018-01-25 22:46:17 +000069template <class ELFT> void ELFWriter<ELFT>::writeShdr(const SectionBase &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +000070 uint8_t *B = Buf.getBufferStart() + Sec.HeaderOffset;
Jordan Rupprechtde965ea2018-08-10 16:25:58 +000071 Elf_Shdr &Shdr = *reinterpret_cast<Elf_Shdr *>(B);
Jake Ehrlich76e91102018-01-25 22:46:17 +000072 Shdr.sh_name = Sec.NameIndex;
73 Shdr.sh_type = Sec.Type;
74 Shdr.sh_flags = Sec.Flags;
75 Shdr.sh_addr = Sec.Addr;
76 Shdr.sh_offset = Sec.Offset;
77 Shdr.sh_size = Sec.Size;
78 Shdr.sh_link = Sec.Link;
79 Shdr.sh_info = Sec.Info;
80 Shdr.sh_addralign = Sec.Align;
81 Shdr.sh_entsize = Sec.EntrySize;
Petr Hosek05a04cb2017-08-01 00:33:58 +000082}
83
Jordan Rupprecht1f821762019-01-03 17:45:30 +000084template <class ELFT> void ELFSectionSizer<ELFT>::visit(Section &Sec) {}
85
86template <class ELFT>
87void ELFSectionSizer<ELFT>::visit(OwnedDataSection &Sec) {}
88
89template <class ELFT>
90void ELFSectionSizer<ELFT>::visit(StringTableSection &Sec) {}
91
92template <class ELFT>
93void ELFSectionSizer<ELFT>::visit(DynamicRelocationSection &Sec) {}
94
95template <class ELFT>
96void ELFSectionSizer<ELFT>::visit(SymbolTableSection &Sec) {
97 Sec.EntrySize = sizeof(Elf_Sym);
98 Sec.Size = Sec.Symbols.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +000099 // Align to the largest field in Elf_Sym.
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000100 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000101}
102
103template <class ELFT>
104void ELFSectionSizer<ELFT>::visit(RelocationSection &Sec) {
105 Sec.EntrySize = Sec.Type == SHT_REL ? sizeof(Elf_Rel) : sizeof(Elf_Rela);
106 Sec.Size = Sec.Relocations.size() * Sec.EntrySize;
Jordan Rupprecht78213c7e2019-01-03 17:51:32 +0000107 // Align to the largest field in Elf_Rel(a).
Jordan Rupprecht415dc5d2019-01-03 19:09:00 +0000108 Sec.Align = ELFT::Is64Bits ? sizeof(Elf_Xword) : sizeof(Elf_Word);
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000109}
110
111template <class ELFT>
112void ELFSectionSizer<ELFT>::visit(GnuDebugLinkSection &Sec) {}
113
114template <class ELFT> void ELFSectionSizer<ELFT>::visit(GroupSection &Sec) {}
115
116template <class ELFT>
117void ELFSectionSizer<ELFT>::visit(SectionIndexSection &Sec) {}
118
119template <class ELFT>
120void ELFSectionSizer<ELFT>::visit(CompressedSection &Sec) {}
121
122template <class ELFT>
123void ELFSectionSizer<ELFT>::visit(DecompressedSection &Sec) {}
Jake Ehrlich76e91102018-01-25 22:46:17 +0000124
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000125void BinarySectionWriter::visit(const SectionIndexSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000126 error("cannot write symbol section index table '" + Sec.Name + "' ");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000127}
128
Jake Ehrlich76e91102018-01-25 22:46:17 +0000129void BinarySectionWriter::visit(const SymbolTableSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000130 error("cannot write symbol table '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000131}
132
133void BinarySectionWriter::visit(const RelocationSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000134 error("cannot write relocation section '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000135}
136
137void BinarySectionWriter::visit(const GnuDebugLinkSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000138 error("cannot write '" + Sec.Name + "' out to binary");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000139}
140
141void BinarySectionWriter::visit(const GroupSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000142 error("cannot write '" + Sec.Name + "' out to binary");
Jake Ehrlich76e91102018-01-25 22:46:17 +0000143}
144
145void SectionWriter::visit(const Section &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000146 if (Sec.Type != SHT_NOBITS)
147 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000148}
149
Eugene Levianta6fb1832019-05-29 11:37:16 +0000150static bool addressOverflows32bit(uint64_t Addr) {
151 // Sign extended 32 bit addresses (e.g 0xFFFFFFFF80000000) are ok
152 return Addr > UINT32_MAX && Addr + 0x80000000 > UINT32_MAX;
153}
154
155template <class T> static T checkedGetHex(StringRef S) {
156 T Value;
157 bool Fail = S.getAsInteger(16, Value);
158 assert(!Fail);
159 (void)Fail;
160 return Value;
161}
162
163// Fills exactly Len bytes of buffer with hexadecimal characters
164// representing value 'X'
165template <class T, class Iterator>
166static Iterator utohexstr(T X, Iterator It, size_t Len) {
167 // Fill range with '0'
168 std::fill(It, It + Len, '0');
169
170 for (long I = Len - 1; I >= 0; --I) {
171 unsigned char Mod = static_cast<unsigned char>(X) & 15;
172 *(It + I) = hexdigit(Mod, false);
173 X >>= 4;
174 }
175 assert(X == 0);
176 return It + Len;
177}
178
179uint8_t IHexRecord::getChecksum(StringRef S) {
180 assert((S.size() & 1) == 0);
181 uint8_t Checksum = 0;
182 while (!S.empty()) {
183 Checksum += checkedGetHex<uint8_t>(S.take_front(2));
184 S = S.drop_front(2);
185 }
186 return -Checksum;
187}
188
189IHexLineData IHexRecord::getLine(uint8_t Type, uint16_t Addr,
190 ArrayRef<uint8_t> Data) {
191 IHexLineData Line(getLineLength(Data.size()));
192 assert(Line.size());
193 auto Iter = Line.begin();
194 *Iter++ = ':';
195 Iter = utohexstr(Data.size(), Iter, 2);
196 Iter = utohexstr(Addr, Iter, 4);
197 Iter = utohexstr(Type, Iter, 2);
198 for (uint8_t X : Data)
199 Iter = utohexstr(X, Iter, 2);
200 StringRef S(Line.data() + 1, std::distance(Line.begin() + 1, Iter));
201 Iter = utohexstr(getChecksum(S), Iter, 2);
202 *Iter++ = '\r';
203 *Iter++ = '\n';
204 assert(Iter == Line.end());
205 return Line;
206}
207
208static uint64_t sectionPhysicalAddr(const SectionBase *Sec) {
209 Segment *Seg = Sec->ParentSegment;
210 if (Seg && Seg->Type != ELF::PT_LOAD)
211 Seg = nullptr;
212 return Seg ? Seg->PAddr + Sec->OriginalOffset - Seg->OriginalOffset
213 : Sec->Addr;
214}
215
216void IHexSectionWriterBase::writeSection(const SectionBase *Sec,
217 ArrayRef<uint8_t> Data) {
218 assert(Data.size() == Sec->Size);
219 const uint32_t ChunkSize = 16;
220 uint32_t Addr = sectionPhysicalAddr(Sec) & 0xFFFFFFFFU;
221 while (!Data.empty()) {
222 uint64_t DataSize = std::min<uint64_t>(Data.size(), ChunkSize);
223 if (Addr > SegmentAddr + BaseAddr + 0xFFFFU) {
224 if (Addr > 0xFFFFFU) {
225 // Write extended address record, zeroing segment address
226 // if needed.
227 if (SegmentAddr != 0)
228 SegmentAddr = writeSegmentAddr(0U);
229 BaseAddr = writeBaseAddr(Addr);
230 } else {
231 // We can still remain 16-bit
232 SegmentAddr = writeSegmentAddr(Addr);
233 }
234 }
235 uint64_t SegOffset = Addr - BaseAddr - SegmentAddr;
236 assert(SegOffset <= 0xFFFFU);
237 DataSize = std::min(DataSize, 0x10000U - SegOffset);
238 writeData(0, SegOffset, Data.take_front(DataSize));
239 Addr += DataSize;
240 Data = Data.drop_front(DataSize);
241 }
242}
243
244uint64_t IHexSectionWriterBase::writeSegmentAddr(uint64_t Addr) {
245 assert(Addr <= 0xFFFFFU);
246 uint8_t Data[] = {static_cast<uint8_t>((Addr & 0xF0000U) >> 12), 0};
247 writeData(2, 0, Data);
248 return Addr & 0xF0000U;
249}
250
251uint64_t IHexSectionWriterBase::writeBaseAddr(uint64_t Addr) {
252 assert(Addr <= 0xFFFFFFFFU);
253 uint64_t Base = Addr & 0xFFFF0000U;
254 uint8_t Data[] = {static_cast<uint8_t>(Base >> 24),
255 static_cast<uint8_t>((Base >> 16) & 0xFF)};
256 writeData(4, 0, Data);
257 return Base;
258}
259
260void IHexSectionWriterBase::writeData(uint8_t Type, uint16_t Addr,
261 ArrayRef<uint8_t> Data) {
262 Offset += IHexRecord::getLineLength(Data.size());
263}
264
265void IHexSectionWriterBase::visit(const Section &Sec) {
266 writeSection(&Sec, Sec.Contents);
267}
268
269void IHexSectionWriterBase::visit(const OwnedDataSection &Sec) {
270 writeSection(&Sec, Sec.Data);
271}
272
273void IHexSectionWriterBase::visit(const StringTableSection &Sec) {
274 // Check that sizer has already done its work
275 assert(Sec.Size == Sec.StrTabBuilder.getSize());
276 // We are free to pass an invalid pointer to writeSection as long
277 // as we don't actually write any data. The real writer class has
278 // to override this method .
Eugene Leviant33da0272019-05-29 12:26:23 +0000279 writeSection(&Sec, {nullptr, static_cast<size_t>(Sec.Size)});
Eugene Levianta6fb1832019-05-29 11:37:16 +0000280}
281
282void IHexSectionWriterBase::visit(const DynamicRelocationSection &Sec) {
283 writeSection(&Sec, Sec.Contents);
284}
285
286void IHexSectionWriter::writeData(uint8_t Type, uint16_t Addr,
287 ArrayRef<uint8_t> Data) {
288 IHexLineData HexData = IHexRecord::getLine(Type, Addr, Data);
289 memcpy(Out.getBufferStart() + Offset, HexData.data(), HexData.size());
290 Offset += HexData.size();
291}
292
293void IHexSectionWriter::visit(const StringTableSection &Sec) {
294 assert(Sec.Size == Sec.StrTabBuilder.getSize());
295 std::vector<uint8_t> Data(Sec.Size);
296 Sec.StrTabBuilder.write(Data.data());
297 writeSection(&Sec, Data);
298}
299
Jake Ehrlich76e91102018-01-25 22:46:17 +0000300void Section::accept(SectionVisitor &Visitor) const { Visitor.visit(*this); }
301
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000302void Section::accept(MutableSectionVisitor &Visitor) { Visitor.visit(*this); }
303
Jake Ehrlich76e91102018-01-25 22:46:17 +0000304void SectionWriter::visit(const OwnedDataSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000305 llvm::copy(Sec.Data, Out.getBufferStart() + Sec.Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000306}
307
Puyan Lotfiaf048642018-10-01 10:29:41 +0000308static const std::vector<uint8_t> ZlibGnuMagic = {'Z', 'L', 'I', 'B'};
309
310static bool isDataGnuCompressed(ArrayRef<uint8_t> Data) {
311 return Data.size() > ZlibGnuMagic.size() &&
312 std::equal(ZlibGnuMagic.begin(), ZlibGnuMagic.end(), Data.data());
313}
314
315template <class ELFT>
316static std::tuple<uint64_t, uint64_t>
317getDecompressedSizeAndAlignment(ArrayRef<uint8_t> Data) {
318 const bool IsGnuDebug = isDataGnuCompressed(Data);
319 const uint64_t DecompressedSize =
320 IsGnuDebug
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000321 ? support::endian::read64be(Data.data() + ZlibGnuMagic.size())
Puyan Lotfiaf048642018-10-01 10:29:41 +0000322 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())->ch_size;
323 const uint64_t DecompressedAlign =
324 IsGnuDebug ? 1
325 : reinterpret_cast<const Elf_Chdr_Impl<ELFT> *>(Data.data())
326 ->ch_addralign;
327
328 return std::make_tuple(DecompressedSize, DecompressedAlign);
329}
330
331template <class ELFT>
332void ELFSectionWriter<ELFT>::visit(const DecompressedSection &Sec) {
Puyan Lotfiaf048642018-10-01 10:29:41 +0000333 const size_t DataOffset = isDataGnuCompressed(Sec.OriginalData)
334 ? (ZlibGnuMagic.size() + sizeof(Sec.Size))
335 : sizeof(Elf_Chdr_Impl<ELFT>);
336
337 StringRef CompressedContent(
338 reinterpret_cast<const char *>(Sec.OriginalData.data()) + DataOffset,
339 Sec.OriginalData.size() - DataOffset);
340
341 SmallVector<char, 128> DecompressedContent;
342 if (Error E = zlib::uncompress(CompressedContent, DecompressedContent,
343 static_cast<size_t>(Sec.Size)))
344 reportError(Sec.Name, std::move(E));
345
George Rimar281a5be2019-03-06 14:12:18 +0000346 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfiaf048642018-10-01 10:29:41 +0000347 std::copy(DecompressedContent.begin(), DecompressedContent.end(), Buf);
348}
349
350void BinarySectionWriter::visit(const DecompressedSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000351 error("cannot write compressed section '" + Sec.Name + "' ");
Puyan Lotfiaf048642018-10-01 10:29:41 +0000352}
353
354void DecompressedSection::accept(SectionVisitor &Visitor) const {
355 Visitor.visit(*this);
356}
357
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000358void DecompressedSection::accept(MutableSectionVisitor &Visitor) {
359 Visitor.visit(*this);
360}
361
Jake Ehrlich76e91102018-01-25 22:46:17 +0000362void OwnedDataSection::accept(SectionVisitor &Visitor) const {
363 Visitor.visit(*this);
Jake Ehrliche8437de2017-12-19 00:47:30 +0000364}
365
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000366void OwnedDataSection::accept(MutableSectionVisitor &Visitor) {
367 Visitor.visit(*this);
368}
369
Eugene Levianta6fb1832019-05-29 11:37:16 +0000370void OwnedDataSection::appendHexData(StringRef HexData) {
371 assert((HexData.size() & 1) == 0);
372 while (!HexData.empty()) {
373 Data.push_back(checkedGetHex<uint8_t>(HexData.take_front(2)));
374 HexData = HexData.drop_front(2);
375 }
376 Size = Data.size();
377}
378
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000379void BinarySectionWriter::visit(const CompressedSection &Sec) {
James Henderson5316a0d2019-05-22 13:23:26 +0000380 error("cannot write compressed section '" + Sec.Name + "' ");
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000381}
382
383template <class ELFT>
384void ELFSectionWriter<ELFT>::visit(const CompressedSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000385 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000386 if (Sec.CompressionType == DebugCompressionType::None) {
387 std::copy(Sec.OriginalData.begin(), Sec.OriginalData.end(), Buf);
388 return;
389 }
390
391 if (Sec.CompressionType == DebugCompressionType::GNU) {
392 const char *Magic = "ZLIB";
393 memcpy(Buf, Magic, strlen(Magic));
394 Buf += strlen(Magic);
395 const uint64_t DecompressedSize =
396 support::endian::read64be(&Sec.DecompressedSize);
397 memcpy(Buf, &DecompressedSize, sizeof(DecompressedSize));
398 Buf += sizeof(DecompressedSize);
399 } else {
400 Elf_Chdr_Impl<ELFT> Chdr;
401 Chdr.ch_type = ELF::ELFCOMPRESS_ZLIB;
402 Chdr.ch_size = Sec.DecompressedSize;
403 Chdr.ch_addralign = Sec.DecompressedAlign;
404 memcpy(Buf, &Chdr, sizeof(Chdr));
405 Buf += sizeof(Chdr);
406 }
407
408 std::copy(Sec.CompressedData.begin(), Sec.CompressedData.end(), Buf);
409}
410
411CompressedSection::CompressedSection(const SectionBase &Sec,
412 DebugCompressionType CompressionType)
413 : SectionBase(Sec), CompressionType(CompressionType),
414 DecompressedSize(Sec.OriginalData.size()), DecompressedAlign(Sec.Align) {
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000415 if (Error E = zlib::compress(
416 StringRef(reinterpret_cast<const char *>(OriginalData.data()),
417 OriginalData.size()),
418 CompressedData))
419 reportError(Name, std::move(E));
420
421 size_t ChdrSize;
422 if (CompressionType == DebugCompressionType::GNU) {
423 Name = ".z" + Sec.Name.substr(1);
424 ChdrSize = sizeof("ZLIB") - 1 + sizeof(uint64_t);
425 } else {
426 Flags |= ELF::SHF_COMPRESSED;
427 ChdrSize =
428 std::max(std::max(sizeof(object::Elf_Chdr_Impl<object::ELF64LE>),
429 sizeof(object::Elf_Chdr_Impl<object::ELF64BE>)),
430 std::max(sizeof(object::Elf_Chdr_Impl<object::ELF32LE>),
431 sizeof(object::Elf_Chdr_Impl<object::ELF32BE>)));
432 }
433 Size = ChdrSize + CompressedData.size();
434 Align = 8;
435}
436
Puyan Lotfiaf048642018-10-01 10:29:41 +0000437CompressedSection::CompressedSection(ArrayRef<uint8_t> CompressedData,
438 uint64_t DecompressedSize,
439 uint64_t DecompressedAlign)
440 : CompressionType(DebugCompressionType::None),
441 DecompressedSize(DecompressedSize), DecompressedAlign(DecompressedAlign) {
442 OriginalData = CompressedData;
443}
444
Puyan Lotfi99124cc2018-09-07 08:10:22 +0000445void CompressedSection::accept(SectionVisitor &Visitor) const {
446 Visitor.visit(*this);
447}
448
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000449void CompressedSection::accept(MutableSectionVisitor &Visitor) {
450 Visitor.visit(*this);
451}
452
George Rimarfaf308b2019-03-18 14:27:41 +0000453void StringTableSection::addString(StringRef Name) { StrTabBuilder.add(Name); }
Petr Hosek05a04cb2017-08-01 00:33:58 +0000454
455uint32_t StringTableSection::findIndex(StringRef Name) const {
456 return StrTabBuilder.getOffset(Name);
457}
458
George Rimarfaf308b2019-03-18 14:27:41 +0000459void StringTableSection::prepareForLayout() {
460 StrTabBuilder.finalize();
461 Size = StrTabBuilder.getSize();
462}
Petr Hosek05a04cb2017-08-01 00:33:58 +0000463
Jake Ehrlich76e91102018-01-25 22:46:17 +0000464void SectionWriter::visit(const StringTableSection &Sec) {
465 Sec.StrTabBuilder.write(Out.getBufferStart() + Sec.Offset);
466}
467
468void StringTableSection::accept(SectionVisitor &Visitor) const {
469 Visitor.visit(*this);
Petr Hosek05a04cb2017-08-01 00:33:58 +0000470}
471
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000472void StringTableSection::accept(MutableSectionVisitor &Visitor) {
473 Visitor.visit(*this);
474}
475
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000476template <class ELFT>
477void ELFSectionWriter<ELFT>::visit(const SectionIndexSection &Sec) {
478 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
George Rimare98a8f72019-05-23 09:18:57 +0000479 llvm::copy(Sec.Indexes, reinterpret_cast<Elf_Word *>(Buf));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000480}
481
482void SectionIndexSection::initialize(SectionTableRef SecTable) {
483 Size = 0;
484 setSymTab(SecTable.getSectionOfType<SymbolTableSection>(
485 Link,
486 "Link field value " + Twine(Link) + " in section " + Name + " is invalid",
487 "Link field value " + Twine(Link) + " in section " + Name +
488 " is not a symbol table"));
489 Symbols->setShndxTable(this);
490}
491
492void SectionIndexSection::finalize() { Link = Symbols->Index; }
493
494void SectionIndexSection::accept(SectionVisitor &Visitor) const {
495 Visitor.visit(*this);
496}
497
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000498void SectionIndexSection::accept(MutableSectionVisitor &Visitor) {
499 Visitor.visit(*this);
500}
501
Petr Hosekc1135772017-09-13 03:04:50 +0000502static bool isValidReservedSectionIndex(uint16_t Index, uint16_t Machine) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000503 switch (Index) {
504 case SHN_ABS:
505 case SHN_COMMON:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000506 return true;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000507 }
Petr Hosekc1135772017-09-13 03:04:50 +0000508 if (Machine == EM_HEXAGON) {
509 switch (Index) {
510 case SHN_HEXAGON_SCOMMON:
511 case SHN_HEXAGON_SCOMMON_2:
512 case SHN_HEXAGON_SCOMMON_4:
513 case SHN_HEXAGON_SCOMMON_8:
514 return true;
515 }
516 }
517 return false;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000518}
519
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000520// Large indexes force us to clarify exactly what this function should do. This
521// function should return the value that will appear in st_shndx when written
522// out.
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000523uint16_t Symbol::getShndx() const {
524 if (DefinedIn != nullptr) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000525 if (DefinedIn->Index >= SHN_LORESERVE)
526 return SHN_XINDEX;
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000527 return DefinedIn->Index;
528 }
529 switch (ShndxType) {
530 // This means that we don't have a defined section but we do need to
531 // output a legitimate section index.
532 case SYMBOL_SIMPLE_INDEX:
533 return SHN_UNDEF;
534 case SYMBOL_ABS:
535 case SYMBOL_COMMON:
536 case SYMBOL_HEXAGON_SCOMMON:
537 case SYMBOL_HEXAGON_SCOMMON_2:
538 case SYMBOL_HEXAGON_SCOMMON_4:
539 case SYMBOL_HEXAGON_SCOMMON_8:
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000540 case SYMBOL_XINDEX:
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000541 return static_cast<uint16_t>(ShndxType);
542 }
543 llvm_unreachable("Symbol with invalid ShndxType encountered");
544}
545
Jordan Rupprechtb47475c2018-11-01 17:26:36 +0000546bool Symbol::isCommon() const { return getShndx() == SHN_COMMON; }
547
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000548void SymbolTableSection::assignIndices() {
549 uint32_t Index = 0;
550 for (auto &Sym : Symbols)
551 Sym->Index = Index++;
552}
553
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000554void SymbolTableSection::addSymbol(Twine Name, uint8_t Bind, uint8_t Type,
Petr Hosek79cee9e2017-08-29 02:12:03 +0000555 SectionBase *DefinedIn, uint64_t Value,
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000556 uint8_t Visibility, uint16_t Shndx,
George Rimar17dbb192019-05-08 07:31:05 +0000557 uint64_t SymbolSize) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000558 Symbol Sym;
Jordan Rupprechtcf676332018-08-17 18:51:11 +0000559 Sym.Name = Name.str();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000560 Sym.Binding = Bind;
561 Sym.Type = Type;
562 Sym.DefinedIn = DefinedIn;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000563 if (DefinedIn != nullptr)
564 DefinedIn->HasSymbol = true;
Jake Ehrlich8b831c12018-03-07 20:33:02 +0000565 if (DefinedIn == nullptr) {
566 if (Shndx >= SHN_LORESERVE)
567 Sym.ShndxType = static_cast<SymbolShndxType>(Shndx);
568 else
569 Sym.ShndxType = SYMBOL_SIMPLE_INDEX;
570 }
Petr Hosek79cee9e2017-08-29 02:12:03 +0000571 Sym.Value = Value;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000572 Sym.Visibility = Visibility;
George Rimar17dbb192019-05-08 07:31:05 +0000573 Sym.Size = SymbolSize;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000574 Sym.Index = Symbols.size();
575 Symbols.emplace_back(llvm::make_unique<Symbol>(Sym));
576 Size += this->EntrySize;
577}
578
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000579Error SymbolTableSection::removeSectionReferences(
James Henderson66a9d0f2019-04-18 09:13:30 +0000580 bool AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000581 function_ref<bool(const SectionBase *)> ToRemove) {
582 if (ToRemove(SectionIndexTable))
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000583 SectionIndexTable = nullptr;
James Henderson66a9d0f2019-04-18 09:13:30 +0000584 if (ToRemove(SymbolNames)) {
585 if (!AllowBrokenLinks)
586 return createStringError(
587 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000588 "string table '%s' cannot be removed because it is "
589 "referenced by the symbol table '%s'",
James Henderson66a9d0f2019-04-18 09:13:30 +0000590 SymbolNames->Name.data(), this->Name.data());
591 SymbolNames = nullptr;
592 }
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000593 return removeSymbols(
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000594 [ToRemove](const Symbol &Sym) { return ToRemove(Sym.DefinedIn); });
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000595}
596
Alexander Shaposhnikov40e9bdf2018-04-26 18:28:17 +0000597void SymbolTableSection::updateSymbols(function_ref<void(Symbol &)> Callable) {
Paul Semel46201fb2018-06-01 16:19:46 +0000598 std::for_each(std::begin(Symbols) + 1, std::end(Symbols),
599 [Callable](SymPtr &Sym) { Callable(*Sym); });
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000600 std::stable_partition(
601 std::begin(Symbols), std::end(Symbols),
602 [](const SymPtr &Sym) { return Sym->Binding == STB_LOCAL; });
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000603 assignIndices();
Jake Ehrlich27a29b02018-01-05 19:19:09 +0000604}
605
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000606Error SymbolTableSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000607 function_ref<bool(const Symbol &)> ToRemove) {
Paul Semel41695f82018-05-02 20:19:22 +0000608 Symbols.erase(
Paul Semel46201fb2018-06-01 16:19:46 +0000609 std::remove_if(std::begin(Symbols) + 1, std::end(Symbols),
Paul Semel41695f82018-05-02 20:19:22 +0000610 [ToRemove](const SymPtr &Sym) { return ToRemove(*Sym); }),
611 std::end(Symbols));
612 Size = Symbols.size() * EntrySize;
613 assignIndices();
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000614 return Error::success();
Paul Semel41695f82018-05-02 20:19:22 +0000615}
616
George Rimar0373bed2019-03-20 13:57:47 +0000617void SymbolTableSection::replaceSectionReferences(
618 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
619 for (std::unique_ptr<Symbol> &Sym : Symbols)
620 if (SectionBase *To = FromTo.lookup(Sym->DefinedIn))
621 Sym->DefinedIn = To;
622}
623
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000624void SymbolTableSection::initialize(SectionTableRef SecTable) {
625 Size = 0;
626 setStrTab(SecTable.getSectionOfType<StringTableSection>(
627 Link,
628 "Symbol table has link index of " + Twine(Link) +
629 " which is not a valid index",
630 "Symbol table has link index of " + Twine(Link) +
631 " which is not a string table"));
632}
633
Petr Hosek79cee9e2017-08-29 02:12:03 +0000634void SymbolTableSection::finalize() {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000635 uint32_t MaxLocalIndex = 0;
George Rimare98a8f72019-05-23 09:18:57 +0000636 for (std::unique_ptr<Symbol> &Sym : Symbols) {
James Henderson66a9d0f2019-04-18 09:13:30 +0000637 Sym->NameIndex =
638 SymbolNames == nullptr ? 0 : SymbolNames->findIndex(Sym->Name);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000639 if (Sym->Binding == STB_LOCAL)
640 MaxLocalIndex = std::max(MaxLocalIndex, Sym->Index);
641 }
642 // Now we need to set the Link and Info fields.
James Henderson66a9d0f2019-04-18 09:13:30 +0000643 Link = SymbolNames == nullptr ? 0 : SymbolNames->Index;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000644 Info = MaxLocalIndex + 1;
645}
646
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +0000647void SymbolTableSection::prepareForLayout() {
Eugene Leviant88089fe2019-04-12 11:59:30 +0000648 // Reserve proper amount of space in section index table, so we can
649 // layout sections correctly. We will fill the table with correct
650 // indexes later in fillShdnxTable.
651 if (SectionIndexTable)
652 SectionIndexTable->reserve(Symbols.size());
James Henderson66a9d0f2019-04-18 09:13:30 +0000653
Petr Hosek79cee9e2017-08-29 02:12:03 +0000654 // Add all of our strings to SymbolNames so that SymbolNames has the right
655 // size before layout is decided.
James Henderson66a9d0f2019-04-18 09:13:30 +0000656 // If the symbol names section has been removed, don't try to add strings to
657 // the table.
658 if (SymbolNames != nullptr)
George Rimare98a8f72019-05-23 09:18:57 +0000659 for (std::unique_ptr<Symbol> &Sym : Symbols)
James Henderson66a9d0f2019-04-18 09:13:30 +0000660 SymbolNames->addString(Sym->Name);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000661}
662
Eugene Leviant88089fe2019-04-12 11:59:30 +0000663void SymbolTableSection::fillShndxTable() {
664 if (SectionIndexTable == nullptr)
665 return;
666 // Fill section index table with real section indexes. This function must
667 // be called after assignOffsets.
George Rimare98a8f72019-05-23 09:18:57 +0000668 for (const std::unique_ptr<Symbol> &Sym : Symbols) {
Eugene Leviant88089fe2019-04-12 11:59:30 +0000669 if (Sym->DefinedIn != nullptr && Sym->DefinedIn->Index >= SHN_LORESERVE)
670 SectionIndexTable->addIndex(Sym->DefinedIn->Index);
671 else
672 SectionIndexTable->addIndex(SHN_UNDEF);
673 }
674}
675
Petr Hosek79cee9e2017-08-29 02:12:03 +0000676const Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) const {
677 if (Symbols.size() <= Index)
James Henderson5316a0d2019-05-22 13:23:26 +0000678 error("invalid symbol index: " + Twine(Index));
Petr Hosek79cee9e2017-08-29 02:12:03 +0000679 return Symbols[Index].get();
680}
681
Paul Semel99dda0b2018-05-25 11:01:25 +0000682Symbol *SymbolTableSection::getSymbolByIndex(uint32_t Index) {
683 return const_cast<Symbol *>(
684 static_cast<const SymbolTableSection *>(this)->getSymbolByIndex(Index));
685}
686
Petr Hosek79cee9e2017-08-29 02:12:03 +0000687template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000688void ELFSectionWriter<ELFT>::visit(const SymbolTableSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000689 Elf_Sym *Sym = reinterpret_cast<Elf_Sym *>(Out.getBufferStart() + Sec.Offset);
Petr Hosek79cee9e2017-08-29 02:12:03 +0000690 // Loop though symbols setting each entry of the symbol table.
George Rimare98a8f72019-05-23 09:18:57 +0000691 for (const std::unique_ptr<Symbol> &Symbol : Sec.Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +0000692 Sym->st_name = Symbol->NameIndex;
693 Sym->st_value = Symbol->Value;
694 Sym->st_size = Symbol->Size;
Jake Ehrlich30d927a2018-01-02 23:01:24 +0000695 Sym->st_other = Symbol->Visibility;
Petr Hosek79cee9e2017-08-29 02:12:03 +0000696 Sym->setBinding(Symbol->Binding);
697 Sym->setType(Symbol->Type);
Petr Hosekec2b3fc2017-09-07 23:02:50 +0000698 Sym->st_shndx = Symbol->getShndx();
Petr Hosek79cee9e2017-08-29 02:12:03 +0000699 ++Sym;
700 }
701}
702
Jake Ehrlich76e91102018-01-25 22:46:17 +0000703void SymbolTableSection::accept(SectionVisitor &Visitor) const {
704 Visitor.visit(*this);
705}
706
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000707void SymbolTableSection::accept(MutableSectionVisitor &Visitor) {
708 Visitor.visit(*this);
709}
710
George Rimar79fb8582019-02-27 11:18:27 +0000711Error RelocationSection::removeSectionReferences(
James Henderson66a9d0f2019-04-18 09:13:30 +0000712 bool AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +0000713 function_ref<bool(const SectionBase *)> ToRemove) {
James Henderson66a9d0f2019-04-18 09:13:30 +0000714 if (ToRemove(Symbols)) {
715 if (!AllowBrokenLinks)
716 return createStringError(
717 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000718 "symbol table '%s' cannot be removed because it is "
719 "referenced by the relocation section '%s'",
James Henderson66a9d0f2019-04-18 09:13:30 +0000720 Symbols->Name.data(), this->Name.data());
721 Symbols = nullptr;
722 }
George Rimar79fb8582019-02-27 11:18:27 +0000723
724 for (const Relocation &R : Relocations) {
725 if (!R.RelocSymbol->DefinedIn || !ToRemove(R.RelocSymbol->DefinedIn))
726 continue;
George Rimarbf447a52019-02-28 08:21:50 +0000727 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000728 "section '%s' cannot be removed: (%s+0x%" PRIx64
George Rimarbf447a52019-02-28 08:21:50 +0000729 ") has relocation against symbol '%s'",
730 R.RelocSymbol->DefinedIn->Name.data(),
731 SecToApplyRel->Name.data(), R.Offset,
732 R.RelocSymbol->Name.c_str());
George Rimar79fb8582019-02-27 11:18:27 +0000733 }
734
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000735 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000736}
737
738template <class SymTabType>
739void RelocSectionWithSymtabBase<SymTabType>::initialize(
740 SectionTableRef SecTable) {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000741 if (Link != SHN_UNDEF)
742 setSymTab(SecTable.getSectionOfType<SymTabType>(
743 Link,
744 "Link field value " + Twine(Link) + " in section " + Name +
745 " is invalid",
746 "Link field value " + Twine(Link) + " in section " + Name +
747 " is not a symbol table"));
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000748
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000749 if (Info != SHN_UNDEF)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000750 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
751 " in section " + Name +
752 " is invalid"));
James Y Knight2ea995a2017-09-26 22:44:01 +0000753 else
754 setSection(nullptr);
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000755}
756
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000757template <class SymTabType>
758void RelocSectionWithSymtabBase<SymTabType>::finalize() {
Jordan Rupprechtec277a82018-09-04 22:28:49 +0000759 this->Link = Symbols ? Symbols->Index : 0;
760
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000761 if (SecToApplyRel != nullptr)
762 this->Info = SecToApplyRel->Index;
Petr Hosekd7df9b22017-09-06 23:41:02 +0000763}
764
765template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000766static void setAddend(Elf_Rel_Impl<ELFT, false> &Rel, uint64_t Addend) {}
Petr Hosekd7df9b22017-09-06 23:41:02 +0000767
768template <class ELFT>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000769static void setAddend(Elf_Rel_Impl<ELFT, true> &Rela, uint64_t Addend) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000770 Rela.r_addend = Addend;
771}
772
Jake Ehrlich76e91102018-01-25 22:46:17 +0000773template <class RelRange, class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +0000774static void writeRel(const RelRange &Relocations, T *Buf) {
Petr Hosekd7df9b22017-09-06 23:41:02 +0000775 for (const auto &Reloc : Relocations) {
776 Buf->r_offset = Reloc.Offset;
777 setAddend(*Buf, Reloc.Addend);
778 Buf->setSymbolAndType(Reloc.RelocSymbol->Index, Reloc.Type, false);
779 ++Buf;
780 }
781}
782
783template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000784void ELFSectionWriter<ELFT>::visit(const RelocationSection &Sec) {
785 uint8_t *Buf = Out.getBufferStart() + Sec.Offset;
786 if (Sec.Type == SHT_REL)
787 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rel *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000788 else
Jake Ehrlich76e91102018-01-25 22:46:17 +0000789 writeRel(Sec.Relocations, reinterpret_cast<Elf_Rela *>(Buf));
Petr Hosekd7df9b22017-09-06 23:41:02 +0000790}
791
Jake Ehrlich76e91102018-01-25 22:46:17 +0000792void RelocationSection::accept(SectionVisitor &Visitor) const {
793 Visitor.visit(*this);
794}
795
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000796void RelocationSection::accept(MutableSectionVisitor &Visitor) {
797 Visitor.visit(*this);
798}
799
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000800Error RelocationSection::removeSymbols(
Paul Semel4246a462018-05-09 21:36:54 +0000801 function_ref<bool(const Symbol &)> ToRemove) {
802 for (const Relocation &Reloc : Relocations)
803 if (ToRemove(*Reloc.RelocSymbol))
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000804 return createStringError(
805 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000806 "not stripping symbol '%s' because it is named in a relocation",
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000807 Reloc.RelocSymbol->Name.data());
808 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000809}
810
Paul Semel99dda0b2018-05-25 11:01:25 +0000811void RelocationSection::markSymbols() {
812 for (const Relocation &Reloc : Relocations)
813 Reloc.RelocSymbol->Referenced = true;
814}
815
George Rimard8a5c6c2019-03-11 11:01:24 +0000816void RelocationSection::replaceSectionReferences(
817 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
818 // Update the target section if it was replaced.
819 if (SectionBase *To = FromTo.lookup(SecToApplyRel))
820 SecToApplyRel = To;
George Rimard8a5c6c2019-03-11 11:01:24 +0000821}
822
Jake Ehrlich76e91102018-01-25 22:46:17 +0000823void SectionWriter::visit(const DynamicRelocationSection &Sec) {
George Rimare98a8f72019-05-23 09:18:57 +0000824 llvm::copy(Sec.Contents, Out.getBufferStart() + Sec.Offset);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000825}
826
827void DynamicRelocationSection::accept(SectionVisitor &Visitor) const {
828 Visitor.visit(*this);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +0000829}
830
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000831void DynamicRelocationSection::accept(MutableSectionVisitor &Visitor) {
George Rimare98a8f72019-05-23 09:18:57 +0000832 Visitor.visit(*this);
833}
834
835Error DynamicRelocationSection::removeSectionReferences(
836 bool AllowBrokenLinks, function_ref<bool(const SectionBase *)> ToRemove) {
837 if (ToRemove(Symbols)) {
838 if (!AllowBrokenLinks)
839 return createStringError(
840 llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000841 "symbol table '%s' cannot be removed because it is "
842 "referenced by the relocation section '%s'",
George Rimare98a8f72019-05-23 09:18:57 +0000843 Symbols->Name.data(), this->Name.data());
844 Symbols = nullptr;
845 }
846
847 // SecToApplyRel contains a section referenced by sh_info field. It keeps
848 // a section to which the relocation section applies. When we remove any
849 // sections we also remove their relocation sections. Since we do that much
850 // earlier, this assert should never be triggered.
851 assert(!SecToApplyRel || !ToRemove(SecToApplyRel));
852 return Error::success();
853}
854
855Error Section::removeSectionReferences(bool AllowBrokenDependency,
856 function_ref<bool(const SectionBase *)> ToRemove) {
857 if (ToRemove(LinkSection)) {
James Henderson66a9d0f2019-04-18 09:13:30 +0000858 if (!AllowBrokenDependency)
859 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000860 "section '%s' cannot be removed because it is "
861 "referenced by the section '%s'",
James Henderson66a9d0f2019-04-18 09:13:30 +0000862 LinkSection->Name.data(), this->Name.data());
863 LinkSection = nullptr;
864 }
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000865 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +0000866}
867
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000868void GroupSection::finalize() {
869 this->Info = Sym->Index;
870 this->Link = SymTab->Index;
871}
872
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000873Error GroupSection::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
874 if (ToRemove(*Sym))
875 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +0000876 "symbol '%s' cannot be removed because it is "
877 "referenced by the section '%s[%d]'",
Jordan Rupprecht971d47622019-02-01 15:20:36 +0000878 Sym->Name.data(), this->Name.data(), this->Index);
879 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +0000880}
881
Paul Semel99dda0b2018-05-25 11:01:25 +0000882void GroupSection::markSymbols() {
883 if (Sym)
884 Sym->Referenced = true;
885}
886
George Rimar27257172019-03-24 14:41:45 +0000887void GroupSection::replaceSectionReferences(
888 const DenseMap<SectionBase *, SectionBase *> &FromTo) {
889 for (SectionBase *&Sec : GroupMembers)
890 if (SectionBase *To = FromTo.lookup(Sec))
891 Sec = To;
892}
893
Alexander Shaposhnikov52db4332018-04-20 20:46:04 +0000894void Section::initialize(SectionTableRef SecTable) {
George Rimare98a8f72019-05-23 09:18:57 +0000895 if (Link == ELF::SHN_UNDEF)
896 return;
897 LinkSection =
898 SecTable.getSection(Link, "Link field value " + Twine(Link) +
899 " in section " + Name + " is invalid");
900 if (LinkSection->Type == ELF::SHT_SYMTAB)
901 LinkSection = nullptr;
Jake Ehrliche5d424b2017-09-20 17:11:58 +0000902}
903
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +0000904void Section::finalize() { this->Link = LinkSection ? LinkSection->Index : 0; }
Jake Ehrlichf5a43772017-09-25 20:37:28 +0000905
James Henderson9df38832019-05-14 10:59:04 +0000906void GnuDebugLinkSection::init(StringRef File) {
Alexander Richardson6c859922018-02-19 19:53:44 +0000907 FileName = sys::path::filename(File);
908 // The format for the .gnu_debuglink starts with the file name and is
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000909 // followed by a null terminator and then the CRC32 of the file. The CRC32
910 // should be 4 byte aligned. So we add the FileName size, a 1 for the null
911 // byte, and then finally push the size to alignment and add 4.
912 Size = alignTo(FileName.size() + 1, 4) + 4;
913 // The CRC32 will only be aligned if we align the whole section.
914 Align = 4;
915 Type = ELF::SHT_PROGBITS;
916 Name = ".gnu_debuglink";
917 // For sections not found in segments, OriginalOffset is only used to
918 // establish the order that sections should go in. By using the maximum
919 // possible offset we cause this section to wind up at the end.
920 OriginalOffset = std::numeric_limits<uint64_t>::max();
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000921}
922
James Henderson9df38832019-05-14 10:59:04 +0000923GnuDebugLinkSection::GnuDebugLinkSection(StringRef File,
924 uint32_t PrecomputedCRC)
925 : FileName(File), CRC32(PrecomputedCRC) {
926 init(File);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000927}
928
929template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +0000930void ELFSectionWriter<ELFT>::visit(const GnuDebugLinkSection &Sec) {
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000931 unsigned char *Buf = Out.getBufferStart() + Sec.Offset;
Jake Ehrlich76e91102018-01-25 22:46:17 +0000932 Elf_Word *CRC =
933 reinterpret_cast<Elf_Word *>(Buf + Sec.Size - sizeof(Elf_Word));
934 *CRC = Sec.CRC32;
Fangrui Song5ed0a8b2019-03-29 08:08:20 +0000935 llvm::copy(Sec.FileName, Buf);
Jake Ehrlich76e91102018-01-25 22:46:17 +0000936}
937
938void GnuDebugLinkSection::accept(SectionVisitor &Visitor) const {
939 Visitor.visit(*this);
Jake Ehrlichea07d3c2018-01-25 22:15:14 +0000940}
941
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000942void GnuDebugLinkSection::accept(MutableSectionVisitor &Visitor) {
943 Visitor.visit(*this);
944}
945
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000946template <class ELFT>
947void ELFSectionWriter<ELFT>::visit(const GroupSection &Sec) {
948 ELF::Elf32_Word *Buf =
949 reinterpret_cast<ELF::Elf32_Word *>(Out.getBufferStart() + Sec.Offset);
950 *Buf++ = Sec.FlagWord;
George Rimare98a8f72019-05-23 09:18:57 +0000951 for (SectionBase *S : Sec.GroupMembers)
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +0000952 support::endian::write32<ELFT::TargetEndianness>(Buf++, S->Index);
953}
954
955void GroupSection::accept(SectionVisitor &Visitor) const {
956 Visitor.visit(*this);
957}
958
Jordan Rupprecht1f821762019-01-03 17:45:30 +0000959void GroupSection::accept(MutableSectionVisitor &Visitor) {
960 Visitor.visit(*this);
961}
962
Petr Hosek05a04cb2017-08-01 00:33:58 +0000963// Returns true IFF a section is wholly inside the range of a segment
964static bool sectionWithinSegment(const SectionBase &Section,
965 const Segment &Segment) {
966 // If a section is empty it should be treated like it has a size of 1. This is
967 // to clarify the case when an empty section lies on a boundary between two
968 // segments and ensures that the section "belongs" to the second segment and
969 // not the first.
970 uint64_t SecSize = Section.Size ? Section.Size : 1;
Peter Collingbourneab09cca2019-05-24 00:21:46 +0000971
972 if (Section.Type == SHT_NOBITS) {
973 if (!(Section.Flags & SHF_ALLOC))
974 return false;
975
976 bool SectionIsTLS = Section.Flags & SHF_TLS;
977 bool SegmentIsTLS = Segment.Type == PT_TLS;
978 if (SectionIsTLS != SegmentIsTLS)
979 return false;
980
981 return Segment.VAddr <= Section.Addr &&
982 Segment.VAddr + Segment.MemSize >= Section.Addr + SecSize;
983 }
984
Petr Hosek05a04cb2017-08-01 00:33:58 +0000985 return Segment.Offset <= Section.OriginalOffset &&
986 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
987}
988
Jake Ehrlichd246b0a2017-09-19 21:37:35 +0000989// Returns true IFF a segment's original offset is inside of another segment's
990// range.
991static bool segmentOverlapsSegment(const Segment &Child,
992 const Segment &Parent) {
993
994 return Parent.OriginalOffset <= Child.OriginalOffset &&
995 Parent.OriginalOffset + Parent.FileSize > Child.OriginalOffset;
996}
997
Jake Ehrlich46814be2018-01-22 19:27:30 +0000998static bool compareSegmentsByOffset(const Segment *A, const Segment *B) {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +0000999 // Any segment without a parent segment should come before a segment
1000 // that has a parent segment.
1001 if (A->OriginalOffset < B->OriginalOffset)
1002 return true;
1003 if (A->OriginalOffset > B->OriginalOffset)
1004 return false;
1005 return A->Index < B->Index;
1006}
1007
Jake Ehrlich46814be2018-01-22 19:27:30 +00001008static bool compareSegmentsByPAddr(const Segment *A, const Segment *B) {
1009 if (A->PAddr < B->PAddr)
1010 return true;
1011 if (A->PAddr > B->PAddr)
1012 return false;
1013 return A->Index < B->Index;
1014}
1015
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001016void BinaryELFBuilder::initFileHeader() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001017 Obj->Flags = 0x0;
1018 Obj->Type = ET_REL;
George Rimar3ac20a92018-12-20 10:59:52 +00001019 Obj->OSABI = ELFOSABI_NONE;
George Rimar4ded7732018-12-20 10:51:42 +00001020 Obj->ABIVersion = 0;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001021 Obj->Entry = 0x0;
1022 Obj->Machine = EMachine;
1023 Obj->Version = 1;
1024}
1025
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001026void BinaryELFBuilder::initHeaderSegment() { Obj->ElfHdrSegment.Index = 0; }
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001027
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001028StringTableSection *BinaryELFBuilder::addStrTab() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001029 auto &StrTab = Obj->addSection<StringTableSection>();
1030 StrTab.Name = ".strtab";
1031
1032 Obj->SectionNames = &StrTab;
1033 return &StrTab;
1034}
1035
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001036SymbolTableSection *BinaryELFBuilder::addSymTab(StringTableSection *StrTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001037 auto &SymTab = Obj->addSection<SymbolTableSection>();
1038
1039 SymTab.Name = ".symtab";
1040 SymTab.Link = StrTab->Index;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001041
1042 // The symbol table always needs a null symbol
1043 SymTab.addSymbol("", 0, 0, nullptr, 0, 0, 0, 0);
1044
1045 Obj->SymbolTable = &SymTab;
1046 return &SymTab;
1047}
1048
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001049void BinaryELFBuilder::addData(SymbolTableSection *SymTab) {
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001050 auto Data = ArrayRef<uint8_t>(
1051 reinterpret_cast<const uint8_t *>(MemBuf->getBufferStart()),
1052 MemBuf->getBufferSize());
1053 auto &DataSection = Obj->addSection<Section>(Data);
1054 DataSection.Name = ".data";
1055 DataSection.Type = ELF::SHT_PROGBITS;
1056 DataSection.Size = Data.size();
1057 DataSection.Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1058
1059 std::string SanitizedFilename = MemBuf->getBufferIdentifier().str();
1060 std::replace_if(std::begin(SanitizedFilename), std::end(SanitizedFilename),
Fangrui Song32a34e62018-11-01 16:02:12 +00001061 [](char C) { return !isalnum(C); }, '_');
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001062 Twine Prefix = Twine("_binary_") + SanitizedFilename;
1063
1064 SymTab->addSymbol(Prefix + "_start", STB_GLOBAL, STT_NOTYPE, &DataSection,
1065 /*Value=*/0, STV_DEFAULT, 0, 0);
1066 SymTab->addSymbol(Prefix + "_end", STB_GLOBAL, STT_NOTYPE, &DataSection,
1067 /*Value=*/DataSection.Size, STV_DEFAULT, 0, 0);
1068 SymTab->addSymbol(Prefix + "_size", STB_GLOBAL, STT_NOTYPE, nullptr,
1069 /*Value=*/DataSection.Size, STV_DEFAULT, SHN_ABS, 0);
1070}
1071
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001072void BinaryELFBuilder::initSections() {
George Rimare98a8f72019-05-23 09:18:57 +00001073 for (SectionBase &Section : Obj->sections())
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001074 Section.initialize(Obj->sections());
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001075}
1076
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001077std::unique_ptr<Object> BinaryELFBuilder::build() {
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001078 initFileHeader();
1079 initHeaderSegment();
George Rimare98a8f72019-05-23 09:18:57 +00001080
1081 SymbolTableSection *SymTab = addSymTab(addStrTab());
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001082 initSections();
1083 addData(SymTab);
1084
1085 return std::move(Obj);
1086}
1087
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001088template <class ELFT> void ELFBuilder<ELFT>::setParentSegment(Segment &Child) {
George Rimare98a8f72019-05-23 09:18:57 +00001089 for (Segment &Parent : Obj.segments()) {
Jake Ehrlich6452b112018-02-14 23:31:33 +00001090 // Every segment will overlap with itself but we don't want a segment to
1091 // be it's own parent so we avoid that situation.
1092 if (&Child != &Parent && segmentOverlapsSegment(Child, Parent)) {
1093 // We want a canonical "most parental" segment but this requires
1094 // inspecting the ParentSegment.
1095 if (compareSegmentsByOffset(&Parent, &Child))
1096 if (Child.ParentSegment == nullptr ||
1097 compareSegmentsByOffset(&Parent, Child.ParentSegment)) {
1098 Child.ParentSegment = &Parent;
1099 }
1100 }
1101 }
1102}
1103
Jake Ehrlich76e91102018-01-25 22:46:17 +00001104template <class ELFT> void ELFBuilder<ELFT>::readProgramHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001105 uint32_t Index = 0;
1106 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
George Rimar33044a72019-06-07 08:34:18 +00001107 if (Phdr.p_offset + Phdr.p_filesz > ElfFile.getBufSize())
1108 error("program header with offset 0x" + Twine::utohexstr(Phdr.p_offset) +
1109 " and file size 0x" + Twine::utohexstr(Phdr.p_filesz) +
1110 " goes past the end of the file");
1111
James Henderson1f448142019-03-25 16:36:26 +00001112 ArrayRef<uint8_t> Data{ElfFile.base() + Phdr.p_offset,
1113 (size_t)Phdr.p_filesz};
1114 Segment &Seg = Obj.addSegment(Data);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001115 Seg.Type = Phdr.p_type;
1116 Seg.Flags = Phdr.p_flags;
Petr Hosek3f383832017-08-26 01:32:20 +00001117 Seg.OriginalOffset = Phdr.p_offset;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001118 Seg.Offset = Phdr.p_offset;
1119 Seg.VAddr = Phdr.p_vaddr;
1120 Seg.PAddr = Phdr.p_paddr;
1121 Seg.FileSize = Phdr.p_filesz;
1122 Seg.MemSize = Phdr.p_memsz;
1123 Seg.Align = Phdr.p_align;
1124 Seg.Index = Index++;
George Rimare98a8f72019-05-23 09:18:57 +00001125 for (SectionBase &Section : Obj.sections()) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001126 if (sectionWithinSegment(Section, Seg)) {
1127 Seg.addSection(&Section);
1128 if (!Section.ParentSegment ||
1129 Section.ParentSegment->Offset > Seg.Offset) {
1130 Section.ParentSegment = &Seg;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001131 }
1132 }
1133 }
1134 }
Jake Ehrlich6452b112018-02-14 23:31:33 +00001135
1136 auto &ElfHdr = Obj.ElfHdrSegment;
Jake Ehrlich6452b112018-02-14 23:31:33 +00001137 ElfHdr.Index = Index++;
1138
1139 const auto &Ehdr = *ElfFile.getHeader();
1140 auto &PrHdr = Obj.ProgramHdrSegment;
1141 PrHdr.Type = PT_PHDR;
1142 PrHdr.Flags = 0;
1143 // The spec requires us to have p_vaddr % p_align == p_offset % p_align.
1144 // Whereas this works automatically for ElfHdr, here OriginalOffset is
1145 // always non-zero and to ensure the equation we assign the same value to
1146 // VAddr as well.
1147 PrHdr.OriginalOffset = PrHdr.Offset = PrHdr.VAddr = Ehdr.e_phoff;
1148 PrHdr.PAddr = 0;
1149 PrHdr.FileSize = PrHdr.MemSize = Ehdr.e_phentsize * Ehdr.e_phnum;
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001150 // The spec requires us to naturally align all the fields.
Jake Ehrlich6452b112018-02-14 23:31:33 +00001151 PrHdr.Align = sizeof(Elf_Addr);
1152 PrHdr.Index = Index++;
1153
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001154 // Now we do an O(n^2) loop through the segments in order to match up
1155 // segments.
George Rimare98a8f72019-05-23 09:18:57 +00001156 for (Segment &Child : Obj.segments())
Jake Ehrlich6452b112018-02-14 23:31:33 +00001157 setParentSegment(Child);
1158 setParentSegment(ElfHdr);
1159 setParentSegment(PrHdr);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001160}
1161
1162template <class ELFT>
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001163void ELFBuilder<ELFT>::initGroupSection(GroupSection *GroupSec) {
George Rimar0a5d4b82019-03-24 13:31:08 +00001164 if (GroupSec->Align % sizeof(ELF::Elf32_Word) != 0)
James Henderson5316a0d2019-05-22 13:23:26 +00001165 error("invalid alignment " + Twine(GroupSec->Align) + " of group section '" +
1166 GroupSec->Name + "'");
George Rimare98a8f72019-05-23 09:18:57 +00001167 SectionTableRef SecTable = Obj.sections();
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001168 auto SymTab = SecTable.template getSectionOfType<SymbolTableSection>(
1169 GroupSec->Link,
James Henderson5316a0d2019-05-22 13:23:26 +00001170 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1171 GroupSec->Name + "' is invalid",
1172 "link field value '" + Twine(GroupSec->Link) + "' in section '" +
1173 GroupSec->Name + "' is not a symbol table");
George Rimare98a8f72019-05-23 09:18:57 +00001174 Symbol *Sym = SymTab->getSymbolByIndex(GroupSec->Info);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001175 if (!Sym)
James Henderson5316a0d2019-05-22 13:23:26 +00001176 error("info field value '" + Twine(GroupSec->Info) + "' in section '" +
1177 GroupSec->Name + "' is not a valid symbol index");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001178 GroupSec->setSymTab(SymTab);
1179 GroupSec->setSymbol(Sym);
1180 if (GroupSec->Contents.size() % sizeof(ELF::Elf32_Word) ||
1181 GroupSec->Contents.empty())
James Henderson5316a0d2019-05-22 13:23:26 +00001182 error("the content of the section " + GroupSec->Name + " is malformed");
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001183 const ELF::Elf32_Word *Word =
1184 reinterpret_cast<const ELF::Elf32_Word *>(GroupSec->Contents.data());
1185 const ELF::Elf32_Word *End =
1186 Word + GroupSec->Contents.size() / sizeof(ELF::Elf32_Word);
1187 GroupSec->setFlagWord(*Word++);
1188 for (; Word != End; ++Word) {
1189 uint32_t Index = support::endian::read32<ELFT::TargetEndianness>(Word);
1190 GroupSec->addMember(SecTable.getSection(
James Henderson5316a0d2019-05-22 13:23:26 +00001191 Index, "group member index " + Twine(Index) + " in section '" +
1192 GroupSec->Name + "' is invalid"));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001193 }
1194}
1195
1196template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001197void ELFBuilder<ELFT>::initSymbolTable(SymbolTableSection *SymTab) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001198 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
1199 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001200 ArrayRef<Elf_Word> ShndxData;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001201
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001202 auto Symbols = unwrapOrError(ElfFile.symbols(&Shdr));
1203 for (const auto &Sym : Symbols) {
Petr Hosek79cee9e2017-08-29 02:12:03 +00001204 SectionBase *DefSection = nullptr;
1205 StringRef Name = unwrapOrError(Sym.getName(StrTabData));
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001206
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001207 if (Sym.st_shndx == SHN_XINDEX) {
1208 if (SymTab->getShndxTable() == nullptr)
James Henderson5316a0d2019-05-22 13:23:26 +00001209 error("symbol '" + Name +
1210 "' has index SHN_XINDEX but no SHT_SYMTAB_SHNDX section exists");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001211 if (ShndxData.data() == nullptr) {
1212 const Elf_Shdr &ShndxSec =
1213 *unwrapOrError(ElfFile.getSection(SymTab->getShndxTable()->Index));
1214 ShndxData = unwrapOrError(
1215 ElfFile.template getSectionContentsAsArray<Elf_Word>(&ShndxSec));
1216 if (ShndxData.size() != Symbols.size())
James Henderson5316a0d2019-05-22 13:23:26 +00001217 error("symbol section index table does not have the same number of "
1218 "entries as the symbol table");
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001219 }
1220 Elf_Word Index = ShndxData[&Sym - Symbols.begin()];
1221 DefSection = Obj.sections().getSection(
1222 Index,
James Henderson5316a0d2019-05-22 13:23:26 +00001223 "symbol '" + Name + "' has invalid section index " + Twine(Index));
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001224 } else if (Sym.st_shndx >= SHN_LORESERVE) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001225 if (!isValidReservedSectionIndex(Sym.st_shndx, Obj.Machine)) {
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001226 error(
James Henderson5316a0d2019-05-22 13:23:26 +00001227 "symbol '" + Name +
Petr Hosekec2b3fc2017-09-07 23:02:50 +00001228 "' has unsupported value greater than or equal to SHN_LORESERVE: " +
1229 Twine(Sym.st_shndx));
1230 }
1231 } else if (Sym.st_shndx != SHN_UNDEF) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001232 DefSection = Obj.sections().getSection(
James Henderson5316a0d2019-05-22 13:23:26 +00001233 Sym.st_shndx, "symbol '" + Name +
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001234 "' is defined has invalid section index " +
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001235 Twine(Sym.st_shndx));
Petr Hosek79cee9e2017-08-29 02:12:03 +00001236 }
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001237
Petr Hosek79cee9e2017-08-29 02:12:03 +00001238 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
Jake Ehrlich30d927a2018-01-02 23:01:24 +00001239 Sym.getValue(), Sym.st_other, Sym.st_shndx, Sym.st_size);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001240 }
1241}
1242
1243template <class ELFT>
Petr Hosekd7df9b22017-09-06 23:41:02 +00001244static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, false> &Rel) {}
1245
1246template <class ELFT>
1247static void getAddend(uint64_t &ToSet, const Elf_Rel_Impl<ELFT, true> &Rela) {
1248 ToSet = Rela.r_addend;
1249}
1250
Jake Ehrlich76e91102018-01-25 22:46:17 +00001251template <class T>
Puyan Lotfic4846a52018-07-16 22:17:05 +00001252static void initRelocations(RelocationSection *Relocs,
1253 SymbolTableSection *SymbolTable, T RelRange) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001254 for (const auto &Rel : RelRange) {
1255 Relocation ToAdd;
1256 ToAdd.Offset = Rel.r_offset;
1257 getAddend(ToAdd.Addend, Rel);
1258 ToAdd.Type = Rel.getType(false);
Paul Semel31a212d2018-05-22 01:04:36 +00001259 ToAdd.RelocSymbol = SymbolTable->getSymbolByIndex(Rel.getSymbol(false));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001260 Relocs->addRelocation(ToAdd);
1261 }
1262}
1263
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001264SectionBase *SectionTableRef::getSection(uint32_t Index, Twine ErrMsg) {
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001265 if (Index == SHN_UNDEF || Index > Sections.size())
1266 error(ErrMsg);
1267 return Sections[Index - 1].get();
1268}
1269
1270template <class T>
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001271T *SectionTableRef::getSectionOfType(uint32_t Index, Twine IndexErrMsg,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001272 Twine TypeErrMsg) {
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00001273 if (T *Sec = dyn_cast<T>(getSection(Index, IndexErrMsg)))
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001274 return Sec;
1275 error(TypeErrMsg);
1276}
1277
Petr Hosekd7df9b22017-09-06 23:41:02 +00001278template <class ELFT>
Jake Ehrlich76e91102018-01-25 22:46:17 +00001279SectionBase &ELFBuilder<ELFT>::makeSection(const Elf_Shdr &Shdr) {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001280 ArrayRef<uint8_t> Data;
1281 switch (Shdr.sh_type) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001282 case SHT_REL:
1283 case SHT_RELA:
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001284 if (Shdr.sh_flags & SHF_ALLOC) {
1285 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001286 return Obj.addSection<DynamicRelocationSection>(Data);
Jake Ehrlich9f1a3902017-09-26 18:02:25 +00001287 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001288 return Obj.addSection<RelocationSection>();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001289 case SHT_STRTAB:
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001290 // If a string table is allocated we don't want to mess with it. That would
1291 // mean altering the memory image. There are no special link types or
1292 // anything so we can just use a Section.
1293 if (Shdr.sh_flags & SHF_ALLOC) {
1294 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001295 return Obj.addSection<Section>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001296 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001297 return Obj.addSection<StringTableSection>();
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001298 case SHT_HASH:
1299 case SHT_GNU_HASH:
1300 // Hash tables should refer to SHT_DYNSYM which we're not going to change.
1301 // Because of this we don't need to mess with the hash tables either.
1302 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001303 return Obj.addSection<Section>(Data);
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001304 case SHT_GROUP:
1305 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
1306 return Obj.addSection<GroupSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001307 case SHT_DYNSYM:
1308 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001309 return Obj.addSection<DynamicSymbolTableSection>(Data);
Jake Ehrliche5d424b2017-09-20 17:11:58 +00001310 case SHT_DYNAMIC:
1311 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001312 return Obj.addSection<DynamicSection>(Data);
Petr Hosek79cee9e2017-08-29 02:12:03 +00001313 case SHT_SYMTAB: {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001314 auto &SymTab = Obj.addSection<SymbolTableSection>();
1315 Obj.SymbolTable = &SymTab;
1316 return SymTab;
Petr Hosek79cee9e2017-08-29 02:12:03 +00001317 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001318 case SHT_SYMTAB_SHNDX: {
1319 auto &ShndxSection = Obj.addSection<SectionIndexSection>();
1320 Obj.SectionIndexTable = &ShndxSection;
1321 return ShndxSection;
1322 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001323 case SHT_NOBITS:
Jake Ehrlich76e91102018-01-25 22:46:17 +00001324 return Obj.addSection<Section>(Data);
Puyan Lotfiaf048642018-10-01 10:29:41 +00001325 default: {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001326 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
Puyan Lotfiaf048642018-10-01 10:29:41 +00001327
George Rimarf2eb8ca2019-03-06 14:01:54 +00001328 StringRef Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1329 if (Name.startswith(".zdebug") || (Shdr.sh_flags & ELF::SHF_COMPRESSED)) {
Puyan Lotfiaf048642018-10-01 10:29:41 +00001330 uint64_t DecompressedSize, DecompressedAlign;
1331 std::tie(DecompressedSize, DecompressedAlign) =
1332 getDecompressedSizeAndAlignment<ELFT>(Data);
1333 return Obj.addSection<CompressedSection>(Data, DecompressedSize,
1334 DecompressedAlign);
1335 }
1336
Jake Ehrlich76e91102018-01-25 22:46:17 +00001337 return Obj.addSection<Section>(Data);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001338 }
Puyan Lotfiaf048642018-10-01 10:29:41 +00001339 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001340}
1341
Jake Ehrlich76e91102018-01-25 22:46:17 +00001342template <class ELFT> void ELFBuilder<ELFT>::readSectionHeaders() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001343 uint32_t Index = 0;
1344 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
1345 if (Index == 0) {
1346 ++Index;
1347 continue;
1348 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001349 auto &Sec = makeSection(Shdr);
1350 Sec.Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
1351 Sec.Type = Shdr.sh_type;
1352 Sec.Flags = Shdr.sh_flags;
1353 Sec.Addr = Shdr.sh_addr;
1354 Sec.Offset = Shdr.sh_offset;
1355 Sec.OriginalOffset = Shdr.sh_offset;
1356 Sec.Size = Shdr.sh_size;
1357 Sec.Link = Shdr.sh_link;
1358 Sec.Info = Shdr.sh_info;
1359 Sec.Align = Shdr.sh_addralign;
1360 Sec.EntrySize = Shdr.sh_entsize;
1361 Sec.Index = Index++;
Paul Semela42dec72018-08-09 17:05:21 +00001362 Sec.OriginalData =
1363 ArrayRef<uint8_t>(ElfFile.base() + Shdr.sh_offset,
1364 (Shdr.sh_type == SHT_NOBITS) ? 0 : Shdr.sh_size);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001365 }
Petr Hosek79cee9e2017-08-29 02:12:03 +00001366
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001367 // If a section index table exists we'll need to initialize it before we
1368 // initialize the symbol table because the symbol table might need to
1369 // reference it.
1370 if (Obj.SectionIndexTable)
1371 Obj.SectionIndexTable->initialize(Obj.sections());
1372
Petr Hosek79cee9e2017-08-29 02:12:03 +00001373 // Now that all of the sections have been added we can fill out some extra
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001374 // details about symbol tables. We need the symbol table filled out before
1375 // any relocations.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001376 if (Obj.SymbolTable) {
1377 Obj.SymbolTable->initialize(Obj.sections());
1378 initSymbolTable(Obj.SymbolTable);
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001379 }
Petr Hosekd7df9b22017-09-06 23:41:02 +00001380
1381 // Now that all sections and symbols have been added we can add
1382 // relocations that reference symbols and set the link and info fields for
1383 // relocation sections.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001384 for (auto &Section : Obj.sections()) {
1385 if (&Section == Obj.SymbolTable)
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001386 continue;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001387 Section.initialize(Obj.sections());
1388 if (auto RelSec = dyn_cast<RelocationSection>(&Section)) {
Petr Hosekd7df9b22017-09-06 23:41:02 +00001389 auto Shdr = unwrapOrError(ElfFile.sections()).begin() + RelSec->Index;
1390 if (RelSec->Type == SHT_REL)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001391 initRelocations(RelSec, Obj.SymbolTable,
1392 unwrapOrError(ElfFile.rels(Shdr)));
Petr Hosekd7df9b22017-09-06 23:41:02 +00001393 else
Jake Ehrlich76e91102018-01-25 22:46:17 +00001394 initRelocations(RelSec, Obj.SymbolTable,
Jake Ehrlichf5a43772017-09-25 20:37:28 +00001395 unwrapOrError(ElfFile.relas(Shdr)));
Alexander Shaposhnikov6ecc6e62018-03-21 19:53:44 +00001396 } else if (auto GroupSec = dyn_cast<GroupSection>(&Section)) {
1397 initGroupSection(GroupSec);
Petr Hosekd7df9b22017-09-06 23:41:02 +00001398 }
1399 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001400}
1401
Jake Ehrlich76e91102018-01-25 22:46:17 +00001402template <class ELFT> void ELFBuilder<ELFT>::build() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001403 const auto &Ehdr = *ElfFile.getHeader();
1404
George Rimar4ded7732018-12-20 10:51:42 +00001405 Obj.OSABI = Ehdr.e_ident[EI_OSABI];
1406 Obj.ABIVersion = Ehdr.e_ident[EI_ABIVERSION];
Jake Ehrlich76e91102018-01-25 22:46:17 +00001407 Obj.Type = Ehdr.e_type;
1408 Obj.Machine = Ehdr.e_machine;
1409 Obj.Version = Ehdr.e_version;
1410 Obj.Entry = Ehdr.e_entry;
1411 Obj.Flags = Ehdr.e_flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001412
Jake Ehrlich76e91102018-01-25 22:46:17 +00001413 readSectionHeaders();
1414 readProgramHeaders();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001415
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001416 uint32_t ShstrIndex = Ehdr.e_shstrndx;
1417 if (ShstrIndex == SHN_XINDEX)
1418 ShstrIndex = unwrapOrError(ElfFile.getSection(0))->sh_link;
1419
James Henderson38cb2382019-04-02 14:11:13 +00001420 if (ShstrIndex == SHN_UNDEF)
1421 Obj.HadShdrs = false;
1422 else
1423 Obj.SectionNames =
1424 Obj.sections().template getSectionOfType<StringTableSection>(
1425 ShstrIndex,
1426 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1427 " in elf header is invalid",
1428 "e_shstrndx field value " + Twine(Ehdr.e_shstrndx) +
1429 " in elf header is not a string table");
Petr Hosek05a04cb2017-08-01 00:33:58 +00001430}
1431
Jake Ehrlich76e91102018-01-25 22:46:17 +00001432Writer::~Writer() {}
1433
1434Reader::~Reader() {}
1435
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001436std::unique_ptr<Object> BinaryReader::create() const {
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001437 return BinaryELFBuilder(MInfo.EMachine, MemBuf).build();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001438}
1439
1440std::unique_ptr<Object> ELFReader::create() const {
Alexander Shaposhnikov58cb1972018-06-07 19:41:42 +00001441 auto Obj = llvm::make_unique<Object>();
Fangrui Song32a34e62018-11-01 16:02:12 +00001442 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
1443 ELFBuilder<ELF32LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001444 Builder.build();
1445 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001446 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
1447 ELFBuilder<ELF64LE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001448 Builder.build();
1449 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001450 } else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
1451 ELFBuilder<ELF32BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001452 Builder.build();
1453 return Obj;
Fangrui Song32a34e62018-11-01 16:02:12 +00001454 } else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
1455 ELFBuilder<ELF64BE> Builder(*O, *Obj);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001456 Builder.build();
1457 return Obj;
1458 }
James Henderson5316a0d2019-05-22 13:23:26 +00001459 error("invalid file type");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001460}
1461
1462template <class ELFT> void ELFWriter<ELFT>::writeEhdr() {
George Rimare98a8f72019-05-23 09:18:57 +00001463 Elf_Ehdr &Ehdr = *reinterpret_cast<Elf_Ehdr *>(Buf.getBufferStart());
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001464 std::fill(Ehdr.e_ident, Ehdr.e_ident + 16, 0);
1465 Ehdr.e_ident[EI_MAG0] = 0x7f;
1466 Ehdr.e_ident[EI_MAG1] = 'E';
1467 Ehdr.e_ident[EI_MAG2] = 'L';
1468 Ehdr.e_ident[EI_MAG3] = 'F';
1469 Ehdr.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1470 Ehdr.e_ident[EI_DATA] =
1471 ELFT::TargetEndianness == support::big ? ELFDATA2MSB : ELFDATA2LSB;
1472 Ehdr.e_ident[EI_VERSION] = EV_CURRENT;
George Rimar4ded7732018-12-20 10:51:42 +00001473 Ehdr.e_ident[EI_OSABI] = Obj.OSABI;
1474 Ehdr.e_ident[EI_ABIVERSION] = Obj.ABIVersion;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001475
Jake Ehrlich76e91102018-01-25 22:46:17 +00001476 Ehdr.e_type = Obj.Type;
1477 Ehdr.e_machine = Obj.Machine;
1478 Ehdr.e_version = Obj.Version;
1479 Ehdr.e_entry = Obj.Entry;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00001480 // We have to use the fully-qualified name llvm::size
1481 // since some compilers complain on ambiguous resolution.
1482 Ehdr.e_phnum = llvm::size(Obj.segments());
Julie Hockett468722e2018-09-12 17:56:31 +00001483 Ehdr.e_phoff = (Ehdr.e_phnum != 0) ? Obj.ProgramHdrSegment.Offset : 0;
1484 Ehdr.e_phentsize = (Ehdr.e_phnum != 0) ? sizeof(Elf_Phdr) : 0;
Jake Ehrlich76e91102018-01-25 22:46:17 +00001485 Ehdr.e_flags = Obj.Flags;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001486 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
Fangrui Song82b01e02019-03-30 14:08:59 +00001487 if (WriteSectionHeaders && Obj.sections().size() != 0) {
Julie Hockett468722e2018-09-12 17:56:31 +00001488 Ehdr.e_shentsize = sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001489 Ehdr.e_shoff = Obj.SHOffset;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001490 // """
1491 // If the number of sections is greater than or equal to
1492 // SHN_LORESERVE (0xff00), this member has the value zero and the actual
1493 // number of section header table entries is contained in the sh_size field
1494 // of the section header at index 0.
1495 // """
Fangrui Song82b01e02019-03-30 14:08:59 +00001496 auto Shnum = Obj.sections().size() + 1;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001497 if (Shnum >= SHN_LORESERVE)
1498 Ehdr.e_shnum = 0;
1499 else
1500 Ehdr.e_shnum = Shnum;
1501 // """
1502 // If the section name string table section index is greater than or equal
1503 // to SHN_LORESERVE (0xff00), this member has the value SHN_XINDEX (0xffff)
1504 // and the actual index of the section name string table section is
1505 // contained in the sh_link field of the section header at index 0.
1506 // """
1507 if (Obj.SectionNames->Index >= SHN_LORESERVE)
1508 Ehdr.e_shstrndx = SHN_XINDEX;
1509 else
1510 Ehdr.e_shstrndx = Obj.SectionNames->Index;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001511 } else {
Julie Hockett468722e2018-09-12 17:56:31 +00001512 Ehdr.e_shentsize = 0;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001513 Ehdr.e_shoff = 0;
1514 Ehdr.e_shnum = 0;
1515 Ehdr.e_shstrndx = 0;
1516 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001517}
1518
Jake Ehrlich76e91102018-01-25 22:46:17 +00001519template <class ELFT> void ELFWriter<ELFT>::writePhdrs() {
1520 for (auto &Seg : Obj.segments())
1521 writePhdr(Seg);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001522}
1523
Jake Ehrlich76e91102018-01-25 22:46:17 +00001524template <class ELFT> void ELFWriter<ELFT>::writeShdrs() {
Petr Hosek05a04cb2017-08-01 00:33:58 +00001525 // This reference serves to write the dummy section header at the begining
Jake Ehrlich425ec9f2017-09-15 22:04:09 +00001526 // of the file. It is not used for anything else
George Rimare98a8f72019-05-23 09:18:57 +00001527 Elf_Shdr &Shdr =
1528 *reinterpret_cast<Elf_Shdr *>(Buf.getBufferStart() + Obj.SHOffset);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001529 Shdr.sh_name = 0;
1530 Shdr.sh_type = SHT_NULL;
1531 Shdr.sh_flags = 0;
1532 Shdr.sh_addr = 0;
1533 Shdr.sh_offset = 0;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001534 // See writeEhdr for why we do this.
Fangrui Song82b01e02019-03-30 14:08:59 +00001535 uint64_t Shnum = Obj.sections().size() + 1;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001536 if (Shnum >= SHN_LORESERVE)
1537 Shdr.sh_size = Shnum;
1538 else
1539 Shdr.sh_size = 0;
1540 // See writeEhdr for why we do this.
1541 if (Obj.SectionNames != nullptr && Obj.SectionNames->Index >= SHN_LORESERVE)
1542 Shdr.sh_link = Obj.SectionNames->Index;
1543 else
1544 Shdr.sh_link = 0;
Petr Hosek05a04cb2017-08-01 00:33:58 +00001545 Shdr.sh_info = 0;
1546 Shdr.sh_addralign = 0;
1547 Shdr.sh_entsize = 0;
1548
George Rimare98a8f72019-05-23 09:18:57 +00001549 for (SectionBase &Sec : Obj.sections())
Jake Ehrlich76e91102018-01-25 22:46:17 +00001550 writeShdr(Sec);
Petr Hosek05a04cb2017-08-01 00:33:58 +00001551}
1552
Jake Ehrlich76e91102018-01-25 22:46:17 +00001553template <class ELFT> void ELFWriter<ELFT>::writeSectionData() {
George Rimare98a8f72019-05-23 09:18:57 +00001554 for (SectionBase &Sec : Obj.sections())
James Henderson1f448142019-03-25 16:36:26 +00001555 // Segments are responsible for writing their contents, so only write the
1556 // section data if the section is not in a segment. Note that this renders
1557 // sections in segments effectively immutable.
1558 if (Sec.ParentSegment == nullptr)
1559 Sec.accept(*SecWriter);
1560}
1561
1562template <class ELFT> void ELFWriter<ELFT>::writeSegmentData() {
1563 for (Segment &Seg : Obj.segments()) {
1564 uint8_t *B = Buf.getBufferStart() + Seg.Offset;
1565 assert(Seg.FileSize == Seg.getContents().size() &&
1566 "Segment size must match contents size");
1567 std::memcpy(B, Seg.getContents().data(), Seg.FileSize);
1568 }
1569
1570 // Iterate over removed sections and overwrite their old data with zeroes.
1571 for (auto &Sec : Obj.removedSections()) {
1572 Segment *Parent = Sec.ParentSegment;
1573 if (Parent == nullptr || Sec.Type == SHT_NOBITS || Sec.Size == 0)
1574 continue;
1575 uint64_t Offset =
1576 Sec.OriginalOffset - Parent->OriginalOffset + Parent->Offset;
George Rimare98a8f72019-05-23 09:18:57 +00001577 std::memset(Buf.getBufferStart() + Offset, 0, Sec.Size);
James Henderson1f448142019-03-25 16:36:26 +00001578 }
Petr Hosek05a04cb2017-08-01 00:33:58 +00001579}
1580
James Henderson38cb2382019-04-02 14:11:13 +00001581template <class ELFT>
1582ELFWriter<ELFT>::ELFWriter(Object &Obj, Buffer &Buf, bool WSH)
1583 : Writer(Obj, Buf), WriteSectionHeaders(WSH && Obj.HadShdrs) {}
1584
James Henderson66a9d0f2019-04-18 09:13:30 +00001585Error Object::removeSections(bool AllowBrokenLinks,
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001586 std::function<bool(const SectionBase &)> ToRemove) {
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001587
1588 auto Iter = std::stable_partition(
1589 std::begin(Sections), std::end(Sections), [=](const SecPtr &Sec) {
1590 if (ToRemove(*Sec))
1591 return false;
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001592 if (auto RelSec = dyn_cast<RelocationSectionBase>(Sec.get())) {
1593 if (auto ToRelSec = RelSec->getSection())
1594 return !ToRemove(*ToRelSec);
1595 }
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001596 return true;
1597 });
1598 if (SymbolTable != nullptr && ToRemove(*SymbolTable))
1599 SymbolTable = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001600 if (SectionNames != nullptr && ToRemove(*SectionNames))
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001601 SectionNames = nullptr;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001602 if (SectionIndexTable != nullptr && ToRemove(*SectionIndexTable))
1603 SectionIndexTable = nullptr;
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001604 // Now make sure there are no remaining references to the sections that will
1605 // be removed. Sometimes it is impossible to remove a reference so we emit
1606 // an error here instead.
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001607 std::unordered_set<const SectionBase *> RemoveSections;
1608 RemoveSections.reserve(std::distance(Iter, std::end(Sections)));
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001609 for (auto &RemoveSec : make_range(Iter, std::end(Sections))) {
1610 for (auto &Segment : Segments)
1611 Segment->removeSection(RemoveSec.get());
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001612 RemoveSections.insert(RemoveSec.get());
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001613 }
George Rimar79fb8582019-02-27 11:18:27 +00001614
1615 // For each section that remains alive, we want to remove the dead references.
1616 // This either might update the content of the section (e.g. remove symbols
1617 // from symbol table that belongs to removed section) or trigger an error if
1618 // a live section critically depends on a section being removed somehow
1619 // (e.g. the removed section is referenced by a relocation).
1620 for (auto &KeepSec : make_range(std::begin(Sections), Iter)) {
James Henderson66a9d0f2019-04-18 09:13:30 +00001621 if (Error E = KeepSec->removeSectionReferences(AllowBrokenLinks,
Jordan Rupprecht52d57812019-02-21 16:45:42 +00001622 [&RemoveSections](const SectionBase *Sec) {
1623 return RemoveSections.find(Sec) != RemoveSections.end();
1624 }))
1625 return E;
George Rimar79fb8582019-02-27 11:18:27 +00001626 }
1627
James Henderson1f448142019-03-25 16:36:26 +00001628 // Transfer removed sections into the Object RemovedSections container for use
1629 // later.
1630 std::move(Iter, Sections.end(), std::back_inserter(RemovedSections));
1631 // Now finally get rid of them all together.
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001632 Sections.erase(Iter, std::end(Sections));
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001633 return Error::success();
Jake Ehrlich36a2eb32017-10-10 18:47:09 +00001634}
1635
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001636Error Object::removeSymbols(function_ref<bool(const Symbol &)> ToRemove) {
1637 if (SymbolTable)
1638 for (const SecPtr &Sec : Sections)
1639 if (Error E = Sec->removeSymbols(ToRemove))
1640 return E;
1641 return Error::success();
Paul Semel4246a462018-05-09 21:36:54 +00001642}
1643
Jake Ehrlich76e91102018-01-25 22:46:17 +00001644void Object::sortSections() {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001645 // Put all sections in offset order. Maintain the ordering as closely as
1646 // possible while meeting that demand however.
Fangrui Songa5355a52019-04-22 15:53:43 +00001647 llvm::stable_sort(Sections, [](const SecPtr &A, const SecPtr &B) {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001648 return A->OriginalOffset < B->OriginalOffset;
Fangrui Songa5355a52019-04-22 15:53:43 +00001649 });
Petr Hosekc4df10e2017-08-04 21:09:26 +00001650}
1651
Jake Ehrlich13153ee2017-11-02 23:24:04 +00001652static uint64_t alignToAddr(uint64_t Offset, uint64_t Addr, uint64_t Align) {
1653 // Calculate Diff such that (Offset + Diff) & -Align == Addr & -Align.
1654 if (Align == 0)
1655 Align = 1;
1656 auto Diff =
1657 static_cast<int64_t>(Addr % Align) - static_cast<int64_t>(Offset % Align);
1658 // We only want to add to Offset, however, so if Diff < 0 we can add Align and
1659 // (Offset + Diff) & -Align == Addr & -Align will still hold.
1660 if (Diff < 0)
1661 Diff += Align;
1662 return Offset + Diff;
1663}
1664
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001665// Orders segments such that if x = y->ParentSegment then y comes before x.
Fangrui Song32a34e62018-11-01 16:02:12 +00001666static void orderSegments(std::vector<Segment *> &Segments) {
Fangrui Songa5355a52019-04-22 15:53:43 +00001667 llvm::stable_sort(Segments, compareSegmentsByOffset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001668}
1669
1670// This function finds a consistent layout for a list of segments starting from
1671// an Offset. It assumes that Segments have been sorted by OrderSegments and
1672// returns an Offset one past the end of the last segment.
Fangrui Song8da6a6c2019-03-29 15:27:58 +00001673static uint64_t layoutSegments(std::vector<Segment *> &Segments,
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001674 uint64_t Offset) {
1675 assert(std::is_sorted(std::begin(Segments), std::end(Segments),
Jake Ehrlich46814be2018-01-22 19:27:30 +00001676 compareSegmentsByOffset));
Petr Hosek3f383832017-08-26 01:32:20 +00001677 // The only way a segment should move is if a section was between two
1678 // segments and that section was removed. If that section isn't in a segment
1679 // then it's acceptable, but not ideal, to simply move it to after the
1680 // segments. So we can simply layout segments one after the other accounting
1681 // for alignment.
George Rimare98a8f72019-05-23 09:18:57 +00001682 for (Segment *Seg : Segments) {
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001683 // We assume that segments have been ordered by OriginalOffset and Index
1684 // such that a parent segment will always come before a child segment in
1685 // OrderedSegments. This means that the Offset of the ParentSegment should
1686 // already be set and we can set our offset relative to it.
George Rimare98a8f72019-05-23 09:18:57 +00001687 if (Seg->ParentSegment != nullptr) {
1688 Segment *Parent = Seg->ParentSegment;
1689 Seg->Offset =
1690 Parent->Offset + Seg->OriginalOffset - Parent->OriginalOffset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001691 } else {
George Rimare98a8f72019-05-23 09:18:57 +00001692 Offset = alignToAddr(Offset, Seg->VAddr, Seg->Align);
1693 Seg->Offset = Offset;
Jake Ehrlichd246b0a2017-09-19 21:37:35 +00001694 }
George Rimare98a8f72019-05-23 09:18:57 +00001695 Offset = std::max(Offset, Seg->Offset + Seg->FileSize);
Petr Hosek3f383832017-08-26 01:32:20 +00001696 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001697 return Offset;
1698}
1699
1700// This function finds a consistent layout for a list of sections. It assumes
1701// that the ->ParentSegment of each section has already been laid out. The
1702// supplied starting Offset is used for the starting offset of any section that
1703// does not have a ParentSegment. It returns either the offset given if all
1704// sections had a ParentSegment or an offset one past the last section if there
1705// was a section that didn't have a ParentSegment.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001706template <class Range>
Fangrui Song32a34e62018-11-01 16:02:12 +00001707static uint64_t layoutSections(Range Sections, uint64_t Offset) {
Petr Hosek3f383832017-08-26 01:32:20 +00001708 // Now the offset of every segment has been set we can assign the offsets
1709 // of each section. For sections that are covered by a segment we should use
1710 // the segment's original offset and the section's original offset to compute
1711 // the offset from the start of the segment. Using the offset from the start
1712 // of the segment we can assign a new offset to the section. For sections not
1713 // covered by segments we can just bump Offset to the next valid location.
1714 uint32_t Index = 1;
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001715 for (auto &Section : Sections) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001716 Section.Index = Index++;
1717 if (Section.ParentSegment != nullptr) {
1718 auto Segment = *Section.ParentSegment;
1719 Section.Offset =
1720 Segment.Offset + (Section.OriginalOffset - Segment.OriginalOffset);
Petr Hosek3f383832017-08-26 01:32:20 +00001721 } else {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001722 Offset = alignTo(Offset, Section.Align == 0 ? 1 : Section.Align);
1723 Section.Offset = Offset;
1724 if (Section.Type != SHT_NOBITS)
1725 Offset += Section.Size;
Petr Hosek3f383832017-08-26 01:32:20 +00001726 }
1727 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001728 return Offset;
1729}
Petr Hosek3f383832017-08-26 01:32:20 +00001730
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001731template <class ELFT> void ELFWriter<ELFT>::initEhdrSegment() {
George Rimare98a8f72019-05-23 09:18:57 +00001732 Segment &ElfHdr = Obj.ElfHdrSegment;
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001733 ElfHdr.Type = PT_PHDR;
1734 ElfHdr.Flags = 0;
1735 ElfHdr.OriginalOffset = ElfHdr.Offset = 0;
1736 ElfHdr.VAddr = 0;
1737 ElfHdr.PAddr = 0;
1738 ElfHdr.FileSize = ElfHdr.MemSize = sizeof(Elf_Ehdr);
1739 ElfHdr.Align = 0;
1740}
1741
Jake Ehrlich76e91102018-01-25 22:46:17 +00001742template <class ELFT> void ELFWriter<ELFT>::assignOffsets() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001743 // We need a temporary list of segments that has a special order to it
1744 // so that we know that anytime ->ParentSegment is set that segment has
1745 // already had its offset properly set.
1746 std::vector<Segment *> OrderedSegments;
George Rimare98a8f72019-05-23 09:18:57 +00001747 for (Segment &Segment : Obj.segments())
Jake Ehrlich76e91102018-01-25 22:46:17 +00001748 OrderedSegments.push_back(&Segment);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001749 OrderedSegments.push_back(&Obj.ElfHdrSegment);
1750 OrderedSegments.push_back(&Obj.ProgramHdrSegment);
Fangrui Song32a34e62018-11-01 16:02:12 +00001751 orderSegments(OrderedSegments);
Jake Ehrlich6452b112018-02-14 23:31:33 +00001752 // Offset is used as the start offset of the first segment to be laid out.
1753 // Since the ELF Header (ElfHdrSegment) must be at the start of the file,
1754 // we start at offset 0.
1755 uint64_t Offset = 0;
Fangrui Song8da6a6c2019-03-29 15:27:58 +00001756 Offset = layoutSegments(OrderedSegments, Offset);
Fangrui Song32a34e62018-11-01 16:02:12 +00001757 Offset = layoutSections(Obj.sections(), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001758 // If we need to write the section header table out then we need to align the
1759 // Offset so that SHOffset is valid.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001760 if (WriteSectionHeaders)
Jordan Rupprechtde965ea2018-08-10 16:25:58 +00001761 Offset = alignTo(Offset, sizeof(Elf_Addr));
Jake Ehrlich76e91102018-01-25 22:46:17 +00001762 Obj.SHOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001763}
1764
Jake Ehrlich76e91102018-01-25 22:46:17 +00001765template <class ELFT> size_t ELFWriter<ELFT>::totalSize() const {
Petr Hosekc4df10e2017-08-04 21:09:26 +00001766 // We already have the section header offset so we can calculate the total
1767 // size by just adding up the size of each section header.
James Henderson38cb2382019-04-02 14:11:13 +00001768 if (!WriteSectionHeaders)
1769 return Obj.SHOffset;
1770 size_t ShdrCount = Obj.sections().size() + 1; // Includes null shdr.
1771 return Obj.SHOffset + ShdrCount * sizeof(Elf_Shdr);
Petr Hosekc4df10e2017-08-04 21:09:26 +00001772}
1773
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001774template <class ELFT> Error ELFWriter<ELFT>::write() {
James Henderson1f448142019-03-25 16:36:26 +00001775 // Segment data must be written first, so that the ELF header and program
1776 // header tables can overwrite it, if covered by a segment.
1777 writeSegmentData();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001778 writeEhdr();
1779 writePhdrs();
1780 writeSectionData();
1781 if (WriteSectionHeaders)
1782 writeShdrs();
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001783 return Buf.commit();
Jake Ehrlich76e91102018-01-25 22:46:17 +00001784}
1785
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001786template <class ELFT> Error ELFWriter<ELFT>::finalize() {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001787 // It could happen that SectionNames has been removed and yet the user wants
1788 // a section header table output. We need to throw an error if a user tries
1789 // to do that.
1790 if (Obj.SectionNames == nullptr && WriteSectionHeaders)
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001791 return createStringError(llvm::errc::invalid_argument,
James Henderson5316a0d2019-05-22 13:23:26 +00001792 "cannot write section header table because "
1793 "section header string table was removed");
Jake Ehrlich76e91102018-01-25 22:46:17 +00001794
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001795 Obj.sortSections();
1796
1797 // We need to assign indexes before we perform layout because we need to know
1798 // if we need large indexes or not. We can assign indexes first and check as
1799 // we go to see if we will actully need large indexes.
1800 bool NeedsLargeIndexes = false;
Fangrui Song82b01e02019-03-30 14:08:59 +00001801 if (Obj.sections().size() >= SHN_LORESERVE) {
George Rimare98a8f72019-05-23 09:18:57 +00001802 SectionTableRef Sections = Obj.sections();
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001803 NeedsLargeIndexes =
1804 std::any_of(Sections.begin() + SHN_LORESERVE, Sections.end(),
1805 [](const SectionBase &Sec) { return Sec.HasSymbol; });
1806 // TODO: handle case where only one section needs the large index table but
1807 // only needs it because the large index table hasn't been removed yet.
1808 }
1809
1810 if (NeedsLargeIndexes) {
1811 // This means we definitely need to have a section index table but if we
1812 // already have one then we should use it instead of making a new one.
1813 if (Obj.SymbolTable != nullptr && Obj.SectionIndexTable == nullptr) {
1814 // Addition of a section to the end does not invalidate the indexes of
1815 // other sections and assigns the correct index to the new section.
1816 auto &Shndx = Obj.addSection<SectionIndexSection>();
1817 Obj.SymbolTable->setShndxTable(&Shndx);
1818 Shndx.setSymTab(Obj.SymbolTable);
1819 }
1820 } else {
1821 // Since we don't need SectionIndexTable we should remove it and all
1822 // references to it.
1823 if (Obj.SectionIndexTable != nullptr) {
James Henderson66a9d0f2019-04-18 09:13:30 +00001824 // We do not support sections referring to the section index table.
1825 if (Error E = Obj.removeSections(false /*AllowBrokenLinks*/,
1826 [this](const SectionBase &Sec) {
1827 return &Sec == Obj.SectionIndexTable;
1828 }))
Jordan Rupprecht971d47622019-02-01 15:20:36 +00001829 return E;
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001830 }
1831 }
1832
1833 // Make sure we add the names of all the sections. Importantly this must be
1834 // done after we decide to add or remove SectionIndexes.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001835 if (Obj.SectionNames != nullptr)
1836 for (const auto &Section : Obj.sections()) {
1837 Obj.SectionNames->addString(Section.Name);
Jake Ehrlichf03384d2017-10-11 18:09:18 +00001838 }
Jake Ehrlich0a151bd2018-03-07 19:59:15 +00001839
Jordan Rupprechtcf676332018-08-17 18:51:11 +00001840 initEhdrSegment();
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001841
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001842 // Before we can prepare for layout the indexes need to be finalized.
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001843 // Also, the output arch may not be the same as the input arch, so fix up
1844 // size-related fields before doing layout calculations.
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001845 uint64_t Index = 0;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001846 auto SecSizer = llvm::make_unique<ELFSectionSizer<ELFT>>();
1847 for (auto &Sec : Obj.sections()) {
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001848 Sec.Index = Index++;
Jordan Rupprecht1f821762019-01-03 17:45:30 +00001849 Sec.accept(*SecSizer);
1850 }
Jake Ehrlichc7f8ac72018-07-16 19:48:52 +00001851
1852 // The symbol table does not update all other sections on update. For
1853 // instance, symbol names are not added as new symbols are added. This means
1854 // that some sections, like .strtab, don't yet have their final size.
1855 if (Obj.SymbolTable != nullptr)
1856 Obj.SymbolTable->prepareForLayout();
1857
George Rimarfaf308b2019-03-18 14:27:41 +00001858 // Now that all strings are added we want to finalize string table builders,
1859 // because that affects section sizes which in turn affects section offsets.
George Rimare98a8f72019-05-23 09:18:57 +00001860 for (SectionBase &Sec : Obj.sections())
George Rimarfaf308b2019-03-18 14:27:41 +00001861 if (auto StrTab = dyn_cast<StringTableSection>(&Sec))
1862 StrTab->prepareForLayout();
1863
Petr Hosekc4df10e2017-08-04 21:09:26 +00001864 assignOffsets();
1865
Eugene Leviant88089fe2019-04-12 11:59:30 +00001866 // layoutSections could have modified section indexes, so we need
1867 // to fill the index table after assignOffsets.
1868 if (Obj.SymbolTable != nullptr)
1869 Obj.SymbolTable->fillShndxTable();
1870
Petr Hosekc4df10e2017-08-04 21:09:26 +00001871 // Finally now that all offsets and indexes have been set we can finalize any
1872 // remaining issues.
Jake Ehrlich76e91102018-01-25 22:46:17 +00001873 uint64_t Offset = Obj.SHOffset + sizeof(Elf_Shdr);
George Rimare98a8f72019-05-23 09:18:57 +00001874 for (SectionBase &Section : Obj.sections()) {
Jake Ehrlich76e91102018-01-25 22:46:17 +00001875 Section.HeaderOffset = Offset;
Petr Hosekc4df10e2017-08-04 21:09:26 +00001876 Offset += sizeof(Elf_Shdr);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001877 if (WriteSectionHeaders)
1878 Section.NameIndex = Obj.SectionNames->findIndex(Section.Name);
1879 Section.finalize();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001880 }
Jake Ehrlich76e91102018-01-25 22:46:17 +00001881
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001882 if (Error E = Buf.allocate(totalSize()))
1883 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001884 SecWriter = llvm::make_unique<ELFSectionWriter<ELFT>>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001885 return Error::success();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001886}
1887
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001888Error BinaryWriter::write() {
George Rimare98a8f72019-05-23 09:18:57 +00001889 for (auto &Section : Obj.sections())
1890 if (Section.Flags & SHF_ALLOC)
1891 Section.accept(*SecWriter);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001892 return Buf.commit();
Petr Hosekc4df10e2017-08-04 21:09:26 +00001893}
1894
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001895Error BinaryWriter::finalize() {
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001896 // TODO: Create a filter range to construct OrderedSegments from so that this
1897 // code can be deduped with assignOffsets above. This should also solve the
1898 // todo below for LayoutSections.
1899 // We need a temporary list of segments that has a special order to it
1900 // so that we know that anytime ->ParentSegment is set that segment has
1901 // already had it's offset properly set. We only want to consider the segments
1902 // that will affect layout of allocated sections so we only add those.
1903 std::vector<Segment *> OrderedSegments;
George Rimare98a8f72019-05-23 09:18:57 +00001904 for (SectionBase &Section : Obj.sections())
1905 if ((Section.Flags & SHF_ALLOC) != 0 && Section.ParentSegment != nullptr)
Jake Ehrlich76e91102018-01-25 22:46:17 +00001906 OrderedSegments.push_back(Section.ParentSegment);
Jake Ehrlich46814be2018-01-22 19:27:30 +00001907
1908 // For binary output, we're going to use physical addresses instead of
1909 // virtual addresses, since a binary output is used for cases like ROM
1910 // loading and physical addresses are intended for ROM loading.
1911 // However, if no segment has a physical address, we'll fallback to using
1912 // virtual addresses for all.
Fangrui Song5ec95db2018-11-17 01:15:55 +00001913 if (all_of(OrderedSegments,
1914 [](const Segment *Seg) { return Seg->PAddr == 0; }))
1915 for (Segment *Seg : OrderedSegments)
1916 Seg->PAddr = Seg->VAddr;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001917
Fangrui Songa5355a52019-04-22 15:53:43 +00001918 llvm::stable_sort(OrderedSegments, compareSegmentsByPAddr);
Jake Ehrlich46814be2018-01-22 19:27:30 +00001919
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001920 // Because we add a ParentSegment for each section we might have duplicate
1921 // segments in OrderedSegments. If there were duplicates then LayoutSegments
1922 // would do very strange things.
1923 auto End =
1924 std::unique(std::begin(OrderedSegments), std::end(OrderedSegments));
1925 OrderedSegments.erase(End, std::end(OrderedSegments));
1926
Jake Ehrlich46814be2018-01-22 19:27:30 +00001927 uint64_t Offset = 0;
1928
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001929 // Modify the first segment so that there is no gap at the start. This allows
Fangrui Song5ec95db2018-11-17 01:15:55 +00001930 // our layout algorithm to proceed as expected while not writing out the gap
1931 // at the start.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001932 if (!OrderedSegments.empty()) {
George Rimare98a8f72019-05-23 09:18:57 +00001933 Segment *Seg = OrderedSegments[0];
1934 const SectionBase *Sec = Seg->firstSection();
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001935 auto Diff = Sec->OriginalOffset - Seg->OriginalOffset;
1936 Seg->OriginalOffset += Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001937 // The size needs to be shrunk as well.
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001938 Seg->FileSize -= Diff;
Jake Ehrlich46814be2018-01-22 19:27:30 +00001939 // The PAddr needs to be increased to remove the gap before the first
1940 // section.
1941 Seg->PAddr += Diff;
1942 uint64_t LowestPAddr = Seg->PAddr;
George Rimare98a8f72019-05-23 09:18:57 +00001943 for (Segment *Segment : OrderedSegments) {
Jake Ehrlich46814be2018-01-22 19:27:30 +00001944 Segment->Offset = Segment->PAddr - LowestPAddr;
1945 Offset = std::max(Offset, Segment->Offset + Segment->FileSize);
1946 }
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001947 }
1948
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001949 // TODO: generalize LayoutSections to take a range. Pass a special range
1950 // constructed from an iterator that skips values for which a predicate does
1951 // not hold. Then pass such a range to LayoutSections instead of constructing
1952 // AllocatedSections here.
1953 std::vector<SectionBase *> AllocatedSections;
George Rimare98a8f72019-05-23 09:18:57 +00001954 for (SectionBase &Section : Obj.sections())
1955 if (Section.Flags & SHF_ALLOC)
1956 AllocatedSections.push_back(&Section);
Fangrui Song32a34e62018-11-01 16:02:12 +00001957 layoutSections(make_pointee_range(AllocatedSections), Offset);
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001958
1959 // Now that every section has been laid out we just need to compute the total
1960 // file size. This might not be the same as the offset returned by
1961 // LayoutSections, because we want to truncate the last segment to the end of
1962 // its last section, to match GNU objcopy's behaviour.
1963 TotalSize = 0;
George Rimare98a8f72019-05-23 09:18:57 +00001964 for (SectionBase *Section : AllocatedSections)
Jake Ehrlichd49c92b2017-11-15 19:13:31 +00001965 if (Section->Type != SHT_NOBITS)
1966 TotalSize = std::max(TotalSize, Section->Offset + Section->Size);
Jake Ehrlich76e91102018-01-25 22:46:17 +00001967
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001968 if (Error E = Buf.allocate(TotalSize))
1969 return E;
Alexander Shaposhnikov42b5ef02018-07-06 17:51:03 +00001970 SecWriter = llvm::make_unique<BinarySectionWriter>(Buf);
Jordan Rupprecht881cae72019-01-22 23:49:16 +00001971 return Error::success();
Petr Hosek05a04cb2017-08-01 00:33:58 +00001972}
1973
Eugene Levianta6fb1832019-05-29 11:37:16 +00001974bool IHexWriter::SectionCompare::operator()(const SectionBase *Lhs,
1975 const SectionBase *Rhs) const {
1976 return (sectionPhysicalAddr(Lhs) & 0xFFFFFFFFU) <
1977 (sectionPhysicalAddr(Rhs) & 0xFFFFFFFFU);
1978}
1979
1980uint64_t IHexWriter::writeEntryPointRecord(uint8_t *Buf) {
1981 IHexLineData HexData;
1982 uint8_t Data[4] = {};
1983 // We don't write entry point record if entry is zero.
1984 if (Obj.Entry == 0)
1985 return 0;
1986
1987 if (Obj.Entry <= 0xFFFFFU) {
1988 Data[0] = ((Obj.Entry & 0xF0000U) >> 12) & 0xFF;
1989 support::endian::write(&Data[2], static_cast<uint16_t>(Obj.Entry),
1990 support::big);
1991 HexData = IHexRecord::getLine(IHexRecord::StartAddr80x86, 0, Data);
1992 } else {
1993 support::endian::write(Data, static_cast<uint32_t>(Obj.Entry),
1994 support::big);
1995 HexData = IHexRecord::getLine(IHexRecord::StartAddr, 0, Data);
1996 }
1997 memcpy(Buf, HexData.data(), HexData.size());
1998 return HexData.size();
1999}
2000
2001uint64_t IHexWriter::writeEndOfFileRecord(uint8_t *Buf) {
2002 IHexLineData HexData = IHexRecord::getLine(IHexRecord::EndOfFile, 0, {});
2003 memcpy(Buf, HexData.data(), HexData.size());
2004 return HexData.size();
2005}
2006
2007Error IHexWriter::write() {
2008 IHexSectionWriter Writer(Buf);
2009 // Write sections.
2010 for (const SectionBase *Sec : Sections)
2011 Sec->accept(Writer);
2012
2013 uint64_t Offset = Writer.getBufferOffset();
2014 // Write entry point address.
2015 Offset += writeEntryPointRecord(Buf.getBufferStart() + Offset);
2016 // Write EOF.
2017 Offset += writeEndOfFileRecord(Buf.getBufferStart() + Offset);
2018 assert(Offset == TotalSize);
2019 return Buf.commit();
2020}
2021
2022Error IHexWriter::checkSection(const SectionBase &Sec) {
2023 uint64_t Addr = sectionPhysicalAddr(&Sec);
2024 if (addressOverflows32bit(Addr) || addressOverflows32bit(Addr + Sec.Size - 1))
2025 return createStringError(
2026 errc::invalid_argument,
Eugene Leviantfa147c92019-05-30 09:09:01 +00002027 "Section '%s' address range [0x%llx, 0x%llx] is not 32 bit", Sec.Name.c_str(),
Eugene Levianta6fb1832019-05-29 11:37:16 +00002028 Addr, Addr + Sec.Size - 1);
2029 return Error::success();
2030}
2031
2032Error IHexWriter::finalize() {
2033 bool UseSegments = false;
2034 auto ShouldWrite = [](const SectionBase &Sec) {
2035 return (Sec.Flags & ELF::SHF_ALLOC) && (Sec.Type != ELF::SHT_NOBITS);
2036 };
2037 auto IsInPtLoad = [](const SectionBase &Sec) {
2038 return Sec.ParentSegment && Sec.ParentSegment->Type == ELF::PT_LOAD;
2039 };
2040
2041 // We can't write 64-bit addresses.
2042 if (addressOverflows32bit(Obj.Entry))
2043 return createStringError(errc::invalid_argument,
Eugene Leviantfa147c92019-05-30 09:09:01 +00002044 "Entry point address 0x%llx overflows 32 bits.",
Eugene Levianta6fb1832019-05-29 11:37:16 +00002045 Obj.Entry);
2046
2047 // If any section we're to write has segment then we
2048 // switch to using physical addresses. Otherwise we
2049 // use section virtual address.
2050 for (auto &Section : Obj.sections())
2051 if (ShouldWrite(Section) && IsInPtLoad(Section)) {
2052 UseSegments = true;
2053 break;
2054 }
2055
2056 for (auto &Section : Obj.sections())
2057 if (ShouldWrite(Section) && (!UseSegments || IsInPtLoad(Section))) {
2058 if (Error E = checkSection(Section))
2059 return E;
2060 Sections.insert(&Section);
2061 }
2062
2063 IHexSectionWriterBase LengthCalc(Buf);
2064 for (const SectionBase *Sec : Sections)
2065 Sec->accept(LengthCalc);
2066
2067 // We need space to write section records + StartAddress record
2068 // (if start adress is not zero) + EndOfFile record.
2069 TotalSize = LengthCalc.getBufferOffset() +
2070 (Obj.Entry ? IHexRecord::getLineLength(4) : 0) +
2071 IHexRecord::getLineLength(0);
2072 if (Error E = Buf.allocate(TotalSize))
2073 return E;
2074 return Error::success();
2075}
2076
Jake Ehrlich76e91102018-01-25 22:46:17 +00002077template class ELFBuilder<ELF64LE>;
2078template class ELFBuilder<ELF64BE>;
2079template class ELFBuilder<ELF32LE>;
2080template class ELFBuilder<ELF32BE>;
Petr Hosekc4df10e2017-08-04 21:09:26 +00002081
Jake Ehrlich76e91102018-01-25 22:46:17 +00002082template class ELFWriter<ELF64LE>;
2083template class ELFWriter<ELF64BE>;
2084template class ELFWriter<ELF32LE>;
2085template class ELFWriter<ELF32BE>;
Alexander Shaposhnikov654d3a92018-10-24 22:49:06 +00002086
2087} // end namespace elf
Puyan Lotfi0f5d5fa2018-07-18 00:10:51 +00002088} // end namespace objcopy
Eugene Zelenko0ad18f82017-11-01 21:16:06 +00002089} // end namespace llvm