elf_object.cc revision 3812:eaa215123a26
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 <string>
33
34// Because of the -Wundef flag we have to do this
35#define __LIBELF_INTERNAL__     0
36#define __LIBELF_NEED_LINK_H    0
37#define __LIBELF_SYMBOL_VERSIONS 0
38
39#include "gelf.h"
40
41#include "base/loader/elf_object.hh"
42#include "base/misc.hh"
43
44#include "base/loader/symtab.hh"
45
46#include "base/trace.hh"	// for DPRINTF
47
48#include "sim/byteswap.hh"
49
50
51using namespace std;
52
53ObjectFile *
54ElfObject::tryFile(const string &fname, int fd, size_t len, uint8_t *data)
55{
56    Elf *elf;
57    GElf_Ehdr ehdr;
58    Arch arch = UnknownArch;
59    OpSys opSys = UnknownOpSys;
60
61    // check that header matches library version
62    if (elf_version(EV_CURRENT) == EV_NONE)
63        panic("wrong elf version number!");
64
65    // get a pointer to elf structure
66    elf = elf_memory((char*)data,len);
67    // will only fail if fd is invalid
68    assert(elf != NULL);
69
70    // Check that we actually have a elf file
71    if (gelf_getehdr(elf, &ehdr) ==0) {
72        DPRINTFR(Loader, "Not ELF\n");
73        elf_end(elf);
74        return NULL;
75    } else {
76        //Detect the architecture
77        //Since we don't know how to check for alpha right now, we'll
78        //just assume if it wasn't something else and it's 64 bit, that's
79        //what it must be.
80        if (ehdr.e_machine == EM_SPARC64 ||
81                ehdr.e_machine == EM_SPARC ||
82                ehdr.e_machine == EM_SPARCV9) {
83            arch = ObjectFile::SPARC;
84        } else if (ehdr.e_machine == EM_MIPS
85                && ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
86            arch = ObjectFile::Mips;
87        } else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
88            arch = ObjectFile::Alpha;
89        } else {
90            warn("Unknown architecture: %d\n", ehdr.e_machine);
91            arch = ObjectFile::UnknownArch;
92        }
93
94        //Detect the operating system
95        switch (ehdr.e_ident[EI_OSABI])
96        {
97
98          case ELFOSABI_LINUX:
99            opSys = ObjectFile::Linux;
100            break;
101          case ELFOSABI_SOLARIS:
102            opSys = ObjectFile::Solaris;
103            break;
104          case ELFOSABI_TRU64:
105            opSys = ObjectFile::Tru64;
106            break;
107          default:
108            opSys = ObjectFile::UnknownOpSys;
109        }
110
111        //take a look at the .note.ABI section
112        //It can let us know what's what.
113        if (opSys == ObjectFile::UnknownOpSys) {
114            Elf_Scn *section;
115            GElf_Shdr shdr;
116            Elf_Data *data;
117            uint32_t osAbi;;
118            int secIdx = 1;
119
120            // Get the first section
121            section = elf_getscn(elf, secIdx);
122
123            // While there are no more sections
124            while (section != NULL && opSys == ObjectFile::UnknownOpSys) {
125                gelf_getshdr(section, &shdr);
126                if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag",
127                            elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name))) {
128                    // we have found a ABI note section
129                    // Check the 5th 32bit word for OS  0 == linux, 1 == hurd,
130                    // 2 == solaris, 3 == freebsd
131                    data = elf_rawdata(section, NULL);
132                    assert(data->d_buf);
133                    if(ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
134                        osAbi = htole(((uint32_t*)data->d_buf)[4]);
135                    else
136                        osAbi = htobe(((uint32_t*)data->d_buf)[4]);
137
138                    switch(osAbi) {
139                      case 0:
140                        opSys = ObjectFile::Linux;
141                        break;
142                      case 2:
143                        opSys = ObjectFile::Solaris;
144                        break;
145                    }
146                } // if section found
147                if (!strcmp(".SUNW_version", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
148                        opSys = ObjectFile::Solaris;
149                if (!strcmp(".stab.index", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
150                        opSys = ObjectFile::Solaris;
151
152            section = elf_getscn(elf, ++secIdx);
153            } // while sections
154        }
155
156        ElfObject * result = new ElfObject(fname, fd, len, data, arch, opSys);
157
158        //The number of headers in the file
159        result->_programHeaderCount = ehdr.e_phnum;
160        //Record the size of each entry
161        result->_programHeaderSize = ehdr.e_phentsize;
162        if(result->_programHeaderCount) //If there is a program header table
163        {
164            //Figure out the virtual address of the header table in the
165            //final memory image. We use the program headers themselves
166            //to translate from a file offset to the address in the image.
167            GElf_Phdr phdr;
168            uint64_t e_phoff = ehdr.e_phoff;
169            result->_programHeaderTable = 0;
170            for(int hdrnum = 0; hdrnum < result->_programHeaderCount; hdrnum++)
171            {
172                gelf_getphdr(elf, hdrnum, &phdr);
173                //Check if we've found the segment with the headers in it
174                if(phdr.p_offset <= e_phoff &&
175                        phdr.p_offset + phdr.p_filesz > e_phoff)
176                {
177                    result->_programHeaderTable = phdr.p_vaddr + e_phoff;
178                    break;
179                }
180            }
181        }
182        else
183            result->_programHeaderTable = 0;
184
185
186        elf_end(elf);
187        return result;
188    }
189}
190
191
192ElfObject::ElfObject(const string &_filename, int _fd,
193                     size_t _len, uint8_t *_data,
194                     Arch _arch, OpSys _opSys)
195    : ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
196
197{
198    Elf *elf;
199    GElf_Ehdr ehdr;
200
201    // check that header matches library version
202    if (elf_version(EV_CURRENT) == EV_NONE)
203        panic("wrong elf version number!");
204
205    // get a pointer to elf structure
206    elf = elf_memory((char*)fileData,len);
207    // will only fail if fd is invalid
208    assert(elf != NULL);
209
210    // Check that we actually have a elf file
211    if (gelf_getehdr(elf, &ehdr) ==0) {
212        panic("Not ELF, shouldn't be here");
213    }
214
215    entry = ehdr.e_entry;
216
217
218    // initialize segment sizes to 0 in case they're not present
219    text.size = data.size = bss.size = 0;
220
221    for (int i = 0; i < ehdr.e_phnum; ++i) {
222        GElf_Phdr phdr;
223        if (gelf_getphdr(elf, i, &phdr) == 0) {
224            panic("gelf_getphdr failed for section %d", i);
225        }
226
227        // for now we don't care about non-loadable segments
228        if (!(phdr.p_type & PT_LOAD))
229            continue;
230
231        // the headers don't explicitly distinguish text from data,
232        // but empirically the text segment comes first.
233        if (text.size == 0) {  // haven't seen text segment yet
234            text.baseAddr = phdr.p_vaddr;
235            text.size = phdr.p_filesz;
236            text.fileImage = fileData + phdr.p_offset;
237            // if there's any padding at the end that's not in the
238            // file, call it the bss.  This happens in the "text"
239            // segment if there's only one loadable segment (as for
240            // kernel images).
241            bss.size = phdr.p_memsz - phdr.p_filesz;
242            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
243            bss.fileImage = NULL;
244        } else if (data.size == 0) { // have text, this must be data
245            data.baseAddr = phdr.p_vaddr;
246            data.size = phdr.p_filesz;
247            data.fileImage = fileData + phdr.p_offset;
248            // if there's any padding at the end that's not in the
249            // file, call it the bss.  Warn if this happens for both
250            // the text & data segments (should only have one bss).
251            if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
252                warn("Two implied bss segments in file!\n");
253            }
254            bss.size = phdr.p_memsz - phdr.p_filesz;
255            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
256            bss.fileImage = NULL;
257        } else {
258            warn("More than two loadable segments in ELF object.");
259            warn("Ignoring segment @ 0x%x length 0x%x.",
260                 phdr.p_vaddr, phdr.p_filesz);
261        }
262    }
263
264    // should have found at least one loadable segment
265    assert(text.size != 0);
266
267    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
268             text.baseAddr, text.size, data.baseAddr, data.size,
269             bss.baseAddr, bss.size);
270
271    elf_end(elf);
272
273    // We will actually read the sections when we need to load them
274}
275
276
277bool
278ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
279{
280    Elf *elf;
281    int sec_idx = 1; // there is a 0 but it is nothing, go figure
282    Elf_Scn *section;
283    GElf_Shdr shdr;
284    Elf_Data *data;
285    int count, ii;
286    bool found = false;
287    GElf_Sym sym;
288
289    if (!symtab)
290        return false;
291
292    // check that header matches library version
293    if (elf_version(EV_CURRENT) == EV_NONE)
294        panic("wrong elf version number!");
295
296    // get a pointer to elf structure
297    elf = elf_memory((char*)fileData,len);
298
299    assert(elf != NULL);
300
301    // Get the first section
302    section = elf_getscn(elf, sec_idx);
303
304    // While there are no more sections
305    while (section != NULL) {
306        gelf_getshdr(section, &shdr);
307
308        if (shdr.sh_type == SHT_SYMTAB) {
309            found = true;
310            data = elf_getdata(section, NULL);
311            count = shdr.sh_size / shdr.sh_entsize;
312            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
313
314            // loop through all the symbols, only loading global ones
315            for (ii = 0; ii < count; ++ii) {
316                gelf_getsym(data, ii, &sym);
317                if (GELF_ST_BIND(sym.st_info) == binding) {
318                   symtab->insert(sym.st_value,
319                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
320                }
321            }
322        }
323        ++sec_idx;
324        section = elf_getscn(elf, sec_idx);
325    }
326
327    elf_end(elf);
328
329    return found;
330}
331
332bool
333ElfObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
334{
335    return loadSomeSymbols(symtab, STB_GLOBAL);
336}
337
338bool
339ElfObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
340{
341    return loadSomeSymbols(symtab, STB_LOCAL);
342}
343