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 gem5
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 from m5.util import code_formatter, compareVersions
56 ########################################################################
57 # Code for adding source files of various types
59 # When specifying a source file of some type, a set of guards can be
60 # specified for that file. When get() is used to find the files, if
61 # get specifies a set of filters, only files that match those filters
62 # will be accepted (unspecified filters on files are assumed to be
63 # false). Current filters are:
64 # main -- specifies the gem5 main() function
65 # skip_lib -- do not put this file into the gem5 library
66 # <unittest> -- unit tests use filters based on the unit test name
68 # A parent can now be specified for a source file and default filter
69 # values will be retrieved recursively from parents (children override
72 class SourceMeta(type):
73 '''Meta class for source files that keeps track of all files of a
74 particular type and has a get function for finding all functions
75 of a certain type that match a set of guards'''
76 def __init__(cls, name, bases, dict):
77 super(SourceMeta, cls).__init__(name, bases, dict)
80 def get(cls, **guards):
81 '''Find all files that match the specified guards. If a source
82 file does not specify a flag, the default is False'''
84 for flag,value in guards.iteritems():
85 # if the flag is found and has a different value, skip
87 if src.all_guards.get(flag, False) != value:
92 class SourceFile(object):
93 '''Base object that encapsulates the notion of a source file.
94 This includes, the source node, target node, various manipulations
95 of those. A source file also specifies a set of guards which
96 describing which builds the source file applies to. A parent can
97 also be specified to get default guards from'''
98 __metaclass__ = SourceMeta
99 def __init__(self, source, parent=None, **guards):
104 if not isinstance(source, SCons.Node.FS.File):
108 self.snode = tnode.srcnode()
110 for base in type(self).__mro__:
111 if issubclass(base, SourceFile):
112 base.all.append(self)
116 return str(self.tnode)
120 return dirname(self.filename)
124 return basename(self.filename)
128 index = self.basename.rfind('.')
130 # dot files aren't extensions
131 return self.basename, None
133 return self.basename[:index], self.basename[index+1:]
136 def all_guards(self):
137 '''find all guards for this object getting default values
138 recursively from its parents'''
141 guards.update(self.parent.guards)
142 guards.update(self.guards)
145 def __lt__(self, other): return self.filename < other.filename
146 def __le__(self, other): return self.filename <= other.filename
147 def __gt__(self, other): return self.filename > other.filename
148 def __ge__(self, other): return self.filename >= other.filename
149 def __eq__(self, other): return self.filename == other.filename
150 def __ne__(self, other): return self.filename != other.filename
152 class Source(SourceFile):
153 '''Add a c/c++ source file to the build'''
154 def __init__(self, source, Werror=True, swig=False, **guards):
155 '''specify the source file, and any guards'''
156 super(Source, self).__init__(source, **guards)
161 class PySource(SourceFile):
162 '''Add a python source file to the named package'''
163 invalid_sym_char = re.compile('[^A-z0-9_]')
168 def __init__(self, package, source, **guards):
169 '''specify the python package, the source file, and any guards'''
170 super(PySource, self).__init__(source, **guards)
172 modname,ext = self.extname
176 path = package.split('.')
181 if modname != '__init__':
182 modpath += [ modname ]
183 modpath = '.'.join(modpath)
185 arcpath = path + [ self.basename ]
186 abspath = self.snode.abspath
187 if not exists(abspath):
188 abspath = self.tnode.abspath
190 self.package = package
191 self.modname = modname
192 self.modpath = modpath
193 self.arcname = joinpath(*arcpath)
194 self.abspath = abspath
195 self.compiled = File(self.filename + 'c')
196 self.cpp = File(self.filename + '.cc')
197 self.symname = PySource.invalid_sym_char.sub('_', modpath)
199 PySource.modules[modpath] = self
200 PySource.tnodes[self.tnode] = self
201 PySource.symnames[self.symname] = self
203 class SimObject(PySource):
204 '''Add a SimObject python file as a python source object and add
205 it to a list of sim object modules'''
210 def __init__(self, source, **guards):
211 '''Specify the source file and any guards (automatically in
212 the m5.objects package)'''
213 super(SimObject, self).__init__('m5.objects', source, **guards)
215 raise AttributeError, "Too late to call SimObject now."
217 bisect.insort_right(SimObject.modnames, self.modname)
219 class SwigSource(SourceFile):
220 '''Add a swig file to build'''
222 def __init__(self, package, source, **guards):
223 '''Specify the python package, the source file, and any guards'''
224 super(SwigSource, self).__init__(source, **guards)
226 modname,ext = self.extname
229 self.module = modname
230 cc_file = joinpath(self.dirname, modname + '_wrap.cc')
231 py_file = joinpath(self.dirname, modname + '.py')
233 self.cc_source = Source(cc_file, swig=True, parent=self)
234 self.py_source = PySource(package, py_file, parent=self)
236 class UnitTest(object):
237 '''Create a UnitTest'''
240 def __init__(self, target, *sources, **kwargs):
241 '''Specify the target name and any sources. Sources that are
242 not SourceFiles are evalued with Source(). All files are
243 guarded with a guard of the same name as the UnitTest
248 if not isinstance(src, SourceFile):
249 src = Source(src, skip_lib=True)
250 src.guards[target] = True
255 self.main = kwargs.get('main', False)
256 UnitTest.all.append(self)
258 # Children should have access
265 ########################################################################
270 def DebugFlag(name, desc=None):
271 if name in debug_flags:
272 raise AttributeError, "Flag %s already specified" % name
273 debug_flags[name] = (name, (), desc)
275 def CompoundFlag(name, flags, desc=None):
276 if name in debug_flags:
277 raise AttributeError, "Flag %s already specified" % name
279 compound = tuple(flags)
280 debug_flags[name] = (name, compound, desc)
283 Export('CompoundFlag')
285 ########################################################################
287 # Set some compiler variables
290 # Include file paths are rooted in this directory. SCons will
291 # automatically expand '.' to refer to both the source directory and
292 # the corresponding build directory to pick up generated include
294 env.Append(CPPPATH=Dir('.'))
296 for extra_dir in extras_dir_list:
297 env.Append(CPPPATH=Dir(extra_dir))
299 # Workaround for bug in SCons version > 0.97d20071212
300 # Scons bug id: 2006 gem5 Bug id: 308
301 for root, dirs, files in os.walk(base_dir, topdown=True):
302 Dir(root[len(base_dir) + 1:])
304 ########################################################################
306 # Walk the tree and execute all SConscripts in subdirectories
309 here = Dir('.').srcnode().abspath
310 for root, dirs, files in os.walk(base_dir, topdown=True):
312 # we don't want to recurse back into this SConscript
315 if 'SConscript' in files:
316 build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
317 SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
319 for extra_dir in extras_dir_list:
320 prefix_len = len(dirname(extra_dir)) + 1
321 for root, dirs, files in os.walk(extra_dir, topdown=True):
322 # if build lives in the extras directory, don't walk down it
326 if 'SConscript' in files:
327 build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
328 SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
330 for opt in export_vars:
333 def makeTheISA(source, target, env):
334 isas = [ src.get_contents() for src in source ]
335 target_isa = env['TARGET_ISA']
337 return isa.upper() + '_ISA'
340 return isa[0].upper() + isa[1:].lower() + 'ISA'
343 code = code_formatter()
345 #ifndef __CONFIG_THE_ISA_HH__
346 #define __CONFIG_THE_ISA_HH__
350 for i,isa in enumerate(isas):
351 code('#define $0 $1', define(isa), i + 1)
355 #define THE_ISA ${{define(target_isa)}}
356 #define TheISA ${{namespace(target_isa)}}
357 #define THE_ISA_STR "${{target_isa}}"
359 #endif // __CONFIG_THE_ISA_HH__''')
361 code.write(str(target[0]))
363 env.Command('config/the_isa.hh', map(Value, all_isa_list),
364 MakeAction(makeTheISA, Transform("CFG ISA", 0)))
366 ########################################################################
368 # Prevent any SimObjects from being added after this point, they
369 # should all have been added in the SConscripts above
371 SimObject.fixed = True
373 class DictImporter(object):
374 '''This importer takes a dictionary of arbitrary module names that
375 map to arbitrary filenames.'''
376 def __init__(self, modules):
377 self.modules = modules
378 self.installed = set()
385 for module in self.installed:
386 del sys.modules[module]
387 self.installed = set()
389 def find_module(self, fullname, path):
390 if fullname == 'm5.defines':
393 if fullname == 'm5.objects':
396 if fullname.startswith('m5.internal'):
399 source = self.modules.get(fullname, None)
400 if source is not None and fullname.startswith('m5.objects'):
405 def load_module(self, fullname):
406 mod = imp.new_module(fullname)
407 sys.modules[fullname] = mod
408 self.installed.add(fullname)
410 mod.__loader__ = self
411 if fullname == 'm5.objects':
412 mod.__path__ = fullname.split('.')
415 if fullname == 'm5.defines':
416 mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
419 source = self.modules[fullname]
420 if source.modname == '__init__':
421 mod.__path__ = source.modpath
422 mod.__file__ = source.abspath
424 exec file(source.abspath, 'r') in mod.__dict__
430 from m5.util import code_formatter
435 # install the python importer so we can grab stuff from the source
436 # tree itself. We can't have SimObjects added after this point or
437 # else we won't know about them for the rest of the stuff.
438 importer = DictImporter(PySource.modules)
439 sys.meta_path[0:0] = [ importer ]
441 # import all sim objects so we can populate the all_objects list
442 # make sure that we're working with a list, then let's sort it
443 for modname in SimObject.modnames:
444 exec('from m5.objects import %s' % modname)
446 # we need to unload all of the currently imported modules so that they
447 # will be re-imported the next time the sconscript is run
449 sys.meta_path.remove(importer)
451 sim_objects = m5.SimObject.allClasses
452 all_enums = m5.params.allEnums
454 # Find param types that need to be explicitly wrapped with swig.
455 # These will be recognized because the ParamDesc will have a
456 # swig_decl() method. Most param types are based on types that don't
457 # need this, either because they're based on native types (like Int)
458 # or because they're SimObjects (which get swigged independently).
459 # For now the only things handled here are VectorParam types.
461 for name,obj in sorted(sim_objects.iteritems()):
462 for param in obj._params.local.values():
463 # load the ptype attribute now because it depends on the
464 # current version of SimObject.allClasses, but when scons
465 # actually uses the value, all versions of
466 # SimObject.allClasses will have been loaded
469 if not hasattr(param, 'swig_decl'):
471 pname = param.ptype_str
472 if pname not in params_to_swig:
473 params_to_swig[pname] = param
475 ########################################################################
477 # calculate extra dependencies
479 module_depends = ["m5", "m5.SimObject", "m5.params"]
480 depends = [ PySource.modules[dep].snode for dep in module_depends ]
482 ########################################################################
484 # Commands for the basic automatically generated python files
487 # Generate Python file containing a dict specifying the current
489 def makeDefinesPyFile(target, source, env):
490 build_env = source[0].get_contents()
492 code = code_formatter()
497 buildEnv = m5.util.SmartDict($build_env)
499 compileDate = m5.internal.core.compileDate
501 for key,val in m5.internal.core.__dict__.iteritems():
502 if key.startswith('flag_'):
507 code.write(target[0].abspath)
509 defines_info = Value(build_env)
510 # Generate a file with all of the compile options in it
511 env.Command('python/m5/defines.py', defines_info,
512 MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
513 PySource('m5', 'python/m5/defines.py')
515 # Generate python file containing info about the M5 source code
516 def makeInfoPyFile(target, source, env):
517 code = code_formatter()
519 data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
520 code('$src = ${{repr(data)}}')
521 code.write(str(target[0]))
523 # Generate a file that wraps the basic top level files
524 env.Command('python/m5/info.py',
525 [ '#/COPYING', '#/LICENSE', '#/README', ],
526 MakeAction(makeInfoPyFile, Transform("INFO")))
527 PySource('m5', 'python/m5/info.py')
529 ########################################################################
531 # Create all of the SimObject param headers and enum headers
534 def createSimObjectParamStruct(target, source, env):
535 assert len(target) == 1 and len(source) == 1
537 name = str(source[0].get_contents())
538 obj = sim_objects[name]
540 code = code_formatter()
541 obj.cxx_param_decl(code)
542 code.write(target[0].abspath)
544 def createParamSwigWrapper(target, source, env):
545 assert len(target) == 1 and len(source) == 1
547 name = str(source[0].get_contents())
548 param = params_to_swig[name]
550 code = code_formatter()
551 param.swig_decl(code)
552 code.write(target[0].abspath)
554 def createEnumStrings(target, source, env):
555 assert len(target) == 1 and len(source) == 1
557 name = str(source[0].get_contents())
558 obj = all_enums[name]
560 code = code_formatter()
562 code.write(target[0].abspath)
564 def createEnumDecls(target, source, env):
565 assert len(target) == 1 and len(source) == 1
567 name = str(source[0].get_contents())
568 obj = all_enums[name]
570 code = code_formatter()
572 code.write(target[0].abspath)
574 def createEnumSwigWrapper(target, source, env):
575 assert len(target) == 1 and len(source) == 1
577 name = str(source[0].get_contents())
578 obj = all_enums[name]
580 code = code_formatter()
582 code.write(target[0].abspath)
584 def createSimObjectSwigWrapper(target, source, env):
585 name = source[0].get_contents()
586 obj = sim_objects[name]
588 code = code_formatter()
590 code.write(target[0].abspath)
592 # Generate all of the SimObject param C++ struct header files
594 for name,simobj in sorted(sim_objects.iteritems()):
595 py_source = PySource.modules[simobj.__module__]
596 extra_deps = [ py_source.tnode ]
598 hh_file = File('params/%s.hh' % name)
599 params_hh_files.append(hh_file)
600 env.Command(hh_file, Value(name),
601 MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
602 env.Depends(hh_file, depends + extra_deps)
604 # Generate any needed param SWIG wrapper files
606 for name,param in params_to_swig.iteritems():
607 i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
608 params_i_files.append(i_file)
609 env.Command(i_file, Value(name),
610 MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
611 env.Depends(i_file, depends)
612 SwigSource('m5.internal', i_file)
614 # Generate all enum header files
615 for name,enum in sorted(all_enums.iteritems()):
616 py_source = PySource.modules[enum.__module__]
617 extra_deps = [ py_source.tnode ]
619 cc_file = File('enums/%s.cc' % name)
620 env.Command(cc_file, Value(name),
621 MakeAction(createEnumStrings, Transform("ENUM STR")))
622 env.Depends(cc_file, depends + extra_deps)
625 hh_file = File('enums/%s.hh' % name)
626 env.Command(hh_file, Value(name),
627 MakeAction(createEnumDecls, Transform("ENUMDECL")))
628 env.Depends(hh_file, depends + extra_deps)
630 i_file = File('python/m5/internal/enum_%s.i' % name)
631 env.Command(i_file, Value(name),
632 MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
633 env.Depends(i_file, depends + extra_deps)
634 SwigSource('m5.internal', i_file)
636 # Generate SimObject SWIG wrapper files
637 for name in sim_objects.iterkeys():
638 i_file = File('python/m5/internal/param_%s.i' % name)
639 env.Command(i_file, Value(name),
640 MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
641 env.Depends(i_file, depends)
642 SwigSource('m5.internal', i_file)
644 # Generate the main swig init file
645 def makeEmbeddedSwigInit(target, source, env):
646 code = code_formatter()
647 module = source[0].get_contents()
649 #include "sim/init.hh"
652 void init_${module}();
655 EmbeddedSwig embed_swig_${module}(init_${module});
657 code.write(str(target[0]))
659 # Build all swig modules
660 for swig in SwigSource.all:
661 env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
662 MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
663 '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
664 cc_file = str(swig.tnode)
665 init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
666 env.Command(init_file, Value(swig.module),
667 MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
668 Source(init_file, **swig.guards)
673 def makeDebugFlagCC(target, source, env):
674 assert(len(target) == 1 and len(source) == 1)
676 val = eval(source[0].get_contents())
677 name, compound, desc = val
678 compound = list(sorted(compound))
680 code = code_formatter()
685 * DO NOT EDIT THIS FILE! Automatically generated
688 #include "base/debug.hh"
691 for flag in compound:
692 code('#include "debug/$flag.hh"')
694 code('namespace Debug {')
698 code('SimpleFlag $name("$name", "$desc");')
700 code('CompoundFlag $name("$name", "$desc",')
702 last = len(compound) - 1
703 for i,flag in enumerate(compound):
711 code('} // namespace Debug')
713 code.write(str(target[0]))
715 def makeDebugFlagHH(target, source, env):
716 assert(len(target) == 1 and len(source) == 1)
718 val = eval(source[0].get_contents())
719 name, compound, desc = val
721 code = code_formatter()
723 # file header boilerplate
726 * DO NOT EDIT THIS FILE!
728 * Automatically generated by SCons
731 #ifndef __DEBUG_${name}_HH__
732 #define __DEBUG_${name}_HH__
738 code('class CompoundFlag;')
739 code('class SimpleFlag;')
742 code('extern CompoundFlag $name;')
743 for flag in compound:
744 code('extern SimpleFlag $flag;')
746 code('extern SimpleFlag $name;')
751 #endif // __DEBUG_${name}_HH__
754 code.write(str(target[0]))
756 for name,flag in sorted(debug_flags.iteritems()):
757 n, compound, desc = flag
760 env.Command('debug/%s.hh' % name, Value(flag),
761 MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
762 env.Command('debug/%s.cc' % name, Value(flag),
763 MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
764 Source('debug/%s.cc' % name)
766 # Embed python files. All .py files that have been indicated by a
767 # PySource() call in a SConscript need to be embedded into the M5
768 # library. To do that, we compile the file to byte code, marshal the
769 # byte code, compress it, and then generate a c++ file that
770 # inserts the result into an array.
771 def embedPyFile(target, source, env):
775 return '"%s"' % string
777 '''Action function to compile a .py into a code object, marshal
778 it, compress it, and stick it into an asm file so the code appears
779 as just bytes with a label in the data section'''
781 src = file(str(source[0]), 'r').read()
783 pysource = PySource.tnodes[source[0]]
784 compiled = compile(src, pysource.abspath, 'exec')
785 marshalled = marshal.dumps(compiled)
786 compressed = zlib.compress(marshalled)
788 sym = pysource.symname
790 code = code_formatter()
792 #include "sim/init.hh"
796 const uint8_t data_${sym}[] = {
800 for i in xrange(0, len(data), step):
801 x = array.array('B', data[i:i+step])
802 code(''.join('%d,' % d for d in x))
807 EmbeddedPython embedded_${sym}(
808 ${{c_str(pysource.arcname)}},
809 ${{c_str(pysource.abspath)}},
810 ${{c_str(pysource.modpath)}},
813 ${{len(marshalled)}});
815 } // anonymous namespace
817 code.write(str(target[0]))
819 for source in PySource.all:
820 env.Command(source.cpp, source.tnode,
821 MakeAction(embedPyFile, Transform("EMBED PY")))
824 ########################################################################
826 # Define binaries. Each different build type (debug, opt, etc.) gets
827 # a slightly different build environment.
830 # List of constructed environments to pass back to SConstruct
833 date_source = Source('base/date.cc', skip_lib=True)
835 # Function to create a new build environment as clone of current
836 # environment 'env' with modified object suffix and optional stripped
837 # binary. Additional keyword arguments are appended to corresponding
838 # build environment vars.
839 def makeEnv(label, objsfx, strip = False, **kwargs):
840 # SCons doesn't know to append a library suffix when there is a '.' in the
841 # name. Use '_' instead.
842 libname = 'gem5_' + label
843 exename = 'gem5.' + label
844 secondary_exename = 'm5.' + label
846 new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
847 new_env.Label = label
848 new_env.Append(**kwargs)
850 swig_env = new_env.Clone()
851 swig_env.Append(CCFLAGS='-Werror')
853 swig_env.Append(CCFLAGS=['-Wno-uninitialized', '-Wno-sign-compare',
854 '-Wno-parentheses', '-Wno-unused-label',
855 '-Wno-unused-value'])
856 if compareVersions(env['GCC_VERSION'], '4.6') >= 0:
857 swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
859 swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
861 werror_env = new_env.Clone()
862 werror_env.Append(CCFLAGS='-Werror')
864 def make_obj(source, static, extra_deps = None):
865 '''This function adds the specified source to the correct
866 build environment, and returns the corresponding SCons Object
877 obj = env.StaticObject(source.tnode)
879 obj = env.SharedObject(source.tnode)
882 env.Depends(obj, extra_deps)
887 [ make_obj(s, True) for s in Source.get(main=False, skip_lib=False) ]
889 [ make_obj(s, False) for s in Source.get(main=False, skip_lib=False) ]
891 static_date = make_obj(date_source, static=True, extra_deps=static_objs)
892 static_objs.append(static_date)
894 shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
895 shared_objs.append(shared_date)
897 # First make a library of everything but main() so other programs can
899 static_lib = new_env.StaticLibrary(libname, static_objs)
900 shared_lib = new_env.SharedLibrary(libname, shared_objs)
902 # Now link a stub with main() and the static library.
903 main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
905 for test in UnitTest.all:
906 flags = { test.target : True }
907 test_sources = Source.get(**flags)
908 test_objs = [ make_obj(s, static=True) for s in test_sources ]
910 test_objs += main_objs
911 testname = "unittest/%s.%s" % (test.target, label)
912 new_env.Program(testname, test_objs + static_objs)
916 progname += '.unstripped'
918 targets = new_env.Program(progname, main_objs + static_objs)
921 if sys.platform == 'sunos5':
922 cmd = 'cp $SOURCE $TARGET; strip $TARGET'
924 cmd = 'strip $SOURCE -o $TARGET'
925 targets = new_env.Command(exename, progname,
926 MakeAction(cmd, Transform("STRIP")))
928 new_env.Command(secondary_exename, exename,
929 MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
931 new_env.M5Binary = targets[0]
932 envList.append(new_env)
937 if sys.platform == 'sunos5':
938 ccflags['debug'] = '-gstabs+'
940 ccflags['debug'] = '-ggdb3'
941 ccflags['opt'] = '-g -O3'
942 ccflags['fast'] = '-O3'
943 ccflags['prof'] = '-O3 -g -pg'
945 ccflags['debug'] = '-g0'
946 ccflags['opt'] = '-g -O'
947 ccflags['fast'] = '-fast'
948 ccflags['prof'] = '-fast -g -pg'
950 ccflags['debug'] = '-g -O0'
951 ccflags['opt'] = '-g -O'
952 ccflags['fast'] = '-fast'
953 ccflags['prof'] = '-fast -g -pg'
955 ccflags['debug'] = '-g -O0'
956 ccflags['opt'] = '-g -O3'
957 ccflags['fast'] = '-O3'
958 ccflags['prof'] = '-O3 -g -pg'
960 print 'Unknown compiler, please fix compiler options'
964 # To speed things up, we only instantiate the build environments we
965 # need. We try to identify the needed environment for each target; if
966 # we can't, we fall back on instantiating all the environments just to
968 target_types = ['debug', 'opt', 'fast', 'prof']
969 obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof'}
971 def identifyTarget(t):
972 ext = t.split('.')[-1]
973 if ext in target_types:
975 if obj2target.has_key(ext):
976 return obj2target[ext]
977 match = re.search(r'/tests/([^/]+)/', t)
978 if match and match.group(1) in target_types:
979 return match.group(1)
982 needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
983 if 'all' in needed_envs:
984 needed_envs += target_types
987 if 'debug' in needed_envs:
988 makeEnv('debug', '.do',
989 CCFLAGS = Split(ccflags['debug']),
990 CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
993 if 'opt' in needed_envs:
995 CCFLAGS = Split(ccflags['opt']),
996 CPPDEFINES = ['TRACING_ON=1'])
999 if 'fast' in needed_envs:
1000 makeEnv('fast', '.fo', strip = True,
1001 CCFLAGS = Split(ccflags['fast']),
1002 CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
1005 if 'prof' in needed_envs:
1006 makeEnv('prof', '.po',
1007 CCFLAGS = Split(ccflags['prof']),
1008 CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],