process.cc revision 2462
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/mem_object.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
50#include "arch/process.hh"
51
52using namespace std;
53using namespace TheISA;
54
55//
56// The purpose of this code is to fake the loader & syscall mechanism
57// when there's no OS: thus there's no resone to use it in FULL_SYSTEM
58// mode when we do have an OS
59//
60#if FULL_SYSTEM
61#error "process.cc not compatible with FULL_SYSTEM"
62#endif
63
64// current number of allocated processes
65int num_processes = 0;
66
67Process::Process(const string &nm,
68                 System *_system,
69                 int stdin_fd, 	// initial I/O descriptors
70                 int stdout_fd,
71                 int stderr_fd)
72    : SimObject(nm), system(_system)
73{
74    // initialize first 3 fds (stdin, stdout, stderr)
75    fd_map[STDIN_FILENO] = stdin_fd;
76    fd_map[STDOUT_FILENO] = stdout_fd;
77    fd_map[STDERR_FILENO] = stderr_fd;
78
79    // mark remaining fds as free
80    for (int i = 3; i <= MAX_FD; ++i) {
81        fd_map[i] = -1;
82    }
83
84    mmap_start = mmap_end = 0;
85    nxm_start = nxm_end = 0;
86    pTable = new PageTable(system);
87    // other parameters will be initialized when the program is loaded
88}
89
90
91void
92Process::regStats()
93{
94    using namespace Stats;
95
96    num_syscalls
97        .name(name() + ".PROG:num_syscalls")
98        .desc("Number of system calls")
99        ;
100}
101
102//
103// static helper functions
104//
105int
106Process::openInputFile(const string &filename)
107{
108    int fd = open(filename.c_str(), O_RDONLY);
109
110    if (fd == -1) {
111        perror(NULL);
112        cerr << "unable to open \"" << filename << "\" for reading\n";
113        fatal("can't open input file");
114    }
115
116    return fd;
117}
118
119
120int
121Process::openOutputFile(const string &filename)
122{
123    int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0774);
124
125    if (fd == -1) {
126        perror(NULL);
127        cerr << "unable to open \"" << filename << "\" for writing\n";
128        fatal("can't open output file");
129    }
130
131    return fd;
132}
133
134
135int
136Process::registerExecContext(ExecContext *xc)
137{
138    // add to list
139    int myIndex = execContexts.size();
140    execContexts.push_back(xc);
141
142    // return CPU number to caller
143    return myIndex;
144}
145
146void
147Process::startup()
148{
149    if (execContexts.empty())
150        fatal("Process %s is not associated with any CPUs!\n", name());
151
152    // first exec context for this process... initialize & enable
153    ExecContext *xc = execContexts[0];
154
155    // mark this context as active so it will start ticking.
156    xc->activate(0);
157
158    // Here we are grabbing the memory port of the CPU hosting the
159    // initial execution context for initialization.  In the long run
160    // this is not what we want, since it means that all
161    // initialization accesses (e.g., loading object file sections)
162    // will be done a cache block at a time through the CPU's cache.
163    // We really want something more like:
164    //
165    // memport = system->physmem->getPort();
166    // myPort.setPeer(memport);
167    // memport->setPeer(&myPort);
168    // initVirtMem = new TranslatingPort(myPort, pTable);
169    //
170    // but we need our own dummy port "myPort" that doesn't exist.
171    // In the short term it works just fine though.
172    initVirtMem = xc->getMemPort();
173}
174
175void
176Process::replaceExecContext(ExecContext *xc, int xcIndex)
177{
178    if (xcIndex >= execContexts.size()) {
179        panic("replaceExecContext: bad xcIndex, %d >= %d\n",
180              xcIndex, execContexts.size());
181    }
182
183    execContexts[xcIndex] = xc;
184}
185
186// map simulator fd sim_fd to target fd tgt_fd
187void
188Process::dup_fd(int sim_fd, int tgt_fd)
189{
190    if (tgt_fd < 0 || tgt_fd > MAX_FD)
191        panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
192
193    fd_map[tgt_fd] = sim_fd;
194}
195
196
197// generate new target fd for sim_fd
198int
199Process::alloc_fd(int sim_fd)
200{
201    // in case open() returns an error, don't allocate a new fd
202    if (sim_fd == -1)
203        return -1;
204
205    // find first free target fd
206    for (int free_fd = 0; free_fd < MAX_FD; ++free_fd) {
207        if (fd_map[free_fd] == -1) {
208            fd_map[free_fd] = sim_fd;
209            return free_fd;
210        }
211    }
212
213    panic("Process::alloc_fd: out of file descriptors!");
214}
215
216
217// free target fd (e.g., after close)
218void
219Process::free_fd(int tgt_fd)
220{
221    if (fd_map[tgt_fd] == -1)
222        warn("Process::free_fd: request to free unused fd %d", tgt_fd);
223
224    fd_map[tgt_fd] = -1;
225}
226
227
228// look up simulator fd for given target fd
229int
230Process::sim_fd(int tgt_fd)
231{
232    if (tgt_fd > MAX_FD)
233        return -1;
234
235    return fd_map[tgt_fd];
236}
237
238
239
240//
241// need to declare these here since there is no concrete Process type
242// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
243// which is where these get declared for concrete types).
244//
245DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
246
247
248////////////////////////////////////////////////////////////////////////
249//
250// LiveProcess member definitions
251//
252////////////////////////////////////////////////////////////////////////
253
254
255static void
256copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
257                TranslatingPort* memPort)
258{
259    Addr data_ptr_swap;
260    for (int i = 0; i < strings.size(); ++i) {
261        data_ptr_swap = htog(data_ptr);
262        memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr_swap, sizeof(Addr));
263        memPort->writeString(data_ptr, strings[i].c_str());
264        array_ptr += sizeof(Addr);
265        data_ptr += strings[i].size() + 1;
266    }
267    // add NULL terminator
268    data_ptr = 0;
269
270    memPort->writeBlob(array_ptr, (uint8_t*)&data_ptr, sizeof(Addr));
271}
272
273LiveProcess::LiveProcess(const string &nm, ObjectFile *_objFile,
274                         System *_system,
275                         int stdin_fd, int stdout_fd, int stderr_fd,
276                         vector<string> &_argv, vector<string> &_envp)
277    : Process(nm, _system, stdin_fd, stdout_fd, stderr_fd),
278      objFile(_objFile), argv(_argv), envp(_envp)
279{
280    prog_fname = argv[0];
281
282    brk_point = objFile->dataBase() + objFile->dataSize() + objFile->bssSize();
283    brk_point = roundUp(brk_point, VMPageSize);
284
285    // Set up stack.  On Alpha, stack goes below text section.  This
286    // code should get moved to some architecture-specific spot.
287    stack_base = objFile->textBase() - (409600+4096);
288
289    // Set up region for mmaps.  Tru64 seems to start just above 0 and
290    // grow up from there.
291    mmap_start = mmap_end = 0x10000;
292
293    // Set pointer for next thread stack.  Reserve 8M for main stack.
294    next_thread_stack_base = stack_base - (8 * 1024 * 1024);
295
296    // load up symbols, if any... these may be used for debugging or
297    // profiling.
298    if (!debugSymbolTable) {
299        debugSymbolTable = new SymbolTable();
300        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
301            !objFile->loadLocalSymbols(debugSymbolTable)) {
302            // didn't load any symbols
303            delete debugSymbolTable;
304            debugSymbolTable = NULL;
305        }
306    }
307}
308
309void
310LiveProcess::startup()
311{
312    Process::startup();
313
314    // load object file into target memory
315    objFile->loadSections(initVirtMem);
316
317    // Calculate how much space we need for arg & env arrays.
318    int argv_array_size = sizeof(Addr) * (argv.size() + 1);
319    int envp_array_size = sizeof(Addr) * (envp.size() + 1);
320    int arg_data_size = 0;
321    for (int i = 0; i < argv.size(); ++i) {
322        arg_data_size += argv[i].size() + 1;
323    }
324    int env_data_size = 0;
325    for (int i = 0; i < envp.size(); ++i) {
326        env_data_size += envp[i].size() + 1;
327    }
328
329    int space_needed =
330        argv_array_size + envp_array_size + arg_data_size + env_data_size;
331    // for SimpleScalar compatibility
332    if (space_needed < 16384)
333        space_needed = 16384;
334
335    // set bottom of stack
336    stack_min = stack_base - space_needed;
337    // align it
338    stack_min &= ~7;
339    stack_size = stack_base - stack_min;
340    // map memory
341    pTable->allocate(roundDown(stack_min, VMPageSize),
342                     roundUp(stack_size, VMPageSize));
343
344    // map out initial stack contents
345    Addr argv_array_base = stack_min + sizeof(uint64_t); // room for argc
346    Addr envp_array_base = argv_array_base + argv_array_size;
347    Addr arg_data_base = envp_array_base + envp_array_size;
348    Addr env_data_base = arg_data_base + arg_data_size;
349
350    // write contents to stack
351    uint64_t argc = argv.size();
352    argc = htog(argc);
353    initVirtMem->writeBlob(stack_min, (uint8_t*)&argc, sizeof(uint64_t));
354
355    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);
356    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
357
358    execContexts[0]->setIntReg(ArgumentReg0, argc);
359    execContexts[0]->setIntReg(ArgumentReg1, argv_array_base);
360    execContexts[0]->setIntReg(StackPointerReg, stack_min);
361    execContexts[0]->setIntReg(GlobalPointerReg, objFile->globalPointer());
362
363    Addr prog_entry = objFile->entryPoint();
364    execContexts[0]->setPC(prog_entry);
365    execContexts[0]->setNextPC(prog_entry + sizeof(MachInst));
366
367    num_processes++;
368}
369
370void
371LiveProcess::syscall(ExecContext *xc)
372{
373    num_syscalls++;
374
375    int64_t callnum = xc->readIntReg(SyscallNumReg);
376
377    SyscallDesc *desc = getDesc(callnum);
378    if (desc == NULL)
379        fatal("Syscall %d out of range", callnum);
380
381    desc->doSyscall(callnum, this, xc);
382}
383
384
385LiveProcess *
386LiveProcess::create(const string &nm, System *system,
387                    int stdin_fd, int stdout_fd, int stderr_fd,
388                    string executable,
389                    vector<string> &argv, vector<string> &envp)
390{
391    LiveProcess *process = NULL;
392    ObjectFile *objFile = createObjectFile(executable);
393    if (objFile == NULL) {
394        fatal("Can't load object file %s", executable);
395    }
396
397    // set up syscall emulation pointer for the current ISA
398    process = createProcess(nm, objFile, system,
399                            stdin_fd, stdout_fd, stderr_fd,
400                            argv, envp);
401
402    if (process == NULL)
403        fatal("Unknown error creating process object.");
404
405    return process;
406}
407
408
409
410BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
411
412    VectorParam<string> cmd;
413    Param<string> executable;
414    Param<string> input;
415    Param<string> output;
416    VectorParam<string> env;
417    SimObjectParam<System *> system;
418
419END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
420
421
422BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
423
424    INIT_PARAM(cmd, "command line (executable plus arguments)"),
425    INIT_PARAM(executable, "executable (overrides cmd[0] if set)"),
426    INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
427    INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
428    INIT_PARAM(env, "environment settings"),
429    INIT_PARAM(system, "system")
430
431END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
432
433
434CREATE_SIM_OBJECT(LiveProcess)
435{
436    string in = input;
437    string out = output;
438
439    // initialize file descriptors to default: same as simulator
440    int stdin_fd, stdout_fd, stderr_fd;
441
442    if (in == "stdin" || in == "cin")
443        stdin_fd = STDIN_FILENO;
444    else
445        stdin_fd = Process::openInputFile(input);
446
447    if (out == "stdout" || out == "cout")
448        stdout_fd = STDOUT_FILENO;
449    else if (out == "stderr" || out == "cerr")
450        stdout_fd = STDERR_FILENO;
451    else
452        stdout_fd = Process::openOutputFile(out);
453
454    stderr_fd = (stdout_fd != STDOUT_FILENO) ? stdout_fd : STDERR_FILENO;
455
456    return LiveProcess::create(getInstanceName(), system,
457                               stdin_fd, stdout_fd, stderr_fd,
458                               (string)executable == "" ? cmd[0] : executable,
459                               cmd, env);
460}
461
462REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)
463