Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/msvccompiler.py
4799 views
"""distutils.msvccompiler12Contains MSVCCompiler, an implementation of the abstract CCompiler class3for the Microsoft Visual Studio.4"""56# Written by Perry Stoll7# hacked by Robin Becker and Thomas Heller to do a better job of8# finding DevStudio (through the registry)910import sys, os11from distutils.errors import \12DistutilsExecError, DistutilsPlatformError, \13CompileError, LibError, LinkError14from distutils.ccompiler import \15CCompiler, gen_lib_options16from distutils import log1718_can_read_reg = False19try:20import winreg2122_can_read_reg = True23hkey_mod = winreg2425RegOpenKeyEx = winreg.OpenKeyEx26RegEnumKey = winreg.EnumKey27RegEnumValue = winreg.EnumValue28RegError = winreg.error2930except ImportError:31try:32import win32api33import win32con34_can_read_reg = True35hkey_mod = win32con3637RegOpenKeyEx = win32api.RegOpenKeyEx38RegEnumKey = win32api.RegEnumKey39RegEnumValue = win32api.RegEnumValue40RegError = win32api.error41except ImportError:42log.info("Warning: Can't read registry to find the "43"necessary compiler setting\n"44"Make sure that Python modules winreg, "45"win32api or win32con are installed.")46pass4748if _can_read_reg:49HKEYS = (hkey_mod.HKEY_USERS,50hkey_mod.HKEY_CURRENT_USER,51hkey_mod.HKEY_LOCAL_MACHINE,52hkey_mod.HKEY_CLASSES_ROOT)5354def read_keys(base, key):55"""Return list of registry keys."""56try:57handle = RegOpenKeyEx(base, key)58except RegError:59return None60L = []61i = 062while True:63try:64k = RegEnumKey(handle, i)65except RegError:66break67L.append(k)68i += 169return L7071def read_values(base, key):72"""Return dict of registry keys and values.7374All names are converted to lowercase.75"""76try:77handle = RegOpenKeyEx(base, key)78except RegError:79return None80d = {}81i = 082while True:83try:84name, value, type = RegEnumValue(handle, i)85except RegError:86break87name = name.lower()88d[convert_mbcs(name)] = convert_mbcs(value)89i += 190return d9192def convert_mbcs(s):93dec = getattr(s, "decode", None)94if dec is not None:95try:96s = dec("mbcs")97except UnicodeError:98pass99return s100101class MacroExpander:102def __init__(self, version):103self.macros = {}104self.load_macros(version)105106def set_macro(self, macro, path, key):107for base in HKEYS:108d = read_values(base, path)109if d:110self.macros["$(%s)" % macro] = d[key]111break112113def load_macros(self, version):114vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version115self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")116self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir")117net = r"Software\Microsoft\.NETFramework"118self.set_macro("FrameworkDir", net, "installroot")119try:120if version > 7.0:121self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")122else:123self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")124except KeyError as exc: #125raise DistutilsPlatformError(126"""Python was built with Visual Studio 2003;127extensions must be built with a compiler than can generate compatible binaries.128Visual Studio 2003 was not found on this system. If you have Cygwin installed,129you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""")130131p = r"Software\Microsoft\NET Framework Setup\Product"132for base in HKEYS:133try:134h = RegOpenKeyEx(base, p)135except RegError:136continue137key = RegEnumKey(h, 0)138d = read_values(base, r"%s\%s" % (p, key))139self.macros["$(FrameworkVersion)"] = d["version"]140141def sub(self, s):142for k, v in self.macros.items():143s = s.replace(k, v)144return s145146def get_build_version():147"""Return the version of MSVC that was used to build Python.148149For Python 2.3 and up, the version number is included in150sys.version. For earlier versions, assume the compiler is MSVC 6.151"""152prefix = "MSC v."153i = sys.version.find(prefix)154if i == -1:155return 6156i = i + len(prefix)157s, rest = sys.version[i:].split(" ", 1)158majorVersion = int(s[:-2]) - 6159if majorVersion >= 13:160# v13 was skipped and should be v14161majorVersion += 1162minorVersion = int(s[2:3]) / 10.0163# I don't think paths are affected by minor version in version 6164if majorVersion == 6:165minorVersion = 0166if majorVersion >= 6:167return majorVersion + minorVersion168# else we don't know what version of the compiler this is169return None170171def get_build_architecture():172"""Return the processor architecture.173174Possible results are "Intel" or "AMD64".175"""176177prefix = " bit ("178i = sys.version.find(prefix)179if i == -1:180return "Intel"181j = sys.version.find(")", i)182return sys.version[i+len(prefix):j]183184def normalize_and_reduce_paths(paths):185"""Return a list of normalized paths with duplicates removed.186187The current order of paths is maintained.188"""189# Paths are normalized so things like: /a and /a/ aren't both preserved.190reduced_paths = []191for p in paths:192np = os.path.normpath(p)193# XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.194if np not in reduced_paths:195reduced_paths.append(np)196return reduced_paths197198199class MSVCCompiler(CCompiler) :200"""Concrete class that implements an interface to Microsoft Visual C++,201as defined by the CCompiler abstract class."""202203compiler_type = 'msvc'204205# Just set this so CCompiler's constructor doesn't barf. We currently206# don't use the 'set_executables()' bureaucracy provided by CCompiler,207# as it really isn't necessary for this sort of single-compiler class.208# Would be nice to have a consistent interface with UnixCCompiler,209# though, so it's worth thinking about.210executables = {}211212# Private class data (need to distinguish C from C++ source for compiler)213_c_extensions = ['.c']214_cpp_extensions = ['.cc', '.cpp', '.cxx']215_rc_extensions = ['.rc']216_mc_extensions = ['.mc']217218# Needed for the filename generation methods provided by the219# base class, CCompiler.220src_extensions = (_c_extensions + _cpp_extensions +221_rc_extensions + _mc_extensions)222res_extension = '.res'223obj_extension = '.obj'224static_lib_extension = '.lib'225shared_lib_extension = '.dll'226static_lib_format = shared_lib_format = '%s%s'227exe_extension = '.exe'228229def __init__(self, verbose=0, dry_run=0, force=0):230super().__init__(verbose, dry_run, force)231self.__version = get_build_version()232self.__arch = get_build_architecture()233if self.__arch == "Intel":234# x86235if self.__version >= 7:236self.__root = r"Software\Microsoft\VisualStudio"237self.__macros = MacroExpander(self.__version)238else:239self.__root = r"Software\Microsoft\Devstudio"240self.__product = "Visual Studio version %s" % self.__version241else:242# Win64. Assume this was built with the platform SDK243self.__product = "Microsoft SDK compiler %s" % (self.__version + 6)244245self.initialized = False246247def initialize(self):248self.__paths = []249if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"):250# Assume that the SDK set up everything alright; don't try to be251# smarter252self.cc = "cl.exe"253self.linker = "link.exe"254self.lib = "lib.exe"255self.rc = "rc.exe"256self.mc = "mc.exe"257else:258self.__paths = self.get_msvc_paths("path")259260if len(self.__paths) == 0:261raise DistutilsPlatformError("Python was built with %s, "262"and extensions need to be built with the same "263"version of the compiler, but it isn't installed."264% self.__product)265266self.cc = self.find_exe("cl.exe")267self.linker = self.find_exe("link.exe")268self.lib = self.find_exe("lib.exe")269self.rc = self.find_exe("rc.exe") # resource compiler270self.mc = self.find_exe("mc.exe") # message compiler271self.set_path_env_var('lib')272self.set_path_env_var('include')273274# extend the MSVC path with the current path275try:276for p in os.environ['path'].split(';'):277self.__paths.append(p)278except KeyError:279pass280self.__paths = normalize_and_reduce_paths(self.__paths)281os.environ['path'] = ";".join(self.__paths)282283self.preprocess_options = None284if self.__arch == "Intel":285self.compile_options = [ '/nologo', '/O2', '/MD', '/W3', '/GX' ,286'/DNDEBUG']287self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX',288'/Z7', '/D_DEBUG']289else:290# Win64291self.compile_options = [ '/nologo', '/O2', '/MD', '/W3', '/GS-' ,292'/DNDEBUG']293self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',294'/Z7', '/D_DEBUG']295296self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']297if self.__version >= 7:298self.ldflags_shared_debug = [299'/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'300]301else:302self.ldflags_shared_debug = [303'/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'304]305self.ldflags_static = [ '/nologo']306307self.initialized = True308309# -- Worker methods ------------------------------------------------310311def object_filenames(self,312source_filenames,313strip_dir=0,314output_dir=''):315# Copied from ccompiler.py, extended to return .res as 'object'-file316# for .rc input file317if output_dir is None: output_dir = ''318obj_names = []319for src_name in source_filenames:320(base, ext) = os.path.splitext (src_name)321base = os.path.splitdrive(base)[1] # Chop off the drive322base = base[os.path.isabs(base):] # If abs, chop off leading /323if ext not in self.src_extensions:324# Better to raise an exception instead of silently continuing325# and later complain about sources and targets having326# different lengths327raise CompileError ("Don't know how to compile %s" % src_name)328if strip_dir:329base = os.path.basename (base)330if ext in self._rc_extensions:331obj_names.append (os.path.join (output_dir,332base + self.res_extension))333elif ext in self._mc_extensions:334obj_names.append (os.path.join (output_dir,335base + self.res_extension))336else:337obj_names.append (os.path.join (output_dir,338base + self.obj_extension))339return obj_names340341342def compile(self, sources,343output_dir=None, macros=None, include_dirs=None, debug=0,344extra_preargs=None, extra_postargs=None, depends=None):345346if not self.initialized:347self.initialize()348compile_info = self._setup_compile(output_dir, macros, include_dirs,349sources, depends, extra_postargs)350macros, objects, extra_postargs, pp_opts, build = compile_info351352compile_opts = extra_preargs or []353compile_opts.append ('/c')354if debug:355compile_opts.extend(self.compile_options_debug)356else:357compile_opts.extend(self.compile_options)358359for obj in objects:360try:361src, ext = build[obj]362except KeyError:363continue364if debug:365# pass the full pathname to MSVC in debug mode,366# this allows the debugger to find the source file367# without asking the user to browse for it368src = os.path.abspath(src)369370if ext in self._c_extensions:371input_opt = "/Tc" + src372elif ext in self._cpp_extensions:373input_opt = "/Tp" + src374elif ext in self._rc_extensions:375# compile .RC to .RES file376input_opt = src377output_opt = "/fo" + obj378try:379self.spawn([self.rc] + pp_opts +380[output_opt] + [input_opt])381except DistutilsExecError as msg:382raise CompileError(msg)383continue384elif ext in self._mc_extensions:385# Compile .MC to .RC file to .RES file.386# * '-h dir' specifies the directory for the387# generated include file388# * '-r dir' specifies the target directory of the389# generated RC file and the binary message resource390# it includes391#392# For now (since there are no options to change this),393# we use the source-directory for the include file and394# the build directory for the RC file and message395# resources. This works at least for win32all.396h_dir = os.path.dirname(src)397rc_dir = os.path.dirname(obj)398try:399# first compile .MC to .RC and .H file400self.spawn([self.mc] +401['-h', h_dir, '-r', rc_dir] + [src])402base, _ = os.path.splitext (os.path.basename (src))403rc_file = os.path.join (rc_dir, base + '.rc')404# then compile .RC to .RES file405self.spawn([self.rc] +406["/fo" + obj] + [rc_file])407408except DistutilsExecError as msg:409raise CompileError(msg)410continue411else:412# how to handle this file?413raise CompileError("Don't know how to compile %s to %s"414% (src, obj))415416output_opt = "/Fo" + obj417try:418self.spawn([self.cc] + compile_opts + pp_opts +419[input_opt, output_opt] +420extra_postargs)421except DistutilsExecError as msg:422raise CompileError(msg)423424return objects425426427def create_static_lib(self,428objects,429output_libname,430output_dir=None,431debug=0,432target_lang=None):433434if not self.initialized:435self.initialize()436(objects, output_dir) = self._fix_object_args(objects, output_dir)437output_filename = self.library_filename(output_libname,438output_dir=output_dir)439440if self._need_link(objects, output_filename):441lib_args = objects + ['/OUT:' + output_filename]442if debug:443pass # XXX what goes here?444try:445self.spawn([self.lib] + lib_args)446except DistutilsExecError as msg:447raise LibError(msg)448else:449log.debug("skipping %s (up-to-date)", output_filename)450451452def link(self,453target_desc,454objects,455output_filename,456output_dir=None,457libraries=None,458library_dirs=None,459runtime_library_dirs=None,460export_symbols=None,461debug=0,462extra_preargs=None,463extra_postargs=None,464build_temp=None,465target_lang=None):466467if not self.initialized:468self.initialize()469(objects, output_dir) = self._fix_object_args(objects, output_dir)470fixed_args = self._fix_lib_args(libraries, library_dirs,471runtime_library_dirs)472(libraries, library_dirs, runtime_library_dirs) = fixed_args473474if runtime_library_dirs:475self.warn ("I don't know what to do with 'runtime_library_dirs': "476+ str (runtime_library_dirs))477478lib_opts = gen_lib_options(self,479library_dirs, runtime_library_dirs,480libraries)481if output_dir is not None:482output_filename = os.path.join(output_dir, output_filename)483484if self._need_link(objects, output_filename):485if target_desc == CCompiler.EXECUTABLE:486if debug:487ldflags = self.ldflags_shared_debug[1:]488else:489ldflags = self.ldflags_shared[1:]490else:491if debug:492ldflags = self.ldflags_shared_debug493else:494ldflags = self.ldflags_shared495496export_opts = []497for sym in (export_symbols or []):498export_opts.append("/EXPORT:" + sym)499500ld_args = (ldflags + lib_opts + export_opts +501objects + ['/OUT:' + output_filename])502503# The MSVC linker generates .lib and .exp files, which cannot be504# suppressed by any linker switches. The .lib files may even be505# needed! Make sure they are generated in the temporary build506# directory. Since they have different names for debug and release507# builds, they can go into the same directory.508if export_symbols is not None:509(dll_name, dll_ext) = os.path.splitext(510os.path.basename(output_filename))511implib_file = os.path.join(512os.path.dirname(objects[0]),513self.library_filename(dll_name))514ld_args.append ('/IMPLIB:' + implib_file)515516if extra_preargs:517ld_args[:0] = extra_preargs518if extra_postargs:519ld_args.extend(extra_postargs)520521self.mkpath(os.path.dirname(output_filename))522try:523self.spawn([self.linker] + ld_args)524except DistutilsExecError as msg:525raise LinkError(msg)526527else:528log.debug("skipping %s (up-to-date)", output_filename)529530531# -- Miscellaneous methods -----------------------------------------532# These are all used by the 'gen_lib_options() function, in533# ccompiler.py.534535def library_dir_option(self, dir):536return "/LIBPATH:" + dir537538def runtime_library_dir_option(self, dir):539raise DistutilsPlatformError(540"don't know how to set runtime library search path for MSVC++")541542def library_option(self, lib):543return self.library_filename(lib)544545546def find_library_file(self, dirs, lib, debug=0):547# Prefer a debugging library if found (and requested), but deal548# with it if we don't have one.549if debug:550try_names = [lib + "_d", lib]551else:552try_names = [lib]553for dir in dirs:554for name in try_names:555libfile = os.path.join(dir, self.library_filename (name))556if os.path.exists(libfile):557return libfile558else:559# Oops, didn't find it in *any* of 'dirs'560return None561562# Helper methods for using the MSVC registry settings563564def find_exe(self, exe):565"""Return path to an MSVC executable program.566567Tries to find the program in several places: first, one of the568MSVC program search paths from the registry; next, the directories569in the PATH environment variable. If any of those work, return an570absolute path that is known to exist. If none of them work, just571return the original program name, 'exe'.572"""573for p in self.__paths:574fn = os.path.join(os.path.abspath(p), exe)575if os.path.isfile(fn):576return fn577578# didn't find it; try existing path579for p in os.environ['Path'].split(';'):580fn = os.path.join(os.path.abspath(p),exe)581if os.path.isfile(fn):582return fn583584return exe585586def get_msvc_paths(self, path, platform='x86'):587"""Get a list of devstudio directories (include, lib or path).588589Return a list of strings. The list will be empty if unable to590access the registry or appropriate registry keys not found.591"""592if not _can_read_reg:593return []594595path = path + " dirs"596if self.__version >= 7:597key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories"598% (self.__root, self.__version))599else:600key = (r"%s\6.0\Build System\Components\Platforms"601r"\Win32 (%s)\Directories" % (self.__root, platform))602603for base in HKEYS:604d = read_values(base, key)605if d:606if self.__version >= 7:607return self.__macros.sub(d[path]).split(";")608else:609return d[path].split(";")610# MSVC 6 seems to create the registry entries we need only when611# the GUI is run.612if self.__version == 6:613for base in HKEYS:614if read_values(base, r"%s\6.0" % self.__root) is not None:615self.warn("It seems you have Visual Studio 6 installed, "616"but the expected registry settings are not present.\n"617"You must at least run the Visual Studio GUI once "618"so that these entries are created.")619break620return []621622def set_path_env_var(self, name):623"""Set environment variable 'name' to an MSVC path type value.624625This is equivalent to a SET command prior to execution of spawned626commands.627"""628629if name == "lib":630p = self.get_msvc_paths("library")631else:632p = self.get_msvc_paths(name)633if p:634os.environ[name] = ';'.join(p)635636637if get_build_version() >= 8.0:638log.debug("Importing new compiler from distutils.msvc9compiler")639OldMSVCCompiler = MSVCCompiler640from distutils.msvc9compiler import MSVCCompiler641# get_build_architecture not really relevant now we support cross-compile642from distutils.msvc9compiler import MacroExpander643644645