changeset 64809024b924 in /z/repo/gem5
details: http://repo.gem5.org/gem5?cmd=changeset;node=64809024b924
description:
config: Add the ability to read a config file using C++ and Python
This patch adds the ability to load in config.ini files generated from
gem5 into another instance of gem5 built without Python configuration
support. The intended use case is for configuring gem5 when it is a
library embedded in another simulation system.
A parallel config file reader is also provided purely in Python to
demonstrate the approach taken and to provided similar functionality
for as-yet-unknown use models. The Python configuration file reader
can read both .ini and .json files.
C++ configuration file reading:
A command line option has been added for scons to enable C++
configuration
file reading: --with-cxx-config
There is an example in util/cxx_config that shows C++ configuration in
action.
util/cxx_config/README explains how to build the example.
Configuration is achieved by the object CxxConfigManager. It handles
reading object descriptions from a CxxConfigFileBase object which
wraps a config file reader. The wrapper class CxxIniFile is provided
which wraps an IniFile for reading .ini files. Reading .json files
from C++ would be possible with a similar wrapper and a JSON parser.
After reading object descriptions, CxxConfigManager creates
SimObjectParam-derived objects from the classes in the (generated with
this
patch) directory build/ARCH/cxx_config
CxxConfigManager can then build SimObjects from those SimObjectParams
(in an
order dictated by the SimObject-value parameters on other objects) and
bind
ports of the produced SimObjects.
A minimal set of instantiate-replacing member functions are provided by
CxxConfigManager and few of the member functions of SimObject (such as
drain)
are extended onto CxxConfigManager.
Python configuration file reading (configs/example/read_config.py):
A Python version of the reader is also supplied with a similar
interface to
CxxConfigFileBase (In Python: ConfigFile) to config file readers.
The Python config file reading will handle both .ini and .json files.
The object construction strategy is slightly different in Python from
the C++
reader as you need to avoid objects prematurely becoming the children
of other
objects when setting parameters.
Port binding also needs to be strictly in the same port-index order as
the
original instantiation.
diffstat:
SConstruct | 3 +
configs/example/read_config.py | 531 +++++++++++++++++++++++++++++
src/SConscript | 67 +++
src/python/m5/SimObject.py | 278 +++++++++++++++
src/python/m5/params.py | 150 ++++++++
src/sim/SConscript | 4 +
src/sim/cxx_config.cc | 45 ++
src/sim/cxx_config.hh | 241 +++++++++++++
src/sim/cxx_config_ini.cc | 104 +++++
src/sim/cxx_config_ini.hh | 87 ++++
src/sim/cxx_manager.cc | 740 +++++++++++++++++++++++++++++++++++++++++
src/sim/cxx_manager.hh | 314 +++++++++++++++++
util/cxx_config/Makefile | 65 +++
util/cxx_config/README | 44 ++
util/cxx_config/main.cc | 319 +++++++++++++++++
util/cxx_config/stats.cc | 115 ++++++
util/cxx_config/stats.hh | 61 +++
17 files changed, 3168 insertions(+), 0 deletions(-)
diffs (truncated from 3385 to 300 lines):
diff -r c0302ad57921 -r 64809024b924 SConstruct
--- a/SConstruct Thu Oct 16 05:49:36 2014 -0400
+++ b/SConstruct Thu Oct 16 05:49:37 2014 -0400
@@ -173,6 +173,9 @@
help="Add color to abbreviated scons output")
AddLocalOption('--no-colors', dest='use_colors', action='store_false',
help="Don't add color to abbreviated scons output")
+AddLocalOption('--with-cxx-config', dest='with_cxx_config',
+ action='store_true',
+ help="Build with support for C++-based configuration")
AddLocalOption('--default', dest='default', type='string', action='store',
help='Override which build_opts file to use for defaults')
AddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
diff -r c0302ad57921 -r 64809024b924 configs/example/read_config.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/configs/example/read_config.py Thu Oct 16 05:49:37 2014 -0400
@@ -0,0 +1,531 @@
+# Copyright (c) 2014 ARM Limited
+# All rights reserved.
+#
+# The license below extends only to copyright in the software and shall
+# not be construed as granting a license to any other intellectual
+# property including but not limited to intellectual property relating
+# to a hardware implementation of the functionality of the software
+# licensed hereunder. You may use the software subject to the license
+# terms below provided that you ensure that this notice is replicated
+# unmodified and in its entirety in all distributions of the software,
+# modified or unmodified, in source code or in binary form.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met: redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer;
+# redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution;
+# neither the name of the copyright holders nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Author: Andrew Bardsley
+
+# This script allows .ini and .json system config file generated from a
+# previous gem5 run to be read in and instantiated.
+#
+# This may be useful as a way of allowing variant run scripts (say,
+# with more complicated than usual checkpointing/stats dumping/
+# simulation control) to read pre-described systems from config scripts
+# with better system-description capabilities. Splitting scripts
+# between system construction and run control may allow better
+# debugging.
+
+import argparse
+import ConfigParser
+import inspect
+import json
+import re
+import sys
+
+import m5
+import m5.ticks as ticks
+
+sim_object_classes_by_name = {
+ cls.__name__: cls for cls in m5.objects.__dict__.itervalues()
+ if inspect.isclass(cls) and issubclass(cls, m5.objects.SimObject) }
+
+# Add some parsing functions to Param classes to handle reading in .ini
+# file elements. This could be moved into src/python/m5/params.py if
+# reading .ini files from Python proves to be useful
+
+def no_parser(cls, flags, param):
+ raise Exception('Can\'t parse string: %s for parameter'
+ ' class: %s' % (str(param), cls.__name__))
+
+def simple_parser(suffix='', cast=lambda i: i):
+ def body(cls, flags, param):
+ return cls(cast(param + suffix))
+ return body
+
+# def tick_parser(cast=m5.objects.Latency): # lambda i: i):
+def tick_parser(cast=lambda i: i):
+ def body(cls, flags, param):
+ old_param = param
+ ret = cls(cast(str(param) + 't'))
+ return ret
+ return body
+
+def addr_range_parser(cls, flags, param):
+ sys.stdout.flush()
+ low, high = param.split(':')
+ return m5.objects.AddrRange(long(low), long(high))
+
+def memory_bandwidth_parser(cls, flags, param):
+ # The string will be in tick/byte
+ # Convert to byte/tick
+ value = 1.0 / float(param)
+ # Convert to byte/s
+ value = ticks.fromSeconds(value)
+ return cls('%fB/s' % value)
+
+# These parameters have trickier parsing from .ini files than might be
+# expected
+param_parsers = {
+ 'Bool': simple_parser(),
+ 'ParamValue': no_parser,
+ 'NumericParamValue': simple_parser(cast=long),
+ 'TickParamValue': tick_parser(),
+ 'Frequency': tick_parser(cast=m5.objects.Latency),
+ 'Voltage': simple_parser(suffix='V'),
+ 'Enum': simple_parser(),
+ 'MemorySize': simple_parser(suffix='B'),
+ 'MemorySize32': simple_parser(suffix='B'),
+ 'AddrRange': addr_range_parser,
+ 'String': simple_parser(),
+ 'MemoryBandwidth': memory_bandwidth_parser,
+ 'Time': simple_parser()
+ }
+
+for name, parser in param_parsers.iteritems():
+ setattr(m5.params.__dict__[name], 'parse_ini', classmethod(parser))
+
+class PortConnection(object):
+ """This class is similar to m5.params.PortRef but with just enough
+ information for ConfigManager"""
+
+ def __init__(self, object_name, port_name, index):
+ self.object_name = object_name
+ self.port_name = port_name
+ self.index = index
+
+ @classmethod
+ def from_string(cls, str):
+ m = re.match('(.*)\.([^.\[]+)(\[(\d+)\])?', str)
+ object_name, port_name, whole_index, index = m.groups()
+ if index is not None:
+ index = int(index)
+ else:
+ index = 0
+
+ return PortConnection(object_name, port_name, index)
+
+ def __str__(self):
+ return '%s.%s[%d]' % (self.object_name, self.port_name, self.index)
+
+ def __cmp__(self, right):
+ return cmp((self.object_name, self.port_name, self.index),
+ (right.object_name, right.port_name, right.index))
+
+def to_list(v):
+ """Convert any non list to a singleton list"""
+ if isinstance(v, list):
+ return v
+ else:
+ return [v]
+
+class ConfigManager(object):
+ """Manager for parsing a Root configuration from a config file"""
+ def __init__(self, config):
+ self.config = config
+ self.objects_by_name = {}
+ self.flags = config.get_flags()
+
+ def find_object(self, object_name):
+ """Find and configure (with just non-SimObject parameters)
+ a single object"""
+
+ if object_name == 'Null':
+ return NULL
+
+ if object_name in self.objects_by_name:
+ return self.objects_by_name[object_name]
+
+ object_type = self.config.get_param(object_name, 'type')
+
+ if object_type not in sim_object_classes_by_name:
+ raise Exception('No SimObject type %s is available to'
+ ' build: %s' % (object_type, object_name))
+
+ object_class = sim_object_classes_by_name[object_type]
+
+ parsed_params = {}
+
+ for param_name, param in object_class._params.iteritems():
+ if issubclass(param.ptype, m5.params.ParamValue):
+ if isinstance(param, m5.params.VectorParamDesc):
+ param_values = self.config.get_param_vector(object_name,
+ param_name)
+
+ param_value = [ param.ptype.parse_ini(self.flags, value)
+ for value in param_values ]
+ else:
+ param_value = param.ptype.parse_ini(
+ self.flags, self.config.get_param(object_name,
+ param_name))
+
+ parsed_params[param_name] = param_value
+
+ obj = object_class(**parsed_params)
+ self.objects_by_name[object_name] = obj
+
+ return obj
+
+ def fill_in_simobj_parameters(self, object_name, obj):
+ """Fill in all references to other SimObjects in an objects
+ parameters. This relies on all referenced objects having been
+ created"""
+
+ if object_name == 'Null':
+ return NULL
+
+ for param_name, param in obj.__class__._params.iteritems():
+ if issubclass(param.ptype, m5.objects.SimObject):
+ if isinstance(param, m5.params.VectorParamDesc):
+ param_values = self.config.get_param_vector(object_name,
+ param_name)
+
+ setattr(obj, param_name, [ self.objects_by_name[name]
+ for name in param_values ])
+ else:
+ param_value = self.config.get_param(object_name,
+ param_name)
+
+ if param_value != 'Null':
+ setattr(obj, param_name, self.objects_by_name[
+ param_value])
+
+ return obj
+
+ def fill_in_children(self, object_name, obj):
+ """Fill in the children of this object. This relies on all the
+ referenced objects having been created"""
+
+ children = self.config.get_object_children(object_name)
+
+ for child_name, child_paths in children:
+ param = obj.__class__._params.get(child_name, None)
+
+ if isinstance(child_paths, list):
+ child_list = [ self.objects_by_name[path]
+ for path in child_paths ]
+ else:
+ child_list = self.objects_by_name[child_paths]
+
+ obj.add_child(child_name, child_list)
+
+ for path in to_list(child_paths):
+ self.fill_in_children(path, self.objects_by_name[path])
+
+ return obj
+
+ def parse_port_name(self, port):
+ """Parse the name of a port"""
+
+ m = re.match('(.*)\.([^.\[]+)(\[(\d+)\])?', port)
+ peer, peer_port, whole_index, index = m.groups()
+ if index is not None:
+ index = int(index)
+ else:
+ index = 0
+
+ return (peer, self.objects_by_name[peer], peer_port, index)
+
+ def gather_port_connections(self, object_name, obj):
+ """Gather all the port-to-port connections from the named object.
+ Returns a list of (PortConnection, PortConnection) with unordered
+ (wrt. master/slave) connection information"""
+
+ if object_name == 'Null':
+ return NULL
+
+ parsed_ports = []
+ for port_name, port in obj.__class__._ports.iteritems():
+ # Assume that unnamed ports are unconnected
+ peers = self.config.get_port_peers(object_name, port_name)
+
+ for index, peer in zip(xrange(0, len(peers)), peers):
+ parsed_ports.append((
+ PortConnection(object_name, port.name, index),
+ PortConnection.from_string(peer)))
+
+ return parsed_ports
+
+ def bind_ports(self, connections):
+ """Bind all ports from the given connection list. Note that the
+ connection list *must* list all connections with both (slave,master)
+ and (master,slave) orderings"""
+
+ # Markup a dict of how many connections are made to each port.
_______________________________________________
gem5-dev mailing list
[email protected]
http://m5sim.org/mailman/listinfo/gem5-dev