Make include paths explicit and update makefile accordingly.
[gem5.git] / sim / main.cc
1 /*
2 * Copyright (c) 2003 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 <stdlib.h>
35 #include <signal.h>
36
37 #include <string>
38 #include <vector>
39
40 #include "sim/host.hh"
41 #include "base/misc.hh"
42
43 #include "base/copyright.hh"
44 #include "base/inifile.hh"
45 #include "sim/configfile.hh"
46 #include "base/pollevent.hh"
47 #include "base/statistics.hh"
48 #include "sim/sim_events.hh"
49 #include "sim/sim_exit.hh"
50 #include "sim/sim_object.hh"
51 #include "sim/sim_stats.hh"
52 #include "sim/sim_time.hh"
53 #include "cpu/full_cpu/smt.hh"
54
55 #include "cpu/base_cpu.hh"
56 #include "sim/async.hh"
57
58 using namespace std;
59
60 // See async.h.
61 volatile bool async_event = false;
62 volatile bool async_dump = false;
63 volatile bool async_exit = false;
64 volatile bool async_io = false;
65 volatile bool async_alarm = false;
66
67 /// Stats signal handler.
68 void
69 dumpStatsHandler(int sigtype)
70 {
71 async_event = true;
72 async_dump = true;
73 }
74
75 /// Exit signal handler.
76 void
77 exitNowHandler(int sigtype)
78 {
79 async_event = true;
80 async_exit = true;
81 }
82
83 /// Simulator executable name
84 const char *myProgName = "";
85
86 /// Show brief help message.
87 static void
88 showBriefHelp(ostream &out)
89 {
90 out << "Usage: " << myProgName
91 << " [-hn] [-Dname[=def]] [-Uname] [-I[dir]] "
92 << "[--<section>:<param>=<value>] [<config file> ...]" << endl
93 << " -h: print long help (including parameter listing)" << endl
94 << " -n: don't load default.ini" << endl
95 << " -u: don't quit on unreferenced parameters" << endl
96 << " -D,-U,-I: passed to cpp for preprocessing .ini files" << endl;
97 }
98
99 /// Show verbose help message. Includes parameter listing from
100 /// showBriefHelp(), plus an exhaustive list of ini-file parameters
101 /// and SimObjects (with their parameters).
102 static void
103 showLongHelp(ostream &out)
104 {
105 showBriefHelp(out);
106
107 out << endl
108 << endl
109 << "-----------------" << endl
110 << "Global Parameters" << endl
111 << "-----------------" << endl
112 << endl;
113
114 ParamContext::describeAllContexts(out);
115
116 out << endl
117 << endl
118 << "-----------------" << endl
119 << "Simulator Objects" << endl
120 << "-----------------" << endl
121 << endl;
122
123 SimObjectClass::describeAllClasses(out);
124 }
125
126 /// Print welcome message.
127 static void
128 sayHello(ostream &out)
129 {
130 extern const char *compileDate; // from date.cc
131
132 ccprintf(out, "M5 Simulator System\n");
133 // display copyright
134 ccprintf(out, "%s\n", briefCopyright);
135 ccprintf(out, "M5 compiled on %d\n", compileDate);
136
137 char *host = getenv("HOSTNAME");
138 if (!host)
139 host = getenv("HOST");
140
141 if (host)
142 ccprintf(out, "M5 executing on %s\n", host);
143
144 ccprintf(out, "M5 simulation started %s\n", Time::start);
145 }
146
147 ///
148 /// Echo the command line for posterity in such a way that it can be
149 /// used to rerun the same simulation (given the same .ini files).
150 ///
151 static void
152 echoCommandLine(int argc, char **argv, ostream &out)
153 {
154 out << "command line: " << argv[0];
155 for (int i = 1; i < argc; i++) {
156 string arg(argv[i]);
157
158 out << ' ';
159
160 // If the arg contains spaces, we need to quote it.
161 // The rest of this is overkill to make it look purty.
162
163 // print dashes first outside quotes
164 int non_dash_pos = arg.find_first_not_of("-");
165 out << arg.substr(0, non_dash_pos); // print dashes
166 string body = arg.substr(non_dash_pos); // the rest
167
168 // if it's an assignment, handle the lhs & rhs separately
169 int eq_pos = body.find("=");
170 if (eq_pos == string::npos) {
171 out << quote(body);
172 }
173 else {
174 string lhs(body.substr(0, eq_pos));
175 string rhs(body.substr(eq_pos + 1));
176
177 out << quote(lhs) << "=" << quote(rhs);
178 }
179 }
180 out << endl << endl;
181 }
182
183
184 ///
185 /// The simulator configuration database. This is the union of all
186 /// specified .ini files. This shouldn't need to be visible outside
187 /// this file, as it is passed as a parameter to all the param-parsing
188 /// routines.
189 ///
190 static IniFile simConfigDB;
191
192 /// Check for a default.ini file and load it if necessary.
193 static void
194 handleDefaultIni(bool &loadIt, vector<char *> &cppArgs)
195 {
196 struct stat sb;
197
198 if (loadIt) {
199 if (stat("default.ini", &sb) == 0) {
200 if (!simConfigDB.loadCPP("default.ini", cppArgs)) {
201 cout << "Error processing file default.ini" << endl;
202 exit(1);
203 }
204 }
205
206 // set this whether it actually was found or not, so we don't
207 // bother to check again next time
208 loadIt = false;
209 }
210 }
211
212
213 /// M5 entry point.
214 int
215 main(int argc, char **argv)
216 {
217 // Save off program name
218 myProgName = argv[0];
219
220 signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths
221 signal(SIGPIPE, SIG_IGN);
222 signal(SIGTRAP, SIG_IGN);
223 signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats
224 signal(SIGINT, exitNowHandler); // dump final stats and exit
225
226 sayHello(cerr);
227
228 // Initialize statistics database
229 initBaseStats();
230
231 vector<char *> cppArgs;
232
233 // Should we use default.ini if it exists? By default, yes. (Use
234 // -n to override.)
235 bool loadDefaultIni = true;
236
237 // Should we quit if there are unreferenced parameters? By
238 // default, yes... it's a good way of catching typos in
239 // section/parameter names (which otherwise go by silently). Use
240 // -u to override.
241 bool quitOnUnreferenced = true;
242
243 // Parse command-line options. The tricky part here is figuring
244 // out whether to look for & load default.ini, and if needed,
245 // doing so at the right time w.r.t. processing the other
246 // parameters.
247 //
248 // Since most of the complex options are handled through the
249 // config database, we don't mess with getopts, and just parse
250 // manually.
251 for (int i = 1; i < argc; ++i) {
252 char *arg_str = argv[i];
253
254 // if arg starts with '-', parse as option,
255 // else treat it as a configuration file name and load it
256 if (arg_str[0] == '-') {
257
258 // switch on second char
259 switch (arg_str[1]) {
260 case 'h':
261 // -h: show help
262 showLongHelp(cerr);
263 exit(1);
264
265 case 'n':
266 // -n: don't load default.ini
267 if (!loadDefaultIni) {
268 cerr << "Warning: -n option needs to precede any "
269 << "explicit configuration file name " << endl
270 << " or command-line configuration parameter."
271 << endl;
272 }
273 loadDefaultIni = false;
274 break;
275
276 case 'u':
277 // -u: don't quit on unreferenced parameters
278 quitOnUnreferenced = false;
279 break;
280
281 case 'D':
282 case 'U':
283 case 'I':
284 // cpp options: record & pass to cpp. Note that these
285 // cannot have spaces, i.e., '-Dname=val' is OK, but
286 // '-D name=val' is not. I don't consider this a
287 // problem, since even though gnu cpp accepts the
288 // latter, other cpp implementations do not (Tru64,
289 // for one).
290 cppArgs.push_back(arg_str);
291 break;
292
293 case '-':
294 // command-line configuration parameter:
295 // '--<section>:<parameter>=<value>'
296
297 // Load default.ini if necessary -- see comment in
298 // else clause below.
299 handleDefaultIni(loadDefaultIni, cppArgs);
300
301 if (!simConfigDB.add(arg_str + 2)) {
302 // parse error
303 ccprintf(cerr,
304 "Could not parse configuration argument '%s'\n"
305 "Expecting --<section>:<parameter>=<value>\n",
306 arg_str);
307 exit(0);
308 }
309 break;
310
311 default:
312 showBriefHelp(cerr);
313 ccprintf(cerr, "Fatal: invalid argument '%s'\n", arg_str);
314 exit(0);
315 }
316 }
317 else {
318 // no '-', treat as config file name
319
320 // If we haven't loaded default.ini yet, and we want to,
321 // now is the time. Can't do it sooner because we need to
322 // look for '-n', can't do it later since we want
323 // default.ini loaded first (so that any other settings
324 // override it).
325 handleDefaultIni(loadDefaultIni, cppArgs);
326
327 if (!simConfigDB.loadCPP(arg_str, cppArgs)) {
328 cprintf("Error processing file %s\n", arg_str);
329 exit(1);
330 }
331 }
332 }
333
334 // Final check for default.ini, in case no config files or
335 // command-line config parameters were given.
336 handleDefaultIni(loadDefaultIni, cppArgs);
337
338 // The configuration database is now complete; start processing it.
339
340 // Parse and check all non-config-hierarchy parameters.
341 ParamContext::parseAllContexts(simConfigDB);
342 ParamContext::checkAllContexts();
343
344 // Print header info into stats file. Can't do this sooner since
345 // the stat file name is set via a .ini param... thus it just got
346 // opened above during ParamContext::checkAllContexts().
347
348 // Print hello message to stats file if it's actually a file. If
349 // it's not (i.e. it's cout or cerr) then we already did it above.
350 if (statStreamIsFile)
351 sayHello(*statStream);
352
353 // Echo command line and all parameter settings to stats file as well.
354 echoCommandLine(argc, argv, *statStream);
355 ParamContext::showAllContexts(*statStream);
356
357 // Now process the configuration hierarchy and create the SimObjects.
358 ConfigHierarchy configHierarchy(simConfigDB);
359 configHierarchy.build();
360 configHierarchy.createSimObjects();
361
362 // Restore checkpointed state, if any.
363 configHierarchy.unserializeSimObjects();
364
365 // Done processing the configuration database.
366 // Check for unreferenced entries.
367 if (simConfigDB.printUnreferenced() && quitOnUnreferenced) {
368 cerr << "Fatal: unreferenced .ini sections/entries." << endl
369 << "If this is not an error, add 'unref_section_ok=y' or "
370 << "'unref_entries_ok=y' to the appropriate sections "
371 << "to suppress this message." << endl;
372 exit(1);
373 }
374
375 SimObject::regAllStats();
376
377 // uncomment the following to get PC-based execution-time profile
378 #ifdef DO_PROFILE
379 init_profile((char *)&_init, (char *)&_fini);
380 #endif
381
382 // Check to make sure that the stats package is properly initialized
383 Statistics::check();
384
385 // Nothing to simulate if we don't have at least one CPU somewhere.
386 if (BaseCPU::numSimulatedCPUs() == 0) {
387 cerr << "Fatal: no CPUs to simulate." << endl;
388 exit(1);
389 }
390
391 while (!mainEventQueue.empty()) {
392 assert(curTick <= mainEventQueue.nextTick() &&
393 "event scheduled in the past");
394
395 // forward current cycle to the time of the first event on the
396 // queue
397 curTick = mainEventQueue.nextTick();
398 mainEventQueue.serviceOne();
399
400 if (async_event) {
401 async_event = false;
402 if (async_dump) {
403 async_dump = false;
404 new DumpStatsEvent();
405 }
406
407 if (async_exit) {
408 async_exit = false;
409 new SimExitEvent("User requested STOP");
410 }
411
412 if (async_io || async_alarm) {
413 async_io = false;
414 async_alarm = false;
415 pollQueue.service();
416 }
417 }
418 }
419
420 // This should never happen... every conceivable way for the
421 // simulation to terminate (hit max cycles/insts, signal,
422 // simulated system halts/exits) generates an exit event, so we
423 // should never run out of events on the queue.
424 exitNow("improperly exited event loop!", 1);
425
426 return 0;
427 }