elf_object.cc revision 2632:1bb2f91485ea
12521SN/A/*
29814Sandreas.hansson@arm.com * Copyright (c) 2003-2005 The Regents of The University of Michigan
38706Sandreas.hansson@arm.com * All rights reserved.
48706Sandreas.hansson@arm.com *
58706Sandreas.hansson@arm.com * Redistribution and use in source and binary forms, with or without
68706Sandreas.hansson@arm.com * modification, are permitted provided that the following conditions are
78706Sandreas.hansson@arm.com * met: redistributions of source code must retain the above copyright
88706Sandreas.hansson@arm.com * notice, this list of conditions and the following disclaimer;
98706Sandreas.hansson@arm.com * redistributions in binary form must reproduce the above copyright
108706Sandreas.hansson@arm.com * notice, this list of conditions and the following disclaimer in the
118706Sandreas.hansson@arm.com * documentation and/or other materials provided with the distribution;
128706Sandreas.hansson@arm.com * neither the name of the copyright holders nor the names of its
138706Sandreas.hansson@arm.com * contributors may be used to endorse or promote products derived from
142521SN/A * this software without specific prior written permission.
152521SN/A *
162521SN/A * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
172521SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
182521SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
192521SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
202521SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
212521SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
222521SN/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
232521SN/A * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
242521SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
252521SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
262521SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272521SN/A */
282521SN/A
292521SN/A#include <string>
302521SN/A
312521SN/A// Because of the -Wundef flag we have to do this
322521SN/A#define __LIBELF_INTERNAL__     0
332521SN/A// counterintuitive, but the flag below causes libelf to define
342521SN/A// 64-bit elf types that apparently didn't exist in some older
352521SN/A// versions of Linux.  They seem to be there in 2.4.x, so don't
362521SN/A// set this now (it causes things to break on 64-bit platforms).
372521SN/A#define __LIBELF64_LINUX        0
382521SN/A#define __LIBELF_NEED_LINK_H    0
392665SN/A#define __LIBELF_SYMBOL_VERSIONS 0
402665SN/A
418706Sandreas.hansson@arm.com#include "libelf/libelf.h"
422521SN/A#include "libelf/gelf.h"
432521SN/A
442521SN/A#include "base/loader/elf_object.hh"
452982SN/A#include "base/misc.hh"
462982SN/A
472521SN/A#include "base/loader/symtab.hh"
482521SN/A
4911793Sbrandon.potter@amd.com#include "base/trace.hh"	// for DPRINTF
5011793Sbrandon.potter@amd.com
519850Sandreas.hansson@arm.com#include "sim/byteswap.hh"
522521SN/A
538706Sandreas.hansson@arm.com
544070SN/Ausing namespace std;
559814Sandreas.hansson@arm.com
568706Sandreas.hansson@arm.comObjectFile *
578706Sandreas.hansson@arm.comElfObject::tryFile(const string &fname, int fd, size_t len, uint8_t *data)
588706Sandreas.hansson@arm.com{
598706Sandreas.hansson@arm.com    Elf *elf;
609814Sandreas.hansson@arm.com    GElf_Ehdr ehdr;
619814Sandreas.hansson@arm.com    Arch arch = UnknownArch;
628706Sandreas.hansson@arm.com    OpSys opSys = UnknownOpSys;
638706Sandreas.hansson@arm.com
648706Sandreas.hansson@arm.com    // check that header matches library version
659814Sandreas.hansson@arm.com    if (elf_version(EV_CURRENT) == EV_NONE)
669814Sandreas.hansson@arm.com        panic("wrong elf version number!");
679814Sandreas.hansson@arm.com
688706Sandreas.hansson@arm.com    // get a pointer to elf structure
698706Sandreas.hansson@arm.com    elf = elf_memory((char*)data,len);
708706Sandreas.hansson@arm.com    // will only fail if fd is invalid
718706Sandreas.hansson@arm.com    assert(elf != NULL);
728706Sandreas.hansson@arm.com
738706Sandreas.hansson@arm.com    // Check that we actually have a elf file
742521SN/A    if (gelf_getehdr(elf, &ehdr) ==0) {
752521SN/A        DPRINTFR(Loader, "Not ELF\n");
768861Sandreas.hansson@arm.com        elf_end(elf);
772521SN/A        return NULL;
782521SN/A    } else {
792521SN/A        //Detect the architecture
808706Sandreas.hansson@arm.com        //Since we don't know how to check for alpha right now, we'll
812521SN/A        //just assume if it wasn't something else and it's 64 bit, that's
828706Sandreas.hansson@arm.com        //what it must be.
838706Sandreas.hansson@arm.com        if (ehdr.e_machine == EM_SPARC64 ||
842521SN/A                ehdr.e_machine == EM_SPARC ||
852521SN/A                ehdr.e_machine == EM_SPARCV9) {
862521SN/A            arch = ObjectFile::SPARC;
8712532Sandreas.sandberg@arm.com        } else if (ehdr.e_machine == EM_MIPS
882521SN/A                && ehdr.e_ident[EI_CLASS] == ELFCLASS32) {
892521SN/A            arch = ObjectFile::Mips;
902521SN/A        } else if (ehdr.e_ident[EI_CLASS] == ELFCLASS64) {
912521SN/A            arch = ObjectFile::Alpha;
922521SN/A        } else {
9310564Sandreas.hansson@arm.com            warn("Unknown architecture: %d\n", ehdr.e_machine);
942521SN/A            arch = ObjectFile::UnknownArch;
952521SN/A        }
962521SN/A
978706Sandreas.hansson@arm.com        //Detect the operating system
982521SN/A        switch (ehdr.e_ident[EI_OSABI])
998706Sandreas.hansson@arm.com        {
1008706Sandreas.hansson@arm.com
1012521SN/A          case ELFOSABI_LINUX:
1022521SN/A            opSys = ObjectFile::Linux;
1032521SN/A            break;
10412532Sandreas.sandberg@arm.com          case ELFOSABI_SOLARIS:
1052521SN/A            opSys = ObjectFile::Solaris;
1062521SN/A            break;
1072521SN/A          case ELFOSABI_TRU64:
1082521SN/A            opSys = ObjectFile::Tru64;
1094070SN/A            break;
1108861Sandreas.hansson@arm.com          default:
1118706Sandreas.hansson@arm.com            opSys = ObjectFile::UnknownOpSys;
1128706Sandreas.hansson@arm.com        }
1138706Sandreas.hansson@arm.com
1148706Sandreas.hansson@arm.com        //take a look at the .note.ABI section
1158706Sandreas.hansson@arm.com        //It can let us know what's what.
1168706Sandreas.hansson@arm.com        if (opSys == ObjectFile::UnknownOpSys) {
1178706Sandreas.hansson@arm.com            Elf_Scn *section;
1188706Sandreas.hansson@arm.com            GElf_Shdr shdr;
1198706Sandreas.hansson@arm.com            Elf_Data *data;
1208706Sandreas.hansson@arm.com            uint32_t osAbi;;
12112532Sandreas.sandberg@arm.com            int secIdx = 1;
1228706Sandreas.hansson@arm.com
1238706Sandreas.hansson@arm.com            // Get the first section
1248706Sandreas.hansson@arm.com            section = elf_getscn(elf, secIdx);
1258706Sandreas.hansson@arm.com
1264070SN/A            // While there are no more sections
1274070SN/A            while (section != NULL && opSys == ObjectFile::UnknownOpSys) {
1284070SN/A                gelf_getshdr(section, &shdr);
1298852Sandreas.hansson@arm.com                if (shdr.sh_type == SHT_NOTE && !strcmp(".note.ABI-tag",
1304070SN/A                            elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name))) {
1314070SN/A                    // we have found a ABI note section
1324070SN/A                    // Check the 5th 32bit word for OS  0 == linux, 1 == hurd,
13310564Sandreas.hansson@arm.com                    // 2 == solaris, 3 == freebsd
1344070SN/A                    data = elf_rawdata(section, NULL);
1354070SN/A                    assert(data->d_buf);
1368852Sandreas.hansson@arm.com                    if(ehdr.e_ident[EI_DATA] == ELFDATA2LSB)
1374070SN/A                        osAbi = htole(((uint32_t*)data->d_buf)[4]);
1384070SN/A                    else
1394070SN/A                        osAbi = htobe(((uint32_t*)data->d_buf)[4]);
1404070SN/A
1414070SN/A                    switch(osAbi) {
1424070SN/A                      case 0:
1438852Sandreas.hansson@arm.com                        opSys = ObjectFile::Linux;
1444070SN/A                        break;
1458722SMitchell.Hayenga@ARM.com                      case 2:
1468722SMitchell.Hayenga@ARM.com                        opSys = ObjectFile::Solaris;
1478852Sandreas.hansson@arm.com                        break;
1488996SAli.Saidi@ARM.com                    }
1498722SMitchell.Hayenga@ARM.com                } // if section found
1508722SMitchell.Hayenga@ARM.com                if (!strcmp(".SUNW_version", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
1518722SMitchell.Hayenga@ARM.com                        opSys = ObjectFile::Solaris;
1524070SN/A                if (!strcmp(".stab.index", elf_strptr(elf, ehdr.e_shstrndx, shdr.sh_name)))
1538722SMitchell.Hayenga@ARM.com                        opSys = ObjectFile::Solaris;
1548722SMitchell.Hayenga@ARM.com
1554070SN/A            section = elf_getscn(elf, ++secIdx);
1564070SN/A            } // while sections
1574070SN/A        }
15810564Sandreas.hansson@arm.com
1594070SN/A        elf_end(elf);
1608852Sandreas.hansson@arm.com        return new ElfObject(fname, fd, len, data, arch, opSys);
1614070SN/A    }
1628852Sandreas.hansson@arm.com}
1634070SN/A
1648852Sandreas.hansson@arm.com
1654070SN/AElfObject::ElfObject(const string &_filename, int _fd,
1664070SN/A                     size_t _len, uint8_t *_data,
1674070SN/A                     Arch _arch, OpSys _opSys)
168    : ObjectFile(_filename, _fd, _len, _data, _arch, _opSys)
169
170{
171    Elf *elf;
172    GElf_Ehdr ehdr;
173
174    // check that header matches library version
175    if (elf_version(EV_CURRENT) == EV_NONE)
176        panic("wrong elf version number!");
177
178    // get a pointer to elf structure
179    elf = elf_memory((char*)fileData,len);
180    // will only fail if fd is invalid
181    assert(elf != NULL);
182
183    // Check that we actually have a elf file
184    if (gelf_getehdr(elf, &ehdr) ==0) {
185        panic("Not ELF, shouldn't be here");
186    }
187
188    entry = ehdr.e_entry;
189
190
191    // initialize segment sizes to 0 in case they're not present
192    text.size = data.size = bss.size = 0;
193
194    for (int i = 0; i < ehdr.e_phnum; ++i) {
195        GElf_Phdr phdr;
196        if (gelf_getphdr(elf, i, &phdr) == 0) {
197            panic("gelf_getphdr failed for section %d", i);
198        }
199
200        // for now we don't care about non-loadable segments
201        if (!(phdr.p_type & PT_LOAD))
202            continue;
203
204        // the headers don't explicitly distinguish text from data,
205        // but empirically the text segment comes first.
206        if (text.size == 0) {  // haven't seen text segment yet
207            text.baseAddr = phdr.p_vaddr;
208            text.size = phdr.p_filesz;
209            text.fileImage = fileData + phdr.p_offset;
210            // if there's any padding at the end that's not in the
211            // file, call it the bss.  This happens in the "text"
212            // segment if there's only one loadable segment (as for
213            // kernel images).
214            bss.size = phdr.p_memsz - phdr.p_filesz;
215            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
216            bss.fileImage = NULL;
217        } else if (data.size == 0) { // have text, this must be data
218            data.baseAddr = phdr.p_vaddr;
219            data.size = phdr.p_filesz;
220            data.fileImage = fileData + phdr.p_offset;
221            // if there's any padding at the end that's not in the
222            // file, call it the bss.  Warn if this happens for both
223            // the text & data segments (should only have one bss).
224            if (phdr.p_memsz - phdr.p_filesz > 0 && bss.size != 0) {
225                warn("Two implied bss segments in file!\n");
226            }
227            bss.size = phdr.p_memsz - phdr.p_filesz;
228            bss.baseAddr = phdr.p_vaddr + phdr.p_filesz;
229            bss.fileImage = NULL;
230        } else {
231            warn("More than two loadable segments in ELF object.");
232            warn("Ignoring segment @ 0x%x length 0x%x.",
233                 phdr.p_vaddr, phdr.p_filesz);
234        }
235    }
236
237    // should have found at least one loadable segment
238    assert(text.size != 0);
239
240    DPRINTFR(Loader, "text: 0x%x %d\ndata: 0x%x %d\nbss: 0x%x %d\n",
241             text.baseAddr, text.size, data.baseAddr, data.size,
242             bss.baseAddr, bss.size);
243
244    elf_end(elf);
245
246    // We will actually read the sections when we need to load them
247}
248
249
250bool
251ElfObject::loadSomeSymbols(SymbolTable *symtab, int binding)
252{
253    Elf *elf;
254    int sec_idx = 1; // there is a 0 but it is nothing, go figure
255    Elf_Scn *section;
256    GElf_Shdr shdr;
257    Elf_Data *data;
258    int count, ii;
259    bool found = false;
260    GElf_Sym sym;
261
262    if (!symtab)
263        return false;
264
265    // check that header matches library version
266    if (elf_version(EV_CURRENT) == EV_NONE)
267        panic("wrong elf version number!");
268
269    // get a pointer to elf structure
270    elf = elf_memory((char*)fileData,len);
271
272    assert(elf != NULL);
273
274    // Get the first section
275    section = elf_getscn(elf, sec_idx);
276
277    // While there are no more sections
278    while (section != NULL) {
279        gelf_getshdr(section, &shdr);
280
281        if (shdr.sh_type == SHT_SYMTAB) {
282            found = true;
283            data = elf_getdata(section, NULL);
284            count = shdr.sh_size / shdr.sh_entsize;
285            DPRINTF(Loader, "Found Symbol Table, %d symbols present\n", count);
286
287            // loop through all the symbols, only loading global ones
288            for (ii = 0; ii < count; ++ii) {
289                gelf_getsym(data, ii, &sym);
290                if (GELF_ST_BIND(sym.st_info) == binding) {
291                   symtab->insert(sym.st_value,
292                                  elf_strptr(elf, shdr.sh_link, sym.st_name));
293                }
294            }
295        }
296        ++sec_idx;
297        section = elf_getscn(elf, sec_idx);
298    }
299
300    elf_end(elf);
301
302    return found;
303}
304
305bool
306ElfObject::loadGlobalSymbols(SymbolTable *symtab)
307{
308    return loadSomeSymbols(symtab, STB_GLOBAL);
309}
310
311bool
312ElfObject::loadLocalSymbols(SymbolTable *symtab)
313{
314    return loadSomeSymbols(symtab, STB_LOCAL);
315}
316