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