elf_object.cc revision 2420
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
29#include <string>
30
31// Because of the -Wundef flag we have to do this
32#define __LIBELF_INTERNAL__     0
33// counterintuitive, but the flag below causes libelf to define
34// 64-bit elf types that apparently didn't exist in some older
35// versions of Linux.  They seem to be there in 2.4.x, so don't
36// set this now (it causes things to break on 64-bit platforms).
37#define __LIBELF64_LINUX        0
38#define __LIBELF_NEED_LINK_H    0
39#define __LIBELF_SYMBOL_VERSIONS 0
40
41#include <libelf/libelf.h>
42#include <libelf/gelf.h>
43
44#include "base/loader/elf_object.hh"
45
46#include "base/loader/symtab.hh"
47
48#include "base/trace.hh"	// for DPRINTF
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
59    // check that header matches library version
60    if (elf_version(EV_CURRENT) == EV_NONE)
61        panic("wrong elf version number!");
62
63    // get a pointer to elf structure
64    elf = elf_memory((char*)data,len);
65    // will only fail if fd is invalid
66    assert(elf != NULL);
67
68    // Check that we actually have a elf file
69    if (gelf_getehdr(elf, &ehdr) ==0) {
70        DPRINTFR(Loader, "Not ELF\n");
71        elf_end(elf);
72        return NULL;
73    }
74    else {
75        if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
76            panic("32 bit ELF Binary, Not Supported");
77        /* @todo this emachine value isn't offical yet.
78         *       so we probably shouldn't check it. */
79//        if (ehdr.e_machine != EM_ALPHA)
80//            panic("Non Alpha Binary, Not Supported");
81
82        elf_end(elf);
83
84        return new ElfObject(fname, fd, len, data,
85                             ObjectFile::Alpha, ObjectFile::Linux);
86    }
87}
88
89
90ElfObject::ElfObject(const string &_filename, int _fd,
91                     size_t _len, uint8_t *_data,
92                     Arch _arch, OpSys _opSys)
93    : ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
94
95{
96    Elf *elf;
97    GElf_Ehdr ehdr;
98
99    // check that header matches library version
100    if (elf_version(EV_CURRENT) == EV_NONE)
101        panic("wrong elf version number!");
102
103    // get a pointer to elf structure
104    elf = elf_memory((char*)fileData,len);
105    // will only fail if fd is invalid
106    assert(elf != NULL);
107
108    // Check that we actually have a elf file
109    if (gelf_getehdr(elf, &ehdr) ==0) {
110        panic("Not ELF, shouldn't be here");
111    }
112
113    entry = ehdr.e_entry;
114
115    // initialize segment sizes to 0 in case they're not present
116    text.size = data.size = bss.size = 0;
117
118    for (int i = 0; i < ehdr.e_phnum; ++i) {
119        GElf_Phdr phdr;
120        if (gelf_getphdr(elf, i, &phdr) == 0) {
121            panic("gelf_getphdr failed for section %d", i);
122        }
123
124        // for now we don't care about non-loadable segments
125        if (!(phdr.p_type & PT_LOAD))
126            continue;
127
128        // the headers don't explicitly distinguish text from data,
129        // but empirically the text segment comes first.
130        if (text.size == 0) {  // haven't seen text segment yet
131            text.baseAddr = phdr.p_vaddr;
132            text.size = phdr.p_filesz;
133            text.fileImage = fileData + phdr.p_offset;
134            // if there's any padding at the end that's not in the
135            // file, call it the bss.  This happens in the "text"
136            // segment if there's only one loadable segment (as for
137            // kernel images).
138            bss.size = phdr.p_memsz - phdr.p_filesz;
139            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
140            bss.fileImage = NULL;
141        }
142        else if (data.size == 0) { // have text, this must be data
143            data.baseAddr = phdr.p_vaddr;
144            data.size = phdr.p_filesz;
145            data.fileImage = fileData + phdr.p_offset;
146            // if there's any padding at the end that's not in the
147            // file, call it the bss.  Warn if this happens for both
148            // the text & data segments (should only have one bss).
149            if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
150                warn("Two implied bss segments in file!\n");
151            }
152            bss.size = phdr.p_memsz - phdr.p_filesz;
153            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
154            bss.fileImage = NULL;
155        }
156    }
157
158    // should have found at least one loadable segment
159    assert(text.size != 0);
160
161    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
162             text.baseAddr, text.size, data.baseAddr, data.size,
163             bss.baseAddr, bss.size);
164
165    elf_end(elf);
166
167    // We will actually read the sections when we need to load them
168}
169
170
171bool
172ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
173{
174    Elf *elf;
175    int sec_idx = 1; // there is a 0 but it is nothing, go figure
176    Elf_Scn *section;
177    GElf_Shdr shdr;
178    Elf_Data *data;
179    int count, ii;
180    bool found = false;
181    GElf_Sym sym;
182
183    if (!symtab)
184        return false;
185
186    // check that header matches library version
187    if (elf_version(EV_CURRENT) == EV_NONE)
188        panic("wrong elf version number!");
189
190    // get a pointer to elf structure
191    elf = elf_memory((char*)fileData,len);
192
193    assert(elf != NULL);
194
195    // Get the first section
196    section = elf_getscn(elf, sec_idx);
197
198    // While there are no more sections
199    while (section != NULL) {
200        gelf_getshdr(section, &shdr);
201
202        if (shdr.sh_type == SHT_SYMTAB) {
203            found = true;
204            data = elf_getdata(section, NULL);
205            count = shdr.sh_size / shdr.sh_entsize;
206            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
207
208            // loop through all the symbols, only loading global ones
209            for (ii = 0; ii < count; ++ii) {
210                gelf_getsym(data, ii, &sym);
211                if (GELF_ST_BIND(sym.st_info) == binding) {
212                   symtab->insert(sym.st_value,
213                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
214                }
215            }
216        }
217        ++sec_idx;
218        section = elf_getscn(elf, sec_idx);
219    }
220
221    elf_end(elf);
222
223    return found;
224}
225
226bool
227ElfObject::loadGlobalSymbols(SymbolTable *symtab)
228{
229    return loadSomeSymbols(symtab, STB_GLOBAL);
230}
231
232bool
233ElfObject::loadLocalSymbols(SymbolTable *symtab)
234{
235    return loadSomeSymbols(symtab, STB_LOCAL);
236}
237