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