gem5  v19.0.0.0
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
elf_object.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011-2013, 2019 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  * Authors: Steve Reinhardt
41  * Ali Saidi
42  */
43 
45 
46 #include <fcntl.h>
47 #include <sys/mman.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <unistd.h>
51 
52 #include <cassert>
53 #include <string>
54 
55 #include "base/bitfield.hh"
56 #include "base/loader/symtab.hh"
57 #include "base/logging.hh"
58 #include "base/trace.hh"
59 #include "debug/Loader.hh"
60 #include "gelf.h"
61 #include "sim/byteswap.hh"
62 
63 ObjectFile *
65 {
66  // check that header matches library version
67  if (elf_version(EV_CURRENT) == EV_NONE)
68  panic("wrong elf version number!");
69 
70  ObjectFile *object = nullptr;
71 
72  // get a pointer to elf structure
73  // Check that we actually have a elf file
74  Elf *elf =
75  elf_memory((char *)const_cast<uint8_t *>(ifd->data()), ifd->len());
76  assert(elf);
77 
78  GElf_Ehdr ehdr;
79  if (gelf_getehdr(elf, &ehdr) == 0)
80  DPRINTFR(Loader, "Not ELF\n");
81  else
82  object = new ElfObject(ifd);
83 
84  elf_end(elf);
85 
86  return object;
87 }
88 
89 namespace
90 {
91 
92 ElfObjectFormat elfObjectFormat;
93 std::string interpDir;
94 
95 } // anonymous namespace
96 
97 void
98 setInterpDir(const std::string &dirname)
99 {
100  fatal_if(!interpDir.empty(),
101  "Error: setInterpDir has already been called once\n");
102  interpDir = dirname;
103 }
104 
106 {
107  // get a pointer to elf structure
108  elf = elf_memory((char *)const_cast<uint8_t *>(imageData->data()),
109  imageData->len());
110  assert(elf);
111  gelf_getehdr(elf, &ehdr);
112 
113  determineArch();
114  determineOpSys();
115 
116  entry = ehdr.e_entry;
117  _programHeaderCount = ehdr.e_phnum;
118  _programHeaderSize = ehdr.e_phentsize;
119 
120  // Go through all the segments in the program and record them.
121  for (int i = 0; i < ehdr.e_phnum; ++i) {
122  GElf_Phdr phdr;
123  if (gelf_getphdr(elf, i, &phdr) == 0) {
124  panic("gelf_getphdr failed for segment %d.", i);
125  }
126 
127  if (phdr.p_type == PT_LOAD)
128  handleLoadableSegment(phdr, i);
129  if (phdr.p_type == PT_INTERP) {
130  // Make sure the interpreter is an valid ELF file.
131  auto interp_path = getInterpPath(phdr);
132  ObjectFile *obj = createObjectFile(interp_path);
133  interpreter = dynamic_cast<ElfObject *>(obj);
134  assert(interpreter != nullptr);
135  }
136  }
137 
138  // should have found at least one loadable segment
139  warn_if(image.segments().empty(),
140  "No loadable segments in '%s'. ELF file corrupted?\n",
141  imageData->filename());
142 
143  for (auto M5_VAR_USED &seg: image.segments())
144  DPRINTFR(Loader, "%s\n", seg);
145 
146  // We will actually read the sections when we need to load them
147 }
148 
149 std::string
150 ElfObject::getInterpPath(const GElf_Phdr &phdr) const
151 {
152  // This is the interpreter path as specified in the elf file
153  const std::string elf_path = (char *)imageData->data() + phdr.p_offset;
154  if (!interpDir.empty())
155  return interpDir + elf_path;
156  else
157  return elf_path;
158 }
159 
160 void
162 {
163  auto &emach = ehdr.e_machine;
164  auto &eclass = ehdr.e_ident[EI_CLASS];
165  auto &edata = ehdr.e_ident[EI_DATA];
166 
167  // Detect the architecture
168  if (emach == EM_SPARC64 || (emach == EM_SPARC && eclass == ELFCLASS64) ||
169  emach == EM_SPARCV9) {
170  arch = SPARC64;
171  } else if (emach == EM_SPARC32PLUS ||
172  (emach == EM_SPARC && eclass == ELFCLASS32)) {
173  arch = SPARC32;
174  } else if (emach == EM_MIPS && eclass == ELFCLASS32) {
175  arch = Mips;
176  if (edata != ELFDATA2LSB) {
177  fatal("The binary you're trying to load is compiled for big "
178  "endian MIPS. gem5\nonly supports little endian MIPS. "
179  "Please recompile your binary.\n");
180  }
181  } else if (emach == EM_X86_64 && eclass == ELFCLASS64) {
182  arch = X86_64;
183  } else if (emach == EM_386 && eclass == ELFCLASS32) {
184  arch = I386;
185  } else if (emach == EM_ARM && eclass == ELFCLASS32) {
186  arch = bits(ehdr.e_entry, 0) ? Thumb : Arm;
187  } else if (emach == EM_AARCH64 && eclass == ELFCLASS64) {
188  arch = Arm64;
189  } else if (emach == EM_RISCV) {
190  arch = (eclass == ELFCLASS64) ? Riscv64 : Riscv32;
191  } else if (emach == EM_PPC && eclass == ELFCLASS32) {
192  arch = Power;
193  if (edata != ELFDATA2MSB) {
194  fatal("The binary you're trying to load is compiled for "
195  "little endian Power.\ngem5 only supports big "
196  "endian Power. Please recompile your binary.\n");
197  }
198  } else if (emach == EM_PPC64) {
199  fatal("The binary you're trying to load is compiled for 64-bit "
200  "Power. M5\n only supports 32-bit Power. Please "
201  "recompile your binary.\n");
202  } else if (eclass == ELFCLASS64) {
203  // Since we don't know how to check for alpha right now, we'll
204  // just assume if it wasn't something else and it's 64 bit, that's
205  // what it must be.
206  arch = Alpha;
207  } else {
208  warn("Unknown architecture: %d\n", emach);
209  }
210 }
211 
212 void
214 {
215  // Detect the operating system
216  switch (ehdr.e_ident[EI_OSABI]) {
217  case ELFOSABI_LINUX:
218  opSys = Linux;
219  return;
220  case ELFOSABI_SOLARIS:
221  opSys = Solaris;
222  return;
223  case ELFOSABI_TRU64:
224  opSys = Tru64;
225  return;
226  case ELFOSABI_ARM:
228  return;
229  case ELFOSABI_FREEBSD:
230  opSys = FreeBSD;
231  return;
232  default:
234  }
235 
236  Elf_Scn *section = elf_getscn(elf, 1);
237  for (int sec_idx = 1; section; section = elf_getscn(elf, ++sec_idx)) {
238  GElf_Shdr shdr;
239  gelf_getshdr(section, &shdr);
240 
241  char *e_str = elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name);
242  if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag", e_str)) {
243  // we have found a ABI note section
244  // Check the 5th 32bit word for OS 0 == linux, 1 == hurd,
245  // 2 == solaris, 3 == freebsd
246  Elf_Data *raw_data = elf_rawdata(section, nullptr);
247  assert(raw_data && raw_data->d_buf);
248 
249  uint32_t raw_abi = ((uint32_t *)raw_data->d_buf)[4];
250  bool is_le = ehdr.e_ident[EI_DATA] == ELFDATA2LSB;
251  uint32_t os_abi = is_le ? htole(raw_abi) : htobe(raw_abi);
252 
253  switch (os_abi) {
254  case 0:
255  opSys = Linux;
256  return;
257  case 1:
258  fatal("gem5 does not support the HURD ABI.\n");
259  case 2:
260  opSys = Solaris;
261  return;
262  case 3:
263  opSys = FreeBSD;
264  return;
265  }
266  }
267 
268  if (!strcmp(".SUNW_version", e_str) || !strcmp(".stab.index", e_str)) {
269  opSys = Solaris;
270  return;
271  }
272  }
273 }
274 
275 void
276 ElfObject::handleLoadableSegment(GElf_Phdr phdr, int seg_num)
277 {
278  auto name = std::to_string(seg_num);
279 
280  image.addSegment({ name, phdr.p_paddr, imageData,
281  phdr.p_offset, phdr.p_filesz });
282  Addr uninitialized = phdr.p_memsz - phdr.p_filesz;
283  if (uninitialized) {
284  // There may be parts of a segment which aren't included in the
285  // file. In those cases, we need to create a new segment with no
286  // data to take up the extra space. This should be zeroed when
287  // loaded into memory.
288  image.addSegment({ name + "(uninitialized)",
289  phdr.p_paddr + phdr.p_filesz, uninitialized });
290  }
291 
292  const Addr file_start = phdr.p_offset;
293  const Addr file_end = file_start + phdr.p_filesz;
294 
295  // If there is a program header table, figure out the virtual
296  // address of the header table in the final memory image. We use
297  // the program headers themselves to translate from a file offset
298  // to the address in the image.
299  if (file_start <= ehdr.e_phoff && file_end > ehdr.e_phoff)
300  _programHeaderTable = phdr.p_vaddr + (ehdr.e_phoff - file_start);
301 }
302 
304 {
305  elf_end(elf);
306 }
307 
308 bool
310  Addr base, Addr offset)
311 {
312  if (!symtab)
313  return false;
314 
315  // check that header matches library version
316  if (elf_version(EV_CURRENT) == EV_NONE)
317  panic("wrong elf version number!");
318 
319  // get a pointer to elf structure
320  Elf *elf = elf_memory((char *)const_cast<uint8_t *>(
321  imageData->data()), imageData->len());
322  assert(elf != NULL);
323 
324  // Get the first section
325  int sec_idx = 1; // there is a 0 but it is nothing, go figure
326  Elf_Scn *section = elf_getscn(elf, sec_idx);
327 
328  // While there are no more sections
329  bool found = false;
330  while (section != NULL) {
331  GElf_Shdr shdr;
332  gelf_getshdr(section, &shdr);
333 
334  if (shdr.sh_type == SHT_SYMTAB) {
335  found = true;
336  Elf_Data *data = elf_getdata(section, NULL);
337  int count = shdr.sh_size / shdr.sh_entsize;
338  DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
339 
340  // loop through all the symbols, only loading global ones
341  for (int i = 0; i < count; ++i) {
342  GElf_Sym sym;
343  gelf_getsym(data, i, &sym);
344  if (GELF_ST_BIND(sym.st_info) == binding) {
345  char *sym_name =
346  elf_strptr(elf, shdr.sh_link, sym.st_name);
347  if (sym_name && sym_name[0] != '$') {
348  Addr value = sym.st_value - base + offset;
349  if (symtab->insert(value & mask, sym_name)) {
350  DPRINTF(Loader, "Symbol: %-40s value %#x\n",
351  sym_name, value);
352  }
353  }
354  }
355  }
356  }
357  ++sec_idx;
358  section = elf_getscn(elf, sec_idx);
359  }
360 
361  elf_end(elf);
362 
363  return found;
364 }
365 
366 bool
368  Addr addr_mask)
369 {
370  return (loadGlobalSymbols(symtab, base, offset, addr_mask) &&
371  loadLocalSymbols(symtab, base, offset, addr_mask) &&
372  loadWeakSymbols(symtab, base, offset, addr_mask));
373 }
374 
375 bool
377  Addr addr_mask)
378 {
379  if (interpreter) {
380  interpreter->loadSomeSymbols(symtab, STB_GLOBAL, addr_mask,
381  base, offset);
382  }
383  return loadSomeSymbols(symtab, STB_GLOBAL, addr_mask, base, offset);
384 }
385 
386 bool
388  Addr addr_mask)
389 {
390  if (interpreter) {
391  interpreter->loadSomeSymbols(symtab, STB_LOCAL, addr_mask,
392  base, offset);
393  }
394  return loadSomeSymbols(symtab, STB_LOCAL, addr_mask, base, offset);
395 }
396 
397 bool
399  Addr addr_mask)
400 {
401  if (interpreter) {
402  interpreter->loadSomeSymbols(symtab, STB_WEAK, addr_mask,
403  base, offset);
404  }
405  return loadSomeSymbols(symtab, STB_WEAK, addr_mask, base, offset);
406 }
407 
408 void
410 {
411  assert(!sectionNames.size());
412 
413  // check that header matches library version
414  if (elf_version(EV_CURRENT) == EV_NONE)
415  panic("wrong elf version number!");
416 
417  // get a pointer to elf structure
418  Elf *elf =
419  elf_memory((char *)const_cast<uint8_t *>(imageData->data()),
420  imageData->len());
421  assert(elf != NULL);
422 
423  // Check that we actually have a elf file
424  GElf_Ehdr ehdr;
425  if (gelf_getehdr(elf, &ehdr) ==0) {
426  panic("Not ELF, shouldn't be here");
427  }
428 
429  // Get the first section
430  int sec_idx = 1; // there is a 0 but it is nothing, go figure
431  Elf_Scn *section = elf_getscn(elf, sec_idx);
432 
433  // While there are no more sections
434  while (section) {
435  GElf_Shdr shdr;
436  gelf_getshdr(section, &shdr);
437  sectionNames.insert(elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name));
438  section = elf_getscn(elf, ++sec_idx);
439  } // while sections
440 
441  elf_end(elf);
442 }
443 
444 bool
445 ElfObject::sectionExists(std::string sec)
446 {
447  if (!sectionNames.size())
448  getSections();
449 
450  return sectionNames.find(sec) != sectionNames.end();
451 }
452 
453 
454 void
456 {
457  // Record the bias.
458  ldBias = bias_addr;
459 
460  // Patch the entry point with bias_addr.
461  entry += bias_addr;
462 
463  // Patch segments with the bias_addr.
464  image.offset(bias_addr);
465 }
count
Definition: misc.hh:705
#define panic(...)
This implements a cprintf based panic() function.
Definition: logging.hh:167
#define DPRINTF(x,...)
Definition: trace.hh:229
GElf_Ehdr ehdr
Definition: elf_object.hh:62
#define fatal(...)
This implements a cprintf based fatal() function.
Definition: logging.hh:175
const std::string & name()
Definition: trace.cc:54
Bitfield< 7 > i
void setInterpDir(const std::string &dirname)
This is the interface for setting up a base path for the elf interpreter.
Definition: elf_object.cc:98
void determineArch()
Definition: elf_object.cc:161
ObjectFile * createObjectFile(const std::string &fname, bool raw)
Definition: object_file.cc:64
void getSections()
Definition: elf_object.cc:409
ElfObject(ImageFileDataPtr ifd)
Definition: elf_object.cc:105
ImageFileDataPtr imageData
Definition: image_file.hh:44
bool sectionExists(std::string sec)
Definition: elf_object.cc:445
Bitfield< 23, 0 > offset
Definition: types.hh:154
MemoryImage image
Definition: elf_object.hh:100
const std::vector< Segment > & segments() const
void handleLoadableSegment(GElf_Phdr phdr, int seg_num)
Definition: elf_object.cc:276
bool loadLocalSymbols(SymbolTable *symtab, Addr base=0, Addr offset=0, Addr addr_mask=MaxAddr) override
Definition: elf_object.cc:387
bool loadAllSymbols(SymbolTable *symtab, Addr base=0, Addr offset=0, Addr addr_mask=MaxAddr) override
Definition: elf_object.cc:367
T htole(T value)
Definition: byteswap.hh:144
void updateBias(Addr bias_addr) override
Definition: elf_object.cc:455
OpSys opSys
Definition: object_file.hh:76
Bitfield< 51, 12 > base
Definition: pagetable.hh:142
#define warn_if(cond,...)
Conditional warning macro that checks the supplied condition and only prints a warning if the conditi...
Definition: logging.hh:228
ObjectFile * load(ImageFileDataPtr data) override
Definition: elf_object.cc:64
MemoryImage & offset(Addr by)
#define fatal_if(cond,...)
Conditional fatal macro that checks the supplied condition and only causes a fatal error if the condi...
Definition: logging.hh:203
bool insert(Addr address, std::string symbol)
Definition: symtab.cc:55
Elf * elf
Definition: elf_object.hh:61
Bitfield< 2, 0 > seg
Definition: types.hh:84
uint64_t Addr
Address type This will probably be moved somewhere else in the near future.
Definition: types.hh:142
uint16_t _programHeaderCount
Definition: elf_object.hh:72
bool loadWeakSymbols(SymbolTable *symtab, Addr base=0, Addr offset=0, Addr addr_mask=MaxAddr) override
Definition: elf_object.cc:398
ElfObject * interpreter
Definition: elf_object.hh:75
Addr _programHeaderTable
Definition: elf_object.hh:70
std::string getInterpPath(const GElf_Phdr &phdr) const
Definition: elf_object.cc:150
T htobe(T value)
Definition: byteswap.hh:146
bool loadSomeSymbols(SymbolTable *symtab, int binding, Addr mask, Addr base, Addr offset)
Helper functions for loadGlobalSymbols() and loadLocalSymbols().
Definition: elf_object.cc:309
uint16_t _programHeaderSize
Definition: elf_object.hh:71
std::set< std::string > sectionNames
Definition: elf_object.hh:73
void addSegment(const Segment &seg)
bool loadGlobalSymbols(SymbolTable *symtab, Addr base=0, Addr offset=0, Addr addr_mask=MaxAddr) override
Definition: elf_object.cc:376
Bitfield< 3, 0 > mask
Definition: types.hh:64
std::shared_ptr< ImageFileData > ImageFileDataPtr
void determineOpSys()
Definition: elf_object.cc:213
#define warn(...)
Definition: logging.hh:212
static const int NumArgumentRegs M5_VAR_USED
Definition: process.cc:84
T bits(T val, int first, int last)
Extract the bitfield from position &#39;first&#39; to &#39;last&#39; (inclusive) from &#39;val&#39; and right justify it...
Definition: bitfield.hh:72
const char data[]
const std::string to_string(sc_enc enc)
Definition: sc_fxdefs.cc:60
Addr ldBias
Definition: elf_object.hh:80
#define DPRINTFR(...)
Definition: trace.hh:231

Generated on Fri Feb 28 2020 16:26:58 for gem5 by doxygen 1.8.13