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