__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
-import string
+import re
+import sys
import SCons.Action
-import SCons.Tool
-import SCons.Errors
import SCons.Builder
+import SCons.Errors
+import SCons.Platform.win32
+import SCons.Tool
+import SCons.Tool.msvs
import SCons.Util
+import SCons.Warnings
+import SCons.Scanner.RC
+
+from MSCommon import msvc_exists, msvc_setup_env_once
CSuffixes = ['.c', '.C']
CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++']
-def get_devstudio_versions():
- """
- Get list of devstudio versions from the Windows registry. Return a
- list of strings containing version numbers; an exception will be raised
- if we were unable to access the registry (eg. couldn't import
- a registry-access module) or the appropriate registry keys weren't
- found.
- """
-
- if not SCons.Util.can_read_reg:
- raise SCons.Errors.InternalError, "No Windows registry module was found"
-
- K = 'Software\\Microsoft\\Devstudio'
- L = []
- for base in (SCons.Util.HKEY_CLASSES_ROOT,
- SCons.Util.HKEY_LOCAL_MACHINE,
- SCons.Util.HKEY_CURRENT_USER,
- SCons.Util.HKEY_USERS):
- try:
- k = SCons.Util.RegOpenKeyEx(base,K)
- i = 0
- while 1:
- try:
- p = SCons.Util.RegEnumKey(k,i)
- if p[0] in '123456789' and p not in L:
- L.append(p)
- except SCons.Util.RegError:
- break
- i = i + 1
- except SCons.Util.RegError:
- pass
-
- if not L:
- raise SCons.Errors.InternalError, "DevStudio was not found."
-
- L.sort()
- L.reverse()
- return L
-
-def get_msvc_path (path, version, platform='x86'):
- """
- Get a list of devstudio directories (include, lib or path). Return
- a string delimited by ';'. An exception will be raised if unable to
- access the registry or appropriate registry keys not found.
- """
-
- if not SCons.Util.can_read_reg:
- raise SCons.Errors.InternalError, "No Windows registry module was found"
-
- if path=='lib':
- path= 'Library'
- path = string.upper(path + ' Dirs')
- K = ('Software\\Microsoft\\Devstudio\\%s\\' +
- 'Build System\\Components\\Platforms\\Win32 (%s)\\Directories') % \
- (version,platform)
- for base in (SCons.Util.HKEY_CLASSES_ROOT,
- SCons.Util.HKEY_LOCAL_MACHINE,
- SCons.Util.HKEY_CURRENT_USER,
- SCons.Util.HKEY_USERS):
- try:
- k = SCons.Util.RegOpenKeyEx(base,K)
- i = 0
- while 1:
- try:
- (p,v,t) = SCons.Util.RegEnumValue(k,i)
- if string.upper(p) == path:
- return v
- i = i + 1
- except SCons.Util.RegError:
- break
- except SCons.Util.RegError:
- pass
-
- # if we got here, then we didn't find the registry entries:
- raise SCons.Errors.InternalError, "%s was not found in the registry."%path
-
-def get_msdev_dir(version):
- """Returns the root directory of the MSDev installation from the
- registry if it can be found, otherwise we guess."""
- if SCons.Util.can_read_reg:
- K = ('Software\\Microsoft\\Devstudio\\%s\\' +
- 'Products\\Microsoft Visual C++') % \
- version
- for base in (SCons.Util.HKEY_LOCAL_MACHINE,
- SCons.Util.HKEY_CURRENT_USER):
- try:
- k = SCons.Util.RegOpenKeyEx(base,K)
- val, tok = SCons.Util.RegQueryValueEx(k, 'ProductDir')
- return os.path.split(val)[0]
- except SCons.Util.RegError:
- pass
-
-def get_msdev_paths(version=None):
- """Return a 3-tuple of (INCLUDE, LIB, PATH) as the values
- of those three environment variables that should be set
- in order to execute the MSVC tools properly."""
- exe_path = ''
- lib_path = ''
- include_path = ''
- try:
- if not version:
- version = get_devstudio_versions()[0] #use highest version
- include_path = get_msvc_path("include", version)
- lib_path = get_msvc_path("lib", version)
- exe_path = get_msvc_path("path", version) + ";" + os.environ['PATH']
- except (SCons.Util.RegError, SCons.Errors.InternalError):
- # Could not get the configured directories from the registry.
- # However, the configured directories only appear if the user
- # changes them from the default. Therefore, we'll see if
- # we can get the path to the MSDev base installation from
- # the registry and deduce the default directories.
- MVSdir = None
- if version:
- MVSdir = get_msdev_dir(version)
- if MVSdir:
- MVSVCdir = r'%s\VC98' % MVSdir
- MVSCommondir = r'%s\Common' % MVSdir
- include_path = r'%s\atl\include;%s\mfc\include;%s\include' % (MVSVCdir, MVSVCdir, MVSVCdir)
- lib_path = r'%s\mfc\lib;%s\lib' % (MVSVCdir, MVSVCdir)
- try:
- extra_path = os.pathsep + os.environ['PATH']
- except KeyError:
- extra_path = ''
- exe_path = (r'%s\MSDev98\Bin;%s\Bin' % (MVSCommondir, MVSVCdir)) + extra_path
- else:
- # The DevStudio environment variables don't exist,
- # so just use the variables from the source environment.
- MVSdir = r'C:\Program Files\Microsoft Visual Studio'
- MVSVCdir = r'%s\VC98' % MVSdir
- MVSCommondir = r'%s\Common' % MVSdir
- try:
- include_path = os.environ['INCLUDE']
- except KeyError:
- include_path = ''
- try:
- lib_path = os.environ['LIB']
- except KeyError:
- lib_path = ''
- try:
- exe_path = os.environ['PATH']
- except KeyError:
- exe_path = ''
- return (include_path, lib_path, exe_path)
-
def validate_vars(env):
- """Validate the PDB, 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."
+ """Validate the PCH and PCHSTOP construction variables."""
+ if 'PCH' in env and env['PCH']:
+ if 'PCHSTOP' not in env:
+ 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']
+ raise SCons.Errors.UserError("The PCHSTOP construction variable must be a string: %r"%env['PCHSTOP'])
def pch_emitter(target, source, env):
- """Sets up the PDB dependencies for a pch file, and adds the object
- file target."""
+ """Adds the object file target."""
validate_vars(env)
obj = None
for t in target:
- if os.path.splitext(str(t))[1] == '.pch':
+ if SCons.Util.splitext(str(t))[1] == '.pch':
pch = t
- if os.path.splitext(str(t))[1] == '.obj':
+ if SCons.Util.splitext(str(t))[1] == '.obj':
obj = t
if not obj:
- obj = os.path.splitext(str(pch))[0]+'.obj'
+ obj = SCons.Util.splitext(str(pch))[0]+'.obj'
target = [pch, obj] # pch must be first, and obj second for the PCHCOM to work
- if env.has_key('PDB') and env['PDB']:
- env.SideEffect(env['PDB'], target)
- env.Precious(env['PDB'])
-
return (target, source)
-def object_emitter(target, source, env):
- """Sets up the PDB and PCH dependencies for an object file."""
+def object_emitter(target, source, env, parent_emitter):
+ """Sets up the PCH dependencies for an object file."""
validate_vars(env)
- if env.has_key('PDB') and env['PDB']:
- env.SideEffect(env['PDB'], target)
- env.Precious(env['PDB'])
-
- if env.has_key('PCH') and env['PCH']:
- env.Depends(target, env['PCH'])
+ parent_emitter(target, source, env)
+
+ # Add a dependency, but only if the target (e.g. 'Source1.obj')
+ # doesn't correspond to the pre-compiled header ('Source1.pch').
+ # If the basenames match, then this was most likely caused by
+ # someone adding the source file to both the env.PCH() and the
+ # env.Program() calls, and adding the explicit dependency would
+ # cause a cycle on the .pch file itself.
+ #
+ # See issue #2505 for a discussion of what to do if it turns
+ # out this assumption causes trouble in the wild:
+ # http://scons.tigris.org/issues/show_bug.cgi?id=2505
+ if 'PCH' in env:
+ pch = env['PCH']
+ if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj':
+ env.Depends(target, pch)
return (target, source)
-pch_builder = SCons.Builder.Builder(action='$PCHCOM', suffix='.pch', emitter=pch_emitter)
-res_builder = SCons.Builder.Builder(action='$RCCOM', suffix='.res')
+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)
-def generate(env, platform):
+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)
+
+
+# Logic to build .rc files into .res files (resource files)
+res_scanner = SCons.Scanner.RC.RCScan()
+res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
+res_builder = SCons.Builder.Builder(action=res_action,
+ src_suffix='.rc',
+ suffix='.res',
+ src_builder=[],
+ source_scanner=res_scanner)
+
+def msvc_batch_key(action, env, target, source):
+ """
+ Returns a key to identify unique batches of sources for compilation.
+
+ If batching is enabled (via the $MSVC_BATCH setting), then all
+ target+source pairs that use the same action, defined by the same
+ environment, and have the same target and source directories, will
+ be batched.
+
+ Returning None specifies that the specified target+source should not
+ be batched with other compilations.
+ """
+ b = env.subst('$MSVC_BATCH')
+ if b in (None, '', '0'):
+ # We're not using batching; return no key.
+ return None
+ t = target[0]
+ s = source[0]
+ if os.path.splitext(t.name)[0] != os.path.splitext(s.name)[0]:
+ # The base names are different, so this *must* be compiled
+ # separately; return no key.
+ return None
+ return (id(action), id(env), t.dir, s.dir)
+
+def msvc_output_flag(target, source, env, for_signature):
+ """
+ Returns the correct /Fo flag for batching.
+
+ If batching is disabled or there's only one source file, then we
+ return an /Fo string that specifies the target explicitly. Otherwise,
+ we return an /Fo string that just specifies the first target's
+ directory (where the Visual C/C++ compiler will put the .obj files).
+ """
+ b = env.subst('$MSVC_BATCH')
+ if b in (None, '', '0') or len(source) == 1:
+ return '/Fo$TARGET'
+ else:
+ # The Visual C/C++ compiler requires a \ at the end of the /Fo
+ # option to indicate an output directory. We use os.sep here so
+ # that the test(s) for this can be run on non-Windows systems
+ # without having a hard-coded backslash mess up command-line
+ # argument parsing.
+ return '/Fo${TARGET.dir}' + os.sep
+
+CAction = SCons.Action.Action("$CCCOM", "$CCCOMSTR",
+ batch_key=msvc_batch_key,
+ targets='$CHANGED_TARGETS')
+ShCAction = SCons.Action.Action("$SHCCCOM", "$SHCCCOMSTR",
+ batch_key=msvc_batch_key,
+ targets='$CHANGED_TARGETS')
+CXXAction = SCons.Action.Action("$CXXCOM", "$CXXCOMSTR",
+ batch_key=msvc_batch_key,
+ targets='$CHANGED_TARGETS')
+ShCXXAction = SCons.Action.Action("$SHCXXCOM", "$SHCXXCOMSTR",
+ batch_key=msvc_batch_key,
+ targets='$CHANGED_TARGETS')
+
+def generate(env):
"""Add Builders and construction variables for MSVC++ to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
+ # TODO(batch): shouldn't reach in to cmdgen this way; necessary
+ # for now to bypass the checks in Builder.DictCmdGenerator.__call__()
+ # and allow .cc and .cpp to be compiled in the same command line.
+ static_obj.cmdgen.source_ext_match = False
+ shared_obj.cmdgen.source_ext_match = False
+
for suffix in CSuffixes:
- static_obj.add_action(suffix, SCons.Defaults.CAction)
- shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
+ static_obj.add_action(suffix, CAction)
+ shared_obj.add_action(suffix, 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)
-
- env['CCPDBFLAGS'] = '${(PDB and "/Zi /Fd%s"%File(PDB)) or ""}'
- env['CCPCHFLAGS'] = '${(PCH and "/Yu%s /Fp%s"%(PCHSTOP or "",File(PCH))) or ""}'
- env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET $CCPCHFLAGS $CCPDBFLAGS'
+ static_obj.add_action(suffix, CXXAction)
+ shared_obj.add_action(suffix, 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['_MSVC_OUTPUT_FLAG'] = msvc_output_flag
+ env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS'
env['CC'] = 'cl'
- env['CCFLAGS'] = '/nologo'
- env['CCCOM'] = '$CC $CCFLAGS $CCCOMFLAGS'
+ env['CCFLAGS'] = SCons.Util.CLVar('/nologo')
+ env['CFLAGS'] = SCons.Util.CLVar('')
+ env['CCCOM'] = '$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM'
env['SHCC'] = '$CC'
- env['SHCCFLAGS'] = '$CCFLAGS'
- env['SHCCCOM'] = '$SHCC $SHCCFLAGS $CCCOMFLAGS'
+ env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
+ env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
+ env['SHCCCOM'] = '$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM'
env['CXX'] = '$CC'
- env['CXXFLAGS'] = '$CCFLAGS'
- env['CXXCOM'] = '$CXX $CXXFLAGS $CCCOMFLAGS'
+ env['CXXFLAGS'] = SCons.Util.CLVar('$( /TP $)')
+ env['CXXCOM'] = '$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM'
env['SHCXX'] = '$CXX'
- env['SHCXXFLAGS'] = '$CXXFLAGS'
- env['SHCXXCOM'] = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS'
+ env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
+ env['SHCXXCOM'] = '$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM'
+ env['CPPDEFPREFIX'] = '/D'
+ env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '/I'
env['INCSUFFIX'] = ''
- env['OBJEMITTER'] = object_emitter
+# 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'] = ''
- env['RCCOM'] = '$RC $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
- env.CScan.add_skey('.rc')
+ env['RCFLAGS'] = SCons.Util.CLVar('')
+ env['RCSUFFIXES']=['.rc','.rc2']
+ env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
env['BUILDERS']['RES'] = res_builder
-
- include_path, lib_path, exe_path = get_msdev_paths()
- env['ENV']['INCLUDE'] = include_path
- env['ENV']['PATH'] = exe_path
+ env['OBJPREFIX'] = ''
+ env['OBJSUFFIX'] = '.obj'
+ env['SHOBJPREFIX'] = '$OBJPREFIX'
+ env['SHOBJSUFFIX'] = '$OBJSUFFIX'
+
+ # Set-up ms tools paths
+ msvc_setup_env_once(env)
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cc'
- env['PCHCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPINCFLAGS /c $SOURCES /Fo${TARGETS[1]} /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS'
+ env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}'])
+ env['PCHCOM'] = '$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'
env['BUILDERS']['PCH'] = pch_builder
+ if 'ENV' not in env:
+ env['ENV'] = {}
+ if 'SystemRoot' not in env['ENV']: # required for dlls in the winsxs folders
+ env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root()
+
def exists(env):
- return env.Detect('cl')
+ return msvc_exists()
+
+# Local Variables:
+# tab-width:4
+# indent-tabs-mode:nil
+# End:
+# vim: set expandtab tabstop=4 shiftwidth=4: