process.cc revision 4117:2807cee7b892
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 * Authors: Nathan Binkert
29 *          Steve Reinhardt
30 *          Ali Saidi
31 */
32
33#include <unistd.h>
34#include <fcntl.h>
35
36#include <string>
37
38#include "arch/remote_gdb.hh"
39#include "base/intmath.hh"
40#include "base/loader/object_file.hh"
41#include "base/loader/symtab.hh"
42#include "base/statistics.hh"
43#include "config/full_system.hh"
44#include "cpu/thread_context.hh"
45#include "mem/page_table.hh"
46#include "mem/physical.hh"
47#include "mem/translating_port.hh"
48#include "sim/builder.hh"
49#include "sim/process.hh"
50#include "sim/stats.hh"
51#include "sim/syscall_emul.hh"
52#include "sim/system.hh"
53
54#include "arch/isa_specific.hh"
55#if THE_ISA == ALPHA_ISA
56#include "arch/alpha/linux/process.hh"
57#include "arch/alpha/tru64/process.hh"
58#elif THE_ISA == SPARC_ISA
59#include "arch/sparc/linux/process.hh"
60#include "arch/sparc/solaris/process.hh"
61#elif THE_ISA == MIPS_ISA
62#include "arch/mips/linux/process.hh"
63#else
64#error "THE_ISA not set"
65#endif
66
67
68using namespace std;
69using namespace TheISA;
70
71//
72// The purpose of this code is to fake the loader & syscall mechanism
73// when there's no OS: thus there's no resone to use it in FULL_SYSTEM
74// mode when we do have an OS
75//
76#if FULL_SYSTEM
77#error "process.cc not compatible with FULL_SYSTEM"
78#endif
79
80// current number of allocated processes
81int num_processes = 0;
82
83Process::Process(const string &nm,
84                 System *_system,
85                 int stdin_fd, 	// initial I/O descriptors
86                 int stdout_fd,
87                 int stderr_fd)
88    : SimObject(nm), system(_system)
89{
90    // initialize first 3 fds (stdin, stdout, stderr)
91    fd_map[STDIN_FILENO] = stdin_fd;
92    fd_map[STDOUT_FILENO] = stdout_fd;
93    fd_map[STDERR_FILENO] = stderr_fd;
94
95    // mark remaining fds as free
96    for (int i = 3; i <= MAX_FD; ++i) {
97        fd_map[i] = -1;
98    }
99
100    mmap_start = mmap_end = 0;
101    nxm_start = nxm_end = 0;
102    pTable = new PageTable(system);
103    // other parameters will be initialized when the program is loaded
104}
105
106
107void
108Process::regStats()
109{
110    using namespace Stats;
111
112    num_syscalls
113        .name(name() + ".PROG:num_syscalls")
114        .desc("Number of system calls")
115        ;
116}
117
118//
119// static helper functions
120//
121int
122Process::openInputFile(const string &filename)
123{
124    int fd = open(filename.c_str(), O_RDONLY);
125
126    if (fd == -1) {
127        perror(NULL);
128        cerr << "unable to open \"" << filename << "\" for reading\n";
129        fatal("can't open input file");
130    }
131
132    return fd;
133}
134
135
136int
137Process::openOutputFile(const string &filename)
138{
139    int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0774);
140
141    if (fd == -1) {
142        perror(NULL);
143        cerr << "unable to open \"" << filename << "\" for writing\n";
144        fatal("can't open output file");
145    }
146
147    return fd;
148}
149
150
151int
152Process::registerThreadContext(ThreadContext *tc)
153{
154    // add to list
155    int myIndex = threadContexts.size();
156    threadContexts.push_back(tc);
157
158    RemoteGDB *rgdb = new RemoteGDB(system, tc);
159    GDBListener *gdbl = new GDBListener(rgdb, 7000 + myIndex);
160    gdbl->listen();
161    //gdbl->accept();
162
163    remoteGDB.push_back(rgdb);
164
165    // return CPU number to caller
166    return myIndex;
167}
168
169void
170Process::startup()
171{
172    if (threadContexts.empty())
173        fatal("Process %s is not associated with any CPUs!\n", name());
174
175    // first thread context for this process... initialize & enable
176    ThreadContext *tc = threadContexts[0];
177
178    // mark this context as active so it will start ticking.
179    tc->activate(0);
180
181    Port *mem_port;
182    mem_port = system->physmem->getPort("functional");
183    initVirtMem = new TranslatingPort("process init port", pTable, true);
184    mem_port->setPeer(initVirtMem);
185    initVirtMem->setPeer(mem_port);
186}
187
188void
189Process::replaceThreadContext(ThreadContext *tc, int tcIndex)
190{
191    if (tcIndex >= threadContexts.size()) {
192        panic("replaceThreadContext: bad tcIndex, %d >= %d\n",
193              tcIndex, threadContexts.size());
194    }
195
196    threadContexts[tcIndex] = tc;
197}
198
199// map simulator fd sim_fd to target fd tgt_fd
200void
201Process::dup_fd(int sim_fd, int tgt_fd)
202{
203    if (tgt_fd < 0 || tgt_fd > MAX_FD)
204        panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
205
206    fd_map[tgt_fd] = sim_fd;
207}
208
209
210// generate new target fd for sim_fd
211int
212Process::alloc_fd(int sim_fd)
213{
214    // in case open() returns an error, don't allocate a new fd
215    if (sim_fd == -1)
216        return -1;
217
218    // find first free target fd
219    for (int free_fd = 0; free_fd < MAX_FD; ++free_fd) {
220        if (fd_map[free_fd] == -1) {
221            fd_map[free_fd] = sim_fd;
222            return free_fd;
223        }
224    }
225
226    panic("Process::alloc_fd: out of file descriptors!");
227}
228
229
230// free target fd (e.g., after close)
231void
232Process::free_fd(int tgt_fd)
233{
234    if (fd_map[tgt_fd] == -1)
235        warn("Process::free_fd: request to free unused fd %d", tgt_fd);
236
237    fd_map[tgt_fd] = -1;
238}
239
240
241// look up simulator fd for given target fd
242int
243Process::sim_fd(int tgt_fd)
244{
245    if (tgt_fd > MAX_FD)
246        return -1;
247
248    return fd_map[tgt_fd];
249}
250
251void
252Process::serialize(std::ostream &os)
253{
254    SERIALIZE_SCALAR(initialContextLoaded);
255    SERIALIZE_SCALAR(brk_point);
256    SERIALIZE_SCALAR(stack_base);
257    SERIALIZE_SCALAR(stack_size);
258    SERIALIZE_SCALAR(stack_min);
259    SERIALIZE_SCALAR(next_thread_stack_base);
260    SERIALIZE_SCALAR(mmap_start);
261    SERIALIZE_SCALAR(mmap_end);
262    SERIALIZE_SCALAR(nxm_start);
263    SERIALIZE_SCALAR(nxm_end);
264    SERIALIZE_ARRAY(fd_map, MAX_FD);
265
266    pTable->serialize(os);
267}
268
269void
270Process::unserialize(Checkpoint *cp, const std::string &section)
271{
272    UNSERIALIZE_SCALAR(initialContextLoaded);
273    UNSERIALIZE_SCALAR(brk_point);
274    UNSERIALIZE_SCALAR(stack_base);
275    UNSERIALIZE_SCALAR(stack_size);
276    UNSERIALIZE_SCALAR(stack_min);
277    UNSERIALIZE_SCALAR(next_thread_stack_base);
278    UNSERIALIZE_SCALAR(mmap_start);
279    UNSERIALIZE_SCALAR(mmap_end);
280    UNSERIALIZE_SCALAR(nxm_start);
281    UNSERIALIZE_SCALAR(nxm_end);
282    UNSERIALIZE_ARRAY(fd_map, MAX_FD);
283
284    pTable->unserialize(cp, section);
285}
286
287
288//
289// need to declare these here since there is no concrete Process type
290// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
291// which is where these get declared for concrete types).
292//
293DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
294
295
296////////////////////////////////////////////////////////////////////////
297//
298// LiveProcess member definitions
299//
300////////////////////////////////////////////////////////////////////////
301
302
303LiveProcess::LiveProcess(const string &nm, ObjectFile *_objFile,
304                         System *_system,
305                         int stdin_fd, int stdout_fd, int stderr_fd,
306                         vector<string> &_argv, vector<string> &_envp,
307                         const string &_cwd,
308                         uint64_t _uid, uint64_t _euid,
309                         uint64_t _gid, uint64_t _egid,
310                         uint64_t _pid, uint64_t _ppid)
311    : Process(nm, _system, stdin_fd, stdout_fd, stderr_fd),
312      objFile(_objFile), argv(_argv), envp(_envp), cwd(_cwd)
313{
314    __uid = _uid;
315    __euid = _euid;
316    __gid = _gid;
317    __egid = _egid;
318    __pid = _pid;
319    __ppid = _ppid;
320
321    prog_fname = argv[0];
322
323    // load up symbols, if any... these may be used for debugging or
324    // profiling.
325    if (!debugSymbolTable) {
326        debugSymbolTable = new SymbolTable();
327        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
328            !objFile->loadLocalSymbols(debugSymbolTable)) {
329            // didn't load any symbols
330            delete debugSymbolTable;
331            debugSymbolTable = NULL;
332        }
333    }
334}
335
336void
337LiveProcess::argsInit(int intSize, int pageSize)
338{
339    Process::startup();
340
341    // load object file into target memory
342    objFile->loadSections(initVirtMem);
343
344    // Calculate how much space we need for arg & env arrays.
345    int argv_array_size = intSize * (argv.size() + 1);
346    int envp_array_size = intSize * (envp.size() + 1);
347    int arg_data_size = 0;
348    for (int i = 0; i < argv.size(); ++i) {
349        arg_data_size += argv[i].size() + 1;
350    }
351    int env_data_size = 0;
352    for (int i = 0; i < envp.size(); ++i) {
353        env_data_size += envp[i].size() + 1;
354    }
355
356    int space_needed =
357        argv_array_size + envp_array_size + arg_data_size + env_data_size;
358    if (space_needed < 32*1024)
359        space_needed = 32*1024;
360
361    // set bottom of stack
362    stack_min = stack_base - space_needed;
363    // align it
364    stack_min = roundDown(stack_min, pageSize);
365    stack_size = stack_base - stack_min;
366    // map memory
367    pTable->allocate(stack_min, roundUp(stack_size, pageSize));
368
369    // map out initial stack contents
370    Addr argv_array_base = stack_min + intSize; // room for argc
371    Addr envp_array_base = argv_array_base + argv_array_size;
372    Addr arg_data_base = envp_array_base + envp_array_size;
373    Addr env_data_base = arg_data_base + arg_data_size;
374
375    // write contents to stack
376    uint64_t argc = argv.size();
377    if (intSize == 8)
378        argc = htog((uint64_t)argc);
379    else if (intSize == 4)
380        argc = htog((uint32_t)argc);
381    else
382        panic("Unknown int size");
383
384    initVirtMem->writeBlob(stack_min, (uint8_t*)&argc, intSize);
385
386    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);
387    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
388
389    threadContexts[0]->setIntReg(ArgumentReg0, argc);
390    threadContexts[0]->setIntReg(ArgumentReg1, argv_array_base);
391    threadContexts[0]->setIntReg(StackPointerReg, stack_min);
392
393    Addr prog_entry = objFile->entryPoint();
394    threadContexts[0]->setPC(prog_entry);
395    threadContexts[0]->setNextPC(prog_entry + sizeof(MachInst));
396
397#if THE_ISA != ALPHA_ISA //e.g. MIPS or Sparc
398    threadContexts[0]->setNextNPC(prog_entry + (2 * sizeof(MachInst)));
399#endif
400
401    num_processes++;
402}
403
404void
405LiveProcess::syscall(int64_t callnum, ThreadContext *tc)
406{
407    num_syscalls++;
408
409    SyscallDesc *desc = getDesc(callnum);
410    if (desc == NULL)
411        fatal("Syscall %d out of range", callnum);
412
413    desc->doSyscall(callnum, this, tc);
414}
415
416LiveProcess *
417LiveProcess::create(const std::string &nm, System *system, int stdin_fd,
418                    int stdout_fd, int stderr_fd, std::string executable,
419                    std::vector<std::string> &argv,
420                    std::vector<std::string> &envp,
421                    const std::string &cwd,
422                    uint64_t _uid, uint64_t _euid,
423                    uint64_t _gid, uint64_t _egid,
424                    uint64_t _pid, uint64_t _ppid)
425{
426    LiveProcess *process = NULL;
427
428    ObjectFile *objFile = createObjectFile(executable);
429    if (objFile == NULL) {
430        fatal("Can't load object file %s", executable);
431    }
432
433    if (objFile->isDynamic())
434       fatal("Object file is a dynamic executable however only static "
435             "executables are supported!\n        Please recompile your "
436             "executable as a static binary and try again.\n");
437
438#if THE_ISA == ALPHA_ISA
439    if (objFile->getArch() != ObjectFile::Alpha)
440        fatal("Object file architecture does not match compiled ISA (Alpha).");
441    switch (objFile->getOpSys()) {
442      case ObjectFile::Tru64:
443        process = new AlphaTru64Process(nm, objFile, system,
444                                        stdin_fd, stdout_fd, stderr_fd,
445                                        argv, envp, cwd,
446                                        _uid, _euid, _gid, _egid, _pid, _ppid);
447        break;
448
449      case ObjectFile::Linux:
450        process = new AlphaLinuxProcess(nm, objFile, system,
451                                        stdin_fd, stdout_fd, stderr_fd,
452                                        argv, envp, cwd,
453                                        _uid, _euid, _gid, _egid, _pid, _ppid);
454        break;
455
456      default:
457        fatal("Unknown/unsupported operating system.");
458    }
459#elif THE_ISA == SPARC_ISA
460    if (objFile->getArch() != ObjectFile::SPARC64 && objFile->getArch() != ObjectFile::SPARC32)
461        fatal("Object file architecture does not match compiled ISA (SPARC).");
462    switch (objFile->getOpSys()) {
463      case ObjectFile::Linux:
464        if (objFile->getArch() == ObjectFile::SPARC64) {
465            process = new Sparc64LinuxProcess(nm, objFile, system,
466                                              stdin_fd, stdout_fd, stderr_fd,
467                                              argv, envp, cwd,
468                                              _uid, _euid, _gid,
469                                              _egid, _pid, _ppid);
470        } else {
471            process = new Sparc32LinuxProcess(nm, objFile, system,
472                                              stdin_fd, stdout_fd, stderr_fd,
473                                              argv, envp, cwd,
474                                              _uid, _euid, _gid,
475                                              _egid, _pid, _ppid);
476        }
477        break;
478
479
480      case ObjectFile::Solaris:
481        process = new SparcSolarisProcess(nm, objFile, system,
482                                        stdin_fd, stdout_fd, stderr_fd,
483                                        argv, envp, cwd,
484                                        _uid, _euid, _gid, _egid, _pid, _ppid);
485        break;
486      default:
487        fatal("Unknown/unsupported operating system.");
488    }
489#elif THE_ISA == MIPS_ISA
490    if (objFile->getArch() != ObjectFile::Mips)
491        fatal("Object file architecture does not match compiled ISA (MIPS).");
492    switch (objFile->getOpSys()) {
493      case ObjectFile::Linux:
494        process = new MipsLinuxProcess(nm, objFile, system,
495                                        stdin_fd, stdout_fd, stderr_fd,
496                                        argv, envp, cwd,
497                                        _uid, _euid, _gid, _egid, _pid, _ppid);
498        break;
499
500      default:
501        fatal("Unknown/unsupported operating system.");
502    }
503#else
504#error "THE_ISA not set"
505#endif
506
507
508    if (process == NULL)
509        fatal("Unknown error creating process object.");
510    return process;
511}
512
513
514BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
515
516    VectorParam<string> cmd;
517    Param<string> executable;
518    Param<string> input;
519    Param<string> output;
520    VectorParam<string> env;
521    Param<string> cwd;
522    SimObjectParam<System *> system;
523    Param<uint64_t> uid;
524    Param<uint64_t> euid;
525    Param<uint64_t> gid;
526    Param<uint64_t> egid;
527    Param<uint64_t> pid;
528    Param<uint64_t> ppid;
529
530END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
531
532
533BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
534
535    INIT_PARAM(cmd, "command line (executable plus arguments)"),
536    INIT_PARAM(executable, "executable (overrides cmd[0] if set)"),
537    INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
538    INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
539    INIT_PARAM(env, "environment settings"),
540    INIT_PARAM(cwd, "current working directory"),
541    INIT_PARAM(system, "system"),
542    INIT_PARAM(uid, "user id"),
543    INIT_PARAM(euid, "effective user id"),
544    INIT_PARAM(gid, "group id"),
545    INIT_PARAM(egid, "effective group id"),
546    INIT_PARAM(pid, "process id"),
547    INIT_PARAM(ppid, "parent process id")
548
549END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
550
551
552CREATE_SIM_OBJECT(LiveProcess)
553{
554    string in = input;
555    string out = output;
556
557    // initialize file descriptors to default: same as simulator
558    int stdin_fd, stdout_fd, stderr_fd;
559
560    if (in == "stdin" || in == "cin")
561        stdin_fd = STDIN_FILENO;
562    else
563        stdin_fd = Process::openInputFile(input);
564
565    if (out == "stdout" || out == "cout")
566        stdout_fd = STDOUT_FILENO;
567    else if (out == "stderr" || out == "cerr")
568        stdout_fd = STDERR_FILENO;
569    else
570        stdout_fd = Process::openOutputFile(out);
571
572    stderr_fd = (stdout_fd != STDOUT_FILENO) ? stdout_fd : STDERR_FILENO;
573
574    return LiveProcess::create(getInstanceName(), system,
575                               stdin_fd, stdout_fd, stderr_fd,
576                               (string)executable == "" ? cmd[0] : executable,
577                               cmd, env, cwd,
578                               uid, euid, gid, egid, pid, ppid);
579}
580
581
582REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)
583