_msvccompiler.py 19 KB

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