Make time format in 'started' line same as 'compiled'.
[gem5.git] / src / python / m5 / main.py
index 96f017cb0993ebd3e833cff71582c87d5047c294..1e217715c9fb25b909e81d986ea7fd83c2bf1d01 100644 (file)
 
 import code
 import datetime
-import optparse
 import os
 import socket
 import sys
 
-from attrdict import attrdict
+from util import attrdict
+import config
 import defines
+from options import OptionParser
 import traceflags
 
 __all__ = [ 'options', 'arguments', 'main' ]
 
-usage="%prog [m5 options] script.py [script options]"
-version="%prog 2.0"
-brief_copyright='''
-Copyright (c) 2001-2006
-The Regents of The University of Michigan
-All Rights Reserved
-'''
-
 def print_list(items, indent=4):
     line = ' ' * indent
     for i,item in enumerate(items):
@@ -60,64 +53,19 @@ def print_list(items, indent=4):
             line += item
             print line
 
-# there's only one option parsing done, so make it global and add some
-# helper functions to make it work well.
-parser = optparse.OptionParser(usage=usage, version=version,
-                               description=brief_copyright,
-                               formatter=optparse.TitledHelpFormatter())
-parser.disable_interspersed_args()
-
-# current option group
-group = None
-
-def set_group(*args, **kwargs):
-    '''set the current option group'''
-    global group
-    if not args and not kwargs:
-        group = None
-    else:
-        group = parser.add_option_group(*args, **kwargs)
-
-class splitter(object):
-    def __init__(self, split):
-        self.split = split
-    def __call__(self, option, opt_str, value, parser):
-        getattr(parser.values, option.dest).extend(value.split(self.split))
-
-def add_option(*args, **kwargs):
-    '''add an option to the current option group, or global none set'''
-
-    # if action=split, but allows the option arguments
-    # themselves to be lists separated by the split variable'''
-
-    if kwargs.get('action', None) == 'append' and 'split' in kwargs:
-        split = kwargs.pop('split')
-        kwargs['default'] = []
-        kwargs['type'] = 'string'
-        kwargs['action'] = 'callback'
-        kwargs['callback'] = splitter(split)
-
-    if group:
-        return group.add_option(*args, **kwargs)
-
-    return parser.add_option(*args, **kwargs)
-
-def bool_option(name, default, help):
-    '''add a boolean option called --name and --no-name.
-    Display help depending on which is the default'''
-
-    tname = '--%s' % name
-    fname = '--no-%s' % name
-    dest = name.replace('-', '_')
-    if default:
-        thelp = optparse.SUPPRESS_HELP
-        fhelp = help
-    else:
-        thelp = help
-        fhelp = optparse.SUPPRESS_HELP
+usage="%prog [m5 options] script.py [script options]"
+version="%prog 2.0"
+brief_copyright='''
+Copyright (c) 2001-2008
+The Regents of The University of Michigan
+All Rights Reserved
+'''
 
-    add_option(tname, action="store_true", default=default, help=thelp)
-    add_option(fname, action="store_false", dest=dest, help=fhelp)
+options = OptionParser(usage=usage, version=version,
+                       description=brief_copyright)
+add_option = options.add_option
+set_group = options.set_group
+usage = options.usage
 
 # Help options
 add_option('-A', "--authors", action="store_true", default=False,
@@ -134,6 +82,14 @@ add_option('-N', "--release-notes", action="store_true", default=False,
 # Options for configuring the base simulator
 add_option('-d', "--outdir", metavar="DIR", default=".",
     help="Set the output directory to DIR [Default: %default]")
+add_option('-r', "--redirect-stdout", action="store_true", default=False,
+           help="Redirect stdout (& stderr, without -e) to file")
+add_option('-e', "--redirect-stderr", action="store_true", default=False,
+           help="Redirect stderr to file")
+add_option("--stdout-file", metavar="FILE", default="simout",
+           help="Filename for -r redirection [Default: %default]")
+add_option("--stderr-file", metavar="FILE", default="simerr",
+           help="Filename for -e redirection [Default: %default]")
 add_option('-i', "--interactive", action="store_true", default=False,
     help="Invoke the interactive interpreter after running the script")
 add_option("--pdb", action="store_true", default=False,
@@ -154,6 +110,8 @@ add_option("--stats-file", metavar="FILE", default="m5stats.txt",
 set_group("Debugging Options")
 add_option("--debug-break", metavar="TIME[,TIME]", action='append', split=',',
     help="Cycle to create a breakpoint")
+add_option("--remote-gdb-port", type='int', default=7000,
+    help="Remote gdb base port")
 
 # Tracing options
 set_group("Trace Options")
@@ -168,31 +126,10 @@ add_option("--trace-file", metavar="FILE", default="cout",
 add_option("--trace-ignore", metavar="EXPR", action='append', split=':',
     help="Ignore EXPR sim objects")
 
-options = attrdict()
-arguments = []
-
-def usage(exitcode=None):
-    parser.print_help()
-    if exitcode is not None:
-        sys.exit(exitcode)
-
-def parse_args():
-    _opts,args = parser.parse_args()
-    opts = attrdict(_opts.__dict__)
-
-    # setting verbose and quiet at the same time doesn't make sense
-    if opts.verbose > 0 and opts.quiet > 0:
-        usage(2)
-
-    # store the verbosity in a single variable.  0 is default,
-    # negative numbers represent quiet and positive values indicate verbose
-    opts.verbose -= opts.quiet
-
-    del opts.quiet
-
-    options.update(opts)
-    arguments.extend(args)
-    return opts,args
+# Help options
+set_group("Help Options")
+add_option("--list-sim-objects", action='store_true', default=False,
+    help="List all built-in SimObjects, their parameters and default values")
 
 def main():
     import defines
@@ -200,7 +137,41 @@ def main():
     import info
     import internal
 
-    parse_args()
+    # load the options.py config file to allow people to set their own
+    # default options
+    options_file = config.get('options.py')
+    if options_file:
+        scope = { 'options' : options }
+        execfile(options_file, scope)
+
+    arguments = options.parse_args()
+
+    if not os.path.isdir(options.outdir):
+        os.makedirs(options.outdir)
+
+    # These filenames are used only if the redirect_std* options are set
+    stdout_file = os.path.join(options.outdir, options.stdout_file)
+    stderr_file = os.path.join(options.outdir, options.stderr_file)
+
+    # Print redirection notices here before doing any redirection
+    if options.redirect_stdout and not options.redirect_stderr:
+        print "Redirecting stdout and stderr to", stdout_file
+    else:
+        if options.redirect_stdout:
+            print "Redirecting stdout to", stdout_file
+        if options.redirect_stderr:
+            print "Redirecting stderr to", stderr_file
+
+    # Now redirect stdout/stderr as desired
+    if options.redirect_stdout:
+        redir_fd = os.open(stdout_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
+        os.dup2(redir_fd, sys.stdout.fileno())
+        if not options.redirect_stderr:
+            os.dup2(redir_fd, sys.stderr.fileno())
+
+    if options.redirect_stderr:
+        redir_fd = os.open(stderr_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
+        os.dup2(redir_fd, sys.stderr.fileno())
 
     done = False
 
@@ -209,8 +180,8 @@ def main():
         print 'Build information:'
         print
         print 'compiled %s' % internal.core.cvar.compileDate;
-        print 'started %s' % datetime.datetime.now().ctime()
-        print 'executing on %s' % socket.gethostname()
+        print "revision %s" % internal.core.cvar.hgRev
+        print "commit date %s" % internal.core.cvar.hgDate
         print 'build options:'
         keys = defines.m5_build_env.keys()
         keys.sort()
@@ -258,16 +229,46 @@ def main():
             print_list(traceflags.compoundFlagMap[flag], indent=8)
             print
 
+    if options.list_sim_objects:
+        import SimObject
+        done = True
+        print "SimObjects:"
+        objects = SimObject.allClasses.keys()
+        objects.sort()
+        for name in objects:
+            obj = SimObject.allClasses[name]
+            print "    %s" % obj
+            params = obj._params.keys()
+            params.sort()
+            for pname in params:
+                param = obj._params[pname]
+                default = getattr(param, 'default', '')
+                print "        %s" % pname
+                if default:
+                    print "            default: %s" % default
+                print "            desc: %s" % param.desc
+                print
+            print
+
     if done:
         sys.exit(0)
 
+    # setting verbose and quiet at the same time doesn't make sense
+    if options.verbose > 0 and options.quiet > 0:
+        options.usage(2)
+
+    verbose = options.verbose - options.quiet
     if options.verbose >= 0:
         print "M5 Simulator System"
         print brief_copyright
         print
         print "M5 compiled %s" % internal.core.cvar.compileDate;
-        print "M5 started %s" % datetime.datetime.now().ctime()
+        print "M5 revision %s" % internal.core.cvar.hgRev
+        print "M5 commit date %s" % internal.core.cvar.hgDate
+
+        print "M5 started %s" % datetime.datetime.now().strftime("%b %e %Y %X")
         print "M5 executing on %s" % socket.gethostname()
+
         print "command line:",
         for argv in sys.argv:
             print argv,
@@ -278,7 +279,7 @@ def main():
         if arguments and not os.path.isfile(arguments[0]):
             print "Script %s not found" % arguments[0]
 
-        usage(2)
+        options.usage(2)
 
     # tell C++ about output directory
     internal.core.setOutputDir(options.outdir)
@@ -292,6 +293,7 @@ def main():
     internal.stats.initText(options.stats_file)
 
     # set debugging options
+    internal.debug.setRemoteGDBPort(options.remote_gdb_port)
     for when in options.debug_break:
         internal.debug.schedBreakCycle(int(when))