PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/distutils/cygwinccompiler.py

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