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

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

#countcontent
1n/a"""Abstract base class for compilers.
2n/a
3n/aThis modules contains CCompiler, an abstract base class that defines the
4n/ainterface for the compiler abstraction model used by packaging.
5n/a"""
6n/a
7n/aimport os
8n/afrom shutil import move
9n/afrom packaging import logger
10n/afrom packaging.util import split_quoted, execute, newer_group, spawn
11n/afrom packaging.errors import (CompileError, LinkError, UnknownFileError)
12n/afrom packaging.compiler import gen_preprocess_options
13n/a
14n/a
15n/aclass CCompiler:
16n/a """Abstract base class to define the interface that must be implemented
17n/a by real compiler classes. Also has some utility methods used by
18n/a several compiler classes.
19n/a
20n/a The basic idea behind a compiler abstraction class is that each
21n/a instance can be used for all the compile/link steps in building a
22n/a single project. Thus, attributes common to all of those compile and
23n/a link steps -- include directories, macros to define, libraries to link
24n/a against, etc. -- are attributes of the compiler instance. To allow for
25n/a variability in how individual files are treated, most of those
26n/a attributes may be varied on a per-compilation or per-link basis.
27n/a """
28n/a
29n/a # 'name' is a class attribute that identifies this class. It
30n/a # keeps code that wants to know what kind of compiler it's dealing with
31n/a # from having to import all possible compiler classes just to do an
32n/a # 'isinstance'.
33n/a name = None
34n/a description = None
35n/a
36n/a # XXX things not handled by this compiler abstraction model:
37n/a # * client can't provide additional options for a compiler,
38n/a # e.g. warning, optimization, debugging flags. Perhaps this
39n/a # should be the domain of concrete compiler abstraction classes
40n/a # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
41n/a # class should have methods for the common ones.
42n/a # * can't completely override the include or library searchg
43n/a # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
44n/a # I'm not sure how widely supported this is even by Unix
45n/a # compilers, much less on other platforms. And I'm even less
46n/a # sure how useful it is; maybe for cross-compiling, but
47n/a # support for that is a ways off. (And anyways, cross
48n/a # compilers probably have a dedicated binary with the
49n/a # right paths compiled in. I hope.)
50n/a # * can't do really freaky things with the library list/library
51n/a # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
52n/a # different versions of libfoo.a in different locations. I
53n/a # think this is useless without the ability to null out the
54n/a # library search path anyways.
55n/a
56n/a
57n/a # Subclasses that rely on the standard filename generation methods
58n/a # implemented below should override these; see the comment near
59n/a # those methods ('object_filenames()' et. al.) for details:
60n/a src_extensions = None # list of strings
61n/a obj_extension = None # string
62n/a static_lib_extension = None
63n/a shared_lib_extension = None # string
64n/a static_lib_format = None # format string
65n/a shared_lib_format = None # prob. same as static_lib_format
66n/a exe_extension = None # string
67n/a
68n/a # Default language settings. language_map is used to detect a source
69n/a # file or Extension target language, checking source filenames.
70n/a # language_order is used to detect the language precedence, when deciding
71n/a # what language to use when mixing source types. For example, if some
72n/a # extension has two files with ".c" extension, and one with ".cpp", it
73n/a # is still linked as c++.
74n/a language_map = {".c": "c",
75n/a ".cc": "c++",
76n/a ".cpp": "c++",
77n/a ".cxx": "c++",
78n/a ".m": "objc",
79n/a }
80n/a language_order = ["c++", "objc", "c"]
81n/a
82n/a def __init__(self, dry_run=False, force=False):
83n/a self.dry_run = dry_run
84n/a self.force = force
85n/a
86n/a # 'output_dir': a common output directory for object, library,
87n/a # shared object, and shared library files
88n/a self.output_dir = None
89n/a
90n/a # 'macros': a list of macro definitions (or undefinitions). A
91n/a # macro definition is a 2-tuple (name, value), where the value is
92n/a # either a string or None (no explicit value). A macro
93n/a # undefinition is a 1-tuple (name,).
94n/a self.macros = []
95n/a
96n/a # 'include_dirs': a list of directories to search for include files
97n/a self.include_dirs = []
98n/a
99n/a # 'libraries': a list of libraries to include in any link
100n/a # (library names, not filenames: eg. "foo" not "libfoo.a")
101n/a self.libraries = []
102n/a
103n/a # 'library_dirs': a list of directories to search for libraries
104n/a self.library_dirs = []
105n/a
106n/a # 'runtime_library_dirs': a list of directories to search for
107n/a # shared libraries/objects at runtime
108n/a self.runtime_library_dirs = []
109n/a
110n/a # 'objects': a list of object files (or similar, such as explicitly
111n/a # named library files) to include on any link
112n/a self.objects = []
113n/a
114n/a for key, value in self.executables.items():
115n/a self.set_executable(key, value)
116n/a
117n/a def set_executables(self, **args):
118n/a """Define the executables (and options for them) that will be run
119n/a to perform the various stages of compilation. The exact set of
120n/a executables that may be specified here depends on the compiler
121n/a class (via the 'executables' class attribute), but most will have:
122n/a compiler the C/C++ compiler
123n/a linker_so linker used to create shared objects and libraries
124n/a linker_exe linker used to create binary executables
125n/a archiver static library creator
126n/a
127n/a On platforms with a command line (Unix, DOS/Windows), each of these
128n/a is a string that will be split into executable name and (optional)
129n/a list of arguments. (Splitting the string is done similarly to how
130n/a Unix shells operate: words are delimited by spaces, but quotes and
131n/a backslashes can override this. See
132n/a 'distutils.util.split_quoted()'.)
133n/a """
134n/a
135n/a # Note that some CCompiler implementation classes will define class
136n/a # attributes 'cpp', 'cc', etc. with hard-coded executable names;
137n/a # this is appropriate when a compiler class is for exactly one
138n/a # compiler/OS combination (eg. MSVCCompiler). Other compiler
139n/a # classes (UnixCCompiler, in particular) are driven by information
140n/a # discovered at run-time, since there are many different ways to do
141n/a # basically the same things with Unix C compilers.
142n/a
143n/a for key, value in args.items():
144n/a if key not in self.executables:
145n/a raise ValueError("unknown executable '%s' for class %s" % \
146n/a (key, self.__class__.__name__))
147n/a self.set_executable(key, value)
148n/a
149n/a def set_executable(self, key, value):
150n/a if isinstance(value, str):
151n/a setattr(self, key, split_quoted(value))
152n/a else:
153n/a setattr(self, key, value)
154n/a
155n/a def _find_macro(self, name):
156n/a i = 0
157n/a for defn in self.macros:
158n/a if defn[0] == name:
159n/a return i
160n/a i = i + 1
161n/a return None
162n/a
163n/a def _check_macro_definitions(self, definitions):
164n/a """Ensures that every element of 'definitions' is a valid macro
165n/a definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
166n/a nothing if all definitions are OK, raise TypeError otherwise.
167n/a """
168n/a for defn in definitions:
169n/a if not (isinstance(defn, tuple) and
170n/a (len(defn) == 1 or
171n/a (len(defn) == 2 and
172n/a (isinstance(defn[1], str) or defn[1] is None))) and
173n/a isinstance(defn[0], str)):
174n/a raise TypeError(("invalid macro definition '%s': " % defn) + \
175n/a "must be tuple (string,), (string, string), or " + \
176n/a "(string, None)")
177n/a
178n/a
179n/a # -- Bookkeeping methods -------------------------------------------
180n/a
181n/a def define_macro(self, name, value=None):
182n/a """Define a preprocessor macro for all compilations driven by this
183n/a compiler object. The optional parameter 'value' should be a
184n/a string; if it is not supplied, then the macro will be defined
185n/a without an explicit value and the exact outcome depends on the
186n/a compiler used (XXX true? does ANSI say anything about this?)
187n/a """
188n/a # Delete from the list of macro definitions/undefinitions if
189n/a # already there (so that this one will take precedence).
190n/a i = self._find_macro(name)
191n/a if i is not None:
192n/a del self.macros[i]
193n/a
194n/a defn = (name, value)
195n/a self.macros.append(defn)
196n/a
197n/a def undefine_macro(self, name):
198n/a """Undefine a preprocessor macro for all compilations driven by
199n/a this compiler object. If the same macro is defined by
200n/a 'define_macro()' and undefined by 'undefine_macro()' the last call
201n/a takes precedence (including multiple redefinitions or
202n/a undefinitions). If the macro is redefined/undefined on a
203n/a per-compilation basis (ie. in the call to 'compile()'), then that
204n/a takes precedence.
205n/a """
206n/a # Delete from the list of macro definitions/undefinitions if
207n/a # already there (so that this one will take precedence).
208n/a i = self._find_macro(name)
209n/a if i is not None:
210n/a del self.macros[i]
211n/a
212n/a undefn = (name,)
213n/a self.macros.append(undefn)
214n/a
215n/a def add_include_dir(self, dir):
216n/a """Add 'dir' to the list of directories that will be searched for
217n/a header files. The compiler is instructed to search directories in
218n/a the order in which they are supplied by successive calls to
219n/a 'add_include_dir()'.
220n/a """
221n/a self.include_dirs.append(dir)
222n/a
223n/a def set_include_dirs(self, dirs):
224n/a """Set the list of directories that will be searched to 'dirs' (a
225n/a list of strings). Overrides any preceding calls to
226n/a 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
227n/a to the list passed to 'set_include_dirs()'. This does not affect
228n/a any list of standard include directories that the compiler may
229n/a search by default.
230n/a """
231n/a self.include_dirs = dirs[:]
232n/a
233n/a def add_library(self, libname):
234n/a """Add 'libname' to the list of libraries that will be included in
235n/a all links driven by this compiler object. Note that 'libname'
236n/a should *not* be the name of a file containing a library, but the
237n/a name of the library itself: the actual filename will be inferred by
238n/a the linker, the compiler, or the compiler class (depending on the
239n/a platform).
240n/a
241n/a The linker will be instructed to link against libraries in the
242n/a order they were supplied to 'add_library()' and/or
243n/a 'set_libraries()'. It is perfectly valid to duplicate library
244n/a names; the linker will be instructed to link against libraries as
245n/a many times as they are mentioned.
246n/a """
247n/a self.libraries.append(libname)
248n/a
249n/a def set_libraries(self, libnames):
250n/a """Set the list of libraries to be included in all links driven by
251n/a this compiler object to 'libnames' (a list of strings). This does
252n/a not affect any standard system libraries that the linker may
253n/a include by default.
254n/a """
255n/a self.libraries = libnames[:]
256n/a
257n/a
258n/a def add_library_dir(self, dir):
259n/a """Add 'dir' to the list of directories that will be searched for
260n/a libraries specified to 'add_library()' and 'set_libraries()'. The
261n/a linker will be instructed to search for libraries in the order they
262n/a are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
263n/a """
264n/a self.library_dirs.append(dir)
265n/a
266n/a def set_library_dirs(self, dirs):
267n/a """Set the list of library search directories to 'dirs' (a list of
268n/a strings). This does not affect any standard library search path
269n/a that the linker may search by default.
270n/a """
271n/a self.library_dirs = dirs[:]
272n/a
273n/a def add_runtime_library_dir(self, dir):
274n/a """Add 'dir' to the list of directories that will be searched for
275n/a shared libraries at runtime.
276n/a """
277n/a self.runtime_library_dirs.append(dir)
278n/a
279n/a def set_runtime_library_dirs(self, dirs):
280n/a """Set the list of directories to search for shared libraries at
281n/a runtime to 'dirs' (a list of strings). This does not affect any
282n/a standard search path that the runtime linker may search by
283n/a default.
284n/a """
285n/a self.runtime_library_dirs = dirs[:]
286n/a
287n/a def add_link_object(self, object):
288n/a """Add 'object' to the list of object files (or analogues, such as
289n/a explicitly named library files or the output of "resource
290n/a compilers") to be included in every link driven by this compiler
291n/a object.
292n/a """
293n/a self.objects.append(object)
294n/a
295n/a def set_link_objects(self, objects):
296n/a """Set the list of object files (or analogues) to be included in
297n/a every link to 'objects'. This does not affect any standard object
298n/a files that the linker may include by default (such as system
299n/a libraries).
300n/a """
301n/a self.objects = objects[:]
302n/a
303n/a
304n/a # -- Private utility methods --------------------------------------
305n/a # (here for the convenience of subclasses)
306n/a
307n/a # Helper method to prep compiler in subclass compile() methods
308n/a def _setup_compile(self, outdir, macros, incdirs, sources, depends,
309n/a extra):
310n/a """Process arguments and decide which source files to compile."""
311n/a if outdir is None:
312n/a outdir = self.output_dir
313n/a elif not isinstance(outdir, str):
314n/a raise TypeError("'output_dir' must be a string or None")
315n/a
316n/a if macros is None:
317n/a macros = self.macros
318n/a elif isinstance(macros, list):
319n/a macros = macros + (self.macros or [])
320n/a else:
321n/a raise TypeError("'macros' (if supplied) must be a list of tuples")
322n/a
323n/a if incdirs is None:
324n/a incdirs = self.include_dirs
325n/a elif isinstance(incdirs, (list, tuple)):
326n/a incdirs = list(incdirs) + (self.include_dirs or [])
327n/a else:
328n/a raise TypeError(
329n/a "'include_dirs' (if supplied) must be a list of strings")
330n/a
331n/a if extra is None:
332n/a extra = []
333n/a
334n/a # Get the list of expected output (object) files
335n/a objects = self.object_filenames(sources,
336n/a strip_dir=False,
337n/a output_dir=outdir)
338n/a assert len(objects) == len(sources)
339n/a
340n/a pp_opts = gen_preprocess_options(macros, incdirs)
341n/a
342n/a build = {}
343n/a for i in range(len(sources)):
344n/a src = sources[i]
345n/a obj = objects[i]
346n/a ext = os.path.splitext(src)[1]
347n/a self.mkpath(os.path.dirname(obj))
348n/a build[obj] = (src, ext)
349n/a
350n/a return macros, objects, extra, pp_opts, build
351n/a
352n/a def _get_cc_args(self, pp_opts, debug, before):
353n/a # works for unixccompiler and cygwinccompiler
354n/a cc_args = pp_opts + ['-c']
355n/a if debug:
356n/a cc_args[:0] = ['-g']
357n/a if before:
358n/a cc_args[:0] = before
359n/a return cc_args
360n/a
361n/a def _fix_compile_args(self, output_dir, macros, include_dirs):
362n/a """Typecheck and fix-up some of the arguments to the 'compile()'
363n/a method, and return fixed-up values. Specifically: if 'output_dir'
364n/a is None, replaces it with 'self.output_dir'; ensures that 'macros'
365n/a is a list, and augments it with 'self.macros'; ensures that
366n/a 'include_dirs' is a list, and augments it with 'self.include_dirs'.
367n/a Guarantees that the returned values are of the correct type,
368n/a i.e. for 'output_dir' either string or None, and for 'macros' and
369n/a 'include_dirs' either list or None.
370n/a """
371n/a if output_dir is None:
372n/a output_dir = self.output_dir
373n/a elif not isinstance(output_dir, str):
374n/a raise TypeError("'output_dir' must be a string or None")
375n/a
376n/a if macros is None:
377n/a macros = self.macros
378n/a elif isinstance(macros, list):
379n/a macros = macros + (self.macros or [])
380n/a else:
381n/a raise TypeError("'macros' (if supplied) must be a list of tuples")
382n/a
383n/a if include_dirs is None:
384n/a include_dirs = self.include_dirs
385n/a elif isinstance(include_dirs, (list, tuple)):
386n/a include_dirs = list(include_dirs) + (self.include_dirs or [])
387n/a else:
388n/a raise TypeError(
389n/a "'include_dirs' (if supplied) must be a list of strings")
390n/a
391n/a return output_dir, macros, include_dirs
392n/a
393n/a def _fix_object_args(self, objects, output_dir):
394n/a """Typecheck and fix up some arguments supplied to various methods.
395n/a Specifically: ensure that 'objects' is a list; if output_dir is
396n/a None, replace with self.output_dir. Return fixed versions of
397n/a 'objects' and 'output_dir'.
398n/a """
399n/a if not isinstance(objects, (list, tuple)):
400n/a raise TypeError("'objects' must be a list or tuple of strings")
401n/a objects = list(objects)
402n/a
403n/a if output_dir is None:
404n/a output_dir = self.output_dir
405n/a elif not isinstance(output_dir, str):
406n/a raise TypeError("'output_dir' must be a string or None")
407n/a
408n/a return objects, output_dir
409n/a
410n/a def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
411n/a """Typecheck and fix up some of the arguments supplied to the
412n/a 'link_*' methods. Specifically: ensure that all arguments are
413n/a lists, and augment them with their permanent versions
414n/a (eg. 'self.libraries' augments 'libraries'). Return a tuple with
415n/a fixed versions of all arguments.
416n/a """
417n/a if libraries is None:
418n/a libraries = self.libraries
419n/a elif isinstance(libraries, (list, tuple)):
420n/a libraries = list(libraries) + (self.libraries or [])
421n/a else:
422n/a raise TypeError(
423n/a "'libraries' (if supplied) must be a list of strings")
424n/a
425n/a if library_dirs is None:
426n/a library_dirs = self.library_dirs
427n/a elif isinstance(library_dirs, (list, tuple)):
428n/a library_dirs = list(library_dirs) + (self.library_dirs or [])
429n/a else:
430n/a raise TypeError(
431n/a "'library_dirs' (if supplied) must be a list of strings")
432n/a
433n/a if runtime_library_dirs is None:
434n/a runtime_library_dirs = self.runtime_library_dirs
435n/a elif isinstance(runtime_library_dirs, (list, tuple)):
436n/a runtime_library_dirs = (list(runtime_library_dirs) +
437n/a (self.runtime_library_dirs or []))
438n/a else:
439n/a raise TypeError("'runtime_library_dirs' (if supplied) "
440n/a "must be a list of strings")
441n/a
442n/a return libraries, library_dirs, runtime_library_dirs
443n/a
444n/a def _need_link(self, objects, output_file):
445n/a """Return true if we need to relink the files listed in 'objects'
446n/a to recreate 'output_file'.
447n/a """
448n/a if self.force:
449n/a return True
450n/a else:
451n/a if self.dry_run:
452n/a newer = newer_group(objects, output_file, missing='newer')
453n/a else:
454n/a newer = newer_group(objects, output_file)
455n/a return newer
456n/a
457n/a def detect_language(self, sources):
458n/a """Detect the language of a given file, or list of files. Uses
459n/a language_map, and language_order to do the job.
460n/a """
461n/a if not isinstance(sources, list):
462n/a sources = [sources]
463n/a lang = None
464n/a index = len(self.language_order)
465n/a for source in sources:
466n/a base, ext = os.path.splitext(source)
467n/a extlang = self.language_map.get(ext)
468n/a try:
469n/a extindex = self.language_order.index(extlang)
470n/a if extindex < index:
471n/a lang = extlang
472n/a index = extindex
473n/a except ValueError:
474n/a pass
475n/a return lang
476n/a
477n/a # -- Worker methods ------------------------------------------------
478n/a # (must be implemented by subclasses)
479n/a
480n/a def preprocess(self, source, output_file=None, macros=None,
481n/a include_dirs=None, extra_preargs=None, extra_postargs=None):
482n/a """Preprocess a single C/C++ source file, named in 'source'.
483n/a Output will be written to file named 'output_file', or stdout if
484n/a 'output_file' not supplied. 'macros' is a list of macro
485n/a definitions as for 'compile()', which will augment the macros set
486n/a with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
487n/a list of directory names that will be added to the default list.
488n/a
489n/a Raises PreprocessError on failure.
490n/a """
491n/a pass
492n/a
493n/a def compile(self, sources, output_dir=None, macros=None,
494n/a include_dirs=None, debug=False, extra_preargs=None,
495n/a extra_postargs=None, depends=None):
496n/a """Compile one or more source files.
497n/a
498n/a 'sources' must be a list of filenames, most likely C/C++
499n/a files, but in reality anything that can be handled by a
500n/a particular compiler and compiler class (eg. MSVCCompiler can
501n/a handle resource files in 'sources'). Return a list of object
502n/a filenames, one per source filename in 'sources'. Depending on
503n/a the implementation, not all source files will necessarily be
504n/a compiled, but all corresponding object filenames will be
505n/a returned.
506n/a
507n/a If 'output_dir' is given, object files will be put under it, while
508n/a retaining their original path component. That is, "foo/bar.c"
509n/a normally compiles to "foo/bar.o" (for a Unix implementation); if
510n/a 'output_dir' is "build", then it would compile to
511n/a "build/foo/bar.o".
512n/a
513n/a 'macros', if given, must be a list of macro definitions. A macro
514n/a definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
515n/a The former defines a macro; if the value is None, the macro is
516n/a defined without an explicit value. The 1-tuple case undefines a
517n/a macro. Later definitions/redefinitions/ undefinitions take
518n/a precedence.
519n/a
520n/a 'include_dirs', if given, must be a list of strings, the
521n/a directories to add to the default include file search path for this
522n/a compilation only.
523n/a
524n/a 'debug' is a boolean; if true, the compiler will be instructed to
525n/a output debug symbols in (or alongside) the object file(s).
526n/a
527n/a 'extra_preargs' and 'extra_postargs' are implementation- dependent.
528n/a On platforms that have the notion of a command line (e.g. Unix,
529n/a DOS/Windows), they are most likely lists of strings: extra
530n/a command-line arguments to prepand/append to the compiler command
531n/a line. On other platforms, consult the implementation class
532n/a documentation. In any event, they are intended as an escape hatch
533n/a for those occasions when the abstract compiler framework doesn't
534n/a cut the mustard.
535n/a
536n/a 'depends', if given, is a list of filenames that all targets
537n/a depend on. If a source file is older than any file in
538n/a depends, then the source file will be recompiled. This
539n/a supports dependency tracking, but only at a coarse
540n/a granularity.
541n/a
542n/a Raises CompileError on failure.
543n/a """
544n/a # A concrete compiler class can either override this method
545n/a # entirely or implement _compile().
546n/a
547n/a macros, objects, extra_postargs, pp_opts, build = \
548n/a self._setup_compile(output_dir, macros, include_dirs, sources,
549n/a depends, extra_postargs)
550n/a cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
551n/a
552n/a for obj in objects:
553n/a try:
554n/a src, ext = build[obj]
555n/a except KeyError:
556n/a continue
557n/a self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
558n/a
559n/a # Return *all* object filenames, not just the ones we just built.
560n/a return objects
561n/a
562n/a def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
563n/a """Compile 'src' to product 'obj'."""
564n/a
565n/a # A concrete compiler class that does not override compile()
566n/a # should implement _compile().
567n/a pass
568n/a
569n/a def create_static_lib(self, objects, output_libname, output_dir=None,
570n/a debug=False, target_lang=None):
571n/a """Link a bunch of stuff together to create a static library file.
572n/a The "bunch of stuff" consists of the list of object files supplied
573n/a as 'objects', the extra object files supplied to
574n/a 'add_link_object()' and/or 'set_link_objects()', the libraries
575n/a supplied to 'add_library()' and/or 'set_libraries()', and the
576n/a libraries supplied as 'libraries' (if any).
577n/a
578n/a 'output_libname' should be a library name, not a filename; the
579n/a filename will be inferred from the library name. 'output_dir' is
580n/a the directory where the library file will be put.
581n/a
582n/a 'debug' is a boolean; if true, debugging information will be
583n/a included in the library (note that on most platforms, it is the
584n/a compile step where this matters: the 'debug' flag is included here
585n/a just for consistency).
586n/a
587n/a 'target_lang' is the target language for which the given objects
588n/a are being compiled. This allows specific linkage time treatment of
589n/a certain languages.
590n/a
591n/a Raises LibError on failure.
592n/a """
593n/a pass
594n/a
595n/a # values for target_desc parameter in link()
596n/a SHARED_OBJECT = "shared_object"
597n/a SHARED_LIBRARY = "shared_library"
598n/a EXECUTABLE = "executable"
599n/a
600n/a def link(self, target_desc, objects, output_filename, output_dir=None,
601n/a libraries=None, library_dirs=None, runtime_library_dirs=None,
602n/a export_symbols=None, debug=False, extra_preargs=None,
603n/a extra_postargs=None, build_temp=None, target_lang=None):
604n/a """Link a bunch of stuff together to create an executable or
605n/a shared library file.
606n/a
607n/a The "bunch of stuff" consists of the list of object files supplied
608n/a as 'objects'. 'output_filename' should be a filename. If
609n/a 'output_dir' is supplied, 'output_filename' is relative to it
610n/a (i.e. 'output_filename' can provide directory components if
611n/a needed).
612n/a
613n/a 'libraries' is a list of libraries to link against. These are
614n/a library names, not filenames, since they're translated into
615n/a filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
616n/a on Unix and "foo.lib" on DOS/Windows). However, they can include a
617n/a directory component, which means the linker will look in that
618n/a specific directory rather than searching all the normal locations.
619n/a
620n/a 'library_dirs', if supplied, should be a list of directories to
621n/a search for libraries that were specified as bare library names
622n/a (ie. no directory component). These are on top of the system
623n/a default and those supplied to 'add_library_dir()' and/or
624n/a 'set_library_dirs()'. 'runtime_library_dirs' is a list of
625n/a directories that will be embedded into the shared library and used
626n/a to search for other shared libraries that *it* depends on at
627n/a run-time. (This may only be relevant on Unix.)
628n/a
629n/a 'export_symbols' is a list of symbols that the shared library will
630n/a export. (This appears to be relevant only on Windows.)
631n/a
632n/a 'debug' is as for 'compile()' and 'create_static_lib()', with the
633n/a slight distinction that it actually matters on most platforms (as
634n/a opposed to 'create_static_lib()', which includes a 'debug' flag
635n/a mostly for form's sake).
636n/a
637n/a 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
638n/a of course that they supply command-line arguments for the
639n/a particular linker being used).
640n/a
641n/a 'target_lang' is the target language for which the given objects
642n/a are being compiled. This allows specific linkage time treatment of
643n/a certain languages.
644n/a
645n/a Raises LinkError on failure.
646n/a """
647n/a raise NotImplementedError
648n/a
649n/a
650n/a # Old 'link_*()' methods, rewritten to use the new 'link()' method.
651n/a
652n/a def link_shared_lib(self, objects, output_libname, output_dir=None,
653n/a libraries=None, library_dirs=None,
654n/a runtime_library_dirs=None, export_symbols=None,
655n/a debug=False, extra_preargs=None, extra_postargs=None,
656n/a build_temp=None, target_lang=None):
657n/a self.link(CCompiler.SHARED_LIBRARY, objects,
658n/a self.library_filename(output_libname, lib_type='shared'),
659n/a output_dir,
660n/a libraries, library_dirs, runtime_library_dirs,
661n/a export_symbols, debug,
662n/a extra_preargs, extra_postargs, build_temp, target_lang)
663n/a
664n/a def link_shared_object(self, objects, output_filename, output_dir=None,
665n/a libraries=None, library_dirs=None,
666n/a runtime_library_dirs=None, export_symbols=None,
667n/a debug=False, extra_preargs=None, extra_postargs=None,
668n/a build_temp=None, target_lang=None):
669n/a self.link(CCompiler.SHARED_OBJECT, objects,
670n/a output_filename, output_dir,
671n/a libraries, library_dirs, runtime_library_dirs,
672n/a export_symbols, debug,
673n/a extra_preargs, extra_postargs, build_temp, target_lang)
674n/a
675n/a def link_executable(self, objects, output_progname, output_dir=None,
676n/a libraries=None, library_dirs=None,
677n/a runtime_library_dirs=None, debug=False,
678n/a extra_preargs=None, extra_postargs=None,
679n/a target_lang=None):
680n/a self.link(CCompiler.EXECUTABLE, objects,
681n/a self.executable_filename(output_progname), output_dir,
682n/a libraries, library_dirs, runtime_library_dirs, None,
683n/a debug, extra_preargs, extra_postargs, None, target_lang)
684n/a
685n/a
686n/a # -- Miscellaneous methods -----------------------------------------
687n/a # These are all used by the 'gen_lib_options() function; there is
688n/a # no appropriate default implementation so subclasses should
689n/a # implement all of these.
690n/a
691n/a def library_dir_option(self, dir):
692n/a """Return the compiler option to add 'dir' to the list of
693n/a directories searched for libraries.
694n/a """
695n/a raise NotImplementedError
696n/a
697n/a def runtime_library_dir_option(self, dir):
698n/a """Return the compiler option to add 'dir' to the list of
699n/a directories searched for runtime libraries.
700n/a """
701n/a raise NotImplementedError
702n/a
703n/a def library_option(self, lib):
704n/a """Return the compiler option to add 'dir' to the list of libraries
705n/a linked into the shared library or executable.
706n/a """
707n/a raise NotImplementedError
708n/a
709n/a def has_function(self, funcname, includes=None, include_dirs=None,
710n/a libraries=None, library_dirs=None):
711n/a """Return a boolean indicating whether funcname is supported on
712n/a the current platform. The optional arguments can be used to
713n/a augment the compilation environment.
714n/a """
715n/a
716n/a # this can't be included at module scope because it tries to
717n/a # import math which might not be available at that point - maybe
718n/a # the necessary logic should just be inlined?
719n/a import tempfile
720n/a if includes is None:
721n/a includes = []
722n/a if include_dirs is None:
723n/a include_dirs = []
724n/a if libraries is None:
725n/a libraries = []
726n/a if library_dirs is None:
727n/a library_dirs = []
728n/a fd, fname = tempfile.mkstemp(".c", funcname, text=True)
729n/a with os.fdopen(fd, "w") as f:
730n/a for incl in includes:
731n/a f.write("""#include "%s"\n""" % incl)
732n/a f.write("""\
733n/amain (int argc, char **argv) {
734n/a %s();
735n/a}
736n/a""" % funcname)
737n/a try:
738n/a objects = self.compile([fname], include_dirs=include_dirs)
739n/a except CompileError:
740n/a return False
741n/a
742n/a try:
743n/a self.link_executable(objects, "a.out",
744n/a libraries=libraries,
745n/a library_dirs=library_dirs)
746n/a except (LinkError, TypeError):
747n/a return False
748n/a return True
749n/a
750n/a def find_library_file(self, dirs, lib, debug=False):
751n/a """Search the specified list of directories for a static or shared
752n/a library file 'lib' and return the full path to that file. If
753n/a 'debug' is true, look for a debugging version (if that makes sense on
754n/a the current platform). Return None if 'lib' wasn't found in any of
755n/a the specified directories.
756n/a """
757n/a raise NotImplementedError
758n/a
759n/a # -- Filename generation methods -----------------------------------
760n/a
761n/a # The default implementation of the filename generating methods are
762n/a # prejudiced towards the Unix/DOS/Windows view of the world:
763n/a # * object files are named by replacing the source file extension
764n/a # (eg. .c/.cpp -> .o/.obj)
765n/a # * library files (shared or static) are named by plugging the
766n/a # library name and extension into a format string, eg.
767n/a # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
768n/a # * executables are named by appending an extension (possibly
769n/a # empty) to the program name: eg. progname + ".exe" for
770n/a # Windows
771n/a #
772n/a # To reduce redundant code, these methods expect to find
773n/a # several attributes in the current object (presumably defined
774n/a # as class attributes):
775n/a # * src_extensions -
776n/a # list of C/C++ source file extensions, eg. ['.c', '.cpp']
777n/a # * obj_extension -
778n/a # object file extension, eg. '.o' or '.obj'
779n/a # * static_lib_extension -
780n/a # extension for static library files, eg. '.a' or '.lib'
781n/a # * shared_lib_extension -
782n/a # extension for shared library/object files, eg. '.so', '.dll'
783n/a # * static_lib_format -
784n/a # format string for generating static library filenames,
785n/a # eg. 'lib%s.%s' or '%s.%s'
786n/a # * shared_lib_format
787n/a # format string for generating shared library filenames
788n/a # (probably same as static_lib_format, since the extension
789n/a # is one of the intended parameters to the format string)
790n/a # * exe_extension -
791n/a # extension for executable files, eg. '' or '.exe'
792n/a
793n/a def object_filenames(self, source_filenames, strip_dir=False, output_dir=''):
794n/a if output_dir is None:
795n/a output_dir = ''
796n/a obj_names = []
797n/a for src_name in source_filenames:
798n/a base, ext = os.path.splitext(src_name)
799n/a base = os.path.splitdrive(base)[1] # Chop off the drive
800n/a base = base[os.path.isabs(base):] # If abs, chop off leading /
801n/a if ext not in self.src_extensions:
802n/a raise UnknownFileError("unknown file type '%s' (from '%s')" %
803n/a (ext, src_name))
804n/a if strip_dir:
805n/a base = os.path.basename(base)
806n/a obj_names.append(os.path.join(output_dir,
807n/a base + self.obj_extension))
808n/a return obj_names
809n/a
810n/a def shared_object_filename(self, basename, strip_dir=False, output_dir=''):
811n/a assert output_dir is not None
812n/a if strip_dir:
813n/a basename = os.path.basename(basename)
814n/a return os.path.join(output_dir, basename + self.shared_lib_extension)
815n/a
816n/a def executable_filename(self, basename, strip_dir=False, output_dir=''):
817n/a assert output_dir is not None
818n/a if strip_dir:
819n/a basename = os.path.basename(basename)
820n/a return os.path.join(output_dir, basename + (self.exe_extension or ''))
821n/a
822n/a def library_filename(self, libname, lib_type='static', # or 'shared'
823n/a strip_dir=False, output_dir=''):
824n/a assert output_dir is not None
825n/a if lib_type not in ("static", "shared", "dylib"):
826n/a raise ValueError(
827n/a "'lib_type' must be 'static', 'shared' or 'dylib'")
828n/a fmt = getattr(self, lib_type + "_lib_format")
829n/a ext = getattr(self, lib_type + "_lib_extension")
830n/a
831n/a dir, base = os.path.split(libname)
832n/a filename = fmt % (base, ext)
833n/a if strip_dir:
834n/a dir = ''
835n/a
836n/a return os.path.join(output_dir, dir, filename)
837n/a
838n/a
839n/a # -- Utility methods -----------------------------------------------
840n/a
841n/a def execute(self, func, args, msg=None, level=1):
842n/a execute(func, args, msg, self.dry_run)
843n/a
844n/a def spawn(self, cmd):
845n/a spawn(cmd, dry_run=self.dry_run)
846n/a
847n/a def move_file(self, src, dst):
848n/a logger.info("moving %r to %r", src, dst)
849n/a if self.dry_run:
850n/a return
851n/a return move(src, dst)
852n/a
853n/a def mkpath(self, name, mode=0o777):
854n/a name = os.path.normpath(name)
855n/a if os.path.isdir(name) or name == '':
856n/a return
857n/a if self.dry_run:
858n/a head = ''
859n/a for part in name.split(os.sep):
860n/a logger.info("created directory %s%s", head, part)
861n/a head += part + os.sep
862n/a return
863n/a os.makedirs(name, mode)