__init__.py revision 8328:03cfd2ecf6bb
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# panic() should be called when something happens that should never
46# ever happen regardless of what the user does (i.e., an acutal m5
47# bug).
48def panic(fmt, *args):
49    print >>sys.stderr, 'panic:', fmt % args
50    sys.exit(1)
51
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.
55def fatal(fmt, *args):
56    print >>sys.stderr, 'fatal:', fmt % args
57    sys.exit(1)
58
59class Singleton(type):
60    def __call__(cls, *args, **kwargs):
61        if hasattr(cls, '_instance'):
62            return cls._instance
63
64        cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
65        return cls._instance
66
67def addToPath(path):
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
70    Python package."""
71
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)
80
81# Apply method to object.
82# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
83def applyMethod(obj, meth, *args, **kwargs):
84    return getattr(obj, meth)(*args, **kwargs)
85
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
89# 'map').
90def applyOrMap(objOrSeq, meth, *args, **kwargs):
91    if not isinstance(objOrSeq, (list, tuple)):
92        return applyMethod(objOrSeq, meth, *args, **kwargs)
93    else:
94        return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq]
95
96def 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
100    """
101    def make_version_list(v):
102        if isinstance(v, (list,tuple)):
103            return v
104        elif isinstance(v, str):
105            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
106        else:
107            raise TypeError
108
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
114        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
118    return 0
119
120def crossproduct(items):
121    if len(items) == 1:
122        for i in items[0]:
123            yield (i,)
124    else:
125        for i in items[0]:
126            for j in crossproduct(items[1:]):
127                yield (i,) + j
128
129def flatten(items):
130    while items:
131        item = items.pop(0)
132        if isinstance(item, (list, tuple)):
133            items[0:0] = item
134        else:
135            yield item
136
137# force scalars to one-element lists for uniformity
138def makeList(objOrList):
139    if isinstance(objOrList, list):
140        return objOrList
141    return [objOrList]
142
143def printList(items, indent=4):
144    line = ' ' * indent
145    for i,item in enumerate(items):
146        if len(line) + len(item) > 76:
147            print line
148            line = ' ' * indent
149
150        if i < len(items) - 1:
151            line += '%s, ' % item
152        else:
153            line += item
154            print line
155
156def 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
160
161    if isinstance(cmd, str):
162        cmd = cmd.split()
163
164    no_exception = 'exception' in kwargs
165    exception = kwargs.pop('exception', None)
166
167    kwargs.setdefault('shell', False)
168    kwargs.setdefault('stdout', PIPE)
169    kwargs.setdefault('stderr', STDOUT)
170    kwargs.setdefault('close_fds', True)
171    try:
172        subp = Popen(cmd, **kwargs)
173    except Exception, e:
174        if no_exception:
175            return exception
176        raise
177
178    return subp.communicate()[0]
179