__init__.py revision 13663:9b64aeabf9a5
1# Copyright (c) 2016 ARM Limited 2# All rights reserved. 3# 4# The license below extends only to copyright in the software and shall 5# not be construed as granting a license to any other intellectual 6# property including but not limited to intellectual property relating 7# to a hardware implementation of the functionality of the software 8# licensed hereunder. You may use the software subject to the license 9# terms below provided that you ensure that this notice is replicated 10# unmodified and in its entirety in all distributions of the software, 11# modified or unmodified, in source code or in binary form. 12# 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 42from __future__ import print_function 43 44import os 45import re 46import sys 47 48import convert 49import jobfile 50 51from attrdict import attrdict, multiattrdict, optiondict 52from code_formatter import code_formatter 53from multidict import multidict 54from orderdict import orderdict 55from smartdict import SmartDict 56from sorteddict import SortedDict 57 58# panic() should be called when something happens that should never 59# ever happen regardless of what the user does (i.e., an acutal m5 60# bug). 61def panic(fmt, *args): 62 print('panic:', fmt % args, file=sys.stderr) 63 sys.exit(1) 64 65# fatal() should be called when the simulation cannot continue due to 66# some condition that is the user's fault (bad configuration, invalid 67# arguments, etc.) and not a simulator bug. 68def fatal(fmt, *args): 69 print('fatal:', fmt % args, file=sys.stderr) 70 sys.exit(1) 71 72# warn() should be called when the user should be warned about some condition 73# that may or may not be the user's fault, but that they should be made aware 74# of as it may affect the simulation or results. 75def warn(fmt, *args): 76 print('warn:', fmt % args, file=sys.stderr) 77 78# inform() should be called when the user should be informed about some 79# condition that they may be interested in. 80def inform(fmt, *args): 81 print('info:', fmt % args, file=sys.stdout) 82 83class Singleton(type): 84 def __call__(cls, *args, **kwargs): 85 if hasattr(cls, '_instance'): 86 return cls._instance 87 88 cls._instance = super(Singleton, cls).__call__(*args, **kwargs) 89 return cls._instance 90 91def addToPath(path): 92 """Prepend given directory to system module search path. We may not 93 need this anymore if we can structure our config library more like a 94 Python package.""" 95 96 # if it's a relative path and we know what directory the current 97 # python script is in, make the path relative to that directory. 98 if not os.path.isabs(path) and sys.path[0]: 99 path = os.path.join(sys.path[0], path) 100 path = os.path.realpath(path) 101 # sys.path[0] should always refer to the current script's directory, 102 # so place the new dir right after that. 103 sys.path.insert(1, path) 104 105# Apply method to object. 106# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>) 107def applyMethod(obj, meth, *args, **kwargs): 108 return getattr(obj, meth)(*args, **kwargs) 109 110# If the first argument is an (non-sequence) object, apply the named 111# method with the given arguments. If the first argument is a 112# sequence, apply the method to each element of the sequence (a la 113# 'map'). 114def applyOrMap(objOrSeq, meth, *args, **kwargs): 115 if not isinstance(objOrSeq, (list, tuple)): 116 return applyMethod(objOrSeq, meth, *args, **kwargs) 117 else: 118 return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq] 119 120def compareVersions(v1, v2): 121 """helper function: compare arrays or strings of version numbers. 122 E.g., compare_version((1,3,25), (1,4,1)') 123 returns -1, 0, 1 if v1 is <, ==, > v2 124 """ 125 def make_version_list(v): 126 if isinstance(v, (list,tuple)): 127 return v 128 elif isinstance(v, str): 129 return map(lambda x: int(re.match('\d+', x).group()), v.split('.')) 130 else: 131 raise TypeError() 132 133 v1 = make_version_list(v1) 134 v2 = make_version_list(v2) 135 # Compare corresponding elements of lists 136 for n1,n2 in zip(v1, v2): 137 if n1 < n2: return -1 138 if n1 > n2: return 1 139 # all corresponding values are equal... see if one has extra values 140 if len(v1) < len(v2): return -1 141 if len(v1) > len(v2): return 1 142 return 0 143 144def crossproduct(items): 145 if len(items) == 1: 146 for i in items[0]: 147 yield (i,) 148 else: 149 for i in items[0]: 150 for j in crossproduct(items[1:]): 151 yield (i,) + j 152 153def flatten(items): 154 while items: 155 item = items.pop(0) 156 if isinstance(item, (list, tuple)): 157 items[0:0] = item 158 else: 159 yield item 160 161# force scalars to one-element lists for uniformity 162def makeList(objOrList): 163 if isinstance(objOrList, list): 164 return objOrList 165 return [objOrList] 166 167def printList(items, indent=4): 168 line = ' ' * indent 169 for i,item in enumerate(items): 170 if len(line) + len(item) > 76: 171 print(line) 172 line = ' ' * indent 173 174 if i < len(items) - 1: 175 line += '%s, ' % item 176 else: 177 line += item 178 print(line) 179 180def readCommand(cmd, **kwargs): 181 """run the command cmd, read the results and return them 182 this is sorta like `cmd` in shell""" 183 from subprocess import Popen, PIPE, STDOUT 184 185 if isinstance(cmd, str): 186 cmd = cmd.split() 187 188 no_exception = 'exception' in kwargs 189 exception = kwargs.pop('exception', None) 190 191 kwargs.setdefault('shell', False) 192 kwargs.setdefault('stdout', PIPE) 193 kwargs.setdefault('stderr', STDOUT) 194 kwargs.setdefault('close_fds', True) 195 try: 196 subp = Popen(cmd, **kwargs) 197 except Exception as e: 198 if no_exception: 199 return exception 200 raise 201 202 return subp.communicate()[0] 203 204def makeDir(path): 205 """Make a directory if it doesn't exist. If the path does exist, 206 ensure that it is a directory""" 207 if os.path.exists(path): 208 if not os.path.isdir(path): 209 raise AttributeError("%s exists but is not directory" % path) 210 else: 211 os.mkdir(path) 212 213def isInteractive(): 214 """Check if the simulator is run interactively or in a batch environment""" 215 216 return sys.__stdin__.isatty() 217