SConscript revision 5518:70caf53d9d7c
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
260py_modules = {}
261for source in py_sources:
262    py_modules[source.modpath] = source.srcpath
263
264# install the python importer so we can grab stuff from the source
265# tree itself.  We can't have SimObjects added after this point or
266# else we won't know about them for the rest of the stuff.
267sim_objects_fixed = True
268importer = DictImporter(py_modules)
269sys.meta_path[0:0] = [ importer ]
270
271import m5
272
273# import all sim objects so we can populate the all_objects list
274# make sure that we're working with a list, then let's sort it
275sim_objects = list(sim_object_modfiles)
276sim_objects.sort()
277for simobj in sim_objects:
278    exec('from m5.objects import %s' % simobj)
279
280# we need to unload all of the currently imported modules so that they
281# will be re-imported the next time the sconscript is run
282importer.unload()
283sys.meta_path.remove(importer)
284
285sim_objects = m5.SimObject.allClasses
286all_enums = m5.params.allEnums
287
288all_params = {}
289for name,obj in sim_objects.iteritems():
290    for param in obj._params.local.values():
291        if not hasattr(param, 'swig_decl'):
292            continue
293        pname = param.ptype_str
294        if pname not in all_params:
295            all_params[pname] = param
296
297########################################################################
298#
299# calculate extra dependencies
300#
301module_depends = ["m5", "m5.SimObject", "m5.params"]
302depends = [ File(py_modules[dep]) for dep in module_depends ]
303
304########################################################################
305#
306# Commands for the basic automatically generated python files
307#
308
309# Generate Python file containing a dict specifying the current
310# build_env flags.
311def makeDefinesPyFile(target, source, env):
312    f = file(str(target[0]), 'w')
313    print >>f, "m5_build_env = ", source[0]
314    f.close()
315
316# Generate python file containing info about the M5 source code
317def makeInfoPyFile(target, source, env):
318    f = file(str(target[0]), 'w')
319    for src in source:
320        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
321        print >>f, "%s = %s" % (src, repr(data))
322    f.close()
323
324# Generate the __init__.py file for m5.objects
325def makeObjectsInitFile(target, source, env):
326    f = file(str(target[0]), 'w')
327    print >>f, 'from params import *'
328    print >>f, 'from m5.SimObject import *'
329    for module in source:
330        print >>f, 'from %s import *' % module.get_contents()
331    f.close()
332
333# Generate a file with all of the compile options in it
334env.Command('python/m5/defines.py', Value(build_env), makeDefinesPyFile)
335PySource('m5', 'python/m5/defines.py')
336
337# Generate a file that wraps the basic top level files
338env.Command('python/m5/info.py',
339            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
340            makeInfoPyFile)
341PySource('m5', 'python/m5/info.py')
342
343# Generate an __init__.py file for the objects package
344env.Command('python/m5/objects/__init__.py',
345            [ Value(o) for o in sort_list(sim_object_modfiles) ],
346            makeObjectsInitFile)
347PySource('m5.objects', 'python/m5/objects/__init__.py')
348
349########################################################################
350#
351# Create all of the SimObject param headers and enum headers
352#
353
354def createSimObjectParam(target, source, env):
355    assert len(target) == 1 and len(source) == 1
356
357    hh_file = file(target[0].abspath, 'w')
358    name = str(source[0].get_contents())
359    obj = sim_objects[name]
360
361    print >>hh_file, obj.cxx_decl()
362
363def createSwigParam(target, source, env):
364    assert len(target) == 1 and len(source) == 1
365
366    i_file = file(target[0].abspath, 'w')
367    name = str(source[0].get_contents())
368    param = all_params[name]
369
370    for line in param.swig_decl():
371        print >>i_file, line
372
373def createEnumStrings(target, source, env):
374    assert len(target) == 1 and len(source) == 1
375
376    cc_file = file(target[0].abspath, 'w')
377    name = str(source[0].get_contents())
378    obj = all_enums[name]
379
380    print >>cc_file, obj.cxx_def()
381    cc_file.close()
382
383def createEnumParam(target, source, env):
384    assert len(target) == 1 and len(source) == 1
385
386    hh_file = file(target[0].abspath, 'w')
387    name = str(source[0].get_contents())
388    obj = all_enums[name]
389
390    print >>hh_file, obj.cxx_decl()
391
392# Generate all of the SimObject param struct header files
393params_hh_files = []
394for name,simobj in sim_objects.iteritems():
395    extra_deps = [ File(py_modules[simobj.__module__]) ]
396
397    hh_file = File('params/%s.hh' % name)
398    params_hh_files.append(hh_file)
399    env.Command(hh_file, Value(name), createSimObjectParam)
400    env.Depends(hh_file, depends + extra_deps)
401
402# Generate any parameter header files needed
403params_i_files = []
404for name,param in all_params.iteritems():
405    if isinstance(param, m5.params.VectorParamDesc):
406        ext = 'vptype'
407    else:
408        ext = 'ptype'
409
410    i_file = File('params/%s_%s.i' % (name, ext))
411    params_i_files.append(i_file)
412    env.Command(i_file, Value(name), createSwigParam)
413    env.Depends(i_file, depends)
414
415# Generate all enum header files
416for name,enum in all_enums.iteritems():
417    extra_deps = [ File(py_modules[enum.__module__]) ]
418
419    cc_file = File('enums/%s.cc' % name)
420    env.Command(cc_file, Value(name), createEnumStrings)
421    env.Depends(cc_file, depends + extra_deps)
422    Source(cc_file)
423
424    hh_file = File('enums/%s.hh' % name)
425    env.Command(hh_file, Value(name), createEnumParam)
426    env.Depends(hh_file, depends + extra_deps)
427
428# Build the big monolithic swigged params module (wraps all SimObject
429# param structs and enum structs)
430def buildParams(target, source, env):
431    names = [ s.get_contents() for s in source ]
432    objs = [ sim_objects[name] for name in names ]
433    out = file(target[0].abspath, 'w')
434
435    ordered_objs = []
436    obj_seen = set()
437    def order_obj(obj):
438        name = str(obj)
439        if name in obj_seen:
440            return
441
442        obj_seen.add(name)
443        if str(obj) != 'SimObject':
444            order_obj(obj.__bases__[0])
445
446        ordered_objs.append(obj)
447
448    for obj in objs:
449        order_obj(obj)
450
451    enums = set()
452    predecls = []
453    pd_seen = set()
454
455    def add_pds(*pds):
456        for pd in pds:
457            if pd not in pd_seen:
458                predecls.append(pd)
459                pd_seen.add(pd)
460
461    for obj in ordered_objs:
462        params = obj._params.local.values()
463        for param in params:
464            ptype = param.ptype
465            if issubclass(ptype, m5.params.Enum):
466                if ptype not in enums:
467                    enums.add(ptype)
468            pds = param.swig_predecls()
469            if isinstance(pds, (list, tuple)):
470                add_pds(*pds)
471            else:
472                add_pds(pds)
473
474    print >>out, '%module params'
475
476    print >>out, '%{'
477    for obj in ordered_objs:
478        print >>out, '#include "params/%s.hh"' % obj
479    print >>out, '%}'
480
481    for pd in predecls:
482        print >>out, pd
483
484    enums = list(enums)
485    enums.sort()
486    for enum in enums:
487        print >>out, '%%include "enums/%s.hh"' % enum.__name__
488    print >>out
489
490    for obj in ordered_objs:
491        if obj.swig_objdecls:
492            for decl in obj.swig_objdecls:
493                print >>out, decl
494            continue
495
496        code = ''
497        base = obj.get_base()
498
499        code += '// stop swig from creating/wrapping default ctor/dtor\n'
500        code += '%%nodefault %s;\n' % obj.cxx_class
501        code += 'class %s ' % obj.cxx_class
502        if base:
503            code += ': public %s' % base
504        code += ' {};\n'
505
506        klass = obj.cxx_class;
507        if hasattr(obj, 'cxx_namespace'):
508            new_code = 'namespace %s {\n' % obj.cxx_namespace
509            new_code += code
510            new_code += '}\n'
511            code = new_code
512            klass = '%s::%s' % (obj.cxx_namespace, klass)
513
514        print >>out, code
515
516    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
517    for obj in ordered_objs:
518        print >>out, '%%include "params/%s.hh"' % obj
519
520params_file = File('params/params.i')
521names = sort_list(sim_objects.keys())
522env.Command(params_file, [ Value(v) for v in names ], buildParams)
523env.Depends(params_file, params_hh_files + params_i_files + depends)
524SwigSource('m5.objects', params_file)
525
526# Build all swig modules
527swig_modules = []
528for source,package in swig_sources:
529    filename = str(source)
530    assert filename.endswith('.i')
531
532    base = '.'.join(filename.split('.')[:-1])
533    module = basename(base)
534    cc_file = base + '_wrap.cc'
535    py_file = base + '.py'
536
537    env.Command([cc_file, py_file], source,
538                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
539                '-o ${TARGETS[0]} $SOURCES')
540    env.Depends(py_file, source)
541    env.Depends(cc_file, source)
542
543    swig_modules.append(Value(module))
544    Source(cc_file)
545    PySource(package, py_file)
546
547# Generate the main swig init file
548def makeSwigInit(target, source, env):
549    f = file(str(target[0]), 'w')
550    print >>f, 'extern "C" {'
551    for module in source:
552        print >>f, '    void init_%s();' % module.get_contents()
553    print >>f, '}'
554    print >>f, 'void init_swig() {'
555    for module in source:
556        print >>f, '    init_%s();' % module.get_contents()
557    print >>f, '}'
558    f.close()
559
560env.Command('swig/init.cc', swig_modules, makeSwigInit)
561Source('swig/init.cc')
562
563# Generate traceflags.py
564def traceFlagsPy(target, source, env):
565    assert(len(target) == 1)
566
567    f = file(str(target[0]), 'w')
568
569    allFlags = []
570    for s in source:
571        val = eval(s.get_contents())
572        allFlags.append(val)
573
574    print >>f, 'baseFlags = ['
575    for flag, compound, desc in allFlags:
576        if not compound:
577            print >>f, "    '%s'," % flag
578    print >>f, "    ]"
579    print >>f
580
581    print >>f, 'compoundFlags = ['
582    print >>f, "    'All',"
583    for flag, compound, desc in allFlags:
584        if compound:
585            print >>f, "    '%s'," % flag
586    print >>f, "    ]"
587    print >>f
588
589    print >>f, "allFlags = frozenset(baseFlags + compoundFlags)"
590    print >>f
591
592    print >>f, 'compoundFlagMap = {'
593    all = tuple([flag for flag,compound,desc in allFlags if not compound])
594    print >>f, "    'All' : %s," % (all, )
595    for flag, compound, desc in allFlags:
596        if compound:
597            print >>f, "    '%s' : %s," % (flag, compound)
598    print >>f, "    }"
599    print >>f
600
601    print >>f, 'flagDescriptions = {'
602    print >>f, "    'All' : 'All flags',"
603    for flag, compound, desc in allFlags:
604        print >>f, "    '%s' : '%s'," % (flag, desc)
605    print >>f, "    }"
606
607    f.close()
608
609def traceFlagsCC(target, source, env):
610    assert(len(target) == 1)
611
612    f = file(str(target[0]), 'w')
613
614    allFlags = []
615    for s in source:
616        val = eval(s.get_contents())
617        allFlags.append(val)
618
619    # file header
620    print >>f, '''
621/*
622 * DO NOT EDIT THIS FILE! Automatically generated
623 */
624
625#include "base/traceflags.hh"
626
627using namespace Trace;
628
629const char *Trace::flagStrings[] =
630{'''
631
632    # The string array is used by SimpleEnumParam to map the strings
633    # provided by the user to enum values.
634    for flag, compound, desc in allFlags:
635        if not compound:
636            print >>f, '    "%s",' % flag
637
638    print >>f, '    "All",'
639    for flag, compound, desc in allFlags:
640        if compound:
641            print >>f, '    "%s",' % flag
642
643    print >>f, '};'
644    print >>f
645    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
646    print >>f
647
648    #
649    # Now define the individual compound flag arrays.  There is an array
650    # for each compound flag listing the component base flags.
651    #
652    all = tuple([flag for flag,compound,desc in allFlags if not compound])
653    print >>f, 'static const Flags AllMap[] = {'
654    for flag, compound, desc in allFlags:
655        if not compound:
656            print >>f, "    %s," % flag
657    print >>f, '};'
658    print >>f
659
660    for flag, compound, desc in allFlags:
661        if not compound:
662            continue
663        print >>f, 'static const Flags %sMap[] = {' % flag
664        for flag in compound:
665            print >>f, "    %s," % flag
666        print >>f, "    (Flags)-1"
667        print >>f, '};'
668        print >>f
669
670    #
671    # Finally the compoundFlags[] array maps the compound flags
672    # to their individual arrays/
673    #
674    print >>f, 'const Flags *Trace::compoundFlags[] ='
675    print >>f, '{'
676    print >>f, '    AllMap,'
677    for flag, compound, desc in allFlags:
678        if compound:
679            print >>f, '    %sMap,' % flag
680    # file trailer
681    print >>f, '};'
682
683    f.close()
684
685def traceFlagsHH(target, source, env):
686    assert(len(target) == 1)
687
688    f = file(str(target[0]), 'w')
689
690    allFlags = []
691    for s in source:
692        val = eval(s.get_contents())
693        allFlags.append(val)
694
695    # file header boilerplate
696    print >>f, '''
697/*
698 * DO NOT EDIT THIS FILE!
699 *
700 * Automatically generated from traceflags.py
701 */
702
703#ifndef __BASE_TRACE_FLAGS_HH__
704#define __BASE_TRACE_FLAGS_HH__
705
706namespace Trace {
707
708enum Flags {'''
709
710    # Generate the enum.  Base flags come first, then compound flags.
711    idx = 0
712    for flag, compound, desc in allFlags:
713        if not compound:
714            print >>f, '    %s = %d,' % (flag, idx)
715            idx += 1
716
717    numBaseFlags = idx
718    print >>f, '    NumFlags = %d,' % idx
719
720    # put a comment in here to separate base from compound flags
721    print >>f, '''
722// The remaining enum values are *not* valid indices for Trace::flags.
723// They are "compound" flags, which correspond to sets of base
724// flags, and are used by changeFlag.'''
725
726    print >>f, '    All = %d,' % idx
727    idx += 1
728    for flag, compound, desc in allFlags:
729        if compound:
730            print >>f, '    %s = %d,' % (flag, idx)
731            idx += 1
732
733    numCompoundFlags = idx - numBaseFlags
734    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
735
736    # trailer boilerplate
737    print >>f, '''\
738}; // enum Flags
739
740// Array of strings for SimpleEnumParam
741extern const char *flagStrings[];
742extern const int numFlagStrings;
743
744// Array of arraay pointers: for each compound flag, gives the list of
745// base flags to set.  Inidividual flag arrays are terminated by -1.
746extern const Flags *compoundFlags[];
747
748/* namespace Trace */ }
749
750#endif // __BASE_TRACE_FLAGS_HH__
751'''
752
753    f.close()
754
755flags = [ Value(f) for f in trace_flags ]
756env.Command('base/traceflags.py', flags, traceFlagsPy)
757PySource('m5', 'base/traceflags.py')
758
759env.Command('base/traceflags.hh', flags, traceFlagsHH)
760env.Command('base/traceflags.cc', flags, traceFlagsCC)
761Source('base/traceflags.cc')
762
763# Generate program_info.cc
764def programInfo(target, source, env):
765    def gen_file(target, rev, node, date):
766        pi_stats = file(target, 'w')
767        print >>pi_stats, 'const char *hgRev = "%s:%s";' %  (rev, node)
768        print >>pi_stats, 'const char *hgDate = "%s";' % date
769        pi_stats.close()
770
771    target = str(target[0])
772    scons_dir = str(source[0].get_contents())
773    try:
774        import mercurial.demandimport, mercurial.hg, mercurial.ui
775        import mercurial.util, mercurial.node
776        if not exists(scons_dir) or not isdir(scons_dir) or \
777               not exists(joinpath(scons_dir, ".hg")):
778            raise ValueError
779        repo = mercurial.hg.repository(mercurial.ui.ui(), scons_dir)
780        rev = mercurial.node.nullrev + repo.changelog.count()
781        changenode = repo.changelog.node(rev)
782        changes = repo.changelog.read(changenode)
783        date = mercurial.util.datestr(changes[2])
784
785        gen_file(target, rev, mercurial.node.hex(changenode), date)
786
787        mercurial.demandimport.disable()
788    except ImportError:
789        gen_file(target, "Unknown", "Unknown", "Unknown")
790
791    except:
792        print "in except"
793        gen_file(target, "Unknown", "Unknown", "Unknown")
794        mercurial.demandimport.disable()
795
796env.Command('base/program_info.cc',
797            Value(str(SCons.Node.FS.default_fs.SConstruct_dir)),
798            programInfo)
799
800# Build the zip file
801def compilePyFile(target, source, env):
802    '''Action function to compile a .py into a .pyc'''
803    py_compile.compile(str(source[0]), str(target[0]))
804
805def buildPyZip(target, source, env):
806    '''Action function to build the zip archive.  Uses the
807    PyZipFile module included in the standard Python library.'''
808
809    py_compiled = {}
810    for s in py_sources:
811        compname = str(s.compiled)
812        assert compname not in py_compiled
813        py_compiled[compname] = s
814
815    zf = zipfile.ZipFile(str(target[0]), 'w')
816    for s in source:
817        zipname = str(s)
818        arcname = py_compiled[zipname].arcname
819        zf.write(zipname, arcname)
820    zf.close()
821
822py_compiled = []
823py_zip_depends = []
824for source in py_sources:
825    env.Command(source.compiled, source.source, compilePyFile)
826    py_compiled.append(source.compiled)
827
828    # make the zipfile depend on the archive name so that the archive
829    # is rebuilt if the name changes
830    py_zip_depends.append(Value(source.arcname))
831
832# Add the zip file target to the environment.
833m5zip = File('m5py.zip')
834env.Command(m5zip, py_compiled, buildPyZip)
835env.Depends(m5zip, py_zip_depends)
836
837########################################################################
838#
839# Define binaries.  Each different build type (debug, opt, etc.) gets
840# a slightly different build environment.
841#
842
843# List of constructed environments to pass back to SConstruct
844envList = []
845
846# This function adds the specified sources to the given build
847# environment, and returns a list of all the corresponding SCons
848# Object nodes (including an extra one for date.cc).  We explicitly
849# add the Object nodes so we can set up special dependencies for
850# date.cc.
851def make_objs(sources, env):
852    objs = [env.Object(s) for s in sources]
853  
854    # make date.cc depend on all other objects so it always gets
855    # recompiled whenever anything else does
856    date_obj = env.Object('base/date.cc')
857
858    # Make the generation of program_info.cc dependend on all 
859    # the other cc files and the compiling of program_info.cc 
860    # dependent on all the objects but program_info.o 
861    pinfo_obj = env.Object('base/program_info.cc')
862    env.Depends('base/program_info.cc', sources)
863    env.Depends(date_obj, objs)
864    env.Depends(pinfo_obj, objs)
865    objs.extend([date_obj,pinfo_obj])
866    return objs
867
868# Function to create a new build environment as clone of current
869# environment 'env' with modified object suffix and optional stripped
870# binary.  Additional keyword arguments are appended to corresponding
871# build environment vars.
872def makeEnv(label, objsfx, strip = False, **kwargs):
873    newEnv = env.Copy(OBJSUFFIX=objsfx)
874    newEnv.Label = label
875    newEnv.Append(**kwargs)
876    exe = 'm5.' + label  # final executable
877    bin = exe + '.bin'   # executable w/o appended Python zip archive
878    newEnv.Program(bin, make_objs(cc_sources, newEnv))
879    if strip:
880        stripped_bin = bin + '.stripped'
881        if sys.platform == 'sunos5':
882            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
883        else:
884            cmd = 'strip $SOURCE -o $TARGET'
885        newEnv.Command(stripped_bin, bin, cmd)
886        bin = stripped_bin
887    targets = newEnv.Concat(exe, [bin, 'm5py.zip'])
888    newEnv.M5Binary = targets[0]
889    envList.append(newEnv)
890
891# Debug binary
892ccflags = {}
893if env['GCC']:
894    if sys.platform == 'sunos5':
895        ccflags['debug'] = '-gstabs+'
896    else:
897        ccflags['debug'] = '-ggdb3'
898    ccflags['opt'] = '-g -O3'
899    ccflags['fast'] = '-O3'
900    ccflags['prof'] = '-O3 -g -pg'
901elif env['SUNCC']:
902    ccflags['debug'] = '-g0'
903    ccflags['opt'] = '-g -O'
904    ccflags['fast'] = '-fast'
905    ccflags['prof'] = '-fast -g -pg'
906elif env['ICC']:
907    ccflags['debug'] = '-g -O0'
908    ccflags['opt'] = '-g -O'
909    ccflags['fast'] = '-fast'
910    ccflags['prof'] = '-fast -g -pg'
911else:
912    print 'Unknown compiler, please fix compiler options'
913    Exit(1)
914
915makeEnv('debug', '.do',
916        CCFLAGS = Split(ccflags['debug']),
917        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
918
919# Optimized binary
920makeEnv('opt', '.o',
921        CCFLAGS = Split(ccflags['opt']),
922        CPPDEFINES = ['TRACING_ON=1'])
923
924# "Fast" binary
925makeEnv('fast', '.fo', strip = True,
926        CCFLAGS = Split(ccflags['fast']),
927        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
928
929# Profiled binary
930makeEnv('prof', '.po',
931        CCFLAGS = Split(ccflags['prof']),
932        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
933        LINKFLAGS = '-pg')
934
935Return('envList')
936