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