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