elf_object.cc revision 5759:6e65ac8a2c80
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            // If it's none of the above but is loadable,
295            // load the filesize worth of data
296            Segment extra;
297            extra.baseAddr = phdr.p_paddr;
298            extra.size = phdr.p_filesz;
299            extra.fileImage = fileData + phdr.p_offset;
300            extraSegments.push_back(extra);
301        }
302    }
303
304    // should have found at least one loadable segment
305    assert(text.size != 0);
306
307    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
308             text.baseAddr, text.size, data.baseAddr, data.size,
309             bss.baseAddr, bss.size);
310
311    elf_end(elf);
312
313    // We will actually read the sections when we need to load them
314}
315
316
317bool
318ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
319{
320    Elf *elf;
321    int sec_idx = 1; // there is a 0 but it is nothing, go figure
322    Elf_Scn *section;
323    GElf_Shdr shdr;
324    Elf_Data *data;
325    int count, ii;
326    bool found = false;
327    GElf_Sym sym;
328
329    if (!symtab)
330        return false;
331
332    // check that header matches library version
333    if (elf_version(EV_CURRENT) == EV_NONE)
334        panic("wrong elf version number!");
335
336    // get a pointer to elf structure
337    elf = elf_memory((char*)fileData,len);
338
339    assert(elf != NULL);
340
341    // Get the first section
342    section = elf_getscn(elf, sec_idx);
343
344    // While there are no more sections
345    while (section != NULL) {
346        gelf_getshdr(section, &shdr);
347
348        if (shdr.sh_type == SHT_SYMTAB) {
349            found = true;
350            data = elf_getdata(section, NULL);
351            count = shdr.sh_size / shdr.sh_entsize;
352            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
353
354            // loop through all the symbols, only loading global ones
355            for (ii = 0; ii < count; ++ii) {
356                gelf_getsym(data, ii, &sym);
357                if (GELF_ST_BIND(sym.st_info) == binding) {
358                   symtab->insert(sym.st_value,
359                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
360                }
361            }
362        }
363        ++sec_idx;
364        section = elf_getscn(elf, sec_idx);
365    }
366
367    elf_end(elf);
368
369    return found;
370}
371
372bool
373ElfObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
374{
375    return loadSomeSymbols(symtab, STB_GLOBAL);
376}
377
378bool
379ElfObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
380{
381    return loadSomeSymbols(symtab, STB_LOCAL);
382}
383
384bool
385ElfObject::loadSections(Port *memPort, Addr addrMask)
386{
387    if (!ObjectFile::loadSections(memPort, addrMask))
388        return false;
389
390    vector<Segment>::iterator extraIt;
391    for (extraIt = extraSegments.begin();
392            extraIt != extraSegments.end(); extraIt++) {
393        if (!loadSection(&(*extraIt), memPort, addrMask)) {
394            return false;
395        }
396    }
397    return true;
398}
399
400void
401ElfObject::getSections()
402{
403    Elf *elf;
404    int sec_idx = 1; // there is a 0 but it is nothing, go figure
405    Elf_Scn *section;
406    GElf_Shdr shdr;
407
408    GElf_Ehdr ehdr;
409
410    assert(!sectionNames.size());
411
412    // check that header matches library version
413    if (elf_version(EV_CURRENT) == EV_NONE)
414        panic("wrong elf version number!");
415
416    // get a pointer to elf structure
417    elf = elf_memory((char*)fileData,len);
418    assert(elf != NULL);
419
420    // Check that we actually have a elf file
421    if (gelf_getehdr(elf, &ehdr) ==0) {
422        panic("Not ELF, shouldn't be here");
423    }
424
425    // Get the first section
426    section = elf_getscn(elf, sec_idx);
427
428    // While there are no more sections
429    while (section != NULL) {
430        gelf_getshdr(section, &shdr);
431        sectionNames.insert(elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name));
432        section = elf_getscn(elf, ++sec_idx);
433    } // while sections
434}
435
436bool
437ElfObject::sectionExists(string sec)
438{
439    if (!sectionNames.size())
440        getSections();
441    return sectionNames.find(sec) != sectionNames.end();
442}
443
444
445