3 # Copyright (c) 2004-2005 The Regents of The University of Michigan
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
8 # met: redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer;
10 # redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution;
13 # neither the name of the copyright holders nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 # Authors: Nathan Binkert
40 from os.path import basename, dirname, exists, isdir, isfile, join as joinpath
44 # This file defines how to build a particular configuration of M5
45 # based on variable settings in the 'env' build environment.
49 # Children need to see the environment
52 build_env = [(opt, env[opt]) for opt in export_vars]
54 ########################################################################
55 # Code for adding source files of various types
57 class SourceMeta(type):
58 def __init__(cls, name, bases, dict):
59 super(SourceMeta, cls).__init__(name, bases, dict)
62 def get(cls, **kwargs):
64 for attr,value in kwargs.iteritems():
65 if getattr(src, attr) != value:
70 class SourceFile(object):
71 __metaclass__ = SourceMeta
72 def __init__(self, source):
74 if not isinstance(source, SCons.Node.FS.File):
78 self.snode = tnode.srcnode()
79 self.filename = str(tnode)
80 self.dirname = dirname(self.filename)
81 self.basename = basename(self.filename)
82 index = self.basename.rfind('.')
84 # dot files aren't extensions
85 self.extname = self.basename, None
87 self.extname = self.basename[:index], self.basename[index+1:]
89 for base in type(self).__mro__:
90 if issubclass(base, SourceFile):
91 bisect.insort_right(base.all, self)
93 def __lt__(self, other): return self.filename < other.filename
94 def __le__(self, other): return self.filename <= other.filename
95 def __gt__(self, other): return self.filename > other.filename
96 def __ge__(self, other): return self.filename >= other.filename
97 def __eq__(self, other): return self.filename == other.filename
98 def __ne__(self, other): return self.filename != other.filename
100 class Source(SourceFile):
101 '''Add a c/c++ source file to the build'''
102 def __init__(self, source, Werror=True, swig=False, bin_only=False,
104 super(Source, self).__init__(source)
108 self.bin_only = bin_only
109 self.skip_lib = bin_only or skip_lib
111 class PySource(SourceFile):
112 '''Add a python source file to the named package'''
113 invalid_sym_char = re.compile('[^A-z0-9_]')
118 def __init__(self, package, source):
119 super(PySource, self).__init__(source)
121 modname,ext = self.extname
125 path = package.split('.')
130 if modname != '__init__':
131 modpath += [ modname ]
132 modpath = '.'.join(modpath)
134 arcpath = path + [ self.basename ]
135 debugname = self.snode.abspath
136 if not exists(debugname):
137 debugname = self.tnode.abspath
139 self.package = package
140 self.modname = modname
141 self.modpath = modpath
142 self.arcname = joinpath(*arcpath)
143 self.debugname = debugname
144 self.compiled = File(self.filename + 'c')
145 self.assembly = File(self.filename + '.s')
146 self.symname = "PyEMB_" + PySource.invalid_sym_char.sub('_', modpath)
148 PySource.modules[modpath] = self
149 PySource.tnodes[self.tnode] = self
150 PySource.symnames[self.symname] = self
152 class SimObject(PySource):
153 '''Add a SimObject python file as a python source object and add
154 it to a list of sim object modules'''
159 def __init__(self, source):
160 super(SimObject, self).__init__('m5.objects', source)
162 raise AttributeError, "Too late to call SimObject now."
164 bisect.insort_right(SimObject.modnames, self.modname)
166 class SwigSource(SourceFile):
167 '''Add a swig file to build'''
169 def __init__(self, package, source):
170 super(SwigSource, self).__init__(source)
172 modname,ext = self.extname
175 self.module = modname
176 cc_file = joinpath(self.dirname, modname + '_wrap.cc')
177 py_file = joinpath(self.dirname, modname + '.py')
179 self.cc_source = Source(cc_file, swig=True)
180 self.py_source = PySource(package, py_file)
183 def UnitTest(target, sources):
184 if not isinstance(sources, (list, tuple)):
185 sources = [ sources ]
187 sources = [ Source(src, skip_lib=True) for src in sources ]
188 unit_tests.append((target, sources))
190 # Children should have access
197 ########################################################################
202 def TraceFlag(name, desc=None):
203 if name in trace_flags:
204 raise AttributeError, "Flag %s already specified" % name
205 trace_flags[name] = (name, (), desc)
207 def CompoundFlag(name, flags, desc=None):
208 if name in trace_flags:
209 raise AttributeError, "Flag %s already specified" % name
211 compound = tuple(flags)
212 trace_flags[name] = (name, compound, desc)
215 Export('CompoundFlag')
217 ########################################################################
219 # Set some compiler variables
222 # Include file paths are rooted in this directory. SCons will
223 # automatically expand '.' to refer to both the source directory and
224 # the corresponding build directory to pick up generated include
226 env.Append(CPPPATH=Dir('.'))
228 for extra_dir in extras_dir_list:
229 env.Append(CPPPATH=Dir(extra_dir))
231 # Workaround for bug in SCons version > 0.97d20071212
232 # Scons bug id: 2006 M5 Bug id: 308
233 for root, dirs, files in os.walk(base_dir, topdown=True):
234 Dir(root[len(base_dir) + 1:])
236 ########################################################################
238 # Walk the tree and execute all SConscripts in subdirectories
241 here = Dir('.').srcnode().abspath
242 for root, dirs, files in os.walk(base_dir, topdown=True):
244 # we don't want to recurse back into this SConscript
247 if 'SConscript' in files:
248 build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
249 SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
251 for extra_dir in extras_dir_list:
252 prefix_len = len(dirname(extra_dir)) + 1
253 for root, dirs, files in os.walk(extra_dir, topdown=True):
254 if 'SConscript' in files:
255 build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
256 SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
258 for opt in export_vars:
261 def makeTheISA(source, target, env):
262 f = file(str(target[0]), 'w')
264 isas = [ src.get_contents() for src in source ]
265 target = env['TARGET_ISA']
267 return isa.upper() + '_ISA'
270 return isa[0].upper() + isa[1:].lower() + 'ISA'
273 print >>f, '#ifndef __CONFIG_THE_ISA_HH__'
274 print >>f, '#define __CONFIG_THE_ISA_HH__'
276 for i,isa in enumerate(isas):
277 print >>f, '#define %s %d' % (define(isa), i + 1)
279 print >>f, '#define THE_ISA %s' % (define(target))
280 print >>f, '#define TheISA %s' % (namespace(target))
282 print >>f, '#endif // __CONFIG_THE_ISA_HH__'
284 env.Command('config/the_isa.hh', map(Value, all_isa_list), makeTheISA)
286 ########################################################################
288 # Prevent any SimObjects from being added after this point, they
289 # should all have been added in the SConscripts above
291 SimObject.fixed = True
293 class DictImporter(object):
294 '''This importer takes a dictionary of arbitrary module names that
295 map to arbitrary filenames.'''
296 def __init__(self, modules):
297 self.modules = modules
298 self.installed = set()
305 for module in self.installed:
306 del sys.modules[module]
307 self.installed = set()
309 def find_module(self, fullname, path):
310 if fullname == 'm5.defines':
313 if fullname == 'm5.objects':
316 if fullname.startswith('m5.internal'):
319 source = self.modules.get(fullname, None)
320 if source is not None and fullname.startswith('m5.objects'):
325 def load_module(self, fullname):
326 mod = imp.new_module(fullname)
327 sys.modules[fullname] = mod
328 self.installed.add(fullname)
330 mod.__loader__ = self
331 if fullname == 'm5.objects':
332 mod.__path__ = fullname.split('.')
335 if fullname == 'm5.defines':
336 mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
339 source = self.modules[fullname]
340 if source.modname == '__init__':
341 mod.__path__ = source.modpath
342 mod.__file__ = source.snode.abspath
344 exec file(source.snode.abspath, 'r') in mod.__dict__
354 # install the python importer so we can grab stuff from the source
355 # tree itself. We can't have SimObjects added after this point or
356 # else we won't know about them for the rest of the stuff.
357 importer = DictImporter(PySource.modules)
358 sys.meta_path[0:0] = [ importer ]
360 # import all sim objects so we can populate the all_objects list
361 # make sure that we're working with a list, then let's sort it
362 for modname in SimObject.modnames:
363 exec('from m5.objects import %s' % modname)
365 # we need to unload all of the currently imported modules so that they
366 # will be re-imported the next time the sconscript is run
368 sys.meta_path.remove(importer)
370 sim_objects = m5.SimObject.allClasses
371 all_enums = m5.params.allEnums
374 for name,obj in sorted(sim_objects.iteritems()):
375 for param in obj._params.local.values():
376 # load the ptype attribute now because it depends on the
377 # current version of SimObject.allClasses, but when scons
378 # actually uses the value, all versions of
379 # SimObject.allClasses will have been loaded
382 if not hasattr(param, 'swig_decl'):
384 pname = param.ptype_str
385 if pname not in all_params:
386 all_params[pname] = param
388 ########################################################################
390 # calculate extra dependencies
392 module_depends = ["m5", "m5.SimObject", "m5.params"]
393 depends = [ PySource.modules[dep].tnode for dep in module_depends ]
395 ########################################################################
397 # Commands for the basic automatically generated python files
400 # Generate Python file containing a dict specifying the current
402 def makeDefinesPyFile(target, source, env):
403 build_env, hg_info = [ x.get_contents() for x in source ]
405 code = m5.util.code_formatter()
410 buildEnv = m5.util.SmartDict($build_env)
413 compileDate = m5.internal.core.compileDate
415 for key,val in m5.internal.core.__dict__.iteritems():
416 if key.startswith('flag_'):
421 code.write(str(target[0]))
423 defines_info = [ Value(build_env), Value(env['HG_INFO']) ]
424 # Generate a file with all of the compile options in it
425 env.Command('python/m5/defines.py', defines_info, makeDefinesPyFile)
426 PySource('m5', 'python/m5/defines.py')
428 # Generate python file containing info about the M5 source code
429 def makeInfoPyFile(target, source, env):
430 f = file(str(target[0]), 'w')
432 data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
433 print >>f, "%s = %s" % (src, repr(data))
436 # Generate a file that wraps the basic top level files
437 env.Command('python/m5/info.py',
438 [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
440 PySource('m5', 'python/m5/info.py')
442 # Generate the __init__.py file for m5.objects
443 def makeObjectsInitFile(target, source, env):
444 f = file(str(target[0]), 'w')
445 print >>f, 'from params import *'
446 print >>f, 'from m5.SimObject import *'
447 for module in source:
448 print >>f, 'from %s import *' % module.get_contents()
451 # Generate an __init__.py file for the objects package
452 env.Command('python/m5/objects/__init__.py',
453 map(Value, SimObject.modnames),
455 PySource('m5.objects', 'python/m5/objects/__init__.py')
457 ########################################################################
459 # Create all of the SimObject param headers and enum headers
462 def createSimObjectParam(target, source, env):
463 assert len(target) == 1 and len(source) == 1
465 hh_file = file(target[0].abspath, 'w')
466 name = str(source[0].get_contents())
467 obj = sim_objects[name]
469 print >>hh_file, obj.cxx_decl()
472 def createSwigParam(target, source, env):
473 assert len(target) == 1 and len(source) == 1
475 i_file = file(target[0].abspath, 'w')
476 name = str(source[0].get_contents())
477 param = all_params[name]
479 for line in param.swig_decl():
483 def createEnumStrings(target, source, env):
484 assert len(target) == 1 and len(source) == 1
486 cc_file = file(target[0].abspath, 'w')
487 name = str(source[0].get_contents())
488 obj = all_enums[name]
490 print >>cc_file, obj.cxx_def()
493 def createEnumParam(target, source, env):
494 assert len(target) == 1 and len(source) == 1
496 hh_file = file(target[0].abspath, 'w')
497 name = str(source[0].get_contents())
498 obj = all_enums[name]
500 print >>hh_file, obj.cxx_decl()
503 # Generate all of the SimObject param struct header files
505 for name,simobj in sorted(sim_objects.iteritems()):
506 py_source = PySource.modules[simobj.__module__]
507 extra_deps = [ py_source.tnode ]
509 hh_file = File('params/%s.hh' % name)
510 params_hh_files.append(hh_file)
511 env.Command(hh_file, Value(name), createSimObjectParam)
512 env.Depends(hh_file, depends + extra_deps)
514 # Generate any parameter header files needed
516 for name,param in all_params.iteritems():
517 i_file = File('params/%s_%s.i' % (name, param.file_ext))
518 params_i_files.append(i_file)
519 env.Command(i_file, Value(name), createSwigParam)
520 env.Depends(i_file, depends)
522 # Generate all enum header files
523 for name,enum in sorted(all_enums.iteritems()):
524 py_source = PySource.modules[enum.__module__]
525 extra_deps = [ py_source.tnode ]
527 cc_file = File('enums/%s.cc' % name)
528 env.Command(cc_file, Value(name), createEnumStrings)
529 env.Depends(cc_file, depends + extra_deps)
532 hh_file = File('enums/%s.hh' % name)
533 env.Command(hh_file, Value(name), createEnumParam)
534 env.Depends(hh_file, depends + extra_deps)
536 # Build the big monolithic swigged params module (wraps all SimObject
537 # param structs and enum structs)
538 def buildParams(target, source, env):
539 names = [ s.get_contents() for s in source ]
540 objs = [ sim_objects[name] for name in names ]
541 out = file(target[0].abspath, 'w')
551 if str(obj) != 'SimObject':
552 order_obj(obj.__bases__[0])
554 ordered_objs.append(obj)
565 if pd not in pd_seen:
569 for obj in ordered_objs:
570 params = obj._params.local.values()
573 if issubclass(ptype, m5.params.Enum):
574 if ptype not in enums:
576 pds = param.swig_predecls()
577 if isinstance(pds, (list, tuple)):
582 print >>out, '%module params'
585 for obj in ordered_objs:
586 print >>out, '#include "params/%s.hh"' % obj
595 print >>out, '%%include "enums/%s.hh"' % enum.__name__
598 for obj in ordered_objs:
599 if obj.swig_objdecls:
600 for decl in obj.swig_objdecls:
604 class_path = obj.cxx_class.split('::')
605 classname = class_path[-1]
606 namespaces = class_path[:-1]
612 code += '// avoid name conflicts\n'
613 sep_string = '_COLONS_'
614 flat_name = sep_string.join(class_path)
615 code += '%%rename(%s) %s;\n' % (flat_name, classname)
617 code += '// stop swig from creating/wrapping default ctor/dtor\n'
618 code += '%%nodefault %s;\n' % classname
619 code += 'class %s ' % classname
621 code += ': public %s' % obj._base.cxx_class
624 for ns in namespaces:
625 new_code = 'namespace %s {\n' % ns
632 print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
633 for obj in ordered_objs:
634 print >>out, '%%include "params/%s.hh"' % obj
636 params_file = File('params/params.i')
637 names = sorted(sim_objects.keys())
638 env.Command(params_file, map(Value, names), buildParams)
639 env.Depends(params_file, params_hh_files + params_i_files + depends)
640 SwigSource('m5.objects', params_file)
642 # Build all swig modules
643 for swig in SwigSource.all:
644 env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
645 '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
646 '-o ${TARGETS[0]} $SOURCES')
647 env.Depends(swig.py_source.tnode, swig.tnode)
648 env.Depends(swig.cc_source.tnode, swig.tnode)
650 # Generate the main swig init file
651 def makeSwigInit(target, source, env):
652 f = file(str(target[0]), 'w')
653 print >>f, 'extern "C" {'
654 for module in source:
655 print >>f, ' void init_%s();' % module.get_contents()
657 print >>f, 'void initSwig() {'
658 for module in source:
659 print >>f, ' init_%s();' % module.get_contents()
663 env.Command('python/swig/init.cc',
664 map(Value, sorted(s.module for s in SwigSource.all)),
666 Source('python/swig/init.cc')
668 def getFlags(source_flags):
671 for s in source_flags:
672 val = eval(s.get_contents())
673 name, compound, desc = val
674 flagsList.append(val)
675 flagsMap[name] = bool(compound)
677 for name, compound, desc in flagsList:
678 for flag in compound:
679 if flag not in flagsMap:
680 raise AttributeError, "Trace flag %s not found" % flag
682 raise AttributeError, \
683 "Compound flag can't point to another compound flag"
689 # Generate traceflags.py
690 def traceFlagsPy(target, source, env):
691 assert(len(target) == 1)
693 f = file(str(target[0]), 'w')
695 allFlags = getFlags(source)
697 print >>f, 'basic = ['
698 for flag, compound, desc in allFlags:
700 print >>f, " '%s'," % flag
704 print >>f, 'compound = ['
706 for flag, compound, desc in allFlags:
708 print >>f, " '%s'," % flag
712 print >>f, "all = frozenset(basic + compound)"
715 print >>f, 'compoundMap = {'
716 all = tuple([flag for flag,compound,desc in allFlags if not compound])
717 print >>f, " 'All' : %s," % (all, )
718 for flag, compound, desc in allFlags:
720 print >>f, " '%s' : %s," % (flag, compound)
724 print >>f, 'descriptions = {'
725 print >>f, " 'All' : 'All flags',"
726 for flag, compound, desc in allFlags:
727 print >>f, " '%s' : '%s'," % (flag, desc)
732 def traceFlagsCC(target, source, env):
733 assert(len(target) == 1)
735 f = file(str(target[0]), 'w')
737 allFlags = getFlags(source)
742 * DO NOT EDIT THIS FILE! Automatically generated
745 #include "base/traceflags.hh"
747 using namespace Trace;
749 const char *Trace::flagStrings[] =
752 # The string array is used by SimpleEnumParam to map the strings
753 # provided by the user to enum values.
754 for flag, compound, desc in allFlags:
756 print >>f, ' "%s",' % flag
759 for flag, compound, desc in allFlags:
761 print >>f, ' "%s",' % flag
765 print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
769 # Now define the individual compound flag arrays. There is an array
770 # for each compound flag listing the component base flags.
772 all = tuple([flag for flag,compound,desc in allFlags if not compound])
773 print >>f, 'static const Flags AllMap[] = {'
774 for flag, compound, desc in allFlags:
776 print >>f, " %s," % flag
780 for flag, compound, desc in allFlags:
783 print >>f, 'static const Flags %sMap[] = {' % flag
784 for flag in compound:
785 print >>f, " %s," % flag
786 print >>f, " (Flags)-1"
791 # Finally the compoundFlags[] array maps the compound flags
792 # to their individual arrays/
794 print >>f, 'const Flags *Trace::compoundFlags[] ='
796 print >>f, ' AllMap,'
797 for flag, compound, desc in allFlags:
799 print >>f, ' %sMap,' % flag
805 def traceFlagsHH(target, source, env):
806 assert(len(target) == 1)
808 f = file(str(target[0]), 'w')
810 allFlags = getFlags(source)
812 # file header boilerplate
815 * DO NOT EDIT THIS FILE!
817 * Automatically generated from traceflags.py
820 #ifndef __BASE_TRACE_FLAGS_HH__
821 #define __BASE_TRACE_FLAGS_HH__
827 # Generate the enum. Base flags come first, then compound flags.
829 for flag, compound, desc in allFlags:
831 print >>f, ' %s = %d,' % (flag, idx)
835 print >>f, ' NumFlags = %d,' % idx
837 # put a comment in here to separate base from compound flags
839 // The remaining enum values are *not* valid indices for Trace::flags.
840 // They are "compound" flags, which correspond to sets of base
841 // flags, and are used by changeFlag.'''
843 print >>f, ' All = %d,' % idx
845 for flag, compound, desc in allFlags:
847 print >>f, ' %s = %d,' % (flag, idx)
850 numCompoundFlags = idx - numBaseFlags
851 print >>f, ' NumCompoundFlags = %d' % numCompoundFlags
853 # trailer boilerplate
857 // Array of strings for SimpleEnumParam
858 extern const char *flagStrings[];
859 extern const int numFlagStrings;
861 // Array of arraay pointers: for each compound flag, gives the list of
862 // base flags to set. Inidividual flag arrays are terminated by -1.
863 extern const Flags *compoundFlags[];
865 /* namespace Trace */ }
867 #endif // __BASE_TRACE_FLAGS_HH__
872 flags = map(Value, trace_flags.values())
873 env.Command('base/traceflags.py', flags, traceFlagsPy)
874 PySource('m5', 'base/traceflags.py')
876 env.Command('base/traceflags.hh', flags, traceFlagsHH)
877 env.Command('base/traceflags.cc', flags, traceFlagsCC)
878 Source('base/traceflags.cc')
880 # embed python files. All .py files that have been indicated by a
881 # PySource() call in a SConscript need to be embedded into the M5
882 # library. To do that, we compile the file to byte code, marshal the
883 # byte code, compress it, and then generate an assembly file that
884 # inserts the result into the data section with symbols indicating the
885 # beginning, and end (and with the size at the end)
886 def objectifyPyFile(target, source, env):
887 '''Action function to compile a .py into a code object, marshal
888 it, compress it, and stick it into an asm file so the code appears
889 as just bytes with a label in the data section'''
891 src = file(str(source[0]), 'r').read()
892 dst = file(str(target[0]), 'w')
894 pysource = PySource.tnodes[source[0]]
895 compiled = compile(src, pysource.debugname, 'exec')
896 marshalled = marshal.dumps(compiled)
897 compressed = zlib.compress(marshalled)
900 # Some C/C++ compilers prepend an underscore to global symbol
901 # names, so if they're going to do that, we need to prepend that
902 # leading underscore to globals in the assembly file.
903 if env['LEADING_UNDERSCORE']:
904 sym = '_' + pysource.symname
906 sym = pysource.symname
910 print >>dst, ".globl %s_beg" % sym
911 print >>dst, ".globl %s_end" % sym
912 print >>dst, "%s_beg:" % sym
913 for i in xrange(0, len(data), step):
914 x = array.array('B', data[i:i+step])
915 print >>dst, ".byte", ','.join([str(d) for d in x])
916 print >>dst, "%s_end:" % sym
917 print >>dst, ".long %d" % len(marshalled)
919 for source in PySource.all:
920 env.Command(source.assembly, source.tnode, objectifyPyFile)
921 Source(source.assembly)
923 # Generate init_python.cc which creates a bunch of EmbeddedPyModule
924 # structs that describe the embedded python code. One such struct
925 # contains information about the importer that python uses to get at
926 # the embedded files, and then there's a list of all of the rest that
927 # the importer uses to load the rest on demand.
928 def pythonInit(target, source, env):
929 dst = file(str(target[0]), 'w')
931 def dump_mod(sym, endchar=','):
932 pysource = PySource.symnames[sym]
933 print >>dst, ' { "%s",' % pysource.arcname
934 print >>dst, ' "%s",' % pysource.modpath
935 print >>dst, ' %s_beg, %s_end,' % (sym, sym)
936 print >>dst, ' %s_end - %s_beg,' % (sym, sym)
937 print >>dst, ' *(int *)%s_end }%s' % (sym, endchar)
939 print >>dst, '#include "sim/init.hh"'
942 sym = sym.get_contents()
943 print >>dst, "extern const char %s_beg[], %s_end[];" % (sym, sym)
945 print >>dst, "const EmbeddedPyModule embeddedPyImporter = "
946 dump_mod("PyEMB_importer", endchar=';');
949 print >>dst, "const EmbeddedPyModule embeddedPyModules[] = {"
950 for i,sym in enumerate(source):
951 sym = sym.get_contents()
952 if sym == "PyEMB_importer":
953 # Skip the importer since we've already exported it
956 print >>dst, " { 0, 0, 0, 0, 0, 0 }"
960 env.Command('sim/init_python.cc',
961 map(Value, (s.symname for s in PySource.all)),
963 Source('sim/init_python.cc')
965 ########################################################################
967 # Define binaries. Each different build type (debug, opt, etc.) gets
968 # a slightly different build environment.
971 # List of constructed environments to pass back to SConstruct
974 date_source = Source('base/date.cc', skip_lib=True)
976 # Function to create a new build environment as clone of current
977 # environment 'env' with modified object suffix and optional stripped
978 # binary. Additional keyword arguments are appended to corresponding
979 # build environment vars.
980 def makeEnv(label, objsfx, strip = False, **kwargs):
981 # SCons doesn't know to append a library suffix when there is a '.' in the
982 # name. Use '_' instead.
983 libname = 'm5_' + label
984 exename = 'm5.' + label
986 new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
987 new_env.Label = label
988 new_env.Append(**kwargs)
990 swig_env = new_env.Clone()
991 swig_env.Append(CCFLAGS='-Werror')
993 swig_env.Append(CCFLAGS='-Wno-uninitialized')
994 swig_env.Append(CCFLAGS='-Wno-sign-compare')
995 swig_env.Append(CCFLAGS='-Wno-parentheses')
997 werror_env = new_env.Clone()
998 werror_env.Append(CCFLAGS='-Werror')
1000 def make_obj(source, static, extra_deps = None):
1001 '''This function adds the specified source to the correct
1002 build environment, and returns the corresponding SCons Object
1013 obj = env.StaticObject(source.tnode)
1015 obj = env.SharedObject(source.tnode)
1018 env.Depends(obj, extra_deps)
1022 static_objs = [ make_obj(s, True) for s in Source.get(skip_lib=False)]
1023 shared_objs = [ make_obj(s, False) for s in Source.get(skip_lib=False)]
1025 static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1026 static_objs.append(static_date)
1028 shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1029 shared_objs.append(shared_date)
1031 # First make a library of everything but main() so other programs can
1033 static_lib = new_env.StaticLibrary(libname, static_objs)
1034 shared_lib = new_env.SharedLibrary(libname, shared_objs)
1036 for target, sources in unit_tests:
1037 objs = [ make_obj(s, static=True) for s in sources ]
1038 new_env.Program("unittest/%s.%s" % (target, label), objs + static_objs)
1040 # Now link a stub with main() and the static library.
1041 bin_objs = [make_obj(s, True) for s in Source.get(bin_only=True) ]
1044 progname += '.unstripped'
1046 targets = new_env.Program(progname, bin_objs + static_objs)
1049 if sys.platform == 'sunos5':
1050 cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1052 cmd = 'strip $SOURCE -o $TARGET'
1053 targets = new_env.Command(exename, progname, cmd)
1055 new_env.M5Binary = targets[0]
1056 envList.append(new_env)
1061 if sys.platform == 'sunos5':
1062 ccflags['debug'] = '-gstabs+'
1064 ccflags['debug'] = '-ggdb3'
1065 ccflags['opt'] = '-g -O3'
1066 ccflags['fast'] = '-O3'
1067 ccflags['prof'] = '-O3 -g -pg'
1069 ccflags['debug'] = '-g0'
1070 ccflags['opt'] = '-g -O'
1071 ccflags['fast'] = '-fast'
1072 ccflags['prof'] = '-fast -g -pg'
1074 ccflags['debug'] = '-g -O0'
1075 ccflags['opt'] = '-g -O'
1076 ccflags['fast'] = '-fast'
1077 ccflags['prof'] = '-fast -g -pg'
1079 print 'Unknown compiler, please fix compiler options'
1082 makeEnv('debug', '.do',
1083 CCFLAGS = Split(ccflags['debug']),
1084 CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
1087 makeEnv('opt', '.o',
1088 CCFLAGS = Split(ccflags['opt']),
1089 CPPDEFINES = ['TRACING_ON=1'])
1092 makeEnv('fast', '.fo', strip = True,
1093 CCFLAGS = Split(ccflags['fast']),
1094 CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
1097 makeEnv('prof', '.po',
1098 CCFLAGS = Split(ccflags['prof']),
1099 CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],