Merge gblack@m5.eecs.umich.edu:/bk/multiarch
[gem5.git] / sim / process.cc
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 #include "sim/syscall_emul.hh"
50
51 #include "arch/process.hh"
52
53 using namespace std;
54 using namespace TheISA;
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 #if FULL_SYSTEM
62 #error "process.cc not compatible with FULL_SYSTEM"
63 #endif
64
65 // current number of allocated processes
66 int num_processes = 0;
67
68 Process::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
96 void
97 Process::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 //
110 int
111 Process::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
125 int
126 Process::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
140 int
141 Process::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
156 void
157 Process::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 so it will start ticking.
166 xc->activate(0);
167 }
168
169 void
170 Process::replaceExecContext(ExecContext *xc, int xcIndex)
171 {
172 if (xcIndex >= execContexts.size()) {
173 panic("replaceExecContext: bad xcIndex, %d >= %d\n",
174 xcIndex, execContexts.size());
175 }
176
177 execContexts[xcIndex] = xc;
178 }
179
180 // map simulator fd sim_fd to target fd tgt_fd
181 void
182 Process::dup_fd(int sim_fd, int tgt_fd)
183 {
184 if (tgt_fd < 0 || tgt_fd > MAX_FD)
185 panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
186
187 fd_map[tgt_fd] = sim_fd;
188 }
189
190
191 // generate new target fd for sim_fd
192 int
193 Process::alloc_fd(int sim_fd)
194 {
195 // in case open() returns an error, don't allocate a new fd
196 if (sim_fd == -1)
197 return -1;
198
199 // find first free target fd
200 for (int free_fd = 0; free_fd < MAX_FD; ++free_fd) {
201 if (fd_map[free_fd] == -1) {
202 fd_map[free_fd] = sim_fd;
203 return free_fd;
204 }
205 }
206
207 panic("Process::alloc_fd: out of file descriptors!");
208 }
209
210
211 // free target fd (e.g., after close)
212 void
213 Process::free_fd(int tgt_fd)
214 {
215 if (fd_map[tgt_fd] == -1)
216 warn("Process::free_fd: request to free unused fd %d", tgt_fd);
217
218 fd_map[tgt_fd] = -1;
219 }
220
221
222 // look up simulator fd for given target fd
223 int
224 Process::sim_fd(int tgt_fd)
225 {
226 if (tgt_fd > MAX_FD)
227 return -1;
228
229 return fd_map[tgt_fd];
230 }
231
232
233
234 //
235 // need to declare these here since there is no concrete Process type
236 // that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
237 // which is where these get declared for concrete types).
238 //
239 DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
240
241
242 ////////////////////////////////////////////////////////////////////////
243 //
244 // LiveProcess member definitions
245 //
246 ////////////////////////////////////////////////////////////////////////
247
248
249 static void
250 copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
251 FunctionalMemory *memory)
252 {
253 Addr data_ptr_swap;
254 for (int i = 0; i < strings.size(); ++i) {
255 data_ptr_swap = htog(data_ptr);
256 memory->access(Write, array_ptr, &data_ptr_swap, sizeof(Addr));
257 memory->writeString(data_ptr, strings[i].c_str());
258 array_ptr += sizeof(Addr);
259 data_ptr += strings[i].size() + 1;
260 }
261 // add NULL terminator
262 data_ptr = 0;
263 memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
264 }
265
266 LiveProcess::LiveProcess(const string &nm, ObjectFile *objFile,
267 int stdin_fd, int stdout_fd, int stderr_fd,
268 vector<string> &argv, vector<string> &envp)
269 : Process(nm, stdin_fd, stdout_fd, stderr_fd)
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 // load object file into target memory
281 objFile->loadSections(memory);
282
283 // load up symbols, if any... these may be used for debugging or
284 // profiling.
285 if (!debugSymbolTable) {
286 debugSymbolTable = new SymbolTable();
287 if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
288 !objFile->loadLocalSymbols(debugSymbolTable)) {
289 // didn't load any symbols
290 delete debugSymbolTable;
291 debugSymbolTable = NULL;
292 }
293 }
294
295 // Set up stack. On Alpha, stack goes below text section. This
296 // code should get moved to some architecture-specific spot.
297 stack_base = text_base - (409600+4096);
298
299 // Set up region for mmaps. Tru64 seems to start just above 0 and
300 // grow up from there.
301 mmap_start = mmap_end = 0x10000;
302
303 // Set pointer for next thread stack. Reserve 8M for main stack.
304 next_thread_stack_base = stack_base - (8 * 1024 * 1024);
305
306 // Calculate how much space we need for arg & env arrays.
307 int argv_array_size = sizeof(Addr) * (argv.size() + 1);
308 int envp_array_size = sizeof(Addr) * (envp.size() + 1);
309 int arg_data_size = 0;
310 for (int i = 0; i < argv.size(); ++i) {
311 arg_data_size += argv[i].size() + 1;
312 }
313 int env_data_size = 0;
314 for (int i = 0; i < envp.size(); ++i) {
315 env_data_size += envp[i].size() + 1;
316 }
317
318 int space_needed =
319 argv_array_size + envp_array_size + arg_data_size + env_data_size;
320 // for SimpleScalar compatibility
321 if (space_needed < 16384)
322 space_needed = 16384;
323
324 // set bottom of stack
325 stack_min = stack_base - space_needed;
326 // align it
327 stack_min &= ~7;
328 stack_size = stack_base - stack_min;
329
330 // map out initial stack contents
331 Addr argv_array_base = stack_min + sizeof(uint64_t); // room for argc
332 Addr envp_array_base = argv_array_base + argv_array_size;
333 Addr arg_data_base = envp_array_base + envp_array_size;
334 Addr env_data_base = arg_data_base + arg_data_size;
335
336 // write contents to stack
337 uint64_t argc = argv.size();
338 argc = htog(argc);
339 memory->access(Write, stack_min, &argc, sizeof(uint64_t));
340
341 copyStringArray(argv, argv_array_base, arg_data_base, memory);
342 copyStringArray(envp, envp_array_base, env_data_base, memory);
343
344 init_regs->intRegFile[ArgumentReg0] = argc;
345 init_regs->intRegFile[ArgumentReg1] = argv_array_base;
346 init_regs->intRegFile[StackPointerReg] = stack_min;
347 init_regs->intRegFile[GlobalPointerReg] = objFile->globalPointer();
348 init_regs->pc = prog_entry;
349 init_regs->npc = prog_entry + sizeof(MachInst);
350 }
351
352 void
353 LiveProcess::syscall(ExecContext *xc)
354 {
355 num_syscalls++;
356
357 int64_t callnum = xc->regs.intRegFile[ReturnValueReg];
358
359 SyscallDesc *desc = getDesc(callnum);
360 if (desc == NULL)
361 fatal("Syscall %d out of range", callnum);
362
363 desc->doSyscall(callnum, this, xc);
364 }
365
366 LiveProcess *
367 LiveProcess::create(const string &nm,
368 int stdin_fd, int stdout_fd, int stderr_fd,
369 string executable,
370 vector<string> &argv, vector<string> &envp)
371 {
372 LiveProcess *process = NULL;
373 ObjectFile *objFile = createObjectFile(executable);
374 if (objFile == NULL) {
375 fatal("Can't load object file %s", executable);
376 }
377
378 // set up syscall emulation pointer for the current ISA
379 process = createProcess(nm, objFile,
380 stdin_fd, stdout_fd, stderr_fd,
381 argv, envp);
382
383 delete objFile;
384
385 if (process == NULL)
386 fatal("Unknown error creating process object.");
387
388 return process;
389 }
390
391
392
393 BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
394
395 VectorParam<string> cmd;
396 Param<string> executable;
397 Param<string> input;
398 Param<string> output;
399 VectorParam<string> env;
400
401 END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
402
403
404 BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
405
406 INIT_PARAM(cmd, "command line (executable plus arguments)"),
407 INIT_PARAM(executable, "executable (overrides cmd[0] if set)"),
408 INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
409 INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
410 INIT_PARAM(env, "environment settings")
411
412 END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
413
414
415 CREATE_SIM_OBJECT(LiveProcess)
416 {
417 string in = input;
418 string out = output;
419
420 // initialize file descriptors to default: same as simulator
421 int stdin_fd, stdout_fd, stderr_fd;
422
423 if (in == "stdin" || in == "cin")
424 stdin_fd = STDIN_FILENO;
425 else
426 stdin_fd = Process::openInputFile(input);
427
428 if (out == "stdout" || out == "cout")
429 stdout_fd = STDOUT_FILENO;
430 else if (out == "stderr" || out == "cerr")
431 stdout_fd = STDERR_FILENO;
432 else
433 stdout_fd = Process::openOutputFile(out);
434
435 stderr_fd = (stdout_fd != STDOUT_FILENO) ? stdout_fd : STDERR_FILENO;
436
437 return LiveProcess::create(getInstanceName(),
438 stdin_fd, stdout_fd, stderr_fd,
439 (string)executable == "" ? cmd[0] : executable,
440 cmd, env);
441 }
442
443 REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)