_msvccompiler.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. # Anaconda/conda-forge customisation, we want our pdbs to be
  289. # relocatable:
  290. # https://developercommunity.visualstudio.com/comments/623156/view.html
  291. d1trimfile_opts = []
  292. if 'SRC_DIR' in os.environ:
  293. d1trimfile_opts.append("/d1trimfile:" + os.environ['SRC_DIR'])
  294. if ext in self._c_extensions:
  295. input_opt = "/Tc" + src
  296. elif ext in self._cpp_extensions:
  297. input_opt = "/Tp" + src
  298. add_cpp_opts = True
  299. elif ext in self._rc_extensions:
  300. # compile .RC to .RES file
  301. input_opt = src
  302. output_opt = "/fo" + obj
  303. try:
  304. self.spawn([self.rc] + pp_opts + [output_opt, input_opt])
  305. except DistutilsExecError as msg:
  306. raise CompileError(msg)
  307. continue
  308. elif ext in self._mc_extensions:
  309. # Compile .MC to .RC file to .RES file.
  310. # * '-h dir' specifies the directory for the
  311. # generated include file
  312. # * '-r dir' specifies the target directory of the
  313. # generated RC file and the binary message resource
  314. # it includes
  315. #
  316. # For now (since there are no options to change this),
  317. # we use the source-directory for the include file and
  318. # the build directory for the RC file and message
  319. # resources. This works at least for win32all.
  320. h_dir = os.path.dirname(src)
  321. rc_dir = os.path.dirname(obj)
  322. try:
  323. # first compile .MC to .RC and .H file
  324. self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])
  325. base, _ = os.path.splitext(os.path.basename (src))
  326. rc_file = os.path.join(rc_dir, base + '.rc')
  327. # then compile .RC to .RES file
  328. self.spawn([self.rc, "/fo" + obj, rc_file])
  329. except DistutilsExecError as msg:
  330. raise CompileError(msg)
  331. continue
  332. else:
  333. # how to handle this file?
  334. raise CompileError("Don't know how to compile {} to {}"
  335. .format(src, obj))
  336. args = [self.cc] + compile_opts + pp_opts + d1trimfile_opts
  337. if add_cpp_opts:
  338. args.append('/EHsc')
  339. args.append(input_opt)
  340. args.append("/Fo" + obj)
  341. args.extend(extra_postargs)
  342. try:
  343. self.spawn(args)
  344. except DistutilsExecError as msg:
  345. raise CompileError(msg)
  346. return objects
  347. def create_static_lib(self,
  348. objects,
  349. output_libname,
  350. output_dir=None,
  351. debug=0,
  352. target_lang=None):
  353. if not self.initialized:
  354. self.initialize()
  355. objects, output_dir = self._fix_object_args(objects, output_dir)
  356. output_filename = self.library_filename(output_libname,
  357. output_dir=output_dir)
  358. if self._need_link(objects, output_filename):
  359. lib_args = objects + ['/OUT:' + output_filename]
  360. if debug:
  361. pass # XXX what goes here?
  362. try:
  363. log.debug('Executing "%s" %s', self.lib, ' '.join(lib_args))
  364. self.spawn([self.lib] + lib_args)
  365. except DistutilsExecError as msg:
  366. raise LibError(msg)
  367. else:
  368. log.debug("skipping %s (up-to-date)", output_filename)
  369. def link(self,
  370. target_desc,
  371. objects,
  372. output_filename,
  373. output_dir=None,
  374. libraries=None,
  375. library_dirs=None,
  376. runtime_library_dirs=None,
  377. export_symbols=None,
  378. debug=0,
  379. extra_preargs=None,
  380. extra_postargs=None,
  381. build_temp=None,
  382. target_lang=None):
  383. if not self.initialized:
  384. self.initialize()
  385. objects, output_dir = self._fix_object_args(objects, output_dir)
  386. fixed_args = self._fix_lib_args(libraries, library_dirs,
  387. runtime_library_dirs)
  388. libraries, library_dirs, runtime_library_dirs = fixed_args
  389. if runtime_library_dirs:
  390. self.warn("I don't know what to do with 'runtime_library_dirs': "
  391. + str(runtime_library_dirs))
  392. lib_opts = gen_lib_options(self,
  393. library_dirs, runtime_library_dirs,
  394. libraries)
  395. if output_dir is not None:
  396. output_filename = os.path.join(output_dir, output_filename)
  397. if self._need_link(objects, output_filename):
  398. ldflags = self._ldflags[target_desc, debug]
  399. export_opts = ["/EXPORT:" + sym for sym in (export_symbols or [])]
  400. ld_args = (ldflags + lib_opts + export_opts +
  401. objects + ['/OUT:' + output_filename])
  402. # The MSVC linker generates .lib and .exp files, which cannot be
  403. # suppressed by any linker switches. The .lib files may even be
  404. # needed! Make sure they are generated in the temporary build
  405. # directory. Since they have different names for debug and release
  406. # builds, they can go into the same directory.
  407. build_temp = os.path.dirname(objects[0])
  408. if export_symbols is not None:
  409. (dll_name, dll_ext) = os.path.splitext(
  410. os.path.basename(output_filename))
  411. implib_file = os.path.join(
  412. build_temp,
  413. self.library_filename(dll_name))
  414. ld_args.append ('/IMPLIB:' + implib_file)
  415. if extra_preargs:
  416. ld_args[:0] = extra_preargs
  417. if extra_postargs:
  418. ld_args.extend(extra_postargs)
  419. output_dir = os.path.dirname(os.path.abspath(output_filename))
  420. self.mkpath(output_dir)
  421. try:
  422. log.debug('Executing "%s" %s', self.linker, ' '.join(ld_args))
  423. self.spawn([self.linker] + ld_args)
  424. except DistutilsExecError as msg:
  425. raise LinkError(msg)
  426. else:
  427. log.debug("skipping %s (up-to-date)", output_filename)
  428. def spawn(self, cmd):
  429. old_path = os.getenv('path')
  430. try:
  431. os.environ['path'] = self._paths
  432. return super().spawn(cmd)
  433. finally:
  434. os.environ['path'] = old_path
  435. # -- Miscellaneous methods -----------------------------------------
  436. # These are all used by the 'gen_lib_options() function, in
  437. # ccompiler.py.
  438. def library_dir_option(self, dir):
  439. return "/LIBPATH:" + dir
  440. def runtime_library_dir_option(self, dir):
  441. raise DistutilsPlatformError(
  442. "don't know how to set runtime library search path for MSVC")
  443. def library_option(self, lib):
  444. return self.library_filename(lib)
  445. def find_library_file(self, dirs, lib, debug=0):
  446. # Prefer a debugging library if found (and requested), but deal
  447. # with it if we don't have one.
  448. if debug:
  449. try_names = [lib + "_d", lib]
  450. else:
  451. try_names = [lib]
  452. for dir in dirs:
  453. for name in try_names:
  454. libfile = os.path.join(dir, self.library_filename(name))
  455. if os.path.isfile(libfile):
  456. return libfile
  457. else:
  458. # Oops, didn't find it in *any* of 'dirs'
  459. return None