_msvccompiler.py 19 KB

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