blob: 3eec067481fbac240481f38d85ce3e65e08f2b91 [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""CCompiler implementations for Cygwin and mingw32 versions of GCC.
2
3This module contains the CygwinCCompiler class, a subclass of
4UnixCCompiler that handles the Cygwin port of the GNU C compiler to
5Windows, and the Mingw32CCompiler class which handles the mingw32 port
6of GCC (same as cygwin in no-cygwin mode).
7"""
8
9# problems:
10#
11# * if you use a msvc compiled python version (1.5.2)
12# 1. you have to insert a __GNUC__ section in its config.h
13# 2. you have to generate a import library for its dll
14# - create a def-file for python??.dll
15# - create a import library using
16# dlltool --dllname python15.dll --def python15.def \
17# --output-lib libpython15.a
18#
19# see also http://starship.python.net/crew/kernr/mingw32/Notes.html
20#
21# * We put export_symbols in a def-file, and don't use
22# --export-all-symbols because it doesn't worked reliable in some
23# tested configurations. And because other windows compilers also
24# need their symbols specified this no serious problem.
25#
26# tested configurations:
27#
28# * cygwin gcc 2.91.57/ld 2.9.4/dllwrap 0.2.4 works
29# (after patching python's config.h and for C++ some other include files)
30# see also http://starship.python.net/crew/kernr/mingw32/Notes.html
31# * mingw32 gcc 2.95.2/ld 2.9.4/dllwrap 0.2.4 works
32# (ld doesn't support -shared, so we use dllwrap)
33# * cygwin gcc 2.95.2/ld 2.10.90/dllwrap 2.10.90 works now
34# - its dllwrap doesn't work, there is a bug in binutils 2.10.90
35# see also http://sources.redhat.com/ml/cygwin/2000-06/msg01274.html
36# - using gcc -mdll instead dllwrap doesn't work without -static because
37# it tries to link against dlls instead their import libraries. (If
38# it finds the dll first.)
39# By specifying -static we force ld to link against the import libraries,
40# this is windows standard and there are normally not the necessary symbols
41# in the dlls.
42# *** only the version of June 2000 shows these problems
43# * cygwin gcc 3.2/ld 2.13.90 works
44# (ld supports -shared)
45# * mingw gcc 3.2/ld 2.13 works
46# (ld supports -shared)
47
48
49import os
50import sys
Tarek Ziade1231a4e2011-05-19 13:07:25 +020051
52from packaging import logger
53from packaging.compiler.unixccompiler import UnixCCompiler
54from packaging.util import write_file
55from packaging.errors import PackagingExecError, CompileError, UnknownFileError
56from packaging.util import get_compiler_versions
57import sysconfig
58
59
60def get_msvcr():
61 """Include the appropriate MSVC runtime library if Python was built
62 with MSVC 7.0 or later.
63 """
64 msc_pos = sys.version.find('MSC v.')
65 if msc_pos != -1:
66 msc_ver = sys.version[msc_pos+6:msc_pos+10]
67 if msc_ver == '1300':
68 # MSVC 7.0
69 return ['msvcr70']
70 elif msc_ver == '1310':
71 # MSVC 7.1
72 return ['msvcr71']
73 elif msc_ver == '1400':
74 # VS2005 / MSVC 8.0
75 return ['msvcr80']
76 elif msc_ver == '1500':
77 # VS2008 / MSVC 9.0
78 return ['msvcr90']
79 else:
80 raise ValueError("Unknown MS Compiler version %s " % msc_ver)
81
82
83class CygwinCCompiler(UnixCCompiler):
84 """ Handles the Cygwin port of the GNU C compiler to Windows.
85 """
86 name = 'cygwin'
87 description = 'Cygwin port of GNU C Compiler for Win32'
88 obj_extension = ".o"
89 static_lib_extension = ".a"
90 shared_lib_extension = ".dll"
91 static_lib_format = "lib%s%s"
92 shared_lib_format = "%s%s"
93 exe_extension = ".exe"
94
Éric Araujo4d155462011-11-15 11:43:20 +010095 def __init__(self, dry_run=False, force=False):
96 super(CygwinCCompiler, self).__init__(dry_run, force)
Tarek Ziade1231a4e2011-05-19 13:07:25 +020097
98 status, details = check_config_h()
99 logger.debug("Python's GCC status: %s (details: %s)", status, details)
100 if status is not CONFIG_H_OK:
101 self.warn(
102 "Python's pyconfig.h doesn't seem to support your compiler. "
103 "Reason: %s. "
104 "Compiling may fail because of undefined preprocessor macros."
105 % details)
106
107 self.gcc_version, self.ld_version, self.dllwrap_version = \
108 get_compiler_versions()
109 logger.debug(self.name + ": gcc %s, ld %s, dllwrap %s\n",
110 self.gcc_version,
111 self.ld_version,
112 self.dllwrap_version)
113
114 # ld_version >= "2.10.90" and < "2.13" should also be able to use
115 # gcc -mdll instead of dllwrap
116 # Older dllwraps had own version numbers, newer ones use the
117 # same as the rest of binutils ( also ld )
118 # dllwrap 2.10.90 is buggy
119 if self.ld_version >= "2.10.90":
120 self.linker_dll = "gcc"
121 else:
122 self.linker_dll = "dllwrap"
123
124 # ld_version >= "2.13" support -shared so use it instead of
125 # -mdll -static
126 if self.ld_version >= "2.13":
127 shared_option = "-shared"
128 else:
129 shared_option = "-mdll -static"
130
131 # Hard-code GCC because that's what this is all about.
132 # XXX optimization, warnings etc. should be customizable.
133 self.set_executables(compiler='gcc -mcygwin -O -Wall',
134 compiler_so='gcc -mcygwin -mdll -O -Wall',
135 compiler_cxx='g++ -mcygwin -O -Wall',
136 linker_exe='gcc -mcygwin',
137 linker_so=('%s -mcygwin %s' %
138 (self.linker_dll, shared_option)))
139
140 # cygwin and mingw32 need different sets of libraries
141 if self.gcc_version == "2.91.57":
142 # cygwin shouldn't need msvcrt, but without the dlls will crash
143 # (gcc version 2.91.57) -- perhaps something about initialization
144 self.dll_libraries=["msvcrt"]
145 self.warn(
146 "Consider upgrading to a newer version of gcc")
147 else:
148 # Include the appropriate MSVC runtime library if Python was built
149 # with MSVC 7.0 or later.
150 self.dll_libraries = get_msvcr()
151
152 def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
153 """Compile the source by spawning GCC and windres if needed."""
154 if ext == '.rc' or ext == '.res':
155 # gcc needs '.res' and '.rc' compiled to object files !!!
156 try:
157 self.spawn(["windres", "-i", src, "-o", obj])
158 except PackagingExecError as msg:
159 raise CompileError(msg)
160 else: # for other files use the C-compiler
161 try:
162 self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
163 extra_postargs)
164 except PackagingExecError as msg:
165 raise CompileError(msg)
166
167 def link(self, target_desc, objects, output_filename, output_dir=None,
168 libraries=None, library_dirs=None, runtime_library_dirs=None,
169 export_symbols=None, debug=False, extra_preargs=None,
170 extra_postargs=None, build_temp=None, target_lang=None):
171 """Link the objects."""
172 # use separate copies, so we can modify the lists
Éric Araujo088025f2011-06-04 18:45:40 +0200173 extra_preargs = list(extra_preargs or [])
174 libraries = list(libraries or [])
175 objects = list(objects or [])
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200176
177 # Additional libraries
178 libraries.extend(self.dll_libraries)
179
180 # handle export symbols by creating a def-file
181 # with executables this only works with gcc/ld as linker
182 if ((export_symbols is not None) and
183 (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
184 # (The linker doesn't do anything if output is up-to-date.
185 # So it would probably better to check if we really need this,
186 # but for this we had to insert some unchanged parts of
187 # UnixCCompiler, and this is not what we want.)
188
189 # we want to put some files in the same directory as the
190 # object files are, build_temp doesn't help much
191 # where are the object files
192 temp_dir = os.path.dirname(objects[0])
193 # name of dll to give the helper files the same base name
194 dll_name, dll_extension = os.path.splitext(
195 os.path.basename(output_filename))
196
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
201 # Generate .def file
202 contents = [
203 "LIBRARY %s" % os.path.basename(output_filename),
204 "EXPORTS"]
205 for sym in export_symbols:
206 contents.append(sym)
207 self.execute(write_file, (def_file, contents),
208 "writing %s" % def_file)
209
210 # next add options for def-file and to creating import libraries
211
212 # dllwrap uses different options than gcc/ld
213 if self.linker_dll == "dllwrap":
214 extra_preargs.extend(("--output-lib", lib_file))
215 # for dllwrap we have to use a special option
216 extra_preargs.extend(("--def", def_file))
217 # we use gcc/ld here and can be sure ld is >= 2.9.10
218 else:
219 # doesn't work: bfd_close build\...\libfoo.a: Invalid operation
220 #extra_preargs.extend(("-Wl,--out-implib,%s" % lib_file))
221 # for gcc/ld the def-file is specified as any object files
222 objects.append(def_file)
223
224 #end: if ((export_symbols is not None) and
225 # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")):
226
227 # who wants symbols and a many times larger output file
228 # should explicitly switch the debug mode on
229 # otherwise we let dllwrap/ld strip the output file
230 # (On my machine: 10KB < stripped_file < ??100KB
231 # unstripped_file = stripped_file + XXX KB
232 # ( XXX=254 for a typical python extension))
233 if not debug:
234 extra_preargs.append("-s")
235
Éric Araujoe749e212011-11-14 19:40:31 +0100236 super(CygwinCCompiler, self).link(
237 target_desc, objects, output_filename, output_dir, libraries,
238 library_dirs, runtime_library_dirs,
239 None, # export_symbols, we do this in our def-file
240 debug, extra_preargs, extra_postargs, build_temp, target_lang)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200241
242 # -- Miscellaneous methods -----------------------------------------
243
244 def object_filenames(self, source_filenames, strip_dir=False,
245 output_dir=''):
246 """Adds supports for rc and res files."""
247 if output_dir is None:
248 output_dir = ''
249 obj_names = []
250 for src_name in source_filenames:
251 # use normcase to make sure '.rc' is really '.rc' and not '.RC'
252 base, ext = os.path.splitext(os.path.normcase(src_name))
253 if ext not in (self.src_extensions + ['.rc','.res']):
254 raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name))
255 if strip_dir:
Éric Araujo80223142011-10-14 17:04:39 +0200256 base = os.path.basename(base)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200257 if ext in ('.res', '.rc'):
258 # these need to be compiled to object files
Éric Araujo80223142011-10-14 17:04:39 +0200259 obj_names.append(os.path.join(output_dir,
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200260 base + ext + self.obj_extension))
261 else:
Éric Araujo80223142011-10-14 17:04:39 +0200262 obj_names.append(os.path.join(output_dir,
263 base + self.obj_extension))
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200264 return obj_names
265
266# the same as cygwin plus some additional parameters
267class Mingw32CCompiler(CygwinCCompiler):
268 """ Handles the Mingw32 port of the GNU C compiler to Windows.
269 """
270 name = 'mingw32'
271 description = 'MinGW32 compiler'
272
Éric Araujo4d155462011-11-15 11:43:20 +0100273 def __init__(self, dry_run=False, force=False):
274 super(Mingw32CCompiler, self).__init__(dry_run, force)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200275
276 # ld_version >= "2.13" support -shared so use it instead of
277 # -mdll -static
278 if self.ld_version >= "2.13":
279 shared_option = "-shared"
280 else:
281 shared_option = "-mdll -static"
282
283 # A real mingw32 doesn't need to specify a different entry point,
284 # but cygwin 2.91.57 in no-cygwin-mode needs it.
285 if self.gcc_version <= "2.91.57":
286 entry_point = '--entry _DllMain@12'
287 else:
288 entry_point = ''
289
290 self.set_executables(compiler='gcc -mno-cygwin -O -Wall',
291 compiler_so='gcc -mno-cygwin -mdll -O -Wall',
292 compiler_cxx='g++ -mno-cygwin -O -Wall',
293 linker_exe='gcc -mno-cygwin',
294 linker_so='%s -mno-cygwin %s %s'
295 % (self.linker_dll, shared_option,
296 entry_point))
297 # Maybe we should also append -mthreads, but then the finished
298 # dlls need another dll (mingwm10.dll see Mingw32 docs)
299 # (-mthreads: Support thread-safe exception handling on `Mingw32')
300
301 # no additional libraries needed
302 self.dll_libraries=[]
303
304 # Include the appropriate MSVC runtime library if Python was built
305 # with MSVC 7.0 or later.
306 self.dll_libraries = get_msvcr()
307
308# Because these compilers aren't configured in Python's pyconfig.h file by
309# default, we should at least warn the user if he is using a unmodified
310# version.
311
312CONFIG_H_OK = "ok"
313CONFIG_H_NOTOK = "not ok"
314CONFIG_H_UNCERTAIN = "uncertain"
315
316def check_config_h():
317 """Check if the current Python installation appears amenable to building
318 extensions with GCC.
319
320 Returns a tuple (status, details), where 'status' is one of the following
321 constants:
322
323 - CONFIG_H_OK: all is well, go ahead and compile
324 - CONFIG_H_NOTOK: doesn't look good
325 - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h
326
327 'details' is a human-readable string explaining the situation.
328
329 Note there are two ways to conclude "OK": either 'sys.version' contains
330 the string "GCC" (implying that this Python was built with GCC), or the
331 installed "pyconfig.h" contains the string "__GNUC__".
332 """
333
334 # XXX since this function also checks sys.version, it's not strictly a
335 # "pyconfig.h" check -- should probably be renamed...
336 # if sys.version contains GCC then python was compiled with GCC, and the
337 # pyconfig.h file should be OK
338 if "GCC" in sys.version:
339 return CONFIG_H_OK, "sys.version mentions 'GCC'"
340
341 # let's see if __GNUC__ is mentioned in python.h
342 fn = sysconfig.get_config_h_filename()
343 try:
344 with open(fn) as config_h:
345 if "__GNUC__" in config_h.read():
346 return CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn
347 else:
348 return CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn
349 except IOError as exc:
350 return (CONFIG_H_UNCERTAIN,
351 "couldn't read '%s': %s" % (fn, exc.strerror))