elf_object.cc revision 10880
1/*
2 * Copyright (c) 2011-2013 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
44#include <cassert>
45#include <string>
46
47#include "base/loader/elf_object.hh"
48#include "base/loader/symtab.hh"
49#include "base/bitfield.hh"
50#include "base/misc.hh"
51#include "base/trace.hh"
52#include "debug/Loader.hh"
53#include "sim/byteswap.hh"
54#include "gelf.h"
55
56using namespace std;
57
58ObjectFile *
59ElfObject::tryFile(const string &fname, size_t len, uint8_t *data)
60{
61    Elf *elf;
62    GElf_Ehdr ehdr;
63    Arch arch = UnknownArch;
64    OpSys opSys = UnknownOpSys;
65
66    // check that header matches library version
67    if (elf_version(EV_CURRENT) == EV_NONE)
68        panic("wrong elf version number!");
69
70    // get a pointer to elf structure
71    elf = elf_memory((char*)data,len);
72    assert(elf != NULL);
73
74    // Check that we actually have a elf file
75    if (gelf_getehdr(elf, &ehdr) == 0) {
76        DPRINTFR(Loader, "Not ELF\n");
77        elf_end(elf);
78        return NULL;
79    } else {
80        //Detect the architecture
81        //Since we don't know how to check for alpha right now, we'll
82        //just assume if it wasn't something else and it's 64 bit, that's
83        //what it must be.
84        if (ehdr.e_machine == EM_SPARC64 ||
85                (ehdr.e_machine == EM_SPARC &&
86                 ehdr.e_ident[EI_CLASS] == ELFCLASS64)||
87                ehdr.e_machine == EM_SPARCV9) {
88            arch = ObjectFile::SPARC64;
89        } else if (ehdr.e_machine == EM_SPARC32PLUS ||
90                        (ehdr.e_machine == EM_SPARC &&
91                         ehdr.e_ident[EI_CLASS] == ELFCLASS32)) {
92            arch = ObjectFile::SPARC32;
93        } else if (ehdr.e_machine == EM_MIPS
94                && ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
95            if (ehdr.e_ident[EI_DATA] == ELFDATA2LSB) {
96                arch = ObjectFile::Mips;
97            } else {
98                fatal("The binary you're trying to load is compiled for big "
99                        "endian MIPS. M5\nonly supports little endian MIPS. "
100                        "Please recompile your binary.\n");
101            }
102        } else if (ehdr.e_machine == EM_X86_64 &&
103                ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
104            arch = ObjectFile::X86_64;
105        } else if (ehdr.e_machine == EM_386 &&
106                ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
107            arch = ObjectFile::I386;
108        } else if (ehdr.e_machine == EM_ARM &&
109                ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
110            if (bits(ehdr.e_entry, 0)) {
111                arch = ObjectFile::Thumb;
112            } else {
113                arch = ObjectFile::Arm;
114            }
115        } else if ((ehdr.e_machine == EM_AARCH64) &&
116                ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
117            arch = ObjectFile::Arm64;
118        } else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
119            arch = ObjectFile::Alpha;
120        } else if (ehdr.e_machine == EM_PPC &&
121                ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
122            if (ehdr.e_ident[EI_DATA] == ELFDATA2MSB) {
123                  arch = ObjectFile::Power;
124            } else {
125                  fatal("The binary you're trying to load is compiled for "
126                        "little endian Power.\nM5 only supports big "
127                        "endian Power. Please recompile your binary.\n");
128            }
129        } else if (ehdr.e_machine == EM_PPC64) {
130            fatal("The binary you're trying to load is compiled for 64-bit "
131                  "Power. M5\n only supports 32-bit Power. Please "
132                  "recompile your binary.\n");
133        } else {
134            warn("Unknown architecture: %d\n", ehdr.e_machine);
135            arch = ObjectFile::UnknownArch;
136        }
137
138        //Detect the operating system
139        switch (ehdr.e_ident[EI_OSABI]) {
140          case ELFOSABI_LINUX:
141            opSys = ObjectFile::Linux;
142            break;
143          case ELFOSABI_SOLARIS:
144            opSys = ObjectFile::Solaris;
145            break;
146          case ELFOSABI_TRU64:
147            opSys = ObjectFile::Tru64;
148            break;
149          case ELFOSABI_ARM:
150            opSys = ObjectFile::LinuxArmOABI;
151            break;
152          case ELFOSABI_FREEBSD:
153            opSys = ObjectFile::FreeBSD;
154            break;
155          default:
156            opSys = ObjectFile::UnknownOpSys;
157        }
158
159        //take a look at the .note.ABI section
160        //It can let us know what's what.
161        if (opSys == ObjectFile::UnknownOpSys) {
162            Elf_Scn *section;
163            GElf_Shdr shdr;
164            Elf_Data *data;
165            uint32_t osAbi;
166            uint32_t *elem;
167            int secIdx = 1;
168
169            // Get the first section
170            section = elf_getscn(elf, secIdx);
171
172            // While there are no more sections
173            while (section != NULL && opSys == ObjectFile::UnknownOpSys) {
174                gelf_getshdr(section, &shdr);
175                if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag",
176                            elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name))) {
177                    // we have found a ABI note section
178                    // Check the 5th 32bit word for OS  0 == linux, 1 == hurd,
179                    // 2 == solaris, 3 == freebsd
180                    data = elf_rawdata(section, NULL);
181                    assert(data->d_buf);
182                    if(ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
183                        osAbi = htole(((uint32_t*)data->d_buf)[4]);
184                    else
185                        osAbi = htobe(((uint32_t*)data->d_buf)[4]);
186
187                    switch(osAbi) {
188                      case 0:
189                        opSys = ObjectFile::Linux;
190                        break;
191                      case 2:
192                        opSys = ObjectFile::Solaris;
193                        break;
194                    }
195                } // if section found
196                if (!strcmp(".SUNW_version", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
197                        opSys = ObjectFile::Solaris;
198                if (!strcmp(".stab.index", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
199                        opSys = ObjectFile::Solaris;
200                if (shdr.sh_type == SHT_NOTE && !strcmp(".note.tag",
201                            elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name))) {
202                    data = elf_rawdata(section, NULL);
203                    assert(data->d_buf);
204                    elem = (uint32_t *)data->d_buf;
205                    if (elem[0] == 0x8) { //size of name
206                        if (memcmp((void *)&elem[3], "FreeBSD", 0x8) == 0)
207                                opSys = ObjectFile::FreeBSD;
208                    }
209                }
210
211            section = elf_getscn(elf, ++secIdx);
212            } // while sections
213        }
214
215        ElfObject * result = new ElfObject(fname, len, data, arch, opSys);
216
217        //The number of headers in the file
218        result->_programHeaderCount = ehdr.e_phnum;
219        //Record the size of each entry
220        result->_programHeaderSize = ehdr.e_phentsize;
221        if(result->_programHeaderCount) //If there is a program header table
222        {
223            //Figure out the virtual address of the header table in the
224            //final memory image. We use the program headers themselves
225            //to translate from a file offset to the address in the image.
226            GElf_Phdr phdr;
227            uint64_t e_phoff = ehdr.e_phoff;
228            result->_programHeaderTable = 0;
229            for(int hdrnum = 0; hdrnum < result->_programHeaderCount; hdrnum++)
230            {
231                gelf_getphdr(elf, hdrnum, &phdr);
232                //Check if we've found the segment with the headers in it
233                if(phdr.p_offset <= e_phoff &&
234                        phdr.p_offset + phdr.p_filesz > e_phoff)
235                {
236                    result->_programHeaderTable =
237                        phdr.p_paddr + (e_phoff - phdr.p_offset);
238                    break;
239                }
240            }
241        }
242        else
243            result->_programHeaderTable = 0;
244
245
246        elf_end(elf);
247        return result;
248    }
249}
250
251
252ElfObject::ElfObject(const string &_filename, size_t _len, uint8_t *_data,
253                     Arch _arch, OpSys _opSys)
254    : ObjectFile(_filename, _len, _data, _arch, _opSys),
255      _programHeaderTable(0), _programHeaderSize(0), _programHeaderCount(0)
256
257{
258    Elf *elf;
259    GElf_Ehdr ehdr;
260
261    // check that header matches library version
262    if (elf_version(EV_CURRENT) == EV_NONE)
263        panic("wrong elf version number!");
264
265    // get a pointer to elf structure
266    elf = elf_memory((char*)fileData,len);
267    assert(elf != NULL);
268
269    // Check that we actually have a elf file
270    if (gelf_getehdr(elf, &ehdr) ==0) {
271        panic("Not ELF, shouldn't be here");
272    }
273
274    entry = ehdr.e_entry;
275
276    // initialize segment sizes to 0 in case they're not present
277    text.size = data.size = bss.size = 0;
278    text.baseAddr = data.baseAddr = bss.baseAddr = 0;
279
280    int secIdx = 1;
281    Elf_Scn *section;
282    GElf_Shdr shdr;
283
284    // The first address of some important sections.
285    Addr textSecStart = 0;
286    Addr dataSecStart = 0;
287    Addr bssSecStart = 0;
288
289    // Get the first section
290    section = elf_getscn(elf, secIdx);
291
292    // Find the beginning of the most interesting sections.
293    while (section != NULL) {
294        gelf_getshdr(section, &shdr);
295        char * secName = elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name);
296
297        if (secName) {
298            if (!strcmp(".text", secName)) {
299                textSecStart = shdr.sh_addr;
300            } else if (!strcmp(".data", secName)) {
301                dataSecStart = shdr.sh_addr;
302            } else if (!strcmp(".bss", secName)) {
303                bssSecStart = shdr.sh_addr;
304            }
305        } else {
306            Elf_Error errorNum = (Elf_Error)elf_errno();
307            if (errorNum != ELF_E_NONE) {
308                const char *errorMessage = elf_errmsg(errorNum);
309                fatal("Error from libelf: %s.\n", errorMessage);
310            }
311        }
312
313        section = elf_getscn(elf, ++secIdx);
314    }
315
316    // Go through all the segments in the program, record them, and scrape
317    // out information about the text, data, and bss areas needed by other
318    // code.
319    for (int i = 0; i < ehdr.e_phnum; ++i) {
320        GElf_Phdr phdr;
321        if (gelf_getphdr(elf, i, &phdr) == 0) {
322            panic("gelf_getphdr failed for segment %d.", i);
323        }
324
325        // for now we don't care about non-loadable segments
326        if (!(phdr.p_type & PT_LOAD))
327            continue;
328
329        // Check to see if this segment contains the bss section.
330        if (phdr.p_paddr <= bssSecStart &&
331                phdr.p_paddr + phdr.p_memsz > bssSecStart &&
332                phdr.p_memsz - phdr.p_filesz > 0) {
333            bss.baseAddr = phdr.p_paddr + phdr.p_filesz;
334            bss.size = phdr.p_memsz - phdr.p_filesz;
335            bss.fileImage = NULL;
336        }
337
338        // Check to see if this is the text or data segment
339        if (phdr.p_vaddr <= textSecStart &&
340                phdr.p_vaddr + phdr.p_filesz > textSecStart) {
341            text.baseAddr = phdr.p_paddr;
342            text.size = phdr.p_filesz;
343            text.fileImage = fileData + phdr.p_offset;
344        } else if (phdr.p_vaddr <= dataSecStart &&
345                phdr.p_vaddr + phdr.p_filesz > dataSecStart) {
346            data.baseAddr = phdr.p_paddr;
347            data.size = phdr.p_filesz;
348            data.fileImage = fileData + phdr.p_offset;
349        } else {
350            // If it's none of the above but is loadable,
351            // load the filesize worth of data
352            Segment extra;
353            extra.baseAddr = phdr.p_paddr;
354            extra.size = phdr.p_filesz;
355            extra.fileImage = fileData + phdr.p_offset;
356            extraSegments.push_back(extra);
357        }
358    }
359
360    // should have found at least one loadable segment
361    assert(text.size != 0);
362
363    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
364             text.baseAddr, text.size, data.baseAddr, data.size,
365             bss.baseAddr, bss.size);
366
367    elf_end(elf);
368
369    // We will actually read the sections when we need to load them
370}
371
372
373bool
374ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding, Addr mask)
375{
376    Elf *elf;
377    int sec_idx = 1; // there is a 0 but it is nothing, go figure
378    Elf_Scn *section;
379    GElf_Shdr shdr;
380    Elf_Data *data;
381    int count, ii;
382    bool found = false;
383    GElf_Sym sym;
384
385    if (!symtab)
386        return false;
387
388    // check that header matches library version
389    if (elf_version(EV_CURRENT) == EV_NONE)
390        panic("wrong elf version number!");
391
392    // get a pointer to elf structure
393    elf = elf_memory((char*)fileData,len);
394
395    assert(elf != NULL);
396
397    // Get the first section
398    section = elf_getscn(elf, sec_idx);
399
400    // While there are no more sections
401    while (section != NULL) {
402        gelf_getshdr(section, &shdr);
403
404        if (shdr.sh_type == SHT_SYMTAB) {
405            found = true;
406            data = elf_getdata(section, NULL);
407            count = shdr.sh_size / shdr.sh_entsize;
408            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
409
410            // loop through all the symbols, only loading global ones
411            for (ii = 0; ii < count; ++ii) {
412                gelf_getsym(data, ii, &sym);
413                if (GELF_ST_BIND(sym.st_info) == binding) {
414                    char *sym_name = elf_strptr(elf, shdr.sh_link, sym.st_name);
415                    if (sym_name && sym_name[0] != '$') {
416                        DPRINTF(Loader, "Symbol: %-40s value %#x\n",
417                                sym_name, sym.st_value);
418                        symtab->insert(sym.st_value & mask, sym_name);
419                    }
420                }
421            }
422        }
423        ++sec_idx;
424        section = elf_getscn(elf, sec_idx);
425    }
426
427    elf_end(elf);
428
429    return found;
430}
431
432bool
433ElfObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
434{
435    return loadSomeSymbols(symtab, STB_GLOBAL, addrMask);
436}
437
438bool
439ElfObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
440{
441    bool found_local = loadSomeSymbols(symtab, STB_LOCAL, addrMask);
442    bool found_weak = loadSomeSymbols(symtab, STB_WEAK, addrMask);
443    return found_local || found_weak;
444}
445
446bool
447ElfObject::loadWeakSymbols(SymbolTable *symtab, Addr addrMask)
448{
449    return loadSomeSymbols(symtab, STB_WEAK, addrMask);
450}
451
452bool
453ElfObject::loadSections(PortProxy& memProxy, Addr addrMask, Addr offset)
454{
455    if (!ObjectFile::loadSections(memProxy, addrMask, offset))
456        return false;
457
458    vector<Segment>::iterator extraIt;
459    for (extraIt = extraSegments.begin();
460            extraIt != extraSegments.end(); extraIt++) {
461        if (!loadSection(&(*extraIt), memProxy, addrMask, offset)) {
462            return false;
463        }
464    }
465    return true;
466}
467
468void
469ElfObject::getSections()
470{
471    Elf *elf;
472    int sec_idx = 1; // there is a 0 but it is nothing, go figure
473    Elf_Scn *section;
474    GElf_Shdr shdr;
475
476    GElf_Ehdr ehdr;
477
478    assert(!sectionNames.size());
479
480    // check that header matches library version
481    if (elf_version(EV_CURRENT) == EV_NONE)
482        panic("wrong elf version number!");
483
484    // get a pointer to elf structure
485    elf = elf_memory((char*)fileData,len);
486    assert(elf != NULL);
487
488    // Check that we actually have a elf file
489    if (gelf_getehdr(elf, &ehdr) ==0) {
490        panic("Not ELF, shouldn't be here");
491    }
492
493    // Get the first section
494    section = elf_getscn(elf, sec_idx);
495
496    // While there are no more sections
497    while (section != NULL) {
498        gelf_getshdr(section, &shdr);
499        sectionNames.insert(elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name));
500        section = elf_getscn(elf, ++sec_idx);
501    } // while sections
502}
503
504bool
505ElfObject::sectionExists(string sec)
506{
507    if (!sectionNames.size())
508        getSections();
509    return sectionNames.find(sec) != sectionNames.end();
510}
511
512
513