cygwinccompiler.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. from subprocess import Popen, PIPE, check_output
  51. import re
  52. import distutils.version
  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
  58. from distutils.spawn import find_executable
  59. def get_msvcr():
  60. """Include the appropriate MSVC runtime library if Python was built
  61. with MSVC 7.0 or later.
  62. """
  63. msc_pos = sys.version.find('MSC v.')
  64. if msc_pos != -1:
  65. msc_ver = sys.version[msc_pos+6:msc_pos+10]
  66. if msc_ver == '1300':
  67. # MSVC 7.0
  68. return ['msvcr70']
  69. elif msc_ver == '1310':
  70. # MSVC 7.1
  71. return ['msvcr71']
  72. elif msc_ver == '1400':
  73. # VS2005 / MSVC 8.0
  74. return ['msvcr80']
  75. elif msc_ver == '1500':
  76. # VS2008 / MSVC 9.0
  77. return ['msvcr90']
  78. elif msc_ver == '1600':
  79. # VS2010 / MSVC 10.0
  80. return ['msvcr100']
  81. elif msc_ver == '1700':
  82. # VS2012 / MSVC 11.0
  83. return ['msvcr110']
  84. elif msc_ver == '1800':
  85. # VS2013 / MSVC 12.0
  86. return ['msvcr120']
  87. elif 1900 <= int(msc_ver) < 2000:
  88. # VS2015 / MSVC 14.0
  89. return ['ucrt', 'vcruntime140']
  90. else:
  91. raise ValueError("Unknown MS Compiler version %s " % msc_ver)
  92. class CygwinCCompiler(UnixCCompiler):
  93. """ Handles the Cygwin port of the GNU C compiler to Windows.
  94. """
  95. compiler_type = 'cygwin'
  96. obj_extension = ".o"
  97. static_lib_extension = ".a"
  98. shared_lib_extension = ".dll"
  99. static_lib_format = "lib%s%s"
  100. shared_lib_format = "%s%s"
  101. exe_extension = ".exe"
  102. def __init__(self, verbose=0, dry_run=0, force=0):
  103. UnixCCompiler.__init__(self, verbose, dry_run, force)
  104. status, details = check_config_h()
  105. self.debug_print("Python's GCC status: %s (details: %s)" %
  106. (status, details))
  107. if status is not CONFIG_H_OK:
  108. self.warn(
  109. "Python's pyconfig.h doesn't seem to support your compiler. "
  110. "Reason: %s. "
  111. "Compiling may fail because of undefined preprocessor macros."
  112. % details)
  113. self.cc = os.environ.get('CC', 'gcc')
  114. self.cxx = os.environ.get('CXX', 'g++')
  115. if ('gcc' in self.cc): # Start gcc workaround
  116. self.gcc_version, self.ld_version, self.dllwrap_version = \
  117. get_versions()
  118. self.debug_print(self.compiler_type + ": gcc %s, ld %s, dllwrap %s\n" %
  119. (self.gcc_version,
  120. self.ld_version,
  121. self.dllwrap_version) )
  122. # ld_version >= "2.10.90" and < "2.13" should also be able to use
  123. # gcc -mdll instead of dllwrap
  124. # Older dllwraps had own version numbers, newer ones use the
  125. # same as the rest of binutils ( also ld )
  126. # dllwrap 2.10.90 is buggy
  127. if self.ld_version >= "2.10.90":
  128. self.linker_dll = self.cc
  129. else:
  130. self.linker_dll = "dllwrap"
  131. # ld_version >= "2.13" support -shared so use it instead of
  132. # -mdll -static
  133. if self.ld_version >= "2.13":
  134. shared_option = "-shared"
  135. else:
  136. shared_option = "-mdll -static"
  137. else: # Assume linker is up to date
  138. self.linker_dll = self.cc
  139. shared_option = "-shared"
  140. self.set_executables(compiler='%s -mcygwin -O -Wall' % self.cc,
  141. compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,
  142. compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,
  143. linker_exe='%s -mcygwin' % self.cc,
  144. linker_so=('%s -mcygwin %s' %
  145. (self.linker_dll, shared_option)))
  146. # cygwin and mingw32 need different sets of libraries
  147. if ('gcc' in self.cc and self.gcc_version == "2.91.57"):
  148. # cygwin shouldn't need msvcrt, but without the dlls will crash
  149. # (gcc version 2.91.57) -- perhaps something about initialization
  150. self.dll_libraries=["msvcrt"]
  151. self.warn(
  152. "Consider upgrading to a newer version of gcc")
  153. else:
  154. # Include the appropriate MSVC runtime library if Python was built
  155. # with MSVC 7.0 or later.
  156. self.dll_libraries = get_msvcr()
  157. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  158. """Compiles the source by spawning GCC and windres if needed."""
  159. if ext == '.rc' or ext == '.res':
  160. # gcc needs '.res' and '.rc' compiled to object files !!!
  161. try:
  162. self.spawn(["windres", "-i", src, "-o", obj])
  163. except DistutilsExecError as msg:
  164. raise CompileError(msg)
  165. else: # for other files use the C-compiler
  166. try:
  167. self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
  168. extra_postargs)
  169. except DistutilsExecError as msg:
  170. raise CompileError(msg)
  171. def link(self, target_desc, objects, output_filename, output_dir=None,
  172. libraries=None, library_dirs=None, runtime_library_dirs=None,
  173. export_symbols=None, debug=0, extra_preargs=None,
  174. extra_postargs=None, build_temp=None, target_lang=None):
  175. """Link the objects."""
  176. # use separate copies, so we can modify the lists
  177. extra_preargs = copy.copy(extra_preargs or [])
  178. libraries = copy.copy(libraries or [])
  179. objects = copy.copy(objects or [])
  180. # Additional libraries
  181. libraries.extend(self.dll_libraries)
  182. # handle export symbols by creating a def-file
  183. # with executables this only works with gcc/ld as linker
  184. if ((export_symbols is not None) and
  185. (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
  186. # (The linker doesn't do anything if output is up-to-date.
  187. # So it would probably better to check if we really need this,
  188. # but for this we had to insert some unchanged parts of
  189. # UnixCCompiler, and this is not what we want.)
  190. # we want to put some files in the same directory as the
  191. # object files are, build_temp doesn't help much
  192. # where are the object files
  193. temp_dir = os.path.dirname(objects[0])
  194. # name of dll to give the helper files the same base name
  195. (dll_name, dll_extension) = os.path.splitext(
  196. os.path.basename(output_filename))
  197. # generate the filenames for these files
  198. def_file = os.path.join(temp_dir, dll_name + ".def")
  199. lib_file = os.path.join(temp_dir, 'lib' + dll_name + ".a")
  200. # Generate .def file
  201. contents = [
  202. "LIBRARY %s" % os.path.basename(output_filename),
  203. "EXPORTS"]
  204. for sym in export_symbols:
  205. contents.append(sym)
  206. self.execute(write_file, (def_file, contents),
  207. "writing %s" % def_file)
  208. # next add options for def-file and to creating import libraries
  209. # dllwrap uses different options than gcc/ld
  210. if self.linker_dll == "dllwrap":
  211. extra_preargs.extend(["--output-lib", lib_file])
  212. # for dllwrap we have to use a special option
  213. extra_preargs.extend(["--def", def_file])
  214. # we use gcc/ld here and can be sure ld is >= 2.9.10
  215. else:
  216. # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
  217. #extra_preargs.extend(["-Wl,--out-implib,%s" % lib_file])
  218. # for gcc/ld the def-file is specified as any object files
  219. objects.append(def_file)
  220. #end: if ((export_symbols is not None) and
  221. # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
  222. # who wants symbols and a many times larger output file
  223. # should explicitly switch the debug mode on
  224. # otherwise we let dllwrap/ld strip the output file
  225. # (On my machine: 10KiB < stripped_file < ??100KiB
  226. # unstripped_file = stripped_file + XXX KiB
  227. # ( XXX=254 for a typical python extension))
  228. if not debug:
  229. extra_preargs.append("-s")
  230. UnixCCompiler.link(self, target_desc, objects, output_filename,
  231. output_dir, libraries, library_dirs,
  232. runtime_library_dirs,
  233. None, # export_symbols, we do this in our def-file
  234. debug, extra_preargs, extra_postargs, build_temp,
  235. target_lang)
  236. # -- Miscellaneous methods -----------------------------------------
  237. def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
  238. """Adds supports for rc and res files."""
  239. if output_dir is None:
  240. output_dir = ''
  241. obj_names = []
  242. for src_name in source_filenames:
  243. # use normcase to make sure '.rc' is really '.rc' and not '.RC'
  244. base, ext = os.path.splitext(os.path.normcase(src_name))
  245. if ext not in (self.src_extensions + ['.rc','.res']):
  246. raise UnknownFileError("unknown file type '%s' (from '%s')" % \
  247. (ext, src_name))
  248. if strip_dir:
  249. base = os.path.basename (base)
  250. if ext in ('.res', '.rc'):
  251. # these need to be compiled to object files
  252. obj_names.append (os.path.join(output_dir,
  253. base + ext + self.obj_extension))
  254. else:
  255. obj_names.append (os.path.join(output_dir,
  256. base + self.obj_extension))
  257. return obj_names
  258. # the same as cygwin plus some additional parameters
  259. class Mingw32CCompiler(CygwinCCompiler):
  260. """ Handles the Mingw32 port of the GNU C compiler to Windows.
  261. """
  262. compiler_type = 'mingw32'
  263. def __init__(self, verbose=0, dry_run=0, force=0):
  264. CygwinCCompiler.__init__ (self, verbose, dry_run, force)
  265. # ld_version >= "2.13" support -shared so use it instead of
  266. # -mdll -static
  267. if ('gcc' in self.cc and self.ld_version < "2.13"):
  268. shared_option = "-mdll -static"
  269. else:
  270. shared_option = "-shared"
  271. # A real mingw32 doesn't need to specify a different entry point,
  272. # but cygwin 2.91.57 in no-cygwin-mode needs it.
  273. if ('gcc' in self.cc and self.gcc_version <= "2.91.57"):
  274. entry_point = '--entry _DllMain@12'
  275. else:
  276. entry_point = ''
  277. if is_cygwincc(self.cc):
  278. raise CCompilerError(
  279. 'Cygwin gcc cannot be used with --compiler=mingw32')
  280. self.set_executables(compiler='%s -O -Wall' % self.cc,
  281. compiler_so='%s -mdll -O -Wall' % self.cc,
  282. compiler_cxx='%s -O -Wall' % self.cxx,
  283. linker_exe='%s' % self.cc,
  284. linker_so='%s %s %s'
  285. % (self.linker_dll, shared_option,
  286. entry_point))
  287. # Maybe we should also append -mthreads, but then the finished
  288. # dlls need another dll (mingwm10.dll see Mingw32 docs)
  289. # (-mthreads: Support thread-safe exception handling on `Mingw32')
  290. # no additional libraries needed
  291. self.dll_libraries=[]
  292. # Include the appropriate MSVC runtime library if Python was built
  293. # with MSVC 7.0 or later.
  294. self.dll_libraries = get_msvcr()
  295. # Because these compilers aren't configured in Python's pyconfig.h file by
  296. # default, we should at least warn the user if he is using an unmodified
  297. # version.
  298. CONFIG_H_OK = "ok"
  299. CONFIG_H_NOTOK = "not ok"
  300. CONFIG_H_UNCERTAIN = "uncertain"
  301. def check_config_h():
  302. """Check if the current Python installation appears amenable to building
  303. extensions with GCC.
  304. Returns a tuple (status, details), where 'status' is one of the following
  305. constants:
  306. - CONFIG_H_OK: all is well, go ahead and compile
  307. - CONFIG_H_NOTOK: doesn't look good
  308. - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
  309. 'details' is a human-readable string explaining the situation.
  310. Note there are two ways to conclude "OK": either 'sys.version' contains
  311. the string "GCC" (implying that this Python was built with GCC), or the
  312. installed "pyconfig.h" contains the string "__GNUC__".
  313. """
  314. # XXX since this function also checks sys.version, it's not strictly a
  315. # "pyconfig.h" check -- should probably be renamed...
  316. from distutils import sysconfig
  317. # if sys.version contains GCC then python was compiled with GCC, and the
  318. # pyconfig.h file should be OK
  319. if "GCC" in sys.version:
  320. return CONFIG_H_OK, "sys.version mentions 'GCC'"
  321. # Clang would also work
  322. if "Clang" in sys.version:
  323. return CONFIG_H_OK, "sys.version mentions 'Clang'"
  324. # let's see if __GNUC__ is mentioned in python.h
  325. fn = sysconfig.get_config_h_filename()
  326. try:
  327. config_h = open(fn)
  328. try:
  329. if "__GNUC__" in config_h.read():
  330. return CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn
  331. else:
  332. return CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn
  333. finally:
  334. config_h.close()
  335. except OSError as exc:
  336. return (CONFIG_H_UNCERTAIN,
  337. "couldn't read '%s': %s" % (fn, exc.strerror))
  338. RE_VERSION = re.compile(br'(\d+\.\d+(\.\d+)*)')
  339. def _find_exe_version(cmd):
  340. """Find the version of an executable by running `cmd` in the shell.
  341. If the command is not found, or the output does not match
  342. `RE_VERSION`, returns None.
  343. """
  344. executable = cmd.split()[0]
  345. if find_executable(executable) is None:
  346. return None
  347. out = Popen(cmd, shell=True, stdout=PIPE).stdout
  348. try:
  349. out_string = out.read()
  350. finally:
  351. out.close()
  352. result = RE_VERSION.search(out_string)
  353. if result is None:
  354. return None
  355. # LooseVersion works with strings; decode
  356. ver_str = result.group(1).decode()
  357. with distutils.version.suppress_known_deprecation():
  358. return LooseVersion(ver_str)
  359. def get_versions():
  360. """ Try to find out the versions of gcc, ld and dllwrap.
  361. If not possible it returns None for it.
  362. """
  363. commands = ['gcc -dumpversion', 'ld -v', 'dllwrap --version']
  364. return tuple([_find_exe_version(cmd) for cmd in commands])
  365. def is_cygwincc(cc):
  366. '''Try to determine if the compiler that would be used is from cygwin.'''
  367. out_string = check_output([cc, '-dumpmachine'])
  368. return out_string.strip().endswith(b'cygwin')