cygwinccompiler.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. """distutils.cygwinccompiler
  2. Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
  3. handles the Cygwin port of the GNU C compiler to Windows. It also contains
  4. the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
  5. cygwin in no-cygwin mode).
  6. """
  7. # problems:
  8. #
  9. # * if you use a msvc compiled python version (1.5.2)
  10. # 1. you have to insert a __GNUC__ section in its config.h
  11. # 2. you have to generate an import library for its dll
  12. # - create a def-file for python??.dll
  13. # - create an import library using
  14. # dlltool --dllname python15.dll --def python15.def \
  15. # --output-lib libpython15.a
  16. #
  17. # see also http://starship.python.net/crew/kernr/mingw32/Notes.html
  18. #
  19. # * We put export_symbols in a def-file, and don't use
  20. # --export-all-symbols because it doesn't worked reliable in some
  21. # tested configurations. And because other windows compilers also
  22. # need their symbols specified this no serious problem.
  23. #
  24. # tested configurations:
  25. #
  26. # * cygwin gcc 2.91.57/ld 2.9.4/dllwrap 0.2.4 works
  27. # (after patching python's config.h and for C++ some other include files)
  28. # see also http://starship.python.net/crew/kernr/mingw32/Notes.html
  29. # * mingw32 gcc 2.95.2/ld 2.9.4/dllwrap 0.2.4 works
  30. # (ld doesn't support -shared, so we use dllwrap)
  31. # * cygwin gcc 2.95.2/ld 2.10.90/dllwrap 2.10.90 works now
  32. # - its dllwrap doesn't work, there is a bug in binutils 2.10.90
  33. # see also http://sources.redhat.com/ml/cygwin/2000-06/msg01274.html
  34. # - using gcc -mdll instead dllwrap doesn't work without -static because
  35. # it tries to link against dlls instead their import libraries. (If
  36. # it finds the dll first.)
  37. # By specifying -static we force ld to link against the import libraries,
  38. # this is windows standard and there are normally not the necessary symbols
  39. # in the dlls.
  40. # *** only the version of June 2000 shows these problems
  41. # * cygwin gcc 3.2/ld 2.13.90 works
  42. # (ld supports -shared)
  43. # * mingw gcc 3.2/ld 2.13 works
  44. # (ld supports -shared)
  45. # * llvm-mingw with Clang 11 works
  46. # (lld supports -shared)
  47. import os
  48. import sys
  49. import copy
  50. import shlex
  51. import warnings
  52. from subprocess import check_output
  53. from distutils.unixccompiler import UnixCCompiler
  54. from distutils.file_util import write_file
  55. from distutils.errors import (DistutilsExecError, CCompilerError,
  56. CompileError, UnknownFileError)
  57. from distutils.version import LooseVersion, suppress_known_deprecation
  58. def get_msvcr():
  59. """Include the appropriate MSVC runtime library if Python was built
  60. with MSVC 7.0 or later.
  61. """
  62. msc_pos = sys.version.find('MSC v.')
  63. if msc_pos != -1:
  64. msc_ver = sys.version[msc_pos+6:msc_pos+10]
  65. if msc_ver == '1300':
  66. # MSVC 7.0
  67. return ['msvcr70']
  68. elif msc_ver == '1310':
  69. # MSVC 7.1
  70. return ['msvcr71']
  71. elif msc_ver == '1400':
  72. # VS2005 / MSVC 8.0
  73. return ['msvcr80']
  74. elif msc_ver == '1500':
  75. # VS2008 / MSVC 9.0
  76. return ['msvcr90']
  77. elif msc_ver == '1600':
  78. # VS2010 / MSVC 10.0
  79. return ['msvcr100']
  80. elif msc_ver == '1700':
  81. # VS2012 / MSVC 11.0
  82. return ['msvcr110']
  83. elif msc_ver == '1800':
  84. # VS2013 / MSVC 12.0
  85. return ['msvcr120']
  86. elif 1900 <= int(msc_ver) < 2000:
  87. # VS2015 / MSVC 14.0
  88. return ['ucrt', 'vcruntime140']
  89. else:
  90. raise ValueError("Unknown MS Compiler version %s " % msc_ver)
  91. class CygwinCCompiler(UnixCCompiler):
  92. """ Handles the Cygwin port of the GNU C compiler to Windows.
  93. """
  94. compiler_type = 'cygwin'
  95. obj_extension = ".o"
  96. static_lib_extension = ".a"
  97. shared_lib_extension = ".dll"
  98. static_lib_format = "lib%s%s"
  99. shared_lib_format = "%s%s"
  100. exe_extension = ".exe"
  101. def __init__(self, verbose=0, dry_run=0, force=0):
  102. super().__init__(verbose, dry_run, force)
  103. status, details = check_config_h()
  104. self.debug_print("Python's GCC status: %s (details: %s)" %
  105. (status, details))
  106. if status is not CONFIG_H_OK:
  107. self.warn(
  108. "Python's pyconfig.h doesn't seem to support your compiler. "
  109. "Reason: %s. "
  110. "Compiling may fail because of undefined preprocessor macros."
  111. % details)
  112. self.cc = os.environ.get('CC', 'gcc')
  113. self.cxx = os.environ.get('CXX', 'g++')
  114. self.linker_dll = self.cc
  115. shared_option = "-shared"
  116. self.set_executables(compiler='%s -mcygwin -O -Wall' % self.cc,
  117. compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,
  118. compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,
  119. linker_exe='%s -mcygwin' % self.cc,
  120. linker_so=('%s -mcygwin %s' %
  121. (self.linker_dll, shared_option)))
  122. # Include the appropriate MSVC runtime library if Python was built
  123. # with MSVC 7.0 or later.
  124. self.dll_libraries = get_msvcr()
  125. @property
  126. def gcc_version(self):
  127. # Older numpy dependend on this existing to check for ancient
  128. # gcc versions. This doesn't make much sense with clang etc so
  129. # just hardcode to something recent.
  130. # https://github.com/numpy/numpy/pull/20333
  131. warnings.warn(
  132. "gcc_version attribute of CygwinCCompiler is deprecated. "
  133. "Instead of returning actual gcc version a fixed value 11.2.0 is returned.",
  134. DeprecationWarning,
  135. stacklevel=2,
  136. )
  137. with suppress_known_deprecation():
  138. return LooseVersion("11.2.0")
  139. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  140. """Compiles the source by spawning GCC and windres if needed."""
  141. if ext == '.rc' or ext == '.res':
  142. # gcc needs '.res' and '.rc' compiled to object files !!!
  143. try:
  144. self.spawn(["windres", "-i", src, "-o", obj])
  145. except DistutilsExecError as msg:
  146. raise CompileError(msg)
  147. else: # for other files use the C-compiler
  148. try:
  149. self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
  150. extra_postargs)
  151. except DistutilsExecError as msg:
  152. raise CompileError(msg)
  153. def link(self, target_desc, objects, output_filename, output_dir=None,
  154. libraries=None, library_dirs=None, runtime_library_dirs=None,
  155. export_symbols=None, debug=0, extra_preargs=None,
  156. extra_postargs=None, build_temp=None, target_lang=None):
  157. """Link the objects."""
  158. # use separate copies, so we can modify the lists
  159. extra_preargs = copy.copy(extra_preargs or [])
  160. libraries = copy.copy(libraries or [])
  161. objects = copy.copy(objects or [])
  162. # Additional libraries
  163. libraries.extend(self.dll_libraries)
  164. # handle export symbols by creating a def-file
  165. # with executables this only works with gcc/ld as linker
  166. if ((export_symbols is not None) and
  167. (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
  168. # (The linker doesn't do anything if output is up-to-date.
  169. # So it would probably better to check if we really need this,
  170. # but for this we had to insert some unchanged parts of
  171. # UnixCCompiler, and this is not what we want.)
  172. # we want to put some files in the same directory as the
  173. # object files are, build_temp doesn't help much
  174. # where are the object files
  175. temp_dir = os.path.dirname(objects[0])
  176. # name of dll to give the helper files the same base name
  177. (dll_name, dll_extension) = os.path.splitext(
  178. os.path.basename(output_filename))
  179. # generate the filenames for these files
  180. def_file = os.path.join(temp_dir, dll_name + ".def")
  181. lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
  182. # Generate .def file
  183. contents = [
  184. "LIBRARY %s" % os.path.basename(output_filename),
  185. "EXPORTS"]
  186. for sym in export_symbols:
  187. contents.append(sym)
  188. self.execute(write_file, (def_file, contents),
  189. "writing %s" % def_file)
  190. # next add options for def-file and to creating import libraries
  191. # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
  192. #extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
  193. # for gcc/ld the def-file is specified as any object files
  194. objects.append(def_file)
  195. #end: if ((export_symbols is not None) and
  196. # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
  197. # who wants symbols and a many times larger output file
  198. # should explicitly switch the debug mode on
  199. # otherwise we let ld strip the output file
  200. # (On my machine: 10KiB < stripped_file < ??100KiB
  201. # unstripped_file = stripped_file + XXX KiB
  202. # ( XXX=254 for a typical python extension))
  203. if not debug:
  204. extra_preargs.append("-s")
  205. UnixCCompiler.link(self, target_desc, objects, output_filename,
  206. output_dir, libraries, library_dirs,
  207. runtime_library_dirs,
  208. None, # export_symbols, we do this in our def-file
  209. debug, extra_preargs, extra_postargs, build_temp,
  210. target_lang)
  211. # -- Miscellaneous methods -----------------------------------------
  212. def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
  213. """Adds supports for rc and res files."""
  214. if output_dir is None:
  215. output_dir = ''
  216. obj_names = []
  217. for src_name in source_filenames:
  218. # use normcase to make sure '.rc' is really '.rc' and not '.RC'
  219. base, ext = os.path.splitext(os.path.normcase(src_name))
  220. if ext not in (self.src_extensions + ['.rc','.res']):
  221. raise UnknownFileError("unknown file type '%s' (from '%s')" % \
  222. (ext, src_name))
  223. if strip_dir:
  224. base = os.path.basename (base)
  225. if ext in ('.res', '.rc'):
  226. # these need to be compiled to object files
  227. obj_names.append (os.path.join(output_dir,
  228. base + ext + self.obj_extension))
  229. else:
  230. obj_names.append (os.path.join(output_dir,
  231. base + self.obj_extension))
  232. return obj_names
  233. # the same as cygwin plus some additional parameters
  234. class Mingw32CCompiler(CygwinCCompiler):
  235. """ Handles the Mingw32 port of the GNU C compiler to Windows.
  236. """
  237. compiler_type = 'mingw32'
  238. def __init__(self, verbose=0, dry_run=0, force=0):
  239. super().__init__ (verbose, dry_run, force)
  240. shared_option = "-shared"
  241. if is_cygwincc(self.cc):
  242. raise CCompilerError(
  243. 'Cygwin gcc cannot be used with --compiler=mingw32')
  244. self.set_executables(compiler='%s -O -Wall' % self.cc,
  245. compiler_so='%s -mdll -O -Wall' % self.cc,
  246. compiler_cxx='%s -O -Wall' % self.cxx,
  247. linker_exe='%s' % self.cc,
  248. linker_so='%s %s'
  249. % (self.linker_dll, shared_option))
  250. # Maybe we should also append -mthreads, but then the finished
  251. # dlls need another dll (mingwm10.dll see Mingw32 docs)
  252. # (-mthreads: Support thread-safe exception handling on `Mingw32')
  253. # no additional libraries needed
  254. self.dll_libraries=[]
  255. # Include the appropriate MSVC runtime library if Python was built
  256. # with MSVC 7.0 or later.
  257. self.dll_libraries = get_msvcr()
  258. # Because these compilers aren't configured in Python's pyconfig.h file by
  259. # default, we should at least warn the user if he is using an unmodified
  260. # version.
  261. CONFIG_H_OK = "ok"
  262. CONFIG_H_NOTOK = "not ok"
  263. CONFIG_H_UNCERTAIN = "uncertain"
  264. def check_config_h():
  265. """Check if the current Python installation appears amenable to building
  266. extensions with GCC.
  267. Returns a tuple (status, details), where 'status' is one of the following
  268. constants:
  269. - CONFIG_H_OK: all is well, go ahead and compile
  270. - CONFIG_H_NOTOK: doesn't look good
  271. - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
  272. 'details' is a human-readable string explaining the situation.
  273. Note there are two ways to conclude "OK": either 'sys.version' contains
  274. the string "GCC" (implying that this Python was built with GCC), or the
  275. installed "pyconfig.h" contains the string "__GNUC__".
  276. """
  277. # XXX since this function also checks sys.version, it's not strictly a
  278. # "pyconfig.h" check -- should probably be renamed...
  279. from distutils import sysconfig
  280. # if sys.version contains GCC then python was compiled with GCC, and the
  281. # pyconfig.h file should be OK
  282. if "GCC" in sys.version:
  283. return CONFIG_H_OK, "sys.version mentions 'GCC'"
  284. # Clang would also work
  285. if "Clang" in sys.version:
  286. return CONFIG_H_OK, "sys.version mentions 'Clang'"
  287. # let's see if __GNUC__ is mentioned in python.h
  288. fn = sysconfig.get_config_h_filename()
  289. try:
  290. config_h = open(fn)
  291. try:
  292. if "__GNUC__" in config_h.read():
  293. return CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn
  294. else:
  295. return CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn
  296. finally:
  297. config_h.close()
  298. except OSError as exc:
  299. return (CONFIG_H_UNCERTAIN,
  300. "couldn't read '%s': %s" % (fn, exc.strerror))
  301. def is_cygwincc(cc):
  302. '''Try to determine if the compiler that would be used is from cygwin.'''
  303. out_string = check_output(shlex.split(cc) + ['-dumpmachine'])
  304. return out_string.strip().endswith(b'cygwin')
  305. get_versions = None
  306. """
  307. A stand-in for the previous get_versions() function to prevent failures
  308. when monkeypatched. See pypa/setuptools#2969.
  309. """