ยปCore Development>Code coverage>Lib/packaging/compiler/cygwinccompiler.py

Python code coverage for Lib/packaging/compiler/cygwinccompiler.py

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