gem5 v24.0.0.0
Loading...
Searching...
No Matches
elf_object.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2011-2013, 2019, 2023 Arm Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2003-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 */
40
42
43#include <fcntl.h>
44#include <sys/mman.h>
45#include <sys/stat.h>
46#include <sys/types.h>
47#include <unistd.h>
48
49#include <cassert>
50#include <string>
51
52#include "base/bitfield.hh"
53#include "base/compiler.hh"
54#include "base/loader/symtab.hh"
55#include "base/logging.hh"
56#include "base/trace.hh"
57#include "debug/Loader.hh"
58#include "gelf.h"
59#include "sim/byteswap.hh"
60
61namespace gem5
62{
63
64namespace loader
65{
66
67ObjectFile *
69{
70 // check that header matches library version
71 if (elf_version(EV_CURRENT) == EV_NONE)
72 panic("wrong elf version number!");
73
74 ObjectFile *object = nullptr;
75
76 // get a pointer to elf structure
77 // Check that we actually have a elf file
78 Elf *elf =
79 elf_memory((char *)const_cast<uint8_t *>(ifd->data()), ifd->len());
80 assert(elf);
81
82 GElf_Ehdr ehdr;
83 if (gelf_getehdr(elf, &ehdr) == 0)
84 DPRINTFR(Loader, "Not ELF\n");
85 else
86 object = new ElfObject(ifd);
87
88 elf_end(elf);
89
90 return object;
91}
92
93namespace
94{
95
96ElfObjectFormat elfObjectFormat;
97std::string interpDir;
98
99} // anonymous namespace
100
101void
102setInterpDir(const std::string &dirname)
103{
104 fatal_if(!interpDir.empty(),
105 "Error: setInterpDir has already been called once\n");
106 interpDir = dirname;
107}
108
110{
111 // get a pointer to elf structure
112 elf = elf_memory((char *)const_cast<uint8_t *>(imageData->data()),
113 imageData->len());
114 assert(elf);
115 gelf_getehdr(elf, &ehdr);
116
120
121 entry = ehdr.e_entry;
122 _programHeaderCount = ehdr.e_phnum;
123 _programHeaderSize = ehdr.e_phentsize;
124
125 // Go through all the segments in the program and record them.
126 for (int i = 0; i < ehdr.e_phnum; ++i) {
127 GElf_Phdr phdr;
128 if (gelf_getphdr(elf, i, &phdr) == 0) {
129 panic("gelf_getphdr failed for segment %d.", i);
130 }
131
132 if (phdr.p_type == PT_LOAD)
134 if (phdr.p_type == PT_INTERP) {
135 // Make sure the interpreter is an valid ELF file.
136 auto interp_path = getInterpPath(phdr);
137 ObjectFile *obj = createObjectFile(interp_path);
138 interpreter = dynamic_cast<ElfObject *>(obj);
139 assert(interpreter != nullptr);
140 _symtab.insert(obj->symtab());
141 }
142 }
143
144 // should have found at least one loadable segment
145 warn_if(image.segments().empty(),
146 "No loadable segments in '%s'. ELF file corrupted?\n",
147 imageData->filename());
148
149 for ([[maybe_unused]] auto &seg: image.segments())
150 DPRINTFR(Loader, "%s\n", seg);
151
152 // We will actually read the sections when we need to load them
153
154 // check that header matches library version
155 if (elf_version(EV_CURRENT) == EV_NONE)
156 panic("wrong elf version number!");
157
158 // Get the first section
159 int sec_idx = 1; // there is a 0 but it is nothing, go figure
160 Elf_Scn *section = elf_getscn(elf, sec_idx);
161
162 // While there are no more sections
163 while (section) {
164 GElf_Shdr shdr;
165 gelf_getshdr(section, &shdr);
166
167 if (shdr.sh_type == SHT_SYMTAB) {
168 Elf_Data *data = elf_getdata(section, nullptr);
169 int count = shdr.sh_size / shdr.sh_entsize;
170 DPRINTF(Loader, "Found Symbol Table, %d symbols present.", count);
171
172 // Loop through all the symbols.
173 for (int i = 0; i < count; ++i) {
174 GElf_Sym sym;
175 gelf_getsym(data, i, &sym);
176
177 char *sym_name = elf_strptr(elf, shdr.sh_link, sym.st_name);
178 if (!sym_name || sym_name[0] == '$')
179 continue;
180
183 switch (GELF_ST_BIND(sym.st_info)) {
184 case STB_GLOBAL:
186 break;
187 case STB_LOCAL:
189 break;
190 case STB_WEAK:
192 break;
193 default:
194 continue;
195 }
196
197 loader::Symbol::SymbolType symbol_type =
199 switch (GELF_ST_TYPE(sym.st_info)) {
200 case STT_NOTYPE:
202 break;
203 case STT_OBJECT:
205 break;
206 case STT_FUNC:
208 break;
209 case STT_SECTION:
211 break;
212 case STT_FILE:
214 break;
215 default:
217 break;
218 }
219
220 loader::Symbol symbol(
221 binding, symbol_type, sym_name, sym.st_value,
222 sym.st_size);
223
224 if (_symtab.insert(symbol)) {
225 DPRINTF(Loader, "Symbol: %-40s value %#x.\n",
226 symbol.name(), symbol.address());
227 }
228 }
229 }
230 ++sec_idx;
231 section = elf_getscn(elf, sec_idx);
232 }
233}
234
235std::string
236ElfObject::getInterpPath(const GElf_Phdr &phdr) const
237{
238 // This is the interpreter path as specified in the elf file
239 const std::string elf_path = (char *)imageData->data() + phdr.p_offset;
240 if (!interpDir.empty())
241 return interpDir + elf_path;
242 else
243 return elf_path;
244}
245
246void
248{
249 auto &emach = ehdr.e_machine;
250 auto &eclass = ehdr.e_ident[EI_CLASS];
251 auto &edata = ehdr.e_ident[EI_DATA];
252
253 // Detect the architecture
254 if (emach == EM_SPARC64 || (emach == EM_SPARC && eclass == ELFCLASS64) ||
255 emach == EM_SPARCV9) {
256 arch = SPARC64;
257 } else if (emach == EM_SPARC32PLUS ||
258 (emach == EM_SPARC && eclass == ELFCLASS32)) {
259 arch = SPARC32;
260 } else if (emach == EM_MIPS && eclass == ELFCLASS32) {
261 arch = Mips;
262 if (edata != ELFDATA2LSB) {
263 fatal("The binary you're trying to load is compiled for big "
264 "endian MIPS. gem5\nonly supports little endian MIPS. "
265 "Please recompile your binary.\n");
266 }
267 } else if (emach == EM_X86_64 && eclass == ELFCLASS64) {
268 arch = X86_64;
269 } else if (emach == EM_386 && eclass == ELFCLASS32) {
270 arch = I386;
271 } else if (emach == EM_ARM && eclass == ELFCLASS32) {
272 arch = bits(ehdr.e_entry, 0) ? Thumb : Arm;
273 } else if (emach == EM_AARCH64 && eclass == ELFCLASS64) {
274 arch = Arm64;
275 } else if (emach == EM_RISCV) {
276 arch = (eclass == ELFCLASS64) ? Riscv64 : Riscv32;
277 } else if (emach == EM_PPC && eclass == ELFCLASS32) {
278 arch = Power;
279 } else if (emach == EM_PPC64 && eclass == ELFCLASS64) {
280 arch = Power64;
281 } else {
282 warn("Unknown architecture: %d\n", emach);
283 }
284}
285
286void
288{
289 // For 64-bit Power, EI_OSABI and EI_ABIVERSION cannot be used to
290 // determine the ABI version used by the ELF object
291 if (ehdr.e_machine == EM_PPC64) {
292 switch (ehdr.e_flags & 0x3) {
293 case 0x1: opSys = LinuxPower64ABIv1; return;
294 case 0x2: opSys = LinuxPower64ABIv2; return;
295 default:
296 if (ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
298 if (ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
300 return;
301 }
302 }
303
304 // Detect the operating system
305 switch (ehdr.e_ident[EI_OSABI]) {
306 case ELFOSABI_LINUX:
307 opSys = Linux;
308 return;
309 case ELFOSABI_SOLARIS:
310 opSys = Solaris;
311 return;
312 case ELFOSABI_TRU64:
313 opSys = Tru64;
314 return;
315 case ELFOSABI_ARM:
317 return;
318 case ELFOSABI_FREEBSD:
319 opSys = FreeBSD;
320 return;
321 default:
323 }
324
325 Elf_Scn *section = elf_getscn(elf, 1);
326 for (int sec_idx = 1; section; section = elf_getscn(elf, ++sec_idx)) {
327 GElf_Shdr shdr;
328 gelf_getshdr(section, &shdr);
329
330 char *e_str = elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name);
331 if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag", e_str)) {
332 // we have found a ABI note section
333 // Check the 5th 32bit word for OS 0 == linux, 1 == hurd,
334 // 2 == solaris, 3 == freebsd
335 Elf_Data *raw_data = elf_rawdata(section, nullptr);
336 assert(raw_data && raw_data->d_buf);
337
338 uint32_t raw_abi = ((uint32_t *)raw_data->d_buf)[4];
339 bool is_le = ehdr.e_ident[EI_DATA] == ELFDATA2LSB;
340 uint32_t os_abi = is_le ? htole(raw_abi) : htobe(raw_abi);
341
342 switch (os_abi) {
343 case 0:
344 opSys = Linux;
345 return;
346 case 1:
347 fatal("gem5 does not support the HURD ABI.\n");
348 case 2:
349 opSys = Solaris;
350 return;
351 case 3:
352 opSys = FreeBSD;
353 return;
354 }
355 }
356
357 if (!strcmp(".SUNW_version", e_str) || !strcmp(".stab.index", e_str)) {
358 opSys = Solaris;
359 return;
360 }
361 }
362}
363
364void
366{
367 auto edata = ehdr.e_ident[EI_DATA];
368 if (edata == ELFDATANONE)
369 panic("invalid ELF data encoding");
370 byteOrder = (edata == ELFDATA2MSB) ? ByteOrder::big : ByteOrder::little;
371}
372
373void
374ElfObject::handleLoadableSegment(GElf_Phdr phdr, int seg_num)
375{
376 auto name = std::to_string(seg_num);
377
378 if (phdr.p_memsz == 0) {
379 warn("Ignoring empty loadable segment %s", name);
380 return;
381 }
382
383 image.addSegment({ name, phdr.p_paddr, imageData,
384 phdr.p_offset, phdr.p_filesz });
385 Addr uninitialized = phdr.p_memsz - phdr.p_filesz;
386 if (uninitialized) {
387 // There may be parts of a segment which aren't included in the
388 // file. In those cases, we need to create a new segment with no
389 // data to take up the extra space. This should be zeroed when
390 // loaded into memory.
391 image.addSegment({ name + "(uninitialized)",
392 phdr.p_paddr + phdr.p_filesz, uninitialized });
393 }
394
395 const Addr file_start = phdr.p_offset;
396 const Addr file_end = file_start + phdr.p_filesz;
397
398 // If there is a program header table, figure out the virtual
399 // address of the header table in the final memory image. We use
400 // the program headers themselves to translate from a file offset
401 // to the address in the image.
402 if (file_start <= ehdr.e_phoff && file_end > ehdr.e_phoff)
403 _programHeaderTable = phdr.p_vaddr + (ehdr.e_phoff - file_start);
404}
405
407{
408 elf_end(elf);
409}
410
411void
413{
414 assert(!sectionNames.size());
415
416 // check that header matches library version
417 if (elf_version(EV_CURRENT) == EV_NONE)
418 panic("wrong elf version number!");
419
420 // get a pointer to elf structure
421 Elf *elf =
422 elf_memory((char *)const_cast<uint8_t *>(imageData->data()),
423 imageData->len());
424 assert(elf != NULL);
425
426 // Check that we actually have a elf file
427 GElf_Ehdr ehdr;
428 if (gelf_getehdr(elf, &ehdr) ==0) {
429 panic("Not ELF, shouldn't be here");
430 }
431
432 // Get the first section
433 int sec_idx = 1; // there is a 0 but it is nothing, go figure
434 Elf_Scn *section = elf_getscn(elf, sec_idx);
435
436 // While there are no more sections
437 while (section) {
438 GElf_Shdr shdr;
439 gelf_getshdr(section, &shdr);
440 sectionNames.insert(elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name));
441 section = elf_getscn(elf, ++sec_idx);
442 } // while sections
443
444 elf_end(elf);
445}
446
447bool
449{
450 if (!sectionNames.size())
451 getSections();
452
453 return sectionNames.find(sec) != sectionNames.end();
454}
455
456
457void
459{
460 // Record the bias.
461 ldBias = bias_addr;
462
463 // Patch the entry point with bias_addr.
464 entry += bias_addr;
465
466 // Patch segments with the bias_addr.
467 image.offset(bias_addr);
468}
469
470} // namespace loader
471} // namespace gem5
#define DPRINTFR(x,...)
Definition trace.hh:224
#define DPRINTF(x,...)
Definition trace.hh:210
const char data[]
ObjectFile * load(ImageFileDataPtr data) override
Definition elf_object.cc:68
std::string getInterpPath(const GElf_Phdr &phdr) const
std::set< std::string > sectionNames
Definition elf_object.hh:79
void handleLoadableSegment(GElf_Phdr phdr, int seg_num)
bool sectionExists(std::string sec)
void updateBias(Addr bias_addr) override
ElfObject(ImageFileDataPtr ifd)
ImageFileDataPtr imageData
Definition image_file.hh:48
const std::vector< Segment > & segments() const
MemoryImage & offset(Addr by)
void addSegment(const Segment &seg)
const SymbolTable & symtab() const
bool insert(const Symbol &symbol)
Insert a new symbol in the table if it does not already exist.
Definition symtab.cc:66
std::string name() const
Definition symtab.hh:106
Addr address() const
Definition symtab.hh:114
constexpr T bits(T val, unsigned first, unsigned last)
Extract the bitfield from position 'first' to 'last' (inclusive) from 'val' and right justify it.
Definition bitfield.hh:79
#define panic(...)
This implements a cprintf based panic() function.
Definition logging.hh:188
#define fatal_if(cond,...)
Conditional fatal macro that checks the supplied condition and only causes a fatal error if the condi...
Definition logging.hh:236
#define fatal(...)
This implements a cprintf based fatal() function.
Definition logging.hh:200
#define warn(...)
Definition logging.hh:256
#define warn_if(cond,...)
Conditional warning macro that checks the supplied condition and only prints a warning if the conditi...
Definition logging.hh:283
Bitfield< 7 > i
Definition misc_types.hh:67
Bitfield< 2, 0 > seg
Definition types.hh:87
void setInterpDir(const std::string &dirname)
This is the interface for setting up a base path for the elf interpreter.
ObjectFile * createObjectFile(const std::string &fname, bool raw)
std::shared_ptr< ImageFileData > ImageFileDataPtr
Copyright (c) 2024 - Pranith Kumar Copyright (c) 2020 Inria All rights reserved.
Definition binary32.hh:36
uint64_t Addr
Address type This will probably be moved somewhere else in the near future.
Definition types.hh:147
T htole(T value)
Definition byteswap.hh:172
T htobe(T value)
Definition byteswap.hh:174
const std::string & name()
Definition trace.cc:48

Generated on Tue Jun 18 2024 16:24:00 for gem5 by doxygen 1.11.0