process.cc revision 2454
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/memory.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    initVirtMem = new TranslatingPort((system->physmem->getPort("DCACHE"))->getPeer(), pTable);
153
154    // first exec context for this process... initialize & enable
155    ExecContext *xc = execContexts[0];
156
157    // mark this context as active so it will start ticking.
158    xc->activate(0);
159}
160
161void
162Process::replaceExecContext(ExecContext *xc, int xcIndex)
163{
164    if (xcIndex >= execContexts.size()) {
165        panic("replaceExecContext: bad xcIndex, %d >= %d\n",
166              xcIndex, execContexts.size());
167    }
168
169    execContexts[xcIndex] = xc;
170}
171
172// map simulator fd sim_fd to target fd tgt_fd
173void
174Process::dup_fd(int sim_fd, int tgt_fd)
175{
176    if (tgt_fd < 0 || tgt_fd > MAX_FD)
177        panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
178
179    fd_map[tgt_fd] = sim_fd;
180}
181
182
183// generate new target fd for sim_fd
184int
185Process::alloc_fd(int sim_fd)
186{
187    // in case open() returns an error, don't allocate a new fd
188    if (sim_fd == -1)
189        return -1;
190
191    // find first free target fd
192    for (int free_fd = 0; free_fd < MAX_FD; ++free_fd) {
193        if (fd_map[free_fd] == -1) {
194            fd_map[free_fd] = sim_fd;
195            return free_fd;
196        }
197    }
198
199    panic("Process::alloc_fd: out of file descriptors!");
200}
201
202
203// free target fd (e.g., after close)
204void
205Process::free_fd(int tgt_fd)
206{
207    if (fd_map[tgt_fd] == -1)
208        warn("Process::free_fd: request to free unused fd %d", tgt_fd);
209
210    fd_map[tgt_fd] = -1;
211}
212
213
214// look up simulator fd for given target fd
215int
216Process::sim_fd(int tgt_fd)
217{
218    if (tgt_fd > MAX_FD)
219        return -1;
220
221    return fd_map[tgt_fd];
222}
223
224
225
226//
227// need to declare these here since there is no concrete Process type
228// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
229// which is where these get declared for concrete types).
230//
231DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
232
233
234////////////////////////////////////////////////////////////////////////
235//
236// LiveProcess member definitions
237//
238////////////////////////////////////////////////////////////////////////
239
240
241static void
242copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
243                TranslatingPort* memPort)
244{
245    Addr data_ptr_swap;
246    for (int i = 0; i < strings.size(); ++i) {
247        data_ptr_swap = htog(data_ptr);
248        memPort->writeBlobFunctional(array_ptr, (uint8_t*)&data_ptr_swap, sizeof(Addr));
249        memPort->writeStringFunctional(data_ptr, strings[i].c_str());
250        array_ptr += sizeof(Addr);
251        data_ptr += strings[i].size() + 1;
252    }
253    // add NULL terminator
254    data_ptr = 0;
255
256    memPort->writeBlobFunctional(array_ptr, (uint8_t*)&data_ptr, sizeof(Addr));
257}
258
259LiveProcess::LiveProcess(const string &nm, ObjectFile *_objFile,
260                         System *_system,
261                         int stdin_fd, int stdout_fd, int stderr_fd,
262                         vector<string> &_argv, vector<string> &_envp)
263    : Process(nm, _system, stdin_fd, stdout_fd, stderr_fd),
264      objFile(_objFile), argv(_argv), envp(_envp)
265{
266    prog_fname = argv[0];
267
268    brk_point = objFile->dataBase() + objFile->dataSize() + objFile->bssSize();
269    brk_point = roundUp(brk_point, VMPageSize);
270
271    // Set up stack.  On Alpha, stack goes below text section.  This
272    // code should get moved to some architecture-specific spot.
273    stack_base = objFile->textBase() - (409600+4096);
274
275    // Set up region for mmaps.  Tru64 seems to start just above 0 and
276    // grow up from there.
277    mmap_start = mmap_end = 0x10000;
278
279    // Set pointer for next thread stack.  Reserve 8M for main stack.
280    next_thread_stack_base = stack_base - (8 * 1024 * 1024);
281
282    // load up symbols, if any... these may be used for debugging or
283    // profiling.
284    if (!debugSymbolTable) {
285        debugSymbolTable = new SymbolTable();
286        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
287            !objFile->loadLocalSymbols(debugSymbolTable)) {
288            // didn't load any symbols
289            delete debugSymbolTable;
290            debugSymbolTable = NULL;
291        }
292    }
293}
294
295void
296LiveProcess::startup()
297{
298    Process::startup();
299
300    // load object file into target memory
301    objFile->loadSections(initVirtMem);
302
303    // Calculate how much space we need for arg & env arrays.
304    int argv_array_size = sizeof(Addr) * (argv.size() + 1);
305    int envp_array_size = sizeof(Addr) * (envp.size() + 1);
306    int arg_data_size = 0;
307    for (int i = 0; i < argv.size(); ++i) {
308        arg_data_size += argv[i].size() + 1;
309    }
310    int env_data_size = 0;
311    for (int i = 0; i < envp.size(); ++i) {
312        env_data_size += envp[i].size() + 1;
313    }
314
315    int space_needed =
316        argv_array_size + envp_array_size + arg_data_size + env_data_size;
317    // for SimpleScalar compatibility
318    if (space_needed < 16384)
319        space_needed = 16384;
320
321    // set bottom of stack
322    stack_min = stack_base - space_needed;
323    // align it
324    stack_min &= ~7;
325    stack_size = stack_base - stack_min;
326    // map memory
327    pTable->allocate(roundDown(stack_min, VMPageSize),
328                     roundUp(stack_size, VMPageSize));
329
330    // map out initial stack contents
331    Addr argv_array_base = stack_min + sizeof(uint64_t); // room for argc
332    Addr envp_array_base = argv_array_base + argv_array_size;
333    Addr arg_data_base = envp_array_base + envp_array_size;
334    Addr env_data_base = arg_data_base + arg_data_size;
335
336    // write contents to stack
337    uint64_t argc = argv.size();
338    argc = htog(argc);
339    initVirtMem->writeBlobFunctional(stack_min, (uint8_t*)&argc, sizeof(uint64_t));
340
341    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);
342    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
343
344    execContexts[0]->setIntReg(ArgumentReg0, argc);
345    execContexts[0]->setIntReg(ArgumentReg1, argv_array_base);
346    execContexts[0]->setIntReg(StackPointerReg, stack_min);
347    execContexts[0]->setIntReg(GlobalPointerReg, objFile->globalPointer());
348
349    Addr prog_entry = objFile->entryPoint();
350    execContexts[0]->setPC(prog_entry);
351    execContexts[0]->setNextPC(prog_entry + sizeof(MachInst));
352
353    num_processes++;
354}
355
356void
357LiveProcess::syscall(ExecContext *xc)
358{
359    num_syscalls++;
360
361    int64_t callnum = xc->readIntReg(SyscallNumReg);
362
363    SyscallDesc *desc = getDesc(callnum);
364    if (desc == NULL)
365        fatal("Syscall %d out of range", callnum);
366
367    desc->doSyscall(callnum, this, xc);
368}
369
370LiveProcess *
371LiveProcess::create(const string &nm, System *system,
372                    int stdin_fd, int stdout_fd, int stderr_fd,
373                    string executable,
374                    vector<string> &argv, vector<string> &envp)
375{
376    LiveProcess *process = NULL;
377    ObjectFile *objFile = createObjectFile(executable);
378    if (objFile == NULL) {
379        fatal("Can't load object file %s", executable);
380    }
381
382    // set up syscall emulation pointer for the current ISA
383    process = createProcess(nm, objFile, system,
384                            stdin_fd, stdout_fd, stderr_fd,
385                            argv, envp);
386
387    if (process == NULL)
388        fatal("Unknown error creating process object.");
389
390    return process;
391}
392
393
394
395BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
396
397    VectorParam<string> cmd;
398    Param<string> executable;
399    Param<string> input;
400    Param<string> output;
401    VectorParam<string> env;
402    SimObjectParam<System *> system;
403
404END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
405
406
407BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
408
409    INIT_PARAM(cmd, "command line (executable plus arguments)"),
410    INIT_PARAM(executable, "executable (overrides cmd[0] if set)"),
411    INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
412    INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
413    INIT_PARAM(env, "environment settings"),
414    INIT_PARAM(system, "system")
415
416END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
417
418
419CREATE_SIM_OBJECT(LiveProcess)
420{
421    string in = input;
422    string out = output;
423
424    // initialize file descriptors to default: same as simulator
425    int stdin_fd, stdout_fd, stderr_fd;
426
427    if (in == "stdin" || in == "cin")
428        stdin_fd = STDIN_FILENO;
429    else
430        stdin_fd = Process::openInputFile(input);
431
432    if (out == "stdout" || out == "cout")
433        stdout_fd = STDOUT_FILENO;
434    else if (out == "stderr" || out == "cerr")
435        stdout_fd = STDERR_FILENO;
436    else
437        stdout_fd = Process::openOutputFile(out);
438
439    stderr_fd = (stdout_fd != STDOUT_FILENO) ? stdout_fd : STDERR_FILENO;
440
441    return LiveProcess::create(getInstanceName(), system,
442                               stdin_fd, stdout_fd, stderr_fd,
443                               (string)executable == "" ? cmd[0] : executable,
444                               cmd, env);
445}
446
447REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)
448