SimObject.py revision 5488
1# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met: redistributions of source code must retain the above copyright
7# notice, this list of conditions and the following disclaimer;
8# redistributions in binary form must reproduce the above copyright
9# notice, this list of conditions and the following disclaimer in the
10# documentation and/or other materials provided with the distribution;
11# neither the name of the copyright holders nor the names of its
12# contributors may be used to endorse or promote products derived from
13# this software without specific prior written permission.
14#
15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26#
27# Authors: Steve Reinhardt
28#          Nathan Binkert
29
30import sys, types
31
32import proxy
33import m5
34from util import *
35
36# These utility functions have to come first because they're
37# referenced in params.py... otherwise they won't be defined when we
38# import params below, and the recursive import of this file from
39# params.py will not find these names.
40def isSimObject(value):
41    return isinstance(value, SimObject)
42
43def isSimObjectClass(value):
44    return issubclass(value, SimObject)
45
46def isSimObjectSequence(value):
47    if not isinstance(value, (list, tuple)) or len(value) == 0:
48        return False
49
50    for val in value:
51        if not isNullPointer(val) and not isSimObject(val):
52            return False
53
54    return True
55
56def isSimObjectOrSequence(value):
57    return isSimObject(value) or isSimObjectSequence(value)
58
59# Have to import params up top since Param is referenced on initial
60# load (when SimObject class references Param to create a class
61# variable, the 'name' param)...
62from params import *
63# There are a few things we need that aren't in params.__all__ since
64# normal users don't need them
65from params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
66
67noDot = False
68try:
69    import pydot
70except:
71    noDot = True
72
73#####################################################################
74#
75# M5 Python Configuration Utility
76#
77# The basic idea is to write simple Python programs that build Python
78# objects corresponding to M5 SimObjects for the desired simulation
79# configuration.  For now, the Python emits a .ini file that can be
80# parsed by M5.  In the future, some tighter integration between M5
81# and the Python interpreter may allow bypassing the .ini file.
82#
83# Each SimObject class in M5 is represented by a Python class with the
84# same name.  The Python inheritance tree mirrors the M5 C++ tree
85# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
86# SimObjects inherit from a single SimObject base class).  To specify
87# an instance of an M5 SimObject in a configuration, the user simply
88# instantiates the corresponding Python object.  The parameters for
89# that SimObject are given by assigning to attributes of the Python
90# object, either using keyword assignment in the constructor or in
91# separate assignment statements.  For example:
92#
93# cache = BaseCache(size='64KB')
94# cache.hit_latency = 3
95# cache.assoc = 8
96#
97# The magic lies in the mapping of the Python attributes for SimObject
98# classes to the actual SimObject parameter specifications.  This
99# allows parameter validity checking in the Python code.  Continuing
100# the example above, the statements "cache.blurfl=3" or
101# "cache.assoc='hello'" would both result in runtime errors in Python,
102# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
103# parameter requires an integer, respectively.  This magic is done
104# primarily by overriding the special __setattr__ method that controls
105# assignment to object attributes.
106#
107# Once a set of Python objects have been instantiated in a hierarchy,
108# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
109# will generate a .ini file.
110#
111#####################################################################
112
113# list of all SimObject classes
114allClasses = {}
115
116# dict to look up SimObjects based on path
117instanceDict = {}
118
119# The metaclass for SimObject.  This class controls how new classes
120# that derive from SimObject are instantiated, and provides inherited
121# class behavior (just like a class controls how instances of that
122# class are instantiated, and provides inherited instance behavior).
123class MetaSimObject(type):
124    # Attributes that can be set only at initialization time
125    init_keywords = { 'abstract' : types.BooleanType,
126                      'cxx_namespace' : types.StringType,
127                      'cxx_class' : types.StringType,
128                      'cxx_type' : types.StringType,
129                      'cxx_predecls' : types.ListType,
130                      'swig_objdecls' : types.ListType,
131                      'swig_predecls' : types.ListType,
132                      'type' : types.StringType }
133    # Attributes that can be set any time
134    keywords = { 'check' : types.FunctionType }
135
136    # __new__ is called before __init__, and is where the statements
137    # in the body of the class definition get loaded into the class's
138    # __dict__.  We intercept this to filter out parameter & port assignments
139    # and only allow "private" attributes to be passed to the base
140    # __new__ (starting with underscore).
141    def __new__(mcls, name, bases, dict):
142        assert name not in allClasses
143
144        # Copy "private" attributes, functions, and classes to the
145        # official dict.  Everything else goes in _init_dict to be
146        # filtered in __init__.
147        cls_dict = {}
148        value_dict = {}
149        for key,val in dict.items():
150            if key.startswith('_') or isinstance(val, (types.FunctionType,
151                                                       types.TypeType)):
152                cls_dict[key] = val
153            else:
154                # must be a param/port setting
155                value_dict[key] = val
156        if 'abstract' not in value_dict:
157            value_dict['abstract'] = False
158        cls_dict['_value_dict'] = value_dict
159        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
160        if 'type' in value_dict:
161            allClasses[name] = cls
162        return cls
163
164    # subclass initialization
165    def __init__(cls, name, bases, dict):
166        # calls type.__init__()... I think that's a no-op, but leave
167        # it here just in case it's not.
168        super(MetaSimObject, cls).__init__(name, bases, dict)
169
170        # initialize required attributes
171
172        # class-only attributes
173        cls._params = multidict() # param descriptions
174        cls._ports = multidict()  # port descriptions
175
176        # class or instance attributes
177        cls._values = multidict()   # param values
178        cls._port_refs = multidict() # port ref objects
179        cls._instantiated = False # really instantiated, cloned, or subclassed
180
181        # We don't support multiple inheritance.  If you want to, you
182        # must fix multidict to deal with it properly.
183        if len(bases) > 1:
184            raise TypeError, "SimObjects do not support multiple inheritance"
185
186        base = bases[0]
187
188        # Set up general inheritance via multidicts.  A subclass will
189        # inherit all its settings from the base class.  The only time
190        # the following is not true is when we define the SimObject
191        # class itself (in which case the multidicts have no parent).
192        if isinstance(base, MetaSimObject):
193            cls._params.parent = base._params
194            cls._ports.parent = base._ports
195            cls._values.parent = base._values
196            cls._port_refs.parent = base._port_refs
197            # mark base as having been subclassed
198            base._instantiated = True
199
200        # default keyword values
201        if 'type' in cls._value_dict:
202            _type = cls._value_dict['type']
203            if 'cxx_class' not in cls._value_dict:
204                cls._value_dict['cxx_class'] = _type
205
206            namespace = cls._value_dict.get('cxx_namespace', None)
207
208            _cxx_class = cls._value_dict['cxx_class']
209            if 'cxx_type' not in cls._value_dict:
210                t = _cxx_class + '*'
211                if namespace:
212                    t = '%s::%s' % (namespace, t)
213                cls._value_dict['cxx_type'] = t
214            if 'cxx_predecls' not in cls._value_dict:
215                # A forward class declaration is sufficient since we are
216                # just declaring a pointer.
217                decl = 'class %s;' % _cxx_class
218                if namespace:
219                    namespaces = namespace.split('::')
220                    namespaces.reverse()
221                    for namespace in namespaces:
222                        decl = 'namespace %s { %s }' % (namespace, decl)
223                cls._value_dict['cxx_predecls'] = [decl]
224
225            if 'swig_predecls' not in cls._value_dict:
226                # A forward class declaration is sufficient since we are
227                # just declaring a pointer.
228                cls._value_dict['swig_predecls'] = \
229                    cls._value_dict['cxx_predecls']
230
231        if 'swig_objdecls' not in cls._value_dict:
232            cls._value_dict['swig_objdecls'] = []
233
234        # Now process the _value_dict items.  They could be defining
235        # new (or overriding existing) parameters or ports, setting
236        # class keywords (e.g., 'abstract'), or setting parameter
237        # values or port bindings.  The first 3 can only be set when
238        # the class is defined, so we handle them here.  The others
239        # can be set later too, so just emulate that by calling
240        # setattr().
241        for key,val in cls._value_dict.items():
242            # param descriptions
243            if isinstance(val, ParamDesc):
244                cls._new_param(key, val)
245
246            # port objects
247            elif isinstance(val, Port):
248                cls._new_port(key, val)
249
250            # init-time-only keywords
251            elif cls.init_keywords.has_key(key):
252                cls._set_keyword(key, val, cls.init_keywords[key])
253
254            # default: use normal path (ends up in __setattr__)
255            else:
256                setattr(cls, key, val)
257
258    def _set_keyword(cls, keyword, val, kwtype):
259        if not isinstance(val, kwtype):
260            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
261                  (keyword, type(val), kwtype)
262        if isinstance(val, types.FunctionType):
263            val = classmethod(val)
264        type.__setattr__(cls, keyword, val)
265
266    def _new_param(cls, name, pdesc):
267        # each param desc should be uniquely assigned to one variable
268        assert(not hasattr(pdesc, 'name'))
269        pdesc.name = name
270        cls._params[name] = pdesc
271        if hasattr(pdesc, 'default'):
272            cls._set_param(name, pdesc.default, pdesc)
273
274    def _set_param(cls, name, value, param):
275        assert(param.name == name)
276        try:
277            cls._values[name] = param.convert(value)
278        except Exception, e:
279            msg = "%s\nError setting param %s.%s to %s\n" % \
280                  (e, cls.__name__, name, value)
281            e.args = (msg, )
282            raise
283
284    def _new_port(cls, name, port):
285        # each port should be uniquely assigned to one variable
286        assert(not hasattr(port, 'name'))
287        port.name = name
288        cls._ports[name] = port
289        if hasattr(port, 'default'):
290            cls._cls_get_port_ref(name).connect(port.default)
291
292    # same as _get_port_ref, effectively, but for classes
293    def _cls_get_port_ref(cls, attr):
294        # Return reference that can be assigned to another port
295        # via __setattr__.  There is only ever one reference
296        # object per port, but we create them lazily here.
297        ref = cls._port_refs.get(attr)
298        if not ref:
299            ref = cls._ports[attr].makeRef(cls)
300            cls._port_refs[attr] = ref
301        return ref
302
303    # Set attribute (called on foo.attr = value when foo is an
304    # instance of class cls).
305    def __setattr__(cls, attr, value):
306        # normal processing for private attributes
307        if attr.startswith('_'):
308            type.__setattr__(cls, attr, value)
309            return
310
311        if cls.keywords.has_key(attr):
312            cls._set_keyword(attr, value, cls.keywords[attr])
313            return
314
315        if cls._ports.has_key(attr):
316            cls._cls_get_port_ref(attr).connect(value)
317            return
318
319        if isSimObjectOrSequence(value) and cls._instantiated:
320            raise RuntimeError, \
321                  "cannot set SimObject parameter '%s' after\n" \
322                  "    class %s has been instantiated or subclassed" \
323                  % (attr, cls.__name__)
324
325        # check for param
326        param = cls._params.get(attr)
327        if param:
328            cls._set_param(attr, value, param)
329            return
330
331        if isSimObjectOrSequence(value):
332            # If RHS is a SimObject, it's an implicit child assignment.
333            # Classes don't have children, so we just put this object
334            # in _values; later, each instance will do a 'setattr(self,
335            # attr, _values[attr])' in SimObject.__init__ which will
336            # add this object as a child.
337            cls._values[attr] = value
338            return
339
340        # no valid assignment... raise exception
341        raise AttributeError, \
342              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
343
344    def __getattr__(cls, attr):
345        if cls._values.has_key(attr):
346            return cls._values[attr]
347
348        raise AttributeError, \
349              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
350
351    def __str__(cls):
352        return cls.__name__
353
354    def get_base(cls):
355        if str(cls) == 'SimObject':
356            return None
357
358        return  cls.__bases__[0].type
359
360    def cxx_decl(cls):
361        code = "#ifndef __PARAMS__%s\n" % cls
362        code += "#define __PARAMS__%s\n\n" % cls
363
364        # The 'dict' attribute restricts us to the params declared in
365        # the object itself, not including inherited params (which
366        # will also be inherited from the base class's param struct
367        # here).
368        params = cls._params.local.values()
369        try:
370            ptypes = [p.ptype for p in params]
371        except:
372            print cls, p, p.ptype_str
373            print params
374            raise
375
376        # get a list of lists of predeclaration lines
377        predecls = []
378        predecls.extend(cls.cxx_predecls)
379        for p in params:
380            predecls.extend(p.cxx_predecls())
381        # remove redundant lines
382        predecls2 = []
383        for pd in predecls:
384            if pd not in predecls2:
385                predecls2.append(pd)
386        predecls2.sort()
387        code += "\n".join(predecls2)
388        code += "\n\n";
389
390        base = cls.get_base()
391        if base:
392            code += '#include "params/%s.hh"\n\n' % base
393
394        for ptype in ptypes:
395            if issubclass(ptype, Enum):
396                code += '#include "enums/%s.hh"\n' % ptype.__name__
397                code += "\n\n"
398
399        code += cls.cxx_struct(base, params)
400
401        # close #ifndef __PARAMS__* guard
402        code += "\n#endif\n"
403        return code
404
405    def cxx_struct(cls, base, params):
406        if cls == SimObject:
407            return '#include "sim/sim_object_params.hh"\n'
408
409        # now generate the actual param struct
410        code = "struct %sParams" % cls
411        if base:
412            code += " : public %sParams" % base
413        code += "\n{\n"
414        if not hasattr(cls, 'abstract') or not cls.abstract:
415            if 'type' in cls.__dict__:
416                code += "    %s create();\n" % cls.cxx_type
417        decls = [p.cxx_decl() for p in params]
418        decls.sort()
419        code += "".join(["    %s\n" % d for d in decls])
420        code += "};\n"
421
422        return code
423
424    def cxx_type_decl(cls):
425        base = cls.get_base()
426        code = ''
427
428        if base:
429            code += '#include "%s_type.h"\n' % base
430
431        # now generate dummy code for inheritance
432        code += "struct %s" % cls.cxx_class
433        if base:
434            code += " : public %s" % base.cxx_class
435        code += "\n{};\n"
436
437        return code
438
439    def swig_decl(cls):
440        base = cls.get_base()
441
442        code = '%%module %s\n' % cls
443
444        code += '%{\n'
445        code += '#include "params/%s.hh"\n' % cls
446        code += '%}\n\n'
447
448        # The 'dict' attribute restricts us to the params declared in
449        # the object itself, not including inherited params (which
450        # will also be inherited from the base class's param struct
451        # here).
452        params = cls._params.local.values()
453        ptypes = [p.ptype for p in params]
454
455        # get a list of lists of predeclaration lines
456        predecls = []
457        predecls.extend([ p.swig_predecls() for p in params ])
458        # flatten
459        predecls = reduce(lambda x,y:x+y, predecls, [])
460        # remove redundant lines
461        predecls2 = []
462        for pd in predecls:
463            if pd not in predecls2:
464                predecls2.append(pd)
465        predecls2.sort()
466        code += "\n".join(predecls2)
467        code += "\n\n";
468
469        if base:
470            code += '%%import "params/%s.i"\n\n' % base
471
472        for ptype in ptypes:
473            if issubclass(ptype, Enum):
474                code += '%%import "enums/%s.hh"\n' % ptype.__name__
475                code += "\n\n"
476
477        code += '%%import "params/%s_type.hh"\n\n' % cls
478        code += '%%include "params/%s.hh"\n\n' % cls
479
480        return code
481
482# The SimObject class is the root of the special hierarchy.  Most of
483# the code in this class deals with the configuration hierarchy itself
484# (parent/child node relationships).
485class SimObject(object):
486    # Specify metaclass.  Any class inheriting from SimObject will
487    # get this metaclass.
488    __metaclass__ = MetaSimObject
489    type = 'SimObject'
490    abstract = True
491
492    swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
493
494    # Initialize new instance.  For objects with SimObject-valued
495    # children, we need to recursively clone the classes represented
496    # by those param values as well in a consistent "deep copy"-style
497    # fashion.  That is, we want to make sure that each instance is
498    # cloned only once, and that if there are multiple references to
499    # the same original object, we end up with the corresponding
500    # cloned references all pointing to the same cloned instance.
501    def __init__(self, **kwargs):
502        ancestor = kwargs.get('_ancestor')
503        memo_dict = kwargs.get('_memo')
504        if memo_dict is None:
505            # prepare to memoize any recursively instantiated objects
506            memo_dict = {}
507        elif ancestor:
508            # memoize me now to avoid problems with recursive calls
509            memo_dict[ancestor] = self
510
511        if not ancestor:
512            ancestor = self.__class__
513        ancestor._instantiated = True
514
515        # initialize required attributes
516        self._parent = None
517        self._children = {}
518        self._ccObject = None  # pointer to C++ object
519        self._ccParams = None
520        self._instantiated = False # really "cloned"
521
522        # Inherit parameter values from class using multidict so
523        # individual value settings can be overridden.
524        self._values = multidict(ancestor._values)
525        # clone SimObject-valued parameters
526        for key,val in ancestor._values.iteritems():
527            if isSimObject(val):
528                setattr(self, key, val(_memo=memo_dict))
529            elif isSimObjectSequence(val) and len(val):
530                setattr(self, key, [ v(_memo=memo_dict) for v in val ])
531        # clone port references.  no need to use a multidict here
532        # since we will be creating new references for all ports.
533        self._port_refs = {}
534        for key,val in ancestor._port_refs.iteritems():
535            self._port_refs[key] = val.clone(self, memo_dict)
536        # apply attribute assignments from keyword args, if any
537        for key,val in kwargs.iteritems():
538            setattr(self, key, val)
539
540    # "Clone" the current instance by creating another instance of
541    # this instance's class, but that inherits its parameter values
542    # and port mappings from the current instance.  If we're in a
543    # "deep copy" recursive clone, check the _memo dict to see if
544    # we've already cloned this instance.
545    def __call__(self, **kwargs):
546        memo_dict = kwargs.get('_memo')
547        if memo_dict is None:
548            # no memo_dict: must be top-level clone operation.
549            # this is only allowed at the root of a hierarchy
550            if self._parent:
551                raise RuntimeError, "attempt to clone object %s " \
552                      "not at the root of a tree (parent = %s)" \
553                      % (self, self._parent)
554            # create a new dict and use that.
555            memo_dict = {}
556            kwargs['_memo'] = memo_dict
557        elif memo_dict.has_key(self):
558            # clone already done & memoized
559            return memo_dict[self]
560        return self.__class__(_ancestor = self, **kwargs)
561
562    def _get_port_ref(self, attr):
563        # Return reference that can be assigned to another port
564        # via __setattr__.  There is only ever one reference
565        # object per port, but we create them lazily here.
566        ref = self._port_refs.get(attr)
567        if not ref:
568            ref = self._ports[attr].makeRef(self)
569            self._port_refs[attr] = ref
570        return ref
571
572    def __getattr__(self, attr):
573        if self._ports.has_key(attr):
574            return self._get_port_ref(attr)
575
576        if self._values.has_key(attr):
577            return self._values[attr]
578
579        raise AttributeError, "object '%s' has no attribute '%s'" \
580              % (self.__class__.__name__, attr)
581
582    # Set attribute (called on foo.attr = value when foo is an
583    # instance of class cls).
584    def __setattr__(self, attr, value):
585        # normal processing for private attributes
586        if attr.startswith('_'):
587            object.__setattr__(self, attr, value)
588            return
589
590        if self._ports.has_key(attr):
591            # set up port connection
592            self._get_port_ref(attr).connect(value)
593            return
594
595        if isSimObjectOrSequence(value) and self._instantiated:
596            raise RuntimeError, \
597                  "cannot set SimObject parameter '%s' after\n" \
598                  "    instance been cloned %s" % (attr, `self`)
599
600        # must be SimObject param
601        param = self._params.get(attr)
602        if param:
603            try:
604                value = param.convert(value)
605            except Exception, e:
606                msg = "%s\nError setting param %s.%s to %s\n" % \
607                      (e, self.__class__.__name__, attr, value)
608                e.args = (msg, )
609                raise
610            self._set_child(attr, value)
611            return
612
613        if isSimObjectOrSequence(value):
614            self._set_child(attr, value)
615            return
616
617        # no valid assignment... raise exception
618        raise AttributeError, "Class %s has no parameter %s" \
619              % (self.__class__.__name__, attr)
620
621
622    # this hack allows tacking a '[0]' onto parameters that may or may
623    # not be vectors, and always getting the first element (e.g. cpus)
624    def __getitem__(self, key):
625        if key == 0:
626            return self
627        raise TypeError, "Non-zero index '%s' to SimObject" % key
628
629    # clear out children with given name, even if it's a vector
630    def clear_child(self, name):
631        if not self._children.has_key(name):
632            return
633        child = self._children[name]
634        if isinstance(child, SimObjVector):
635            for i in xrange(len(child)):
636                del self._children["s%d" % (name, i)]
637        del self._children[name]
638
639    def add_child(self, name, value):
640        self._children[name] = value
641
642    def _maybe_set_parent(self, parent, name):
643        if not self._parent:
644            self._parent = parent
645            self._name = name
646            parent.add_child(name, self)
647
648    def _set_child(self, attr, value):
649        # if RHS is a SimObject, it's an implicit child assignment
650        # clear out old child with this name, if any
651        self.clear_child(attr)
652
653        if isSimObject(value):
654            value._maybe_set_parent(self, attr)
655        elif isSimObjectSequence(value):
656            value = SimObjVector(value)
657            if len(value) == 1:
658                value[0]._maybe_set_parent(self, attr)
659            else:
660                for i,v in enumerate(value):
661                    v._maybe_set_parent(self, "%s%d" % (attr, i))
662
663        self._values[attr] = value
664
665    def path(self):
666        if not self._parent:
667            return 'root'
668        ppath = self._parent.path()
669        if ppath == 'root':
670            return self._name
671        return ppath + "." + self._name
672
673    def __str__(self):
674        return self.path()
675
676    def ini_str(self):
677        return self.path()
678
679    def find_any(self, ptype):
680        if isinstance(self, ptype):
681            return self, True
682
683        found_obj = None
684        for child in self._children.itervalues():
685            if isinstance(child, ptype):
686                if found_obj != None and child != found_obj:
687                    raise AttributeError, \
688                          'parent.any matched more than one: %s %s' % \
689                          (found_obj.path, child.path)
690                found_obj = child
691        # search param space
692        for pname,pdesc in self._params.iteritems():
693            if issubclass(pdesc.ptype, ptype):
694                match_obj = self._values[pname]
695                if found_obj != None and found_obj != match_obj:
696                    raise AttributeError, \
697                          'parent.any matched more than one: %s' % obj.path
698                found_obj = match_obj
699        return found_obj, found_obj != None
700
701    def unproxy(self, base):
702        return self
703
704    def unproxy_all(self):
705        for param in self._params.iterkeys():
706            value = self._values.get(param)
707            if value != None and proxy.isproxy(value):
708                try:
709                    value = value.unproxy(self)
710                except:
711                    print "Error in unproxying param '%s' of %s" % \
712                          (param, self.path())
713                    raise
714                setattr(self, param, value)
715
716        # Unproxy ports in sorted order so that 'append' operations on
717        # vector ports are done in a deterministic fashion.
718        port_names = self._ports.keys()
719        port_names.sort()
720        for port_name in port_names:
721            port = self._port_refs.get(port_name)
722            if port != None:
723                port.unproxy(self)
724
725        # Unproxy children in sorted order for determinism also.
726        child_names = self._children.keys()
727        child_names.sort()
728        for child in child_names:
729            self._children[child].unproxy_all()
730
731    def print_ini(self, ini_file):
732        print >>ini_file, '[' + self.path() + ']'	# .ini section header
733
734        instanceDict[self.path()] = self
735
736        if hasattr(self, 'type'):
737            print >>ini_file, 'type=%s' % self.type
738
739        child_names = self._children.keys()
740        child_names.sort()
741        if len(child_names):
742            print >>ini_file, 'children=%s' % ' '.join(child_names)
743
744        param_names = self._params.keys()
745        param_names.sort()
746        for param in param_names:
747            value = self._values.get(param)
748            if value != None:
749                print >>ini_file, '%s=%s' % (param,
750                                             self._values[param].ini_str())
751
752        port_names = self._ports.keys()
753        port_names.sort()
754        for port_name in port_names:
755            port = self._port_refs.get(port_name, None)
756            if port != None:
757                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
758
759        print >>ini_file	# blank line between objects
760
761        for child in child_names:
762            self._children[child].print_ini(ini_file)
763
764    def getCCParams(self):
765        if self._ccParams:
766            return self._ccParams
767
768        cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
769        cc_params = cc_params_struct()
770        cc_params.pyobj = self
771        cc_params.name = str(self)
772
773        param_names = self._params.keys()
774        param_names.sort()
775        for param in param_names:
776            value = self._values.get(param)
777            if value is None:
778                continue
779
780            value = value.getValue()
781            if isinstance(self._params[param], VectorParamDesc):
782                assert isinstance(value, list)
783                vec = getattr(cc_params, param)
784                assert not len(vec)
785                for v in value:
786                    vec.append(v)
787            else:
788                setattr(cc_params, param, value)
789
790        port_names = self._ports.keys()
791        port_names.sort()
792        for port_name in port_names:
793            port = self._port_refs.get(port_name, None)
794            if port != None:
795                setattr(cc_params, port_name, port)
796        self._ccParams = cc_params
797        return self._ccParams
798
799    # Get C++ object corresponding to this object, calling C++ if
800    # necessary to construct it.  Does *not* recursively create
801    # children.
802    def getCCObject(self):
803        if not self._ccObject:
804            # Cycles in the configuration heirarchy are not supported. This
805            # will catch the resulting recursion and stop.
806            self._ccObject = -1
807            params = self.getCCParams()
808            self._ccObject = params.create()
809        elif self._ccObject == -1:
810            raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
811                  % self.path()
812        return self._ccObject
813
814    # Call C++ to create C++ object corresponding to this object and
815    # (recursively) all its children
816    def createCCObject(self):
817        self.getCCParams()
818        self.getCCObject() # force creation
819        for child in self._children.itervalues():
820            child.createCCObject()
821
822    def getValue(self):
823        return self.getCCObject()
824
825    # Create C++ port connections corresponding to the connections in
826    # _port_refs (& recursively for all children)
827    def connectPorts(self):
828        for portRef in self._port_refs.itervalues():
829            portRef.ccConnect()
830        for child in self._children.itervalues():
831            child.connectPorts()
832
833    def startDrain(self, drain_event, recursive):
834        count = 0
835        if isinstance(self, SimObject):
836            count += self._ccObject.drain(drain_event)
837        if recursive:
838            for child in self._children.itervalues():
839                count += child.startDrain(drain_event, True)
840        return count
841
842    def resume(self):
843        if isinstance(self, SimObject):
844            self._ccObject.resume()
845        for child in self._children.itervalues():
846            child.resume()
847
848    def getMemoryMode(self):
849        if not isinstance(self, m5.objects.System):
850            return None
851
852        return self._ccObject.getMemoryMode()
853
854    def changeTiming(self, mode):
855        if isinstance(self, m5.objects.System):
856            # i don't know if there's a better way to do this - calling
857            # setMemoryMode directly from self._ccObject results in calling
858            # SimObject::setMemoryMode, not the System::setMemoryMode
859            self._ccObject.setMemoryMode(mode)
860        for child in self._children.itervalues():
861            child.changeTiming(mode)
862
863    def takeOverFrom(self, old_cpu):
864        self._ccObject.takeOverFrom(old_cpu._ccObject)
865
866    # generate output file for 'dot' to display as a pretty graph.
867    # this code is currently broken.
868    def outputDot(self, dot):
869        label = "{%s|" % self.path
870        if isSimObject(self.realtype):
871            label +=  '%s|' % self.type
872
873        if self.children:
874            # instantiate children in same order they were added for
875            # backward compatibility (else we can end up with cpu1
876            # before cpu0).
877            for c in self.children:
878                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
879
880        simobjs = []
881        for param in self.params:
882            try:
883                if param.value is None:
884                    raise AttributeError, 'Parameter with no value'
885
886                value = param.value
887                string = param.string(value)
888            except Exception, e:
889                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
890                e.args = (msg, )
891                raise
892
893            if isSimObject(param.ptype) and string != "Null":
894                simobjs.append(string)
895            else:
896                label += '%s = %s\\n' % (param.name, string)
897
898        for so in simobjs:
899            label += "|<%s> %s" % (so, so)
900            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
901                                    tailport="w"))
902        label += '}'
903        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
904
905        # recursively dump out children
906        for c in self.children:
907            c.outputDot(dot)
908
909# Function to provide to C++ so it can look up instances based on paths
910def resolveSimObject(name):
911    obj = instanceDict[name]
912    return obj.getCCObject()
913
914# __all__ defines the list of symbols that get exported when
915# 'from config import *' is invoked.  Try to keep this reasonably
916# short to avoid polluting other namespaces.
917__all__ = [ 'SimObject' ]
918