msvc9compiler.py 29 KB

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