elf_object.cc revision 5616
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Steve Reinhardt
29 *          Ali Saidi
30 */
31
32#include <cassert>
33#include <string>
34
35#include "gelf.h"
36
37#include "base/loader/elf_object.hh"
38#include "base/loader/symtab.hh"
39#include "base/misc.hh"
40#include "base/trace.hh"        // for DPRINTF
41#include "sim/byteswap.hh"
42
43using namespace std;
44
45ObjectFile *
46ElfObject::tryFile(const string &fname, int fd, size_t len, uint8_t *data)
47{
48    Elf *elf;
49    GElf_Ehdr ehdr;
50    Arch arch = UnknownArch;
51    OpSys opSys = UnknownOpSys;
52
53    // check that header matches library version
54    if (elf_version(EV_CURRENT) == EV_NONE)
55        panic("wrong elf version number!");
56
57    // get a pointer to elf structure
58    elf = elf_memory((char*)data,len);
59    // will only fail if fd is invalid
60    assert(elf != NULL);
61
62    // Check that we actually have a elf file
63    if (gelf_getehdr(elf, &ehdr) ==0) {
64        DPRINTFR(Loader, "Not ELF\n");
65        elf_end(elf);
66        return NULL;
67    } else {
68        //Detect the architecture
69        //Since we don't know how to check for alpha right now, we'll
70        //just assume if it wasn't something else and it's 64 bit, that's
71        //what it must be.
72        if (ehdr.e_machine == EM_SPARC64 ||
73                (ehdr.e_machine == EM_SPARC &&
74                 ehdr.e_ident[EI_CLASS] == ELFCLASS64)||
75                ehdr.e_machine == EM_SPARCV9) {
76            arch = ObjectFile::SPARC64;
77        } else if (ehdr.e_machine == EM_SPARC32PLUS ||
78                        (ehdr.e_machine == EM_SPARC &&
79                         ehdr.e_ident[EI_CLASS] == ELFCLASS32)) {
80            arch = ObjectFile::SPARC32;
81        } else if (ehdr.e_machine == EM_MIPS
82                && ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
83            if (ehdr.e_ident[EI_DATA] == ELFDATA2LSB) {
84                arch = ObjectFile::Mips;
85            } else {
86                fatal("The binary you're trying to load is compiled for big "
87                        "endian MIPS. M5\nonly supports little endian MIPS. "
88                        "Please recompile your binary.\n");
89            }
90        } else if (ehdr.e_machine == EM_X86_64 &&
91                ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
92            //In the future, we might want to differentiate between 32 bit
93            //and 64 bit x86 processes in case there are differences in their
94            //initial stack frame.
95            arch = ObjectFile::X86;
96        } else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
97            arch = ObjectFile::Alpha;
98        } else if (ehdr.e_machine == EM_ARM) {
99            arch = ObjectFile::Arm;
100        } else {
101            warn("Unknown architecture: %d\n", ehdr.e_machine);
102            arch = ObjectFile::UnknownArch;
103        }
104
105        //Detect the operating system
106        switch (ehdr.e_ident[EI_OSABI])
107        {
108
109          case ELFOSABI_LINUX:
110          case ELFOSABI_ARM:
111            opSys = ObjectFile::Linux;
112            break;
113          case ELFOSABI_SOLARIS:
114            opSys = ObjectFile::Solaris;
115            break;
116          case ELFOSABI_TRU64:
117            opSys = ObjectFile::Tru64;
118            break;
119          default:
120            opSys = ObjectFile::UnknownOpSys;
121        }
122
123        //take a look at the .note.ABI section
124        //It can let us know what's what.
125        if (opSys == ObjectFile::UnknownOpSys) {
126            Elf_Scn *section;
127            GElf_Shdr shdr;
128            Elf_Data *data;
129            uint32_t osAbi;;
130            int secIdx = 1;
131
132            // Get the first section
133            section = elf_getscn(elf, secIdx);
134
135            // While there are no more sections
136            while (section != NULL && opSys == ObjectFile::UnknownOpSys) {
137                gelf_getshdr(section, &shdr);
138                if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag",
139                            elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name))) {
140                    // we have found a ABI note section
141                    // Check the 5th 32bit word for OS  0 == linux, 1 == hurd,
142                    // 2 == solaris, 3 == freebsd
143                    data = elf_rawdata(section, NULL);
144                    assert(data->d_buf);
145                    if(ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
146                        osAbi = htole(((uint32_t*)data->d_buf)[4]);
147                    else
148                        osAbi = htobe(((uint32_t*)data->d_buf)[4]);
149
150                    switch(osAbi) {
151                      case 0:
152                        opSys = ObjectFile::Linux;
153                        break;
154                      case 2:
155                        opSys = ObjectFile::Solaris;
156                        break;
157                    }
158                } // if section found
159                if (!strcmp(".SUNW_version", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
160                        opSys = ObjectFile::Solaris;
161                if (!strcmp(".stab.index", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
162                        opSys = ObjectFile::Solaris;
163
164            section = elf_getscn(elf, ++secIdx);
165            } // while sections
166        }
167
168        ElfObject * result = new ElfObject(fname, fd, len, data, arch, opSys);
169
170        //The number of headers in the file
171        result->_programHeaderCount = ehdr.e_phnum;
172        //Record the size of each entry
173        result->_programHeaderSize = ehdr.e_phentsize;
174        if(result->_programHeaderCount) //If there is a program header table
175        {
176            //Figure out the virtual address of the header table in the
177            //final memory image. We use the program headers themselves
178            //to translate from a file offset to the address in the image.
179            GElf_Phdr phdr;
180            uint64_t e_phoff = ehdr.e_phoff;
181            result->_programHeaderTable = 0;
182            for(int hdrnum = 0; hdrnum < result->_programHeaderCount; hdrnum++)
183            {
184                gelf_getphdr(elf, hdrnum, &phdr);
185                //Check if we've found the segment with the headers in it
186                if(phdr.p_offset <= e_phoff &&
187                        phdr.p_offset + phdr.p_filesz > e_phoff)
188                {
189                    result->_programHeaderTable = phdr.p_paddr + e_phoff;
190                    break;
191                }
192            }
193        }
194        else
195            result->_programHeaderTable = 0;
196
197
198        elf_end(elf);
199        return result;
200    }
201}
202
203
204ElfObject::ElfObject(const string &_filename, int _fd,
205                     size_t _len, uint8_t *_data,
206                     Arch _arch, OpSys _opSys)
207    : ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
208
209{
210    Elf *elf;
211    GElf_Ehdr ehdr;
212
213    // check that header matches library version
214    if (elf_version(EV_CURRENT) == EV_NONE)
215        panic("wrong elf version number!");
216
217    // get a pointer to elf structure
218    elf = elf_memory((char*)fileData,len);
219    // will only fail if fd is invalid
220    assert(elf != NULL);
221
222    // Check that we actually have a elf file
223    if (gelf_getehdr(elf, &ehdr) ==0) {
224        panic("Not ELF, shouldn't be here");
225    }
226
227    entry = ehdr.e_entry;
228
229    // initialize segment sizes to 0 in case they're not present
230    text.size = data.size = bss.size = 0;
231
232    int secIdx = 1;
233    Elf_Scn *section;
234    GElf_Shdr shdr;
235
236    // The first address of some important sections.
237    Addr textSecStart = 0;
238    Addr dataSecStart = 0;
239    Addr bssSecStart = 0;
240
241    // Get the first section
242    section = elf_getscn(elf, secIdx);
243
244    // Find the beginning of the most interesting sections.
245    while (section != NULL) {
246        gelf_getshdr(section, &shdr);
247        char * secName = elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name);
248
249        if (!strcmp(".text", secName)) {
250            textSecStart = shdr.sh_addr;
251        } else if (!strcmp(".data", secName)) {
252            dataSecStart = shdr.sh_addr;
253        } else if (!strcmp(".bss", secName)) {
254            bssSecStart = shdr.sh_addr;
255        }
256
257        section = elf_getscn(elf, ++secIdx);
258    }
259
260    // Go through all the segments in the program, record them, and scrape
261    // out information about the text, data, and bss areas needed by other
262    // code.
263    for (int i = 0; i < ehdr.e_phnum; ++i) {
264        GElf_Phdr phdr;
265        if (gelf_getphdr(elf, i, &phdr) == 0) {
266            panic("gelf_getphdr failed for segment %d.", i);
267        }
268
269        // for now we don't care about non-loadable segments
270        if (!(phdr.p_type & PT_LOAD))
271            continue;
272
273        // Check to see if this segment contains the bss section.
274        if (phdr.p_paddr <= bssSecStart &&
275                phdr.p_paddr + phdr.p_memsz > bssSecStart &&
276                phdr.p_memsz - phdr.p_filesz > 0) {
277            bss.baseAddr = phdr.p_paddr + phdr.p_filesz;
278            bss.size = phdr.p_memsz - phdr.p_filesz;
279            bss.fileImage = NULL;
280        }
281
282        // Check to see if this is the text or data segment
283        if (phdr.p_vaddr <= textSecStart &&
284                phdr.p_vaddr + phdr.p_filesz > textSecStart) {
285            text.baseAddr = phdr.p_paddr;
286            text.size = phdr.p_filesz;
287            text.fileImage = fileData + phdr.p_offset;
288        } else if (phdr.p_vaddr <= dataSecStart &&
289                phdr.p_vaddr + phdr.p_filesz > dataSecStart) {
290            data.baseAddr = phdr.p_paddr;
291            data.size = phdr.p_filesz;
292            data.fileImage = fileData + phdr.p_offset;
293        } else {
294            Segment extra;
295            extra.baseAddr = phdr.p_paddr;
296            extra.size = phdr.p_filesz;
297            extra.fileImage = fileData + phdr.p_offset;
298            extraSegments.push_back(extra);
299        }
300    }
301
302    // should have found at least one loadable segment
303    assert(text.size != 0);
304
305    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
306             text.baseAddr, text.size, data.baseAddr, data.size,
307             bss.baseAddr, bss.size);
308
309    elf_end(elf);
310
311    // We will actually read the sections when we need to load them
312}
313
314
315bool
316ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
317{
318    Elf *elf;
319    int sec_idx = 1; // there is a 0 but it is nothing, go figure
320    Elf_Scn *section;
321    GElf_Shdr shdr;
322    Elf_Data *data;
323    int count, ii;
324    bool found = false;
325    GElf_Sym sym;
326
327    if (!symtab)
328        return false;
329
330    // check that header matches library version
331    if (elf_version(EV_CURRENT) == EV_NONE)
332        panic("wrong elf version number!");
333
334    // get a pointer to elf structure
335    elf = elf_memory((char*)fileData,len);
336
337    assert(elf != NULL);
338
339    // Get the first section
340    section = elf_getscn(elf, sec_idx);
341
342    // While there are no more sections
343    while (section != NULL) {
344        gelf_getshdr(section, &shdr);
345
346        if (shdr.sh_type == SHT_SYMTAB) {
347            found = true;
348            data = elf_getdata(section, NULL);
349            count = shdr.sh_size / shdr.sh_entsize;
350            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
351
352            // loop through all the symbols, only loading global ones
353            for (ii = 0; ii < count; ++ii) {
354                gelf_getsym(data, ii, &sym);
355                if (GELF_ST_BIND(sym.st_info) == binding) {
356                   symtab->insert(sym.st_value,
357                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
358                }
359            }
360        }
361        ++sec_idx;
362        section = elf_getscn(elf, sec_idx);
363    }
364
365    elf_end(elf);
366
367    return found;
368}
369
370bool
371ElfObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
372{
373    return loadSomeSymbols(symtab, STB_GLOBAL);
374}
375
376bool
377ElfObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
378{
379    return loadSomeSymbols(symtab, STB_LOCAL);
380}
381
382bool
383ElfObject::loadSections(Port *memPort, Addr addrMask)
384{
385    if (!ObjectFile::loadSections(memPort, addrMask))
386        return false;
387
388    vector<Segment>::iterator extraIt;
389    for (extraIt = extraSegments.begin();
390            extraIt != extraSegments.end(); extraIt++) {
391        if (!loadSection(&(*extraIt), memPort, addrMask)) {
392            return false;
393        }
394    }
395    return true;
396}
397
398void
399ElfObject::getSections()
400{
401    Elf *elf;
402    int sec_idx = 1; // there is a 0 but it is nothing, go figure
403    Elf_Scn *section;
404    GElf_Shdr shdr;
405
406    GElf_Ehdr ehdr;
407
408    assert(!sectionNames.size());
409
410    // check that header matches library version
411    if (elf_version(EV_CURRENT) == EV_NONE)
412        panic("wrong elf version number!");
413
414    // get a pointer to elf structure
415    elf = elf_memory((char*)fileData,len);
416    assert(elf != NULL);
417
418    // Check that we actually have a elf file
419    if (gelf_getehdr(elf, &ehdr) ==0) {
420        panic("Not ELF, shouldn't be here");
421    }
422
423    // Get the first section
424    section = elf_getscn(elf, sec_idx);
425
426    // While there are no more sections
427    while (section != NULL) {
428        gelf_getshdr(section, &shdr);
429        sectionNames.insert(elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name));
430        section = elf_getscn(elf, ++sec_idx);
431    } // while sections
432}
433
434bool
435ElfObject::sectionExists(string sec)
436{
437    if (!sectionNames.size())
438        getSections();
439    return sectionNames.find(sec) != sectionNames.end();
440}
441
442
443