cygwinccompiler.py 17 KB

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