main.py revision 5528:10a17e8a6d35
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
36import config
37import defines
38from options import OptionParser
39import traceflags
40
41__all__ = [ 'options', 'arguments', 'main' ]
42
43def print_list(items, indent=4):
44    line = ' ' * indent
45    for i,item in enumerate(items):
46        if len(line) + len(item) > 76:
47            print line
48            line = ' ' * indent
49
50        if i < len(items) - 1:
51            line += '%s, ' % item
52        else:
53            line += item
54            print line
55
56usage="%prog [m5 options] script.py [script options]"
57version="%prog 2.0"
58brief_copyright='''
59Copyright (c) 2001-2008
60The Regents of The University of Michigan
61All Rights Reserved
62'''
63
64options = OptionParser(usage=usage, version=version,
65                       description=brief_copyright)
66add_option = options.add_option
67set_group = options.set_group
68usage = options.usage
69
70# Help options
71add_option('-A', "--authors", action="store_true", default=False,
72    help="Show author information")
73add_option('-B', "--build-info", action="store_true", default=False,
74    help="Show build information")
75add_option('-C', "--copyright", action="store_true", default=False,
76    help="Show full copyright information")
77add_option('-R', "--readme", action="store_true", default=False,
78    help="Show the readme")
79add_option('-N', "--release-notes", action="store_true", default=False,
80    help="Show the release notes")
81
82# Options for configuring the base simulator
83add_option('-d', "--outdir", metavar="DIR", default=".",
84    help="Set the output directory to DIR [Default: %default]")
85add_option('-r', "--redirect-stdout", action="store_true", default=False,
86           help="Redirect stdout (& stderr, without -e) to file")
87add_option('-e', "--redirect-stderr", action="store_true", default=False,
88           help="Redirect stderr to file")
89add_option("--stdout-file", metavar="FILE", default="simout",
90           help="Filename for -r redirection [Default: %default]")
91add_option("--stderr-file", metavar="FILE", default="simerr",
92           help="Filename for -e redirection [Default: %default]")
93add_option('-i', "--interactive", action="store_true", default=False,
94    help="Invoke the interactive interpreter after running the script")
95add_option("--pdb", action="store_true", default=False,
96    help="Invoke the python debugger before running the script")
97add_option('-p', "--path", metavar="PATH[:PATH]", action='append', split=':',
98    help="Prepend PATH to the system path when invoking the script")
99add_option('-q', "--quiet", action="count", default=0,
100    help="Reduce verbosity")
101add_option('-v', "--verbose", action="count", default=0,
102    help="Increase verbosity")
103
104# Statistics options
105set_group("Statistics Options")
106add_option("--stats-file", metavar="FILE", default="m5stats.txt",
107    help="Sets the output file for statistics [Default: %default]")
108
109# Debugging options
110set_group("Debugging Options")
111add_option("--debug-break", metavar="TIME[,TIME]", action='append', split=',',
112    help="Cycle to create a breakpoint")
113add_option("--remote-gdb-port", type='int', default=7000,
114    help="Remote gdb base port")
115
116# Tracing options
117set_group("Trace Options")
118add_option("--trace-help", action='store_true',
119    help="Print help on trace flags")
120add_option("--trace-flags", metavar="FLAG[,FLAG]", action='append', split=',',
121    help="Sets the flags for tracing (-FLAG disables a flag)")
122add_option("--trace-start", metavar="TIME", type='int',
123    help="Start tracing at TIME (must be in ticks)")
124add_option("--trace-file", metavar="FILE", default="cout",
125    help="Sets the output file for tracing [Default: %default]")
126add_option("--trace-ignore", metavar="EXPR", action='append', split=':',
127    help="Ignore EXPR sim objects")
128
129# Help options
130set_group("Help Options")
131add_option("--list-sim-objects", action='store_true', default=False,
132    help="List all built-in SimObjects, their parameters and default values")
133
134def main():
135    import defines
136    import event
137    import info
138    import internal
139
140    # load the options.py config file to allow people to set their own
141    # default options
142    options_file = config.get('options.py')
143    if options_file:
144        scope = { 'options' : options }
145        execfile(options_file, scope)
146
147    arguments = options.parse_args()
148
149    if not os.path.isdir(options.outdir):
150        os.makedirs(options.outdir)
151
152    # These filenames are used only if the redirect_std* options are set
153    stdout_file = os.path.join(options.outdir, options.stdout_file)
154    stderr_file = os.path.join(options.outdir, options.stderr_file)
155
156    # Print redirection notices here before doing any redirection
157    if options.redirect_stdout and not options.redirect_stderr:
158        print "Redirecting stdout and stderr to", stdout_file
159    else:
160        if options.redirect_stdout:
161            print "Redirecting stdout to", stdout_file
162        if options.redirect_stderr:
163            print "Redirecting stderr to", stderr_file
164
165    # Now redirect stdout/stderr as desired
166    if options.redirect_stdout:
167        redir_fd = os.open(stdout_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
168        os.dup2(redir_fd, sys.stdout.fileno())
169        if not options.redirect_stderr:
170            os.dup2(redir_fd, sys.stderr.fileno())
171
172    if options.redirect_stderr:
173        redir_fd = os.open(stderr_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
174        os.dup2(redir_fd, sys.stderr.fileno())
175
176    done = False
177
178    if options.build_info:
179        done = True
180        print 'Build information:'
181        print
182        print 'compiled %s' % internal.core.cvar.compileDate;
183        print "revision %s" % internal.core.cvar.hgRev
184        print "commit date %s" % internal.core.cvar.hgDate
185        print 'build options:'
186        keys = defines.m5_build_env.keys()
187        keys.sort()
188        for key in keys:
189            val = defines.m5_build_env[key]
190            print '    %s = %s' % (key, val)
191        print
192
193    if options.copyright:
194        done = True
195        print info.LICENSE
196        print
197
198    if options.authors:
199        done = True
200        print 'Author information:'
201        print
202        print info.AUTHORS
203        print
204
205    if options.readme:
206        done = True
207        print 'Readme:'
208        print
209        print info.README
210        print
211
212    if options.release_notes:
213        done = True
214        print 'Release Notes:'
215        print
216        print info.RELEASE_NOTES
217        print
218
219    if options.trace_help:
220        done = True
221        print "Base Flags:"
222        print_list(traceflags.baseFlags, indent=4)
223        print
224        print "Compound Flags:"
225        for flag in traceflags.compoundFlags:
226            if flag == 'All':
227                continue
228            print "    %s:" % flag
229            print_list(traceflags.compoundFlagMap[flag], indent=8)
230            print
231
232    if options.list_sim_objects:
233        import SimObject
234        done = True
235        print "SimObjects:"
236        objects = SimObject.allClasses.keys()
237        objects.sort()
238        for name in objects:
239            obj = SimObject.allClasses[name]
240            print "    %s" % obj
241            params = obj._params.keys()
242            params.sort()
243            for pname in params:
244                param = obj._params[pname]
245                default = getattr(param, 'default', '')
246                print "        %s" % pname
247                if default:
248                    print "            default: %s" % default
249                print "            desc: %s" % param.desc
250                print
251            print
252
253    if done:
254        sys.exit(0)
255
256    # setting verbose and quiet at the same time doesn't make sense
257    if options.verbose > 0 and options.quiet > 0:
258        options.usage(2)
259
260    verbose = options.verbose - options.quiet
261    if options.verbose >= 0:
262        print "M5 Simulator System"
263        print brief_copyright
264        print
265        print "M5 compiled %s" % internal.core.cvar.compileDate;
266        print "M5 revision %s" % internal.core.cvar.hgRev
267        print "M5 commit date %s" % internal.core.cvar.hgDate
268
269        print "M5 started %s" % datetime.datetime.now().strftime("%b %e %Y %X")
270        print "M5 executing on %s" % socket.gethostname()
271
272        print "command line:",
273        for argv in sys.argv:
274            print argv,
275        print
276
277    # check to make sure we can find the listed script
278    if not arguments or not os.path.isfile(arguments[0]):
279        if arguments and not os.path.isfile(arguments[0]):
280            print "Script %s not found" % arguments[0]
281
282        options.usage(2)
283
284    # tell C++ about output directory
285    internal.core.setOutputDir(options.outdir)
286
287    # update the system path with elements from the -p option
288    sys.path[0:0] = options.path
289
290    import objects
291
292    # set stats options
293    internal.stats.initText(options.stats_file)
294
295    # set debugging options
296    internal.debug.setRemoteGDBPort(options.remote_gdb_port)
297    for when in options.debug_break:
298        internal.debug.schedBreakCycle(int(when))
299
300    on_flags = []
301    off_flags = []
302    for flag in options.trace_flags:
303        off = False
304        if flag.startswith('-'):
305            flag = flag[1:]
306            off = True
307        if flag not in traceflags.allFlags:
308            print >>sys.stderr, "invalid trace flag '%s'" % flag
309            sys.exit(1)
310
311        if off:
312            off_flags.append(flag)
313        else:
314            on_flags.append(flag)
315
316    for flag in on_flags:
317        internal.trace.set(flag)
318
319    for flag in off_flags:
320        internal.trace.clear(flag)
321
322    if options.trace_start:
323        def enable_trace():
324            internal.trace.cvar.enabled = True
325        event.create(enable_trace, int(options.trace_start))
326    else:
327        internal.trace.cvar.enabled = True
328
329    internal.trace.output(options.trace_file)
330
331    for ignore in options.trace_ignore:
332        internal.trace.ignore(ignore)
333
334    sys.argv = arguments
335    sys.path = [ os.path.dirname(sys.argv[0]) ] + sys.path
336
337    scope = { '__file__' : sys.argv[0],
338              '__name__' : '__m5_main__' }
339
340    # we want readline if we're doing anything interactive
341    if options.interactive or options.pdb:
342        exec "import readline" in scope
343
344    # if pdb was requested, execfile the thing under pdb, otherwise,
345    # just do the execfile normally
346    if options.pdb:
347        from pdb import Pdb
348        debugger = Pdb()
349        debugger.run('execfile("%s")' % sys.argv[0], scope)
350    else:
351        execfile(sys.argv[0], scope)
352
353    # once the script is done
354    if options.interactive:
355        interact = code.InteractiveConsole(scope)
356        interact.interact("M5 Interactive Console")
357
358if __name__ == '__main__':
359    from pprint import pprint
360
361    parse_args()
362
363    print 'opts:'
364    pprint(options, indent=4)
365    print
366
367    print 'args:'
368    pprint(arguments, indent=4)
369