_msvccompiler.py 20 KB

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