SConscript revision 5517
1# -*- mode:python -*-
2
3# Copyright (c) 2004-2005 The Regents of The University of Michigan
4# All rights reserved.
5#
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.
16#
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.
28#
29# Authors: Nathan Binkert
30
31import imp
32import os
33import py_compile
34import sys
35import zipfile
36
37from os.path import basename, exists, isdir, isfile, join as joinpath
38
39import SCons
40
41# This file defines how to build a particular configuration of M5
42# based on variable settings in the 'env' build environment.
43
44Import('*')
45
46# Children need to see the environment
47Export('env')
48
49build_env = dict([(opt, env[opt]) for opt in env.ExportOptions])
50
51def sort_list(_list):
52    """return a sorted copy of '_list'"""
53    if isinstance(_list, list):
54        _list = _list[:]
55    else:
56        _list = list(_list)
57    _list.sort()
58    return _list
59
60class PySourceFile(object):
61    def __init__(self, package, source):
62        filename = str(source)
63        pyname = basename(filename)
64        assert pyname.endswith('.py')
65        name = pyname[:-3]
66        path = package.split('.')
67        modpath = path
68        if name != '__init__':
69            modpath += [name]
70        modpath = '.'.join(modpath)
71
72        arcpath = package.split('.') + [ pyname + 'c' ]
73        arcname = joinpath(*arcpath)
74
75        self.source = source
76        self.pyname = pyname
77        self.srcpath = source.srcnode().abspath
78        self.package = package
79        self.modpath = modpath
80        self.arcname = arcname
81        self.filename = filename
82        self.compiled = File(filename + 'c')
83
84########################################################################
85# Code for adding source files of various types
86#
87cc_sources = []
88def Source(source):
89    '''Add a C/C++ source file to the build'''
90    if not isinstance(source, SCons.Node.FS.File):
91        source = File(source)
92
93    cc_sources.append(source)
94
95py_sources = []
96def PySource(package, source):
97    '''Add a python source file to the named package'''
98    if not isinstance(source, SCons.Node.FS.File):
99        source = File(source)
100
101    source = PySourceFile(package, source)
102    py_sources.append(source)
103
104sim_objects_fixed = False
105sim_object_modfiles = set()
106def SimObject(source):
107    '''Add a SimObject python file as a python source object and add
108    it to a list of sim object modules'''
109
110    if sim_objects_fixed:
111        raise AttributeError, "Too late to call SimObject now."
112
113    if not isinstance(source, SCons.Node.FS.File):
114        source = File(source)
115
116    PySource('m5.objects', source)
117    modfile = basename(str(source))
118    assert modfile.endswith('.py')
119    modname = modfile[:-3]
120    sim_object_modfiles.add(modname)
121
122swig_sources = []
123def SwigSource(package, source):
124    '''Add a swig file to build'''
125    if not isinstance(source, SCons.Node.FS.File):
126        source = File(source)
127    val = source,package
128    swig_sources.append(val)
129
130# Children should have access
131Export('Source')
132Export('PySource')
133Export('SimObject')
134Export('SwigSource')
135
136########################################################################
137#
138# Trace Flags
139#
140all_flags = {}
141trace_flags = []
142def TraceFlag(name, desc=''):
143    if name in all_flags:
144        raise AttributeError, "Flag %s already specified" % name
145    flag = (name, (), desc)
146    trace_flags.append(flag)
147    all_flags[name] = ()
148
149def CompoundFlag(name, flags, desc=''):
150    if name in all_flags:
151        raise AttributeError, "Flag %s already specified" % name
152
153    compound = tuple(flags)
154    for flag in compound:
155        if flag not in all_flags:
156            raise AttributeError, "Trace flag %s not found" % flag
157        if all_flags[flag]:
158            raise AttributeError, \
159                "Compound flag can't point to another compound flag"
160
161    flag = (name, compound, desc)
162    trace_flags.append(flag)
163    all_flags[name] = compound
164
165Export('TraceFlag')
166Export('CompoundFlag')
167
168########################################################################
169#
170# Set some compiler variables
171#
172
173# Include file paths are rooted in this directory.  SCons will
174# automatically expand '.' to refer to both the source directory and
175# the corresponding build directory to pick up generated include
176# files.
177env.Append(CPPPATH=Dir('.'))
178
179# Add a flag defining what THE_ISA should be for all compilation
180env.Append(CPPDEFINES=[('THE_ISA','%s_ISA' % env['TARGET_ISA'].upper())])
181
182########################################################################
183#
184# Walk the tree and execute all SConscripts in subdirectories
185#
186
187for base_dir in base_dir_list:
188    here = Dir('.').srcnode().abspath
189    for root, dirs, files in os.walk(base_dir, topdown=True):
190        if root == here:
191            # we don't want to recurse back into this SConscript
192            continue
193
194        if 'SConscript' in files:
195            build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
196            SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
197
198for opt in env.ExportOptions:
199    env.ConfigFile(opt)
200
201########################################################################
202#
203# Prevent any SimObjects from being added after this point, they
204# should all have been added in the SConscripts above
205#
206class DictImporter(object):
207    '''This importer takes a dictionary of arbitrary module names that
208    map to arbitrary filenames.'''
209    def __init__(self, modules):
210        self.modules = modules
211        self.installed = set()
212
213    def __del__(self):
214        self.unload()
215
216    def unload(self):
217        import sys
218        for module in self.installed:
219            del sys.modules[module]
220        self.installed = set()
221
222    def find_module(self, fullname, path):
223        if fullname == '__scons':
224            return self
225
226        if fullname == 'm5.objects':
227            return self
228
229        if fullname.startswith('m5.internal'):
230            return None
231
232        if fullname in self.modules and exists(self.modules[fullname]):
233            return self
234
235        return None
236
237    def load_module(self, fullname):
238        mod = imp.new_module(fullname)
239        sys.modules[fullname] = mod
240        self.installed.add(fullname)
241
242        mod.__loader__ = self
243        if fullname == 'm5.objects':
244            mod.__path__ = fullname.split('.')
245            return mod
246
247        if fullname == '__scons':
248            mod.__dict__['m5_build_env'] = build_env
249            return mod
250
251        srcfile = self.modules[fullname]
252        if basename(srcfile) == '__init__.py':
253            mod.__path__ = fullname.split('.')
254        mod.__file__ = srcfile
255
256        exec file(srcfile, 'r') in mod.__dict__
257
258        return mod
259
260class ordered_dict(dict):
261    def keys(self):
262        keys = super(ordered_dict, self).keys()
263        keys.sort()
264        return keys
265
266    def values(self):
267        return [ self[key] for key in self.keys() ]
268
269    def items(self):
270        return [ (key,self[key]) for key in self.keys() ]
271
272    def iterkeys(self):
273        for key in self.keys():
274            yield key
275
276    def itervalues(self):
277        for value in self.values():
278            yield value
279
280    def iteritems(self):
281        for key,value in self.items():
282            yield key, value
283
284py_modules = {}
285for source in py_sources:
286    py_modules[source.modpath] = source.srcpath
287
288# install the python importer so we can grab stuff from the source
289# tree itself.  We can't have SimObjects added after this point or
290# else we won't know about them for the rest of the stuff.
291sim_objects_fixed = True
292importer = DictImporter(py_modules)
293sys.meta_path[0:0] = [ importer ]
294
295import m5
296
297# import all sim objects so we can populate the all_objects list
298# make sure that we're working with a list, then let's sort it
299sim_objects = list(sim_object_modfiles)
300sim_objects.sort()
301for simobj in sim_objects:
302    exec('from m5.objects import %s' % simobj)
303
304# we need to unload all of the currently imported modules so that they
305# will be re-imported the next time the sconscript is run
306importer.unload()
307sys.meta_path.remove(importer)
308
309sim_objects = m5.SimObject.allClasses
310all_enums = m5.params.allEnums
311
312all_params = {}
313for name,obj in sim_objects.iteritems():
314    for param in obj._params.local.values():
315        if not hasattr(param, 'swig_decl'):
316            continue
317        pname = param.ptype_str
318        if pname not in all_params:
319            all_params[pname] = param
320
321########################################################################
322#
323# calculate extra dependencies
324#
325module_depends = ["m5", "m5.SimObject", "m5.params"]
326depends = [ File(py_modules[dep]) for dep in module_depends ]
327
328########################################################################
329#
330# Commands for the basic automatically generated python files
331#
332
333# Generate Python file containing a dict specifying the current
334# build_env flags.
335def makeDefinesPyFile(target, source, env):
336    f = file(str(target[0]), 'w')
337    print >>f, "m5_build_env = ", source[0]
338    f.close()
339
340# Generate python file containing info about the M5 source code
341def makeInfoPyFile(target, source, env):
342    f = file(str(target[0]), 'w')
343    for src in source:
344        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
345        print >>f, "%s = %s" % (src, repr(data))
346    f.close()
347
348# Generate the __init__.py file for m5.objects
349def makeObjectsInitFile(target, source, env):
350    f = file(str(target[0]), 'w')
351    print >>f, 'from params import *'
352    print >>f, 'from m5.SimObject import *'
353    for module in source:
354        print >>f, 'from %s import *' % module.get_contents()
355    f.close()
356
357# Generate a file with all of the compile options in it
358env.Command('python/m5/defines.py', Value(build_env), makeDefinesPyFile)
359PySource('m5', 'python/m5/defines.py')
360
361# Generate a file that wraps the basic top level files
362env.Command('python/m5/info.py',
363            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
364            makeInfoPyFile)
365PySource('m5', 'python/m5/info.py')
366
367# Generate an __init__.py file for the objects package
368env.Command('python/m5/objects/__init__.py',
369            [ Value(o) for o in sort_list(sim_object_modfiles) ],
370            makeObjectsInitFile)
371PySource('m5.objects', 'python/m5/objects/__init__.py')
372
373########################################################################
374#
375# Create all of the SimObject param headers and enum headers
376#
377
378def createSimObjectParam(target, source, env):
379    assert len(target) == 1 and len(source) == 1
380
381    hh_file = file(target[0].abspath, 'w')
382    name = str(source[0].get_contents())
383    obj = sim_objects[name]
384
385    print >>hh_file, obj.cxx_decl()
386
387def createSwigParam(target, source, env):
388    assert len(target) == 1 and len(source) == 1
389
390    i_file = file(target[0].abspath, 'w')
391    name = str(source[0].get_contents())
392    param = all_params[name]
393
394    for line in param.swig_decl():
395        print >>i_file, line
396
397def createEnumStrings(target, source, env):
398    assert len(target) == 1 and len(source) == 1
399
400    cc_file = file(target[0].abspath, 'w')
401    name = str(source[0].get_contents())
402    obj = all_enums[name]
403
404    print >>cc_file, obj.cxx_def()
405    cc_file.close()
406
407def createEnumParam(target, source, env):
408    assert len(target) == 1 and len(source) == 1
409
410    hh_file = file(target[0].abspath, 'w')
411    name = str(source[0].get_contents())
412    obj = all_enums[name]
413
414    print >>hh_file, obj.cxx_decl()
415
416# Generate all of the SimObject param struct header files
417params_hh_files = []
418for name,simobj in sim_objects.iteritems():
419    extra_deps = [ File(py_modules[simobj.__module__]) ]
420
421    hh_file = File('params/%s.hh' % name)
422    params_hh_files.append(hh_file)
423    env.Command(hh_file, Value(name), createSimObjectParam)
424    env.Depends(hh_file, depends + extra_deps)
425
426# Generate any parameter header files needed
427params_i_files = []
428for name,param in all_params.iteritems():
429    if isinstance(param, m5.params.VectorParamDesc):
430        ext = 'vptype'
431    else:
432        ext = 'ptype'
433
434    i_file = File('params/%s_%s.i' % (name, ext))
435    params_i_files.append(i_file)
436    env.Command(i_file, Value(name), createSwigParam)
437    env.Depends(i_file, depends)
438
439# Generate all enum header files
440for name,enum in all_enums.iteritems():
441    extra_deps = [ File(py_modules[enum.__module__]) ]
442
443    cc_file = File('enums/%s.cc' % name)
444    env.Command(cc_file, Value(name), createEnumStrings)
445    env.Depends(cc_file, depends + extra_deps)
446    Source(cc_file)
447
448    hh_file = File('enums/%s.hh' % name)
449    env.Command(hh_file, Value(name), createEnumParam)
450    env.Depends(hh_file, depends + extra_deps)
451
452# Build the big monolithic swigged params module (wraps all SimObject
453# param structs and enum structs)
454def buildParams(target, source, env):
455    names = [ s.get_contents() for s in source ]
456    objs = [ sim_objects[name] for name in names ]
457    out = file(target[0].abspath, 'w')
458
459    ordered_objs = []
460    obj_seen = set()
461    def order_obj(obj):
462        name = str(obj)
463        if name in obj_seen:
464            return
465
466        obj_seen.add(name)
467        if str(obj) != 'SimObject':
468            order_obj(obj.__bases__[0])
469
470        ordered_objs.append(obj)
471
472    for obj in objs:
473        order_obj(obj)
474
475    enums = set()
476    predecls = []
477    pd_seen = set()
478
479    def add_pds(*pds):
480        for pd in pds:
481            if pd not in pd_seen:
482                predecls.append(pd)
483                pd_seen.add(pd)
484
485    for obj in ordered_objs:
486        params = obj._params.local.values()
487        for param in params:
488            ptype = param.ptype
489            if issubclass(ptype, m5.params.Enum):
490                if ptype not in enums:
491                    enums.add(ptype)
492            pds = param.swig_predecls()
493            if isinstance(pds, (list, tuple)):
494                add_pds(*pds)
495            else:
496                add_pds(pds)
497
498    print >>out, '%module params'
499
500    print >>out, '%{'
501    for obj in ordered_objs:
502        print >>out, '#include "params/%s.hh"' % obj
503    print >>out, '%}'
504
505    for pd in predecls:
506        print >>out, pd
507
508    enums = list(enums)
509    enums.sort()
510    for enum in enums:
511        print >>out, '%%include "enums/%s.hh"' % enum.__name__
512    print >>out
513
514    for obj in ordered_objs:
515        if obj.swig_objdecls:
516            for decl in obj.swig_objdecls:
517                print >>out, decl
518            continue
519
520        code = ''
521        base = obj.get_base()
522
523        code += '// stop swig from creating/wrapping default ctor/dtor\n'
524        code += '%%nodefault %s;\n' % obj.cxx_class
525        code += 'class %s ' % obj.cxx_class
526        if base:
527            code += ': public %s' % base
528        code += ' {};\n'
529
530        klass = obj.cxx_class;
531        if hasattr(obj, 'cxx_namespace'):
532            new_code = 'namespace %s {\n' % obj.cxx_namespace
533            new_code += code
534            new_code += '}\n'
535            code = new_code
536            klass = '%s::%s' % (obj.cxx_namespace, klass)
537
538        print >>out, code
539
540    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
541    for obj in ordered_objs:
542        print >>out, '%%include "params/%s.hh"' % obj
543
544params_file = File('params/params.i')
545names = sort_list(sim_objects.keys())
546env.Command(params_file, [ Value(v) for v in names ], buildParams)
547env.Depends(params_file, params_hh_files + params_i_files + depends)
548SwigSource('m5.objects', params_file)
549
550# Build all swig modules
551swig_modules = []
552for source,package in swig_sources:
553    filename = str(source)
554    assert filename.endswith('.i')
555
556    base = '.'.join(filename.split('.')[:-1])
557    module = basename(base)
558    cc_file = base + '_wrap.cc'
559    py_file = base + '.py'
560
561    env.Command([cc_file, py_file], source,
562                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
563                '-o ${TARGETS[0]} $SOURCES')
564    env.Depends(py_file, source)
565    env.Depends(cc_file, source)
566
567    swig_modules.append(Value(module))
568    Source(cc_file)
569    PySource(package, py_file)
570
571# Generate the main swig init file
572def makeSwigInit(target, source, env):
573    f = file(str(target[0]), 'w')
574    print >>f, 'extern "C" {'
575    for module in source:
576        print >>f, '    void init_%s();' % module.get_contents()
577    print >>f, '}'
578    print >>f, 'void init_swig() {'
579    for module in source:
580        print >>f, '    init_%s();' % module.get_contents()
581    print >>f, '}'
582    f.close()
583
584env.Command('swig/init.cc', swig_modules, makeSwigInit)
585Source('swig/init.cc')
586
587# Generate traceflags.py
588def traceFlagsPy(target, source, env):
589    assert(len(target) == 1)
590
591    f = file(str(target[0]), 'w')
592
593    allFlags = []
594    for s in source:
595        val = eval(s.get_contents())
596        allFlags.append(val)
597
598    print >>f, 'baseFlags = ['
599    for flag, compound, desc in allFlags:
600        if not compound:
601            print >>f, "    '%s'," % flag
602    print >>f, "    ]"
603    print >>f
604
605    print >>f, 'compoundFlags = ['
606    print >>f, "    'All',"
607    for flag, compound, desc in allFlags:
608        if compound:
609            print >>f, "    '%s'," % flag
610    print >>f, "    ]"
611    print >>f
612
613    print >>f, "allFlags = frozenset(baseFlags + compoundFlags)"
614    print >>f
615
616    print >>f, 'compoundFlagMap = {'
617    all = tuple([flag for flag,compound,desc in allFlags if not compound])
618    print >>f, "    'All' : %s," % (all, )
619    for flag, compound, desc in allFlags:
620        if compound:
621            print >>f, "    '%s' : %s," % (flag, compound)
622    print >>f, "    }"
623    print >>f
624
625    print >>f, 'flagDescriptions = {'
626    print >>f, "    'All' : 'All flags',"
627    for flag, compound, desc in allFlags:
628        print >>f, "    '%s' : '%s'," % (flag, desc)
629    print >>f, "    }"
630
631    f.close()
632
633def traceFlagsCC(target, source, env):
634    assert(len(target) == 1)
635
636    f = file(str(target[0]), 'w')
637
638    allFlags = []
639    for s in source:
640        val = eval(s.get_contents())
641        allFlags.append(val)
642
643    # file header
644    print >>f, '''
645/*
646 * DO NOT EDIT THIS FILE! Automatically generated
647 */
648
649#include "base/traceflags.hh"
650
651using namespace Trace;
652
653const char *Trace::flagStrings[] =
654{'''
655
656    # The string array is used by SimpleEnumParam to map the strings
657    # provided by the user to enum values.
658    for flag, compound, desc in allFlags:
659        if not compound:
660            print >>f, '    "%s",' % flag
661
662    print >>f, '    "All",'
663    for flag, compound, desc in allFlags:
664        if compound:
665            print >>f, '    "%s",' % flag
666
667    print >>f, '};'
668    print >>f
669    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
670    print >>f
671
672    #
673    # Now define the individual compound flag arrays.  There is an array
674    # for each compound flag listing the component base flags.
675    #
676    all = tuple([flag for flag,compound,desc in allFlags if not compound])
677    print >>f, 'static const Flags AllMap[] = {'
678    for flag, compound, desc in allFlags:
679        if not compound:
680            print >>f, "    %s," % flag
681    print >>f, '};'
682    print >>f
683
684    for flag, compound, desc in allFlags:
685        if not compound:
686            continue
687        print >>f, 'static const Flags %sMap[] = {' % flag
688        for flag in compound:
689            print >>f, "    %s," % flag
690        print >>f, "    (Flags)-1"
691        print >>f, '};'
692        print >>f
693
694    #
695    # Finally the compoundFlags[] array maps the compound flags
696    # to their individual arrays/
697    #
698    print >>f, 'const Flags *Trace::compoundFlags[] ='
699    print >>f, '{'
700    print >>f, '    AllMap,'
701    for flag, compound, desc in allFlags:
702        if compound:
703            print >>f, '    %sMap,' % flag
704    # file trailer
705    print >>f, '};'
706
707    f.close()
708
709def traceFlagsHH(target, source, env):
710    assert(len(target) == 1)
711
712    f = file(str(target[0]), 'w')
713
714    allFlags = []
715    for s in source:
716        val = eval(s.get_contents())
717        allFlags.append(val)
718
719    # file header boilerplate
720    print >>f, '''
721/*
722 * DO NOT EDIT THIS FILE!
723 *
724 * Automatically generated from traceflags.py
725 */
726
727#ifndef __BASE_TRACE_FLAGS_HH__
728#define __BASE_TRACE_FLAGS_HH__
729
730namespace Trace {
731
732enum Flags {'''
733
734    # Generate the enum.  Base flags come first, then compound flags.
735    idx = 0
736    for flag, compound, desc in allFlags:
737        if not compound:
738            print >>f, '    %s = %d,' % (flag, idx)
739            idx += 1
740
741    numBaseFlags = idx
742    print >>f, '    NumFlags = %d,' % idx
743
744    # put a comment in here to separate base from compound flags
745    print >>f, '''
746// The remaining enum values are *not* valid indices for Trace::flags.
747// They are "compound" flags, which correspond to sets of base
748// flags, and are used by changeFlag.'''
749
750    print >>f, '    All = %d,' % idx
751    idx += 1
752    for flag, compound, desc in allFlags:
753        if compound:
754            print >>f, '    %s = %d,' % (flag, idx)
755            idx += 1
756
757    numCompoundFlags = idx - numBaseFlags
758    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
759
760    # trailer boilerplate
761    print >>f, '''\
762}; // enum Flags
763
764// Array of strings for SimpleEnumParam
765extern const char *flagStrings[];
766extern const int numFlagStrings;
767
768// Array of arraay pointers: for each compound flag, gives the list of
769// base flags to set.  Inidividual flag arrays are terminated by -1.
770extern const Flags *compoundFlags[];
771
772/* namespace Trace */ }
773
774#endif // __BASE_TRACE_FLAGS_HH__
775'''
776
777    f.close()
778
779flags = [ Value(f) for f in trace_flags ]
780env.Command('base/traceflags.py', flags, traceFlagsPy)
781PySource('m5', 'base/traceflags.py')
782
783env.Command('base/traceflags.hh', flags, traceFlagsHH)
784env.Command('base/traceflags.cc', flags, traceFlagsCC)
785Source('base/traceflags.cc')
786
787# Generate program_info.cc
788def programInfo(target, source, env):
789    def gen_file(target, rev, node, date):
790        pi_stats = file(target, 'w')
791        print >>pi_stats, 'const char *hgRev = "%s:%s";' %  (rev, node)
792        print >>pi_stats, 'const char *hgDate = "%s";' % date
793        pi_stats.close()
794
795    target = str(target[0])
796    scons_dir = str(source[0].get_contents())
797    try:
798        import mercurial.demandimport, mercurial.hg, mercurial.ui
799        import mercurial.util, mercurial.node
800        if not exists(scons_dir) or not isdir(scons_dir) or \
801               not exists(joinpath(scons_dir, ".hg")):
802            raise ValueError
803        repo = mercurial.hg.repository(mercurial.ui.ui(), scons_dir)
804        rev = mercurial.node.nullrev + repo.changelog.count()
805        changenode = repo.changelog.node(rev)
806        changes = repo.changelog.read(changenode)
807        date = mercurial.util.datestr(changes[2])
808
809        gen_file(target, rev, mercurial.node.hex(changenode), date)
810
811        mercurial.demandimport.disable()
812    except ImportError:
813        gen_file(target, "Unknown", "Unknown", "Unknown")
814
815    except:
816        print "in except"
817        gen_file(target, "Unknown", "Unknown", "Unknown")
818        mercurial.demandimport.disable()
819
820env.Command('base/program_info.cc',
821            Value(str(SCons.Node.FS.default_fs.SConstruct_dir)),
822            programInfo)
823
824# Build the zip file
825def compilePyFile(target, source, env):
826    '''Action function to compile a .py into a .pyc'''
827    py_compile.compile(str(source[0]), str(target[0]))
828
829def buildPyZip(target, source, env):
830    '''Action function to build the zip archive.  Uses the
831    PyZipFile module included in the standard Python library.'''
832
833    py_compiled = {}
834    for s in py_sources:
835        compname = str(s.compiled)
836        assert compname not in py_compiled
837        py_compiled[compname] = s
838
839    zf = zipfile.ZipFile(str(target[0]), 'w')
840    for s in source:
841        zipname = str(s)
842        arcname = py_compiled[zipname].arcname
843        zf.write(zipname, arcname)
844    zf.close()
845
846py_compiled = []
847py_zip_depends = []
848for source in py_sources:
849    env.Command(source.compiled, source.source, compilePyFile)
850    py_compiled.append(source.compiled)
851
852    # make the zipfile depend on the archive name so that the archive
853    # is rebuilt if the name changes
854    py_zip_depends.append(Value(source.arcname))
855
856# Add the zip file target to the environment.
857m5zip = File('m5py.zip')
858env.Command(m5zip, py_compiled, buildPyZip)
859env.Depends(m5zip, py_zip_depends)
860
861########################################################################
862#
863# Define binaries.  Each different build type (debug, opt, etc.) gets
864# a slightly different build environment.
865#
866
867# List of constructed environments to pass back to SConstruct
868envList = []
869
870# This function adds the specified sources to the given build
871# environment, and returns a list of all the corresponding SCons
872# Object nodes (including an extra one for date.cc).  We explicitly
873# add the Object nodes so we can set up special dependencies for
874# date.cc.
875def make_objs(sources, env):
876    objs = [env.Object(s) for s in sources]
877  
878    # make date.cc depend on all other objects so it always gets
879    # recompiled whenever anything else does
880    date_obj = env.Object('base/date.cc')
881
882    # Make the generation of program_info.cc dependend on all 
883    # the other cc files and the compiling of program_info.cc 
884    # dependent on all the objects but program_info.o 
885    pinfo_obj = env.Object('base/program_info.cc')
886    env.Depends('base/program_info.cc', sources)
887    env.Depends(date_obj, objs)
888    env.Depends(pinfo_obj, objs)
889    objs.extend([date_obj,pinfo_obj])
890    return objs
891
892# Function to create a new build environment as clone of current
893# environment 'env' with modified object suffix and optional stripped
894# binary.  Additional keyword arguments are appended to corresponding
895# build environment vars.
896def makeEnv(label, objsfx, strip = False, **kwargs):
897    newEnv = env.Copy(OBJSUFFIX=objsfx)
898    newEnv.Label = label
899    newEnv.Append(**kwargs)
900    exe = 'm5.' + label  # final executable
901    bin = exe + '.bin'   # executable w/o appended Python zip archive
902    newEnv.Program(bin, make_objs(cc_sources, newEnv))
903    if strip:
904        stripped_bin = bin + '.stripped'
905        if sys.platform == 'sunos5':
906            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
907        else:
908            cmd = 'strip $SOURCE -o $TARGET'
909        newEnv.Command(stripped_bin, bin, cmd)
910        bin = stripped_bin
911    targets = newEnv.Concat(exe, [bin, 'm5py.zip'])
912    newEnv.M5Binary = targets[0]
913    envList.append(newEnv)
914
915# Debug binary
916ccflags = {}
917if env['GCC']:
918    if sys.platform == 'sunos5':
919        ccflags['debug'] = '-gstabs+'
920    else:
921        ccflags['debug'] = '-ggdb3'
922    ccflags['opt'] = '-g -O3'
923    ccflags['fast'] = '-O3'
924    ccflags['prof'] = '-O3 -g -pg'
925elif env['SUNCC']:
926    ccflags['debug'] = '-g0'
927    ccflags['opt'] = '-g -O'
928    ccflags['fast'] = '-fast'
929    ccflags['prof'] = '-fast -g -pg'
930elif env['ICC']:
931    ccflags['debug'] = '-g -O0'
932    ccflags['opt'] = '-g -O'
933    ccflags['fast'] = '-fast'
934    ccflags['prof'] = '-fast -g -pg'
935else:
936    print 'Unknown compiler, please fix compiler options'
937    Exit(1)
938
939makeEnv('debug', '.do',
940        CCFLAGS = Split(ccflags['debug']),
941        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
942
943# Optimized binary
944makeEnv('opt', '.o',
945        CCFLAGS = Split(ccflags['opt']),
946        CPPDEFINES = ['TRACING_ON=1'])
947
948# "Fast" binary
949makeEnv('fast', '.fo', strip = True,
950        CCFLAGS = Split(ccflags['fast']),
951        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
952
953# Profiled binary
954makeEnv('prof', '.po',
955        CCFLAGS = Split(ccflags['prof']),
956        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
957        LINKFLAGS = '-pg')
958
959Return('envList')
960