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