elf_object.cc revision 1708
1/*
2 * Copyright (c) 2003-2004 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 "mem/functional_mem/functional_memory.hh"
47#include "base/loader/symtab.hh"
48
49#include "base/trace.hh"	// for DPRINTF
50
51
52using namespace std;
53
54ObjectFile *
55ElfObject::tryFile(const string &fname, int fd, size_t len, uint8_t *data)
56{
57    Elf *elf;
58    GElf_Ehdr ehdr;
59
60    // check that header matches library version
61    if (elf_version(EV_CURRENT) == EV_NONE)
62        panic("wrong elf version number!");
63
64    // get a pointer to elf structure
65    elf = elf_memory((char*)data,len);
66    // will only fail if fd is invalid
67    assert(elf != NULL);
68
69    // Check that we actually have a elf file
70    if (gelf_getehdr(elf, &ehdr) ==0) {
71        DPRINTFR(Loader, "Not ELF\n");
72        elf_end(elf);
73        return NULL;
74    }
75    else {
76        if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
77            panic("32 bit ELF Binary, Not Supported");
78        /* @todo this emachine value isn't offical yet.
79         *       so we probably shouldn't check it. */
80//        if (ehdr.e_machine != EM_ALPHA)
81//            panic("Non Alpha Binary, Not Supported");
82
83        elf_end(elf);
84
85        return new ElfObject(fname, fd, len, data,
86                             ObjectFile::Alpha, ObjectFile::Linux);
87    }
88}
89
90
91ElfObject::ElfObject(const string &_filename, int _fd,
92                     size_t _len, uint8_t *_data,
93                     Arch _arch, OpSys _opSys)
94    : ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
95
96{
97    Elf *elf;
98    GElf_Ehdr ehdr;
99
100    // check that header matches library version
101    if (elf_version(EV_CURRENT) == EV_NONE)
102        panic("wrong elf version number!");
103
104    // get a pointer to elf structure
105    elf = elf_memory((char*)fileData,len);
106    // will only fail if fd is invalid
107    assert(elf != NULL);
108
109    // Check that we actually have a elf file
110    if (gelf_getehdr(elf, &ehdr) ==0) {
111        panic("Not ELF, shouldn't be here");
112    }
113
114    entry = ehdr.e_entry;
115
116    // initialize segment sizes to 0 in case they're not present
117    text.size = data.size = bss.size = 0;
118
119    for (int i = 0; i < ehdr.e_phnum; ++i) {
120        GElf_Phdr phdr;
121        if (gelf_getphdr(elf, i, &phdr) == 0) {
122            panic("gelf_getphdr failed for section %d", i);
123        }
124
125        // for now we don't care about non-loadable segments
126        if (!(phdr.p_type & PT_LOAD))
127            continue;
128
129        // the headers don't explicitly distinguish text from data,
130        // but empirically the text segment comes first.
131        if (text.size == 0) {  // haven't seen text segment yet
132            text.baseAddr = phdr.p_vaddr;
133            text.size = phdr.p_filesz;
134            // remember where the data is for loadSections()
135            fileTextBits = fileData + phdr.p_offset;
136            // if there's any padding at the end that's not in the
137            // file, call it the bss.  This happens in the "text"
138            // segment if there's only one loadable segment (as for
139            // kernel images).
140            bss.size = phdr.p_memsz - phdr.p_filesz;
141            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
142        }
143        else if (data.size == 0) { // have text, this must be data
144            data.baseAddr = phdr.p_vaddr;
145            data.size = phdr.p_filesz;
146            // remember where the data is for loadSections()
147            fileDataBits = fileData + phdr.p_offset;
148            // if there's any padding at the end that's not in the
149            // file, call it the bss.  Warn if this happens for both
150            // the text & data segments (should only have one bss).
151            if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
152                warn("Two implied bss segments in file!\n");
153            }
154            bss.size = phdr.p_memsz - phdr.p_filesz;
155            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
156        }
157    }
158
159    // should have found at least one loadable segment
160    assert(text.size != 0);
161
162    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
163             text.baseAddr, text.size, data.baseAddr, data.size,
164             bss.baseAddr, bss.size);
165
166    elf_end(elf);
167
168    // We will actually read the sections when we need to load them
169}
170
171
172bool
173ElfObject::loadSections(FunctionalMemory *mem, bool loadPhys)
174{
175    Addr textAddr = text.baseAddr;
176    Addr dataAddr = data.baseAddr;
177
178    if (loadPhys) {
179        textAddr &= (ULL(1) << 40) - 1;
180        dataAddr &= (ULL(1) << 40) - 1;
181    }
182
183    // Since we don't really have an MMU and all memory is
184    // zero-filled, there's no need to set up the BSS segment.
185    if (text.size != 0)
186        mem->prot_write(textAddr, fileTextBits, text.size);
187    if (data.size != 0)
188        mem->prot_write(dataAddr, fileDataBits, data.size);
189
190    return true;
191}
192
193
194bool
195ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
196{
197    Elf *elf;
198    int sec_idx = 1; // there is a 0 but it is nothing, go figure
199    Elf_Scn *section;
200    GElf_Shdr shdr;
201    Elf_Data *data;
202    int count, ii;
203    bool found = false;
204    GElf_Sym sym;
205
206    if (!symtab)
207        return false;
208
209    // check that header matches library version
210    if (elf_version(EV_CURRENT) == EV_NONE)
211        panic("wrong elf version number!");
212
213    // get a pointer to elf structure
214    elf = elf_memory((char*)fileData,len);
215
216    assert(elf != NULL);
217
218    // Get the first section
219    section = elf_getscn(elf, sec_idx);
220
221    // While there are no more sections
222    while (section != NULL) {
223        gelf_getshdr(section, &shdr);
224
225        if (shdr.sh_type == SHT_SYMTAB) {
226            found = true;
227            data = elf_getdata(section, NULL);
228            count = shdr.sh_size / shdr.sh_entsize;
229            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
230
231            // loop through all the symbols, only loading global ones
232            for (ii = 0; ii < count; ++ii) {
233                gelf_getsym(data, ii, &sym);
234                if (GELF_ST_BIND(sym.st_info) == binding) {
235                   symtab->insert(sym.st_value,
236                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
237                }
238            }
239        }
240        ++sec_idx;
241        section = elf_getscn(elf, sec_idx);
242    }
243
244    elf_end(elf);
245
246    return found;
247}
248
249bool
250ElfObject::loadGlobalSymbols(SymbolTable *symtab)
251{
252    return loadSomeSymbols(symtab, STB_GLOBAL);
253}
254
255bool
256ElfObject::loadLocalSymbols(SymbolTable *symtab)
257{
258    return loadSomeSymbols(symtab, STB_LOCAL);
259}
260