__init__.py revision 8224:75527411e636
1# Copyright (c) 2008-2009 The Hewlett-Packard Development Company 2# Copyright (c) 2004-2006 The Regents of The University of Michigan 3# All rights reserved. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: redistributions of source code must retain the above copyright 8# notice, this list of conditions and the following disclaimer; 9# redistributions in binary form must reproduce the above copyright 10# notice, this list of conditions and the following disclaimer in the 11# documentation and/or other materials provided with the distribution; 12# neither the name of the copyright holders nor the names of its 13# contributors may be used to endorse or promote products derived from 14# this software without specific prior written permission. 15# 16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27# 28# Authors: Nathan Binkert 29 30import os 31import re 32import sys 33 34import convert 35import jobfile 36 37from attrdict import attrdict, multiattrdict, optiondict 38from code_formatter import code_formatter 39from multidict import multidict 40from orderdict import orderdict 41from smartdict import SmartDict 42from sorteddict import SortedDict 43from region import neg_inf, pos_inf, Region, Regions 44 45# define this here so we can use it right away if necessary 46def errorURL(prefix, s): 47 try: 48 import zlib 49 hashstr = "%x" % zlib.crc32(s) 50 except: 51 hashstr = "UnableToHash" 52 return "For more information see: http://www.m5sim.org/%s/%s" % \ 53 (prefix, hashstr) 54 55# panic() should be called when something happens that should never 56# ever happen regardless of what the user does (i.e., an acutal m5 57# bug). 58def panic(fmt, *args): 59 print >>sys.stderr, 'panic:', fmt % args 60 print >>sys.stderr, errorURL('panic',fmt) 61 sys.exit(1) 62 63# fatal() should be called when the simulation cannot continue due to 64# some condition that is the user's fault (bad configuration, invalid 65# arguments, etc.) and not a simulator bug. 66def fatal(fmt, *args): 67 print >>sys.stderr, 'fatal:', fmt % args 68 print >>sys.stderr, errorURL('fatal',fmt) 69 sys.exit(1) 70 71class Singleton(type): 72 def __call__(cls, *args, **kwargs): 73 if hasattr(cls, '_instance'): 74 return cls._instance 75 76 cls._instance = super(Singleton, cls).__call__(*args, **kwargs) 77 return cls._instance 78 79def addToPath(path): 80 """Prepend given directory to system module search path. We may not 81 need this anymore if we can structure our config library more like a 82 Python package.""" 83 84 # if it's a relative path and we know what directory the current 85 # python script is in, make the path relative to that directory. 86 if not os.path.isabs(path) and sys.path[0]: 87 path = os.path.join(sys.path[0], path) 88 path = os.path.realpath(path) 89 # sys.path[0] should always refer to the current script's directory, 90 # so place the new dir right after that. 91 sys.path.insert(1, path) 92 93# Apply method to object. 94# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>) 95def applyMethod(obj, meth, *args, **kwargs): 96 return getattr(obj, meth)(*args, **kwargs) 97 98# If the first argument is an (non-sequence) object, apply the named 99# method with the given arguments. If the first argument is a 100# sequence, apply the method to each element of the sequence (a la 101# 'map'). 102def applyOrMap(objOrSeq, meth, *args, **kwargs): 103 if not isinstance(objOrSeq, (list, tuple)): 104 return applyMethod(objOrSeq, meth, *args, **kwargs) 105 else: 106 return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq] 107 108def compareVersions(v1, v2): 109 """helper function: compare arrays or strings of version numbers. 110 E.g., compare_version((1,3,25), (1,4,1)') 111 returns -1, 0, 1 if v1 is <, ==, > v2 112 """ 113 def make_version_list(v): 114 if isinstance(v, (list,tuple)): 115 return v 116 elif isinstance(v, str): 117 return map(lambda x: int(re.match('\d+', x).group()), v.split('.')) 118 else: 119 raise TypeError 120 121 v1 = make_version_list(v1) 122 v2 = make_version_list(v2) 123 # Compare corresponding elements of lists 124 for n1,n2 in zip(v1, v2): 125 if n1 < n2: return -1 126 if n1 > n2: return 1 127 # all corresponding values are equal... see if one has extra values 128 if len(v1) < len(v2): return -1 129 if len(v1) > len(v2): return 1 130 return 0 131 132def crossproduct(items): 133 if len(items) == 1: 134 for i in items[0]: 135 yield (i,) 136 else: 137 for i in items[0]: 138 for j in crossproduct(items[1:]): 139 yield (i,) + j 140 141def flatten(items): 142 while items: 143 item = items.pop(0) 144 if isinstance(item, (list, tuple)): 145 items[0:0] = item 146 else: 147 yield item 148 149# force scalars to one-element lists for uniformity 150def makeList(objOrList): 151 if isinstance(objOrList, list): 152 return objOrList 153 return [objOrList] 154 155def printList(items, indent=4): 156 line = ' ' * indent 157 for i,item in enumerate(items): 158 if len(line) + len(item) > 76: 159 print line 160 line = ' ' * indent 161 162 if i < len(items) - 1: 163 line += '%s, ' % item 164 else: 165 line += item 166 print line 167 168def readCommand(cmd, **kwargs): 169 """run the command cmd, read the results and return them 170 this is sorta like `cmd` in shell""" 171 from subprocess import Popen, PIPE, STDOUT 172 173 if isinstance(cmd, str): 174 cmd = cmd.split() 175 176 no_exception = 'exception' in kwargs 177 exception = kwargs.pop('exception', None) 178 179 kwargs.setdefault('shell', False) 180 kwargs.setdefault('stdout', PIPE) 181 kwargs.setdefault('stderr', STDOUT) 182 kwargs.setdefault('close_fds', True) 183 try: 184 subp = Popen(cmd, **kwargs) 185 except Exception, e: 186 if no_exception: 187 return exception 188 raise 189 190 return subp.communicate()[0] 191