_msvccompiler.py 20 KB

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