PageRenderTime 53ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/couchjs/scons/scons-local-2.0.1/SCons/Tool/MSCommon/vc.py

http://github.com/cloudant/bigcouch
Python | 456 lines | 423 code | 2 blank | 31 comment | 2 complexity | 83ecb02673d35aad1cda281037a31565 MD5 | raw file
Possible License(s): Apache-2.0
  1. #
  2. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining
  5. # a copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish,
  8. # distribute, sublicense, and/or sell copies of the Software, and to
  9. # permit persons to whom the Software is furnished to do so, subject to
  10. # the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  16. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  17. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. #
  23. # TODO:
  24. # * supported arch for versions: for old versions of batch file without
  25. # argument, giving bogus argument cannot be detected, so we have to hardcode
  26. # this here
  27. # * print warning when msvc version specified but not found
  28. # * find out why warning do not print
  29. # * test on 64 bits XP + VS 2005 (and VS 6 if possible)
  30. # * SDK
  31. # * Assembly
  32. __revision__ = "src/engine/SCons/Tool/MSCommon/vc.py 5134 2010/08/16 23:02:40 bdeegan"
  33. __doc__ = """Module for Visual C/C++ detection and configuration.
  34. """
  35. import SCons.compat
  36. import os
  37. import platform
  38. from string import digits as string_digits
  39. import SCons.Warnings
  40. import common
  41. debug = common.debug
  42. import sdk
  43. get_installed_sdks = sdk.get_installed_sdks
  44. class VisualCException(Exception):
  45. pass
  46. class UnsupportedVersion(VisualCException):
  47. pass
  48. class UnsupportedArch(VisualCException):
  49. pass
  50. class MissingConfiguration(VisualCException):
  51. pass
  52. class NoVersionFound(VisualCException):
  53. pass
  54. class BatchFileExecutionError(VisualCException):
  55. pass
  56. # Dict to 'canonalize' the arch
  57. _ARCH_TO_CANONICAL = {
  58. "amd64" : "amd64",
  59. "emt64" : "amd64",
  60. "i386" : "x86",
  61. "i486" : "x86",
  62. "i586" : "x86",
  63. "i686" : "x86",
  64. "ia64" : "ia64",
  65. "itanium" : "ia64",
  66. "x86" : "x86",
  67. "x86_64" : "amd64",
  68. }
  69. # Given a (host, target) tuple, return the argument for the bat file. Both host
  70. # and targets should be canonalized.
  71. _HOST_TARGET_ARCH_TO_BAT_ARCH = {
  72. ("x86", "x86"): "x86",
  73. ("x86", "amd64"): "x86_amd64",
  74. ("amd64", "amd64"): "amd64",
  75. ("amd64", "x86"): "x86",
  76. ("x86", "ia64"): "x86_ia64"
  77. }
  78. def get_host_target(env):
  79. debug('vc.py:get_host_target()')
  80. host_platform = env.get('HOST_ARCH')
  81. if not host_platform:
  82. host_platform = platform.machine()
  83. # TODO(2.5): the native Python platform.machine() function returns
  84. # '' on all Python versions before 2.6, after which it also uses
  85. # PROCESSOR_ARCHITECTURE.
  86. if not host_platform:
  87. host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  88. # Retain user requested TARGET_ARCH
  89. req_target_platform = env.get('TARGET_ARCH')
  90. debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform)
  91. if req_target_platform:
  92. # If user requested a specific platform then only try that one.
  93. target_platform = req_target_platform
  94. else:
  95. target_platform = host_platform
  96. try:
  97. host = _ARCH_TO_CANONICAL[host_platform.lower()]
  98. except KeyError, e:
  99. msg = "Unrecognized host architecture %s"
  100. raise ValueError(msg % repr(host_platform))
  101. try:
  102. target = _ARCH_TO_CANONICAL[target_platform.lower()]
  103. except KeyError, e:
  104. raise ValueError("Unrecognized target architecture %s" % target_platform)
  105. return (host, target,req_target_platform)
  106. _VCVER = ["10.0", "9.0", "9.0Exp","8.0", "8.0Exp","7.1", "7.0", "6.0"]
  107. _VCVER_TO_PRODUCT_DIR = {
  108. '10.0': [
  109. r'Microsoft\VisualStudio\10.0\Setup\VC\ProductDir'],
  110. '9.0': [
  111. r'Microsoft\VisualStudio\9.0\Setup\VC\ProductDir'],
  112. '9.0Exp' : [
  113. r'Microsoft\VCExpress\9.0\Setup\VC\ProductDir'],
  114. '8.0': [
  115. r'Microsoft\VisualStudio\8.0\Setup\VC\ProductDir'],
  116. '8.0Exp': [
  117. r'Microsoft\VCExpress\8.0\Setup\VC\ProductDir'],
  118. '7.1': [
  119. r'Microsoft\VisualStudio\7.1\Setup\VC\ProductDir'],
  120. '7.0': [
  121. r'Microsoft\VisualStudio\7.0\Setup\VC\ProductDir'],
  122. '6.0': [
  123. r'Microsoft\VisualStudio\6.0\Setup\Microsoft Visual C++\ProductDir']
  124. }
  125. def msvc_version_to_maj_min(msvc_version):
  126. msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.'])
  127. t = msvc_version_numeric.split(".")
  128. if not len(t) == 2:
  129. raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
  130. try:
  131. maj = int(t[0])
  132. min = int(t[1])
  133. return maj, min
  134. except ValueError, e:
  135. raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric))
  136. def is_host_target_supported(host_target, msvc_version):
  137. """Return True if the given (host, target) tuple is supported given the
  138. msvc version.
  139. Parameters
  140. ----------
  141. host_target: tuple
  142. tuple of (canonalized) host-target, e.g. ("x86", "amd64") for cross
  143. compilation from 32 bits windows to 64 bits.
  144. msvc_version: str
  145. msvc version (major.minor, e.g. 10.0)
  146. Note
  147. ----
  148. This only check whether a given version *may* support the given (host,
  149. target), not that the toolchain is actually present on the machine.
  150. """
  151. # We assume that any Visual Studio version supports x86 as a target
  152. if host_target[1] != "x86":
  153. maj, min = msvc_version_to_maj_min(msvc_version)
  154. if maj < 8:
  155. return False
  156. return True
  157. def find_vc_pdir(msvc_version):
  158. """Try to find the product directory for the given
  159. version.
  160. Note
  161. ----
  162. If for some reason the requested version could not be found, an
  163. exception which inherits from VisualCException will be raised."""
  164. root = 'Software\\'
  165. if common.is_win64():
  166. root = root + 'Wow6432Node\\'
  167. try:
  168. hkeys = _VCVER_TO_PRODUCT_DIR[msvc_version]
  169. except KeyError:
  170. debug("Unknown version of MSVC: %s" % msvc_version)
  171. raise UnsupportedVersion("Unknown version %s" % msvc_version)
  172. for key in hkeys:
  173. key = root + key
  174. try:
  175. comps = common.read_reg(key)
  176. except WindowsError, e:
  177. debug('find_vc_dir(): no VC registry key %s' % repr(key))
  178. else:
  179. debug('find_vc_dir(): found VC in registry: %s' % comps)
  180. if os.path.exists(comps):
  181. return comps
  182. else:
  183. debug('find_vc_dir(): reg says dir is %s, but it does not exist. (ignoring)'\
  184. % comps)
  185. raise MissingConfiguration("registry dir %s not found on the filesystem" % comps)
  186. return None
  187. def find_batch_file(env,msvc_version,host_arch,target_arch):
  188. """
  189. Find the location of the batch script which should set up the compiler
  190. for any TARGET_ARCH whose compilers were installed by Visual Studio/VCExpress
  191. """
  192. pdir = find_vc_pdir(msvc_version)
  193. if pdir is None:
  194. raise NoVersionFound("No version of Visual Studio found")
  195. debug('vc.py: find_batch_file() pdir:%s'%pdir)
  196. # filter out e.g. "Exp" from the version name
  197. msvc_ver_numeric = ''.join([x for x in msvc_version if x in string_digits + "."])
  198. vernum = float(msvc_ver_numeric)
  199. if 7 <= vernum < 8:
  200. pdir = os.path.join(pdir, os.pardir, "Common7", "Tools")
  201. batfilename = os.path.join(pdir, "vsvars32.bat")
  202. elif vernum < 7:
  203. pdir = os.path.join(pdir, "Bin")
  204. batfilename = os.path.join(pdir, "vcvars32.bat")
  205. else: # >= 8
  206. batfilename = os.path.join(pdir, "vcvarsall.bat")
  207. if not os.path.exists(batfilename):
  208. debug("Not found: %s" % batfilename)
  209. batfilename = None
  210. installed_sdks=get_installed_sdks()
  211. for _sdk in installed_sdks:
  212. sdk_bat_file=_sdk.get_sdk_vc_script(host_arch,target_arch)
  213. sdk_bat_file_path=os.path.join(pdir,sdk_bat_file)
  214. debug('vc.py:find_batch_file() sdk_bat_file_path:%s'%sdk_bat_file_path)
  215. if os.path.exists(sdk_bat_file_path):
  216. return (batfilename,sdk_bat_file_path)
  217. else:
  218. debug("vc.py:find_batch_file() not found:%s"%sdk_bat_file_path)
  219. else:
  220. return (batfilename,None)
  221. __INSTALLED_VCS_RUN = None
  222. def cached_get_installed_vcs():
  223. global __INSTALLED_VCS_RUN
  224. if __INSTALLED_VCS_RUN is None:
  225. ret = get_installed_vcs()
  226. __INSTALLED_VCS_RUN = ret
  227. return __INSTALLED_VCS_RUN
  228. def get_installed_vcs():
  229. installed_versions = []
  230. for ver in _VCVER:
  231. debug('trying to find VC %s' % ver)
  232. try:
  233. if find_vc_pdir(ver):
  234. debug('found VC %s' % ver)
  235. installed_versions.append(ver)
  236. else:
  237. debug('find_vc_pdir return None for ver %s' % ver)
  238. except VisualCException, e:
  239. debug('did not find VC %s: caught exception %s' % (ver, str(e)))
  240. return installed_versions
  241. def reset_installed_vcs():
  242. """Make it try again to find VC. This is just for the tests."""
  243. __INSTALLED_VCS_RUN = None
  244. def script_env(script, args=None):
  245. stdout = common.get_output(script, args)
  246. # Stupid batch files do not set return code: we take a look at the
  247. # beginning of the output for an error message instead
  248. olines = stdout.splitlines()
  249. if olines[0].startswith("The specified configuration type is missing"):
  250. raise BatchFileExecutionError("\n".join(olines[:2]))
  251. return common.parse_output(stdout)
  252. def get_default_version(env):
  253. debug('get_default_version()')
  254. msvc_version = env.get('MSVC_VERSION')
  255. msvs_version = env.get('MSVS_VERSION')
  256. debug('get_default_version(): msvc_version:%s msvs_version:%s'%(msvc_version,msvs_version))
  257. if msvs_version and not msvc_version:
  258. SCons.Warnings.warn(
  259. SCons.Warnings.DeprecatedWarning,
  260. "MSVS_VERSION is deprecated: please use MSVC_VERSION instead ")
  261. return msvs_version
  262. elif msvc_version and msvs_version:
  263. if not msvc_version == msvs_version:
  264. SCons.Warnings.warn(
  265. SCons.Warnings.VisualVersionMismatch,
  266. "Requested msvc version (%s) and msvs version (%s) do " \
  267. "not match: please use MSVC_VERSION only to request a " \
  268. "visual studio version, MSVS_VERSION is deprecated" \
  269. % (msvc_version, msvs_version))
  270. return msvs_version
  271. if not msvc_version:
  272. installed_vcs = cached_get_installed_vcs()
  273. debug('installed_vcs:%s' % installed_vcs)
  274. if not installed_vcs:
  275. msg = 'No installed VCs'
  276. debug('msv %s\n' % repr(msg))
  277. SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, msg)
  278. return None
  279. msvc_version = installed_vcs[0]
  280. debug('msvc_setup_env: using default installed MSVC version %s\n' % repr(msvc_version))
  281. return msvc_version
  282. def msvc_setup_env_once(env):
  283. try:
  284. has_run = env["MSVC_SETUP_RUN"]
  285. except KeyError:
  286. has_run = False
  287. if not has_run:
  288. msvc_setup_env(env)
  289. env["MSVC_SETUP_RUN"] = True
  290. def msvc_find_valid_batch_script(env,version):
  291. debug('vc.py:msvc_find_valid_batch_script()')
  292. # Find the host platform, target platform, and if present the requested
  293. # target platform
  294. (host_platform, target_platform,req_target_platform) = get_host_target(env)
  295. # If the user hasn't specifically requested a TARGET_ARCH, and
  296. # The TARGET_ARCH is amd64 then also try 32 bits if there are no viable
  297. # 64 bit tools installed
  298. try_target_archs = [target_platform]
  299. if not req_target_platform and target_platform=='amd64':
  300. try_target_archs.append('x86')
  301. d = None
  302. for tp in try_target_archs:
  303. # Set to current arch.
  304. env['TARGET_ARCH']=tp
  305. debug("vc.py:msvc_find_valid_batch_script() trying target_platform:%s"%tp)
  306. host_target = (host_platform, tp)
  307. if not is_host_target_supported(host_target, version):
  308. warn_msg = "host, target = %s not supported for MSVC version %s" % \
  309. (host_target, version)
  310. SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
  311. arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target]
  312. # Try to locate a batch file for this host/target platform combo
  313. try:
  314. (vc_script,sdk_script) = find_batch_file(env,version,host_platform,tp)
  315. debug('vc.py:msvc_find_valid_batch_script() vc_script:%s sdk_script:%s'%(vc_script,sdk_script))
  316. except VisualCException, e:
  317. msg = str(e)
  318. debug('Caught exception while looking for batch file (%s)' % msg)
  319. warn_msg = "VC version %s not installed. " + \
  320. "C/C++ compilers are most likely not set correctly.\n" + \
  321. " Installed versions are: %s"
  322. warn_msg = warn_msg % (version, cached_get_installed_vcs())
  323. SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
  324. continue
  325. # Try to use the located batch file for this host/target platform combo
  326. debug('vc.py:msvc_find_valid_batch_script() use_script 2 %s, args:%s\n' % (repr(vc_script), arg))
  327. if vc_script:
  328. try:
  329. d = script_env(vc_script, args=arg)
  330. except BatchFileExecutionError, e:
  331. debug('vc.py:msvc_find_valid_batch_script() use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e))
  332. vc_script=None
  333. if not vc_script and sdk_script:
  334. debug('vc.py:msvc_find_valid_batch_script() use_script 4: trying sdk script: %s'%(sdk_script))
  335. try:
  336. d = script_env(sdk_script,args=[])
  337. except BatchFileExecutionError,e:
  338. debug('vc.py:msvc_find_valid_batch_script() use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e))
  339. continue
  340. elif not vc_script and not sdk_script:
  341. debug('vc.py:msvc_find_valid_batch_script() use_script 6: Neither VC script nor SDK script found')
  342. continue
  343. # If we cannot find a viable installed compiler, reset the TARGET_ARCH
  344. # To it's initial value
  345. if not d:
  346. env['TARGET_ARCH']=req_target_platform
  347. return d
  348. def msvc_setup_env(env):
  349. debug('msvc_setup_env()')
  350. version = get_default_version(env)
  351. if version is None:
  352. warn_msg = "No version of Visual Studio compiler found - C/C++ " \
  353. "compilers most likely not set correctly"
  354. SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
  355. return None
  356. debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version))
  357. # XXX: we set-up both MSVS version for backward
  358. # compatibility with the msvs tool
  359. env['MSVC_VERSION'] = version
  360. env['MSVS_VERSION'] = version
  361. env['MSVS'] = {}
  362. use_script = env.get('MSVC_USE_SCRIPT', True)
  363. if SCons.Util.is_String(use_script):
  364. debug('vc.py:msvc_setup_env() use_script 1 %s\n' % repr(use_script))
  365. d = script_env(use_script)
  366. elif use_script:
  367. d = msvc_find_valid_batch_script(env,version)
  368. debug('vc.py:msvc_setup_env() use_script 2 %s\n' % d)
  369. if not d:
  370. return d
  371. else:
  372. debug('MSVC_USE_SCRIPT set to False')
  373. warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \
  374. "set correctly."
  375. SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg)
  376. return None
  377. for k, v in d.items():
  378. debug('vc.py:msvc_setup_env() env:%s -> %s'%(k,v))
  379. env.PrependENVPath(k, v, delete_existing=True)
  380. def msvc_exists(version=None):
  381. vcs = cached_get_installed_vcs()
  382. if version is None:
  383. return len(vcs) > 0
  384. return version in vcs