cygwinccompiler.py 16 KB

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