1/* 2 * Copyright (c) 2000-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/// 30/// @file sim/main.cc 31///
|
32#include <Python.h> // must be before system headers... see Python docs 33 |
34#include <sys/types.h> 35#include <sys/stat.h> 36#include <errno.h> 37#include <libgen.h> 38#include <stdlib.h> 39#include <signal.h> 40 41#include <list> 42#include <string> 43#include <vector> 44
|
43#include "base/copyright.hh"
44#include "base/embedfile.hh"
|
45#include "base/inifile.hh" 46#include "base/misc.hh" 47#include "base/output.hh" 48#include "base/pollevent.hh" 49#include "base/statistics.hh" 50#include "base/str.hh" 51#include "base/time.hh" 52#include "cpu/base.hh" 53#include "cpu/smt.hh"
|
54#include "python/pyconfig.hh"
|
54#include "sim/async.hh" 55#include "sim/builder.hh" 56#include "sim/configfile.hh" 57#include "sim/host.hh" 58#include "sim/sim_events.hh" 59#include "sim/sim_exit.hh" 60#include "sim/sim_object.hh" 61#include "sim/stat_control.hh" 62#include "sim/stats.hh" 63#include "sim/root.hh" 64 65using namespace std; 66 67// See async.h. 68volatile bool async_event = false; 69volatile bool async_dump = false; 70volatile bool async_dumpreset = false; 71volatile bool async_exit = false; 72volatile bool async_io = false; 73volatile bool async_alarm = false; 74 75/// Stats signal handler. 76void 77dumpStatsHandler(int sigtype) 78{ 79 async_event = true; 80 async_dump = true; 81} 82 83void 84dumprstStatsHandler(int sigtype) 85{ 86 async_event = true; 87 async_dumpreset = true; 88} 89 90/// Exit signal handler. 91void 92exitNowHandler(int sigtype) 93{ 94 async_event = true; 95 async_exit = true; 96} 97 98/// Abort signal handler. 99void 100abortHandler(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 111char *myProgName = ""; 112
|
114/// Show brief help message.
115void
116showBriefHelp(ostream &out)
117{
118 char *prog = basename(myProgName);
119
120 ccprintf(out, "Usage:\n");
121 ccprintf(out,
122"%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n"
123" [--<var>=<val>] <config file>\n"
124"\n"
125" -d set the output directory to <dir>\n"
126" -E set the environment variable <var> to <val> (or 'True')\n"
127" -I add the directory <dir> to python's path\n"
128" -P execute <python> directly in the configuration\n"
129" --var=val set the python variable <var> to '<val>'\n"
130" <configfile> config file name (ends in .py)\n\n",
131 prog);
132
133 ccprintf(out, "%s -X\n -X extract embedded files\n\n", prog);
134 ccprintf(out, "%s -h\n -h print short help\n\n", prog);
135}
136
137/// Print welcome message.
138void
139sayHello(ostream &out)
140{
141 extern const char *compileDate; // from date.cc
142
143 ccprintf(out, "M5 Simulator System\n");
144 // display copyright
145 ccprintf(out, "%s\n", briefCopyright);
146 ccprintf(out, "M5 compiled on %d\n", compileDate);
147
148 char *host = getenv("HOSTNAME");
149 if (!host)
150 host = getenv("HOST");
151
152 if (host)
153 ccprintf(out, "M5 executing on %s\n", host);
154
155 ccprintf(out, "M5 simulation started %s\n", Time::start);
156}
157
|
113/// 114/// Echo the command line for posterity in such a way that it can be 115/// used to rerun the same simulation (given the same .ini files). 116/// 117void 118echoCommandLine(int argc, char **argv, ostream &out) 119{ 120 out << "command line: " << argv[0]; 121 for (int i = 1; i < argc; i++) { 122 string arg(argv[i]); 123 124 out << ' '; 125 126 // If the arg contains spaces, we need to quote it. 127 // The rest of this is overkill to make it look purty. 128 129 // print dashes first outside quotes 130 int non_dash_pos = arg.find_first_not_of("-"); 131 out << arg.substr(0, non_dash_pos); // print dashes 132 string body = arg.substr(non_dash_pos); // the rest 133 134 // if it's an assignment, handle the lhs & rhs separately 135 int eq_pos = body.find("="); 136 if (eq_pos == string::npos) { 137 out << quote(body); 138 } 139 else { 140 string lhs(body.substr(0, eq_pos)); 141 string rhs(body.substr(eq_pos + 1)); 142 143 out << quote(lhs) << "=" << quote(rhs); 144 } 145 } 146 out << endl << endl; 147} 148
|
194char *
195getOptionString(int &index, int argc, char **argv)
196{
197 char *option = argv[index] + 2;
198 if (*option != '\0')
199 return option;
|
149#include "config/python_build_env.hh" |
150
|
201 // We didn't find an argument, it must be in the next variable.
202 if (++index >= argc)
203 panic("option string for option '%s' not found", argv[index - 1]);
204
205 return argv[index];
206}
207
|
151int 152main(int argc, char **argv) 153{ 154 // Save off program name 155 myProgName = argv[0]; 156 157 signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths 158 signal(SIGTRAP, SIG_IGN); 159 signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats 160 signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats 161 signal(SIGINT, exitNowHandler); // dump final stats and exit 162 signal(SIGABRT, abortHandler); 163
|
221 bool configfile_found = false;
222 PythonConfig pyconfig;
223 string outdir;
|
164 // Python embedded interpreter invocation 165 Py_SetProgramName(argv[0]); 166 const char *fileName = Py_GetProgramFullPath(); 167 Py_Initialize(); 168 PySys_SetArgv(argc, argv); |
169
|
225 if (argc < 2) {
226 showBriefHelp(cerr);
227 exit(1);
228 }
|
170 // loadSwigModules(); |
171
|
230 sayHello(cerr);
|
172 // Set Python module path to include current file to find embedded 173 // zip archive 174 PyRun_SimpleString("import sys"); 175 string pathCmd = csprintf("sys.path[1:1] = ['%s']", fileName); 176 PyRun_SimpleString(pathCmd.c_str()); |
177
|
232 // Parse command-line options.
233 // Since most of the complex options are handled through the
234 // config database, we don't mess with getopts, and just parse
235 // manually.
236 for (int i = 1; i < argc; ++i) {
237 char *arg_str = argv[i];
|
178 // Pass compile timestamp string to Python 179 extern const char *compileDate; // from date.cc 180 string setCompileDate = csprintf("compileDate = '%s'", compileDate); 181 PyRun_SimpleString(setCompileDate.c_str()); |
182
|
239 // if arg starts with '--', parse as a special python option
240 // of the format --<python var>=<string value>, if the arg
241 // starts with '-', it should be a simulator option with a
242 // format similar to getopt. In any other case, treat the
243 // option as a configuration file name and load it.
244 if (arg_str[0] == '-' && arg_str[1] == '-') {
245 string str = &arg_str[2];
246 string var, val;
|
183 // PyRun_InteractiveLoop(stdin, "stdin"); 184 // m5/__init__.py currently contains main argv parsing loop etc., 185 // and will write out config.ini file before returning. 186 PyImport_ImportModule("defines"); 187 PyImport_ImportModule("m5"); 188 Py_Finalize(); |
189
|
248 if (!split_first(str, var, val, '='))
249 panic("Could not parse configuration argument '%s'\n"
250 "Expecting --<variable>=<value>\n", arg_str);
|
190 configStream = simout.find("config.out"); |
191
|
252 pyconfig.setVariable(var, val);
253 } else if (arg_str[0] == '-') {
254 char *option;
255 string var, val;
256
257 // switch on second char
258 switch (arg_str[1]) {
259 case 'd':
260 outdir = getOptionString(i, argc, argv);
261 break;
262
263 case 'h':
264 showBriefHelp(cerr);
265 exit(1);
266
267 case 'E':
268 option = getOptionString(i, argc, argv);
269 if (!split_first(option, var, val, '='))
270 val = "True";
271
272 if (setenv(var.c_str(), val.c_str(), true) == -1)
273 panic("setenv: %s\n", strerror(errno));
274 break;
275
276 case 'I':
277 option = getOptionString(i, argc, argv);
278 pyconfig.addPath(option);
279 break;
280
281 case 'P':
282 option = getOptionString(i, argc, argv);
283 pyconfig.writeLine(option);
284 break;
285
286 case 'X': {
287 list<EmbedFile> lst;
288 EmbedMap::all(lst);
289 list<EmbedFile>::iterator i = lst.begin();
290 list<EmbedFile>::iterator end = lst.end();
291
292 while (i != end) {
293 cprintf("Embedded File: %s\n", i->name);
294 cout.write(i->data, i->length);
295 ++i;
296 }
297
298 return 0;
299 }
300
301 default:
302 showBriefHelp(cerr);
303 panic("invalid argument '%s'\n", arg_str);
304 }
305 } else {
306 string file(arg_str);
307 string base, ext;
308
309 if (!split_last(file, base, ext, '.') || ext != "py")
310 panic("Config file '%s' must end in '.py'\n", file);
311
312 pyconfig.load(file);
313 configfile_found = true;
314 }
315 }
316
317 if (outdir.empty()) {
318 char *env = getenv("OUTPUT_DIR");
319 outdir = env ? env : ".";
320 }
321
322 simout.setDirectory(outdir);
323
324 char *env = getenv("CONFIG_OUTPUT");
325 if (!env)
326 env = "config.out";
327 configStream = simout.find(env);
328
329 if (!configfile_found)
330 panic("no configuration file specified!");
331
|
192 // The configuration database is now complete; start processing it. 193 IniFile inifile;
|
334 if (!pyconfig.output(inifile))
335 panic("Error processing python code");
|
194 inifile.load("config.ini"); |
195 196 // Initialize statistics database 197 Stats::InitSimStats(); 198 199 // Now process the configuration hierarchy and create the SimObjects. 200 ConfigHierarchy configHierarchy(inifile); 201 configHierarchy.build(); 202 configHierarchy.createSimObjects(); 203 204 // Parse and check all non-config-hierarchy parameters. 205 ParamContext::parseAllContexts(inifile); 206 ParamContext::checkAllContexts(); 207
|
349 // Print hello message to stats file if it's actually a file. If
350 // it's not (i.e. it's cout or cerr) then we already did it above.
351 if (simout.isFile(*outputStream))
352 sayHello(*outputStream);
353
|
208 // Echo command line and all parameter settings to stats file as well. 209 echoCommandLine(argc, argv, *outputStream); 210 ParamContext::showAllContexts(*configStream); 211 212 // Any objects that can't connect themselves until after construction should 213 // do so now 214 SimObject::connectAll(); 215 216 // Do a second pass to finish initializing the sim objects 217 SimObject::initAll(); 218 219 // Restore checkpointed state, if any. 220 configHierarchy.unserializeSimObjects(); 221 222 // Done processing the configuration database. 223 // Check for unreferenced entries. 224 if (inifile.printUnreferenced()) 225 panic("unreferenced sections/entries in the intermediate ini file"); 226 227 SimObject::regAllStats(); 228 229 // uncomment the following to get PC-based execution-time profile 230#ifdef DO_PROFILE 231 init_profile((char *)&_init, (char *)&_fini); 232#endif 233 234 // Check to make sure that the stats package is properly initialized 235 Stats::check(); 236 237 // Reset to put the stats in a consistent state. 238 Stats::reset(); 239 240 warn("Entering event queue. Starting simulation...\n"); 241 SimStartup(); 242 while (!mainEventQueue.empty()) { 243 assert(curTick <= mainEventQueue.nextTick() && 244 "event scheduled in the past"); 245 246 // forward current cycle to the time of the first event on the 247 // queue 248 curTick = mainEventQueue.nextTick(); 249 mainEventQueue.serviceOne(); 250 251 if (async_event) { 252 async_event = false; 253 if (async_dump) { 254 async_dump = false; 255 256 using namespace Stats; 257 SetupEvent(Dump, curTick); 258 } 259 260 if (async_dumpreset) { 261 async_dumpreset = false; 262 263 using namespace Stats; 264 SetupEvent(Dump | Reset, curTick); 265 } 266 267 if (async_exit) { 268 async_exit = false; 269 new SimExitEvent("User requested STOP"); 270 } 271 272 if (async_io || async_alarm) { 273 async_io = false; 274 async_alarm = false; 275 pollQueue.service(); 276 } 277 } 278 } 279 280 // This should never happen... every conceivable way for the 281 // simulation to terminate (hit max cycles/insts, signal, 282 // simulated system halts/exits) generates an exit event, so we 283 // should never run out of events on the queue. 284 exitNow("no events on event loop! All CPUs must be idle.", 1); 285 286 return 0; 287}
|