Path: blob/main/Tools/c-analyzer/distutils/cygwinccompiler.py
12 views
"""distutils.cygwinccompiler12Provides the CygwinCCompiler class, a subclass of UnixCCompiler that3handles the Cygwin port of the GNU C compiler to Windows. It also contains4the Mingw32CCompiler class which handles the mingw32 port of GCC (same as5cygwin in no-cygwin mode).6"""78# problems:9#10# * if you use a msvc compiled python version (1.5.2)11# 1. you have to insert a __GNUC__ section in its config.h12# 2. you have to generate an import library for its dll13# - create a def-file for python??.dll14# - create an import library using15# dlltool --dllname python15.dll --def python15.def \16# --output-lib libpython15.a17#18# see also http://starship.python.net/crew/kernr/mingw32/Notes.html19#20# * We put export_symbols in a def-file, and don't use21# --export-all-symbols because it doesn't worked reliable in some22# tested configurations. And because other windows compilers also23# need their symbols specified this no serious problem.24#25# tested configurations:26#27# * cygwin gcc 2.91.57/ld 2.9.4/dllwrap 0.2.4 works28# (after patching python's config.h and for C++ some other include files)29# see also http://starship.python.net/crew/kernr/mingw32/Notes.html30# * mingw32 gcc 2.95.2/ld 2.9.4/dllwrap 0.2.4 works31# (ld doesn't support -shared, so we use dllwrap)32# * cygwin gcc 2.95.2/ld 2.10.90/dllwrap 2.10.90 works now33# - its dllwrap doesn't work, there is a bug in binutils 2.10.9034# see also http://sources.redhat.com/ml/cygwin/2000-06/msg01274.html35# - using gcc -mdll instead dllwrap doesn't work without -static because36# it tries to link against dlls instead their import libraries. (If37# it finds the dll first.)38# By specifying -static we force ld to link against the import libraries,39# this is windows standard and there are normally not the necessary symbols40# in the dlls.41# *** only the version of June 2000 shows these problems42# * cygwin gcc 3.2/ld 2.13.90 works43# (ld supports -shared)44# * mingw gcc 3.2/ld 2.13 works45# (ld supports -shared)4647import sys48from subprocess import Popen, PIPE, check_output49import re5051from distutils.unixccompiler import UnixCCompiler52from distutils.errors import CCompilerError53from distutils.version import LooseVersion54from distutils.spawn import find_executable5556def get_msvcr():57"""Include the appropriate MSVC runtime library if Python was built58with MSVC 7.0 or later.59"""60msc_pos = sys.version.find('MSC v.')61if msc_pos != -1:62msc_ver = sys.version[msc_pos+6:msc_pos+10]63if msc_ver == '1300':64# MSVC 7.065return ['msvcr70']66elif msc_ver == '1310':67# MSVC 7.168return ['msvcr71']69elif msc_ver == '1400':70# VS2005 / MSVC 8.071return ['msvcr80']72elif msc_ver == '1500':73# VS2008 / MSVC 9.074return ['msvcr90']75elif msc_ver == '1600':76# VS2010 / MSVC 10.077return ['msvcr100']78else:79raise ValueError("Unknown MS Compiler version %s " % msc_ver)808182class CygwinCCompiler(UnixCCompiler):83""" Handles the Cygwin port of the GNU C compiler to Windows.84"""85compiler_type = 'cygwin'86obj_extension = ".o"87static_lib_extension = ".a"88shared_lib_extension = ".dll"89static_lib_format = "lib%s%s"90shared_lib_format = "%s%s"91exe_extension = ".exe"9293def __init__(self, verbose=0, dry_run=0, force=0):9495UnixCCompiler.__init__(self, verbose, dry_run, force)9697status, details = check_config_h()98self.debug_print("Python's GCC status: %s (details: %s)" %99(status, details))100if status is not CONFIG_H_OK:101self.warn(102"Python's pyconfig.h doesn't seem to support your compiler. "103"Reason: %s. "104"Compiling may fail because of undefined preprocessor macros."105% details)106107self.gcc_version, self.ld_version, self.dllwrap_version = \108get_versions()109self.debug_print(self.compiler_type + ": gcc %s, ld %s, dllwrap %s\n" %110(self.gcc_version,111self.ld_version,112self.dllwrap_version) )113114# ld_version >= "2.10.90" and < "2.13" should also be able to use115# gcc -mdll instead of dllwrap116# Older dllwraps had own version numbers, newer ones use the117# same as the rest of binutils ( also ld )118# dllwrap 2.10.90 is buggy119if self.ld_version >= "2.10.90":120self.linker_dll = "gcc"121else:122self.linker_dll = "dllwrap"123124# ld_version >= "2.13" support -shared so use it instead of125# -mdll -static126if self.ld_version >= "2.13":127shared_option = "-shared"128else:129shared_option = "-mdll -static"130131# Hard-code GCC because that's what this is all about.132# XXX optimization, warnings etc. should be customizable.133self.set_executables(compiler='gcc -mcygwin -O -Wall',134compiler_so='gcc -mcygwin -mdll -O -Wall',135compiler_cxx='g++ -mcygwin -O -Wall',136linker_exe='gcc -mcygwin',137linker_so=('%s -mcygwin %s' %138(self.linker_dll, shared_option)))139140# cygwin and mingw32 need different sets of libraries141if self.gcc_version == "2.91.57":142# cygwin shouldn't need msvcrt, but without the dlls will crash143# (gcc version 2.91.57) -- perhaps something about initialization144self.dll_libraries=["msvcrt"]145self.warn(146"Consider upgrading to a newer version of gcc")147else:148# Include the appropriate MSVC runtime library if Python was built149# with MSVC 7.0 or later.150self.dll_libraries = get_msvcr()151152153# the same as cygwin plus some additional parameters154class Mingw32CCompiler(CygwinCCompiler):155""" Handles the Mingw32 port of the GNU C compiler to Windows.156"""157compiler_type = 'mingw32'158159def __init__(self, verbose=0, dry_run=0, force=0):160161CygwinCCompiler.__init__ (self, verbose, dry_run, force)162163# ld_version >= "2.13" support -shared so use it instead of164# -mdll -static165if self.ld_version >= "2.13":166shared_option = "-shared"167else:168shared_option = "-mdll -static"169170# A real mingw32 doesn't need to specify a different entry point,171# but cygwin 2.91.57 in no-cygwin-mode needs it.172if self.gcc_version <= "2.91.57":173entry_point = '--entry _DllMain@12'174else:175entry_point = ''176177if is_cygwingcc():178raise CCompilerError(179'Cygwin gcc cannot be used with --compiler=mingw32')180181self.set_executables(compiler='gcc -O -Wall',182compiler_so='gcc -mdll -O -Wall',183compiler_cxx='g++ -O -Wall',184linker_exe='gcc',185linker_so='%s %s %s'186% (self.linker_dll, shared_option,187entry_point))188# Maybe we should also append -mthreads, but then the finished189# dlls need another dll (mingwm10.dll see Mingw32 docs)190# (-mthreads: Support thread-safe exception handling on `Mingw32')191192# no additional libraries needed193self.dll_libraries=[]194195# Include the appropriate MSVC runtime library if Python was built196# with MSVC 7.0 or later.197self.dll_libraries = get_msvcr()198199# Because these compilers aren't configured in Python's pyconfig.h file by200# default, we should at least warn the user if he is using an unmodified201# version.202203CONFIG_H_OK = "ok"204CONFIG_H_NOTOK = "not ok"205CONFIG_H_UNCERTAIN = "uncertain"206207def check_config_h():208"""Check if the current Python installation appears amenable to building209extensions with GCC.210211Returns a tuple (status, details), where 'status' is one of the following212constants:213214- CONFIG_H_OK: all is well, go ahead and compile215- CONFIG_H_NOTOK: doesn't look good216- CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h217218'details' is a human-readable string explaining the situation.219220Note there are two ways to conclude "OK": either 'sys.version' contains221the string "GCC" (implying that this Python was built with GCC), or the222installed "pyconfig.h" contains the string "__GNUC__".223"""224225# XXX since this function also checks sys.version, it's not strictly a226# "pyconfig.h" check -- should probably be renamed...227228import sysconfig229230# if sys.version contains GCC then python was compiled with GCC, and the231# pyconfig.h file should be OK232if "GCC" in sys.version:233return CONFIG_H_OK, "sys.version mentions 'GCC'"234235# let's see if __GNUC__ is mentioned in python.h236fn = sysconfig.get_config_h_filename()237try:238config_h = open(fn)239try:240if "__GNUC__" in config_h.read():241return CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn242else:243return CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn244finally:245config_h.close()246except OSError as exc:247return (CONFIG_H_UNCERTAIN,248"couldn't read '%s': %s" % (fn, exc.strerror))249250RE_VERSION = re.compile(br'(\d+\.\d+(\.\d+)*)')251252def _find_exe_version(cmd):253"""Find the version of an executable by running `cmd` in the shell.254255If the command is not found, or the output does not match256`RE_VERSION`, returns None.257"""258executable = cmd.split()[0]259if find_executable(executable) is None:260return None261out = Popen(cmd, shell=True, stdout=PIPE).stdout262try:263out_string = out.read()264finally:265out.close()266result = RE_VERSION.search(out_string)267if result is None:268return None269# LooseVersion works with strings270# so we need to decode our bytes271return LooseVersion(result.group(1).decode())272273def get_versions():274""" Try to find out the versions of gcc, ld and dllwrap.275276If not possible it returns None for it.277"""278commands = ['gcc -dumpversion', 'ld -v', 'dllwrap --version']279return tuple([_find_exe_version(cmd) for cmd in commands])280281def is_cygwingcc():282'''Try to determine if the gcc that would be used is from cygwin.'''283out_string = check_output(['gcc', '-dumpmachine'])284return out_string.strip().endswith(b'cygwin')285286287