elf_object.cc revision 4166:ecebe3ac19b4
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_ident[EI_CLASS] == ELFCLASS64)||
83                ehdr.e_machine == EM_SPARCV9) {
84            arch = ObjectFile::SPARC64;
85        } else if (ehdr.e_machine == EM_SPARC32PLUS ||
86                        (ehdr.e_machine == EM_SPARC &&
87                         ehdr.e_ident[EI_CLASS] == ELFCLASS32)) {
88            arch = ObjectFile::SPARC32;
89        } else if (ehdr.e_machine == EM_MIPS
90                && ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
91            arch = ObjectFile::Mips;
92        } else if (ehdr.e_machine == EM_X86_64 &&
93                ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
94            //In the future, we might want to differentiate between 32 bit
95            //and 64 bit x86 processes in case there are differences in their
96            //initial stack frame.
97            arch = ObjectFile::X86;
98        } else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
99            arch = ObjectFile::Alpha;
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            opSys = ObjectFile::Linux;
111            break;
112          case ELFOSABI_SOLARIS:
113            opSys = ObjectFile::Solaris;
114            break;
115          case ELFOSABI_TRU64:
116            opSys = ObjectFile::Tru64;
117            break;
118          default:
119            opSys = ObjectFile::UnknownOpSys;
120        }
121
122        //take a look at the .note.ABI section
123        //It can let us know what's what.
124        if (opSys == ObjectFile::UnknownOpSys) {
125            Elf_Scn *section;
126            GElf_Shdr shdr;
127            Elf_Data *data;
128            uint32_t osAbi;;
129            int secIdx = 1;
130
131            // Get the first section
132            section = elf_getscn(elf, secIdx);
133
134            // While there are no more sections
135            while (section != NULL && opSys == ObjectFile::UnknownOpSys) {
136                gelf_getshdr(section, &shdr);
137                if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag",
138                            elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name))) {
139                    // we have found a ABI note section
140                    // Check the 5th 32bit word for OS  0 == linux, 1 == hurd,
141                    // 2 == solaris, 3 == freebsd
142                    data = elf_rawdata(section, NULL);
143                    assert(data->d_buf);
144                    if(ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
145                        osAbi = htole(((uint32_t*)data->d_buf)[4]);
146                    else
147                        osAbi = htobe(((uint32_t*)data->d_buf)[4]);
148
149                    switch(osAbi) {
150                      case 0:
151                        opSys = ObjectFile::Linux;
152                        break;
153                      case 2:
154                        opSys = ObjectFile::Solaris;
155                        break;
156                    }
157                } // if section found
158                if (!strcmp(".SUNW_version", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
159                        opSys = ObjectFile::Solaris;
160                if (!strcmp(".stab.index", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
161                        opSys = ObjectFile::Solaris;
162
163            section = elf_getscn(elf, ++secIdx);
164            } // while sections
165        }
166
167        ElfObject * result = new ElfObject(fname, fd, len, data, arch, opSys);
168
169        //The number of headers in the file
170        result->_programHeaderCount = ehdr.e_phnum;
171        //Record the size of each entry
172        result->_programHeaderSize = ehdr.e_phentsize;
173        if(result->_programHeaderCount) //If there is a program header table
174        {
175            //Figure out the virtual address of the header table in the
176            //final memory image. We use the program headers themselves
177            //to translate from a file offset to the address in the image.
178            GElf_Phdr phdr;
179            uint64_t e_phoff = ehdr.e_phoff;
180            result->_programHeaderTable = 0;
181            for(int hdrnum = 0; hdrnum < result->_programHeaderCount; hdrnum++)
182            {
183                gelf_getphdr(elf, hdrnum, &phdr);
184                //Check if we've found the segment with the headers in it
185                if(phdr.p_offset <= e_phoff &&
186                        phdr.p_offset + phdr.p_filesz > e_phoff)
187                {
188                    result->_programHeaderTable = phdr.p_vaddr + e_phoff;
189                    break;
190                }
191            }
192        }
193        else
194            result->_programHeaderTable = 0;
195
196
197        elf_end(elf);
198        return result;
199    }
200}
201
202
203ElfObject::ElfObject(const string &_filename, int _fd,
204                     size_t _len, uint8_t *_data,
205                     Arch _arch, OpSys _opSys)
206    : ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
207
208{
209    Elf *elf;
210    GElf_Ehdr ehdr;
211
212    // check that header matches library version
213    if (elf_version(EV_CURRENT) == EV_NONE)
214        panic("wrong elf version number!");
215
216    // get a pointer to elf structure
217    elf = elf_memory((char*)fileData,len);
218    // will only fail if fd is invalid
219    assert(elf != NULL);
220
221    // Check that we actually have a elf file
222    if (gelf_getehdr(elf, &ehdr) ==0) {
223        panic("Not ELF, shouldn't be here");
224    }
225
226    entry = ehdr.e_entry;
227
228
229    // initialize segment sizes to 0 in case they're not present
230    text.size = data.size = bss.size = 0;
231
232    for (int i = 0; i < ehdr.e_phnum; ++i) {
233        GElf_Phdr phdr;
234        if (gelf_getphdr(elf, i, &phdr) == 0) {
235            panic("gelf_getphdr failed for section %d", i);
236        }
237
238        // for now we don't care about non-loadable segments
239        if (!(phdr.p_type & PT_LOAD))
240            continue;
241
242        // the headers don't explicitly distinguish text from data,
243        // but empirically the text segment comes first.
244        if (text.size == 0) {  // haven't seen text segment yet
245            text.baseAddr = phdr.p_vaddr;
246            text.size = phdr.p_filesz;
247            text.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.  This happens in the "text"
250            // segment if there's only one loadable segment (as for
251            // kernel images).
252            bss.size = phdr.p_memsz - phdr.p_filesz;
253            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
254            bss.fileImage = NULL;
255        } else if (data.size == 0) { // have text, this must be data
256            data.baseAddr = phdr.p_vaddr;
257            data.size = phdr.p_filesz;
258            data.fileImage = fileData + phdr.p_offset;
259            // if there's any padding at the end that's not in the
260            // file, call it the bss.  Warn if this happens for both
261            // the text & data segments (should only have one bss).
262            if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
263                warn("Two implied bss segments in file!\n");
264            }
265            bss.size = phdr.p_memsz - phdr.p_filesz;
266            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
267            bss.fileImage = NULL;
268        } else {
269            warn("More than two loadable segments in ELF object.");
270            warn("Ignoring segment @ 0x%x length 0x%x.",
271                 phdr.p_vaddr, phdr.p_filesz);
272        }
273    }
274
275    // should have found at least one loadable segment
276    assert(text.size != 0);
277
278    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
279             text.baseAddr, text.size, data.baseAddr, data.size,
280             bss.baseAddr, bss.size);
281
282    elf_end(elf);
283
284    // We will actually read the sections when we need to load them
285}
286
287
288bool
289ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
290{
291    Elf *elf;
292    int sec_idx = 1; // there is a 0 but it is nothing, go figure
293    Elf_Scn *section;
294    GElf_Shdr shdr;
295    Elf_Data *data;
296    int count, ii;
297    bool found = false;
298    GElf_Sym sym;
299
300    if (!symtab)
301        return false;
302
303    // check that header matches library version
304    if (elf_version(EV_CURRENT) == EV_NONE)
305        panic("wrong elf version number!");
306
307    // get a pointer to elf structure
308    elf = elf_memory((char*)fileData,len);
309
310    assert(elf != NULL);
311
312    // Get the first section
313    section = elf_getscn(elf, sec_idx);
314
315    // While there are no more sections
316    while (section != NULL) {
317        gelf_getshdr(section, &shdr);
318
319        if (shdr.sh_type == SHT_SYMTAB) {
320            found = true;
321            data = elf_getdata(section, NULL);
322            count = shdr.sh_size / shdr.sh_entsize;
323            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
324
325            // loop through all the symbols, only loading global ones
326            for (ii = 0; ii < count; ++ii) {
327                gelf_getsym(data, ii, &sym);
328                if (GELF_ST_BIND(sym.st_info) == binding) {
329                   symtab->insert(sym.st_value,
330                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
331                }
332            }
333        }
334        ++sec_idx;
335        section = elf_getscn(elf, sec_idx);
336    }
337
338    elf_end(elf);
339
340    return found;
341}
342
343bool
344ElfObject::loadGlobalSymbols(SymbolTable *symtab, Addr addrMask)
345{
346    return loadSomeSymbols(symtab, STB_GLOBAL);
347}
348
349bool
350ElfObject::loadLocalSymbols(SymbolTable *symtab, Addr addrMask)
351{
352    return loadSomeSymbols(symtab, STB_LOCAL);
353}
354
355bool
356ElfObject::isDynamic()
357{
358    Elf *elf;
359    int sec_idx = 1; // there is a 0 but it is nothing, go figure
360    Elf_Scn *section;
361    GElf_Shdr shdr;
362
363    GElf_Ehdr ehdr;
364
365    // check that header matches library version
366    if (elf_version(EV_CURRENT) == EV_NONE)
367        panic("wrong elf version number!");
368
369    // get a pointer to elf structure
370    elf = elf_memory((char*)fileData,len);
371    assert(elf != NULL);
372
373    // Check that we actually have a elf file
374    if (gelf_getehdr(elf, &ehdr) ==0) {
375        panic("Not ELF, shouldn't be here");
376    }
377
378    // Get the first section
379    section = elf_getscn(elf, sec_idx);
380
381    // While there are no more sections
382    while (section != NULL) {
383        gelf_getshdr(section, &shdr);
384        if (!strcmp(".interp", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
385            return true;
386        section = elf_getscn(elf, ++sec_idx);
387    } // while sections
388    return false;
389}
390
391
392