1 # Copyright (c) 2008-2009 The Hewlett-Packard Development Company
2 # Copyright (c) 2004-2006 The Regents of The University of Michigan
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.
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.
28 # Authors: Nathan Binkert
37 from attrdict
import attrdict
, multiattrdict
, optiondict
38 from code_formatter
import code_formatter
39 from multidict
import multidict
40 from orderdict
import orderdict
41 from smartdict
import SmartDict
42 from sorteddict
import SortedDict
43 from region
import neg_inf
, pos_inf
, Region
, Regions
45 # panic() should be called when something happens that should never
46 # ever happen regardless of what the user does (i.e., an acutal m5
48 def panic(fmt
, *args
):
49 print >>sys
.stderr
, 'panic:', fmt
% args
52 # fatal() should be called when the simulation cannot continue due to
53 # some condition that is the user's fault (bad configuration, invalid
54 # arguments, etc.) and not a simulator bug.
55 def fatal(fmt
, *args
):
56 print >>sys
.stderr
, 'fatal:', fmt
% args
59 class Singleton(type):
60 def __call__(cls
, *args
, **kwargs
):
61 if hasattr(cls
, '_instance'):
64 cls
._instance
= super(Singleton
, cls
).__call
__(*args
, **kwargs
)
68 """Prepend given directory to system module search path. We may not
69 need this anymore if we can structure our config library more like a
72 # if it's a relative path and we know what directory the current
73 # python script is in, make the path relative to that directory.
74 if not os
.path
.isabs(path
) and sys
.path
[0]:
75 path
= os
.path
.join(sys
.path
[0], path
)
76 path
= os
.path
.realpath(path
)
77 # sys.path[0] should always refer to the current script's directory,
78 # so place the new dir right after that.
79 sys
.path
.insert(1, path
)
81 # Apply method to object.
82 # applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
83 def applyMethod(obj
, meth
, *args
, **kwargs
):
84 return getattr(obj
, meth
)(*args
, **kwargs
)
86 # If the first argument is an (non-sequence) object, apply the named
87 # method with the given arguments. If the first argument is a
88 # sequence, apply the method to each element of the sequence (a la
90 def applyOrMap(objOrSeq
, meth
, *args
, **kwargs
):
91 if not isinstance(objOrSeq
, (list, tuple)):
92 return applyMethod(objOrSeq
, meth
, *args
, **kwargs
)
94 return [applyMethod(o
, meth
, *args
, **kwargs
) for o
in objOrSeq
]
96 def compareVersions(v1
, v2
):
97 """helper function: compare arrays or strings of version numbers.
98 E.g., compare_version((1,3,25), (1,4,1)')
99 returns -1, 0, 1 if v1 is <, ==, > v2
101 def make_version_list(v
):
102 if isinstance(v
, (list,tuple)):
104 elif isinstance(v
, str):
105 return map(lambda x
: int(re
.match('\d+', x
).group()), v
.split('.'))
109 v1
= make_version_list(v1
)
110 v2
= make_version_list(v2
)
111 # Compare corresponding elements of lists
112 for n1
,n2
in zip(v1
, v2
):
113 if n1
< n2
: return -1
115 # all corresponding values are equal... see if one has extra values
116 if len(v1
) < len(v2
): return -1
117 if len(v1
) > len(v2
): return 1
120 def crossproduct(items
):
126 for j
in crossproduct(items
[1:]):
132 if isinstance(item
, (list, tuple)):
137 # force scalars to one-element lists for uniformity
138 def makeList(objOrList
):
139 if isinstance(objOrList
, list):
143 def printList(items
, indent
=4):
145 for i
,item
in enumerate(items
):
146 if len(line
) + len(item
) > 76:
150 if i
< len(items
) - 1:
151 line
+= '%s, ' % item
156 def readCommand(cmd
, **kwargs
):
157 """run the command cmd, read the results and return them
158 this is sorta like `cmd` in shell"""
159 from subprocess
import Popen
, PIPE
, STDOUT
161 if isinstance(cmd
, str):
164 no_exception
= 'exception' in kwargs
165 exception
= kwargs
.pop('exception', None)
167 kwargs
.setdefault('shell', False)
168 kwargs
.setdefault('stdout', PIPE
)
169 kwargs
.setdefault('stderr', STDOUT
)
170 kwargs
.setdefault('close_fds', True)
172 subp
= Popen(cmd
, **kwargs
)
178 return subp
.communicate()[0]
181 """Make a directory if it doesn't exist. If the path does exist,
182 ensure that it is a directory"""
183 if os
.path
.exists(path
):
184 if not os
.path
.isdir(path
):
185 raise AttributeError, "%s exists but is not directory" % path