Debian Codegraph @

rpython/tool/setuptools_msvc.py

raw symbols SCIP
1 """
2 Improved support for Microsoft Visual C++ compilers.
3
4 Known supported compilers:
5 --------------------------
6 Microsoft Visual C++ 9.0:
7 Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64)
8 Microsoft Windows SDK 6.1 (x86, x64, ia64)
9 Microsoft Windows SDK 7.0 (x86, x64, ia64)
10
11 Microsoft Visual C++ 10.0:
12 Microsoft Windows SDK 7.1 (x86, x64, ia64)
13
14 Microsoft Visual C++ 14.X:
15 Microsoft Visual C++ Build Tools 2015 (x86, x64, arm)
16 Microsoft Visual Studio Build Tools 2017 (x86, x64, arm, arm64)
17 Microsoft Visual Studio Build Tools 2019 (x86, x64, arm, arm64)
18
19 This may also support compilers shipped with compatible Visual Studio versions.
20 """
21
22 # copied as-is from python3
23 # modified to:
24 # - commented out monkey patching
25 # - lookup() returns str not unicode
26
27 import json
28 from io import open
29 from os import listdir, pathsep
30 from os.path import join, isfile, isdir, dirname
31 import sys
32 import platform
33 import itertools
34 import distutils.errors
35
36 #from .monkey import get_unpatched
37
38 if platform.system() == 'Windows':
39 if sys.version_info[0] < 3:
40 import _winreg as winreg
41 from itertools import ifilterfalse as filterfalse
42 else:
43 import winreg
44 from itertools import filterfalse
45 from os import environ
46 else:
47 # Mock winreg and environ so the module can be imported on this platform.
48
49 class winreg:
50 HKEY_USERS = None
51 HKEY_CURRENT_USER = None
52 HKEY_LOCAL_MACHINE = None
53 HKEY_CLASSES_ROOT = None
54
55 environ = dict()
56
57 _msvc9_suppress_errors = (
58 # msvc9compiler isn't available on some platforms
59 ImportError,
60
61 # msvc9compiler raises DistutilsPlatformError in some
62 # environments. See #1118.
63 distutils.errors.DistutilsPlatformError,
64 )
65
66 try:
67 from distutils.msvc9compiler import Reg
68 except _msvc9_suppress_errors:
69 pass
70
71
72 def msvc9_find_vcvarsall(version):
73 """
74 Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone
75 compiler build for Python
76 (VCForPython / Microsoft Visual C++ Compiler for Python 2.7).
77
78 Fall back to original behavior when the standalone compiler is not
79 available.
80
81 Redirect the path of "vcvarsall.bat".
82
83 Parameters
84 ----------
85 version: float
86 Required Microsoft Visual C++ version.
87
88 Return
89 ------
90 str
91 vcvarsall.bat path
92 """
93 vc_base = r'Software\%sMicrosoft\DevDiv\VCForPython\%0.1f'
94 key = vc_base % ('', version)
95 try:
96 # Per-user installs register the compiler path here
97 productdir = Reg.get_value(key, "installdir")
98 except KeyError:
99 try:
100 # All-user installs on a 64-bit system register here
101 key = vc_base % ('Wow6432Node\\', version)
102 productdir = Reg.get_value(key, "installdir")
103 except KeyError:
104 productdir = None
105
106 if productdir:
107 vcvarsall = join(productdir, "vcvarsall.bat")
108 if isfile(vcvarsall):
109 return vcvarsall
110
111 return get_unpatched(msvc9_find_vcvarsall)(version)
112
113
114 def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs):
115 """
116 Patched "distutils.msvc9compiler.query_vcvarsall" for support extra
117 Microsoft Visual C++ 9.0 and 10.0 compilers.
118
119 Set environment without use of "vcvarsall.bat".
120
121 Parameters
122 ----------
123 ver: float
124 Required Microsoft Visual C++ version.
125 arch: str
126 Target architecture.
127
128 Return
129 ------
130 dict
131 environment
132 """
133 # Try to get environment from vcvarsall.bat (Classical way)
134 #try:
135 # orig = get_unpatched(msvc9_query_vcvarsall)
136 # return orig(ver, arch, *args, **kwargs)
137 #except distutils.errors.DistutilsPlatformError:
138 # # Pass error if Vcvarsall.bat is missing
139 # pass
140 #except ValueError:
141 # # Pass error if environment not set after executing vcvarsall.bat
142 # pass
143
144 # If error, try to set environment directly
145 try:
146 return EnvironmentInfo(arch, ver).return_env()
147 except distutils.errors.DistutilsPlatformError as exc:
148 _augment_exception(exc, ver, arch)
149 raise
150
151
152 def msvc14_get_vc_env(plat_spec):
153 """
154 Patched "distutils._msvccompiler._get_vc_env" for support extra
155 Microsoft Visual C++ 14.X compilers.
156
157 Set environment without use of "vcvarsall.bat".
158
159 Parameters
160 ----------
161 plat_spec: str
162 Target architecture.
163
164 Return
165 ------
166 dict
167 environment
168 """
169 # Try to get environment from vcvarsall.bat (Classical way)
170 #try:
171 # return get_unpatched(msvc14_get_vc_env)(plat_spec)
172 #except distutils.errors.DistutilsPlatformError:
173 # Pass error Vcvarsall.bat is missing
174 # pass
175
176 # If error, try to set environment directly
177 try:
178 return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env()
179 except distutils.errors.DistutilsPlatformError as exc:
180 _augment_exception(exc, 14.0)
181 raise
182
183
184 def msvc14_gen_lib_options(*args, **kwargs):
185 """
186 Patched "distutils._msvccompiler.gen_lib_options" for fix
187 compatibility between "numpy.distutils" and "distutils._msvccompiler"
188 (for Numpy < 1.11.2)
189 """
190 if "numpy.distutils" in sys.modules:
191 import numpy as np
192 from pkg_resources.extern.packaging.version import LegacyVersion
193 if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):
194 return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)
195 return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs)
196
197
198 def _augment_exception(exc, version, arch=''):
199 """
200 Add details to the exception message to help guide the user
201 as to what action will resolve it.
202 """
203 # Error if MSVC++ directory not found or environment not set
204 message = exc.args[0]
205
206 if "vcvarsall" in message.lower() or "visual c" in message.lower():
207 # Special error message if MSVC++ not installed
208 tmpl = 'Microsoft Visual C++ {version:0.1f} is required.'
209 message = tmpl.format(**locals())
210 msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
211 if version == 9.0:
212 if arch.lower().find('ia64') > -1:
213 # For VC++ 9.0, if IA64 support is needed, redirect user
214 # to Windows SDK 7.0.
215 # Note: No download link available from Microsoft.
216 message += ' Get it with "Microsoft Windows SDK 7.0"'
217 else:
218 # For VC++ 9.0 redirect user to Vc++ for Python 2.7 :
219 # This redirection link is maintained by Microsoft.
220 # Contact [email protected] if it needs updating.
221 message += ' Get it from http://aka.ms/vcpython27'
222 elif version == 10.0:
223 # For VC++ 10.0 Redirect user to Windows SDK 7.1
224 message += ' Get it with "Microsoft Windows SDK 7.1": '
225 message += msdownload % 8279
226 elif version >= 14.0:
227 # For VC++ 14.X Redirect user to latest Visual C++ Build Tools
228 message += (' Get it with "Build Tools for Visual Studio": '
229 r'https://visualstudio.microsoft.com/downloads/')
230
231 exc.args = (message, )
232
233
234 class PlatformInfo:
235 """
236 Current and Target Architectures information.
237
238 Parameters
239 ----------
240 arch: str
241 Target architecture.
242 """
243 current_cpu = environ.get('processor_architecture', '').lower()
244
245 def __init__(self, arch):
246 self.arch = arch.lower().replace('x64', 'amd64')
247
248 @property
249 def target_cpu(self):
250 """
251 Return Target CPU architecture.
252
253 Return
254 ------
255 str
256 Target CPU
257 """
258 return self.arch[self.arch.find('_') + 1:]
259
260 def target_is_x86(self):
261 """
262 Return True if target CPU is x86 32 bits..
263
264 Return
265 ------
266 bool
267 CPU is x86 32 bits
268 """
269 return self.target_cpu == 'x86'
270
271 def current_is_x86(self):
272 """
273 Return True if current CPU is x86 32 bits..
274
275 Return
276 ------
277 bool
278 CPU is x86 32 bits
279 """
280 return self.current_cpu == 'x86'
281
282 def current_dir(self, hidex86=False, x64=False):
283 """
284 Current platform specific subfolder.
285
286 Parameters
287 ----------
288 hidex86: bool
289 return '' and not '\x86' if architecture is x86.
290 x64: bool
291 return '\x64' and not '\amd64' if architecture is amd64.
292
293 Return
294 ------
295 str
296 subfolder: '\target', or '' (see hidex86 parameter)
297 """
298 return (
299 '' if (self.current_cpu == 'x86' and hidex86) else
300 r'\x64' if (self.current_cpu == 'amd64' and x64) else
301 r'\%s' % self.current_cpu
302 )
303
304 def target_dir(self, hidex86=False, x64=False):
305 r"""
306 Target platform specific subfolder.
307
308 Parameters
309 ----------
310 hidex86: bool
311 return '' and not '\x86' if architecture is x86.
312 x64: bool
313 return '\x64' and not '\amd64' if architecture is amd64.
314
315 Return
316 ------
317 str
318 subfolder: '\current', or '' (see hidex86 parameter)
319 """
320 return (
321 '' if (self.target_cpu == 'x86' and hidex86) else
322 r'\x64' if (self.target_cpu == 'amd64' and x64) else
323 r'\%s' % self.target_cpu
324 )
325
326 def cross_dir(self, forcex86=False):
327 r"""
328 Cross platform specific subfolder.
329
330 Parameters
331 ----------
332 forcex86: bool
333 Use 'x86' as current architecture even if current architecture is
334 not x86.
335
336 Return
337 ------
338 str
339 subfolder: '' if target architecture is current architecture,
340 '\current_target' if not.
341 """
342 current = 'x86' if forcex86 else self.current_cpu
343 return (
344 '' if self.target_cpu == current else
345 self.target_dir().replace('\\', '\\%s_' % current)
346 )
347
348
349 class RegistryInfo:
350 """
351 Microsoft Visual Studio related registry information.
352
353 Parameters
354 ----------
355 platform_info: PlatformInfo
356 "PlatformInfo" instance.
357 """
358 HKEYS = (winreg.HKEY_USERS,
359 winreg.HKEY_CURRENT_USER,
360 winreg.HKEY_LOCAL_MACHINE,
361 winreg.HKEY_CLASSES_ROOT)
362
363 def __init__(self, platform_info):
364 self.pi = platform_info
365
366 @property
367 def visualstudio(self):
368 """
369 Microsoft Visual Studio root registry key.
370
371 Return
372 ------
373 str
374 Registry key
375 """
376 return 'VisualStudio'
377
378 @property
379 def sxs(self):
380 """
381 Microsoft Visual Studio SxS registry key.
382
383 Return
384 ------
385 str
386 Registry key
387 """
388 return join(self.visualstudio, 'SxS')
389
390 @property
391 def vc(self):
392 """
393 Microsoft Visual C++ VC7 registry key.
394
395 Return
396 ------
397 str
398 Registry key
399 """
400 return join(self.sxs, 'VC7')
401
402 @property
403 def vs(self):
404 """
405 Microsoft Visual Studio VS7 registry key.
406
407 Return
408 ------
409 str
410 Registry key
411 """
412 return join(self.sxs, 'VS7')
413
414 @property
415 def vc_for_python(self):
416 """
417 Microsoft Visual C++ for Python registry key.
418
419 Return
420 ------
421 str
422 Registry key
423 """
424 return r'DevDiv\VCForPython'
425
426 @property
427 def microsoft_sdk(self):
428 """
429 Microsoft SDK registry key.
430
431 Return
432 ------
433 str
434 Registry key
435 """
436 return 'Microsoft SDKs'
437
438 @property
439 def windows_sdk(self):
440 """
441 Microsoft Windows/Platform SDK registry key.
442
443 Return
444 ------
445 str
446 Registry key
447 """
448 return join(self.microsoft_sdk, 'Windows')
449
450 @property
451 def netfx_sdk(self):
452 """
453 Microsoft .NET Framework SDK registry key.
454
455 Return
456 ------
457 str
458 Registry key
459 """
460 return join(self.microsoft_sdk, 'NETFXSDK')
461
462 @property
463 def windows_kits_roots(self):
464 """
465 Microsoft Windows Kits Roots registry key.
466
467 Return
468 ------
469 str
470 Registry key
471 """
472 return r'Windows Kits\Installed Roots'
473
474 def microsoft(self, key, x86=False):
475 """
476 Return key in Microsoft software registry.
477
478 Parameters
479 ----------
480 key: str
481 Registry key path where look.
482 x86: str
483 Force x86 software registry.
484
485 Return
486 ------
487 str
488 Registry key
489 """
490 node64 = '' if self.pi.current_is_x86() or x86 else 'Wow6432Node'
491 return join('Software', node64, 'Microsoft', key)
492
493 def lookup(self, key, name):
494 """
495 Look for values in registry in Microsoft software registry.
496
497 Parameters
498 ----------
499 key: str
500 Registry key path where look.
501 name: str
502 Value name to find.
503
504 Return
505 ------
506 str
507 value
508 """
509 key_read = winreg.KEY_READ
510 openkey = winreg.OpenKey
511 ms = self.microsoft
512 for hkey in self.HKEYS:
513 try:
514 bkey = openkey(hkey, ms(key), 0, key_read)
515 except (OSError, IOError):
516 if not self.pi.current_is_x86():
517 try:
518 bkey = openkey(hkey, ms(key, True), 0, key_read)
519 except (OSError, IOError):
520 continue
521 else:
522 continue
523 try:
524 return winreg.QueryValueEx(bkey, name)[0]
525 except (OSError, IOError):
526 pass
527
528
529 class SystemInfo:
530 """
531 Microsoft Windows and Visual Studio related system information.
532
533 Parameters
534 ----------
535 registry_info: RegistryInfo
536 "RegistryInfo" instance.
537 vc_ver: float
538 Required Microsoft Visual C++ version.
539 """
540
541 # Variables and properties in this class use originals CamelCase variables
542 # names from Microsoft source files for more easy comparison.
543 WinDir = environ.get('WinDir', '')
544 ProgramFiles = environ.get('ProgramFiles', '')
545 ProgramFilesx86 = environ.get('ProgramFiles(x86)', ProgramFiles)
546
547 def __init__(self, registry_info, vc_ver=None):
548 self.ri = registry_info
549 self.pi = self.ri.pi
550 # self.vc_ver = vc_ver or self._find_latest_available_vc_ver()
551
552 self.known_vs_paths = self.find_programdata_vs_vers()
553
554 # Except for VS15+, VC version is aligned with VS version
555 self.vs_ver = self.vc_ver = (
556 vc_ver or self._find_latest_available_vs_ver())
557
558 def _find_latest_available_vs_ver(self):
559 """
560 Find the latest VC version
561
562 Return
563 ------
564 float
565 version
566 """
567 reg_vc_vers = self.find_reg_vs_vers()
568
569 if not (reg_vc_vers or self.known_vs_paths):
570 raise distutils.errors.DistutilsPlatformError(
571 'No Microsoft Visual C++ version found')
572
573 vc_vers = set(reg_vc_vers)
574 vc_vers.update(self.known_vs_paths)
575 return sorted(vc_vers)[-1]
576
577 def find_reg_vs_vers(self):
578 """
579 Find Microsoft Visual Studio versions available in registry.
580
581 Return
582 ------
583 list of float
584 Versions
585 """
586 ms = self.ri.microsoft
587 vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs)
588 vs_vers = []
589 for hkey in self.ri.HKEYS:
590 for key in vckeys:
591 try:
592 bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ)
593 except (OSError, IOError):
594 continue
595 subkeys, values, _ = winreg.QueryInfoKey(bkey)
596 for i in range(values):
597 try:
598 ver = float(winreg.EnumValue(bkey, i)[0])
599 if ver not in vs_vers:
600 vs_vers.append(ver)
601 except ValueError:
602 pass
603 for i in range(subkeys):
604 try:
605 ver = float(winreg.EnumKey(bkey, i))
606 if ver not in vs_vers:
607 vs_vers.append(ver)
608 except ValueError:
609 pass
610 return sorted(vs_vers)
611
612 def find_programdata_vs_vers(self):
613 r"""
614 Find Visual studio 2017+ versions from information in
615 "C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances".
616
617 Return
618 ------
619 dict
620 float version as key, path as value.
621 """
622 vs_versions = {}
623 instances_dir = \
624 r'C:\ProgramData\Microsoft\VisualStudio\Packages\_Instances'
625
626 try:
627 hashed_names = listdir(instances_dir)
628
629 except (OSError, IOError):
630 # Directory not exists with all Visual Studio versions
631 return vs_versions
632
633 for name in hashed_names:
634 try:
635 # Get VS installation path from "state.json" file
636 state_path = join(instances_dir, name, 'state.json')
637 with open(state_path, 'rt', encoding='utf-8') as state_file:
638 state = json.load(state_file)
639 vs_path = state['installationPath']
640
641 # Raises OSError if this VS installation does not contain VC
642 listdir(join(vs_path, r'VC\Tools\MSVC'))
643
644 # Store version and path
645 vs_versions[self._as_float_version(
646 state['installationVersion'])] = vs_path
647
648 except (OSError, IOError, KeyError):
649 # Skip if "state.json" file is missing or bad format
650 continue
651
652 return vs_versions
653
654 @staticmethod
655 def _as_float_version(version):
656 """
657 Return a string version as a simplified float version (major.minor)
658
659 Parameters
660 ----------
661 version: str
662 Version.
663
664 Return
665 ------
666 float
667 version
668 """
669 return float('.'.join(version.split('.')[:2]))
670
671 @property
672 def VSInstallDir(self):
673 """
674 Microsoft Visual Studio directory.
675
676 Return
677 ------
678 str
679 path
680 """
681 # Default path
682 default = join(self.ProgramFilesx86,
683 'Microsoft Visual Studio %0.1f' % self.vs_ver)
684
685 # Try to get path from registry, if fail use default path
686 return self.ri.lookup(self.ri.vs, '%0.1f' % self.vs_ver) or default
687
688 @property
689 def VCInstallDir(self):
690 """
691 Microsoft Visual C++ directory.
692
693 Return
694 ------
695 str
696 path
697 """
698 path = self._guess_vc() or self._guess_vc_legacy()
699
700 if not isdir(path):
701 msg = 'Microsoft Visual C++ directory not found'
702 raise distutils.errors.DistutilsPlatformError(msg)
703
704 return path
705
706 def _guess_vc(self):
707 """
708 Locate Visual C++ for VS2017+.
709
710 Return
711 ------
712 str
713 path
714 """
715 if self.vs_ver <= 14.0:
716 return ''
717
718 try:
719 # First search in known VS paths
720 vs_dir = self.known_vs_paths[self.vs_ver]
721 except KeyError:
722 # Else, search with path from registry
723 vs_dir = self.VSInstallDir
724
725 guess_vc = join(vs_dir, r'VC\Tools\MSVC')
726
727 # Subdir with VC exact version as name
728 try:
729 # Update the VC version with real one instead of VS version
730 vc_ver = listdir(guess_vc)[-1]
731 self.vc_ver = self._as_float_version(vc_ver)
732 return join(guess_vc, vc_ver)
733 except (OSError, IOError, IndexError):
734 return ''
735
736 def _guess_vc_legacy(self):
737 """
738 Locate Visual C++ for versions prior to 2017.
739
740 Return
741 ------
742 str
743 path
744 """
745 default = join(self.ProgramFilesx86,
746 r'Microsoft Visual Studio %0.1f\VC' % self.vs_ver)
747
748 # Try to get "VC++ for Python" path from registry as default path
749 reg_path = join(self.ri.vc_for_python, '%0.1f' % self.vs_ver)
750 python_vc = self.ri.lookup(reg_path, 'installdir')
751 default_vc = join(python_vc, 'VC') if python_vc else default
752
753 # Try to get path from registry, if fail use default path
754 return self.ri.lookup(self.ri.vc, '%0.1f' % self.vs_ver) or default_vc
755
756 @property
757 def WindowsSdkVersion(self):
758 """
759 Microsoft Windows SDK versions for specified MSVC++ version.
760
761 Return
762 ------
763 tuple of str
764 versions
765 """
766 if self.vs_ver <= 9.0:
767 return '7.0', '6.1', '6.0a'
768 elif self.vs_ver == 10.0:
769 return '7.1', '7.0a'
770 elif self.vs_ver == 11.0:
771 return '8.0', '8.0a'
772 elif self.vs_ver == 12.0:
773 return '8.1', '8.1a'
774 elif self.vs_ver >= 14.0:
775 return '10.0', '8.1'
776
777 @property
778 def WindowsSdkLastVersion(self):
779 """
780 Microsoft Windows SDK last version.
781
782 Return
783 ------
784 str
785 version
786 """
787 return self._use_last_dir_name(join(self.WindowsSdkDir, 'lib'))
788
789 @property
790 def WindowsSdkDir(self):
791 """
792 Microsoft Windows SDK directory.
793
794 Return
795 ------
796 str
797 path
798 """
799 sdkdir = ''
800 for ver in self.WindowsSdkVersion:
801 # Try to get it from registry
802 loc = join(self.ri.windows_sdk, 'v%s' % ver)
803 sdkdir = self.ri.lookup(loc, 'installationfolder')
804 if sdkdir:
805 break
806 if not sdkdir or not isdir(sdkdir):
807 # Try to get "VC++ for Python" version from registry
808 path = join(self.ri.vc_for_python, '%0.1f' % self.vc_ver)
809 install_base = self.ri.lookup(path, 'installdir')
810 if install_base:
811 sdkdir = join(install_base, 'WinSDK')
812 if not sdkdir or not isdir(sdkdir):
813 # If fail, use default new path
814 for ver in self.WindowsSdkVersion:
815 intver = ver[:ver.rfind('.')]
816 path = r'Microsoft SDKs\Windows Kits\%s' % intver
817 d = join(self.ProgramFiles, path)
818 if isdir(d):
819 sdkdir = d
820 if not sdkdir or not isdir(sdkdir):
821 # If fail, use default old path
822 for ver in self.WindowsSdkVersion:
823 path = r'Microsoft SDKs\Windows\v%s' % ver
824 d = join(self.ProgramFiles, path)
825 if isdir(d):
826 sdkdir = d
827 if not sdkdir:
828 # If fail, use Platform SDK
829 sdkdir = join(self.VCInstallDir, 'PlatformSDK')
830 return sdkdir
831
832 @property
833 def WindowsSDKExecutablePath(self):
834 """
835 Microsoft Windows SDK executable directory.
836
837 Return
838 ------
839 str
840 path
841 """
842 # Find WinSDK NetFx Tools registry dir name
843 if self.vs_ver <= 11.0:
844 netfxver = 35
845 arch = ''
846 else:
847 netfxver = 40
848 hidex86 = True if self.vs_ver <= 12.0 else False
849 arch = self.pi.current_dir(x64=True, hidex86=hidex86)
850 fx = 'WinSDK-NetFx%dTools%s' % (netfxver, arch.replace('\\', '-'))
851
852 # list all possibles registry paths
853 regpaths = []
854 if self.vs_ver >= 14.0:
855 for ver in self.NetFxSdkVersion:
856 regpaths += [join(self.ri.netfx_sdk, ver, fx)]
857
858 for ver in self.WindowsSdkVersion:
859 regpaths += [join(self.ri.windows_sdk, 'v%sA' % ver, fx)]
860
861 # Return installation folder from the more recent path
862 for path in regpaths:
863 execpath = self.ri.lookup(path, 'installationfolder')
864 if execpath:
865 return execpath
866
867 @property
868 def FSharpInstallDir(self):
869 """
870 Microsoft Visual F# directory.
871
872 Return
873 ------
874 str
875 path
876 """
877 path = join(self.ri.visualstudio, r'%0.1f\Setup\F#' % self.vs_ver)
878 return self.ri.lookup(path, 'productdir') or ''
879
880 @property
881 def UniversalCRTSdkDir(self):
882 """
883 Microsoft Universal CRT SDK directory.
884
885 Return
886 ------
887 str
888 path
889 """
890 # Set Kit Roots versions for specified MSVC++ version
891 vers = ('10', '81') if self.vs_ver >= 14.0 else ()
892
893 # Find path of the more recent Kit
894 for ver in vers:
895 sdkdir = self.ri.lookup(self.ri.windows_kits_roots,
896 'kitsroot%s' % ver)
897 if sdkdir:
898 return sdkdir or ''
899
900 @property
901 def UniversalCRTSdkLastVersion(self):
902 """
903 Microsoft Universal C Runtime SDK last version.
904
905 Return
906 ------
907 str
908 version
909 """
910 return self._use_last_dir_name(join(self.UniversalCRTSdkDir, 'lib'))
911
912 @property
913 def NetFxSdkVersion(self):
914 """
915 Microsoft .NET Framework SDK versions.
916
917 Return
918 ------
919 tuple of str
920 versions
921 """
922 # Set FxSdk versions for specified VS version
923 return (('4.7.2', '4.7.1', '4.7',
924 '4.6.2', '4.6.1', '4.6',
925 '4.5.2', '4.5.1', '4.5')
926 if self.vs_ver >= 14.0 else ())
927
928 @property
929 def NetFxSdkDir(self):
930 """
931 Microsoft .NET Framework SDK directory.
932
933 Return
934 ------
935 str
936 path
937 """
938 sdkdir = ''
939 for ver in self.NetFxSdkVersion:
940 loc = join(self.ri.netfx_sdk, ver)
941 sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')
942 if sdkdir:
943 break
944 return sdkdir
945
946 @property
947 def FrameworkDir32(self):
948 """
949 Microsoft .NET Framework 32bit directory.
950
951 Return
952 ------
953 str
954 path
955 """
956 # Default path
957 guess_fw = join(self.WinDir, r'Microsoft.NET\Framework')
958
959 # Try to get path from registry, if fail use default path
960 return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw
961
962 @property
963 def FrameworkDir64(self):
964 """
965 Microsoft .NET Framework 64bit directory.
966
967 Return
968 ------
969 str
970 path
971 """
972 # Default path
973 guess_fw = join(self.WinDir, r'Microsoft.NET\Framework64')
974
975 # Try to get path from registry, if fail use default path
976 return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw
977
978 @property
979 def FrameworkVersion32(self):
980 """
981 Microsoft .NET Framework 32bit versions.
982
983 Return
984 ------
985 tuple of str
986 versions
987 """
988 return self._find_dot_net_versions(32)
989
990 @property
991 def FrameworkVersion64(self):
992 """
993 Microsoft .NET Framework 64bit versions.
994
995 Return
996 ------
997 tuple of str
998 versions
999 """
1000 return self._find_dot_net_versions(64)
1001
1002 def _find_dot_net_versions(self, bits):
1003 """
1004 Find Microsoft .NET Framework versions.
1005
1006 Parameters
1007 ----------
1008 bits: int
1009 Platform number of bits: 32 or 64.
1010
1011 Return
1012 ------
1013 tuple of str
1014 versions
1015 """
1016 # Find actual .NET version in registry
1017 reg_ver = self.ri.lookup(self.ri.vc, 'frameworkver%d' % bits)
1018 dot_net_dir = getattr(self, 'FrameworkDir%d' % bits)
1019 ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or ''
1020
1021 # Set .NET versions for specified MSVC++ version
1022 if self.vs_ver >= 12.0:
1023 return ver, 'v4.0'
1024 elif self.vs_ver >= 10.0:
1025 return 'v4.0.30319' if ver.lower()[:2] != 'v4' else ver, 'v3.5'
1026 elif self.vs_ver == 9.0:
1027 return 'v3.5', 'v2.0.50727'
1028 elif self.vs_ver == 8.0:
1029 return 'v3.0', 'v2.0.50727'
1030
1031 @staticmethod
1032 def _use_last_dir_name(path, prefix=''):
1033 """
1034 Return name of the last dir in path or '' if no dir found.
1035
1036 Parameters
1037 ----------
1038 path: str
1039 Use dirs in this path
1040 prefix: str
1041 Use only dirs starting by this prefix
1042
1043 Return
1044 ------
1045 str
1046 name
1047 """
1048 matching_dirs = (
1049 dir_name
1050 for dir_name in reversed(listdir(path))
1051 if isdir(join(path, dir_name)) and
1052 dir_name.startswith(prefix)
1053 )
1054 return next(matching_dirs, None) or ''
1055
1056
1057 class EnvironmentInfo:
1058 """
1059 Return environment variables for specified Microsoft Visual C++ version
1060 and platform : Lib, Include, Path and libpath.
1061
1062 This function is compatible with Microsoft Visual C++ 9.0 to 14.X.
1063
1064 Script created by analysing Microsoft environment configuration files like
1065 "vcvars[...].bat", "SetEnv.Cmd", "vcbuildtools.bat", ...
1066
1067 Parameters
1068 ----------
1069 arch: str
1070 Target architecture.
1071 vc_ver: float
1072 Required Microsoft Visual C++ version. If not set, autodetect the last
1073 version.
1074 vc_min_ver: float
1075 Minimum Microsoft Visual C++ version.
1076 """
1077
1078 # Variables and properties in this class use originals CamelCase variables
1079 # names from Microsoft source files for more easy comparison.
1080
1081 def __init__(self, arch, vc_ver=None, vc_min_ver=0):
1082 self.pi = PlatformInfo(arch)
1083 self.ri = RegistryInfo(self.pi)
1084 self.si = SystemInfo(self.ri, vc_ver)
1085
1086 if self.vc_ver < vc_min_ver:
1087 err = 'No suitable Microsoft Visual C++ version found'
1088 raise distutils.errors.DistutilsPlatformError(err)
1089
1090 @property
1091 def vs_ver(self):
1092 """
1093 Microsoft Visual Studio.
1094
1095 Return
1096 ------
1097 float
1098 version
1099 """
1100 return self.si.vs_ver
1101
1102 @property
1103 def vc_ver(self):
1104 """
1105 Microsoft Visual C++ version.
1106
1107 Return
1108 ------
1109 float
1110 version
1111 """
1112 return self.si.vc_ver
1113
1114 @property
1115 def VSTools(self):
1116 """
1117 Microsoft Visual Studio Tools.
1118
1119 Return
1120 ------
1121 list of str
1122 paths
1123 """
1124 paths = [r'Common7\IDE', r'Common7\Tools']
1125
1126 if self.vs_ver >= 14.0:
1127 arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
1128 paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
1129 paths += [r'Team Tools\Performance Tools']
1130 paths += [r'Team Tools\Performance Tools%s' % arch_subdir]
1131
1132 return [join(self.si.VSInstallDir, path) for path in paths]
1133
1134 @property
1135 def VCIncludes(self):
1136 """
1137 Microsoft Visual C++ & Microsoft Foundation Class Includes.
1138
1139 Return
1140 ------
1141 list of str
1142 paths
1143 """
1144 return [join(self.si.VCInstallDir, 'Include'),
1145 join(self.si.VCInstallDir, r'ATLMFC\Include')]
1146
1147 @property
1148 def VCLibraries(self):
1149 """
1150 Microsoft Visual C++ & Microsoft Foundation Class Libraries.
1151
1152 Return
1153 ------
1154 list of str
1155 paths
1156 """
1157 if self.vs_ver >= 15.0:
1158 arch_subdir = self.pi.target_dir(x64=True)
1159 else:
1160 arch_subdir = self.pi.target_dir(hidex86=True)
1161 paths = ['Lib%s' % arch_subdir, r'ATLMFC\Lib%s' % arch_subdir]
1162
1163 if self.vs_ver >= 14.0:
1164 paths += [r'Lib\store%s' % arch_subdir]
1165
1166 return [join(self.si.VCInstallDir, path) for path in paths]
1167
1168 @property
1169 def VCStoreRefs(self):
1170 """
1171 Microsoft Visual C++ store references Libraries.
1172
1173 Return
1174 ------
1175 list of str
1176 paths
1177 """
1178 if self.vs_ver < 14.0:
1179 return []
1180 return [join(self.si.VCInstallDir, r'Lib\store\references')]
1181
1182 @property
1183 def VCTools(self):
1184 """
1185 Microsoft Visual C++ Tools.
1186
1187 Return
1188 ------
1189 list of str
1190 paths
1191 """
1192 si = self.si
1193 tools = [join(si.VCInstallDir, 'VCPackages')]
1194
1195 forcex86 = True if self.vs_ver <= 10.0 else False
1196 arch_subdir = self.pi.cross_dir(forcex86)
1197 if arch_subdir:
1198 tools += [join(si.VCInstallDir, 'Bin%s' % arch_subdir)]
1199
1200 if self.vs_ver == 14.0:
1201 path = 'Bin%s' % self.pi.current_dir(hidex86=True)
1202 tools += [join(si.VCInstallDir, path)]
1203
1204 elif self.vs_ver >= 15.0:
1205 host_dir = (r'bin\HostX86%s' if self.pi.current_is_x86() else
1206 r'bin\HostX64%s')
1207 tools += [join(
1208 si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))]
1209
1210 if self.pi.current_cpu != self.pi.target_cpu:
1211 tools += [join(
1212 si.VCInstallDir, host_dir % self.pi.current_dir(x64=True))]
1213
1214 else:
1215 tools += [join(si.VCInstallDir, 'Bin')]
1216
1217 return tools
1218
1219 @property
1220 def OSLibraries(self):
1221 """
1222 Microsoft Windows SDK Libraries.
1223
1224 Return
1225 ------
1226 list of str
1227 paths
1228 """
1229 if self.vs_ver <= 10.0:
1230 arch_subdir = self.pi.target_dir(hidex86=True, x64=True)
1231 return [join(self.si.WindowsSdkDir, 'Lib%s' % arch_subdir)]
1232
1233 else:
1234 arch_subdir = self.pi.target_dir(x64=True)
1235 lib = join(self.si.WindowsSdkDir, 'lib')
1236 libver = self._sdk_subdir
1237 return [join(lib, '%sum%s' % (libver , arch_subdir))]
1238
1239 @property
1240 def OSIncludes(self):
1241 """
1242 Microsoft Windows SDK Include.
1243
1244 Return
1245 ------
1246 list of str
1247 paths
1248 """
1249 include = join(self.si.WindowsSdkDir, 'include')
1250
1251 if self.vs_ver <= 10.0:
1252 return [include, join(include, 'gl')]
1253
1254 else:
1255 if self.vs_ver >= 14.0:
1256 sdkver = self._sdk_subdir
1257 else:
1258 sdkver = ''
1259 return [join(include, '%sshared' % sdkver),
1260 join(include, '%sum' % sdkver),
1261 join(include, '%swinrt' % sdkver)]
1262
1263 @property
1264 def OSLibpath(self):
1265 """
1266 Microsoft Windows SDK Libraries Paths.
1267
1268 Return
1269 ------
1270 list of str
1271 paths
1272 """
1273 ref = join(self.si.WindowsSdkDir, 'References')
1274 libpath = []
1275
1276 if self.vs_ver <= 9.0:
1277 libpath += self.OSLibraries
1278
1279 if self.vs_ver >= 11.0:
1280 libpath += [join(ref, r'CommonConfiguration\Neutral')]
1281
1282 if self.vs_ver >= 14.0:
1283 libpath += [
1284 ref,
1285 join(self.si.WindowsSdkDir, 'UnionMetadata'),
1286 join(ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'),
1287 join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'),
1288 join(ref,'Windows.Networking.Connectivity.WwanContract',
1289 '1.0.0.0'),
1290 join(self.si.WindowsSdkDir, 'ExtensionSDKs', 'Microsoft.VCLibs',
1291 '%0.1f' % self.vs_ver, 'References', 'CommonConfiguration',
1292 'neutral'),
1293 ]
1294 return libpath
1295
1296 @property
1297 def SdkTools(self):
1298 """
1299 Microsoft Windows SDK Tools.
1300
1301 Return
1302 ------
1303 list of str
1304 paths
1305 """
1306 return list(self._sdk_tools())
1307
1308 def _sdk_tools(self):
1309 """
1310 Microsoft Windows SDK Tools paths generator.
1311
1312 Return
1313 ------
1314 generator of str
1315 paths
1316 """
1317 if self.vs_ver < 15.0:
1318 bin_dir = 'Bin' if self.vs_ver <= 11.0 else r'Bin\x86'
1319 yield join(self.si.WindowsSdkDir, bin_dir)
1320
1321 if not self.pi.current_is_x86():
1322 arch_subdir = self.pi.current_dir(x64=True)
1323 path = 'Bin%s' % arch_subdir
1324 yield join(self.si.WindowsSdkDir, path)
1325
1326 if self.vs_ver in (10.0, 11.0):
1327 if self.pi.target_is_x86():
1328 arch_subdir = ''
1329 else:
1330 arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
1331 path = r'Bin\NETFX 4.0 Tools%s' % arch_subdir
1332 yield join(self.si.WindowsSdkDir, path)
1333
1334 elif self.vs_ver >= 15.0:
1335 path = join(self.si.WindowsSdkDir, 'Bin')
1336 arch_subdir = self.pi.current_dir(x64=True)
1337 sdkver = self.si.WindowsSdkLastVersion
1338 yield join(path, '%s%s' % (sdkver, arch_subdir))
1339
1340 if self.si.WindowsSDKExecutablePath:
1341 yield self.si.WindowsSDKExecutablePath
1342
1343 @property
1344 def _sdk_subdir(self):
1345 """
1346 Microsoft Windows SDK version subdir.
1347
1348 Return
1349 ------
1350 str
1351 subdir
1352 """
1353 ucrtver = self.si.WindowsSdkLastVersion
1354 return ('%s\\' % ucrtver) if ucrtver else ''
1355
1356 @property
1357 def SdkSetup(self):
1358 """
1359 Microsoft Windows SDK Setup.
1360
1361 Return
1362 ------
1363 list of str
1364 paths
1365 """
1366 if self.vs_ver > 9.0:
1367 return []
1368
1369 return [join(self.si.WindowsSdkDir, 'Setup')]
1370
1371 @property
1372 def FxTools(self):
1373 """
1374 Microsoft .NET Framework Tools.
1375
1376 Return
1377 ------
1378 list of str
1379 paths
1380 """
1381 pi = self.pi
1382 si = self.si
1383
1384 if self.vs_ver <= 10.0:
1385 include32 = True
1386 include64 = not pi.target_is_x86() and not pi.current_is_x86()
1387 else:
1388 include32 = pi.target_is_x86() or pi.current_is_x86()
1389 include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64'
1390
1391 tools = []
1392 if include32:
1393 tools += [join(si.FrameworkDir32, ver)
1394 for ver in si.FrameworkVersion32]
1395 if include64:
1396 tools += [join(si.FrameworkDir64, ver)
1397 for ver in si.FrameworkVersion64]
1398 return tools
1399
1400 @property
1401 def NetFxSDKLibraries(self):
1402 """
1403 Microsoft .Net Framework SDK Libraries.
1404
1405 Return
1406 ------
1407 list of str
1408 paths
1409 """
1410 if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
1411 return []
1412
1413 arch_subdir = self.pi.target_dir(x64=True)
1414 return [join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)]
1415
1416 @property
1417 def NetFxSDKIncludes(self):
1418 """
1419 Microsoft .Net Framework SDK Includes.
1420
1421 Return
1422 ------
1423 list of str
1424 paths
1425 """
1426 if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:
1427 return []
1428
1429 return [join(self.si.NetFxSdkDir, r'include\um')]
1430
1431 @property
1432 def VsTDb(self):
1433 """
1434 Microsoft Visual Studio Team System Database.
1435
1436 Return
1437 ------
1438 list of str
1439 paths
1440 """
1441 return [join(self.si.VSInstallDir, r'VSTSDB\Deploy')]
1442
1443 @property
1444 def MSBuild(self):
1445 """
1446 Microsoft Build Engine.
1447
1448 Return
1449 ------
1450 list of str
1451 paths
1452 """
1453 if self.vs_ver < 12.0:
1454 return []
1455 elif self.vs_ver < 15.0:
1456 base_path = self.si.ProgramFilesx86
1457 arch_subdir = self.pi.current_dir(hidex86=True)
1458 else:
1459 base_path = self.si.VSInstallDir
1460 arch_subdir = ''
1461
1462 path = r'MSBuild\%0.1f\bin%s' % (self.vs_ver, arch_subdir)
1463 build = [join(base_path, path)]
1464
1465 if self.vs_ver >= 15.0:
1466 # Add Roslyn C# & Visual Basic Compiler
1467 build += [join(base_path, path, 'Roslyn')]
1468
1469 return build
1470
1471 @property
1472 def HTMLHelpWorkshop(self):
1473 """
1474 Microsoft HTML Help Workshop.
1475
1476 Return
1477 ------
1478 list of str
1479 paths
1480 """
1481 if self.vs_ver < 11.0:
1482 return []
1483
1484 return [join(self.si.ProgramFilesx86, 'HTML Help Workshop')]
1485
1486 @property
1487 def UCRTLibraries(self):
1488 """
1489 Microsoft Universal C Runtime SDK Libraries.
1490
1491 Return
1492 ------
1493 list of str
1494 paths
1495 """
1496 if self.vs_ver < 14.0:
1497 return []
1498
1499 arch_subdir = self.pi.target_dir(x64=True)
1500 lib = join(self.si.UniversalCRTSdkDir, 'lib')
1501 ucrtver = self._ucrt_subdir
1502 return [join(lib, '%sucrt%s' % (ucrtver, arch_subdir))]
1503
1504 @property
1505 def UCRTIncludes(self):
1506 """
1507 Microsoft Universal C Runtime SDK Include.
1508
1509 Return
1510 ------
1511 list of str
1512 paths
1513 """
1514 if self.vs_ver < 14.0:
1515 return []
1516
1517 include = join(self.si.UniversalCRTSdkDir, 'include')
1518 return [join(include, '%sucrt' % self._ucrt_subdir)]
1519
1520 @property
1521 def _ucrt_subdir(self):
1522 """
1523 Microsoft Universal C Runtime SDK version subdir.
1524
1525 Return
1526 ------
1527 str
1528 subdir
1529 """
1530 ucrtver = self.si.UniversalCRTSdkLastVersion
1531 return ('%s\\' % ucrtver) if ucrtver else ''
1532
1533 @property
1534 def FSharp(self):
1535 """
1536 Microsoft Visual F#.
1537
1538 Return
1539 ------
1540 list of str
1541 paths
1542 """
1543 if 11.0 > self.vs_ver > 12.0:
1544 return []
1545
1546 return [self.si.FSharpInstallDir]
1547
1548 @property
1549 def VCRuntimeRedist(self):
1550 """
1551 Microsoft Visual C++ runtime redistributable dll.
1552
1553 Return
1554 ------
1555 str
1556 path
1557 """
1558 vcruntime = 'vcruntime%d0.dll' % self.vc_ver
1559 arch_subdir = self.pi.target_dir(x64=True).strip('\\')
1560
1561 # Installation prefixes candidates
1562 prefixes = []
1563 tools_path = self.si.VCInstallDir
1564 redist_path = dirname(tools_path.replace(r'\Tools', r'\Redist'))
1565 if isdir(redist_path):
1566 # Redist version may not be exactly the same as tools
1567 redist_path = join(redist_path, listdir(redist_path)[-1])
1568 prefixes += [redist_path, join(redist_path, 'onecore')]
1569
1570 prefixes += [join(tools_path, 'redist')] # VS14 legacy path
1571
1572 # CRT directory
1573 crt_dirs = ('Microsoft.VC%d.CRT' % (self.vc_ver * 10),
1574 # Sometime store in directory with VS version instead of VC
1575 'Microsoft.VC%d.CRT' % (int(self.vs_ver) * 10))
1576
1577 # vcruntime path
1578 for prefix, crt_dir in itertools.product(prefixes, crt_dirs):
1579 path = join(prefix, arch_subdir, crt_dir, vcruntime)
1580 if isfile(path):
1581 return path
1582 return ''
1583
1584 def return_env(self, exists=True):
1585 """
1586 Return environment dict.
1587
1588 Parameters
1589 ----------
1590 exists: bool
1591 It True, only return existing paths.
1592
1593 Return
1594 ------
1595 dict
1596 environment
1597 """
1598 env = dict(
1599 include=self._build_paths('include',
1600 [self.VCIncludes,
1601 self.OSIncludes,
1602 self.UCRTIncludes,
1603 self.NetFxSDKIncludes],
1604 exists),
1605 lib=self._build_paths('lib',
1606 [self.VCLibraries,
1607 self.OSLibraries,
1608 self.FxTools,
1609 self.UCRTLibraries,
1610 self.NetFxSDKLibraries],
1611 exists),
1612 libpath=self._build_paths('libpath',
1613 [self.VCLibraries,
1614 self.FxTools,
1615 self.VCStoreRefs,
1616 self.OSLibpath],
1617 exists),
1618 path=self._build_paths('path',
1619 [self.VCTools,
1620 self.VSTools,
1621 self.VsTDb,
1622 self.SdkTools,
1623 self.SdkSetup,
1624 self.FxTools,
1625 self.MSBuild,
1626 self.HTMLHelpWorkshop,
1627 self.FSharp],
1628 exists),
1629 )
1630 if self.vs_ver >= 14 and isfile(self.VCRuntimeRedist):
1631 env['py_vcruntime_redist'] = self.VCRuntimeRedist
1632 return env
1633
1634 def _build_paths(self, name, spec_path_lists, exists):
1635 """
1636 Given an environment variable name and specified paths,
1637 return a pathsep-separated string of paths containing
1638 unique, extant, directories from those paths and from
1639 the environment variable. Raise an error if no paths
1640 are resolved.
1641
1642 Parameters
1643 ----------
1644 name: str
1645 Environment variable name
1646 spec_path_lists: list of str
1647 Paths
1648 exists: bool
1649 It True, only return existing paths.
1650
1651 Return
1652 ------
1653 str
1654 Pathsep-separated paths
1655 """
1656 # flatten spec_path_lists
1657 spec_paths = itertools.chain.from_iterable(spec_path_lists)
1658 env_paths = environ.get(name, '').split(pathsep)
1659 paths = itertools.chain(spec_paths, env_paths)
1660 extant_paths = list(filter(isdir, paths)) if exists else paths
1661 if not extant_paths:
1662 msg = "%s environment variable is empty" % name.upper()
1663 raise distutils.errors.DistutilsPlatformError(msg)
1664 unique_paths = self._unique_everseen(extant_paths)
1665 return pathsep.join(unique_paths)
1666
1667 # from Python docs
1668 @staticmethod
1669 def _unique_everseen(iterable, key=None):
1670 """
1671 List unique elements, preserving order.
1672 Remember all elements ever seen.
1673
1674 _unique_everseen('AAAABBBCCDAABBB') --> A B C D
1675
1676 _unique_everseen('ABBCcAD', str.lower) --> A B C D
1677 """
1678 seen = set()
1679 seen_add = seen.add
1680 if key is None:
1681 for element in filterfalse(seen.__contains__, iterable):
1682 seen_add(element)
1683 yield element
1684 else:
1685 for element in iterable:
1686 k = key(element)
1687 if k not in seen:
1688 seen_add(k)
1689 yield element