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