__init__.py revision 7503:37da2c208f5f
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# define this here so we can use it right away if necessary 45def errorURL(prefix, s): 46 try: 47 import zlib 48 hashstr = "%x" % zlib.crc32(s) 49 except: 50 hashstr = "UnableToHash" 51 return "For more information see: http://www.m5sim.org/%s/%s" % \ 52 (prefix, hashstr) 53 54# panic() should be called when something happens that should never 55# ever happen regardless of what the user does (i.e., an acutal m5 56# bug). 57def panic(fmt, *args): 58 print >>sys.stderr, 'panic:', fmt % args 59 print >>sys.stderr, errorURL('panic',fmt) 60 sys.exit(1) 61 62# fatal() should be called when the simulation cannot continue due to 63# some condition that is the user's fault (bad configuration, invalid 64# arguments, etc.) and not a simulator bug. 65def fatal(fmt, *args): 66 print >>sys.stderr, 'fatal:', fmt % args 67 print >>sys.stderr, errorURL('fatal',fmt) 68 sys.exit(1) 69 70class Singleton(type): 71 def __call__(cls, *args, **kwargs): 72 if hasattr(cls, '_instance'): 73 return cls._instance 74 75 cls._instance = super(Singleton, cls).__call__(*args, **kwargs) 76 return cls._instance 77 78def addToPath(path): 79 """Prepend given directory to system module search path. We may not 80 need this anymore if we can structure our config library more like a 81 Python package.""" 82 83 # if it's a relative path and we know what directory the current 84 # python script is in, make the path relative to that directory. 85 if not os.path.isabs(path) and sys.path[0]: 86 path = os.path.join(sys.path[0], path) 87 path = os.path.realpath(path) 88 # sys.path[0] should always refer to the current script's directory, 89 # so place the new dir right after that. 90 sys.path.insert(1, path) 91 92# Apply method to object. 93# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>) 94def applyMethod(obj, meth, *args, **kwargs): 95 return getattr(obj, meth)(*args, **kwargs) 96 97# If the first argument is an (non-sequence) object, apply the named 98# method with the given arguments. If the first argument is a 99# sequence, apply the method to each element of the sequence (a la 100# 'map'). 101def applyOrMap(objOrSeq, meth, *args, **kwargs): 102 if not isinstance(objOrSeq, (list, tuple)): 103 return applyMethod(objOrSeq, meth, *args, **kwargs) 104 else: 105 return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq] 106 107def compareVersions(v1, v2): 108 """helper function: compare arrays or strings of version numbers. 109 E.g., compare_version((1,3,25), (1,4,1)') 110 returns -1, 0, 1 if v1 is <, ==, > v2 111 """ 112 def make_version_list(v): 113 if isinstance(v, (list,tuple)): 114 return v 115 elif isinstance(v, str): 116 return map(lambda x: int(re.match('\d+', x).group()), v.split('.')) 117 else: 118 raise TypeError 119 120 v1 = make_version_list(v1) 121 v2 = make_version_list(v2) 122 # Compare corresponding elements of lists 123 for n1,n2 in zip(v1, v2): 124 if n1 < n2: return -1 125 if n1 > n2: return 1 126 # all corresponding values are equal... see if one has extra values 127 if len(v1) < len(v2): return -1 128 if len(v1) > len(v2): return 1 129 return 0 130 131def crossproduct(items): 132 if len(items) == 1: 133 for i in items[0]: 134 yield (i,) 135 else: 136 for i in items[0]: 137 for j in crossproduct(items[1:]): 138 yield (i,) + j 139 140def flatten(items): 141 while items: 142 item = items.pop(0) 143 if isinstance(item, (list, tuple)): 144 items[0:0] = item 145 else: 146 yield item 147 148# force scalars to one-element lists for uniformity 149def makeList(objOrList): 150 if isinstance(objOrList, list): 151 return objOrList 152 return [objOrList] 153 154def printList(items, indent=4): 155 line = ' ' * indent 156 for i,item in enumerate(items): 157 if len(line) + len(item) > 76: 158 print line 159 line = ' ' * indent 160 161 if i < len(items) - 1: 162 line += '%s, ' % item 163 else: 164 line += item 165 print line 166 167def readCommand(cmd, **kwargs): 168 """run the command cmd, read the results and return them 169 this is sorta like `cmd` in shell""" 170 from subprocess import Popen, PIPE, STDOUT 171 172 if isinstance(cmd, str): 173 cmd = cmd.split() 174 175 no_exception = 'exception' in kwargs 176 exception = kwargs.pop('exception', None) 177 178 kwargs.setdefault('shell', False) 179 kwargs.setdefault('stdout', PIPE) 180 kwargs.setdefault('stderr', STDOUT) 181 kwargs.setdefault('close_fds', True) 182 try: 183 subp = Popen(cmd, **kwargs) 184 except Exception, e: 185 if no_exception: 186 return exception 187 raise 188 189 return subp.communicate()[0] 190