main.py revision 5512:755fcaf7a4cf
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('-i', "--interactive", action="store_true", default=False,
86    help="Invoke the interactive interpreter after running the script")
87add_option("--pdb", action="store_true", default=False,
88    help="Invoke the python debugger before running the script")
89add_option('-p', "--path", metavar="PATH[:PATH]", action='append', split=':',
90    help="Prepend PATH to the system path when invoking the script")
91add_option('-q', "--quiet", action="count", default=0,
92    help="Reduce verbosity")
93add_option('-v', "--verbose", action="count", default=0,
94    help="Increase verbosity")
95
96# Statistics options
97set_group("Statistics Options")
98add_option("--stats-file", metavar="FILE", default="m5stats.txt",
99    help="Sets the output file for statistics [Default: %default]")
100
101# Debugging options
102set_group("Debugging Options")
103add_option("--debug-break", metavar="TIME[,TIME]", action='append', split=',',
104    help="Cycle to create a breakpoint")
105add_option("--remote-gdb-port", type='int', default=7000,
106    help="Remote gdb base port")
107
108# Tracing options
109set_group("Trace Options")
110add_option("--trace-help", action='store_true',
111    help="Print help on trace flags")
112add_option("--trace-flags", metavar="FLAG[,FLAG]", action='append', split=',',
113    help="Sets the flags for tracing (-FLAG disables a flag)")
114add_option("--trace-start", metavar="TIME", type='int',
115    help="Start tracing at TIME (must be in ticks)")
116add_option("--trace-file", metavar="FILE", default="cout",
117    help="Sets the output file for tracing [Default: %default]")
118add_option("--trace-ignore", metavar="EXPR", action='append', split=':',
119    help="Ignore EXPR sim objects")
120
121# Help options
122set_group("Help Options")
123add_option("--list-sim-objects", action='store_true', default=False,
124    help="List all built-in SimObjects, their parameters and default values")
125
126def main():
127    import defines
128    import event
129    import info
130    import internal
131
132    # load the options.py config file to allow people to set their own
133    # default options
134    options_file = config.get('options.py')
135    if options_file:
136        scope = { 'options' : options }
137        execfile(options_file, scope)
138
139    arguments = options.parse_args()
140
141    done = False
142
143    if options.build_info:
144        done = True
145        print 'Build information:'
146        print
147        print 'compiled %s' % internal.core.cvar.compileDate;
148        print 'started %s' % datetime.datetime.now().ctime()
149        print 'executing on %s' % socket.gethostname()
150        print 'build options:'
151        keys = defines.m5_build_env.keys()
152        keys.sort()
153        for key in keys:
154            val = defines.m5_build_env[key]
155            print '    %s = %s' % (key, val)
156        print
157
158    if options.copyright:
159        done = True
160        print info.LICENSE
161        print
162
163    if options.authors:
164        done = True
165        print 'Author information:'
166        print
167        print info.AUTHORS
168        print
169
170    if options.readme:
171        done = True
172        print 'Readme:'
173        print
174        print info.README
175        print
176
177    if options.release_notes:
178        done = True
179        print 'Release Notes:'
180        print
181        print info.RELEASE_NOTES
182        print
183
184    if options.trace_help:
185        done = True
186        print "Base Flags:"
187        print_list(traceflags.baseFlags, indent=4)
188        print
189        print "Compound Flags:"
190        for flag in traceflags.compoundFlags:
191            if flag == 'All':
192                continue
193            print "    %s:" % flag
194            print_list(traceflags.compoundFlagMap[flag], indent=8)
195            print
196
197    if options.list_sim_objects:
198        import SimObject
199        done = True
200        print "SimObjects:"
201        objects = SimObject.allClasses.keys()
202        objects.sort()
203        for name in objects:
204            obj = SimObject.allClasses[name]
205            print "    %s" % obj
206            params = obj._params.keys()
207            params.sort()
208            for pname in params:
209                param = obj._params[pname]
210                default = getattr(param, 'default', '')
211                print "        %s" % pname
212                if default:
213                    print "            default: %s" % default
214                print "            desc: %s" % param.desc
215                print
216            print
217
218    if done:
219        sys.exit(0)
220
221    # setting verbose and quiet at the same time doesn't make sense
222    if options.verbose > 0 and options.quiet > 0:
223        options.usage(2)
224
225    verbose = options.verbose - options.quiet
226    if options.verbose >= 0:
227        print "M5 Simulator System"
228        print brief_copyright
229        print
230        print "M5 compiled %s" % internal.core.cvar.compileDate;
231        print "M5 started %s" % datetime.datetime.now().ctime()
232        print "M5 executing on %s" % socket.gethostname()
233
234        print "M5 revision %s" % internal.core.cvar.hgRev
235        print "M5 commit date %s" % internal.core.cvar.hgDate
236
237        print "command line:",
238        for argv in sys.argv:
239            print argv,
240        print
241
242    # check to make sure we can find the listed script
243    if not arguments or not os.path.isfile(arguments[0]):
244        if arguments and not os.path.isfile(arguments[0]):
245            print "Script %s not found" % arguments[0]
246
247        options.usage(2)
248
249    # tell C++ about output directory
250    internal.core.setOutputDir(options.outdir)
251
252    # update the system path with elements from the -p option
253    sys.path[0:0] = options.path
254
255    import objects
256
257    # set stats options
258    internal.stats.initText(options.stats_file)
259
260    # set debugging options
261    internal.debug.setRemoteGDBPort(options.remote_gdb_port)
262    for when in options.debug_break:
263        internal.debug.schedBreakCycle(int(when))
264
265    on_flags = []
266    off_flags = []
267    for flag in options.trace_flags:
268        off = False
269        if flag.startswith('-'):
270            flag = flag[1:]
271            off = True
272        if flag not in traceflags.allFlags:
273            print >>sys.stderr, "invalid trace flag '%s'" % flag
274            sys.exit(1)
275
276        if off:
277            off_flags.append(flag)
278        else:
279            on_flags.append(flag)
280
281    for flag in on_flags:
282        internal.trace.set(flag)
283
284    for flag in off_flags:
285        internal.trace.clear(flag)
286
287    if options.trace_start:
288        def enable_trace():
289            internal.trace.cvar.enabled = True
290        event.create(enable_trace, int(options.trace_start))
291    else:
292        internal.trace.cvar.enabled = True
293
294    internal.trace.output(options.trace_file)
295
296    for ignore in options.trace_ignore:
297        internal.trace.ignore(ignore)
298
299    sys.argv = arguments
300    sys.path = [ os.path.dirname(sys.argv[0]) ] + sys.path
301
302    scope = { '__file__' : sys.argv[0],
303              '__name__' : '__m5_main__' }
304
305    # we want readline if we're doing anything interactive
306    if options.interactive or options.pdb:
307        exec "import readline" in scope
308
309    # if pdb was requested, execfile the thing under pdb, otherwise,
310    # just do the execfile normally
311    if options.pdb:
312        from pdb import Pdb
313        debugger = Pdb()
314        debugger.run('execfile("%s")' % sys.argv[0], scope)
315    else:
316        execfile(sys.argv[0], scope)
317
318    # once the script is done
319    if options.interactive:
320        interact = code.InteractiveConsole(scope)
321        interact.interact("M5 Interactive Console")
322
323if __name__ == '__main__':
324    from pprint import pprint
325
326    parse_args()
327
328    print 'opts:'
329    pprint(options, indent=4)
330    print
331
332    print 'args:'
333    pprint(arguments, indent=4)
334