cygwinccompiler.py 16 KB

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