1/*
2 * Copyright (c) 2002-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 * Authors: Nathan Binkert
29 *          Steve Reinhardt
30 */
31
32#include "base/loader/object_file.hh"
33
34#include <fcntl.h>
35#include <sys/mman.h>
36#include <sys/types.h>
37#include <unistd.h>
38#include <zlib.h>
39
40#include <cstdio>
41#include <list>
42#include <string>
43#include <vector>
44
45#include "base/cprintf.hh"
46#include "base/loader/aout_object.hh"
47#include "base/loader/dtb_object.hh"
48#include "base/loader/ecoff_object.hh"
49#include "base/loader/elf_object.hh"
50#include "base/loader/raw_object.hh"
51#include "base/loader/symtab.hh"
52#include "mem/port_proxy.hh"
53
54using namespace std;
55
56ObjectFile::ObjectFile(const string &_filename,
57                       size_t _len, uint8_t *_data,
58                       Arch _arch, OpSys _op_sys)
59    : filename(_filename), fileData(_data), len(_len),
60      arch(_arch), opSys(_op_sys), entry(0), globalPtr(0),
61      text{0, nullptr, 0}, data{0, nullptr, 0}, bss{0, nullptr, 0}
62{
63}
64
65
66ObjectFile::~ObjectFile()
67{
68    if (fileData) {
69        ::munmap((char*)fileData, len);
70        fileData = NULL;
71    }
72}
73
74
75bool
76ObjectFile::loadSection(Section *sec, const PortProxy& mem_proxy,
77                        Addr addr_mask, Addr offset)
78{
79    if (sec->size != 0) {
80        Addr addr = (sec->baseAddr & addr_mask) + offset;
81        if (sec->fileImage) {
82            mem_proxy.writeBlob(addr, sec->fileImage, sec->size);
83        }
84        else {
85            // no image: must be bss
86            mem_proxy.memsetBlob(addr, 0, sec->size);
87        }
88    }
89    return true;
90}
91
92
93bool
94ObjectFile::loadSections(const PortProxy& mem_proxy, Addr addr_mask,
95                         Addr offset)
96{
97    return (loadSection(&text, mem_proxy, addr_mask, offset)
98            && loadSection(&data, mem_proxy, addr_mask, offset)
99            && loadSection(&bss, mem_proxy, addr_mask, offset));
100}
101
102namespace
103{
104
105typedef std::vector<ObjectFile::Loader *> LoaderList;
106
107LoaderList &
108object_file_loaders()
109{
110    static LoaderList loaders;
111    return loaders;
112}
113
114} // anonymous namespace
115
116ObjectFile::Loader::Loader()
117{
118    object_file_loaders().emplace_back(this);
119}
120
121Process *
122ObjectFile::tryLoaders(ProcessParams *params, ObjectFile *obj_file)
123{
124    for (auto &loader: object_file_loaders()) {
125        Process *p = loader->load(params, obj_file);
126        if (p)
127            return p;
128    }
129
130    return nullptr;
131}
132
133static bool
134hasGzipMagic(int fd)
135{
136    uint8_t buf[2] = {0};
137    size_t sz = pread(fd, buf, 2, 0);
138    panic_if(sz != 2, "Couldn't read magic bytes from object file");
139    return ((buf[0] == 0x1f) && (buf[1] == 0x8b));
140}
141
142static int
143doGzipLoad(int fd)
144{
145    const size_t blk_sz = 4096;
146
147    gzFile fdz = gzdopen(fd, "rb");
148    if (!fdz) {
149        return -1;
150    }
151
152    size_t tmp_len = strlen(P_tmpdir);
153    char *tmpnam = (char*) malloc(tmp_len + 20);
154    strcpy(tmpnam, P_tmpdir);
155    strcpy(tmpnam+tmp_len, "/gem5-gz-obj-XXXXXX"); // 19 chars
156    fd = mkstemp(tmpnam); // repurposing fd variable for output
157    if (fd < 0) {
158        free(tmpnam);
159        gzclose(fdz);
160        return fd;
161    }
162
163    if (unlink(tmpnam) != 0)
164        warn("couldn't remove temporary file %s\n", tmpnam);
165
166    free(tmpnam);
167
168    auto buf = new uint8_t[blk_sz];
169    int r; // size of (r)emaining uncopied data in (buf)fer
170    while ((r = gzread(fdz, buf, blk_sz)) > 0) {
171        auto p = buf; // pointer into buffer
172        while (r > 0) {
173            auto sz = write(fd, p, r);
174            assert(sz <= r);
175            r -= sz;
176            p += sz;
177        }
178    }
179    delete[] buf;
180    gzclose(fdz);
181    if (r < 0) { // error
182        close(fd);
183        return -1;
184    }
185    assert(r == 0); // finished successfully
186    return fd; // return fd to decompressed temporary file for mmap()'ing
187}
188
189ObjectFile *
190createObjectFile(const string &fname, bool raw)
191{
192    // open the file
193    int fd = open(fname.c_str(), O_RDONLY);
194    if (fd < 0) {
195        return NULL;
196    }
197
198    // decompress GZ files
199    if (hasGzipMagic(fd)) {
200        fd = doGzipLoad(fd);
201        if (fd < 0) {
202            return NULL;
203        }
204    }
205
206    // find the length of the file by seeking to the end
207    off_t off = lseek(fd, 0, SEEK_END);
208    fatal_if(off < 0,
209             "Failed to determine size of object file %s\n", fname);
210    auto len = static_cast<size_t>(off);
211
212    // mmap the whole shebang
213    uint8_t *file_data = (uint8_t *)mmap(NULL, len, PROT_READ, MAP_SHARED,
214                                         fd, 0);
215    close(fd);
216
217    if (file_data == MAP_FAILED) {
218        return NULL;
219    }
220
221    ObjectFile *file_obj = NULL;
222
223    // figure out what we have here
224    if ((file_obj = ElfObject::tryFile(fname, len, file_data)) != NULL) {
225        return file_obj;
226    }
227
228    if ((file_obj = EcoffObject::tryFile(fname, len, file_data)) != NULL) {
229        return file_obj;
230    }
231
232    if ((file_obj = AoutObject::tryFile(fname, len, file_data)) != NULL) {
233        return file_obj;
234    }
235
236    if ((file_obj = DtbObject::tryFile(fname, len, file_data)) != NULL) {
237        return file_obj;
238    }
239
240    if (raw)
241        return RawObject::tryFile(fname, len, file_data);
242
243    // don't know what it is
244    munmap((char*)file_data, len);
245    return NULL;
246}
247