]> git.cworth.org Git - apitrace/commitdiff
More versatile scons support.
authorJosé Fonseca <jfonseca@vmware.com>
Mon, 4 May 2009 09:23:21 +0000 (10:23 +0100)
committerJosé Fonseca <jfonseca@vmware.com>
Mon, 4 May 2009 09:23:21 +0000 (10:23 +0100)
Support MinGW, WINSDK, etc.

SConstruct
scons/crossmingw.py [new file with mode: 0644]
scons/scons/crossmingw.py [new file with mode: 0644]
scons/scons/mslib_sa.py [new file with mode: 0644]
scons/scons/mslink_sa.py [new file with mode: 0644]
scons/scons/msvc_sa.py [new file with mode: 0644]
scons/scons/winsdk.py [new file with mode: 0644]

index 37c4bde61e6f25d9c9a5958820fce978c5f509b0..60e956a3764503aed98c921dab783d74fd72de84 100644 (file)
 
 import os
 import os.path
+import platform
 import sys
 
-opts = Options('config.py')
-opts.Add(BoolOption('debug', 'build debug version', 'no'))
-opts.Add(PathOption('dxsdk', 'DirectX SDK installation dir', os.environ.get('DXSDK_DIR', 'C:\\DXSDK')))
-opts.Add(EnumOption('MSVS_VERSION', 'Microsoft Visual Studio version', None, allowed_values=('7.1', '8.0', '9.0')))
+_platform_map = {
+    'freebsd': 'freebsd',
+    'linux2': 'linux',
+    'win32': 'windows',
+}
+
+default_platform = _platform_map.get(sys.platform, 'unix')
+
+_machine_map = {
+    'x86': 'x86',
+    'i386': 'x86',
+    'i486': 'x86',
+    'i586': 'x86',
+    'i686': 'x86',
+    'ppc' : 'ppc',
+    'x86_64': 'x86_64',
+}
+if 'PROCESSOR_ARCHITECTURE' in os.environ:
+    default_machine = os.environ['PROCESSOR_ARCHITECTURE']
+else:
+    default_machine = platform.machine()
+default_machine = _machine_map.get(default_machine, 'generic')
+
+vars = Variables()
+vars.Add(BoolVariable('debug', 'debug build', 'no'))
+vars.Add(EnumVariable('platform', 'target platform', default_platform,
+                      allowed_values=('linux', 'freebsd', 'unix', 'other', 'windows')))
+vars.Add(EnumVariable('machine', 'use machine-specific assembly code', default_machine,
+                      allowed_values=('generic', 'ppc', 'x86', 'x86_64')))
+vars.Add(EnumVariable('toolchain', 'compiler toolchain', 'default',
+                      allowed_values=('default', 'crossmingw', 'winsdk')))
+#vars.Add(PathVariable('dxsdk', 'DirectX SDK installation dir', os.environ.get('DXSDK_DIR', 'C:\\DXSDK')))
+vars.Add(EnumVariable('MSVS_VERSION', 'Microsoft Visual Studio version', None, allowed_values=('7.1', '8.0', '9.0')))
 
 env = Environment(
-    options = opts, 
+    variables = vars, 
     ENV = os.environ)
-Help(opts.GenerateHelpText(env))
-
-env.Append(CPPDEFINES = [
-    'WIN32', 
-    '_WINDOWS', 
-    '_UNICODE',
-    'UNICODE',
-    '_CRT_SECURE_NO_DEPRECATE',
-    '_CRT_NON_CONFORMING_SWPRINTFS',
-    'WIN32_LEAN_AND_MEAN',
-    '_USRDLL',
-    ('_WIN32_WINNT', '0x0501'), # minimum required OS version
-])
+Help(vars.GenerateHelpText(env))
 
-if env['debug']:
-    env.Append(CPPDEFINES = ['_DEBUG'])
-else:
-    env.Append(CPPDEFINES = ['NDEBUG'])
-env['PDB'] = '${TARGET.base}.pdb'
+Export(['env'])
 
-cflags = [
-    '/W4', # warning level
-]
-if env['debug']:
-    cflags += [
-      '/Od', # disable optimizations
-      '/Oy-', # disable frame pointer omission
+env.Tool(env['toolchain'], ['scons'])
+
+env['gcc'] = 'gcc' in os.path.basename(env['CC']).split('-')
+env['msvc'] = env['CC'] == 'cl'
+
+# C preprocessor options
+cppdefines = []
+if not env['debug']:
+    cppdefines += ['NDEBUG']
+if env['platform'] == 'windows':
+    cppdefines += [
+        'WIN32',
+        '_WINDOWS', 
+        '_UNICODE',
+        'UNICODE',
+        '_CRT_SECURE_NO_DEPRECATE',
+        '_CRT_NON_CONFORMING_SWPRINTFS',
+        'WIN32_LEAN_AND_MEAN',
+        '_USRDLL',
+        ('_WIN32_WINNT', '0x0501'), # minimum required OS version
+    ]
+    if env['debug']:
+        cppdefines += ['_DEBUG']
+env.Append(CPPDEFINES = cppdefines)
+
+# C compiler options
+cflags = [] # C
+cxxflags = [] # C++
+ccflags = [] # C & C++
+if env['gcc']:
+    if env['debug']:
+        ccflags += ['-O0', '-g3']
+    else:
+        ccflags += ['-O3', '-g0']
+    if env['machine'] == 'x86':
+        ccflags += ['-m32']
+    if env['machine'] == 'x86_64':
+        ccflags += ['-m64']
+    # See also:
+    # - http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
+    ccflags += [
+        '-Werror=declaration-after-statement',
+        '-Wall',
+        '-Wmissing-field-initializers',
+        '-Wpointer-arith',
+        '-fmessage-length=0', # be nice to Eclipse
     ]
-else:
     cflags += [
-      '/Ox', # maximum optimizations
-      '/Os', # favor code space
+        '-Wmissing-prototypes',
+    ]
+if env['msvc']:
+    if env['debug']:
+        ccflags += [
+          '/Od', # disable optimizations
+          '/Oi', # enable intrinsic functions
+          '/Oy-', # disable frame pointer omission
+          '/GL-', # disable whole program optimization
+        ]
+    else:
+        ccflags += [
+          '/Ox', # maximum optimizations
+          '/Oi', # enable intrinsic functions
+          '/Ot', # favor code speed
+        ]
+    ccflags += [
+        '/EHsc', # set exception handling model
+        '/W4', # warning level
+        #'/Wp64', # enable 64 bit porting warnings
     ]
-cflags += [
-    '/Oi', # enable intrinsic functions
-    '/GF', # enable read-only string pooling
-    '/MT',
-]
+    # Automatic pdb generation
+    # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
+    env.EnsureSConsVersion(0, 98, 0)
+    env['PDB'] = '${TARGET.base}.pdb'
+env.Append(CCFLAGS = ccflags)
 env.Append(CFLAGS = cflags)
-env.Append(CXXFLAGS = cflags)
+env.Append(CXXFLAGS = cxxflags)
+
+if env['platform'] == 'windows' and env['msvc']:
+    # Choose the appropriate MSVC CRT
+    # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
+    if env['debug']:
+        env.Append(CCFLAGS = ['/MTd'])
+        env.Append(SHCCFLAGS = ['/LDd'])
+    else:
+        env.Append(CCFLAGS = ['/MT'])
+        env.Append(SHCCFLAGS = ['/LD'])
+    
+# Assembler options
+if env['gcc']:
+    if env['machine'] == 'x86':
+        env.Append(ASFLAGS = ['-m32'])
+    if env['machine'] == 'x86_64':
+        env.Append(ASFLAGS = ['-m64'])
+
+# Linker options
+linkflags = []
+if env['gcc']:
+    if env['machine'] == 'x86':
+        linkflags += ['-m32']
+    if env['machine'] == 'x86_64':
+        linkflags += ['-m64']
+if env['platform'] == 'windows' and env['msvc']:
+    # See also:
+    # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
+    linkflags += [
+        '/fixed:no',
+        '/incremental:no',
+    ]
+env.Append(LINKFLAGS = linkflags)
 
 env.Prepend(LIBS = [
     'kernel32',
@@ -76,12 +179,12 @@ env.Prepend(LIBS = [
     'gdi32',
 ])
 
-Export('env')
 SConscript('zlib/SConscript')
 
-env.Append(CPPPATH = [
-    os.path.join(env['dxsdk'], 'Include'),
-])
+try:
+    env.Append(CPPPATH = [os.path.join(os.environ['DXSDK'], 'Include'),]) 
+except KeyError:
+    pass
 
 conf = Configure(env)
 has_d3d9 = conf.CheckCHeader('d3d9.h')
diff --git a/scons/crossmingw.py b/scons/crossmingw.py
new file mode 100644 (file)
index 0000000..bf81f16
--- /dev/null
@@ -0,0 +1,185 @@
+"""SCons.Tool.gcc
+
+Tool-specific initialization for MinGW (http://www.mingw.org/)
+
+There normally shouldn't be any need to import this module directly.
+It will usually be imported through the generic SCons.Tool.Tool()
+selection method.
+
+See also http://www.scons.org/wiki/CrossCompilingMingw
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os
+import os.path
+import string
+
+import SCons.Action
+import SCons.Builder
+import SCons.Tool
+import SCons.Util
+
+# This is what we search for to find mingw:
+prefixes = SCons.Util.Split("""
+    mingw32-
+    mingw32msvc-
+    i386-mingw32-
+    i486-mingw32-
+    i586-mingw32-
+    i686-mingw32-
+    i386-mingw32msvc-
+    i486-mingw32msvc-
+    i586-mingw32msvc-
+    i686-mingw32msvc-
+""")
+
+def find(env):
+    for prefix in prefixes:
+        # First search in the SCons path and then the OS path:
+        if env.WhereIs(prefix + 'gcc') or SCons.Util.WhereIs(prefix + 'gcc'):
+            return prefix
+
+    return ''
+
+def shlib_generator(target, source, env, for_signature):
+    cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) 
+
+    dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
+    if dll: cmd.extend(['-o', dll])
+
+    cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS'])
+
+    implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX')
+    if implib: cmd.append('-Wl,--out-implib,'+implib.get_string(for_signature))
+
+    def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')
+    if def_target: cmd.append('-Wl,--output-def,'+def_target.get_string(for_signature))
+
+    return [cmd]
+
+def shlib_emitter(target, source, env):
+    dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
+    no_import_lib = env.get('no_import_lib', 0)
+
+    if not dll:
+        raise SCons.Errors.UserError, "A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX")
+    
+    if not no_import_lib and \
+       not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'):
+
+        # Append an import library to the list of targets.
+        target.append(env.ReplaceIxes(dll,  
+                                      'SHLIBPREFIX', 'SHLIBSUFFIX',
+                                      'LIBPREFIX', 'LIBSUFFIX'))
+
+    # Append a def file target if there isn't already a def file target
+    # or a def file source. There is no option to disable def file
+    # target emitting, because I can't figure out why someone would ever
+    # want to turn it off.
+    def_source = env.FindIxes(source, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')
+    def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')
+    if not def_source and not def_target:
+        target.append(env.ReplaceIxes(dll,  
+                                      'SHLIBPREFIX', 'SHLIBSUFFIX',
+                                      'WIN32DEFPREFIX', 'WIN32DEFSUFFIX'))
+    
+    return (target, source)
+                         
+
+shlib_action = SCons.Action.Action(shlib_generator, generator=1)
+
+res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
+
+res_builder = SCons.Builder.Builder(action=res_action, suffix='.o',
+                                    source_scanner=SCons.Tool.SourceFileScanner)
+SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan)
+
+def generate(env):
+    mingw_prefix = find(env)
+
+    if mingw_prefix:
+        dir = os.path.dirname(env.WhereIs(mingw_prefix + 'gcc') or SCons.Util.WhereIs(mingw_prefix + 'gcc'))
+
+        # The mingw bin directory must be added to the path:
+        path = env['ENV'].get('PATH', [])
+        if not path: 
+            path = []
+        if SCons.Util.is_String(path):
+            path = string.split(path, os.pathsep)
+
+        env['ENV']['PATH'] = string.join([dir] + path, os.pathsep)
+
+    # Most of mingw is the same as gcc and friends...
+    gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas']
+    for tool in gnu_tools:
+        SCons.Tool.Tool(tool)(env)
+
+    #... but a few things differ:
+    env['CC'] = mingw_prefix + 'gcc'
+    env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
+    env['CXX'] = mingw_prefix + 'g++'
+    env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
+    env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
+    env['SHLINKCOM']   = shlib_action
+    env.Append(SHLIBEMITTER = [shlib_emitter])
+    env['LINK'] = mingw_prefix + 'g++'
+    env['AR'] = mingw_prefix + 'ar'
+    env['RANLIB'] = mingw_prefix + 'ranlib'
+    env['LINK'] = mingw_prefix + 'g++'
+    env['AS'] = mingw_prefix + 'as'
+    env['WIN32DEFPREFIX']        = ''
+    env['WIN32DEFSUFFIX']        = '.def'
+    env['SHOBJSUFFIX'] = '.o'
+    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
+
+    env['RC'] = mingw_prefix + 'windres'
+    env['RCFLAGS'] = SCons.Util.CLVar('')
+    env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS ${INCPREFIX}${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET'
+    env['BUILDERS']['RES'] = res_builder
+    
+    # Some setting from the platform also have to be overridden:
+    env['OBJPREFIX']      = ''
+    env['OBJSUFFIX']      = '.o'
+    env['SHOBJPREFIX']    = '$OBJPREFIX'
+    env['SHOBJSUFFIX']    = '$OBJSUFFIX'
+    env['PROGPREFIX']     = ''
+    env['PROGSUFFIX']     = '.exe'
+    env['LIBPREFIX']      = 'lib'
+    env['LIBSUFFIX']      = '.a'
+    env['SHLIBPREFIX']    = ''
+    env['SHLIBSUFFIX']    = '.dll'
+    env['LIBPREFIXES']    = [ 'lib', '' ]
+    env['LIBSUFFIXES']    = [ '.a', '.lib' ]
+
+    # MinGW port of gdb does not handle well dwarf debug info which is the
+    # default in recent gcc versions
+    env.AppendUnique(CFLAGS = ['-gstabs'])
+
+    env.AppendUnique(LIBS = ['iberty'])
+    env.AppendUnique(SHLINKFLAGS = ['-Wl,--enable-stdcall-fixup'])
+    #env.AppendUnique(SHLINKFLAGS = ['-Wl,--kill-at'])
+
+def exists(env):
+    return find(env)
diff --git a/scons/scons/crossmingw.py b/scons/scons/crossmingw.py
new file mode 100644 (file)
index 0000000..bf81f16
--- /dev/null
@@ -0,0 +1,185 @@
+"""SCons.Tool.gcc
+
+Tool-specific initialization for MinGW (http://www.mingw.org/)
+
+There normally shouldn't be any need to import this module directly.
+It will usually be imported through the generic SCons.Tool.Tool()
+selection method.
+
+See also http://www.scons.org/wiki/CrossCompilingMingw
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os
+import os.path
+import string
+
+import SCons.Action
+import SCons.Builder
+import SCons.Tool
+import SCons.Util
+
+# This is what we search for to find mingw:
+prefixes = SCons.Util.Split("""
+    mingw32-
+    mingw32msvc-
+    i386-mingw32-
+    i486-mingw32-
+    i586-mingw32-
+    i686-mingw32-
+    i386-mingw32msvc-
+    i486-mingw32msvc-
+    i586-mingw32msvc-
+    i686-mingw32msvc-
+""")
+
+def find(env):
+    for prefix in prefixes:
+        # First search in the SCons path and then the OS path:
+        if env.WhereIs(prefix + 'gcc') or SCons.Util.WhereIs(prefix + 'gcc'):
+            return prefix
+
+    return ''
+
+def shlib_generator(target, source, env, for_signature):
+    cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) 
+
+    dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
+    if dll: cmd.extend(['-o', dll])
+
+    cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS'])
+
+    implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX')
+    if implib: cmd.append('-Wl,--out-implib,'+implib.get_string(for_signature))
+
+    def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')
+    if def_target: cmd.append('-Wl,--output-def,'+def_target.get_string(for_signature))
+
+    return [cmd]
+
+def shlib_emitter(target, source, env):
+    dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
+    no_import_lib = env.get('no_import_lib', 0)
+
+    if not dll:
+        raise SCons.Errors.UserError, "A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX")
+    
+    if not no_import_lib and \
+       not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'):
+
+        # Append an import library to the list of targets.
+        target.append(env.ReplaceIxes(dll,  
+                                      'SHLIBPREFIX', 'SHLIBSUFFIX',
+                                      'LIBPREFIX', 'LIBSUFFIX'))
+
+    # Append a def file target if there isn't already a def file target
+    # or a def file source. There is no option to disable def file
+    # target emitting, because I can't figure out why someone would ever
+    # want to turn it off.
+    def_source = env.FindIxes(source, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')
+    def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')
+    if not def_source and not def_target:
+        target.append(env.ReplaceIxes(dll,  
+                                      'SHLIBPREFIX', 'SHLIBSUFFIX',
+                                      'WIN32DEFPREFIX', 'WIN32DEFSUFFIX'))
+    
+    return (target, source)
+                         
+
+shlib_action = SCons.Action.Action(shlib_generator, generator=1)
+
+res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
+
+res_builder = SCons.Builder.Builder(action=res_action, suffix='.o',
+                                    source_scanner=SCons.Tool.SourceFileScanner)
+SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan)
+
+def generate(env):
+    mingw_prefix = find(env)
+
+    if mingw_prefix:
+        dir = os.path.dirname(env.WhereIs(mingw_prefix + 'gcc') or SCons.Util.WhereIs(mingw_prefix + 'gcc'))
+
+        # The mingw bin directory must be added to the path:
+        path = env['ENV'].get('PATH', [])
+        if not path: 
+            path = []
+        if SCons.Util.is_String(path):
+            path = string.split(path, os.pathsep)
+
+        env['ENV']['PATH'] = string.join([dir] + path, os.pathsep)
+
+    # Most of mingw is the same as gcc and friends...
+    gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas']
+    for tool in gnu_tools:
+        SCons.Tool.Tool(tool)(env)
+
+    #... but a few things differ:
+    env['CC'] = mingw_prefix + 'gcc'
+    env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
+    env['CXX'] = mingw_prefix + 'g++'
+    env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
+    env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
+    env['SHLINKCOM']   = shlib_action
+    env.Append(SHLIBEMITTER = [shlib_emitter])
+    env['LINK'] = mingw_prefix + 'g++'
+    env['AR'] = mingw_prefix + 'ar'
+    env['RANLIB'] = mingw_prefix + 'ranlib'
+    env['LINK'] = mingw_prefix + 'g++'
+    env['AS'] = mingw_prefix + 'as'
+    env['WIN32DEFPREFIX']        = ''
+    env['WIN32DEFSUFFIX']        = '.def'
+    env['SHOBJSUFFIX'] = '.o'
+    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
+
+    env['RC'] = mingw_prefix + 'windres'
+    env['RCFLAGS'] = SCons.Util.CLVar('')
+    env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS ${INCPREFIX}${SOURCE.dir} $RCFLAGS -i $SOURCE -o $TARGET'
+    env['BUILDERS']['RES'] = res_builder
+    
+    # Some setting from the platform also have to be overridden:
+    env['OBJPREFIX']      = ''
+    env['OBJSUFFIX']      = '.o'
+    env['SHOBJPREFIX']    = '$OBJPREFIX'
+    env['SHOBJSUFFIX']    = '$OBJSUFFIX'
+    env['PROGPREFIX']     = ''
+    env['PROGSUFFIX']     = '.exe'
+    env['LIBPREFIX']      = 'lib'
+    env['LIBSUFFIX']      = '.a'
+    env['SHLIBPREFIX']    = ''
+    env['SHLIBSUFFIX']    = '.dll'
+    env['LIBPREFIXES']    = [ 'lib', '' ]
+    env['LIBSUFFIXES']    = [ '.a', '.lib' ]
+
+    # MinGW port of gdb does not handle well dwarf debug info which is the
+    # default in recent gcc versions
+    env.AppendUnique(CFLAGS = ['-gstabs'])
+
+    env.AppendUnique(LIBS = ['iberty'])
+    env.AppendUnique(SHLINKFLAGS = ['-Wl,--enable-stdcall-fixup'])
+    #env.AppendUnique(SHLINKFLAGS = ['-Wl,--kill-at'])
+
+def exists(env):
+    return find(env)
diff --git a/scons/scons/mslib_sa.py b/scons/scons/mslib_sa.py
new file mode 100644 (file)
index 0000000..da51c57
--- /dev/null
@@ -0,0 +1,49 @@
+"""mslib_sa
+
+Tool-specific initialization for lib (MicroSoft library archiver).
+
+Based on SCons.Tool.mslib, without the MSVC detection.
+
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import SCons.Defaults
+import SCons.Tool
+import SCons.Util
+
+def generate(env):
+    """Add Builders and construction variables for lib to an Environment."""
+    SCons.Tool.createStaticLibBuilder(env)
+
+    env['AR']          = 'lib'
+    env['ARFLAGS']     = SCons.Util.CLVar('/nologo')
+    env['ARCOM']       = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}"
+    env['LIBPREFIX']   = ''
+    env['LIBSUFFIX']   = '.lib'
+
+def exists(env):
+    return env.Detect('lib')
+
+# vim:set ts=4 sw=4 et:
diff --git a/scons/scons/mslink_sa.py b/scons/scons/mslink_sa.py
new file mode 100644 (file)
index 0000000..53331de
--- /dev/null
@@ -0,0 +1,211 @@
+"""mslink_sa
+
+Tool-specific initialization for the Microsoft linker.
+
+Based on SCons.Tool.mslink, without the MSVS detection.
+
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os.path
+
+import SCons.Action
+import SCons.Defaults
+import SCons.Errors
+import SCons.Platform.win32
+import SCons.Tool
+import SCons.Tool.msvc
+import SCons.Util
+
+def pdbGenerator(env, target, source, for_signature):
+    try:
+        return ['/PDB:%s' % target[0].attributes.pdb, '/DEBUG']
+    except (AttributeError, IndexError):
+        return None
+
+def windowsShlinkTargets(target, source, env, for_signature):
+    listCmd = []
+    dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX')
+    if dll: listCmd.append("/out:%s"%dll.get_string(for_signature))
+
+    implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX')
+    if implib: listCmd.append("/implib:%s"%implib.get_string(for_signature))
+
+    return listCmd
+
+def windowsShlinkSources(target, source, env, for_signature):
+    listCmd = []
+
+    deffile = env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX")
+    for src in source:
+        if src == deffile:
+            # Treat this source as a .def file.
+            listCmd.append("/def:%s" % src.get_string(for_signature))
+        else:
+            # Just treat it as a generic source file.
+            listCmd.append(src)
+    return listCmd
+
+def windowsLibEmitter(target, source, env):
+    SCons.Tool.msvc.validate_vars(env)
+
+    extratargets = []
+    extrasources = []
+
+    dll = env.FindIxes(target, "SHLIBPREFIX", "SHLIBSUFFIX")
+    no_import_lib = env.get('no_import_lib', 0)
+
+    if not dll:
+        raise SCons.Errors.UserError, "A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX")
+
+    insert_def = env.subst("$WINDOWS_INSERT_DEF")
+    if not insert_def in ['', '0', 0] and \
+       not env.FindIxes(source, "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"):
+
+        # append a def file to the list of sources
+        extrasources.append(
+            env.ReplaceIxes(dll,
+                            "SHLIBPREFIX", "SHLIBSUFFIX",
+                            "WINDOWSDEFPREFIX", "WINDOWSDEFSUFFIX"))
+
+    if env.has_key('PDB') and env['PDB']:
+        pdb = env.arg2nodes('$PDB', target=target, source=source)[0]
+        extratargets.append(pdb)
+        target[0].attributes.pdb = pdb
+
+    if not no_import_lib and \
+       not env.FindIxes(target, "LIBPREFIX", "LIBSUFFIX"):
+        # Append an import library to the list of targets.
+        extratargets.append(
+            env.ReplaceIxes(dll,
+                            "SHLIBPREFIX", "SHLIBSUFFIX",
+                            "LIBPREFIX", "LIBSUFFIX"))
+        # and .exp file is created if there are exports from a DLL
+        extratargets.append(
+            env.ReplaceIxes(dll,
+                            "SHLIBPREFIX", "SHLIBSUFFIX",
+                            "WINDOWSEXPPREFIX", "WINDOWSEXPSUFFIX"))
+
+    return (target+extratargets, source+extrasources)
+
+def prog_emitter(target, source, env):
+    SCons.Tool.msvc.validate_vars(env)
+
+    extratargets = []
+
+    exe = env.FindIxes(target, "PROGPREFIX", "PROGSUFFIX")
+    if not exe:
+        raise SCons.Errors.UserError, "An executable should have exactly one target with the suffix: %s" % env.subst("$PROGSUFFIX")
+
+    if env.has_key('PDB') and env['PDB']:
+        pdb = env.arg2nodes('$PDB', target=target, source=source)[0]
+        extratargets.append(pdb)
+        target[0].attributes.pdb = pdb
+
+    return (target+extratargets,source)
+
+def RegServerFunc(target, source, env):
+    if env.has_key('register') and env['register']:
+        ret = regServerAction([target[0]], [source[0]], env)
+        if ret:
+            raise SCons.Errors.UserError, "Unable to register %s" % target[0]
+        else:
+            print "Registered %s sucessfully" % target[0]
+        return ret
+    return 0
+
+regServerAction = SCons.Action.Action("$REGSVRCOM", "$REGSVRCOMSTR")
+regServerCheck = SCons.Action.Action(RegServerFunc, None)
+shlibLinkAction = SCons.Action.Action('${TEMPFILE("$SHLINK $SHLINKFLAGS $_SHLINK_TARGETS $( $_LIBDIRFLAGS $) $_LIBFLAGS $_PDB $_SHLINK_SOURCES")}')
+compositeLinkAction = shlibLinkAction + regServerCheck
+
+def generate(env):
+    """Add Builders and construction variables for ar to an Environment."""
+    SCons.Tool.createSharedLibBuilder(env)
+    SCons.Tool.createProgBuilder(env)
+
+    env['SHLINK']      = '$LINK'
+    env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS /dll')
+    env['_SHLINK_TARGETS'] = windowsShlinkTargets
+    env['_SHLINK_SOURCES'] = windowsShlinkSources
+    env['SHLINKCOM']   =  compositeLinkAction
+    env.Append(SHLIBEMITTER = [windowsLibEmitter])
+    env['LINK']        = 'link'
+    env['LINKFLAGS']   = SCons.Util.CLVar('/nologo')
+    env['_PDB'] = pdbGenerator
+    env['LINKCOM'] = '${TEMPFILE("$LINK $LINKFLAGS /OUT:$TARGET.windows $( $_LIBDIRFLAGS $) $_LIBFLAGS $_PDB $SOURCES.windows")}'
+    env.Append(PROGEMITTER = [prog_emitter])
+    env['LIBDIRPREFIX']='/LIBPATH:'
+    env['LIBDIRSUFFIX']=''
+    env['LIBLINKPREFIX']=''
+    env['LIBLINKSUFFIX']='$LIBSUFFIX'
+
+    env['WIN32DEFPREFIX']        = ''
+    env['WIN32DEFSUFFIX']        = '.def'
+    env['WIN32_INSERT_DEF']      = 0
+    env['WINDOWSDEFPREFIX']      = '${WIN32DEFPREFIX}'
+    env['WINDOWSDEFSUFFIX']      = '${WIN32DEFSUFFIX}'
+    env['WINDOWS_INSERT_DEF']    = '${WIN32_INSERT_DEF}'
+
+    env['WIN32EXPPREFIX']        = ''
+    env['WIN32EXPSUFFIX']        = '.exp'
+    env['WINDOWSEXPPREFIX']      = '${WIN32EXPPREFIX}'
+    env['WINDOWSEXPSUFFIX']      = '${WIN32EXPSUFFIX}'
+
+    env['WINDOWSSHLIBMANIFESTPREFIX'] = ''
+    env['WINDOWSSHLIBMANIFESTSUFFIX'] = '${SHLIBSUFFIX}.manifest'
+    env['WINDOWSPROGMANIFESTPREFIX']  = ''
+    env['WINDOWSPROGMANIFESTSUFFIX']  = '${PROGSUFFIX}.manifest'
+
+    env['REGSVRACTION'] = regServerCheck
+    env['REGSVR'] = os.path.join(SCons.Platform.win32.get_system_root(),'System32','regsvr32')
+    env['REGSVRFLAGS'] = '/s '
+    env['REGSVRCOM'] = '$REGSVR $REGSVRFLAGS ${TARGET.windows}'
+
+    # For most platforms, a loadable module is the same as a shared
+    # library.  Platforms which are different can override these, but
+    # setting them the same means that LoadableModule works everywhere.
+    SCons.Tool.createLoadableModuleBuilder(env)
+    env['LDMODULE'] = '$SHLINK'
+    env['LDMODULEPREFIX'] = '$SHLIBPREFIX'
+    env['LDMODULESUFFIX'] = '$SHLIBSUFFIX'
+    env['LDMODULEFLAGS'] = '$SHLINKFLAGS'
+    # We can't use '$SHLINKCOM' here because that will stringify the
+    # action list on expansion, and will then try to execute expanded
+    # strings, with the upshot that it would try to execute RegServerFunc
+    # as a command.
+    env['LDMODULECOM'] = compositeLinkAction
+
+def exists(env):
+    platform = env.get('PLATFORM', '')
+    if platform in ('win32', 'cygwin'):
+        # Only explicitly search for a 'link' executable on Windows
+        # systems.  Some other systems (e.g. Ubuntu Linux) have an
+        # executable named 'link' and we don't want that to make SCons
+        # think Visual Studio is installed.
+        return env.Detect('link')
+    return None
+
+# vim:set ts=4 sw=4 et:
diff --git a/scons/scons/msvc_sa.py b/scons/scons/msvc_sa.py
new file mode 100644 (file)
index 0000000..136d305
--- /dev/null
@@ -0,0 +1,173 @@
+"""msvc_sa
+
+Tool-specific initialization for Microsoft Visual C/C++.
+
+Based on SCons.Tool.msvc, without the MSVS detection.
+
+"""
+
+#
+# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os.path
+import re
+import string
+
+import SCons.Action
+import SCons.Builder
+import SCons.Errors
+import SCons.Platform.win32
+import SCons.Tool
+import SCons.Util
+import SCons.Warnings
+
+CSuffixes = ['.c', '.C']
+CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++']
+
+def validate_vars(env):
+    """Validate the PCH and PCHSTOP construction variables."""
+    if env.has_key('PCH') and env['PCH']:
+        if not env.has_key('PCHSTOP'):
+            raise SCons.Errors.UserError, "The PCHSTOP construction must be defined if PCH is defined."
+        if not SCons.Util.is_String(env['PCHSTOP']):
+            raise SCons.Errors.UserError, "The PCHSTOP construction variable must be a string: %r"%env['PCHSTOP']
+
+def pch_emitter(target, source, env):
+    """Adds the object file target."""
+
+    validate_vars(env)
+
+    pch = None
+    obj = None
+
+    for t in target:
+        if SCons.Util.splitext(str(t))[1] == '.pch':
+            pch = t
+        if SCons.Util.splitext(str(t))[1] == '.obj':
+            obj = t
+
+    if not obj:
+        obj = SCons.Util.splitext(str(pch))[0]+'.obj'
+
+    target = [pch, obj] # pch must be first, and obj second for the PCHCOM to work
+
+    return (target, source)
+
+def object_emitter(target, source, env, parent_emitter):
+    """Sets up the PCH dependencies for an object file."""
+
+    validate_vars(env)
+
+    parent_emitter(target, source, env)
+
+    if env.has_key('PCH') and env['PCH']:
+        env.Depends(target, env['PCH'])
+
+    return (target, source)
+
+def static_object_emitter(target, source, env):
+    return object_emitter(target, source, env,
+                          SCons.Defaults.StaticObjectEmitter)
+
+def shared_object_emitter(target, source, env):
+    return object_emitter(target, source, env,
+                          SCons.Defaults.SharedObjectEmitter)
+
+pch_action = SCons.Action.Action('$PCHCOM', '$PCHCOMSTR')
+pch_builder = SCons.Builder.Builder(action=pch_action, suffix='.pch',
+                                    emitter=pch_emitter,
+                                    source_scanner=SCons.Tool.SourceFileScanner)
+res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
+res_builder = SCons.Builder.Builder(action=res_action,
+                                    src_suffix='.rc',
+                                    suffix='.res',
+                                    src_builder=[],
+                                    source_scanner=SCons.Tool.SourceFileScanner)
+SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan)
+
+def generate(env):
+    """Add Builders and construction variables for MSVC++ to an Environment."""
+    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
+
+    for suffix in CSuffixes:
+        static_obj.add_action(suffix, SCons.Defaults.CAction)
+        shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
+        static_obj.add_emitter(suffix, static_object_emitter)
+        shared_obj.add_emitter(suffix, shared_object_emitter)
+
+    for suffix in CXXSuffixes:
+        static_obj.add_action(suffix, SCons.Defaults.CXXAction)
+        shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction)
+        static_obj.add_emitter(suffix, static_object_emitter)
+        shared_obj.add_emitter(suffix, shared_object_emitter)
+
+    env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}'])
+    env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s /Fp%s"%(PCHSTOP or "",File(PCH))) or ""}'])
+    env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET $CCPCHFLAGS $CCPDBFLAGS'
+    env['CC']         = 'cl'
+    env['CCFLAGS']    = SCons.Util.CLVar('/nologo')
+    env['CFLAGS']     = SCons.Util.CLVar('')
+    env['CCCOM']      = '$CC $CFLAGS $CCFLAGS $CCCOMFLAGS'
+    env['SHCC']       = '$CC'
+    env['SHCCFLAGS']  = SCons.Util.CLVar('$CCFLAGS')
+    env['SHCFLAGS']   = SCons.Util.CLVar('$CFLAGS')
+    env['SHCCCOM']    = '$SHCC $SHCFLAGS $SHCCFLAGS $CCCOMFLAGS'
+    env['CXX']        = '$CC'
+    env['CXXFLAGS']   = SCons.Util.CLVar('$CCFLAGS $( /TP $)')
+    env['CXXCOM']     = '$CXX $CXXFLAGS $CCCOMFLAGS'
+    env['SHCXX']      = '$CXX'
+    env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
+    env['SHCXXCOM']   = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS'
+    env['CPPDEFPREFIX']  = '/D'
+    env['CPPDEFSUFFIX']  = ''
+    env['INCPREFIX']  = '/I'
+    env['INCSUFFIX']  = ''
+#    env.Append(OBJEMITTER = [static_object_emitter])
+#    env.Append(SHOBJEMITTER = [shared_object_emitter])
+    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
+
+    env['RC'] = 'rc'
+    env['RCFLAGS'] = SCons.Util.CLVar('')
+    env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
+    env['BUILDERS']['RES'] = res_builder
+    env['OBJPREFIX']      = ''
+    env['OBJSUFFIX']      = '.obj'
+    env['SHOBJPREFIX']    = '$OBJPREFIX'
+    env['SHOBJSUFFIX']    = '$OBJSUFFIX'
+
+    env['CFILESUFFIX'] = '.c'
+    env['CXXFILESUFFIX'] = '.cc'
+
+    env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}'])
+    env['PCHCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo${TARGETS[1]} /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'
+    env['BUILDERS']['PCH'] = pch_builder
+
+    if not env.has_key('ENV'):
+        env['ENV'] = {}
+    if not env['ENV'].has_key('SystemRoot'):    # required for dlls in the winsxs folders
+        env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root()
+
+def exists(env):
+    return env.Detect('cl')
+
+# vim:set ts=4 sw=4 et:
diff --git a/scons/scons/winsdk.py b/scons/scons/winsdk.py
new file mode 100644 (file)
index 0000000..255f9c5
--- /dev/null
@@ -0,0 +1,139 @@
+"""winsdk
+
+Tool-specific initialization for Microsoft Windows SDK.
+
+"""
+
+#
+# Copyright (c) 2001-2007 The SCons Foundation
+# Copyright (c) 2008 Tungsten Graphics, Inc.
+# Copyright (c) 2009 VMware, Inc.
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+
+import os.path
+import platform
+
+import SCons.Errors
+import SCons.Util
+
+import msvc_sa
+import mslib_sa
+import mslink_sa
+
+
+def get_vs_root(env):
+    # TODO: Check HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VS7 
+    path = os.path.join(os.getenv('ProgramFiles', r'C:\Program Files'), 'Microsoft Visual Studio 9.0')
+    return path 
+
+def get_vs_paths(env):
+    vs_root = get_vs_root(env)
+    if vs_root is None:
+        raise SCons.Errors.InternalError, "WINSDK compiler not found"
+
+    tool_path = os.path.join(vs_root, 'Common7', 'IDE')
+
+    env.PrependENVPath('PATH', tool_path)
+
+def get_vc_root(env):
+    # TODO: Check HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\SxS\VC7 
+    path = os.path.join(os.getenv('ProgramFiles', r'C:\Program Files'), 'Microsoft Visual Studio 9.0', 'VC')
+    return path 
+
+def get_vc_paths(env):
+    vc_root = get_vc_root(env)
+    if vc_root is None:
+        raise SCons.Errors.InternalError, "WINSDK compiler not found"
+
+    target_cpu = env['machine']
+
+    if target_cpu in ('generic', 'x86'):
+        bin_dir = 'bin'
+        lib_dir = 'lib'
+    elif target_cpu == 'x86_64':
+        # TODO: take in consideration the host cpu
+        bin_dir = r'bin\x86_amd64'
+        lib_dir = r'lib\amd64'
+    else:
+        raise SCons.Errors.InternalError, "Unsupported target machine"
+    include_dir = 'include'
+
+    exe_path     = os.path.join(vc_root, bin_dir)
+    include_path = os.path.join(vc_root, include_dir)
+    lib_path     = os.path.join(vc_root, lib_dir)
+
+    env.PrependENVPath('INCLUDE', include_path)
+    env.PrependENVPath('LIB', lib_path)
+    env.PrependENVPath('PATH', exe_path)
+
+def get_sdk_root(env):
+    if SCons.Util.can_read_reg:
+        key = r'SOFTWARE\Microsoft\Microsoft SDKs\Windows\CurrentInstallFolder'
+        try:
+            path, t = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE, key)
+        except SCons.Util.RegError:
+            pass
+        else:
+            return path
+
+    return None 
+
+def get_sdk_paths(env):
+    sdk_root = get_sdk_root(env)
+    if sdk_root is None:
+        raise SCons.Errors.InternalError, "WINSDK not found"
+
+    target_cpu = env['machine']
+
+    bin_dir = 'Bin'
+    if target_cpu in ('generic', 'x86'):
+        lib_dir = 'Lib'
+    elif target_cpu == 'x86_64':
+        lib_dir = 'Lib/x64'
+    else:
+        raise SCons.Errors.InternalError, "Unsupported target machine"
+    include_dir = 'Include'
+
+    exe_path     = os.path.join(sdk_root, bin_dir)
+    include_path = os.path.join(sdk_root, include_dir)
+    lib_path     = os.path.join(sdk_root, lib_dir)
+
+    env.PrependENVPath('INCLUDE', include_path)
+    env.PrependENVPath('LIB', lib_path)
+    env.PrependENVPath('PATH', exe_path)
+
+def generate(env):
+    if not env.has_key('ENV'):
+        env['ENV'] = {}
+    
+    get_vs_paths(env)
+    get_vc_paths(env)
+    get_sdk_paths(env)
+
+    msvc_sa.generate(env)
+    mslib_sa.generate(env)
+    mslink_sa.generate(env)
+
+def exists(env):
+    return get_vc_root(env) is not None and get_sdk_root(env) is not None
+
+# vim:set ts=4 sw=4 et: