2 * Copyright (c) 2000-2005 The Regents of The University of Michigan
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.
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.
28 * Authors: Steve Raasch
36 #include <Python.h> // must be before system headers... see Python docs
38 #include <sys/types.h>
50 #include "base/callback.hh"
51 #include "base/inifile.hh"
52 #include "base/misc.hh"
53 #include "base/output.hh"
54 #include "base/pollevent.hh"
55 #include "base/statistics.hh"
56 #include "base/str.hh"
57 #include "base/time.hh"
58 #include "cpu/base.hh"
60 #include "mem/mem_object.hh"
61 #include "mem/port.hh"
62 #include "sim/async.hh"
63 #include "sim/builder.hh"
64 #include "sim/host.hh"
65 #include "sim/serialize.hh"
66 #include "sim/sim_events.hh"
67 #include "sim/sim_exit.hh"
68 #include "sim/sim_object.hh"
69 #include "sim/stat_control.hh"
70 #include "sim/stats.hh"
71 #include "sim/root.hh"
76 volatile bool async_event
= false;
77 volatile bool async_dump
= false;
78 volatile bool async_dumpreset
= false;
79 volatile bool async_exit
= false;
80 volatile bool async_io
= false;
81 volatile bool async_alarm
= false;
83 /// Stats signal handler.
85 dumpStatsHandler(int sigtype
)
92 dumprstStatsHandler(int sigtype
)
95 async_dumpreset
= true;
98 /// Exit signal handler.
100 exitNowHandler(int sigtype
)
106 /// Abort signal handler.
108 abortHandler(int sigtype
)
110 cerr
<< "Program aborted at cycle " << curTick
<< endl
;
113 // dump trace buffer, if there is one
114 Trace::theLog
.dump(cerr
);
118 /// Simulator executable name
119 char *myProgName
= "";
121 /// Show brief help message.
123 showBriefHelp(ostream
&out
)
125 char *prog
= basename(myProgName
);
127 ccprintf(out
, "Usage:\n");
129 "%s [-p <path>] [-i ] [-h] <config file>\n"
131 " -p, --path <path> prepends <path> to PYTHONPATH instead of using\n"
132 " built-in zip archive. Useful when developing/debugging\n"
133 " changes to built-in Python libraries, as the new Python\n"
134 " can be tested without building a new m5 binary.\n\n"
135 " -i, --interactive forces entry into interactive mode after the supplied\n"
136 " script is executed (just like the -i option to the\n"
137 " Python interpreter).\n\n"
138 " -h Prints this help\n\n"
139 " <configfile> config file name which ends in .py. (Normally you can\n"
140 " run <configfile> --help to get help on that config files\n"
146 const char *briefCopyright
=
147 "Copyright (c) 2001-2006\n"
148 "The Regents of The University of Michigan\n"
149 "All Rights Reserved\n";
151 /// Print welcome message.
153 sayHello(ostream
&out
)
155 extern const char *compileDate
; // from date.cc
157 ccprintf(out
, "M5 Simulator System\n");
159 ccprintf(out
, "%s\n", briefCopyright
);
160 ccprintf(out
, "M5 compiled %d\n", compileDate
);
161 ccprintf(out
, "M5 started %s\n", Time::start
);
163 char *host
= getenv("HOSTNAME");
165 host
= getenv("HOST");
168 ccprintf(out
, "M5 executing on %s\n", host
);
172 extern "C" { void init_cc_main(); }
175 main(int argc
, char **argv
)
177 // Saze off program name
178 myProgName
= argv
[0];
182 signal(SIGFPE
, SIG_IGN
); // may occur on misspeculated paths
183 signal(SIGTRAP
, SIG_IGN
);
184 signal(SIGUSR1
, dumpStatsHandler
); // dump intermediate stats
185 signal(SIGUSR2
, dumprstStatsHandler
); // dump and reset stats
186 signal(SIGINT
, exitNowHandler
); // dump final stats and exit
187 signal(SIGABRT
, abortHandler
);
189 Py_SetProgramName(argv
[0]);
191 // default path to m5 python code is the currently executing
192 // file... Python ZipImporter will find embedded zip archive
193 char *pythonpath
= argv
[0];
195 bool interactive
= false;
196 bool show_help
= false;
197 bool getopt_done
= false;
200 static struct option long_options
[] = {
201 {"python", 1, 0, 'p'},
202 {"interactive", 0, 0, 'i'},
208 switch (getopt_long(argc
, argv
, "+p:ih", long_options
, &opt_index
)) {
209 // -p <path> prepends <path> to PYTHONPATH instead of
210 // using built-in zip archive. Useful when
211 // developing/debugging changes to built-in Python
212 // libraries, as the new Python can be tested without
213 // building a new m5 binary.
218 // -i forces entry into interactive mode after the
219 // supplied script is executed (just like the -i option to
220 // the Python interpreter).
233 fatal("Unrecognized option %c\n", optopt
);
235 } while (!getopt_done
);
242 // Fix up argc & argv to hide arguments we just processed.
243 // getopt() sets optind to the index of the first non-processed
248 // Set up PYTHONPATH to make sure the m5 module is found
249 string
newpath(pythonpath
);
251 char *oldpath
= getenv("PYTHONPATH");
252 if (oldpath
!= NULL
) {
257 if (setenv("PYTHONPATH", newpath
.c_str(), true) == -1)
258 fatal("setenv: %s\n", strerror(errno
));
260 // initialize embedded Python interpreter
262 PySys_SetArgv(argc
, argv
);
264 // initialize SWIG 'cc_main' module
268 // extra arg(s): first is script file, remaining ones are args
270 char *filename
= argv
[0];
271 FILE *fp
= fopen(filename
, "r");
273 fatal("cannot open file '%s'\n", filename
);
276 PyRun_AnyFile(fp
, filename
);
278 // no script file argument... force interactive prompt
283 // The following code to import readline was copied from Python
284 // 2.4.3's Modules/main.c.
285 // Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006
286 // Python Software Foundation; All Rights Reserved
287 // We should only enable this if we're actually using an
288 // interactive prompt.
290 v
= PyImport_ImportModule("readline");
296 PyRun_InteractiveLoop(stdin
, "stdin");
299 // clean up Python intepreter.
305 setOutputDir(const string
&dir
)
307 simout
.setDirectory(dir
);
314 createSimObject(const string
&name
)
316 return SimObjectClass::createObject(inifile
, name
);
321 * Pointer to the Python function that maps names to SimObjects.
323 PyObject
*resolveFunc
= NULL
;
326 * Convert a pointer to the Python object that SWIG wraps around a C++
327 * SimObject pointer back to the actual C++ pointer. See main.i.
329 extern "C" SimObject
*convertSwigSimObjectPtr(PyObject
*);
333 resolveSimObject(const string
&name
)
335 PyObject
*pyPtr
= PyEval_CallFunction(resolveFunc
, "(s)", name
.c_str());
338 panic("resolveSimObject: failure on call to Python for %s", name
);
341 SimObject
*simObj
= convertSwigSimObjectPtr(pyPtr
);
343 panic("resolveSimObject: failure on pointer conversion for %s", name
);
350 * Load config.ini into C++ database. Exported to Python via SWIG;
351 * invoked from m5.instantiate().
354 loadIniFile(PyObject
*_resolveFunc
)
356 resolveFunc
= _resolveFunc
;
357 configStream
= simout
.find("config.out");
359 // The configuration database is now complete; start processing it.
360 inifile
.load("config.ini");
362 // Initialize statistics database
363 Stats::InitSimStats();
368 * Look up a MemObject port. Helper function for connectPorts().
371 lookupPort(SimObject
*so
, const std::string
&name
, int i
)
373 MemObject
*mo
= dynamic_cast<MemObject
*>(so
);
375 warn("error casting SimObject %s to MemObject", so
->name());
379 Port
*p
= mo
->getPort(name
, i
);
381 warn("error looking up port %s on object %s", name
, so
->name());
387 * Connect the described MemObject ports. Called from Python via SWIG.
390 connectPorts(SimObject
*o1
, const std::string
&name1
, int i1
,
391 SimObject
*o2
, const std::string
&name2
, int i2
)
393 Port
*p1
= lookupPort(o1
, name1
, i1
);
394 Port
*p2
= lookupPort(o2
, name2
, i2
);
396 if (p1
== NULL
|| p2
== NULL
) {
397 warn("connectPorts: port lookup error");
408 * Do final initialization steps after object construction but before
409 * start of simulation.
414 // Parse and check all non-config-hierarchy parameters.
415 ParamContext::parseAllContexts(inifile
);
416 ParamContext::checkAllContexts();
418 // Echo all parameter settings to stats file as well.
419 ParamContext::showAllContexts(*configStream
);
421 // Do a second pass to finish initializing the sim objects
422 SimObject::initAll();
424 // Restore checkpointed state, if any.
426 configHierarchy
.unserializeSimObjects();
429 SimObject::regAllStats();
431 // Check to make sure that the stats package is properly initialized
434 // Reset to put the stats in a consistent state.
441 /** Simulate for num_cycles additional cycles. If num_cycles is -1
442 * (the default), do not limit simulation; some other event must
443 * terminate the loop. Exported to Python via SWIG.
444 * @return The SimLoopExitEvent that caused the loop to exit.
447 simulate(Tick num_cycles
= -1)
449 warn("Entering event queue @ %d. Starting simulation...\n", curTick
);
451 // Fix up num_cycles. Special default value -1 means simulate
452 // "forever"... schedule event at MaxTick just to be safe.
453 // Otherwise it's a delta for additional cycles to simulate past
454 // curTick, and thus must be non-negative.
455 if (num_cycles
== -1)
456 num_cycles
= MaxTick
;
457 else if (num_cycles
< 0)
458 fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles
);
460 num_cycles
= curTick
+ num_cycles
;
462 Event
*limit_event
= new SimLoopExitEvent(num_cycles
,
463 "simulate() limit reached");
466 // there should always be at least one event (the SimLoopExitEvent
467 // we just scheduled) in the queue
468 assert(!mainEventQueue
.empty());
469 assert(curTick
<= mainEventQueue
.nextTick() &&
470 "event scheduled in the past");
472 // forward current cycle to the time of the first event on the
474 curTick
= mainEventQueue
.nextTick();
475 Event
*exit_event
= mainEventQueue
.serviceOne();
476 if (exit_event
!= NULL
) {
477 // hit some kind of exit event; return to Python
478 // event must be subclass of SimLoopExitEvent...
479 SimLoopExitEvent
*se_event
= dynamic_cast<SimLoopExitEvent
*>(exit_event
);
480 if (se_event
== NULL
)
481 panic("Bogus exit event class!");
483 // if we didn't hit limit_event, delete it
484 if (se_event
!= limit_event
) {
485 assert(limit_event
->scheduled());
486 limit_event
->deschedule();
498 using namespace Stats
;
499 SetupEvent(Dump
, curTick
);
502 if (async_dumpreset
) {
503 async_dumpreset
= false;
505 using namespace Stats
;
506 SetupEvent(Dump
| Reset
, curTick
);
511 exitSimLoop("user interrupt received");
514 if (async_io
|| async_alarm
) {
522 // not reached... only exit is return on SimLoopExitEvent
528 return new CountedDrainEvent();
532 cleanupCountedDrain(Event
*counted_drain
)
534 CountedDrainEvent
*event
=
535 dynamic_cast<CountedDrainEvent
*>(counted_drain
);
537 fatal("Called cleanupCountedDrain() on an event that was not "
538 "a CountedDrainEvent.");
540 assert(event
->getCount() == 0);
547 Serializable::serializeAll();
553 Serializable::unserializeAll();
557 * Queue of C++ callbacks to invoke on simulator exit.
559 CallbackQueue exitCallbacks
;
562 * Register an exit callback.
565 registerExitCallback(Callback
*callback
)
567 exitCallbacks
.add(callback
);
571 convertToBaseCPUPtr(SimObject
*obj
)
573 BaseCPU
*ptr
= dynamic_cast<BaseCPU
*>(obj
);
576 warn("Casting to BaseCPU pointer failed");
581 * Do C++ simulator exit processing. Exported to SWIG to be invoked
582 * when simulator terminates via Python's atexit mechanism.
587 exitCallbacks
.process();
588 exitCallbacks
.clear();
592 ParamContext::cleanupAllContexts();
594 // print simulation stats