_msvccompiler.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. """distutils._msvccompiler
  2. Contains MSVCCompiler, an implementation of the abstract CCompiler class
  3. for Microsoft Visual Studio 2015.
  4. The module is compatible with VS 2015 and later. You can find legacy support
  5. for older versions in distutils.msvc9compiler and 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 VS 2005 and VS 2008 by Christian Heimes
  11. # ported to VS 2015 by Steve Dower
  12. import os
  13. import subprocess
  14. import contextlib
  15. import warnings
  16. import unittest.mock as mock
  17. with contextlib.suppress(ImportError):
  18. import winreg
  19. from distutils.errors import (
  20. DistutilsExecError,
  21. DistutilsPlatformError,
  22. CompileError,
  23. LibError,
  24. LinkError,
  25. )
  26. from distutils.ccompiler import CCompiler, gen_lib_options
  27. from distutils import log
  28. from distutils.util import get_platform
  29. from itertools import count
  30. def _find_vc2015():
  31. try:
  32. key = winreg.OpenKeyEx(
  33. winreg.HKEY_LOCAL_MACHINE,
  34. r"Software\Microsoft\VisualStudio\SxS\VC7",
  35. access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,
  36. )
  37. except OSError:
  38. log.debug("Visual C++ is not registered")
  39. return None, None
  40. best_version = 0
  41. best_dir = None
  42. with key:
  43. for i in count():
  44. try:
  45. v, vc_dir, vt = winreg.EnumValue(key, i)
  46. except OSError:
  47. break
  48. if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):
  49. try:
  50. version = int(float(v))
  51. except (ValueError, TypeError):
  52. continue
  53. if version >= 14 and version > best_version:
  54. best_version, best_dir = version, vc_dir
  55. return best_version, best_dir
  56. def _find_vc2017():
  57. """Returns "15, path" based on the result of invoking vswhere.exe
  58. If no install is found, returns "None, None"
  59. The version is returned to avoid unnecessarily changing the function
  60. result. It may be ignored when the path is not None.
  61. If vswhere.exe is not available, by definition, VS 2017 is not
  62. installed.
  63. """
  64. root = os.environ.get("ProgramFiles(x86)") or os.environ.get("ProgramFiles")
  65. if not root:
  66. return None, None
  67. try:
  68. path = subprocess.check_output(
  69. [
  70. os.path.join(
  71. root, "Microsoft Visual Studio", "Installer", "vswhere.exe"
  72. ),
  73. "-latest",
  74. "-prerelease",
  75. "-requires",
  76. "Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
  77. "-property",
  78. "installationPath",
  79. "-products",
  80. "*",
  81. ],
  82. encoding="mbcs",
  83. errors="strict",
  84. ).strip()
  85. except (subprocess.CalledProcessError, OSError, UnicodeDecodeError):
  86. return None, None
  87. path = os.path.join(path, "VC", "Auxiliary", "Build")
  88. if os.path.isdir(path):
  89. return 15, path
  90. return None, None
  91. PLAT_SPEC_TO_RUNTIME = {
  92. 'x86': 'x86',
  93. 'x86_amd64': 'x64',
  94. 'x86_arm': 'arm',
  95. 'x86_arm64': 'arm64',
  96. }
  97. def _find_vcvarsall(plat_spec):
  98. # bpo-38597: Removed vcruntime return value
  99. _, best_dir = _find_vc2017()
  100. if not best_dir:
  101. best_version, best_dir = _find_vc2015()
  102. if not best_dir:
  103. log.debug("No suitable Visual C++ version found")
  104. return None, None
  105. vcvarsall = os.path.join(best_dir, "vcvarsall.bat")
  106. if not os.path.isfile(vcvarsall):
  107. log.debug("%s cannot be found", vcvarsall)
  108. return None, None
  109. return vcvarsall, None
  110. def _get_vc_env(plat_spec):
  111. if os.getenv("DISTUTILS_USE_SDK"):
  112. return {key.lower(): value for key, value in os.environ.items()}
  113. vcvarsall, _ = _find_vcvarsall(plat_spec)
  114. if not vcvarsall:
  115. raise DistutilsPlatformError("Unable to find vcvarsall.bat")
  116. try:
  117. out = subprocess.check_output(
  118. f'cmd /u /c "{vcvarsall}" {plat_spec} && set',
  119. stderr=subprocess.STDOUT,
  120. ).decode('utf-16le', errors='replace')
  121. except subprocess.CalledProcessError as exc:
  122. log.error(exc.output)
  123. raise DistutilsPlatformError(f"Error executing {exc.cmd}")
  124. env = {
  125. key.lower(): value
  126. for key, _, value in (line.partition('=') for line in out.splitlines())
  127. if key and value
  128. }
  129. return env
  130. def _find_exe(exe, paths=None):
  131. """Return path to an MSVC executable program.
  132. Tries to find the program in several places: first, one of the
  133. MSVC program search paths from the registry; next, the directories
  134. in the PATH environment variable. If any of those work, return an
  135. absolute path that is known to exist. If none of them work, just
  136. return the original program name, 'exe'.
  137. """
  138. if not paths:
  139. paths = os.getenv('path').split(os.pathsep)
  140. for p in paths:
  141. fn = os.path.join(os.path.abspath(p), exe)
  142. if os.path.isfile(fn):
  143. return fn
  144. return exe
  145. # A map keyed by get_platform() return values to values accepted by
  146. # 'vcvarsall.bat'. Always cross-compile from x86 to work with the
  147. # lighter-weight MSVC installs that do not include native 64-bit tools.
  148. PLAT_TO_VCVARS = {
  149. 'win32': 'x86',
  150. 'win-amd64': 'x86_amd64',
  151. 'win-arm32': 'x86_arm',
  152. 'win-arm64': 'x86_arm64',
  153. }
  154. class MSVCCompiler(CCompiler):
  155. """Concrete class that implements an interface to Microsoft Visual C++,
  156. as defined by the CCompiler abstract class."""
  157. compiler_type = 'msvc'
  158. # Just set this so CCompiler's constructor doesn't barf. We currently
  159. # don't use the 'set_executables()' bureaucracy provided by CCompiler,
  160. # as it really isn't necessary for this sort of single-compiler class.
  161. # Would be nice to have a consistent interface with UnixCCompiler,
  162. # though, so it's worth thinking about.
  163. executables = {}
  164. # Private class data (need to distinguish C from C++ source for compiler)
  165. _c_extensions = ['.c']
  166. _cpp_extensions = ['.cc', '.cpp', '.cxx']
  167. _rc_extensions = ['.rc']
  168. _mc_extensions = ['.mc']
  169. # Needed for the filename generation methods provided by the
  170. # base class, CCompiler.
  171. src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions
  172. res_extension = '.res'
  173. obj_extension = '.obj'
  174. static_lib_extension = '.lib'
  175. shared_lib_extension = '.dll'
  176. static_lib_format = shared_lib_format = '%s%s'
  177. exe_extension = '.exe'
  178. def __init__(self, verbose=0, dry_run=0, force=0):
  179. super().__init__(verbose, dry_run, force)
  180. # target platform (.plat_name is consistent with 'bdist')
  181. self.plat_name = None
  182. self.initialized = False
  183. @classmethod
  184. def _configure(cls, vc_env):
  185. """
  186. Set class-level include/lib dirs.
  187. """
  188. cls.include_dirs = cls._parse_path(vc_env.get('include', ''))
  189. cls.library_dirs = cls._parse_path(vc_env.get('lib', ''))
  190. @staticmethod
  191. def _parse_path(val):
  192. return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir]
  193. def initialize(self, plat_name=None):
  194. # multi-init means we would need to check platform same each time...
  195. assert not self.initialized, "don't init multiple times"
  196. if plat_name is None:
  197. plat_name = get_platform()
  198. # sanity check for platforms to prevent obscure errors later.
  199. if plat_name not in PLAT_TO_VCVARS:
  200. raise DistutilsPlatformError(
  201. f"--plat-name must be one of {tuple(PLAT_TO_VCVARS)}"
  202. )
  203. # Get the vcvarsall.bat spec for the requested platform.
  204. plat_spec = PLAT_TO_VCVARS[plat_name]
  205. vc_env = _get_vc_env(plat_spec)
  206. if not vc_env:
  207. raise DistutilsPlatformError(
  208. "Unable to find a compatible " "Visual Studio installation."
  209. )
  210. self._configure(vc_env)
  211. self._paths = vc_env.get('path', '')
  212. paths = self._paths.split(os.pathsep)
  213. self.cc = _find_exe("cl.exe", paths)
  214. self.linker = _find_exe("link.exe", paths)
  215. self.lib = _find_exe("lib.exe", paths)
  216. self.rc = _find_exe("rc.exe", paths) # resource compiler
  217. self.mc = _find_exe("mc.exe", paths) # message compiler
  218. self.mt = _find_exe("mt.exe", paths) # message compiler
  219. self.preprocess_options = None
  220. # bpo-38597: Always compile with dynamic linking
  221. # Future releases of Python 3.x will include all past
  222. # versions of vcruntime*.dll for compatibility.
  223. self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']
  224. self.compile_options_debug = [
  225. '/nologo',
  226. '/Od',
  227. '/MDd',
  228. '/Zi',
  229. '/W3',
  230. '/D_DEBUG',
  231. ]
  232. ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']
  233. ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']
  234. self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']
  235. self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']
  236. self.ldflags_shared = [
  237. *ldflags,
  238. '/DLL',
  239. '/MANIFEST:EMBED,ID=2',
  240. '/MANIFESTUAC:NO',
  241. ]
  242. self.ldflags_shared_debug = [
  243. *ldflags_debug,
  244. '/DLL',
  245. '/MANIFEST:EMBED,ID=2',
  246. '/MANIFESTUAC:NO',
  247. ]
  248. self.ldflags_static = [*ldflags]
  249. self.ldflags_static_debug = [*ldflags_debug]
  250. self._ldflags = {
  251. (CCompiler.EXECUTABLE, None): self.ldflags_exe,
  252. (CCompiler.EXECUTABLE, False): self.ldflags_exe,
  253. (CCompiler.EXECUTABLE, True): self.ldflags_exe_debug,
  254. (CCompiler.SHARED_OBJECT, None): self.ldflags_shared,
  255. (CCompiler.SHARED_OBJECT, False): self.ldflags_shared,
  256. (CCompiler.SHARED_OBJECT, True): self.ldflags_shared_debug,
  257. (CCompiler.SHARED_LIBRARY, None): self.ldflags_static,
  258. (CCompiler.SHARED_LIBRARY, False): self.ldflags_static,
  259. (CCompiler.SHARED_LIBRARY, True): self.ldflags_static_debug,
  260. }
  261. self.initialized = True
  262. # -- Worker methods ------------------------------------------------
  263. @property
  264. def out_extensions(self):
  265. return {
  266. **super().out_extensions,
  267. **{
  268. ext: self.res_extension
  269. for ext in self._rc_extensions + self._mc_extensions
  270. },
  271. }
  272. def compile( # noqa: C901
  273. self,
  274. sources,
  275. output_dir=None,
  276. macros=None,
  277. include_dirs=None,
  278. debug=0,
  279. extra_preargs=None,
  280. extra_postargs=None,
  281. depends=None,
  282. ):
  283. if not self.initialized:
  284. self.initialize()
  285. compile_info = self._setup_compile(
  286. output_dir, macros, include_dirs, sources, depends, extra_postargs
  287. )
  288. macros, objects, extra_postargs, pp_opts, build = compile_info
  289. compile_opts = extra_preargs or []
  290. compile_opts.append('/c')
  291. if debug:
  292. compile_opts.extend(self.compile_options_debug)
  293. else:
  294. compile_opts.extend(self.compile_options)
  295. add_cpp_opts = False
  296. for obj in objects:
  297. try:
  298. src, ext = build[obj]
  299. except KeyError:
  300. continue
  301. if debug:
  302. # pass the full pathname to MSVC in debug mode,
  303. # this allows the debugger to find the source file
  304. # without asking the user to browse for it
  305. src = os.path.abspath(src)
  306. if ext in self._c_extensions:
  307. input_opt = "/Tc" + src
  308. elif ext in self._cpp_extensions:
  309. input_opt = "/Tp" + src
  310. add_cpp_opts = True
  311. elif ext in self._rc_extensions:
  312. # compile .RC to .RES file
  313. input_opt = src
  314. output_opt = "/fo" + obj
  315. try:
  316. self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
  317. except DistutilsExecError as msg:
  318. raise CompileError(msg)
  319. continue
  320. elif ext in self._mc_extensions:
  321. # Compile .MC to .RC file to .RES file.
  322. # * '-h dir' specifies the directory for the
  323. # generated include file
  324. # * '-r dir' specifies the target directory of the
  325. # generated RC file and the binary message resource
  326. # it includes
  327. #
  328. # For now (since there are no options to change this),
  329. # we use the source-directory for the include file and
  330. # the build directory for the RC file and message
  331. # resources. This works at least for win32all.
  332. h_dir = os.path.dirname(src)
  333. rc_dir = os.path.dirname(obj)
  334. try:
  335. # first compile .MC to .RC and .H file
  336. self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
  337. base, _ = os.path.splitext(os.path.basename(src))
  338. rc_file = os.path.join(rc_dir, base + '.rc')
  339. # then compile .RC to .RES file
  340. self.spawn([self.rc, "/fo" + obj, rc_file])
  341. except DistutilsExecError as msg:
  342. raise CompileError(msg)
  343. continue
  344. else:
  345. # how to handle this file?
  346. raise CompileError(f"Don't know how to compile {src} to {obj}")
  347. args = [self.cc] + compile_opts + pp_opts
  348. if add_cpp_opts:
  349. args.append('/EHsc')
  350. args.append(input_opt)
  351. args.append("/Fo" + obj)
  352. args.extend(extra_postargs)
  353. try:
  354. self.spawn(args)
  355. except DistutilsExecError as msg:
  356. raise CompileError(msg)
  357. return objects
  358. def create_static_lib(
  359. self, objects, output_libname, output_dir=None, debug=0, target_lang=None
  360. ):
  361. if not self.initialized:
  362. self.initialize()
  363. objects, output_dir = self._fix_object_args(objects, output_dir)
  364. output_filename = self.library_filename(output_libname, output_dir=output_dir)
  365. if self._need_link(objects, output_filename):
  366. lib_args = objects + ['/OUT:' + output_filename]
  367. if debug:
  368. pass # XXX what goes here?
  369. try:
  370. log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
  371. self.spawn([self.lib] + lib_args)
  372. except DistutilsExecError as msg:
  373. raise LibError(msg)
  374. else:
  375. log.debug("skipping %s (up-to-date)", output_filename)
  376. def link(
  377. self,
  378. target_desc,
  379. objects,
  380. output_filename,
  381. output_dir=None,
  382. libraries=None,
  383. library_dirs=None,
  384. runtime_library_dirs=None,
  385. export_symbols=None,
  386. debug=0,
  387. extra_preargs=None,
  388. extra_postargs=None,
  389. build_temp=None,
  390. target_lang=None,
  391. ):
  392. if not self.initialized:
  393. self.initialize()
  394. objects, output_dir = self._fix_object_args(objects, output_dir)
  395. fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
  396. libraries, library_dirs, runtime_library_dirs = fixed_args
  397. if runtime_library_dirs:
  398. self.warn(
  399. "I don't know what to do with 'runtime_library_dirs': "
  400. + str(runtime_library_dirs)
  401. )
  402. lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
  403. if output_dir is not None:
  404. output_filename = os.path.join(output_dir, output_filename)
  405. if self._need_link(objects, output_filename):
  406. ldflags = self._ldflags[target_desc, debug]
  407. export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
  408. ld_args = (
  409. ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]
  410. )
  411. # The MSVC linker generates .lib and .exp files, which cannot be
  412. # suppressed by any linker switches. The .lib files may even be
  413. # needed! Make sure they are generated in the temporary build
  414. # directory. Since they have different names for debug and release
  415. # builds, they can go into the same directory.
  416. build_temp = os.path.dirname(objects[0])
  417. if export_symbols is not None:
  418. (dll_name, dll_ext) = os.path.splitext(
  419. os.path.basename(output_filename)
  420. )
  421. implib_file = os.path.join(build_temp, self.library_filename(dll_name))
  422. ld_args.append('/IMPLIB:' + implib_file)
  423. if extra_preargs:
  424. ld_args[:0] = extra_preargs
  425. if extra_postargs:
  426. ld_args.extend(extra_postargs)
  427. output_dir = os.path.dirname(os.path.abspath(output_filename))
  428. self.mkpath(output_dir)
  429. try:
  430. log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
  431. self.spawn([self.linker] + ld_args)
  432. except DistutilsExecError as msg:
  433. raise LinkError(msg)
  434. else:
  435. log.debug("skipping %s (up-to-date)", output_filename)
  436. def spawn(self, cmd):
  437. env = dict(os.environ, PATH=self._paths)
  438. with self._fallback_spawn(cmd, env) as fallback:
  439. return super().spawn(cmd, env=env)
  440. return fallback.value
  441. @contextlib.contextmanager
  442. def _fallback_spawn(self, cmd, env):
  443. """
  444. Discovered in pypa/distutils#15, some tools monkeypatch the compiler,
  445. so the 'env' kwarg causes a TypeError. Detect this condition and
  446. restore the legacy, unsafe behavior.
  447. """
  448. bag = type('Bag', (), {})()
  449. try:
  450. yield bag
  451. except TypeError as exc:
  452. if "unexpected keyword argument 'env'" not in str(exc):
  453. raise
  454. else:
  455. return
  456. warnings.warn("Fallback spawn triggered. Please update distutils monkeypatch.")
  457. with mock.patch.dict('os.environ', env):
  458. bag.value = super().spawn(cmd)
  459. # -- Miscellaneous methods -----------------------------------------
  460. # These are all used by the 'gen_lib_options() function, in
  461. # ccompiler.py.
  462. def library_dir_option(self, dir):
  463. return "/LIBPATH:" + dir
  464. def runtime_library_dir_option(self, dir):
  465. raise DistutilsPlatformError(
  466. "don't know how to set runtime library search path for MSVC"
  467. )
  468. def library_option(self, lib):
  469. return self.library_filename(lib)
  470. def find_library_file(self, dirs, lib, debug=0):
  471. # Prefer a debugging library if found (and requested), but deal
  472. # with it if we don't have one.
  473. if debug:
  474. try_names = [lib + "_d", lib]
  475. else:
  476. try_names = [lib]
  477. for dir in dirs:
  478. for name in try_names:
  479. libfile = os.path.join(dir, self.library_filename(name))
  480. if os.path.isfile(libfile):
  481. return libfile
  482. else:
  483. # Oops, didn't find it in *any* of 'dirs'
  484. return None