process.cc revision 1514
1/*
2 * Copyright (c) 2001-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
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 "cpu/exec_context.hh"
40#include "cpu/full_cpu/smt.hh"
41#include "cpu/full_cpu/thread.hh"
42#include "eio/eio.hh"
43#include "mem/functional_mem/main_memory.hh"
44#include "sim/builder.hh"
45#include "sim/fake_syscall.hh"
46#include "sim/process.hh"
47#include "sim/stats.hh"
48
49#ifdef TARGET_ALPHA
50#include "arch/alpha/alpha_tru64_process.hh"
51#include "arch/alpha/alpha_linux_process.hh"
52#endif
53
54using namespace std;
55
56//
57// The purpose of this code is to fake the loader & syscall mechanism
58// when there's no OS: thus there's no resone to use it in FULL_SYSTEM
59// mode when we do have an OS
60//
61#ifdef FULL_SYSTEM
62#error "process.cc not compatible with FULL_SYSTEM"
63#endif
64
65// current number of allocated processes
66int num_processes = 0;
67
68Process::Process(const string &nm,
69                 int stdin_fd, 	// initial I/O descriptors
70                 int stdout_fd,
71                 int stderr_fd)
72    : SimObject(nm)
73{
74    // allocate memory space
75    memory = new MainMemory(nm + ".MainMem");
76
77    // allocate initial register file
78    init_regs = new RegFile;
79    memset(init_regs, 0, sizeof(RegFile));
80
81    // initialize first 3 fds (stdin, stdout, stderr)
82    fd_map[STDIN_FILENO] = stdin_fd;
83    fd_map[STDOUT_FILENO] = stdout_fd;
84    fd_map[STDERR_FILENO] = stderr_fd;
85
86    // mark remaining fds as free
87    for (int i = 3; i <= MAX_FD; ++i) {
88        fd_map[i] = -1;
89    }
90
91    mmap_start = mmap_end = 0;
92    nxm_start = nxm_end = 0;
93    // other parameters will be initialized when the program is loaded
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    if (myIndex == 0) {
148        // copy process's initial regs struct
149        xc->regs = *init_regs;
150    }
151
152    // return CPU number to caller and increment available CPU count
153    return myIndex;
154}
155
156void
157Process::startup()
158{
159    if (execContexts.empty())
160        return;
161
162    // first exec context for this process... initialize & enable
163    ExecContext *xc = execContexts[0];
164
165    // mark this context as active.
166    // activate with zero delay so that we start ticking right
167    // away on cycle 0
168    xc->activate(0);
169}
170
171void
172Process::replaceExecContext(ExecContext *xc, int xcIndex)
173{
174    if (xcIndex >= execContexts.size()) {
175        panic("replaceExecContext: bad xcIndex, %d >= %d\n",
176              xcIndex, execContexts.size());
177    }
178
179    execContexts[xcIndex] = xc;
180}
181
182// map simulator fd sim_fd to target fd tgt_fd
183void
184Process::dup_fd(int sim_fd, int tgt_fd)
185{
186    if (tgt_fd < 0 || tgt_fd > MAX_FD)
187        panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
188
189    fd_map[tgt_fd] = sim_fd;
190}
191
192
193// generate new target fd for sim_fd
194int
195Process::open_fd(int sim_fd)
196{
197    int free_fd;
198
199    // in case open() returns an error, don't allocate a new fd
200    if (sim_fd == -1)
201        return -1;
202
203    // find first free target fd
204    for (free_fd = 0; fd_map[free_fd] >= 0; ++free_fd) {
205        if (free_fd == MAX_FD)
206            panic("Process::open_fd: out of file descriptors!");
207    }
208
209    fd_map[free_fd] = sim_fd;
210
211    return free_fd;
212}
213
214
215// look up simulator fd for given target fd
216int
217Process::sim_fd(int tgt_fd)
218{
219    if (tgt_fd > MAX_FD)
220        return -1;
221
222    return fd_map[tgt_fd];
223}
224
225
226
227//
228// need to declare these here since there is no concrete Process type
229// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
230// which is where these get declared for concrete types).
231//
232DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
233
234
235////////////////////////////////////////////////////////////////////////
236//
237// LiveProcess member definitions
238//
239////////////////////////////////////////////////////////////////////////
240
241
242static void
243copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
244                FunctionalMemory *memory)
245{
246    for (int i = 0; i < strings.size(); ++i) {
247        memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
248        memory->writeString(data_ptr, strings[i].c_str());
249        array_ptr += sizeof(Addr);
250        data_ptr += strings[i].size() + 1;
251    }
252    // add NULL terminator
253    data_ptr = 0;
254    memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
255}
256
257LiveProcess::LiveProcess(const string &nm, ObjectFile *objFile,
258                         int stdin_fd, int stdout_fd, int stderr_fd,
259                         vector<string> &argv, vector<string> &envp)
260    : Process(nm, stdin_fd, stdout_fd, stderr_fd)
261{
262    prog_fname = argv[0];
263
264    prog_entry = objFile->entryPoint();
265    text_base = objFile->textBase();
266    text_size = objFile->textSize();
267    data_base = objFile->dataBase();
268    data_size = objFile->dataSize() + objFile->bssSize();
269    brk_point = RoundUp<uint64_t>(data_base + data_size, VMPageSize);
270
271    // load object file into target memory
272    objFile->loadSections(memory);
273
274    // load up symbols, if any... these may be used for debugging or
275    // profiling.
276    if (!debugSymbolTable) {
277        debugSymbolTable = new SymbolTable();
278        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
279            !objFile->loadLocalSymbols(debugSymbolTable)) {
280            // didn't load any symbols
281            delete debugSymbolTable;
282            debugSymbolTable = NULL;
283        }
284    }
285
286    // Set up stack.  On Alpha, stack goes below text section.  This
287    // code should get moved to some architecture-specific spot.
288    stack_base = text_base - (409600+4096);
289
290    // Set up region for mmaps.  Tru64 seems to start just above 0 and
291    // grow up from there.
292    mmap_start = mmap_end = 0x10000;
293
294    // Set pointer for next thread stack.  Reserve 8M for main stack.
295    next_thread_stack_base = stack_base - (8 * 1024 * 1024);
296
297    // Calculate how much space we need for arg & env arrays.
298    int argv_array_size = sizeof(Addr) * (argv.size() + 1);
299    int envp_array_size = sizeof(Addr) * (envp.size() + 1);
300    int arg_data_size = 0;
301    for (int i = 0; i < argv.size(); ++i) {
302        arg_data_size += argv[i].size() + 1;
303    }
304    int env_data_size = 0;
305    for (int i = 0; i < envp.size(); ++i) {
306        env_data_size += envp[i].size() + 1;
307    }
308
309    int space_needed =
310        argv_array_size + envp_array_size + arg_data_size + env_data_size;
311    // for SimpleScalar compatibility
312    if (space_needed < 16384)
313        space_needed = 16384;
314
315    // set bottom of stack
316    stack_min = stack_base - space_needed;
317    // align it
318    stack_min &= ~7;
319    stack_size = stack_base - stack_min;
320
321    // map out initial stack contents
322    Addr argv_array_base = stack_min + sizeof(uint64_t); // room for argc
323    Addr envp_array_base = argv_array_base + argv_array_size;
324    Addr arg_data_base = envp_array_base + envp_array_size;
325    Addr env_data_base = arg_data_base + arg_data_size;
326
327    // write contents to stack
328    uint64_t argc = argv.size();
329    memory->access(Write, stack_min, &argc, sizeof(uint64_t));
330
331    copyStringArray(argv, argv_array_base, arg_data_base, memory);
332    copyStringArray(envp, envp_array_base, env_data_base, memory);
333
334    init_regs->intRegFile[ArgumentReg0] = argc;
335    init_regs->intRegFile[ArgumentReg1] = argv_array_base;
336    init_regs->intRegFile[StackPointerReg] = stack_min;
337    init_regs->intRegFile[GlobalPointerReg] = objFile->globalPointer();
338    init_regs->pc = prog_entry;
339    init_regs->npc = prog_entry + sizeof(MachInst);
340}
341
342
343LiveProcess *
344LiveProcess::create(const string &nm,
345                    int stdin_fd, int stdout_fd, int stderr_fd,
346                    vector<string> &argv, vector<string> &envp)
347{
348    LiveProcess *process = NULL;
349    ObjectFile *objFile = createObjectFile(argv[0]);
350    if (objFile == NULL) {
351        fatal("Can't load object file %s", argv[0]);
352    }
353
354    // check object type & set up syscall emulation pointer
355    if (objFile->getArch() == ObjectFile::Alpha) {
356        switch (objFile->getOpSys()) {
357          case ObjectFile::Tru64:
358            process = new AlphaTru64Process(nm, objFile,
359                                            stdin_fd, stdout_fd, stderr_fd,
360                                            argv, envp);
361            break;
362
363          case ObjectFile::Linux:
364            process = new AlphaLinuxProcess(nm, objFile,
365                                            stdin_fd, stdout_fd, stderr_fd,
366                                            argv, envp);
367            break;
368
369          default:
370            fatal("Unknown/unsupported operating system.");
371        }
372    } else {
373        fatal("Unknown object file architecture.");
374    }
375
376    delete objFile;
377
378    if (process == NULL)
379        fatal("Unknown error creating process object.");
380
381    return process;
382}
383
384
385BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
386
387    VectorParam<string> cmd;
388    Param<string> input;
389    Param<string> output;
390    VectorParam<string> env;
391
392END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
393
394
395BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
396
397    INIT_PARAM(cmd, "command line (executable plus arguments)"),
398    INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
399    INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
400    INIT_PARAM(env, "environment settings")
401
402END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
403
404
405CREATE_SIM_OBJECT(LiveProcess)
406{
407    string in = input;
408    string out = output;
409
410    // initialize file descriptors to default: same as simulator
411    int stdin_fd, stdout_fd, stderr_fd;
412
413    if (in == "stdin" || in == "cin")
414        stdin_fd = STDIN_FILENO;
415    else
416        stdin_fd = Process::openInputFile(input);
417
418    if (out == "stdout" || out == "cout")
419        stdout_fd = STDOUT_FILENO;
420    else if (out == "stderr" || out == "cerr")
421        stdout_fd = STDERR_FILENO;
422    else
423        stdout_fd = Process::openOutputFile(out);
424
425    stderr_fd = (stdout_fd != STDOUT_FILENO) ? stdout_fd : STDERR_FILENO;
426
427    return LiveProcess::create(getInstanceName(),
428                               stdin_fd, stdout_fd, stderr_fd,
429                               cmd, env);
430}
431
432REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)
433