main.py revision 8219:0e2333b86562
1# Copyright (c) 2005 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Nathan Binkert
28
29import code
30import datetime
31import os
32import socket
33import sys
34
35from util import attrdict, fatal
36import config
37from options import OptionParser
38
39__all__ = [ 'options', 'arguments', 'main' ]
40
41usage="%prog [m5 options] script.py [script options]"
42version="%prog 2.0"
43brief_copyright='''
44Copyright (c) 2001-2008
45The Regents of The University of Michigan
46All Rights Reserved
47'''
48
49options = OptionParser(usage=usage, version=version,
50                       description=brief_copyright)
51add_option = options.add_option
52set_group = options.set_group
53usage = options.usage
54
55# Help options
56add_option('-A', "--authors", action="store_true", default=False,
57    help="Show author information")
58add_option('-B', "--build-info", action="store_true", default=False,
59    help="Show build information")
60add_option('-C', "--copyright", action="store_true", default=False,
61    help="Show full copyright information")
62add_option('-R', "--readme", action="store_true", default=False,
63    help="Show the readme")
64
65# Options for configuring the base simulator
66add_option('-d', "--outdir", metavar="DIR", default="m5out",
67    help="Set the output directory to DIR [Default: %default]")
68add_option('-r', "--redirect-stdout", action="store_true", default=False,
69           help="Redirect stdout (& stderr, without -e) to file")
70add_option('-e', "--redirect-stderr", action="store_true", default=False,
71           help="Redirect stderr to file")
72add_option("--stdout-file", metavar="FILE", default="simout",
73           help="Filename for -r redirection [Default: %default]")
74add_option("--stderr-file", metavar="FILE", default="simerr",
75           help="Filename for -e redirection [Default: %default]")
76add_option('-i', "--interactive", action="store_true", default=False,
77    help="Invoke the interactive interpreter after running the script")
78add_option("--pdb", action="store_true", default=False,
79    help="Invoke the python debugger before running the script")
80add_option('-p', "--path", metavar="PATH[:PATH]", action='append', split=':',
81    help="Prepend PATH to the system path when invoking the script")
82add_option('-q', "--quiet", action="count", default=0,
83    help="Reduce verbosity")
84add_option('-v', "--verbose", action="count", default=0,
85    help="Increase verbosity")
86
87# Statistics options
88set_group("Statistics Options")
89add_option("--stats-file", metavar="FILE", default="stats.txt",
90    help="Sets the output file for statistics [Default: %default]")
91
92# Configuration Options
93set_group("Configuration Options")
94add_option("--dump-config", metavar="FILE", default="config.ini",
95    help="Dump configuration output file [Default: %default]")
96
97# Debugging options
98set_group("Debugging Options")
99add_option("--debug-break", metavar="TIME[,TIME]", action='append', split=',',
100    help="Cycle to create a breakpoint")
101add_option("--remote-gdb-port", type='int', default=7000,
102    help="Remote gdb base port (set to 0 to disable listening)")
103
104# Tracing options
105set_group("Trace Options")
106add_option("--trace-help", action='store_true',
107    help="Print help on trace flags")
108add_option("--trace-flags", metavar="FLAG[,FLAG]", action='append', split=',',
109    help="Sets the flags for tracing (-FLAG disables a flag)")
110add_option("--trace-start", metavar="TIME", type='int',
111    help="Start tracing at TIME (must be in ticks)")
112add_option("--trace-file", metavar="FILE", default="cout",
113    help="Sets the output file for tracing [Default: %default]")
114add_option("--trace-ignore", metavar="EXPR", action='append', split=':',
115    help="Ignore EXPR sim objects")
116
117# Help options
118set_group("Help Options")
119add_option("--list-sim-objects", action='store_true', default=False,
120    help="List all built-in SimObjects, their parameters and default values")
121
122# load the options.py config file to allow people to set their own
123# default options
124options_file = config.get('options.py')
125if options_file:
126    scope = { 'options' : options }
127    execfile(options_file, scope)
128
129arguments = options.parse_args()
130
131def interact(scope):
132    banner = "M5 Interactive Console"
133    sys.argv = []
134    try:
135        from IPython.Shell import IPShellEmbed
136        ipshell = IPShellEmbed(banner=banner,user_ns=scope)
137        ipshell()
138    except ImportError:
139        code.InteractiveConsole(scope).interact(banner)
140
141def main():
142    import core
143    import debug
144    import defines
145    import event
146    import info
147    import stats
148    import trace
149
150    def check_tracing():
151        if defines.TRACING_ON:
152            return
153
154        fatal("Tracing is not enabled.  Compile with TRACING_ON")
155
156    if not os.path.isdir(options.outdir):
157        os.makedirs(options.outdir)
158
159    # These filenames are used only if the redirect_std* options are set
160    stdout_file = os.path.join(options.outdir, options.stdout_file)
161    stderr_file = os.path.join(options.outdir, options.stderr_file)
162
163    # Print redirection notices here before doing any redirection
164    if options.redirect_stdout and not options.redirect_stderr:
165        print "Redirecting stdout and stderr to", stdout_file
166    else:
167        if options.redirect_stdout:
168            print "Redirecting stdout to", stdout_file
169        if options.redirect_stderr:
170            print "Redirecting stderr to", stderr_file
171
172    # Now redirect stdout/stderr as desired
173    if options.redirect_stdout:
174        redir_fd = os.open(stdout_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
175        os.dup2(redir_fd, sys.stdout.fileno())
176        if not options.redirect_stderr:
177            os.dup2(redir_fd, sys.stderr.fileno())
178
179    if options.redirect_stderr:
180        redir_fd = os.open(stderr_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
181        os.dup2(redir_fd, sys.stderr.fileno())
182
183    done = False
184
185    if options.build_info:
186        done = True
187        print 'Build information:'
188        print
189        print 'compiled %s' % defines.compileDate;
190        print 'build options:'
191        keys = defines.buildEnv.keys()
192        keys.sort()
193        for key in keys:
194            val = defines.buildEnv[key]
195            print '    %s = %s' % (key, val)
196        print
197
198    if options.copyright:
199        done = True
200        print info.LICENSE
201        print
202
203    if options.authors:
204        done = True
205        print 'Author information:'
206        print
207        print info.AUTHORS
208        print
209
210    if options.readme:
211        done = True
212        print 'Readme:'
213        print
214        print info.README
215        print
216
217    if options.trace_help:
218        done = True
219        check_tracing()
220        trace.help()
221
222    if options.list_sim_objects:
223        import SimObject
224        done = True
225        print "SimObjects:"
226        objects = SimObject.allClasses.keys()
227        objects.sort()
228        for name in objects:
229            obj = SimObject.allClasses[name]
230            print "    %s" % obj
231            params = obj._params.keys()
232            params.sort()
233            for pname in params:
234                param = obj._params[pname]
235                default = getattr(param, 'default', '')
236                print "        %s" % pname
237                if default:
238                    print "            default: %s" % default
239                print "            desc: %s" % param.desc
240                print
241            print
242
243    if done:
244        sys.exit(0)
245
246    # setting verbose and quiet at the same time doesn't make sense
247    if options.verbose > 0 and options.quiet > 0:
248        options.usage(2)
249
250    verbose = options.verbose - options.quiet
251    if options.verbose >= 0:
252        print "M5 Simulator System"
253        print brief_copyright
254        print
255
256        print "M5 compiled %s" % defines.compileDate;
257
258        print "M5 started %s" % datetime.datetime.now().strftime("%b %e %Y %X")
259        print "M5 executing on %s" % socket.gethostname()
260
261        print "command line:",
262        for argv in sys.argv:
263            print argv,
264        print
265
266    # check to make sure we can find the listed script
267    if not arguments or not os.path.isfile(arguments[0]):
268        if arguments and not os.path.isfile(arguments[0]):
269            print "Script %s not found" % arguments[0]
270
271        options.usage(2)
272
273    # tell C++ about output directory
274    core.setOutputDir(options.outdir)
275
276    # update the system path with elements from the -p option
277    sys.path[0:0] = options.path
278
279    # set stats options
280    stats.initText(options.stats_file)
281
282    # set debugging options
283    debug.setRemoteGDBPort(options.remote_gdb_port)
284    for when in options.debug_break:
285        debug.schedBreakCycle(int(when))
286
287    if options.trace_flags:
288        check_tracing()
289
290        on_flags = []
291        off_flags = []
292        for flag in options.trace_flags:
293            off = False
294            if flag.startswith('-'):
295                flag = flag[1:]
296                off = True
297            if flag not in trace.flags.all and flag != "All":
298                print >>sys.stderr, "invalid trace flag '%s'" % flag
299                sys.exit(1)
300
301            if off:
302                off_flags.append(flag)
303            else:
304                on_flags.append(flag)
305
306        for flag in on_flags:
307            trace.set(flag)
308
309        for flag in off_flags:
310            trace.clear(flag)
311
312    if options.trace_start:
313        check_tracing()
314        e = event.create(trace.enable, event.Event.Trace_Enable_Pri)
315        event.mainq.schedule(e, options.trace_start)
316    else:
317        trace.enable()
318
319    trace.output(options.trace_file)
320
321    for ignore in options.trace_ignore:
322        check_tracing()
323        trace.ignore(ignore)
324
325    sys.argv = arguments
326    sys.path = [ os.path.dirname(sys.argv[0]) ] + sys.path
327
328    filename = sys.argv[0]
329    filedata = file(filename, 'r').read()
330    filecode = compile(filedata, filename, 'exec')
331    scope = { '__file__' : filename,
332              '__name__' : '__m5_main__' }
333
334    # we want readline if we're doing anything interactive
335    if options.interactive or options.pdb:
336        exec "import readline" in scope
337
338    # if pdb was requested, execfile the thing under pdb, otherwise,
339    # just do the execfile normally
340    if options.pdb:
341        import pdb
342        import traceback
343
344        pdb = pdb.Pdb()
345        try:
346            pdb.run(filecode, scope)
347        except SystemExit:
348            print "The program exited via sys.exit(). Exit status: ",
349            print sys.exc_info()[1]
350        except:
351            traceback.print_exc()
352            print "Uncaught exception. Entering post mortem debugging"
353            t = sys.exc_info()[2]
354            while t.tb_next is not None:
355                t = t.tb_next
356                pdb.interaction(t.tb_frame,t)
357    else:
358        exec filecode in scope
359
360    # once the script is done
361    if options.interactive:
362        interact(scope)
363
364if __name__ == '__main__':
365    from pprint import pprint
366
367    print 'opts:'
368    pprint(options, indent=4)
369    print
370
371    print 'args:'
372    pprint(arguments, indent=4)
373