python: Move more code into m5.util allow SCons to use that code.
authorNathan Binkert <nate@binkert.org>
Tue, 22 Sep 2009 22:24:16 +0000 (15:24 -0700)
committerNathan Binkert <nate@binkert.org>
Tue, 22 Sep 2009 22:24:16 +0000 (15:24 -0700)
Get rid of misc.py and just stick misc things in __init__.py
Move utility functions out of SCons files and into m5.util
Move utility type stuff from m5/__init__.py to m5/util/__init__.py
Remove buildEnv from m5 and allow access only from m5.defines
Rename AddToPath to addToPath while we're moving it to m5.util
Rename read_command to readCommand while we're moving it
Rename compare_versions to compareVersions while we're moving it.

--HG--
rename : src/python/m5/convert.py => src/python/m5/util/convert.py
rename : src/python/m5/smartdict.py => src/python/m5/util/smartdict.py

66 files changed:
SConstruct
configs/common/Caches.py
configs/common/FSConfig.py
configs/common/Simulation.py
configs/example/fs.py
configs/example/memtest.py
configs/example/ruby_se.py
configs/example/se.py
configs/splash2/cluster.py
configs/splash2/run.py
src/SConscript
src/arch/mips/BISystem.py
src/arch/mips/MipsCPU.py
src/arch/mips/MipsSystem.py
src/arch/x86/X86TLB.py
src/cpu/BaseCPU.py
src/cpu/CheckerCPU.py
src/cpu/inorder/InOrderCPU.py
src/cpu/memtest/MemTest.py
src/cpu/o3/O3CPU.py
src/cpu/o3/O3Checker.py
src/cpu/ozone/OzoneCPU.py
src/cpu/ozone/OzoneChecker.py
src/cpu/ozone/SimpleOzoneCPU.py
src/cpu/simple/AtomicSimpleCPU.py
src/cpu/simple/TimingSimpleCPU.py
src/dev/Uart.py
src/mem/Bus.py
src/python/SConscript
src/python/m5/SimObject.py
src/python/m5/__init__.py
src/python/m5/convert.py [deleted file]
src/python/m5/environment.py [deleted file]
src/python/m5/main.py
src/python/m5/params.py
src/python/m5/simulate.py
src/python/m5/smartdict.py [deleted file]
src/python/m5/ticks.py
src/python/m5/trace.py
src/python/m5/util/__init__.py
src/python/m5/util/convert.py [new file with mode: 0644]
src/python/m5/util/jobfile.py
src/python/m5/util/misc.py [deleted file]
src/python/m5/util/smartdict.py [new file with mode: 0644]
src/sim/System.py
tests/configs/inorder-timing.py
tests/configs/o3-timing-mp-ruby.py
tests/configs/o3-timing-mp.py
tests/configs/o3-timing-ruby.py
tests/configs/o3-timing.py
tests/configs/t1000-simple-atomic.py
tests/configs/tsunami-o3-dual.py
tests/configs/tsunami-o3.py
tests/configs/tsunami-simple-atomic-dual.py
tests/configs/tsunami-simple-atomic.py
tests/configs/tsunami-simple-timing-dual.py
tests/configs/tsunami-simple-timing.py
tests/configs/twosys-tsunami-simple-atomic.py
tests/long/00.gzip/test.py
tests/long/10.mcf/test.py
tests/long/20.parser/test.py
tests/long/30.eon/test.py
tests/long/40.perlbmk/test.py
tests/long/50.vortex/test.py
tests/long/60.bzip2/test.py
tests/long/70.twolf/test.py

index 85c5de1423b9fd10efd81edfd4ccc55dfa8c2be2..e34d60ec8521c1d5622ff78e7e724d95b6622df5 100644 (file)
@@ -96,6 +96,7 @@ For more details, see:
 """
     raise
 
+# Global Python includes
 import os
 import re
 import subprocess
@@ -106,55 +107,14 @@ from os.path import abspath, basename, dirname, expanduser, normpath
 from os.path import exists,  isdir, isfile
 from os.path import join as joinpath, split as splitpath
 
+# SCons includes
 import SCons
 import SCons.Node
 
-def read_command(cmd, **kwargs):
-    """run the command cmd, read the results and return them
-    this is sorta like `cmd` in shell"""
-    from subprocess import Popen, PIPE, STDOUT
-
-    if isinstance(cmd, str):
-        cmd = cmd.split()
-
-    no_exception = 'exception' in kwargs
-    exception = kwargs.pop('exception', None)
-    
-    kwargs.setdefault('shell', False)
-    kwargs.setdefault('stdout', PIPE)
-    kwargs.setdefault('stderr', STDOUT)
-    kwargs.setdefault('close_fds', True)
-    try:
-        subp = Popen(cmd, **kwargs)
-    except Exception, e:
-        if no_exception:
-            return exception
-        raise
-
-    return subp.communicate()[0]
-
-# helper function: compare arrays or strings of version numbers.
-# E.g., compare_version((1,3,25), (1,4,1)')
-# returns -1, 0, 1 if v1 is <, ==, > v2
-def compare_versions(v1, v2):
-    def make_version_list(v):
-        if isinstance(v, (list,tuple)):
-            return v
-        elif isinstance(v, str):
-            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
-        else:
-            raise TypeError
-
-    v1 = make_version_list(v1)
-    v2 = make_version_list(v2)
-    # Compare corresponding elements of lists
-    for n1,n2 in zip(v1, v2):
-        if n1 < n2: return -1
-        if n1 > n2: return  1
-    # all corresponding values are equal... see if one has extra values
-    if len(v1) < len(v2): return -1
-    if len(v1) > len(v2): return  1
-    return 0
+# M5 includes
+sys.path[1:1] = [ Dir('src/python').srcnode().abspath ]
+
+from m5.util import compareVersions, readCommand
 
 ########################################################################
 #
@@ -217,7 +177,7 @@ if hgdir.exists():
     # 1) Grab repository revision if we know it.
     cmd = "hg id -n -i -t -b"
     try:
-        hg_info = read_command(cmd, cwd=main.root.abspath).strip()
+        hg_info = readCommand(cmd, cwd=main.root.abspath).strip()
     except OSError:
         print mercurial_bin_not_found
 
@@ -381,8 +341,8 @@ main.Append(CPPPATH=[Dir('ext')])
 # M5_PLY is used by isa_parser.py to find the PLY package.
 main.Append(ENV = { 'M5_PLY' : Dir('ext/ply').abspath })
 
-CXX_version = read_command([main['CXX'],'--version'], exception=False)
-CXX_V = read_command([main['CXX'],'-V'], exception=False)
+CXX_version = readCommand([main['CXX'],'--version'], exception=False)
+CXX_V = readCommand([main['CXX'],'-V'], exception=False)
 
 main['GCC'] = CXX_version and CXX_version.find('g++') >= 0
 main['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
@@ -435,7 +395,7 @@ if not main.has_key('SWIG'):
     Exit(1)
 
 # Check for appropriate SWIG version
-swig_version = read_command(('swig', '-version'), exception='').split()
+swig_version = readCommand(('swig', '-version'), exception='').split()
 # First 3 words should be "SWIG Version x.y.z"
 if len(swig_version) < 3 or \
         swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
@@ -443,7 +403,7 @@ if len(swig_version) < 3 or \
     Exit(1)
 
 min_swig_version = '1.3.28'
-if compare_versions(swig_version[2], min_swig_version) < 0:
+if compareVersions(swig_version[2], min_swig_version) < 0:
     print 'Error: SWIG version', min_swig_version, 'or newer required.'
     print '       Installed version:', swig_version[2]
     Exit(1)
@@ -514,8 +474,8 @@ conf.CheckLeading()
 try:
     import platform
     uname = platform.uname()
-    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
-        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
+    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
+        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
             main.Append(CCFLAGS='-arch x86_64')
             main.Append(CFLAGS='-arch x86_64')
             main.Append(LINKFLAGS='-arch x86_64')
@@ -615,9 +575,9 @@ have_mysql = bool(mysql_config)
 
 # Check MySQL version.
 if have_mysql:
-    mysql_version = read_command(mysql_config + ' --version')
+    mysql_version = readCommand(mysql_config + ' --version')
     min_mysql_version = '4.1'
-    if compare_versions(mysql_version, min_mysql_version) < 0:
+    if compareVersions(mysql_version, min_mysql_version) < 0:
         print 'Warning: MySQL', min_mysql_version, 'or newer required.'
         print '         Version', mysql_version, 'detected.'
         have_mysql = False
index 1c3b089c799d28e678994da5c683cf0205ea9a57..412cfd3b1467ab220b679689c5aeca84f6620615 100644 (file)
@@ -26,7 +26,6 @@
 #
 # Authors: Lisa Hsu
 
-import m5
 from m5.objects import *
 
 class L1Cache(BaseCache):
index 180e0ac52e0f561be0c68506d847b6250220f39f..bd20a2bacc7b3f0633b200c0697d97a24799fef7 100644 (file)
@@ -26,8 +26,6 @@
 #
 # Authors: Kevin Lim
 
-import m5
-from m5 import makeList
 from m5.objects import *
 from Benchmarks import *
 
index 23dfad6c6b07808b2231e86d8e18b01693e1c7d9..112a951b668b37d16c38bdb32c05debfe6d9d411 100644 (file)
 
 from os import getcwd
 from os.path import join as joinpath
+
 import m5
+from m5.defines import buildEnv
 from m5.objects import *
-m5.AddToPath('../common')
+from m5.util import *
+
+addToPath('../common')
 
 def setCPUClass(options):
 
@@ -82,10 +86,10 @@ def run(options, root, testsys, cpu_class):
         cptdir = getcwd()
 
     if options.fast_forward and options.checkpoint_restore != None:
-        m5.fatal("Error: Can't specify both --fast-forward and --checkpoint-restore")
+        fatal("Can't specify both --fast-forward and --checkpoint-restore")
 
     if options.standard_switch and not options.caches:
-        m5.fatal("Error: Must specify --caches when using --standard-switch")
+        fatal("Must specify --caches when using --standard-switch")
 
     np = options.num_cpus
     max_checkpoints = options.max_checkpoints
@@ -107,7 +111,7 @@ def run(options, root, testsys, cpu_class):
             if options.fast_forward:
                 testsys.cpu[i].max_insts_any_thread = int(options.fast_forward)
             switch_cpus[i].system =  testsys
-            if not m5.build_env['FULL_SYSTEM']:
+            if not buildEnv['FULL_SYSTEM']:
                 switch_cpus[i].workload = testsys.cpu[i].workload
             switch_cpus[i].clock = testsys.cpu[0].clock
             # simulation period
@@ -126,7 +130,7 @@ def run(options, root, testsys, cpu_class):
         for i in xrange(np):
             switch_cpus[i].system =  testsys
             switch_cpus_1[i].system =  testsys
-            if not m5.build_env['FULL_SYSTEM']:
+            if not buildEnv['FULL_SYSTEM']:
                 switch_cpus[i].workload = testsys.cpu[i].workload
                 switch_cpus_1[i].workload = testsys.cpu[i].workload
             switch_cpus[i].clock = testsys.cpu[0].clock
@@ -141,7 +145,7 @@ def run(options, root, testsys, cpu_class):
             # Fast forward to a simpoint (warning: time consuming)
             elif options.simpoint:
                 if testsys.cpu[i].workload[0].simpoint == 0:
-                    m5.fatal('simpoint not found')
+                    fatal('simpoint not found')
                 testsys.cpu[i].max_insts_any_thread = \
                     testsys.cpu[i].workload[0].simpoint
             # No distance specified, just switch
@@ -174,7 +178,7 @@ def run(options, root, testsys, cpu_class):
         if options.simpoint:
             for i in xrange(np):
                 if testsys.cpu[i].workload[0].simpoint == 0:
-                    m5.fatal('no simpoint for testsys.cpu[%d].workload[0]', i)
+                    fatal('no simpoint for testsys.cpu[%d].workload[0]', i)
                 checkpoint_inst = int(testsys.cpu[i].workload[0].simpoint) + offset
                 testsys.cpu[i].max_insts_any_thread = checkpoint_inst
                 # used for output below
@@ -194,14 +198,13 @@ def run(options, root, testsys, cpu_class):
         import re
 
         if not isdir(cptdir):
-            m5.fatal("checkpoint dir %s does not exist!", cptdir)
+            fatal("checkpoint dir %s does not exist!", cptdir)
 
         if options.at_instruction:
             checkpoint_dir = joinpath(cptdir, "cpt.%s.%s" % \
                     (options.bench, options.checkpoint_restore))
             if not exists(checkpoint_dir):
-                m5.fatal("Unable to find checkpoint directory %s",
-                         checkpoint_dir)
+                fatal("Unable to find checkpoint directory %s", checkpoint_dir)
 
             print "Restoring checkpoint ..."
             m5.restoreCheckpoint(root, checkpoint_dir)
@@ -209,7 +212,7 @@ def run(options, root, testsys, cpu_class):
         elif options.simpoint:
             # assume workload 0 has the simpoint
             if testsys.cpu[0].workload[0].simpoint == 0:
-                m5.fatal('Unable to find simpoint')
+                fatal('Unable to find simpoint')
 
             options.checkpoint_restore += \
                 int(testsys.cpu[0].workload[0].simpoint)
@@ -217,8 +220,8 @@ def run(options, root, testsys, cpu_class):
             checkpoint_dir = joinpath(cptdir, "cpt.%s.%d" % \
                     (options.bench, options.checkpoint_restore))
             if not exists(checkpoint_dir):
-                m5.fatal("Unable to find checkpoint directory %s.%s",
-                        options.bench, options.checkpoint_restore)
+                fatal("Unable to find checkpoint directory %s.%s",
+                      options.bench, options.checkpoint_restore)
 
             print "Restoring checkpoint ..."
             m5.restoreCheckpoint(root,checkpoint_dir)
@@ -237,7 +240,7 @@ def run(options, root, testsys, cpu_class):
             cpt_num = options.checkpoint_restore
 
             if cpt_num > len(cpts):
-                m5.fatal('Checkpoint %d not found', cpt_num)
+                fatal('Checkpoint %d not found', cpt_num)
 
             ## Adjust max tick based on our starting tick
             maxtick = maxtick - int(cpts[cpt_num - 1])
index 3164b6fb42b653f9cf95e614f1b306fffa4861b9..23285e101766b8ec565e7481d22f13cd88f51aff 100644 (file)
 #
 # Authors: Ali Saidi
 
-import optparse, os, sys
+import optparse
+import os
+import sys
 
 import m5
+from m5.defines import buildEnv
+from m5.objects import *
+from m5.util import addToPath, fatal
 
-if not m5.build_env['FULL_SYSTEM']:
-    m5.fatal("This script requires full-system mode (*_FS).")
+if not buildEnv['FULL_SYSTEM']:
+    fatal("This script requires full-system mode (*_FS).")
+
+addToPath('../common')
 
-from m5.objects import *
-m5.AddToPath('../common')
 from FSConfig import *
 from SysPaths import *
 from Benchmarks import *
@@ -98,16 +103,16 @@ else:
 
 np = options.num_cpus
 
-if m5.build_env['TARGET_ISA'] == "alpha":
+if buildEnv['TARGET_ISA'] == "alpha":
     test_sys = makeLinuxAlphaSystem(test_mem_mode, bm[0])
-elif m5.build_env['TARGET_ISA'] == "mips":
+elif buildEnv['TARGET_ISA'] == "mips":
     test_sys = makeLinuxMipsSystem(test_mem_mode, bm[0])
-elif m5.build_env['TARGET_ISA'] == "sparc":
+elif buildEnv['TARGET_ISA'] == "sparc":
     test_sys = makeSparcSystem(test_mem_mode, bm[0])
-elif m5.build_env['TARGET_ISA'] == "x86":
+elif buildEnv['TARGET_ISA'] == "x86":
     test_sys = makeLinuxX86System(test_mem_mode, np, bm[0])
 else:
-    m5.fatal("incapable of building non-alpha or non-sparc full system!")
+    fatal("incapable of building non-alpha or non-sparc full system!")
 
 if options.kernel is not None:
     test_sys.kernel = binary(options.kernel)
@@ -142,17 +147,17 @@ for i in xrange(np):
     if options.fastmem:
         test_sys.cpu[i].physmem_port = test_sys.physmem.port
 
-if m5.build_env['TARGET_ISA'] == 'mips':
+if buildEnv['TARGET_ISA'] == 'mips':
     setMipsOptions(TestCPUClass)
 
 if len(bm) == 2:
-    if m5.build_env['TARGET_ISA'] == 'alpha':
+    if buildEnv['TARGET_ISA'] == 'alpha':
         drive_sys = makeLinuxAlphaSystem(drive_mem_mode, bm[1])
-    elif m5.build_env['TARGET_ISA'] == 'mips':
+    elif buildEnv['TARGET_ISA'] == 'mips':
         drive_sys = makeLinuxMipsSystem(drive_mem_mode, bm[1])
-    elif m5.build_env['TARGET_ISA'] == 'sparc':
+    elif buildEnv['TARGET_ISA'] == 'sparc':
         drive_sys = makeSparcSystem(drive_mem_mode, bm[1])
-    elif m5.build.env['TARGET_ISA'] == 'x86':
+    elif buildEnv['TARGET_ISA'] == 'x86':
         drive_sys = makeX86System(drive_mem_mode, np, bm[1])
     drive_sys.cpu = DriveCPUClass(cpu_id=0)
     drive_sys.cpu.connectMemPorts(drive_sys.membus)
index 5bb874e8543043e7ff0c772389750f687fea668f..d4497092bf27dd87b1bec01e99affbccf4b4f6af 100644 (file)
 #
 # Authors: Ron Dreslinski
 
+import optparse
+import sys
+
 import m5
 from m5.objects import *
-import os, optparse, sys
-m5.AddToPath('../common')
 
 parser = optparse.OptionParser()
 
index 488ccb64a50c611f1921aa32228a063c7133d956..76668f7631d442a19fbc794cd774b0380991ffee 100644 (file)
 #
 # "m5 test.py"
 
+import os
+import optparse
+import sys
+from os.path import join as joinpath
+
 import m5
+from m5.defines import buildEnv
+from m5.objects import *
+from m5.util import addToPath, panic
 
-if m5.build_env['FULL_SYSTEM']:
-    m5.panic("This script requires syscall emulation mode (*_SE).")
+if buildEnv['FULL_SYSTEM']:
+    panic("This script requires syscall emulation mode (*_SE).")
+
+addToPath('../common')
 
-from m5.objects import *
-import os, optparse, sys
-from os.path import join as joinpath
-m5.AddToPath('../common')
 import Simulation
-#from Caches import *
 from cpu2000 import *
 
 # Get paths we might need.  It's expected this file is in m5/configs/example.
@@ -72,7 +77,7 @@ if args:
 
 if options.bench:
     try:
-        if m5.build_env['TARGET_ISA'] != 'alpha':
+        if buildEnv['TARGET_ISA'] != 'alpha':
             print >>sys.stderr, "Simpoints code only works for Alpha ISA at this time"
             sys.exit(1)
         exec("workload = %s('alpha', 'tru64', 'ref')" % options.bench)
index e7fcc8261169b77579e1643c64833af959f15fc4..c490ed6b611c551ed9696ae56fabac148d0c4655 100644 (file)
 #
 # "m5 test.py"
 
+import os
+import optparse
+import sys
+from os.path import join as joinpath
+
 import m5
+from m5.defines import buildEnv
+from m5.objects import *
+from m5.util import addToPath, fatal
 
-if m5.build_env['FULL_SYSTEM']:
-    m5.fatal("This script requires syscall emulation mode (*_SE).")
+if buildEnv['FULL_SYSTEM']:
+    fatal("This script requires syscall emulation mode (*_SE).")
+
+addToPath('../common')
 
-from m5.objects import *
-import os, optparse, sys
-from os.path import join as joinpath
-m5.AddToPath('../common')
 import Simulation
 from Caches import *
 from cpu2000 import *
@@ -70,7 +76,7 @@ if args:
 
 if options.bench:
     try:
-        if m5.build_env['TARGET_ISA'] != 'alpha':
+        if buildEnv['TARGET_ISA'] != 'alpha':
             print >>sys.stderr, "Simpoints code only works for Alpha ISA at this time"
             sys.exit(1)
         exec("workload = %s('alpha', 'tru64', 'ref')" % options.bench)
index 769bdcf5a9acdec78f925a791661aeff2ad7a002..45c9ede82bd5d04818ef8b9c61b5eedf49ffaff7 100644 (file)
 #
 # "m5 test.py"
 
+import os
+import optparse
+import sys
+
 import m5
 from m5.objects import *
-import os, optparse, sys
-m5.AddToPath('../common')
+
+m5.util.addToPath('../common')
 
 # --------------------
 # Define Command Line Options
@@ -266,10 +270,11 @@ elif options.benchmark == 'WaterNSquared':
 elif options.benchmark == 'WaterSpatial':
     root.workload = Water_spatial()
 else:
-    panic("The --benchmark environment variable was set to something" \
-          +" improper.\nUse Cholesky, FFT, LUContig, LUNoncontig, Radix" \
-          +", Barnes, FMM, OceanContig,\nOceanNoncontig, Raytrace," \
-          +" WaterNSquared, or WaterSpatial\n")
+    m5.util.panic("""
+The --benchmark environment variable was set to something improper.
+Use Cholesky, FFT, LUContig, LUNoncontig, Radix, Barnes, FMM, OceanContig,
+OceanNoncontig, Raytrace, WaterNSquared, or WaterSpatial
+""")
 
 # --------------------
 # Assign the workload to the cpus
index afa85a8f17a48d4882322d65630c559a06fcb52f..95ec790ba9586da653941a604faff0fdb4903ce5 100644 (file)
 # Splash2 Run Script
 #
 
+import os
+import optparse
+import sys
+
 import m5
 from m5.objects import *
-import os, optparse, sys
-m5.AddToPath('../common')
+
+m5.util.addToPath('../common')
 
 # --------------------
 # Define Command Line Options
index d96922b49e3c919e8eb460095ca2156adeb4c73d..687709ac136bbcfe78306e31469ece4a3d631b96 100644 (file)
@@ -49,7 +49,7 @@ Import('*')
 # Children need to see the environment
 Export('env')
 
-build_env = dict([(opt, env[opt]) for opt in export_vars])
+build_env = [(opt, env[opt]) for opt in export_vars]
 
 ########################################################################
 # Code for adding source files of various types
@@ -266,6 +266,8 @@ for opt in export_vars:
 # Prevent any SimObjects from being added after this point, they
 # should all have been added in the SConscripts above
 #
+SimObject.fixed = True
+
 class DictImporter(object):
     '''This importer takes a dictionary of arbitrary module names that
     map to arbitrary filenames.'''
@@ -283,7 +285,7 @@ class DictImporter(object):
         self.installed = set()
 
     def find_module(self, fullname, path):
-        if fullname == 'defines':
+        if fullname == 'm5.defines':
             return self
 
         if fullname == 'm5.objects':
@@ -293,7 +295,7 @@ class DictImporter(object):
             return None
 
         source = self.modules.get(fullname, None)
-        if source is not None and exists(source.snode.abspath):
+        if source is not None and fullname.startswith('m5.objects'):
             return self
 
         return None
@@ -308,8 +310,8 @@ class DictImporter(object):
             mod.__path__ = fullname.split('.')
             return mod
 
-        if fullname == 'defines':
-            mod.__dict__['buildEnv'] = build_env
+        if fullname == 'm5.defines':
+            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
             return mod
 
         source = self.modules[fullname]
@@ -321,15 +323,18 @@ class DictImporter(object):
 
         return mod
 
+import m5.SimObject
+import m5.params
+
+m5.SimObject.clear()
+m5.params.clear()
+
 # install the python importer so we can grab stuff from the source
 # tree itself.  We can't have SimObjects added after this point or
 # else we won't know about them for the rest of the stuff.
-SimObject.fixed = True
 importer = DictImporter(PySource.modules)
 sys.meta_path[0:0] = [ importer ]
 
-import m5
-
 # import all sim objects so we can populate the all_objects list
 # make sure that we're working with a list, then let's sort it
 for modname in SimObject.modnames:
@@ -346,6 +351,12 @@ all_enums = m5.params.allEnums
 all_params = {}
 for name,obj in sorted(sim_objects.iteritems()):
     for param in obj._params.local.values():
+        # load the ptype attribute now because it depends on the
+        # current version of SimObject.allClasses, but when scons
+        # actually uses the value, all versions of
+        # SimObject.allClasses will have been loaded
+        param.ptype
+
         if not hasattr(param, 'swig_decl'):
             continue
         pname = param.ptype_str
@@ -365,13 +376,24 @@ depends = [ PySource.modules[dep].tnode for dep in module_depends ]
 #
 
 # Generate Python file containing a dict specifying the current
-# build_env flags.
+# buildEnv flags.
 def makeDefinesPyFile(target, source, env):
-    f = file(str(target[0]), 'w')
     build_env, hg_info = [ x.get_contents() for x in source ]
-    print >>f, "buildEnv = %s" % build_env
-    print >>f, "hgRev = '%s'" % hg_info
-    f.close()
+
+    code = m5.util.code_formatter()
+    code("""
+import m5.internal
+import m5.util
+
+buildEnv = m5.util.SmartDict($build_env)
+hgRev = '$hg_info'
+
+compileDate = m5.internal.core.compileDate
+for k,v in m5.internal.core.__dict__.iteritems():
+    if k.startswith('flag_'):
+        setattr(buildEnv, k[5:], v)
+""")
+    code.write(str(target[0]))
 
 defines_info = [ Value(build_env), Value(env['HG_INFO']) ]
 # Generate a file with all of the compile options in it
index dd4e4fe2595ae39f6e2733725afaef9d09b3a2dc..a6e4091f25372c8cb37e0a48418afb63543241a3 100755 (executable)
 #
 # Authors: Jaidev Patwardhan
 
-from m5 import build_env
+from m5.defines import buildEnv
+
 from System import *
 
-if build_env['FULL_SYSTEM']:
+if buildEnv['FULL_SYSTEM']:
     class BareIronMipsSystem(MipsSystem):
         type = 'BareIronMipsSystem'
         system_type = 34
index 81c6bdacf687261ef348ecff4f01205812e41bab..48ee4171c7f91449cf0cc697e558edc13c3d4722 100644 (file)
 # Authors: Jaidev Patwardhan
 #          Korey Sewell
 
-from m5.SimObject import SimObject
+from m5.defines import buildEnv
 from m5.params import *
+
 from BaseCPU import BaseCPU
 
 class BaseMipsCPU(BaseCPU)
-    if build_env['TARGET_ISA'] == 'mips':
+    if buildEnv['TARGET_ISA'] == 'mips':
         CP0_IntCtl_IPTI = Param.Unsigned(0,"No Description")
         CP0_IntCtl_IPPCI = Param.Unsigned(0,"No Description")
         CP0_SrsCtl_HSS = Param.Unsigned(0,"No Description")
index c3dcf4e0b483ff118a83b6149d464ce1c33d658f..d271bd3872eab50cedcd155f8709da7693642e52 100644 (file)
 #
 # Authors: Jaidev Patwardhan
 
-from m5.SimObject import SimObject
+from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
+
 from System import System
 
 class MipsSystem(System):
@@ -42,7 +42,7 @@ class MipsSystem(System):
     system_type = Param.UInt64("Type of system we are emulating")
     system_rev = Param.UInt64("Revision of system we are emulating")
 
-if build_env['FULL_SYSTEM']:
+if buildEnv['FULL_SYSTEM']:
     class LinuxMipsSystem(MipsSystem):
         type = 'LinuxMipsSystem'
         system_type = 34
index 15b03fd33d17367ee743254c9409080a56c93502..9f7dc43b3fdb9e427d59b1bf53dd25439be72eb0 100644 (file)
 #
 # Authors: Gabe Black
 
-from MemObject import MemObject
+from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
+
 from BaseTLB import BaseTLB
+from MemObject import MemObject
 
-if build_env['FULL_SYSTEM']:
+if buildEnv['FULL_SYSTEM']:
     class X86PagetableWalker(MemObject):
         type = 'X86PagetableWalker'
         cxx_class = 'X86ISA::Walker'
@@ -70,6 +71,6 @@ class X86TLB(BaseTLB):
     type = 'X86TLB'
     cxx_class = 'X86ISA::TLB'
     size = Param.Int(64, "TLB size")
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         walker = Param.X86PagetableWalker(\
                 X86PagetableWalker(), "page table walker")
index 4661375ba4486bbcba38c60c9cfe22b71e035ac0..75114053e7a8f3de2c02beea66591414b66dfaf5 100644 (file)
 #
 # Authors: Nathan Binkert
 
-from MemObject import MemObject
+import sys
+
+from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
+
 from Bus import Bus
 from InstTracer import InstTracer
 from ExeTracer import ExeTracer
-import sys
+from MemObject import MemObject
 
 default_tracer = ExeTracer()
 
-if build_env['TARGET_ISA'] == 'alpha':
+if buildEnv['TARGET_ISA'] == 'alpha':
     from AlphaTLB import AlphaDTB, AlphaITB
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         from AlphaInterrupts import AlphaInterrupts
-elif build_env['TARGET_ISA'] == 'sparc':
+elif buildEnv['TARGET_ISA'] == 'sparc':
     from SparcTLB import SparcTLB
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         from SparcInterrupts import SparcInterrupts
-elif build_env['TARGET_ISA'] == 'x86':
+elif buildEnv['TARGET_ISA'] == 'x86':
     from X86TLB import X86TLB
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         from X86LocalApic import X86LocalApic
-elif build_env['TARGET_ISA'] == 'mips':
+elif buildEnv['TARGET_ISA'] == 'mips':
     from MipsTLB import MipsTLB
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         from MipsInterrupts import MipsInterrupts
-elif build_env['TARGET_ISA'] == 'arm':
+elif buildEnv['TARGET_ISA'] == 'arm':
     from ArmTLB import ArmTLB
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         from ArmInterrupts import ArmInterrupts
 
 class BaseCPU(MemObject):
@@ -76,47 +78,47 @@ class BaseCPU(MemObject):
     do_statistics_insts = Param.Bool(True,
         "enable statistics pseudo instructions")
 
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         profile = Param.Latency('0ns', "trace the kernel stack")
         do_quiesce = Param.Bool(True, "enable quiesce instructions")
     else:
         workload = VectorParam.Process("processes to run")
 
-    if build_env['TARGET_ISA'] == 'sparc':
+    if buildEnv['TARGET_ISA'] == 'sparc':
         dtb = Param.SparcTLB(SparcTLB(), "Data TLB")
         itb = Param.SparcTLB(SparcTLB(), "Instruction TLB")
-        if build_env['FULL_SYSTEM']:
+        if buildEnv['FULL_SYSTEM']:
             interrupts = Param.SparcInterrupts(
                 SparcInterrupts(), "Interrupt Controller")
-    elif build_env['TARGET_ISA'] == 'alpha':
+    elif buildEnv['TARGET_ISA'] == 'alpha':
         dtb = Param.AlphaTLB(AlphaDTB(), "Data TLB")
         itb = Param.AlphaTLB(AlphaITB(), "Instruction TLB")
-        if build_env['FULL_SYSTEM']:
+        if buildEnv['FULL_SYSTEM']:
             interrupts = Param.AlphaInterrupts(
                 AlphaInterrupts(), "Interrupt Controller")
-    elif build_env['TARGET_ISA'] == 'x86':
+    elif buildEnv['TARGET_ISA'] == 'x86':
         dtb = Param.X86TLB(X86TLB(), "Data TLB")
         itb = Param.X86TLB(X86TLB(), "Instruction TLB")
-        if build_env['FULL_SYSTEM']:
+        if buildEnv['FULL_SYSTEM']:
             _localApic = X86LocalApic(pio_addr=0x2000000000000000)
             interrupts = \
                 Param.X86LocalApic(_localApic, "Interrupt Controller")
-    elif build_env['TARGET_ISA'] == 'mips':
+    elif buildEnv['TARGET_ISA'] == 'mips':
         dtb = Param.MipsTLB(MipsTLB(), "Data TLB")
         itb = Param.MipsTLB(MipsTLB(), "Instruction TLB")
-        if build_env['FULL_SYSTEM']:
+        if buildEnv['FULL_SYSTEM']:
             interrupts = Param.MipsInterrupts(
                     MipsInterrupts(), "Interrupt Controller")
-    elif build_env['TARGET_ISA'] == 'arm':
+    elif buildEnv['TARGET_ISA'] == 'arm':
         UnifiedTLB = Param.Bool(True, "Is this a Unified TLB?")
         dtb = Param.ArmTLB(ArmTLB(), "Data TLB")
         itb = Param.ArmTLB(ArmTLB(), "Instruction TLB")
-        if build_env['FULL_SYSTEM']:
+        if buildEnv['FULL_SYSTEM']:
             interrupts = Param.ArmInterrupts(
                     ArmInterrupts(), "Interrupt Controller")
     else:
         print "Don't know what TLB to use for ISA %s" % \
-            build_env['TARGET_ISA']
+            buildEnv['TARGET_ISA']
         sys.exit(1)
 
     max_insts_all_threads = Param.Counter(0,
@@ -139,7 +141,7 @@ class BaseCPU(MemObject):
     tracer = Param.InstTracer(default_tracer, "Instruction tracer")
 
     _mem_ports = []
-    if build_env['TARGET_ISA'] == 'x86' and build_env['FULL_SYSTEM']:
+    if buildEnv['TARGET_ISA'] == 'x86' and buildEnv['FULL_SYSTEM']:
         _mem_ports = ["itb.walker.port",
                       "dtb.walker.port",
                       "interrupts.pio",
@@ -157,7 +159,7 @@ class BaseCPU(MemObject):
         self.icache_port = ic.cpu_side
         self.dcache_port = dc.cpu_side
         self._mem_ports = ['icache.mem_side', 'dcache.mem_side']
-        if build_env['TARGET_ISA'] == 'x86' and build_env['FULL_SYSTEM']:
+        if buildEnv['TARGET_ISA'] == 'x86' and buildEnv['FULL_SYSTEM']:
             self._mem_ports += ["itb.walker_port", "dtb.walker_port"]
 
     def addTwoLevelCacheHierarchy(self, ic, dc, l2c):
@@ -168,7 +170,7 @@ class BaseCPU(MemObject):
         self.l2cache.cpu_side = self.toL2Bus.port
         self._mem_ports = ['l2cache.mem_side']
 
-    if build_env['TARGET_ISA'] == 'mips':
+    if buildEnv['TARGET_ISA'] == 'mips':
         CP0_IntCtl_IPTI = Param.Unsigned(0,"No Description")
         CP0_IntCtl_IPPCI = Param.Unsigned(0,"No Description")
         CP0_SrsCtl_HSS = Param.Unsigned(0,"No Description")
index bff9af62d280754b6f8f6cf2eb4eddafd19898c0..132254413fded21070e5e0721bbfa1cbcfaf4b2c 100644 (file)
@@ -27,7 +27,6 @@
 # Authors: Nathan Binkert
 
 from m5.params import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 
 class CheckerCPU(BaseCPU):
index 9faadc68cb2b64bb785c08536ba0fa12a72b6710..a0b0466a70922168bf201acf39e6baee4b897889 100644 (file)
@@ -28,7 +28,6 @@
 
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 
 class InOrderCPU(BaseCPU):
index 629fd4877fbd275d0ecdabd48d49a2bf564cade3..8e1b3a8d09f732e624cce75d7ff0e07e76064a1c 100644 (file)
@@ -29,7 +29,6 @@
 from MemObject import MemObject
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
 
 class MemTest(MemObject):
     type = 'MemTest'
index 56e537ad2f6671e66ff9593c6851dbf38b8c7e70..3f2210e44c7a910c1d7ce96e4081e978d92e47b5 100644 (file)
 #
 # Authors: Kevin Lim
 
+from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 from FUPool import *
 
-if build_env['USE_CHECKER']:
+if buildEnv['USE_CHECKER']:
     from O3Checker import O3Checker
 
 class DerivO3CPU(BaseCPU):
     type = 'DerivO3CPU'
     activity = Param.Unsigned(0, "Initial count")
 
-    if build_env['USE_CHECKER']:
-        if not build_env['FULL_SYSTEM']:
+    if buildEnv['USE_CHECKER']:
+        if not buildEnv['FULL_SYSTEM']:
             checker = Param.BaseCPU(O3Checker(workload=Parent.workload,
                                               exitOnError=False,
                                               updateOnError=True,
index edc6dc9b6fdc78d61bf049075c92fa591b26d47f..d0c4ce537e2a7afeeb90c4ade32b9884b168e66c 100644 (file)
@@ -27,7 +27,6 @@
 # Authors: Nathan Binkert
 
 from m5.params import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 
 class O3Checker(BaseCPU):
index 37386898d1682c78636630197b2bf5c7cda964c9..2c7b8475fd785c52ef0b3f418f7c44bb21b6773f 100644 (file)
 #
 # Authors: Kevin Lim
 
+from m5.defines import buildEnv
 from m5.params import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 
-if build_env['USE_CHECKER']:
+if buildEnv['USE_CHECKER']:
     from OzoneChecker import OzoneChecker
 
 class DerivOzoneCPU(BaseCPU):
@@ -38,7 +38,7 @@ class DerivOzoneCPU(BaseCPU):
 
     numThreads = Param.Unsigned("number of HW thread contexts")
 
-    if build_env['USE_CHECKER']:
+    if buildEnv['USE_CHECKER']:
         checker = Param.BaseCPU("Checker CPU")
 
     icache_port = Port("Instruction Port")
index bfa39ead90f697ed3d9fc3c0f1d58c82c2fbc6c8..bbe46db18b83fd581f0e9be2eaedf3d7ef6fe869 100644 (file)
@@ -27,7 +27,6 @@
 # Authors: Nathan Binkert
 
 from m5.params import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 
 class OzoneChecker(BaseCPU):
index 93603092bf6333c7752a3531f5192ad1442b8326..d4620cd8e7bd7aa3cffa6a8d2a6663e8ef9a0c1c 100644 (file)
@@ -26,8 +26,8 @@
 #
 # Authors: Kevin Lim
 
+from m5.defines import buildEnv
 from m5.params import *
-from m5 import build_env
 from BaseCPU import BaseCPU
 
 class SimpleOzoneCPU(BaseCPU):
@@ -35,7 +35,7 @@ class SimpleOzoneCPU(BaseCPU):
 
     numThreads = Param.Unsigned("number of HW thread contexts")
 
-    if not build_env['FULL_SYSTEM']:
+    if not buildEnv['FULL_SYSTEM']:
         mem = Param.FunctionalMemory(NULL, "memory")
 
     width = Param.Unsigned("Width")
index b7174bb4396d7cee11404297e3a8fd7283c9c4dc..3d72f4098fe66d3eb61e338b159868421e0ac42b 100644 (file)
@@ -27,7 +27,6 @@
 # Authors: Nathan Binkert
 
 from m5.params import *
-from m5 import build_env
 from BaseSimpleCPU import BaseSimpleCPU
 
 class AtomicSimpleCPU(BaseSimpleCPU):
index ce6839241116fb14735dfcfda64015a7a2aea7ad..6b83c41aafe0243a5854de10a330e4e5bdc68253 100644 (file)
@@ -27,7 +27,6 @@
 # Authors: Nathan Binkert
 
 from m5.params import *
-from m5 import build_env
 from BaseSimpleCPU import BaseSimpleCPU
 
 class TimingSimpleCPU(BaseSimpleCPU):
index 5135a064d8efded0430dcf0f6f5e8d0c643d1ade..9254dc695e3d40303a22275b48e29f0060b33470 100644 (file)
@@ -28,7 +28,6 @@
 
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
 from Device import BasicPioDevice
 
 class Uart(BasicPioDevice):
index 0f113cc09de2729c5d4b7ea98bb367d1b1d8647e..b3f6b29463579ba01d562971cc4494ead278e00c 100644 (file)
 #
 # Authors: Nathan Binkert
 
-from m5 import build_env
+from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
 from MemObject import MemObject
 
-if build_env['FULL_SYSTEM']:
+if buildEnv['FULL_SYSTEM']:
     from Device import BadAddr
 
 class Bus(MemObject):
index bb892f3765dffbbd759eecaaceda46a5e7285877..935986a12f72e40175e8c11249e49c111c8948f0 100644 (file)
@@ -38,7 +38,6 @@ PySource('', 'importer.py')
 PySource('m5', 'm5/__init__.py')
 PySource('m5', 'm5/SimObject.py')
 PySource('m5', 'm5/config.py')
-PySource('m5', 'm5/convert.py')
 PySource('m5', 'm5/core.py')
 PySource('m5', 'm5/debug.py')
 PySource('m5', 'm5/event.py')
@@ -47,18 +46,18 @@ PySource('m5', 'm5/options.py')
 PySource('m5', 'm5/params.py')
 PySource('m5', 'm5/proxy.py')
 PySource('m5', 'm5/simulate.py')
-PySource('m5', 'm5/smartdict.py')
 PySource('m5', 'm5/stats.py')
 PySource('m5', 'm5/ticks.py')
 PySource('m5', 'm5/trace.py')
 PySource('m5.util', 'm5/util/__init__.py')
 PySource('m5.util', 'm5/util/attrdict.py')
 PySource('m5.util', 'm5/util/code_formatter.py')
+PySource('m5.util', 'm5/util/convert.py')
 PySource('m5.util', 'm5/util/grammar.py')
 PySource('m5.util', 'm5/util/jobfile.py')
-PySource('m5.util', 'm5/util/misc.py')
 PySource('m5.util', 'm5/util/multidict.py')
 PySource('m5.util', 'm5/util/orderdict.py')
+PySource('m5.util', 'm5/util/smartdict.py')
 
 SwigSource('m5.internal', 'swig/core.i')
 SwigSource('m5.internal', 'swig/debug.i')
index 8ef22be4e3f43438f04da55a9a9ed4526b2ef88e..0e0ffaea98efb417175eaf33b97c09536689dc3a 100644 (file)
@@ -31,47 +31,24 @@ import math
 import sys
 import types
 
-import proxy
-import m5
-from util import *
-
-# These utility functions have to come first because they're
-# referenced in params.py... otherwise they won't be defined when we
-# import params below, and the recursive import of this file from
-# params.py will not find these names.
-def isSimObject(value):
-    return isinstance(value, SimObject)
-
-def isSimObjectClass(value):
-    return issubclass(value, SimObject)
-
-def isSimObjectSequence(value):
-    if not isinstance(value, (list, tuple)) or len(value) == 0:
-        return False
-
-    for val in value:
-        if not isNullPointer(val) and not isSimObject(val):
-            return False
-
-    return True
+try:
+    import pydot
+except:
+    pydot = False
 
-def isSimObjectOrSequence(value):
-    return isSimObject(value) or isSimObjectSequence(value)
+import m5
+from m5.util import *
 
 # Have to import params up top since Param is referenced on initial
 # load (when SimObject class references Param to create a class
 # variable, the 'name' param)...
-from params import *
+from m5.params import *
 # There are a few things we need that aren't in params.__all__ since
 # normal users don't need them
-from params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
-from proxy import *
+from m5.params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
 
-noDot = False
-try:
-    import pydot
-except:
-    noDot = True
+from m5.proxy import *
+from m5.proxy import isproxy
 
 #####################################################################
 #
@@ -141,7 +118,7 @@ class MetaSimObject(type):
     # and only allow "private" attributes to be passed to the base
     # __new__ (starting with underscore).
     def __new__(mcls, name, bases, dict):
-        assert name not in allClasses
+        assert name not in allClasses, "SimObject %s already present" % name
 
         # Copy "private" attributes, functions, and classes to the
         # official dict.  Everything else goes in _init_dict to be
@@ -678,7 +655,7 @@ class SimObject(object):
     def unproxy_all(self):
         for param in self._params.iterkeys():
             value = self._values.get(param)
-            if value != None and proxy.isproxy(value):
+            if value != None and isproxy(value):
                 try:
                     value = value.unproxy(self)
                 except:
@@ -749,8 +726,8 @@ class SimObject(object):
         for param in param_names:
             value = self._values.get(param)
             if value is None:
-                m5.fatal("%s.%s without default or user set value",
-                        self.path(), param)
+                fatal("%s.%s without default or user set value",
+                      self.path(), param)
 
             value = value.getValue()
             if isinstance(self._params[param], VectorParamDesc):
@@ -886,6 +863,34 @@ def resolveSimObject(name):
     obj = instanceDict[name]
     return obj.getCCObject()
 
+def isSimObject(value):
+    return isinstance(value, SimObject)
+
+def isSimObjectClass(value):
+    return issubclass(value, SimObject)
+
+def isSimObjectSequence(value):
+    if not isinstance(value, (list, tuple)) or len(value) == 0:
+        return False
+
+    for val in value:
+        if not isNullPointer(val) and not isSimObject(val):
+            return False
+
+    return True
+
+def isSimObjectOrSequence(value):
+    return isSimObject(value) or isSimObjectSequence(value)
+
+baseClasses = allClasses.copy()
+baseInstances = instanceDict.copy()
+
+def clear():
+    global allClasses, instanceDict
+
+    allClasses = baseClasses.copy()
+    instanceDict = baseInstances.copy()
+
 # __all__ defines the list of symbols that get exported when
 # 'from config import *' is invoked.  Try to keep this reasonably
 # short to avoid polluting other namespaces.
index c3512cd0dd39d1a506375098b8763571ab09e086..9f9459ae8b80b8dd8253cfadb7d19a7d8e5870d0 100644 (file)
 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 #
 # Authors: Nathan Binkert
-#          Steve Reinhardt
 
-import os
-import sys
+# Import useful subpackages of M5, but *only* when run as an m5
+# script.  This is mostly to keep backward compatibility with existing
+# scripts while allowing new SCons code to operate properly.
 
-import smartdict
-
-# define a MaxTick parameter
-MaxTick = 2**63 - 1
-
-# define this here so we can use it right away if necessary
-
-def errorURL(prefix, s):
-    try:
-        import zlib
-        hashstr = "%x" % zlib.crc32(s)
-    except:
-        hashstr = "UnableToHash"
-    return "For more information see: http://www.m5sim.org/%s/%s" % \
-            (prefix, hashstr)
-
-
-# panic() should be called when something happens that should never
-# ever happen regardless of what the user does (i.e., an acutal m5
-# bug).
-def panic(fmt, *args):
-    print >>sys.stderr, 'panic:', fmt % args
-    print >>sys.stderr, errorURL('panic',fmt)
-    sys.exit(1)
-
-# fatal() should be called when the simulation cannot continue due to
-# some condition that is the user's fault (bad configuration, invalid
-# arguments, etc.) and not a simulator bug.
-def fatal(fmt, *args):
-    print >>sys.stderr, 'fatal:', fmt % args
-    print >>sys.stderr, errorURL('fatal',fmt)
-    sys.exit(1)
-
-# force scalars to one-element lists for uniformity
-def makeList(objOrList):
-    if isinstance(objOrList, list):
-        return objOrList
-    return [objOrList]
-
-# Prepend given directory to system module search path.  We may not
-# need this anymore if we can structure our config library more like a
-# Python package.
-def AddToPath(path):
-    # if it's a relative path and we know what directory the current
-    # python script is in, make the path relative to that directory.
-    if not os.path.isabs(path) and sys.path[0]:
-        path = os.path.join(sys.path[0], path)
-    path = os.path.realpath(path)
-    # sys.path[0] should always refer to the current script's directory,
-    # so place the new dir right after that.
-    sys.path.insert(1, path)
-
-# make a SmartDict out of the build options for our local use
-build_env = smartdict.SmartDict()
-
-# make a SmartDict out of the OS environment too
-env = smartdict.SmartDict()
-env.update(os.environ)
-
-# Since we have so many mutual imports in this package, we should:
-# 1. Put all intra-package imports at the *bottom* of the file, unless
-#    they're absolutely needed before that (for top-level statements
-#    or class attributes).  Imports of "trivial" packages that don't
-#    import other packages (e.g., 'smartdict') can be at the top.
-# 2. Never use 'from foo import *' on an intra-package import since
-#    you can get the wrong result if foo is only partially imported
-#    at the point you do that (i.e., because foo is in the middle of
-#    importing *you*).
 try:
     import internal
 except ImportError:
     internal = None
 
-try:
-    import defines
-    build_env.update(defines.buildEnv)
-except ImportError:
-    defines = None
-
 if internal:
-    defines.compileDate = internal.core.compileDate
-    for k,v in internal.core.__dict__.iteritems():
-        if k.startswith('flag_'):
-            setattr(defines, k[5:], v)
+    import SimObject
+    import core
+    import objects
+    import params
+    import stats
+    import util
 
     from event import *
-    from simulate import *
     from main import options, main
-    import stats
-    import core
-
-import SimObject
-import params
-
-try:
-    import objects
-except ImportError:
-    objects = None
+    from simulate import *
diff --git a/src/python/m5/convert.py b/src/python/m5/convert.py
deleted file mode 100644 (file)
index bb9e3e1..0000000
+++ /dev/null
@@ -1,250 +0,0 @@
-# Copyright (c) 2005 The Regents of The University of Michigan
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met: redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer;
-# redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution;
-# neither the name of the copyright holders nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Authors: Nathan Binkert
-
-# metric prefixes
-exa  = 1.0e18
-peta = 1.0e15
-tera = 1.0e12
-giga = 1.0e9
-mega = 1.0e6
-kilo = 1.0e3
-
-milli = 1.0e-3
-micro = 1.0e-6
-nano  = 1.0e-9
-pico  = 1.0e-12
-femto = 1.0e-15
-atto  = 1.0e-18
-
-# power of 2 prefixes
-kibi = 1024
-mebi = kibi * 1024
-gibi = mebi * 1024
-tebi = gibi * 1024
-pebi = tebi * 1024
-exbi = pebi * 1024
-
-# memory size configuration stuff
-def toFloat(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    if value.endswith('Ei'):
-        return float(value[:-2]) * exbi
-    elif value.endswith('Pi'):
-        return float(value[:-2]) * pebi
-    elif value.endswith('Ti'):
-        return float(value[:-2]) * tebi
-    elif value.endswith('Gi'):
-        return float(value[:-2]) * gibi
-    elif value.endswith('Mi'):
-        return float(value[:-2]) * mebi
-    elif value.endswith('ki'):
-        return float(value[:-2]) * kibi
-    elif value.endswith('E'):
-        return float(value[:-1]) * exa
-    elif value.endswith('P'):
-        return float(value[:-1]) * peta
-    elif value.endswith('T'):
-        return float(value[:-1]) * tera
-    elif value.endswith('G'):
-        return float(value[:-1]) * giga
-    elif value.endswith('M'):
-        return float(value[:-1]) * mega
-    elif value.endswith('k'):
-        return float(value[:-1]) * kilo
-    elif value.endswith('m'):
-        return float(value[:-1]) * milli
-    elif value.endswith('u'):
-        return float(value[:-1]) * micro
-    elif value.endswith('n'):
-        return float(value[:-1]) * nano
-    elif value.endswith('p'):
-        return float(value[:-1]) * pico
-    elif value.endswith('f'):
-        return float(value[:-1]) * femto
-    else:
-        return float(value)
-
-def toInteger(value):
-    value = toFloat(value)
-    result = long(value)
-    if value != result:
-        raise ValueError, "cannot convert '%s' to integer" % value
-
-    return result
-
-_bool_dict = {
-    'true' : True,   't' : True,  'yes' : True, 'y' : True,  '1' : True,
-    'false' : False, 'f' : False, 'no' : False, 'n' : False, '0' : False
-    }
-
-def toBool(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    value = value.lower()
-    result = _bool_dict.get(value, None)
-    if result == None:
-        raise ValueError, "cannot convert '%s' to bool" % value
-    return result
-
-def toFrequency(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    if value.endswith('THz'):
-        return float(value[:-3]) * tera
-    elif value.endswith('GHz'):
-        return float(value[:-3]) * giga
-    elif value.endswith('MHz'):
-        return float(value[:-3]) * mega
-    elif value.endswith('kHz'):
-        return float(value[:-3]) * kilo
-    elif value.endswith('Hz'):
-        return float(value[:-2])
-
-    raise ValueError, "cannot convert '%s' to frequency" % value
-
-def toLatency(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    if value.endswith('ps'):
-        return float(value[:-2]) * pico
-    elif value.endswith('ns'):
-        return float(value[:-2]) * nano
-    elif value.endswith('us'):
-        return float(value[:-2]) * micro
-    elif value.endswith('ms'):
-        return float(value[:-2]) * milli
-    elif value.endswith('s'):
-        return float(value[:-1])
-
-    raise ValueError, "cannot convert '%s' to latency" % value
-
-def anyToLatency(value):
-    """result is a clock period"""
-
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    try:
-        val = toFrequency(value)
-        if val != 0:
-            val = 1 / val
-        return val
-    except ValueError:
-        pass
-
-    try:
-        val = toLatency(value)
-        return val
-    except ValueError:
-        pass
-
-    raise ValueError, "cannot convert '%s' to clock period" % value
-
-def anyToFrequency(value):
-    """result is a clock period"""
-
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    try:
-        val = toFrequency(value)
-        return val
-    except ValueError:
-        pass
-
-    try:
-        val = toLatency(value)
-        if val != 0:
-            val = 1 / val
-        return val
-    except ValueError:
-        pass
-
-    raise ValueError, "cannot convert '%s' to clock period" % value
-
-def toNetworkBandwidth(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    if value.endswith('Tbps'):
-        return float(value[:-4]) * tera
-    elif value.endswith('Gbps'):
-        return float(value[:-4]) * giga
-    elif value.endswith('Mbps'):
-        return float(value[:-4]) * mega
-    elif value.endswith('kbps'):
-        return float(value[:-4]) * kilo
-    elif value.endswith('bps'):
-        return float(value[:-3])
-    else:
-        return float(value)
-
-    raise ValueError, "cannot convert '%s' to network bandwidth" % value
-
-def toMemoryBandwidth(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    if value.endswith('PB/s'):
-        return float(value[:-4]) * pebi
-    elif value.endswith('TB/s'):
-        return float(value[:-4]) * tebi
-    elif value.endswith('GB/s'):
-        return float(value[:-4]) * gibi
-    elif value.endswith('MB/s'):
-        return float(value[:-4]) * mebi
-    elif value.endswith('kB/s'):
-        return float(value[:-4]) * kibi
-    elif value.endswith('B/s'):
-        return float(value[:-3])
-
-    raise ValueError, "cannot convert '%s' to memory bandwidth" % value
-
-def toMemorySize(value):
-    if not isinstance(value, str):
-        raise TypeError, "wrong type '%s' should be str" % type(value)
-
-    if value.endswith('PB'):
-        return long(value[:-2]) * pebi
-    elif value.endswith('TB'):
-        return long(value[:-2]) * tebi
-    elif value.endswith('GB'):
-        return long(value[:-2]) * gibi
-    elif value.endswith('MB'):
-        return long(value[:-2]) * mebi
-    elif value.endswith('kB'):
-        return long(value[:-2]) * kibi
-    elif value.endswith('B'):
-        return long(value[:-1])
-
-    raise ValueError, "cannot convert '%s' to memory size" % value
diff --git a/src/python/m5/environment.py b/src/python/m5/environment.py
deleted file mode 100644 (file)
index bea0bc1..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) 2005 The Regents of The University of Michigan
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met: redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer;
-# redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution;
-# neither the name of the copyright holders nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Authors: Nathan Binkert
-#          Steve Reinhardt
-
-import os
-
-# import the m5 compile options
-import defines
-
-# make a SmartDict out of the build options for our local use
-import smartdict
-build_env = smartdict.SmartDict()
-build_env.update(defines.m5_build_env)
-
-# make a SmartDict out of the OS environment too
-env = smartdict.SmartDict()
-env.update(os.environ)
-
index 2a308ff09f21363d9fcd968c566db7355c1f9da6..29f8cc9764fcac4d05006ed1de127ccaec8e4f00 100644 (file)
@@ -32,7 +32,7 @@ import os
 import socket
 import sys
 
-from util import attrdict
+from util import attrdict, fatal
 import config
 from options import OptionParser
 
index edd78fa28818a7b6708ffb7077fb86b4ced3ce57..3a3a300148219ab24f69c624504a6cd97787c4e8 100644 (file)
@@ -50,13 +50,10 @@ import re
 import sys
 import time
 
-import convert
 import proxy
 import ticks
 from util import *
 
-import SimObject
-
 def isSimObject(*args, **kwargs):
     return SimObject.isSimObject(*args, **kwargs)
 
@@ -711,32 +708,31 @@ class MetaEnum(MetaParamValue):
 
         super(MetaEnum, cls).__init__(name, bases, init_dict)
 
-    def __str__(cls):
-        return cls.__name__
-
     # Generate C++ class declaration for this enum type.
     # Note that we wrap the enum in a class/struct to act as a namespace,
     # so that the enum strings can be brief w/o worrying about collisions.
     def cxx_decl(cls):
-        code = "#ifndef __ENUM__%s\n" % cls
-        code += '#define __ENUM__%s\n' % cls
+        name = cls.__name__
+        code = "#ifndef __ENUM__%s\n" % name
+        code += '#define __ENUM__%s\n' % name
         code += '\n'
         code += 'namespace Enums {\n'
-        code += '    enum %s {\n' % cls
+        code += '    enum %s {\n' % name
         for val in cls.vals:
             code += '        %s = %d,\n' % (val, cls.map[val])
-        code += '        Num_%s = %d,\n' % (cls, len(cls.vals))
+        code += '        Num_%s = %d,\n' % (name, len(cls.vals))
         code += '    };\n'
-        code += '    extern const char *%sStrings[Num_%s];\n' % (cls, cls)
+        code += '    extern const char *%sStrings[Num_%s];\n' % (name, name)
         code += '}\n'
         code += '\n'
         code += '#endif\n'
         return code
 
     def cxx_def(cls):
-        code = '#include "enums/%s.hh"\n' % cls
+        name = cls.__name__
+        code = '#include "enums/%s.hh"\n' % name
         code += 'namespace Enums {\n'
-        code += '    const char *%sStrings[Num_%s] =\n' % (cls, cls)
+        code += '    const char *%sStrings[Num_%s] =\n' % (name, name)
         code += '    {\n'
         for val in cls.vals:
             code += '        "%s",\n' % val
@@ -1170,6 +1166,15 @@ class PortParamDesc(object):
     ptype_str = 'Port'
     ptype = Port
 
+baseEnums = allEnums.copy()
+baseParams = allParams.copy()
+
+def clear():
+    global allEnums, allParams
+
+    allEnums = baseEnums.copy()
+    allParams = baseParams.copy()
+
 __all__ = ['Param', 'VectorParam',
            'Enum', 'Bool', 'String', 'Float',
            'Int', 'Unsigned', 'Int8', 'UInt8', 'Int16', 'UInt16',
@@ -1184,3 +1189,5 @@ __all__ = ['Param', 'VectorParam',
            'Time',
            'NextEthernetAddr', 'NULL',
            'Port', 'VectorPort']
+
+import SimObject
index 45992fe85ecf8893fbdf3cd5bf478a981c8e6e71..092bd03395dab12c431689333ada813c42e10cca 100644 (file)
@@ -40,6 +40,9 @@ import SimObject
 import ticks
 import objects
 
+# define a MaxTick parameter
+MaxTick = 2**63 - 1
+
 # The final hook to generate .ini files.  Called from the user script
 # once the config is built.
 def instantiate(root):
diff --git a/src/python/m5/smartdict.py b/src/python/m5/smartdict.py
deleted file mode 100644 (file)
index d85dbd5..0000000
+++ /dev/null
@@ -1,154 +0,0 @@
-# Copyright (c) 2005 The Regents of The University of Michigan
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met: redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer;
-# redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution;
-# neither the name of the copyright holders nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Authors: Nathan Binkert
-
-# The SmartDict class fixes a couple of issues with using the content
-# of os.environ or similar dicts of strings as Python variables:
-#
-# 1) Undefined variables should return False rather than raising KeyError.
-#
-# 2) String values of 'False', '0', etc., should evaluate to False
-#    (not just the empty string).
-#
-# #1 is solved by overriding __getitem__, and #2 is solved by using a
-# proxy class for values and overriding __nonzero__ on the proxy.
-# Everything else is just to (a) make proxies behave like normal
-# values otherwise, (b) make sure any dict operation returns a proxy
-# rather than a normal value, and (c) coerce values written to the
-# dict to be strings.
-
-
-from convert import *
-
-class Variable(str):
-    """Intelligent proxy class for SmartDict.  Variable will use the
-    various convert functions to attempt to convert values to useable
-    types"""
-    def __int__(self):
-        return toInteger(str(self))
-    def __long__(self):
-        return toLong(str(self))
-    def __float__(self):
-        return toFloat(str(self))
-    def __nonzero__(self):
-        return toBool(str(self))
-    def convert(self, other):
-        t = type(other)
-        if t == bool:
-            return bool(self)
-        if t == int:
-            return int(self)
-        if t == long:
-            return long(self)
-        if t == float:
-            return float(self)
-        return str(self)
-    def __lt__(self, other):
-        return self.convert(other) < other
-    def __le__(self, other):
-        return self.convert(other) <= other
-    def __eq__(self, other):
-        return self.convert(other) == other
-    def __ne__(self, other):
-        return self.convert(other) != other
-    def __gt__(self, other):
-        return self.convert(other) > other
-    def __ge__(self, other):
-        return self.convert(other) >= other
-
-    def __add__(self, other):
-        return self.convert(other) + other
-    def __sub__(self, other):
-        return self.convert(other) - other
-    def __mul__(self, other):
-        return self.convert(other) * other
-    def __div__(self, other):
-        return self.convert(other) / other
-    def __truediv__(self, other):
-        return self.convert(other) / other
-
-    def __radd__(self, other):
-        return other + self.convert(other)
-    def __rsub__(self, other):
-        return other - self.convert(other)
-    def __rmul__(self, other):
-        return other * self.convert(other)
-    def __rdiv__(self, other):
-        return other / self.convert(other)
-    def __rtruediv__(self, other):
-        return other / self.convert(other)
-
-class UndefinedVariable(object):
-    """Placeholder class to represent undefined variables.  Will
-    generally cause an exception whenever it is used, but evaluates to
-    zero for boolean truth testing such as in an if statement"""
-    def __nonzero__(self):
-        return False
-
-class SmartDict(dict):
-    """Dictionary class that holds strings, but intelligently converts
-    those strings to other types depending on their usage"""
-
-    def __getitem__(self, key):
-        """returns a Variable proxy if the values exists in the database and
-        returns an UndefinedVariable otherwise"""
-
-        if key in self:
-            return Variable(dict.get(self, key))
-        else:
-            # Note that this does *not* change the contents of the dict,
-            # so that even after we call env['foo'] we still get a
-            # meaningful answer from "'foo' in env" (which
-            # calls dict.__contains__, which we do not override).
-            return UndefinedVariable()
-
-    def __setitem__(self, key, item):
-        """intercept the setting of any variable so that we always
-        store strings in the dict"""
-        dict.__setitem__(self, key, str(item))
-
-    def values(self):
-        return [ Variable(v) for v in dict.values(self) ]
-
-    def itervalues(self):
-        for value in dict.itervalues(self):
-            yield Variable(value)
-
-    def items(self):
-        return [ (k, Variable(v)) for k,v in dict.items(self) ]
-
-    def iteritems(self):
-        for key,value in dict.iteritems(self):
-            yield key, Variable(value)
-
-    def get(self, key, default='False'):
-        return Variable(dict.get(self, key, str(default)))
-
-    def setdefault(self, key, default='False'):
-        return Variable(dict.setdefault(self, key, str(default)))
-
-__all__ = [ 'SmartDict' ]
index 91834c9c8809ee426b8346d0f4deddc6d8b06973..181a65eba68c7e7e01da9e499cbca805b83db87d 100644 (file)
@@ -41,7 +41,7 @@ def fixGlobalFrequency():
         print "Global frequency set at %d ticks per second" % int(tps)
 
 def setGlobalFrequency(ticksPerSecond):
-    import convert
+    from m5.util import convert
 
     global tps, tps_fixed
 
index 17aa6196c8764bdb29af90277dea63599c64c8ef..db239040ab3b23af935f48291a544292f82e010b 100644 (file)
@@ -48,5 +48,5 @@ def help():
         if flag == 'All':
             continue
         print "    %s: %s" % (flag, flags.descriptions[flag])
-        util.print_list(flags.compoundMap[flag], indent=8)
+        util.printList(flags.compoundMap[flag], indent=8)
         print
index 3930c8b6f459deaab9df330b6ab80b92525bfd46..7a674dd2dd670586604d4dd222fd6d8dd2a2eb1a 100644 (file)
@@ -1,4 +1,5 @@
-# Copyright (c) 2008 The Hewlett-Packard Development Company
+# Copyright (c) 2008-2009 The Hewlett-Packard Development Company
+# Copyright (c) 2004-2006 The Regents of The University of Michigan
 # All rights reserved.
 #
 # Redistribution and use in source and binary forms, with or without
 #
 # Authors: Nathan Binkert
 
+import os
+import re
+import sys
+
+import convert
+import jobfile
+
 from attrdict import attrdict, optiondict
 from code_formatter import code_formatter
-from misc import *
 from multidict import multidict
 from orderdict import orderdict
-import jobfile
+from smartdict import SmartDict
+
+# define this here so we can use it right away if necessary
+def errorURL(prefix, s):
+    try:
+        import zlib
+        hashstr = "%x" % zlib.crc32(s)
+    except:
+        hashstr = "UnableToHash"
+    return "For more information see: http://www.m5sim.org/%s/%s" % \
+            (prefix, hashstr)
+
+# panic() should be called when something happens that should never
+# ever happen regardless of what the user does (i.e., an acutal m5
+# bug).
+def panic(fmt, *args):
+    print >>sys.stderr, 'panic:', fmt % args
+    print >>sys.stderr, errorURL('panic',fmt)
+    sys.exit(1)
+
+# fatal() should be called when the simulation cannot continue due to
+# some condition that is the user's fault (bad configuration, invalid
+# arguments, etc.) and not a simulator bug.
+def fatal(fmt, *args):
+    print >>sys.stderr, 'fatal:', fmt % args
+    print >>sys.stderr, errorURL('fatal',fmt)
+    sys.exit(1)
+
+class Singleton(type):
+    def __call__(cls, *args, **kwargs):
+        if hasattr(cls, '_instance'):
+            return cls._instance
+
+        cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
+        return cls._instance
+
+def addToPath(path):
+    """Prepend given directory to system module search path.  We may not
+    need this anymore if we can structure our config library more like a
+    Python package."""
+
+    # if it's a relative path and we know what directory the current
+    # python script is in, make the path relative to that directory.
+    if not os.path.isabs(path) and sys.path[0]:
+        path = os.path.join(sys.path[0], path)
+    path = os.path.realpath(path)
+    # sys.path[0] should always refer to the current script's directory,
+    # so place the new dir right after that.
+    sys.path.insert(1, path)
+
+# Apply method to object.
+# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
+def applyMethod(obj, meth, *args, **kwargs):
+    return getattr(obj, meth)(*args, **kwargs)
 
-def print_list(items, indent=4):
+# If the first argument is an (non-sequence) object, apply the named
+# method with the given arguments.  If the first argument is a
+# sequence, apply the method to each element of the sequence (a la
+# 'map').
+def applyOrMap(objOrSeq, meth, *args, **kwargs):
+    if not isinstance(objOrSeq, (list, tuple)):
+        return applyMethod(objOrSeq, meth, *args, **kwargs)
+    else:
+        return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq]
+
+def compareVersions(v1, v2):
+    """helper function: compare arrays or strings of version numbers.
+    E.g., compare_version((1,3,25), (1,4,1)')
+    returns -1, 0, 1 if v1 is <, ==, > v2
+    """
+    def make_version_list(v):
+        if isinstance(v, (list,tuple)):
+            return v
+        elif isinstance(v, str):
+            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
+        else:
+            raise TypeError
+
+    v1 = make_version_list(v1)
+    v2 = make_version_list(v2)
+    # Compare corresponding elements of lists
+    for n1,n2 in zip(v1, v2):
+        if n1 < n2: return -1
+        if n1 > n2: return  1
+    # all corresponding values are equal... see if one has extra values
+    if len(v1) < len(v2): return -1
+    if len(v1) > len(v2): return  1
+    return 0
+
+def crossproduct(items):
+    if len(items) == 1:
+        for i in items[0]:
+            yield (i,)
+    else:
+        for i in items[0]:
+            for j in crossproduct(items[1:]):
+                yield (i,) + j
+
+def flatten(items):
+    while items:
+        item = items.pop(0)
+        if isinstance(item, (list, tuple)):
+            items[0:0] = item
+        else:
+            yield item
+
+# force scalars to one-element lists for uniformity
+def makeList(objOrList):
+    if isinstance(objOrList, list):
+        return objOrList
+    return [objOrList]
+
+def printList(items, indent=4):
     line = ' ' * indent
     for i,item in enumerate(items):
         if len(line) + len(item) > 76:
@@ -45,3 +162,27 @@ def print_list(items, indent=4):
         else:
             line += item
             print line
+
+def readCommand(cmd, **kwargs):
+    """run the command cmd, read the results and return them
+    this is sorta like `cmd` in shell"""
+    from subprocess import Popen, PIPE, STDOUT
+
+    if isinstance(cmd, str):
+        cmd = cmd.split()
+
+    no_exception = 'exception' in kwargs
+    exception = kwargs.pop('exception', None)
+    
+    kwargs.setdefault('shell', False)
+    kwargs.setdefault('stdout', PIPE)
+    kwargs.setdefault('stderr', STDOUT)
+    kwargs.setdefault('close_fds', True)
+    try:
+        subp = Popen(cmd, **kwargs)
+    except Exception, e:
+        if no_exception:
+            return exception
+        raise
+
+    return subp.communicate()[0]
diff --git a/src/python/m5/util/convert.py b/src/python/m5/util/convert.py
new file mode 100644 (file)
index 0000000..bb9e3e1
--- /dev/null
@@ -0,0 +1,250 @@
+# Copyright (c) 2005 The Regents of The University of Michigan
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met: redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer;
+# redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution;
+# neither the name of the copyright holders nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Authors: Nathan Binkert
+
+# metric prefixes
+exa  = 1.0e18
+peta = 1.0e15
+tera = 1.0e12
+giga = 1.0e9
+mega = 1.0e6
+kilo = 1.0e3
+
+milli = 1.0e-3
+micro = 1.0e-6
+nano  = 1.0e-9
+pico  = 1.0e-12
+femto = 1.0e-15
+atto  = 1.0e-18
+
+# power of 2 prefixes
+kibi = 1024
+mebi = kibi * 1024
+gibi = mebi * 1024
+tebi = gibi * 1024
+pebi = tebi * 1024
+exbi = pebi * 1024
+
+# memory size configuration stuff
+def toFloat(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    if value.endswith('Ei'):
+        return float(value[:-2]) * exbi
+    elif value.endswith('Pi'):
+        return float(value[:-2]) * pebi
+    elif value.endswith('Ti'):
+        return float(value[:-2]) * tebi
+    elif value.endswith('Gi'):
+        return float(value[:-2]) * gibi
+    elif value.endswith('Mi'):
+        return float(value[:-2]) * mebi
+    elif value.endswith('ki'):
+        return float(value[:-2]) * kibi
+    elif value.endswith('E'):
+        return float(value[:-1]) * exa
+    elif value.endswith('P'):
+        return float(value[:-1]) * peta
+    elif value.endswith('T'):
+        return float(value[:-1]) * tera
+    elif value.endswith('G'):
+        return float(value[:-1]) * giga
+    elif value.endswith('M'):
+        return float(value[:-1]) * mega
+    elif value.endswith('k'):
+        return float(value[:-1]) * kilo
+    elif value.endswith('m'):
+        return float(value[:-1]) * milli
+    elif value.endswith('u'):
+        return float(value[:-1]) * micro
+    elif value.endswith('n'):
+        return float(value[:-1]) * nano
+    elif value.endswith('p'):
+        return float(value[:-1]) * pico
+    elif value.endswith('f'):
+        return float(value[:-1]) * femto
+    else:
+        return float(value)
+
+def toInteger(value):
+    value = toFloat(value)
+    result = long(value)
+    if value != result:
+        raise ValueError, "cannot convert '%s' to integer" % value
+
+    return result
+
+_bool_dict = {
+    'true' : True,   't' : True,  'yes' : True, 'y' : True,  '1' : True,
+    'false' : False, 'f' : False, 'no' : False, 'n' : False, '0' : False
+    }
+
+def toBool(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    value = value.lower()
+    result = _bool_dict.get(value, None)
+    if result == None:
+        raise ValueError, "cannot convert '%s' to bool" % value
+    return result
+
+def toFrequency(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    if value.endswith('THz'):
+        return float(value[:-3]) * tera
+    elif value.endswith('GHz'):
+        return float(value[:-3]) * giga
+    elif value.endswith('MHz'):
+        return float(value[:-3]) * mega
+    elif value.endswith('kHz'):
+        return float(value[:-3]) * kilo
+    elif value.endswith('Hz'):
+        return float(value[:-2])
+
+    raise ValueError, "cannot convert '%s' to frequency" % value
+
+def toLatency(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    if value.endswith('ps'):
+        return float(value[:-2]) * pico
+    elif value.endswith('ns'):
+        return float(value[:-2]) * nano
+    elif value.endswith('us'):
+        return float(value[:-2]) * micro
+    elif value.endswith('ms'):
+        return float(value[:-2]) * milli
+    elif value.endswith('s'):
+        return float(value[:-1])
+
+    raise ValueError, "cannot convert '%s' to latency" % value
+
+def anyToLatency(value):
+    """result is a clock period"""
+
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    try:
+        val = toFrequency(value)
+        if val != 0:
+            val = 1 / val
+        return val
+    except ValueError:
+        pass
+
+    try:
+        val = toLatency(value)
+        return val
+    except ValueError:
+        pass
+
+    raise ValueError, "cannot convert '%s' to clock period" % value
+
+def anyToFrequency(value):
+    """result is a clock period"""
+
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    try:
+        val = toFrequency(value)
+        return val
+    except ValueError:
+        pass
+
+    try:
+        val = toLatency(value)
+        if val != 0:
+            val = 1 / val
+        return val
+    except ValueError:
+        pass
+
+    raise ValueError, "cannot convert '%s' to clock period" % value
+
+def toNetworkBandwidth(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    if value.endswith('Tbps'):
+        return float(value[:-4]) * tera
+    elif value.endswith('Gbps'):
+        return float(value[:-4]) * giga
+    elif value.endswith('Mbps'):
+        return float(value[:-4]) * mega
+    elif value.endswith('kbps'):
+        return float(value[:-4]) * kilo
+    elif value.endswith('bps'):
+        return float(value[:-3])
+    else:
+        return float(value)
+
+    raise ValueError, "cannot convert '%s' to network bandwidth" % value
+
+def toMemoryBandwidth(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    if value.endswith('PB/s'):
+        return float(value[:-4]) * pebi
+    elif value.endswith('TB/s'):
+        return float(value[:-4]) * tebi
+    elif value.endswith('GB/s'):
+        return float(value[:-4]) * gibi
+    elif value.endswith('MB/s'):
+        return float(value[:-4]) * mebi
+    elif value.endswith('kB/s'):
+        return float(value[:-4]) * kibi
+    elif value.endswith('B/s'):
+        return float(value[:-3])
+
+    raise ValueError, "cannot convert '%s' to memory bandwidth" % value
+
+def toMemorySize(value):
+    if not isinstance(value, str):
+        raise TypeError, "wrong type '%s' should be str" % type(value)
+
+    if value.endswith('PB'):
+        return long(value[:-2]) * pebi
+    elif value.endswith('TB'):
+        return long(value[:-2]) * tebi
+    elif value.endswith('GB'):
+        return long(value[:-2]) * gibi
+    elif value.endswith('MB'):
+        return long(value[:-2]) * mebi
+    elif value.endswith('kB'):
+        return long(value[:-2]) * kibi
+    elif value.endswith('B'):
+        return long(value[:-1])
+
+    raise ValueError, "cannot convert '%s' to memory size" % value
index c830895f675d355ea612e87bf9b87d0bacf715b1..9c59778e5416a1bef9f40589f24a136e1253884f 100644 (file)
@@ -28,9 +28,6 @@
 
 import sys
 
-from attrdict import optiondict
-from misc import crossproduct
-
 class Data(object):
     def __init__(self, name, desc, **kwargs):
         self.name = name
@@ -108,7 +105,8 @@ class Data(object):
                 yield key
 
     def optiondict(self):
-        result = optiondict()
+        import m5.util
+        result = m5.util.optiondict()
         for key in self:
             result[key] = self[key]
         return result
@@ -328,7 +326,9 @@ class Configuration(Data):
             optgroups = [ g.subopts() for g in groups ]
         if not optgroups:
             return
-        for options in crossproduct(optgroups):
+
+        import m5.util
+        for options in m5.util.crossproduct(optgroups):
             for opt in options:
                 cpt = opt._group._checkpoint
                 if not isinstance(cpt, bool) and cpt != opt:
diff --git a/src/python/m5/util/misc.py b/src/python/m5/util/misc.py
deleted file mode 100644 (file)
index 094e3ed..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-# Copyright (c) 2004-2006 The Regents of The University of Michigan
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met: redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer;
-# redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution;
-# neither the name of the copyright holders nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Authors: Steve Reinhardt
-#          Nathan Binkert
-
-#############################
-#
-# Utility classes & methods
-#
-#############################
-
-class Singleton(type):
-    def __call__(cls, *args, **kwargs):
-        if hasattr(cls, '_instance'):
-            return cls._instance
-
-        cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
-        return cls._instance
-
-# Apply method to object.
-# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
-def applyMethod(obj, meth, *args, **kwargs):
-    return getattr(obj, meth)(*args, **kwargs)
-
-# If the first argument is an (non-sequence) object, apply the named
-# method with the given arguments.  If the first argument is a
-# sequence, apply the method to each element of the sequence (a la
-# 'map').
-def applyOrMap(objOrSeq, meth, *args, **kwargs):
-    if not isinstance(objOrSeq, (list, tuple)):
-        return applyMethod(objOrSeq, meth, *args, **kwargs)
-    else:
-        return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq]
-
-def crossproduct(items):
-    if not isinstance(items, (list, tuple)):
-        raise AttributeError, 'crossproduct works only on sequences'
-
-    if not items:
-        yield None
-        return
-
-    current = items[0]
-    remainder = items[1:]
-
-    if not hasattr(current, '__iter__'):
-        current = [ current ]
-
-    for item in current:
-        for rem in crossproduct(remainder):
-            data = [ item ]
-            if rem:
-                data += rem
-            yield data
-
-def flatten(items):
-    if not isinstance(items, (list, tuple)):
-        yield items
-        return
-
-    for item in items:
-        for flat in flatten(item):
-            yield flat
diff --git a/src/python/m5/util/smartdict.py b/src/python/m5/util/smartdict.py
new file mode 100644 (file)
index 0000000..d85dbd5
--- /dev/null
@@ -0,0 +1,154 @@
+# Copyright (c) 2005 The Regents of The University of Michigan
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met: redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer;
+# redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution;
+# neither the name of the copyright holders nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Authors: Nathan Binkert
+
+# The SmartDict class fixes a couple of issues with using the content
+# of os.environ or similar dicts of strings as Python variables:
+#
+# 1) Undefined variables should return False rather than raising KeyError.
+#
+# 2) String values of 'False', '0', etc., should evaluate to False
+#    (not just the empty string).
+#
+# #1 is solved by overriding __getitem__, and #2 is solved by using a
+# proxy class for values and overriding __nonzero__ on the proxy.
+# Everything else is just to (a) make proxies behave like normal
+# values otherwise, (b) make sure any dict operation returns a proxy
+# rather than a normal value, and (c) coerce values written to the
+# dict to be strings.
+
+
+from convert import *
+
+class Variable(str):
+    """Intelligent proxy class for SmartDict.  Variable will use the
+    various convert functions to attempt to convert values to useable
+    types"""
+    def __int__(self):
+        return toInteger(str(self))
+    def __long__(self):
+        return toLong(str(self))
+    def __float__(self):
+        return toFloat(str(self))
+    def __nonzero__(self):
+        return toBool(str(self))
+    def convert(self, other):
+        t = type(other)
+        if t == bool:
+            return bool(self)
+        if t == int:
+            return int(self)
+        if t == long:
+            return long(self)
+        if t == float:
+            return float(self)
+        return str(self)
+    def __lt__(self, other):
+        return self.convert(other) < other
+    def __le__(self, other):
+        return self.convert(other) <= other
+    def __eq__(self, other):
+        return self.convert(other) == other
+    def __ne__(self, other):
+        return self.convert(other) != other
+    def __gt__(self, other):
+        return self.convert(other) > other
+    def __ge__(self, other):
+        return self.convert(other) >= other
+
+    def __add__(self, other):
+        return self.convert(other) + other
+    def __sub__(self, other):
+        return self.convert(other) - other
+    def __mul__(self, other):
+        return self.convert(other) * other
+    def __div__(self, other):
+        return self.convert(other) / other
+    def __truediv__(self, other):
+        return self.convert(other) / other
+
+    def __radd__(self, other):
+        return other + self.convert(other)
+    def __rsub__(self, other):
+        return other - self.convert(other)
+    def __rmul__(self, other):
+        return other * self.convert(other)
+    def __rdiv__(self, other):
+        return other / self.convert(other)
+    def __rtruediv__(self, other):
+        return other / self.convert(other)
+
+class UndefinedVariable(object):
+    """Placeholder class to represent undefined variables.  Will
+    generally cause an exception whenever it is used, but evaluates to
+    zero for boolean truth testing such as in an if statement"""
+    def __nonzero__(self):
+        return False
+
+class SmartDict(dict):
+    """Dictionary class that holds strings, but intelligently converts
+    those strings to other types depending on their usage"""
+
+    def __getitem__(self, key):
+        """returns a Variable proxy if the values exists in the database and
+        returns an UndefinedVariable otherwise"""
+
+        if key in self:
+            return Variable(dict.get(self, key))
+        else:
+            # Note that this does *not* change the contents of the dict,
+            # so that even after we call env['foo'] we still get a
+            # meaningful answer from "'foo' in env" (which
+            # calls dict.__contains__, which we do not override).
+            return UndefinedVariable()
+
+    def __setitem__(self, key, item):
+        """intercept the setting of any variable so that we always
+        store strings in the dict"""
+        dict.__setitem__(self, key, str(item))
+
+    def values(self):
+        return [ Variable(v) for v in dict.values(self) ]
+
+    def itervalues(self):
+        for value in dict.itervalues(self):
+            yield Variable(value)
+
+    def items(self):
+        return [ (k, Variable(v)) for k,v in dict.items(self) ]
+
+    def iteritems(self):
+        for key,value in dict.iteritems(self):
+            yield key, Variable(value)
+
+    def get(self, key, default='False'):
+        return Variable(dict.get(self, key, str(default)))
+
+    def setdefault(self, key, default='False'):
+        return Variable(dict.setdefault(self, key, str(default)))
+
+__all__ = [ 'SmartDict' ]
index 3b0bc1e46254bba00ef5f0eea2ada60211cce8f7..06a54a78db2b977533c31165882ffbfa3dc97bfe 100644 (file)
 # Authors: Nathan Binkert
 
 from m5.SimObject import SimObject
+from m5.defines import buildEnv
 from m5.params import *
 from m5.proxy import *
-from m5 import build_env
+
 from PhysicalMemory import *
 
 class MemoryMode(Enum): vals = ['invalid', 'atomic', 'timing']
@@ -40,7 +41,7 @@ class System(SimObject):
 
     physmem = Param.PhysicalMemory(Parent.any, "physical memory")
     mem_mode = Param.MemoryMode('atomic', "The mode the memory system is in")
-    if build_env['FULL_SYSTEM']:
+    if buildEnv['FULL_SYSTEM']:
         abstract = True
         boot_cpu_frequency = Param.Frequency(Self.cpu[0].clock.frequency,
                                              "boot processor frequency")
index 62f8b5850402b63292b1f6b3a4aa2425d2daee5e..10f9e42321bcb5d1850badcf0bc9b6ed7253b6bb 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 
 class MyCache(BaseCache):
     assoc = 2
index eab9bfaf23ebfff05bd7766a632c4733835ab636..77e1ba9924d7373c0353c6e9939ec1c545d1f8f3 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 
 nb_cores = 4
 cpus = [ DerivO3CPU(cpu_id=i) for i in xrange(nb_cores) ]
index fc6a72a82494896716891fa84c30a0781b1d94d1..59776d5c3eeb2ec371176bd6ece7311f91a412d2 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 
 # --------------------
 # Base L1 Cache
index a91a9cf39844f3745c6700da8604ffdde04a0287..f7ad41d99cf68817fdc2ba4884ff5f42f0f9cda3 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 
 
 import ruby_config
index 366a3eb0d4f3dd02ef105cd8de5b166ad0ce2edb..563772213f7d22dca4d36f8b65a7fdbc3370739e 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 
 class MyCache(BaseCache):
     assoc = 2
index 6a078e715258e63b76215bbf6946f4ec06b19fda..35b329f5782a78658dfc2d20d307f1858badda74 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 cpu = AtomicSimpleCPU(cpu_id=0)
index 3044f54335a5cdccd9e8d8add61ca7e63a5f1e2f..76aca38062a64b10662ce932f39b32bcaea04df4 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 
index 34fa235bd68729fa2810a98c7fec55e096415e06..9b52cd92be8288d44c69aba60163a378679da7f5 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 
index 593b026801ed820f58252064dcfa7c96d1493aa5..dfbdd101df5ec0cb75cb1a1a5a8a0cb2160f5d68 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 # --------------------
index 0c6feaeace1b3dff234e93c6aa336efd5a84d752..cfc619b061b95d12b833dc0c72286598b4b23978 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 # --------------------
index 21244991415bcc8f1b2cb1e5bb202558bf47c6bf..ce17475e34fa3dabde55529388b7804f902cc1f7 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 # --------------------
index f0eaa08d7d6dfa7507407ce8a27007a8b4ff6dbb..0c398462881cf1dd7c5f01fece99cd0abc3ba371 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 import FSConfig
 
 
index e7214a0598afda980c512ae60a496a1ba7a844bd..ce191930ea7f635d603d1d3b1949061fb6d35def 100644 (file)
@@ -28,7 +28,7 @@
 
 import m5
 from m5.objects import *
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from FSConfig import *
 from Benchmarks import *
 
index f69914046e914bcd4591ad48279982186fba2cf5..7acce6e81afd6a06bb73851599ce035baa516ec3 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import gzip_log
 
 workload = gzip_log(isa, opsys, 'smred')
index c4ffb248ad85730b79055a0a537007081c1a946a..9bd18a83fcf9ac734da446e541aa1c550338dfa2 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import mcf
 
 workload = mcf(isa, opsys, 'smred')
index 8e745ec262aec4580d3c9a91239c9eb662a6736c..c96a46e60d5859ba6e14bc4074708e73f83758d2 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import parser
 
 workload = parser(isa, opsys, 'mdred')
index 318da1049f150a7cff5f9ff1065bb521a6e10a66..de4d12dd846a9907551c37509fa6595a0c15274f 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import eon_cook
 
 workload = eon_cook(isa, opsys, 'mdred')
index e32416265490f57c5e530989f1a3c3d40a424ff0..8fe5d60473886d70f824c7a270382376c1c20b15 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import perlbmk_makerand
 
 workload = perlbmk_makerand(isa, opsys, 'lgred')
index fbf0dc08194fc05eeb8eb9d426e1f168ed5bf2e2..92422c234e9b5451c0d3b57d7f05168b3175c12c 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import vortex
 
 workload = vortex(isa, opsys, 'smred')
index 7fa3d1a078155e051a0ef6c71cc83305b63a842e..fa74d08602636c87e214bcaa02e95ee61f80979a 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import bzip2_source
 
 workload = bzip2_source(isa, opsys, 'lgred')
index 85b106eb4e505084cff269ad70482484429bbbed..761ec8b2e616616e0f117e8ff4098f58a36bd52e 100644 (file)
@@ -26,7 +26,7 @@
 #
 # Authors: Korey Sewell
 
-m5.AddToPath('../configs/common')
+m5.util.addToPath('../configs/common')
 from cpu2000 import twolf
 import os