main.py revision 2922
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, optparse, os, socket, sys
30from datetime import datetime
31from attrdict import attrdict
32
33try:
34    import info
35except ImportError:
36    info = None
37
38__all__ = [ 'options', 'arguments', 'main' ]
39
40usage="%prog [m5 options] script.py [script options]"
41version="%prog 2.0"
42brief_copyright='''
43Copyright (c) 2001-2006
44The Regents of The University of Michigan
45All Rights Reserved
46'''
47
48# there's only one option parsing done, so make it global and add some
49# helper functions to make it work well.
50parser = optparse.OptionParser(usage=usage, version=version,
51                               description=brief_copyright,
52                               formatter=optparse.TitledHelpFormatter())
53parser.disable_interspersed_args()
54
55# current option group
56group = None
57
58def set_group(*args, **kwargs):
59    '''set the current option group'''
60    global group
61    if not args and not kwargs:
62        group = None
63    else:
64        group = parser.add_option_group(*args, **kwargs)
65
66class splitter(object):
67    def __init__(self, split):
68        self.split = split
69    def __call__(self, option, opt_str, value, parser):
70        getattr(parser.values, option.dest).extend(value.split(self.split))
71
72def add_option(*args, **kwargs):
73    '''add an option to the current option group, or global none set'''
74
75    # if action=split, but allows the option arguments
76    # themselves to be lists separated by the split variable'''
77
78    if kwargs.get('action', None) == 'append' and 'split' in kwargs:
79        split = kwargs.pop('split')
80        kwargs['default'] = []
81        kwargs['type'] = 'string'
82        kwargs['action'] = 'callback'
83        kwargs['callback'] = splitter(split)
84
85    if group:
86        return group.add_option(*args, **kwargs)
87
88    return parser.add_option(*args, **kwargs)
89
90def bool_option(name, default, help):
91    '''add a boolean option called --name and --no-name.
92    Display help depending on which is the default'''
93
94    tname = '--%s' % name
95    fname = '--no-%s' % name
96    dest = name.replace('-', '_')
97    if default:
98        thelp = optparse.SUPPRESS_HELP
99        fhelp = help
100    else:
101        thelp = help
102        fhelp = optparse.SUPPRESS_HELP
103
104    add_option(tname, action="store_true", default=default, help=thelp)
105    add_option(fname, action="store_false", dest=dest, help=fhelp)
106
107# Help options
108add_option('-A', "--authors", action="store_true", default=False,
109    help="Show author information")
110add_option('-C', "--copyright", action="store_true", default=False,
111    help="Show full copyright information")
112add_option('-R', "--readme", action="store_true", default=False,
113    help="Show the readme")
114add_option('-N', "--release-notes", action="store_true", default=False,
115    help="Show the release notes")
116
117# Options for configuring the base simulator
118add_option('-d', "--outdir", metavar="DIR", default=".",
119    help="Set the output directory to DIR [Default: %default]")
120add_option('-i', "--interactive", action="store_true", default=False,
121    help="Invoke the interactive interpreter after running the script")
122add_option("--pdb", action="store_true", default=False,
123    help="Invoke the python debugger before running the script")
124add_option('-p', "--path", metavar="PATH[:PATH]", action='append', split=':',
125    help="Prepend PATH to the system path when invoking the script")
126add_option('-q', "--quiet", action="count", default=0,
127    help="Reduce verbosity")
128add_option('-v', "--verbose", action="count", default=0,
129    help="Increase verbosity")
130
131# Statistics options
132set_group("Statistics Options")
133add_option("--stats-file", metavar="FILE", default="m5stats.txt",
134    help="Sets the output file for statistics [Default: %default]")
135
136# Debugging options
137set_group("Debugging Options")
138add_option("--debug-break", metavar="TIME[,TIME]", action='append', split=',',
139    help="Cycle to create a breakpoint")
140
141# Tracing options
142set_group("Trace Options")
143add_option("--trace-flags", metavar="FLAG[,FLAG]", action='append', split=',',
144    help="Sets the flags for tracing")
145add_option("--trace-start", metavar="TIME", default='0s',
146    help="Start tracing at TIME (must have units)")
147add_option("--trace-file", metavar="FILE", default="cout",
148    help="Sets the output file for tracing [Default: %default]")
149add_option("--trace-circlebuf", metavar="SIZE", type="int", default=0,
150    help="If SIZE is non-zero, turn on the circular buffer with SIZE lines")
151add_option("--no-trace-circlebuf", action="store_const", const=0,
152    dest='trace_circlebuf', help=optparse.SUPPRESS_HELP)
153bool_option("trace-dumponexit", default=False,
154    help="Dump trace buffer on exit")
155add_option("--trace-ignore", metavar="EXPR", action='append', split=':',
156    help="Ignore EXPR sim objects")
157
158# Execution Trace options
159set_group("Execution Trace Options")
160bool_option("speculative", default=True,
161    help="Don't capture speculative instructions")
162bool_option("print-cycle", default=True,
163    help="Don't print cycle numbers in trace output")
164bool_option("print-symbol", default=True,
165    help="Disable PC symbols in trace output")
166bool_option("print-opclass", default=True,
167    help="Don't print op class type in trace output")
168bool_option("print-thread", default=True,
169    help="Don't print thread number in trace output")
170bool_option("print-effaddr", default=True,
171    help="Don't print effective address in trace output")
172bool_option("print-data", default=True,
173    help="Don't print result data in trace output")
174bool_option("print-iregs", default=False,
175    help="Print fetch sequence numbers in trace output")
176bool_option("print-fetch-seq", default=False,
177    help="Print fetch sequence numbers in trace output")
178bool_option("print-cpseq", default=False,
179    help="Print correct path sequence numbers in trace output")
180
181options = attrdict()
182arguments = []
183
184def usage(exitcode=None):
185    print parser.help
186    if exitcode is not None:
187        sys.exit(exitcode)
188
189def parse_args():
190    _opts,args = parser.parse_args()
191    opts = attrdict(_opts.__dict__)
192
193    # setting verbose and quiet at the same time doesn't make sense
194    if opts.verbose > 0 and opts.quiet > 0:
195        usage(2)
196
197    # store the verbosity in a single variable.  0 is default,
198    # negative numbers represent quiet and positive values indicate verbose
199    opts.verbose -= opts.quiet
200
201    del opts.quiet
202
203    options.update(opts)
204    arguments.extend(args)
205    return opts,args
206
207def main():
208    import cc_main
209
210    parse_args()
211
212    done = False
213    if options.copyright:
214        done = True
215        print info.LICENSE
216        print
217
218    if options.authors:
219        done = True
220        print 'Author information:'
221        print
222        print info.AUTHORS
223        print
224
225    if options.readme:
226        done = True
227        print 'Readme:'
228        print
229        print info.README
230        print
231
232    if options.release_notes:
233        done = True
234        print 'Release Notes:'
235        print
236        print info.RELEASE_NOTES
237        print
238
239    if done:
240        sys.exit(0)
241
242    if options.verbose >= 0:
243        print "M5 Simulator System"
244        print brief_copyright
245        print
246        print "M5 compiled %s" % cc_main.cvar.compileDate;
247        print "M5 started %s" % datetime.now().ctime()
248        print "M5 executing on %s" % socket.gethostname()
249
250    # check to make sure we can find the listed script
251    if not arguments or not os.path.isfile(arguments[0]):
252        if arguments and not os.path.isfile(arguments[0]):
253            print "Script %s not found" % arguments[0]
254        usage(2)
255
256    # tell C++ about output directory
257    cc_main.setOutputDir(options.outdir)
258
259    # update the system path with elements from the -p option
260    sys.path[0:0] = options.path
261
262    import objects
263
264    # set stats options
265    objects.Statistics.text_file = options.stats_file
266
267    # set debugging options
268    objects.Debug.break_cycles = options.debug_break
269
270    # set tracing options
271    objects.Trace.flags = options.trace_flags
272    objects.Trace.start = options.trace_start
273    objects.Trace.file = options.trace_file
274    objects.Trace.bufsize = options.trace_circlebuf
275    objects.Trace.dump_on_exit = options.trace_dumponexit
276    objects.Trace.ignore = options.trace_ignore
277
278    # set execution trace options
279    objects.ExecutionTrace.speculative = options.speculative
280    objects.ExecutionTrace.print_cycle = options.print_cycle
281    objects.ExecutionTrace.pc_symbol = options.print_symbol
282    objects.ExecutionTrace.print_opclass = options.print_opclass
283    objects.ExecutionTrace.print_thread = options.print_thread
284    objects.ExecutionTrace.print_effaddr = options.print_effaddr
285    objects.ExecutionTrace.print_data = options.print_data
286    objects.ExecutionTrace.print_iregs = options.print_iregs
287    objects.ExecutionTrace.print_fetchseq = options.print_fetch_seq
288    objects.ExecutionTrace.print_cpseq = options.print_cpseq
289
290    sys.argv = arguments
291    sys.path = [ os.path.dirname(sys.argv[0]) ] + sys.path
292
293    scope = { '__file__' : sys.argv[0] }
294
295    # we want readline if we're doing anything interactive
296    if options.interactive or options.pdb:
297        exec("import readline", scope)
298
299    # if pdb was requested, execfile the thing under pdb, otherwise,
300    # just do the execfile normally
301    if options.pdb:
302        from pdb import Pdb
303        debugger = Pdb()
304        debugger.run('execfile("%s")' % sys.argv[0], scope)
305    else:
306        execfile(sys.argv[0], scope)
307
308    # once the script is done
309    if options.interactive:
310        interact = code.InteractiveConsole(scope)
311        interact.interact("M5 Interactive Console")
312
313if __name__ == '__main__':
314    from pprint import pprint
315
316    parse_args()
317
318    print 'opts:'
319    pprint(options, indent=4)
320    print
321
322    print 'args:'
323    pprint(arguments, indent=4)
324