Make code more portable.
[gem5.git] / sim / main.cc
1 /*
2 * Copyright (c) 2000-2004 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 ///
30 /// @file sim/main.cc
31 ///
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <libgen.h>
35 #include <stdlib.h>
36 #include <signal.h>
37
38 #include <list>
39 #include <string>
40 #include <vector>
41
42 #include "base/copyright.hh"
43 #include "base/embedfile.hh"
44 #include "base/inifile.hh"
45 #include "base/misc.hh"
46 #include "base/output.hh"
47 #include "base/pollevent.hh"
48 #include "base/statistics.hh"
49 #include "base/str.hh"
50 #include "base/time.hh"
51 #include "cpu/base_cpu.hh"
52 #include "cpu/full_cpu/smt.hh"
53 #include "sim/async.hh"
54 #include "sim/builder.hh"
55 #include "sim/configfile.hh"
56 #include "sim/host.hh"
57 #include "sim/sim_events.hh"
58 #include "sim/sim_exit.hh"
59 #include "sim/sim_object.hh"
60 #include "sim/stat_control.hh"
61 #include "sim/stats.hh"
62 #include "sim/universe.hh"
63 #include "sim/pyconfig/pyconfig.hh"
64
65 using namespace std;
66
67 // See async.h.
68 volatile bool async_event = false;
69 volatile bool async_dump = false;
70 volatile bool async_dumpreset = false;
71 volatile bool async_exit = false;
72 volatile bool async_io = false;
73 volatile bool async_alarm = false;
74
75 /// Stats signal handler.
76 void
77 dumpStatsHandler(int sigtype)
78 {
79 async_event = true;
80 async_dump = true;
81 }
82
83 void
84 dumprstStatsHandler(int sigtype)
85 {
86 async_event = true;
87 async_dumpreset = true;
88 }
89
90 /// Exit signal handler.
91 void
92 exitNowHandler(int sigtype)
93 {
94 async_event = true;
95 async_exit = true;
96 }
97
98 /// Abort signal handler.
99 void
100 abortHandler(int sigtype)
101 {
102 cerr << "Program aborted at cycle " << curTick << endl;
103
104 #if TRACING_ON
105 // dump trace buffer, if there is one
106 Trace::theLog.dump(cerr);
107 #endif
108 }
109
110 /// Simulator executable name
111 const char *myProgName = "";
112
113 /// Show brief help message.
114 void
115 showBriefHelp(ostream &out)
116 {
117 char *prog = basename(myProgName);
118
119 ccprintf(out, "Usage:\n");
120 ccprintf(out,
121 "%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n"
122 " [--<var>=<val>] <config file>\n"
123 "\n"
124 " -d set the output directory to <dir>\n"
125 " -E set the environment variable <var> to <val> (or 'True')\n"
126 " -I add the directory <dir> to python's path\n"
127 " -P execute <python> directly in the configuration\n"
128 " --var=val set the python variable <var> to '<val>'\n"
129 " <configfile> config file name (.py or .mpy)\n",
130 prog);
131
132 ccprintf(out, "%s -X\n -X extract embedded files\n", prog);
133 ccprintf(out, "%s -h\n -h print long help\n", prog);
134 }
135
136 /// Show verbose help message. Includes parameter listing from
137 /// showBriefHelp(), plus an exhaustive list of ini-file parameters
138 /// and SimObjects (with their parameters).
139 void
140 showLongHelp(ostream &out)
141 {
142 showBriefHelp(out);
143
144 out << endl
145 << endl
146 << "-----------------" << endl
147 << "Global Parameters" << endl
148 << "-----------------" << endl
149 << endl;
150
151 ParamContext::describeAllContexts(out);
152
153 out << endl
154 << endl
155 << "-----------------" << endl
156 << "Simulator Objects" << endl
157 << "-----------------" << endl
158 << endl;
159
160 SimObjectClass::describeAllClasses(out);
161 }
162
163 /// Print welcome message.
164 void
165 sayHello(ostream &out)
166 {
167 extern const char *compileDate; // from date.cc
168
169 ccprintf(out, "M5 Simulator System\n");
170 // display copyright
171 ccprintf(out, "%s\n", briefCopyright);
172 ccprintf(out, "M5 compiled on %d\n", compileDate);
173
174 char *host = getenv("HOSTNAME");
175 if (!host)
176 host = getenv("HOST");
177
178 if (host)
179 ccprintf(out, "M5 executing on %s\n", host);
180
181 ccprintf(out, "M5 simulation started %s\n", Time::start);
182 }
183
184 ///
185 /// Echo the command line for posterity in such a way that it can be
186 /// used to rerun the same simulation (given the same .ini files).
187 ///
188 void
189 echoCommandLine(int argc, char **argv, ostream &out)
190 {
191 out << "command line: " << argv[0];
192 for (int i = 1; i < argc; i++) {
193 string arg(argv[i]);
194
195 out << ' ';
196
197 // If the arg contains spaces, we need to quote it.
198 // The rest of this is overkill to make it look purty.
199
200 // print dashes first outside quotes
201 int non_dash_pos = arg.find_first_not_of("-");
202 out << arg.substr(0, non_dash_pos); // print dashes
203 string body = arg.substr(non_dash_pos); // the rest
204
205 // if it's an assignment, handle the lhs & rhs separately
206 int eq_pos = body.find("=");
207 if (eq_pos == string::npos) {
208 out << quote(body);
209 }
210 else {
211 string lhs(body.substr(0, eq_pos));
212 string rhs(body.substr(eq_pos + 1));
213
214 out << quote(lhs) << "=" << quote(rhs);
215 }
216 }
217 out << endl << endl;
218 }
219
220 char *
221 getOptionString(int &index, int argc, char **argv)
222 {
223 char *option = argv[index] + 2;
224 if (*option != '\0')
225 return option;
226
227 // We didn't find an argument, it must be in the next variable.
228 if (++index >= argc)
229 panic("option string for option '%s' not found", argv[index - 1]);
230
231 return argv[index];
232 }
233
234 int
235 main(int argc, char **argv)
236 {
237 // Save off program name
238 myProgName = argv[0];
239
240 signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths
241 signal(SIGTRAP, SIG_IGN);
242 signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats
243 signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats
244 signal(SIGINT, exitNowHandler); // dump final stats and exit
245 signal(SIGABRT, abortHandler);
246
247 sayHello(cerr);
248
249 bool configfile_found = false;
250 PythonConfig pyconfig;
251 string outdir;
252
253 // Parse command-line options.
254 // Since most of the complex options are handled through the
255 // config database, we don't mess with getopts, and just parse
256 // manually.
257 for (int i = 1; i < argc; ++i) {
258 char *arg_str = argv[i];
259
260 // if arg starts with '--', parse as a special python option
261 // of the format --<python var>=<string value>, if the arg
262 // starts with '-', it should be a simulator option with a
263 // format similar to getopt. In any other case, treat the
264 // option as a configuration file name and load it.
265 if (arg_str[0] == '-' && arg_str[1] == '-') {
266 string str = &arg_str[2];
267 string var, val;
268
269 if (!split_first(str, var, val, '='))
270 panic("Could not parse configuration argument '%s'\n"
271 "Expecting --<variable>=<value>\n", arg_str);
272
273 pyconfig.setVariable(var, val);
274 } else if (arg_str[0] == '-') {
275 char *option;
276 string var, val;
277
278 // switch on second char
279 switch (arg_str[1]) {
280 case 'd':
281 outdir = getOptionString(i, argc, argv);
282 break;
283
284 case 'h':
285 showLongHelp(cerr);
286 exit(1);
287
288 case 'E':
289 option = getOptionString(i, argc, argv);
290 if (!split_first(option, var, val, '='))
291 val = "True";
292
293 if (setenv(var.c_str(), val.c_str(), true) == -1)
294 panic("setenv: %s\n", strerror(errno));
295 break;
296
297 case 'I':
298 option = getOptionString(i, argc, argv);
299 pyconfig.addPath(option);
300 break;
301
302 case 'P':
303 option = getOptionString(i, argc, argv);
304 pyconfig.writeLine(option);
305 break;
306
307 case 'X': {
308 list<EmbedFile> lst;
309 EmbedMap::all(lst);
310 list<EmbedFile>::iterator i = lst.begin();
311 list<EmbedFile>::iterator end = lst.end();
312
313 while (i != end) {
314 cprintf("Embedded File: %s\n", i->name);
315 cout.write(i->data, i->length);
316 ++i;
317 }
318
319 return 0;
320 }
321
322 default:
323 showBriefHelp(cerr);
324 panic("invalid argument '%s'\n", arg_str);
325 }
326 } else {
327 string file(arg_str);
328 string base, ext;
329
330 if (!split_last(file, base, ext, '.') ||
331 ext != "py" && ext != "mpy")
332 panic("Config file '%s' must end in '.py' or '.mpy'\n", file);
333
334 pyconfig.load(file);
335 configfile_found = true;
336 }
337 }
338
339 if (outdir.empty()) {
340 char *env = getenv("OUTPUT_DIR");
341 outdir = env ? env : ".";
342 }
343
344 simout.setDirectory(outdir);
345
346 char *env = getenv("CONFIG_OUTPUT");
347 if (!env)
348 env = "config.out";
349 configStream = simout.find(env);
350
351 if (!configfile_found)
352 panic("no configuration file specified!");
353
354 // The configuration database is now complete; start processing it.
355 IniFile inifile;
356 if (!pyconfig.output(inifile))
357 panic("Error processing python code");
358
359 // Initialize statistics database
360 Stats::InitSimStats();
361
362 // Now process the configuration hierarchy and create the SimObjects.
363 ConfigHierarchy configHierarchy(inifile);
364 configHierarchy.build();
365 configHierarchy.createSimObjects();
366
367 // Parse and check all non-config-hierarchy parameters.
368 ParamContext::parseAllContexts(inifile);
369 ParamContext::checkAllContexts();
370
371 // Print hello message to stats file if it's actually a file. If
372 // it's not (i.e. it's cout or cerr) then we already did it above.
373 if (simout.isFile(*outputStream))
374 sayHello(*outputStream);
375
376 // Echo command line and all parameter settings to stats file as well.
377 echoCommandLine(argc, argv, *outputStream);
378 ParamContext::showAllContexts(*configStream);
379
380 // Do a second pass to finish initializing the sim objects
381 SimObject::initAll();
382
383 // Restore checkpointed state, if any.
384 configHierarchy.unserializeSimObjects();
385
386 // Done processing the configuration database.
387 // Check for unreferenced entries.
388 if (inifile.printUnreferenced())
389 panic("unreferenced sections/entries in the intermediate ini file");
390
391 SimObject::regAllStats();
392
393 // uncomment the following to get PC-based execution-time profile
394 #ifdef DO_PROFILE
395 init_profile((char *)&_init, (char *)&_fini);
396 #endif
397
398 // Check to make sure that the stats package is properly initialized
399 Stats::check();
400
401 // Reset to put the stats in a consistent state.
402 Stats::reset();
403
404 // Nothing to simulate if we don't have at least one CPU somewhere.
405 if (BaseCPU::numSimulatedCPUs() == 0) {
406 cerr << "Fatal: no CPUs to simulate." << endl;
407 exit(1);
408 }
409
410 warn("Entering event queue. Starting simulation...\n");
411 SimStartup();
412 while (!mainEventQueue.empty()) {
413 assert(curTick <= mainEventQueue.nextTick() &&
414 "event scheduled in the past");
415
416 // forward current cycle to the time of the first event on the
417 // queue
418 curTick = mainEventQueue.nextTick();
419 mainEventQueue.serviceOne();
420
421 if (async_event) {
422 async_event = false;
423 if (async_dump) {
424 async_dump = false;
425
426 using namespace Stats;
427 SetupEvent(Dump, curTick);
428 }
429
430 if (async_dumpreset) {
431 async_dumpreset = false;
432
433 using namespace Stats;
434 SetupEvent(Dump | Reset, curTick);
435 }
436
437 if (async_exit) {
438 async_exit = false;
439 new SimExitEvent("User requested STOP");
440 }
441
442 if (async_io || async_alarm) {
443 async_io = false;
444 async_alarm = false;
445 pollQueue.service();
446 }
447 }
448 }
449
450 // This should never happen... every conceivable way for the
451 // simulation to terminate (hit max cycles/insts, signal,
452 // simulated system halts/exits) generates an exit event, so we
453 // should never run out of events on the queue.
454 exitNow("no events on event loop! All CPUs must be idle.", 1);
455
456 return 0;
457 }