process.cc revision 2523
1/*
2 * Copyright (c) 2001-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 <unistd.h>
30#include <fcntl.h>
31
32#include <cstdio>
33#include <string>
34
35#include "base/intmath.hh"
36#include "base/loader/object_file.hh"
37#include "base/loader/symtab.hh"
38#include "base/statistics.hh"
39#include "config/full_system.hh"
40#include "cpu/exec_context.hh"
41#include "mem/page_table.hh"
42#include "mem/physical.hh"
43#include "mem/translating_port.hh"
44#include "sim/builder.hh"
45#include "sim/process.hh"
46#include "sim/stats.hh"
47#include "sim/syscall_emul.hh"
48#include "sim/system.hh"
49
50using namespace std;
51using namespace TheISA;
52
53//
54// The purpose of this code is to fake the loader & syscall mechanism
55// when there's no OS: thus there's no resone to use it in FULL_SYSTEM
56// mode when we do have an OS
57//
58#if FULL_SYSTEM
59#error "process.cc not compatible with FULL_SYSTEM"
60#endif
61
62// current number of allocated processes
63int num_processes = 0;
64
65Process::Process(const string &nm,
66                 System *_system,
67                 int stdin_fd, 	// initial I/O descriptors
68                 int stdout_fd,
69                 int stderr_fd)
70    : SimObject(nm), system(_system)
71{
72    // initialize first 3 fds (stdin, stdout, stderr)
73    fd_map[STDIN_FILENO] = stdin_fd;
74    fd_map[STDOUT_FILENO] = stdout_fd;
75    fd_map[STDERR_FILENO] = stderr_fd;
76
77    // mark remaining fds as free
78    for (int i = 3; i <= MAX_FD; ++i) {
79        fd_map[i] = -1;
80    }
81
82    mmap_start = mmap_end = 0;
83    nxm_start = nxm_end = 0;
84    pTable = new PageTable(system);
85    // other parameters will be initialized when the program is loaded
86}
87
88
89void
90Process::regStats()
91{
92    using namespace Stats;
93
94    num_syscalls
95        .name(name() + ".PROG:num_syscalls")
96        .desc("Number of system calls")
97        ;
98}
99
100//
101// static helper functions
102//
103int
104Process::openInputFile(const string &filename)
105{
106    int fd = open(filename.c_str(), O_RDONLY);
107
108    if (fd == -1) {
109        perror(NULL);
110        cerr << "unable to open \"" << filename << "\" for reading\n";
111        fatal("can't open input file");
112    }
113
114    return fd;
115}
116
117
118int
119Process::openOutputFile(const string &filename)
120{
121    int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0774);
122
123    if (fd == -1) {
124        perror(NULL);
125        cerr << "unable to open \"" << filename << "\" for writing\n";
126        fatal("can't open output file");
127    }
128
129    return fd;
130}
131
132
133int
134Process::registerExecContext(ExecContext *xc)
135{
136    // add to list
137    int myIndex = execContexts.size();
138    execContexts.push_back(xc);
139
140    // return CPU number to caller
141    return myIndex;
142}
143
144void
145Process::startup()
146{
147    if (execContexts.empty())
148        fatal("Process %s is not associated with any CPUs!\n", name());
149
150    // first exec context for this process... initialize & enable
151    ExecContext *xc = execContexts[0];
152
153    // mark this context as active so it will start ticking.
154    xc->activate(0);
155
156    Port *mem_port;
157    mem_port = system->physmem->getPort("functional");
158    initVirtMem = new TranslatingPort(pTable, true);
159    mem_port->setPeer(initVirtMem);
160    initVirtMem->setPeer(mem_port);
161}
162
163void
164Process::replaceExecContext(ExecContext *xc, int xcIndex)
165{
166    if (xcIndex >= execContexts.size()) {
167        panic("replaceExecContext: bad xcIndex, %d >= %d\n",
168              xcIndex, execContexts.size());
169    }
170
171    execContexts[xcIndex] = xc;
172}
173
174// map simulator fd sim_fd to target fd tgt_fd
175void
176Process::dup_fd(int sim_fd, int tgt_fd)
177{
178    if (tgt_fd < 0 || tgt_fd > MAX_FD)
179        panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
180
181    fd_map[tgt_fd] = sim_fd;
182}
183
184
185// generate new target fd for sim_fd
186int
187Process::alloc_fd(int sim_fd)
188{
189    // in case open() returns an error, don't allocate a new fd
190    if (sim_fd == -1)
191        return -1;
192
193    // find first free target fd
194    for (int free_fd = 0; free_fd < MAX_FD; ++free_fd) {
195        if (fd_map[free_fd] == -1) {
196            fd_map[free_fd] = sim_fd;
197            return free_fd;
198        }
199    }
200
201    panic("Process::alloc_fd: out of file descriptors!");
202}
203
204
205// free target fd (e.g., after close)
206void
207Process::free_fd(int tgt_fd)
208{
209    if (fd_map[tgt_fd] == -1)
210        warn("Process::free_fd: request to free unused fd %d", tgt_fd);
211
212    fd_map[tgt_fd] = -1;
213}
214
215
216// look up simulator fd for given target fd
217int
218Process::sim_fd(int tgt_fd)
219{
220    if (tgt_fd > MAX_FD)
221        return -1;
222
223    return fd_map[tgt_fd];
224}
225
226
227
228//
229// need to declare these here since there is no concrete Process type
230// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
231// which is where these get declared for concrete types).
232//
233DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
234
235
236////////////////////////////////////////////////////////////////////////
237//
238// LiveProcess member definitions
239//
240////////////////////////////////////////////////////////////////////////
241
242
243static void
244copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
245                TranslatingPort* memPort)
246{
247    Addr data_ptr_swap;
248    for (int i = 0; i < strings.size(); ++i) {
249        data_ptr_swap = htog(data_ptr);
250        memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr_swap, sizeof(Addr));
251        memPort->writeString(data_ptr, strings[i].c_str());
252        array_ptr += sizeof(Addr);
253        data_ptr += strings[i].size() + 1;
254    }
255    // add NULL terminator
256    data_ptr = 0;
257
258    memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr, sizeof(Addr));
259}
260
261LiveProcess::LiveProcess(const string &nm, ObjectFile *_objFile,
262                         System *_system,
263                         int stdin_fd, int stdout_fd, int stderr_fd,
264                         vector<string> &_argv, vector<string> &_envp)
265    : Process(nm, _system, stdin_fd, stdout_fd, stderr_fd),
266      objFile(_objFile), argv(_argv), envp(_envp)
267{
268    prog_fname = argv[0];
269
270    // load up symbols, if any... these may be used for debugging or
271    // profiling.
272    if (!debugSymbolTable) {
273        debugSymbolTable = new SymbolTable();
274        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
275            !objFile->loadLocalSymbols(debugSymbolTable)) {
276            // didn't load any symbols
277            delete debugSymbolTable;
278            debugSymbolTable = NULL;
279        }
280    }
281}
282
283void
284LiveProcess::argsInit(int intSize, int pageSize)
285{
286    Process::startup();
287
288    // load object file into target memory
289    objFile->loadSections(initVirtMem);
290
291    // Calculate how much space we need for arg & env arrays.
292    int argv_array_size = intSize * (argv.size() + 1);
293    int envp_array_size = intSize * (envp.size() + 1);
294    int arg_data_size = 0;
295    for (int i = 0; i < argv.size(); ++i) {
296        arg_data_size += argv[i].size() + 1;
297    }
298    int env_data_size = 0;
299    for (int i = 0; i < envp.size(); ++i) {
300        env_data_size += envp[i].size() + 1;
301    }
302
303    int space_needed =
304        argv_array_size + envp_array_size + arg_data_size + env_data_size;
305    // for SimpleScalar compatibility
306    if (space_needed < 16384)
307        space_needed = 16384;
308
309    // set bottom of stack
310    stack_min = stack_base - space_needed;
311    // align it
312    stack_min &= ~(intSize-1);
313    stack_size = stack_base - stack_min;
314    // map memory
315    pTable->allocate(roundDown(stack_min, pageSize),
316                     roundUp(stack_size, pageSize));
317
318    // map out initial stack contents
319    Addr argv_array_base = stack_min + intSize; // room for argc
320    Addr envp_array_base = argv_array_base + argv_array_size;
321    Addr arg_data_base = envp_array_base + envp_array_size;
322    Addr env_data_base = arg_data_base + arg_data_size;
323
324    // write contents to stack
325    uint64_t argc = argv.size();
326    if (intSize == 8)
327        argc = htog((uint64_t)argc);
328    else if (intSize == 4)
329        argc = htog((uint32_t)argc);
330    else
331        panic("Unknown int size");
332
333    initVirtMem->writeBlob(stack_min, (uint8_t*)&argc, intSize);
334
335    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);
336    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
337
338    execContexts[0]->setIntReg(ArgumentReg0, argc);
339    execContexts[0]->setIntReg(ArgumentReg1, argv_array_base);
340    execContexts[0]->setIntReg(StackPointerReg, stack_min);
341
342    Addr prog_entry = objFile->entryPoint();
343    execContexts[0]->setPC(prog_entry);
344    execContexts[0]->setNextPC(prog_entry + sizeof(MachInst));
345    execContexts[0]->setNextNPC(prog_entry + (2 * sizeof(MachInst)));
346
347    num_processes++;
348}
349
350void
351LiveProcess::syscall(ExecContext *xc)
352{
353    num_syscalls++;
354
355    int64_t callnum = xc->readIntReg(SyscallNumReg);
356
357    SyscallDesc *desc = getDesc(callnum);
358    if (desc == NULL)
359        fatal("Syscall %d out of range", callnum);
360
361    desc->doSyscall(callnum, this, xc);
362}
363
364DEFINE_SIM_OBJECT_CLASS_NAME("LiveProcess", LiveProcess);
365