llvm.org GIT mirror llvm / e5551a7
Reland "[LLVM][llvm-objcopy] Added basic plumbing to get things started" As discussed on llvm-dev I've implemented the first basic steps towards llvm-objcopy/llvm-objtool (name pending). This change adds the ability to copy (without modification) 64-bit little endian ELF executables that have SHT_PROGBITS, SHT_NOBITS, SHT_NULL and SHT_STRTAB sections. Patch by Jake Ehrlich Differential Revision: https://reviews.llvm.org/D33964 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@309643 91177308-0d34-0410-b5e6-96231b3b80d8 Petr Hosek 2 years ago
12 changed file(s) with 825 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
6060 llvm-modextract
6161 llvm-mt
6262 llvm-nm
63 llvm-objcopy
6364 llvm-objdump
6465 llvm-opt-report
6566 llvm-pdbutil
301301 r"\bllvm-mcmarkup\b",
302302 r"\bllvm-modextract\b",
303303 r"\bllvm-nm\b",
304 r"\bllvm-objcopy\b",
304305 r"\bllvm-objdump\b",
305306 r"\bllvm-pdbutil\b",
306307 r"\bllvm-profdata\b",
0 # RUN: yaml2obj %s > %t
1 # RUN: llvm-objcopy %t %t2
2 # RUN: llvm-readobj -sections %t2 | FileCheck %s
3
4 !ELF
5 FileHeader:
6 Class: ELFCLASS64
7 Data: ELFDATA2LSB
8 Type: ET_EXEC
9 Machine: EM_X86_64
10 Sections:
11 - Name: .bss
12 Type: SHT_NOBITS
13 Flags: [ SHF_ALLOC ]
14 AddressAlign: 0x0000000000000010
15 Size: 64
16 - Name: .text
17 Type: SHT_PROGBITS
18 Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
19 AddressAlign: 0x0000000000000010
20 Content: "00000000"
21
22 # CHECK: Type: SHT_NULL
23
24 # CHECK: Name: .bss
25 # CHECK-NEXT: Type: SHT_NOBITS
26 # CHECK-NEXT: Flags [
27 # CHECK-NEXT: SHF_ALLOC
28 # CHECK-NEXT: ]
29 # CHECK-NEXT: Address:
30 # CHECK-NEXT: Offset: [[OFFSET:0x[0-9A-F]+]]
31 # CHECK-NEXT: Size: 64
32
33 # CHECK: Name: .text
34 # CHECK-NEXT: Type: SHT_PROGBITS
35 # CHECK-NEXT: Flags [
36 # CHECK-NEXT: SHF_ALLOC
37 # CHECK-NEXT: SHF_EXECINSTR
38 # CHECK-NEXT: ]
39 # CHECK-NEXT: Address:
40 # CHECK-NEXT: Offset: [[OFFSET]]
41 # CHECK-NEXT: Size: 4
42
43 # CHECK: Name: .shstrtab
44 # CHECK-NEXT: Type: SHT_STRTAB
45 # CHECK-NEXT: Flags [
46 # CHECK-NEXT: ]
0 # RUN: yaml2obj %s > %t
1 # RUN: llvm-objcopy %t %t2
2 # RUN: llvm-readobj -sections %t2 | FileCheck %s
3
4 !ELF
5 FileHeader:
6 Class: ELFCLASS64
7 Data: ELFDATA2LSB
8 Type: ET_EXEC
9 Machine: EM_X86_64
10 Sections:
11 - Name: .text
12 Type: SHT_PROGBITS
13 Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
14 Address: 0x0
15 AddressAlign: 0x0000000000001000
16 Content: "00000000"
17 - Name: .empty
18 Type: SHT_PROGBITS
19 Flags: [ SHF_ALLOC ]
20 Address: 0x1000
21 AddressAlign: 0x0000000000001000
22 Content: ""
23 - Name: .data
24 Type: SHT_PROGBITS
25 Flags: [ SHF_ALLOC ]
26 Address: 0x1000
27 AddressAlign: 0x0000000000001000
28 Content: "00000000"
29
30
31 # CHECK: Name: .text
32 # CHECK-NEXT: Type: SHT_PROGBITS
33 # CHECK-NEXT: Flags [
34 # CHECK-NEXT: SHF_ALLOC
35 # CHECK-NEXT: SHF_EXECINSTR
36 # CHECK-NEXT: ]
37
38 # CHECK: Name: .empty
39 # CHECK-NEXT: Type: SHT_PROGBITS
40 # CHECK-NEXT: Flags [
41 # CHECK-NEXT: SHF_ALLOC
42 # CHECK-NEXT: ]
43 # CHECK-NEXT: Address: 0x1000
44 # CHECK-NEXT: Offset: 0x2000
45 # CHECK-NEXT: Size: 0
46
47 # CHECK: Name: .data
48 # CHECK-NEXT: Type: SHT_PROGBITS
49 # CHECK-NEXT: Flags [
50 # CHECK-NEXT: SHF_ALLOC
51 # CHECK-NEXT: ]
52 # CHECK-NEXT: Address: 0x1000
53 # CHECK-NEXT: Offset: 0x2000
54 # CHECK-NEXT: Size: 4
0 # RUN: yaml2obj %s -o %t
1 # RUN: llvm-objcopy %t %t2
2 # RUN: llvm-readobj -program-headers %t2 | FileCheck %s
3
4 !ELF
5 FileHeader:
6 Class: ELFCLASS64
7 Data: ELFDATA2LSB
8 Type: ET_EXEC
9 Machine: EM_X86_64
10 Sections:
11 - Name: .text
12 Type: SHT_PROGBITS
13 Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
14 Address: 0xAAAA1000
15 AddressAlign: 0x0000000000001000
16 Content: "00000000"
17 - Name: .init
18 Type: SHT_PROGBITS
19 Flags: [ SHF_ALLOC, SHF_EXECINSTR ]
20 Content: "00000000"
21 Address: 0xAAAA1010
22 AddressAlign: 0x0000000000000010
23 - Name: .data
24 Type: SHT_PROGBITS
25 Flags: [ SHF_ALLOC ]
26 Content: "00000000"
27 Address: 0xAAAA2000
28 AddressAlign: 0x0000000000001000
29 ProgramHeaders:
30 - Type: PT_LOAD
31 Flags: [ PF_X, PF_R ]
32 VAddr: 0xAAAA1000
33 PAddr: 0xFFFF1000
34 Sections:
35 - Section: .text
36 - Section: .init
37 - Type: PT_LOAD
38 Flags: [ PF_R ]
39 VAddr: 0xAAAA2000
40 PAddr: 0xFFFF2000
41 Sections:
42 - Section: .data
43
44 #CHECK: ProgramHeaders [
45 #CHECK-NEXT: ProgramHeader {
46 #CHECK-NEXT: Type: PT_LOAD
47 #CHECK-NEXT: Offset: 0x1000
48 #CHECK-NEXT: VirtualAddress: 0xAAAA1000
49 #CHECK-NEXT: PhysicalAddress: 0xFFFF1000
50 #CHECK-NEXT: FileSize: 20
51 #CHECK-NEXT: MemSize: 20
52 #CHECK-NEXT: Flags [
53 #CHECK-NEXT: PF_R
54 #CHECK-NEXT: PF_X
55 #CHECK-NEXT: ]
56 #CHECK-NEXT: Alignment: 4096
57 #CHECK-NEXT: }
58 #CHECK-NEXT: ProgramHeader {
59 #CHECK-NEXT: Type: PT_LOAD
60 #CHECK-NEXT: Offset: 0x2000
61 #CHECK-NEXT: VirtualAddress: 0xAAAA2000
62 #CHECK-NEXT: PhysicalAddress: 0xFFFF2000
63 #CHECK-NEXT: FileSize: 4
64 #CHECK-NEXT: MemSize: 4
65 #CHECK-NEXT: Flags [
66 #CHECK-NEXT: PF_R
67 #CHECK-NEXT: ]
68 #CHECK-NEXT: Alignment: 4096
69 #CHECK-NEXT: }
70 #CHECK-NEXT:]
3939 llvm-modextract
4040 llvm-mt
4141 llvm-nm
42 llvm-objcopy
4243 llvm-objdump
4344 llvm-pdbutil
4445 llvm-profdata
0 set(LLVM_LINK_COMPONENTS
1 Object
2 Support
3 MC
4 )
5 add_llvm_tool(llvm-objcopy
6 llvm-objcopy.cpp
7 Object.cpp
8 )
0 ;===- ./tools/llvm-objcopy/LLVMBuild.txt -----------------------*- Conf -*--===;
1 ;
2 ; The LLVM Compiler Infrastructure
3 ;
4 ; This file is distributed under the University of Illinois Open Source
5 ; License. See LICENSE.TXT for details.
6 ;
7 ;===------------------------------------------------------------------------===;
8 ;
9 ; This is an LLVMBuild description file for the components in this subdirectory.
10 ;
11 ; For more information on the LLVMBuild system, please see:
12 ;
13 ; http://llvm.org/docs/LLVMBuild.html
14 ;
15 ;===------------------------------------------------------------------------===;
16 [component_0]
17 type = Tool
18 name = llvm-objcopy
19 parent = Tools
20 required_libraries = Object MC
0 //===- Object.cpp -----------------------------------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 #include "Object.h"
9 #include "llvm-objcopy.h"
10
11 using namespace llvm;
12 using namespace object;
13 using namespace ELF;
14
15 template void Segment::writeHeader(FileOutputBuffer &Out) const {
16 typedef typename ELFT::Ehdr Elf_Ehdr;
17 typedef typename ELFT::Phdr Elf_Phdr;
18
19 uint8_t *Buf = Out.getBufferStart();
20 Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
21 Elf_Phdr &Phdr = *reinterpret_cast(Buf);
22 Phdr.p_type = Type;
23 Phdr.p_flags = Flags;
24 Phdr.p_offset = Offset;
25 Phdr.p_vaddr = VAddr;
26 Phdr.p_paddr = PAddr;
27 Phdr.p_filesz = FileSize;
28 Phdr.p_memsz = MemSize;
29 Phdr.p_align = Align;
30 }
31
32 void Segment::finalize() {
33 auto FirstSec = firstSection();
34 if (FirstSec) {
35 // It is possible for a gap to be at the begining of a segment. Because of
36 // this we need to compute the new offset based on how large this gap was
37 // in the source file. Section layout should have already ensured that this
38 // space is not used for something else.
39 uint64_t OriginalOffset = Offset;
40 Offset = FirstSec->Offset - (FirstSec->OriginalOffset - OriginalOffset);
41 }
42 }
43
44 void SectionBase::finalize() {}
45
46 template
47 void SectionBase::writeHeader(FileOutputBuffer &Out) const {
48 uint8_t *Buf = Out.getBufferStart();
49 Buf += HeaderOffset;
50 typename ELFT::Shdr &Shdr = *reinterpret_cast(Buf);
51 Shdr.sh_name = NameIndex;
52 Shdr.sh_type = Type;
53 Shdr.sh_flags = Flags;
54 Shdr.sh_addr = Addr;
55 Shdr.sh_offset = Offset;
56 Shdr.sh_size = Size;
57 Shdr.sh_link = Link;
58 Shdr.sh_info = Info;
59 Shdr.sh_addralign = Align;
60 Shdr.sh_entsize = EntrySize;
61 }
62
63 void Section::writeSection(FileOutputBuffer &Out) const {
64 if (Type == SHT_NOBITS)
65 return;
66 uint8_t *Buf = Out.getBufferStart() + Offset;
67 std::copy(std::begin(Contents), std::end(Contents), Buf);
68 }
69
70 void StringTableSection::addString(StringRef Name) {
71 StrTabBuilder.add(Name);
72 Size = StrTabBuilder.getSize();
73 }
74
75 uint32_t StringTableSection::findIndex(StringRef Name) const {
76 return StrTabBuilder.getOffset(Name);
77 }
78
79 void StringTableSection::finalize() { StrTabBuilder.finalize(); }
80
81 void StringTableSection::writeSection(FileOutputBuffer &Out) const {
82 StrTabBuilder.write(Out.getBufferStart() + Offset);
83 }
84
85 // Returns true IFF a section is wholly inside the range of a segment
86 static bool sectionWithinSegment(const SectionBase &Section,
87 const Segment &Segment) {
88 // If a section is empty it should be treated like it has a size of 1. This is
89 // to clarify the case when an empty section lies on a boundary between two
90 // segments and ensures that the section "belongs" to the second segment and
91 // not the first.
92 uint64_t SecSize = Section.Size ? Section.Size : 1;
93 return Segment.Offset <= Section.OriginalOffset &&
94 Segment.Offset + Segment.FileSize >= Section.OriginalOffset + SecSize;
95 }
96
97 template
98 void Object::readProgramHeaders(const ELFFile &ElfFile) {
99 uint32_t Index = 0;
100 for (const auto &Phdr : unwrapOrError(ElfFile.program_headers())) {
101 Segments.emplace_back(llvm::make_unique());
102 Segment &Seg = *Segments.back();
103 Seg.Type = Phdr.p_type;
104 Seg.Flags = Phdr.p_flags;
105 Seg.Offset = Phdr.p_offset;
106 Seg.VAddr = Phdr.p_vaddr;
107 Seg.PAddr = Phdr.p_paddr;
108 Seg.FileSize = Phdr.p_filesz;
109 Seg.MemSize = Phdr.p_memsz;
110 Seg.Align = Phdr.p_align;
111 Seg.Index = Index++;
112 for (auto &Section : Sections) {
113 if (sectionWithinSegment(*Section, Seg)) {
114 Seg.addSection(&*Section);
115 if (!Section->ParentSegment ||
116 Section->ParentSegment->Offset > Seg.Offset) {
117 Section->ParentSegment = &Seg;
118 }
119 }
120 }
121 }
122 }
123
124 template
125 std::unique_ptr
126 Object::makeSection(const llvm::object::ELFFile &ElfFile,
127 const Elf_Shdr &Shdr) {
128 ArrayRef Data;
129 switch (Shdr.sh_type) {
130 case SHT_STRTAB:
131 return llvm::make_unique();
132 case SHT_NOBITS:
133 return llvm::make_unique
(Data);
134 default:
135 Data = unwrapOrError(ElfFile.getSectionContents(&Shdr));
136 return llvm::make_unique
(Data);
137 };
138 }
139
140 template
141 void Object::readSectionHeaders(const ELFFile &ElfFile) {
142 uint32_t Index = 0;
143 for (const auto &Shdr : unwrapOrError(ElfFile.sections())) {
144 if (Index == 0) {
145 ++Index;
146 continue;
147 }
148 SecPtr Sec = makeSection(ElfFile, Shdr);
149 Sec->Name = unwrapOrError(ElfFile.getSectionName(&Shdr));
150 Sec->Type = Shdr.sh_type;
151 Sec->Flags = Shdr.sh_flags;
152 Sec->Addr = Shdr.sh_addr;
153 Sec->Offset = Shdr.sh_offset;
154 Sec->OriginalOffset = Shdr.sh_offset;
155 Sec->Size = Shdr.sh_size;
156 Sec->Link = Shdr.sh_link;
157 Sec->Info = Shdr.sh_info;
158 Sec->Align = Shdr.sh_addralign;
159 Sec->EntrySize = Shdr.sh_entsize;
160 Sec->Index = Index++;
161 Sections.push_back(std::move(Sec));
162 }
163 }
164
165 template size_t Object::totalSize() const {
166 // We already have the section header offset so we can calculate the total
167 // size by just adding up the size of each section header.
168 return SHOffset + Sections.size() * sizeof(Elf_Shdr) + sizeof(Elf_Shdr);
169 }
170
171 template Object::Object(const ELFObjectFile &Obj) {
172 const auto &ElfFile = *Obj.getELFFile();
173 const auto &Ehdr = *ElfFile.getHeader();
174
175 std::copy(Ehdr.e_ident, Ehdr.e_ident + 16, Ident);
176 Type = Ehdr.e_type;
177 Machine = Ehdr.e_machine;
178 Version = Ehdr.e_version;
179 Entry = Ehdr.e_entry;
180 Flags = Ehdr.e_flags;
181
182 readSectionHeaders(ElfFile);
183 readProgramHeaders(ElfFile);
184
185 SectionNames =
186 dyn_cast(Sections[Ehdr.e_shstrndx - 1].get());
187 }
188
189 template void Object::sortSections() {
190 // Put all sections in offset order. Maintain the ordering as closely as
191 // possible while meeting that demand however.
192 auto CompareSections = [](const SecPtr &A, const SecPtr &B) {
193 return A->OriginalOffset < B->OriginalOffset;
194 };
195 std::stable_sort(std::begin(Sections), std::end(Sections), CompareSections);
196 }
197
198 template void Object::assignOffsets() {
199 // Decide file offsets and indexes.
200 size_t PhdrSize = Segments.size() * sizeof(Elf_Phdr);
201 // We can put section data after the ELF header and the program headers.
202 uint64_t Offset = sizeof(Elf_Ehdr) + PhdrSize;
203 uint64_t Index = 1;
204 for (auto &Section : Sections) {
205 // The segment can have a different alignment than the section. In the case
206 // that there is a parent segment then as long as we satisfy the alignment
207 // of the segment it should follow that that the section is aligned.
208 if (Section->ParentSegment) {
209 auto FirstInSeg = Section->ParentSegment->firstSection();
210 if (FirstInSeg == Section.get()) {
211 Offset = alignTo(Offset, Section->ParentSegment->Align);
212 // There can be gaps at the start of a segment before the first section.
213 // So first we assign the alignment of the segment and then assign the
214 // location of the section from there
215 Section->Offset =
216 Offset + Section->OriginalOffset - Section->ParentSegment->Offset;
217 }
218 // We should respect interstitial gaps of allocated sections. We *must*
219 // maintain the memory image so that addresses are preserved. As, with the
220 // exception of SHT_NOBITS sections at the end of segments, the memory
221 // image is a copy of the file image, we preserve the file image as well.
222 // There's a strange case where a thread local SHT_NOBITS can cause the
223 // memory image and file image to not be the same. This occurs, on some
224 // systems, when a thread local SHT_NOBITS is between two SHT_PROGBITS
225 // and the thread local SHT_NOBITS section is at the end of a TLS segment.
226 // In this case to faithfully copy the segment file image we must use
227 // relative offsets. In any other case this would be the same as using the
228 // relative addresses so this should maintian the memory image as desired.
229 Offset = FirstInSeg->Offset + Section->OriginalOffset -
230 FirstInSeg->OriginalOffset;
231 }
232 // Alignment should have already been handled by the above if statement if
233 // this if this section is in a segment. Technically this shouldn't do
234 // anything bad if the alignments of the sections are all correct and the
235 // file image isn't corrupted. Still in sticking with the motto "maintain
236 // the file image" we should avoid messing up the file image if the
237 // alignment disagrees with the file image.
238 if (!Section->ParentSegment && Section->Align)
239 Offset = alignTo(Offset, Section->Align);
240 Section->Offset = Offset;
241 Section->Index = Index++;
242 if (Section->Type != SHT_NOBITS)
243 Offset += Section->Size;
244 }
245 // 'offset' should now be just after all the section data so we should set the
246 // section header table offset to be exactly here. This spot might not be
247 // aligned properly however so we should align it as needed. For 32-bit ELF
248 // this needs to be 4-byte aligned and on 64-bit it needs to be 8-byte aligned
249 // so the size of ELFT::Addr is used to ensure this.
250 Offset = alignTo(Offset, sizeof(typename ELFT::Addr));
251 SHOffset = Offset;
252 }
253
254 template void Object::finalize() {
255 for (auto &Section : Sections)
256 SectionNames->addString(Section->Name);
257
258 sortSections();
259 assignOffsets();
260
261 // Finalize SectionNames first so that we can assign name indexes.
262 SectionNames->finalize();
263 // Finally now that all offsets and indexes have been set we can finalize any
264 // remaining issues.
265 uint64_t Offset = SHOffset + sizeof(Elf_Shdr);
266 for (auto &Section : Sections) {
267 Section->HeaderOffset = Offset;
268 Offset += sizeof(Elf_Shdr);
269 Section->NameIndex = SectionNames->findIndex(Section->Name);
270 Section->finalize();
271 }
272
273 for (auto &Segment : Segments)
274 Segment->finalize();
275 }
276
277 template
278 void Object::writeHeader(FileOutputBuffer &Out) const {
279 uint8_t *Buf = Out.getBufferStart();
280 Elf_Ehdr &Ehdr = *reinterpret_cast(Buf);
281 std::copy(Ident, Ident + 16, Ehdr.e_ident);
282 Ehdr.e_type = Type;
283 Ehdr.e_machine = Machine;
284 Ehdr.e_version = Version;
285 Ehdr.e_entry = Entry;
286 Ehdr.e_phoff = sizeof(Elf_Ehdr);
287 Ehdr.e_shoff = SHOffset;
288 Ehdr.e_flags = Flags;
289 Ehdr.e_ehsize = sizeof(Elf_Ehdr);
290 Ehdr.e_phentsize = sizeof(Elf_Phdr);
291 Ehdr.e_phnum = Segments.size();
292 Ehdr.e_shentsize = sizeof(Elf_Shdr);
293 Ehdr.e_shnum = Sections.size() + 1;
294 Ehdr.e_shstrndx = SectionNames->Index;
295 }
296
297 template
298 void Object::writeProgramHeaders(FileOutputBuffer &Out) const {
299 for (auto &Phdr : Segments)
300 Phdr->template writeHeader(Out);
301 }
302
303 template
304 void Object::writeSectionHeaders(FileOutputBuffer &Out) const {
305 uint8_t *Buf = Out.getBufferStart() + SHOffset;
306 // This reference serves to write the dummy section header at the begining
307 // of the file.
308 Elf_Shdr &Shdr = *reinterpret_cast(Buf);
309 Shdr.sh_name = 0;
310 Shdr.sh_type = SHT_NULL;
311 Shdr.sh_flags = 0;
312 Shdr.sh_addr = 0;
313 Shdr.sh_offset = 0;
314 Shdr.sh_size = 0;
315 Shdr.sh_link = 0;
316 Shdr.sh_info = 0;
317 Shdr.sh_addralign = 0;
318 Shdr.sh_entsize = 0;
319
320 for (auto &Section : Sections)
321 Section->template writeHeader(Out);
322 }
323
324 template
325 void Object::writeSectionData(FileOutputBuffer &Out) const {
326 for (auto &Section : Sections)
327 Section->writeSection(Out);
328 }
329
330 template void Object::write(FileOutputBuffer &Out) {
331 writeHeader(Out);
332 writeProgramHeaders(Out);
333 writeSectionData(Out);
334 writeSectionHeaders(Out);
335 }
336
337 template class Object;
338 template class Object;
339 template class Object;
340 template class Object;
0 //===- Object.h -------------------------------------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef LLVM_OBJCOPY_OBJECT_H
10 #define LLVM_OBJCOPY_OBJECT_H
11
12 #include "llvm/MC/StringTableBuilder.h"
13 #include "llvm/Object/ELFObjectFile.h"
14 #include "llvm/Support/FileOutputBuffer.h"
15
16 #include
17 #include
18
19 class Segment;
20
21 class SectionBase {
22 public:
23 llvm::StringRef Name;
24 Segment *ParentSegment = nullptr;
25 uint64_t HeaderOffset;
26 uint64_t OriginalOffset;
27 uint32_t Index;
28
29 uint64_t Addr = 0;
30 uint64_t Align = 1;
31 uint32_t EntrySize = 0;
32 uint64_t Flags = 0;
33 uint64_t Info = 0;
34 uint64_t Link = llvm::ELF::SHN_UNDEF;
35 uint64_t NameIndex = 0;
36 uint64_t Offset = 0;
37 uint64_t Size = 0;
38 uint64_t Type = llvm::ELF::SHT_NULL;
39
40 virtual ~SectionBase() {}
41 virtual void finalize();
42 template void writeHeader(llvm::FileOutputBuffer &Out) const;
43 virtual void writeSection(llvm::FileOutputBuffer &Out) const = 0;
44 };
45
46 class Segment {
47 private:
48 struct SectionCompare {
49 bool operator()(const SectionBase *Lhs, const SectionBase *Rhs) const {
50 // Some sections might have the same address if one of them is empty. To
51 // fix this we can use the lexicographic ordering on ->Addr and the
52 // address of the actully stored section.
53 if (Lhs->OriginalOffset == Rhs->OriginalOffset)
54 return Lhs < Rhs;
55 return Lhs->OriginalOffset < Rhs->OriginalOffset;
56 }
57 };
58
59 std::set Sections;
60
61 public:
62 uint64_t Align;
63 uint64_t FileSize;
64 uint32_t Flags;
65 uint32_t Index;
66 uint64_t MemSize;
67 uint64_t Offset;
68 uint64_t PAddr;
69 uint64_t Type;
70 uint64_t VAddr;
71
72 void finalize();
73 const SectionBase *firstSection() const {
74 if (!Sections.empty())
75 return *Sections.begin();
76 return nullptr;
77 }
78 void addSection(const SectionBase *sec) { Sections.insert(sec); }
79 template void writeHeader(llvm::FileOutputBuffer &Out) const;
80 };
81
82 class Section : public SectionBase {
83 private:
84 llvm::ArrayRef Contents;
85
86 public:
87 Section(llvm::ArrayRef Data) : Contents(Data) {}
88 void writeSection(llvm::FileOutputBuffer &Out) const override;
89 };
90
91 // This is just a wraper around a StringTableBuilder that implements SectionBase
92 class StringTableSection : public SectionBase {
93 private:
94 llvm::StringTableBuilder StrTabBuilder;
95
96 public:
97 StringTableSection() : StrTabBuilder(llvm::StringTableBuilder::ELF) {
98 Type = llvm::ELF::SHT_STRTAB;
99 }
100
101 void addString(llvm::StringRef Name);
102 uint32_t findIndex(llvm::StringRef Name) const;
103 void finalize() override;
104 void writeSection(llvm::FileOutputBuffer &Out) const override;
105 static bool classof(const SectionBase *S) {
106 return S->Type == llvm::ELF::SHT_STRTAB;
107 }
108 };
109
110 template class Object {
111 private:
112 typedef std::unique_ptr SecPtr;
113 typedef std::unique_ptr SegPtr;
114
115 typedef typename ELFT::Shdr Elf_Shdr;
116 typedef typename ELFT::Ehdr Elf_Ehdr;
117 typedef typename ELFT::Phdr Elf_Phdr;
118
119 StringTableSection *SectionNames;
120 std::vector Sections;
121 std::vector Segments;
122
123 void sortSections();
124 void assignOffsets();
125 SecPtr makeSection(const llvm::object::ELFFile &ElfFile,
126 const Elf_Shdr &Shdr);
127 void readProgramHeaders(const llvm::object::ELFFile &ElfFile);
128 void readSectionHeaders(const llvm::object::ELFFile &ElfFile);
129 void writeHeader(llvm::FileOutputBuffer &Out) const;
130 void writeProgramHeaders(llvm::FileOutputBuffer &Out) const;
131 void writeSectionData(llvm::FileOutputBuffer &Out) const;
132 void writeSectionHeaders(llvm::FileOutputBuffer &Out) const;
133
134 public:
135 uint8_t Ident[16];
136 uint64_t Entry;
137 uint64_t SHOffset;
138 uint32_t Type;
139 uint32_t Machine;
140 uint32_t Version;
141 uint32_t Flags;
142
143 Object(const llvm::object::ELFObjectFile &Obj);
144 size_t totalSize() const;
145 void finalize();
146 void write(llvm::FileOutputBuffer &Out);
147 };
148
149 #endif
0 //===- llvm-objcopy.cpp -----------------------------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 #include "llvm-objcopy.h"
9 #include "Object.h"
10 #include "llvm/Support/CommandLine.h"
11 #include "llvm/Support/FileOutputBuffer.h"
12 #include "llvm/Support/PrettyStackTrace.h"
13 #include "llvm/Support/Signals.h"
14 #include "llvm/Support/ToolOutputFile.h"
15
16 #include
17 #include
18 #include
19
20 using namespace llvm;
21 using namespace object;
22 using namespace ELF;
23
24 // The name this program was invoked as.
25 static StringRef ToolName;
26
27 namespace llvm {
28
29 LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
30 errs() << ToolName << ": " << Message << ".\n";
31 errs().flush();
32 exit(1);
33 }
34
35 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, std::error_code EC) {
36 assert(EC);
37 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
38 exit(1);
39 }
40
41 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, llvm::Error E) {
42 assert(E);
43 std::string Buf;
44 raw_string_ostream OS(Buf);
45 logAllUnhandledErrors(std::move(E), OS, "");
46 OS.flush();
47 errs() << ToolName << ": '" << File << "': " << Buf;
48 exit(1);
49 }
50 }
51
52 cl::opt InputFilename(cl::Positional, cl::desc(""));
53 cl::opt OutputFilename(cl::Positional, cl::desc(""),
54 cl::init("-"));
55
56 void CopyBinary(const ELFObjectFile &ObjFile) {
57 std::unique_ptr Buffer;
58 Object Obj{ObjFile};
59 Obj.finalize();
60 ErrorOr> BufferOrErr =
61 FileOutputBuffer::create(OutputFilename, Obj.totalSize(),
62 FileOutputBuffer::F_executable);
63 if (BufferOrErr.getError())
64 error("failed to open " + OutputFilename);
65 else
66 Buffer = std::move(*BufferOrErr);
67 std::error_code EC;
68 if (EC)
69 report_fatal_error(EC.message());
70 Obj.write(*Buffer);
71 if (auto EC = Buffer->commit())
72 reportError(OutputFilename, EC);
73 }
74
75 int main(int argc, char **argv) {
76 // Print a stack trace if we signal out.
77 sys::PrintStackTraceOnErrorSignal(argv[0]);
78 PrettyStackTraceProgram X(argc, argv);
79 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
80 cl::ParseCommandLineOptions(argc, argv, "llvm objcopy utility\n");
81 ToolName = argv[0];
82 if (InputFilename.empty()) {
83 cl::PrintHelpMessage();
84 return 2;
85 }
86 Expected> BinaryOrErr = createBinary(InputFilename);
87 if (!BinaryOrErr)
88 reportError(InputFilename, BinaryOrErr.takeError());
89 Binary &Binary = *BinaryOrErr.get().getBinary();
90 if (ELFObjectFile *o = dyn_cast>(&Binary)) {
91 CopyBinary(*o);
92 return 0;
93 }
94 reportError(InputFilename, object_error::invalid_file_type);
95 }
0 //===- llvm-objcopy.h -------------------------------------------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 #ifndef LLVM_OBJCOPY_H
9 #define LLVM_OBJCOPY_H
10
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/Support/Error.h"
13
14 namespace llvm {
15
16 LLVM_ATTRIBUTE_NORETURN extern void error(Twine Message);
17
18 // This is taken from llvm-readobj.
19 // [see here](llvm/tools/llvm-readobj/llvm-readobj.h:38)
20 template T unwrapOrError(Expected EO) {
21 if (EO)
22 return *EO;
23 std::string Buf;
24 raw_string_ostream OS(Buf);
25 logAllUnhandledErrors(EO.takeError(), OS, "");
26 OS.flush();
27 error(Buf);
28 }
29 }
30
31 #endif