PageRenderTime 63ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/distutils/msvc9compiler.py

https://bitbucket.org/SeanTater/pypy-bugfix-st
Python | 802 lines | 721 code | 31 blank | 50 comment | 46 complexity | 5aa05c9e839c30e8e7ca7c075c5b28b2 MD5 | raw file
  1. """distutils.msvc9compiler
  2. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  3. for the Microsoft Visual Studio 2008.
  4. The module is compatible with VS 2005 and VS 2008. You can find legacy support
  5. for older versions of VS in distutils.msvccompiler.
  6. """
  7. # Written by Perry Stoll
  8. # hacked by Robin Becker and Thomas Heller to do a better job of
  9. # finding DevStudio (through the registry)
  10. # ported to VS2005 and VS 2008 by Christian Heimes
  11. __revision__ = "$Id$"
  12. import os
  13. import subprocess
  14. import sys
  15. import re
  16. from distutils.errors import (DistutilsExecError, DistutilsPlatformError,
  17. CompileError, LibError, LinkError)
  18. from distutils.ccompiler import CCompiler, gen_lib_options
  19. from distutils import log
  20. from distutils.util import get_platform
  21. import _winreg
  22. RegOpenKeyEx = _winreg.OpenKeyEx
  23. RegEnumKey = _winreg.EnumKey
  24. RegEnumValue = _winreg.EnumValue
  25. RegError = _winreg.error
  26. HKEYS = (_winreg.HKEY_USERS,
  27. _winreg.HKEY_CURRENT_USER,
  28. _winreg.HKEY_LOCAL_MACHINE,
  29. _winreg.HKEY_CLASSES_ROOT)
  30. NATIVE_WIN64 = (sys.platform == 'win32' and sys.maxsize > 2**32)
  31. if NATIVE_WIN64:
  32. # Visual C++ is a 32-bit application, so we need to look in
  33. # the corresponding registry branch, if we're running a
  34. # 64-bit Python on Win64
  35. VS_BASE = r"Software\Wow6432Node\Microsoft\VisualStudio\%0.1f"
  36. VSEXPRESS_BASE = r"Software\Wow6432Node\Microsoft\VCExpress\%0.1f"
  37. WINSDK_BASE = r"Software\Wow6432Node\Microsoft\Microsoft SDKs\Windows"
  38. NET_BASE = r"Software\Wow6432Node\Microsoft\.NETFramework"
  39. else:
  40. VS_BASE = r"Software\Microsoft\VisualStudio\%0.1f"
  41. VSEXPRESS_BASE = r"Software\Microsoft\VCExpress\%0.1f"
  42. WINSDK_BASE = r"Software\Microsoft\Microsoft SDKs\Windows"
  43. NET_BASE = r"Software\Microsoft\.NETFramework"
  44. # A map keyed by get_platform() return values to values accepted by
  45. # 'vcvarsall.bat'. Note a cross-compile may combine these (eg, 'x86_amd64' is
  46. # the param to cross-compile on x86 targetting amd64.)
  47. PLAT_TO_VCVARS = {
  48. 'win32' : 'x86',
  49. 'win-amd64' : 'amd64',
  50. 'win-ia64' : 'ia64',
  51. }
  52. class Reg:
  53. """Helper class to read values from the registry
  54. """
  55. def get_value(cls, path, key):
  56. for base in HKEYS:
  57. d = cls.read_values(base, path)
  58. if d and key in d:
  59. return d[key]
  60. raise KeyError(key)
  61. get_value = classmethod(get_value)
  62. def read_keys(cls, base, key):
  63. """Return list of registry keys."""
  64. try:
  65. handle = RegOpenKeyEx(base, key)
  66. except RegError:
  67. return None
  68. L = []
  69. i = 0
  70. while True:
  71. try:
  72. k = RegEnumKey(handle, i)
  73. except RegError:
  74. break
  75. L.append(k)
  76. i += 1
  77. return L
  78. read_keys = classmethod(read_keys)
  79. def read_values(cls, base, key):
  80. """Return dict of registry keys and values.
  81. All names are converted to lowercase.
  82. """
  83. try:
  84. handle = RegOpenKeyEx(base, key)
  85. except RegError:
  86. return None
  87. d = {}
  88. i = 0
  89. while True:
  90. try:
  91. name, value, type = RegEnumValue(handle, i)
  92. except RegError:
  93. break
  94. name = name.lower()
  95. d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)
  96. i += 1
  97. return d
  98. read_values = classmethod(read_values)
  99. def convert_mbcs(s):
  100. dec = getattr(s, "decode", None)
  101. if dec is not None:
  102. try:
  103. s = dec("mbcs")
  104. except UnicodeError:
  105. pass
  106. return s
  107. convert_mbcs = staticmethod(convert_mbcs)
  108. class MacroExpander:
  109. def __init__(self, version):
  110. self.macros = {}
  111. self.vsbase = VS_BASE % version
  112. self.load_macros(version)
  113. def set_macro(self, macro, path, key):
  114. self.macros["$(%s)" % macro] = Reg.get_value(path, key)
  115. def load_macros(self, version):
  116. self.set_macro("VCInstallDir", self.vsbase + r"\Setup\VC", "productdir")
  117. self.set_macro("VSInstallDir", self.vsbase + r"\Setup\VS", "productdir")
  118. self.set_macro("FrameworkDir", NET_BASE, "installroot")
  119. try:
  120. if version >= 8.0:
  121. self.set_macro("FrameworkSDKDir", NET_BASE,
  122. "sdkinstallrootv2.0")
  123. else:
  124. raise KeyError("sdkinstallrootv2.0")
  125. except KeyError:
  126. raise DistutilsPlatformError(
  127. """Python was built with Visual Studio 2008;
  128. extensions must be built with a compiler than can generate compatible binaries.
  129. Visual Studio 2008 was not found on this system. If you have Cygwin installed,
  130. you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")
  131. if version >= 9.0:
  132. self.set_macro("FrameworkVersion", self.vsbase, "clr version")
  133. self.set_macro("WindowsSdkDir", WINSDK_BASE, "currentinstallfolder")
  134. else:
  135. p = r"Software\Microsoft\NET Framework Setup\Product"
  136. for base in HKEYS:
  137. try:
  138. h = RegOpenKeyEx(base, p)
  139. except RegError:
  140. continue
  141. key = RegEnumKey(h, 0)
  142. d = Reg.get_value(base, r"%s\%s" % (p, key))
  143. self.macros["$(FrameworkVersion)"] = d["version"]
  144. def sub(self, s):
  145. for k, v in self.macros.items():
  146. s = s.replace(k, v)
  147. return s
  148. def get_build_version():
  149. """Return the version of MSVC that was used to build Python.
  150. For Python 2.3 and up, the version number is included in
  151. sys.version. For earlier versions, assume the compiler is MSVC 6.
  152. """
  153. prefix = "MSC v."
  154. i = sys.version.find(prefix)
  155. if i == -1:
  156. return 6
  157. i = i + len(prefix)
  158. s, rest = sys.version[i:].split(" ", 1)
  159. majorVersion = int(s[:-2]) - 6
  160. minorVersion = int(s[2:3]) / 10.0
  161. # I don't think paths are affected by minor version in version 6
  162. if majorVersion == 6:
  163. minorVersion = 0
  164. if majorVersion >= 6:
  165. return majorVersion + minorVersion
  166. # else we don't know what version of the compiler this is
  167. return None
  168. def normalize_and_reduce_paths(paths):
  169. """Return a list of normalized paths with duplicates removed.
  170. The current order of paths is maintained.
  171. """
  172. # Paths are normalized so things like: /a and /a/ aren't both preserved.
  173. reduced_paths = []
  174. for p in paths:
  175. np = os.path.normpath(p)
  176. # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.
  177. if np not in reduced_paths:
  178. reduced_paths.append(np)
  179. return reduced_paths
  180. def removeDuplicates(variable):
  181. """Remove duplicate values of an environment variable.
  182. """
  183. oldList = variable.split(os.pathsep)
  184. newList = []
  185. for i in oldList:
  186. if i not in newList:
  187. newList.append(i)
  188. newVariable = os.pathsep.join(newList)
  189. return newVariable
  190. def find_vcvarsall(version):
  191. """Find the vcvarsall.bat file
  192. At first it tries to find the productdir of VS 2008 in the registry. If
  193. that fails it falls back to the VS90COMNTOOLS env var.
  194. """
  195. vsbase = VS_BASE % version
  196. try:
  197. productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
  198. "productdir")
  199. except KeyError:
  200. productdir = None
  201. # trying Express edition
  202. if productdir is None:
  203. vsbase = VSEXPRESS_BASE % version
  204. try:
  205. productdir = Reg.get_value(r"%s\Setup\VC" % vsbase,
  206. "productdir")
  207. except KeyError:
  208. productdir = None
  209. log.debug("Unable to find productdir in registry")
  210. if not productdir or not os.path.isdir(productdir):
  211. toolskey = "VS%0.f0COMNTOOLS" % version
  212. toolsdir = os.environ.get(toolskey, None)
  213. if toolsdir and os.path.isdir(toolsdir):
  214. productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC")
  215. productdir = os.path.abspath(productdir)
  216. if not os.path.isdir(productdir):
  217. log.debug("%s is not a valid directory" % productdir)
  218. return None
  219. else:
  220. log.debug("Env var %s is not set or invalid" % toolskey)
  221. if not productdir:
  222. log.debug("No productdir found")
  223. return None
  224. vcvarsall = os.path.join(productdir, "vcvarsall.bat")
  225. if os.path.isfile(vcvarsall):
  226. return vcvarsall
  227. log.debug("Unable to find vcvarsall.bat")
  228. return None
  229. def query_vcvarsall(version, arch="x86"):
  230. """Launch vcvarsall.bat and read the settings from its environment
  231. """
  232. vcvarsall = find_vcvarsall(version)
  233. interesting = set(("include", "lib", "libpath", "path"))
  234. result = {}
  235. if vcvarsall is None:
  236. raise DistutilsPlatformError("Unable to find vcvarsall.bat")
  237. log.debug("Calling 'vcvarsall.bat %s' (version=%s)", arch, version)
  238. popen = subprocess.Popen('"%s" %s & set' % (vcvarsall, arch),
  239. stdout=subprocess.PIPE,
  240. stderr=subprocess.PIPE)
  241. try:
  242. stdout, stderr = popen.communicate()
  243. if popen.wait() != 0:
  244. raise DistutilsPlatformError(stderr.decode("mbcs"))
  245. stdout = stdout.decode("mbcs")
  246. for line in stdout.split("\n"):
  247. line = Reg.convert_mbcs(line)
  248. if '=' not in line:
  249. continue
  250. line = line.strip()
  251. key, value = line.split('=', 1)
  252. key = key.lower()
  253. if key in interesting:
  254. if value.endswith(os.pathsep):
  255. value = value[:-1]
  256. result[key] = removeDuplicates(value)
  257. finally:
  258. popen.stdout.close()
  259. popen.stderr.close()
  260. if len(result) != len(interesting):
  261. raise ValueError(str(list(result.keys())))
  262. return result
  263. # More globals
  264. VERSION = get_build_version()
  265. if VERSION < 8.0:
  266. raise DistutilsPlatformError("VC %0.1f is not supported by this module" % VERSION)
  267. # MACROS = MacroExpander(VERSION)
  268. class MSVCCompiler(CCompiler) :
  269. """Concrete class that implements an interface to Microsoft Visual C++,
  270. as defined by the CCompiler abstract class."""
  271. compiler_type = 'msvc'
  272. # Just set this so CCompiler's constructor doesn't barf. We currently
  273. # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  274. # as it really isn't necessary for this sort of single-compiler class.
  275. # Would be nice to have a consistent interface with UnixCCompiler,
  276. # though, so it's worth thinking about.
  277. executables = {}
  278. # Private class data (need to distinguish C from C++ source for compiler)
  279. _c_extensions = ['.c']
  280. _cpp_extensions = ['.cc', '.cpp', '.cxx']
  281. _rc_extensions = ['.rc']
  282. _mc_extensions = ['.mc']
  283. # Needed for the filename generation methods provided by the
  284. # base class, CCompiler.
  285. src_extensions = (_c_extensions + _cpp_extensions +
  286. _rc_extensions + _mc_extensions)
  287. res_extension = '.res'
  288. obj_extension = '.obj'
  289. static_lib_extension = '.lib'
  290. shared_lib_extension = '.dll'
  291. static_lib_format = shared_lib_format = '%s%s'
  292. exe_extension = '.exe'
  293. def __init__(self, verbose=0, dry_run=0, force=0):
  294. CCompiler.__init__ (self, verbose, dry_run, force)
  295. self.__version = VERSION
  296. self.__root = r"Software\Microsoft\VisualStudio"
  297. # self.__macros = MACROS
  298. self.__paths = []
  299. # target platform (.plat_name is consistent with 'bdist')
  300. self.plat_name = None
  301. self.__arch = None # deprecated name
  302. self.initialized = False
  303. def initialize(self, plat_name=None):
  304. # multi-init means we would need to check platform same each time...
  305. assert not self.initialized, "don't init multiple times"
  306. if plat_name is None:
  307. plat_name = get_platform()
  308. # sanity check for platforms to prevent obscure errors later.
  309. ok_plats = 'win32', 'win-amd64', 'win-ia64'
  310. if plat_name not in ok_plats:
  311. raise DistutilsPlatformError("--plat-name must be one of %s" %
  312. (ok_plats,))
  313. if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):
  314. # Assume that the SDK set up everything alright; don't try to be
  315. # smarter
  316. self.cc = "cl.exe"
  317. self.linker = "link.exe"
  318. self.lib = "lib.exe"
  319. self.rc = "rc.exe"
  320. self.mc = "mc.exe"
  321. else:
  322. # On x86, 'vcvars32.bat amd64' creates an env that doesn't work;
  323. # to cross compile, you use 'x86_amd64'.
  324. # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross
  325. # compile use 'x86' (ie, it runs the x86 compiler directly)
  326. # No idea how itanium handles this, if at all.
  327. if plat_name == get_platform() or plat_name == 'win32':
  328. # native build or cross-compile to win32
  329. plat_spec = PLAT_TO_VCVARS[plat_name]
  330. else:
  331. # cross compile from win32 -> some 64bit
  332. plat_spec = PLAT_TO_VCVARS[get_platform()] + '_' + \
  333. PLAT_TO_VCVARS[plat_name]
  334. vc_env = query_vcvarsall(VERSION, plat_spec)
  335. # take care to only use strings in the environment.
  336. self.__paths = vc_env['path'].encode('mbcs').split(os.pathsep)
  337. os.environ['lib'] = vc_env['lib'].encode('mbcs')
  338. os.environ['include'] = vc_env['include'].encode('mbcs')
  339. if len(self.__paths) == 0:
  340. raise DistutilsPlatformError("Python was built with %s, "
  341. "and extensions need to be built with the same "
  342. "version of the compiler, but it isn't installed."
  343. % self.__product)
  344. self.cc = self.find_exe("cl.exe")
  345. self.linker = self.find_exe("link.exe")
  346. self.lib = self.find_exe("lib.exe")
  347. self.rc = self.find_exe("rc.exe") # resource compiler
  348. self.mc = self.find_exe("mc.exe") # message compiler
  349. #self.set_path_env_var('lib')
  350. #self.set_path_env_var('include')
  351. # extend the MSVC path with the current path
  352. try:
  353. for p in os.environ['path'].split(';'):
  354. self.__paths.append(p)
  355. except KeyError:
  356. pass
  357. self.__paths = normalize_and_reduce_paths(self.__paths)
  358. os.environ['path'] = ";".join(self.__paths)
  359. self.preprocess_options = None
  360. if self.__arch == "x86":
  361. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3',
  362. '/DNDEBUG']
  363. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3',
  364. '/Z7', '/D_DEBUG']
  365. else:
  366. # Win64
  367. self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' ,
  368. '/DNDEBUG']
  369. self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
  370. '/Z7', '/D_DEBUG']
  371. self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
  372. if self.__version >= 7:
  373. self.ldflags_shared_debug = [
  374. '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG', '/pdb:None'
  375. ]
  376. self.ldflags_static = [ '/nologo']
  377. self.initialized = True
  378. # -- Worker methods ------------------------------------------------
  379. def object_filenames(self,
  380. source_filenames,
  381. strip_dir=0,
  382. output_dir=''):
  383. # Copied from ccompiler.py, extended to return .res as 'object'-file
  384. # for .rc input file
  385. if output_dir is None: output_dir = ''
  386. obj_names = []
  387. for src_name in source_filenames:
  388. (base, ext) = os.path.splitext (src_name)
  389. base = os.path.splitdrive(base)[1] # Chop off the drive
  390. base = base[os.path.isabs(base):] # If abs, chop off leading /
  391. if ext not in self.src_extensions:
  392. # Better to raise an exception instead of silently continuing
  393. # and later complain about sources and targets having
  394. # different lengths
  395. raise CompileError ("Don't know how to compile %s" % src_name)
  396. if strip_dir:
  397. base = os.path.basename (base)
  398. if ext in self._rc_extensions:
  399. obj_names.append (os.path.join (output_dir,
  400. base + self.res_extension))
  401. elif ext in self._mc_extensions:
  402. obj_names.append (os.path.join (output_dir,
  403. base + self.res_extension))
  404. else:
  405. obj_names.append (os.path.join (output_dir,
  406. base + self.obj_extension))
  407. return obj_names
  408. def compile(self, sources,
  409. output_dir=None, macros=None, include_dirs=None, debug=0,
  410. extra_preargs=None, extra_postargs=None, depends=None):
  411. if not self.initialized:
  412. self.initialize()
  413. compile_info = self._setup_compile(output_dir, macros, include_dirs,
  414. sources, depends, extra_postargs)
  415. macros, objects, extra_postargs, pp_opts, build = compile_info
  416. compile_opts = extra_preargs or []
  417. compile_opts.append ('/c')
  418. if debug:
  419. compile_opts.extend(self.compile_options_debug)
  420. else:
  421. compile_opts.extend(self.compile_options)
  422. for obj in objects:
  423. try:
  424. src, ext = build[obj]
  425. except KeyError:
  426. continue
  427. if debug:
  428. # pass the full pathname to MSVC in debug mode,
  429. # this allows the debugger to find the source file
  430. # without asking the user to browse for it
  431. src = os.path.abspath(src)
  432. if ext in self._c_extensions:
  433. input_opt = "/Tc" + src
  434. elif ext in self._cpp_extensions:
  435. input_opt = "/Tp" + src
  436. elif ext in self._rc_extensions:
  437. # compile .RC to .RES file
  438. input_opt = src
  439. output_opt = "/fo" + obj
  440. try:
  441. self.spawn([self.rc] + pp_opts +
  442. [output_opt] + [input_opt])
  443. except DistutilsExecError, msg:
  444. raise CompileError(msg)
  445. continue
  446. elif ext in self._mc_extensions:
  447. # Compile .MC to .RC file to .RES file.
  448. # * '-h dir' specifies the directory for the
  449. # generated include file
  450. # * '-r dir' specifies the target directory of the
  451. # generated RC file and the binary message resource
  452. # it includes
  453. #
  454. # For now (since there are no options to change this),
  455. # we use the source-directory for the include file and
  456. # the build directory for the RC file and message
  457. # resources. This works at least for win32all.
  458. h_dir = os.path.dirname(src)
  459. rc_dir = os.path.dirname(obj)
  460. try:
  461. # first compile .MC to .RC and .H file
  462. self.spawn([self.mc] +
  463. ['-h', h_dir, '-r', rc_dir] + [src])
  464. base, _ = os.path.splitext (os.path.basename (src))
  465. rc_file = os.path.join (rc_dir, base + '.rc')
  466. # then compile .RC to .RES file
  467. self.spawn([self.rc] +
  468. ["/fo" + obj] + [rc_file])
  469. except DistutilsExecError, msg:
  470. raise CompileError(msg)
  471. continue
  472. else:
  473. # how to handle this file?
  474. raise CompileError("Don't know how to compile %s to %s"
  475. % (src, obj))
  476. output_opt = "/Fo" + obj
  477. try:
  478. self.spawn([self.cc] + compile_opts + pp_opts +
  479. [input_opt, output_opt] +
  480. extra_postargs)
  481. except DistutilsExecError, msg:
  482. raise CompileError(msg)
  483. return objects
  484. def create_static_lib(self,
  485. objects,
  486. output_libname,
  487. output_dir=None,
  488. debug=0,
  489. target_lang=None):
  490. if not self.initialized:
  491. self.initialize()
  492. (objects, output_dir) = self._fix_object_args(objects, output_dir)
  493. output_filename = self.library_filename(output_libname,
  494. output_dir=output_dir)
  495. if self._need_link(objects, output_filename):
  496. lib_args = objects + ['/OUT:' + output_filename]
  497. if debug:
  498. pass # XXX what goes here?
  499. try:
  500. self.spawn([self.lib] + lib_args)
  501. except DistutilsExecError, msg:
  502. raise LibError(msg)
  503. else:
  504. log.debug("skipping %s (up-to-date)", output_filename)
  505. def link(self,
  506. target_desc,
  507. objects,
  508. output_filename,
  509. output_dir=None,
  510. libraries=None,
  511. library_dirs=None,
  512. runtime_library_dirs=None,
  513. export_symbols=None,
  514. debug=0,
  515. extra_preargs=None,
  516. extra_postargs=None,
  517. build_temp=None,
  518. target_lang=None):
  519. if not self.initialized:
  520. self.initialize()
  521. (objects, output_dir) = self._fix_object_args(objects, output_dir)
  522. fixed_args = self._fix_lib_args(libraries, library_dirs,
  523. runtime_library_dirs)
  524. (libraries, library_dirs, runtime_library_dirs) = fixed_args
  525. if runtime_library_dirs:
  526. self.warn ("I don't know what to do with 'runtime_library_dirs': "
  527. + str (runtime_library_dirs))
  528. lib_opts = gen_lib_options(self,
  529. library_dirs, runtime_library_dirs,
  530. libraries)
  531. if output_dir is not None:
  532. output_filename = os.path.join(output_dir, output_filename)
  533. if self._need_link(objects, output_filename):
  534. if target_desc == CCompiler.EXECUTABLE:
  535. if debug:
  536. ldflags = self.ldflags_shared_debug[1:]
  537. else:
  538. ldflags = self.ldflags_shared[1:]
  539. else:
  540. if debug:
  541. ldflags = self.ldflags_shared_debug
  542. else:
  543. ldflags = self.ldflags_shared
  544. export_opts = []
  545. for sym in (export_symbols or []):
  546. export_opts.append("/EXPORT:" + sym)
  547. ld_args = (ldflags + lib_opts + export_opts +
  548. objects + ['/OUT:' + output_filename])
  549. # The MSVC linker generates .lib and .exp files, which cannot be
  550. # suppressed by any linker switches. The .lib files may even be
  551. # needed! Make sure they are generated in the temporary build
  552. # directory. Since they have different names for debug and release
  553. # builds, they can go into the same directory.
  554. build_temp = os.path.dirname(objects[0])
  555. if export_symbols is not None:
  556. (dll_name, dll_ext) = os.path.splitext(
  557. os.path.basename(output_filename))
  558. implib_file = os.path.join(
  559. build_temp,
  560. self.library_filename(dll_name))
  561. ld_args.append ('/IMPLIB:' + implib_file)
  562. self.manifest_setup_ldargs(output_filename, build_temp, ld_args)
  563. if extra_preargs:
  564. ld_args[:0] = extra_preargs
  565. if extra_postargs:
  566. ld_args.extend(extra_postargs)
  567. self.mkpath(os.path.dirname(output_filename))
  568. try:
  569. self.spawn([self.linker] + ld_args)
  570. except DistutilsExecError, msg:
  571. raise LinkError(msg)
  572. # embed the manifest
  573. # XXX - this is somewhat fragile - if mt.exe fails, distutils
  574. # will still consider the DLL up-to-date, but it will not have a
  575. # manifest. Maybe we should link to a temp file? OTOH, that
  576. # implies a build environment error that shouldn't go undetected.
  577. mfinfo = self.manifest_get_embed_info(target_desc, ld_args)
  578. if mfinfo is not None:
  579. mffilename, mfid = mfinfo
  580. out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
  581. try:
  582. self.spawn(['mt.exe', '-nologo', '-manifest',
  583. mffilename, out_arg])
  584. except DistutilsExecError, msg:
  585. raise LinkError(msg)
  586. else:
  587. log.debug("skipping %s (up-to-date)", output_filename)
  588. def manifest_setup_ldargs(self, output_filename, build_temp, ld_args):
  589. # If we need a manifest at all, an embedded manifest is recommended.
  590. # See MSDN article titled
  591. # "How to: Embed a Manifest Inside a C/C++ Application"
  592. # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
  593. # Ask the linker to generate the manifest in the temp dir, so
  594. # we can check it, and possibly embed it, later.
  595. temp_manifest = os.path.join(
  596. build_temp,
  597. os.path.basename(output_filename) + ".manifest")
  598. ld_args.append('/MANIFEST')
  599. ld_args.append('/MANIFESTFILE:' + temp_manifest)
  600. def manifest_get_embed_info(self, target_desc, ld_args):
  601. # If a manifest should be embedded, return a tuple of
  602. # (manifest_filename, resource_id). Returns None if no manifest
  603. # should be embedded. See http://bugs.python.org/issue7833 for why
  604. # we want to avoid any manifest for extension modules if we can)
  605. for arg in ld_args:
  606. if arg.startswith("/MANIFESTFILE:"):
  607. temp_manifest = arg.split(":", 1)[1]
  608. break
  609. else:
  610. # no /MANIFESTFILE so nothing to do.
  611. return None
  612. if target_desc == CCompiler.EXECUTABLE:
  613. # by default, executables always get the manifest with the
  614. # CRT referenced.
  615. mfid = 1
  616. else:
  617. # Extension modules try and avoid any manifest if possible.
  618. mfid = 2
  619. temp_manifest = self._remove_visual_c_ref(temp_manifest)
  620. if temp_manifest is None:
  621. return None
  622. return temp_manifest, mfid
  623. def _remove_visual_c_ref(self, manifest_file):
  624. try:
  625. # Remove references to the Visual C runtime, so they will
  626. # fall through to the Visual C dependency of Python.exe.
  627. # This way, when installed for a restricted user (e.g.
  628. # runtimes are not in WinSxS folder, but in Python's own
  629. # folder), the runtimes do not need to be in every folder
  630. # with .pyd's.
  631. # Returns either the filename of the modified manifest or
  632. # None if no manifest should be embedded.
  633. manifest_f = open(manifest_file)
  634. try:
  635. manifest_buf = manifest_f.read()
  636. finally:
  637. manifest_f.close()
  638. pattern = re.compile(
  639. r"""<assemblyIdentity.*?name=("|')Microsoft\."""\
  640. r"""VC\d{2}\.CRT("|').*?(/>|</assemblyIdentity>)""",
  641. re.DOTALL)
  642. manifest_buf = re.sub(pattern, "", manifest_buf)
  643. pattern = "<dependentAssembly>\s*</dependentAssembly>"
  644. manifest_buf = re.sub(pattern, "", manifest_buf)
  645. # Now see if any other assemblies are referenced - if not, we
  646. # don't want a manifest embedded.
  647. pattern = re.compile(
  648. r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')"""
  649. r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL)
  650. if re.search(pattern, manifest_buf) is None:
  651. return None
  652. manifest_f = open(manifest_file, 'w')
  653. try:
  654. manifest_f.write(manifest_buf)
  655. return manifest_file
  656. finally:
  657. manifest_f.close()
  658. except IOError:
  659. pass
  660. # -- Miscellaneous methods -----------------------------------------
  661. # These are all used by the 'gen_lib_options() function, in
  662. # ccompiler.py.
  663. def library_dir_option(self, dir):
  664. return "/LIBPATH:" + dir
  665. def runtime_library_dir_option(self, dir):
  666. raise DistutilsPlatformError(
  667. "don't know how to set runtime library search path for MSVC++")
  668. def library_option(self, lib):
  669. return self.library_filename(lib)
  670. def find_library_file(self, dirs, lib, debug=0):
  671. # Prefer a debugging library if found (and requested), but deal
  672. # with it if we don't have one.
  673. if debug:
  674. try_names = [lib + "_d", lib]
  675. else:
  676. try_names = [lib]
  677. for dir in dirs:
  678. for name in try_names:
  679. libfile = os.path.join(dir, self.library_filename (name))
  680. if os.path.exists(libfile):
  681. return libfile
  682. else:
  683. # Oops, didn't find it in *any* of 'dirs'
  684. return None
  685. # Helper methods for using the MSVC registry settings
  686. def find_exe(self, exe):
  687. """Return path to an MSVC executable program.
  688. Tries to find the program in several places: first, one of the
  689. MSVC program search paths from the registry; next, the directories
  690. in the PATH environment variable. If any of those work, return an
  691. absolute path that is known to exist. If none of them work, just
  692. return the original program name, 'exe'.
  693. """
  694. for p in self.__paths:
  695. fn = os.path.join(os.path.abspath(p), exe)
  696. if os.path.isfile(fn):
  697. return fn
  698. # didn't find it; try existing path
  699. for p in os.environ['Path'].split(';'):
  700. fn = os.path.join(os.path.abspath(p),exe)
  701. if os.path.isfile(fn):
  702. return fn
  703. return exe