ยปCore Development>Code coverage>setup.py

Python code coverage for setup.py

#countcontent
1n/a# Autodetecting setup.py script for building the Python extensions
2n/a#
3n/a
4n/a__version__ = "$Revision: 84278 $"
5n/a
6n/aimport sys, os, imp, re, optparse
7n/afrom glob import glob
8n/aimport sysconfig
9n/a
10n/afrom distutils import log
11n/afrom distutils import text_file
12n/afrom distutils.errors import *
13n/afrom distutils.core import Extension, setup
14n/afrom distutils.command.build_ext import build_ext
15n/afrom distutils.command.install import install
16n/afrom distutils.command.install_lib import install_lib
17n/afrom distutils.spawn import find_executable
18n/a
19n/a# Were we compiled --with-pydebug or with #define Py_DEBUG?
20n/aCOMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
21n/a
22n/a# This global variable is used to hold the list of modules to be disabled.
23n/adisabled_module_list = []
24n/a
25n/a# File which contains the directory for shared mods (for sys.path fixup
26n/a# when running from the build dir, see Modules/getpath.c)
27n/a_BUILDDIR_COOKIE = "pybuilddir.txt"
28n/a
29n/adef add_dir_to_list(dirlist, dir):
30n/a """Add the directory 'dir' to the list 'dirlist' (at the front) if
31n/a 1) 'dir' is not already in 'dirlist'
32n/a 2) 'dir' actually exists, and is a directory."""
33n/a if dir is not None and os.path.isdir(dir) and dir not in dirlist:
34n/a dirlist.insert(0, dir)
35n/a
36n/adef macosx_sdk_root():
37n/a """
38n/a Return the directory of the current OSX SDK,
39n/a or '/' if no SDK was specified.
40n/a """
41n/a cflags = sysconfig.get_config_var('CFLAGS')
42n/a m = re.search(r'-isysroot\s+(\S+)', cflags)
43n/a if m is None:
44n/a sysroot = '/'
45n/a else:
46n/a sysroot = m.group(1)
47n/a return sysroot
48n/a
49n/adef is_macosx_sdk_path(path):
50n/a """
51n/a Returns True if 'path' can be located in an OSX SDK
52n/a """
53n/a return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/')
54n/a
55n/adef find_file(filename, std_dirs, paths):
56n/a """Searches for the directory where a given file is located,
57n/a and returns a possibly-empty list of additional directories, or None
58n/a if the file couldn't be found at all.
59n/a
60n/a 'filename' is the name of a file, such as readline.h or libcrypto.a.
61n/a 'std_dirs' is the list of standard system directories; if the
62n/a file is found in one of them, no additional directives are needed.
63n/a 'paths' is a list of additional locations to check; if the file is
64n/a found in one of them, the resulting list will contain the directory.
65n/a """
66n/a if sys.platform == 'darwin':
67n/a # Honor the MacOSX SDK setting when one was specified.
68n/a # An SDK is a directory with the same structure as a real
69n/a # system, but with only header files and libraries.
70n/a sysroot = macosx_sdk_root()
71n/a
72n/a # Check the standard locations
73n/a for dir in std_dirs:
74n/a f = os.path.join(dir, filename)
75n/a
76n/a if sys.platform == 'darwin' and is_macosx_sdk_path(dir):
77n/a f = os.path.join(sysroot, dir[1:], filename)
78n/a
79n/a if os.path.exists(f): return []
80n/a
81n/a # Check the additional directories
82n/a for dir in paths:
83n/a f = os.path.join(dir, filename)
84n/a
85n/a if sys.platform == 'darwin' and is_macosx_sdk_path(dir):
86n/a f = os.path.join(sysroot, dir[1:], filename)
87n/a
88n/a if os.path.exists(f):
89n/a return [dir]
90n/a
91n/a # Not found anywhere
92n/a return None
93n/a
94n/adef find_library_file(compiler, libname, std_dirs, paths):
95n/a result = compiler.find_library_file(std_dirs + paths, libname)
96n/a if result is None:
97n/a return None
98n/a
99n/a if sys.platform == 'darwin':
100n/a sysroot = macosx_sdk_root()
101n/a
102n/a # Check whether the found file is in one of the standard directories
103n/a dirname = os.path.dirname(result)
104n/a for p in std_dirs:
105n/a # Ensure path doesn't end with path separator
106n/a p = p.rstrip(os.sep)
107n/a
108n/a if sys.platform == 'darwin' and is_macosx_sdk_path(p):
109n/a if os.path.join(sysroot, p[1:]) == dirname:
110n/a return [ ]
111n/a
112n/a if p == dirname:
113n/a return [ ]
114n/a
115n/a # Otherwise, it must have been in one of the additional directories,
116n/a # so we have to figure out which one.
117n/a for p in paths:
118n/a # Ensure path doesn't end with path separator
119n/a p = p.rstrip(os.sep)
120n/a
121n/a if sys.platform == 'darwin' and is_macosx_sdk_path(p):
122n/a if os.path.join(sysroot, p[1:]) == dirname:
123n/a return [ p ]
124n/a
125n/a if p == dirname:
126n/a return [p]
127n/a else:
128n/a assert False, "Internal error: Path not found in std_dirs or paths"
129n/a
130n/adef module_enabled(extlist, modname):
131n/a """Returns whether the module 'modname' is present in the list
132n/a of extensions 'extlist'."""
133n/a extlist = [ext for ext in extlist if ext.name == modname]
134n/a return len(extlist)
135n/a
136n/adef find_module_file(module, dirlist):
137n/a """Find a module in a set of possible folders. If it is not found
138n/a return the unadorned filename"""
139n/a list = find_file(module, [], dirlist)
140n/a if not list:
141n/a return module
142n/a if len(list) > 1:
143n/a log.info("WARNING: multiple copies of %s found"%module)
144n/a return os.path.join(list[0], module)
145n/a
146n/aclass PyBuildExt(build_ext):
147n/a
148n/a def __init__(self, dist):
149n/a build_ext.__init__(self, dist)
150n/a self.failed = []
151n/a
152n/a def build_extensions(self):
153n/a
154n/a # Detect which modules should be compiled
155n/a missing = self.detect_modules()
156n/a
157n/a # Remove modules that are present on the disabled list
158n/a extensions = [ext for ext in self.extensions
159n/a if ext.name not in disabled_module_list]
160n/a # move ctypes to the end, it depends on other modules
161n/a ext_map = dict((ext.name, i) for i, ext in enumerate(extensions))
162n/a if "_ctypes" in ext_map:
163n/a ctypes = extensions.pop(ext_map["_ctypes"])
164n/a extensions.append(ctypes)
165n/a self.extensions = extensions
166n/a
167n/a # Fix up the autodetected modules, prefixing all the source files
168n/a # with Modules/.
169n/a srcdir = sysconfig.get_config_var('srcdir')
170n/a if not srcdir:
171n/a # Maybe running on Windows but not using CYGWIN?
172n/a raise ValueError("No source directory; cannot proceed.")
173n/a srcdir = os.path.abspath(srcdir)
174n/a moddirlist = [os.path.join(srcdir, 'Modules')]
175n/a
176n/a # Platform-dependent module source and include directories
177n/a platform = self.get_platform()
178n/a
179n/a # Fix up the paths for scripts, too
180n/a self.distribution.scripts = [os.path.join(srcdir, filename)
181n/a for filename in self.distribution.scripts]
182n/a
183n/a # Python header files
184n/a headers = [sysconfig.get_config_h_filename()]
185n/a headers += glob(os.path.join(sysconfig.get_path('platinclude'), "*.h"))
186n/a
187n/a for ext in self.extensions[:]:
188n/a ext.sources = [ find_module_file(filename, moddirlist)
189n/a for filename in ext.sources ]
190n/a if ext.depends is not None:
191n/a ext.depends = [find_module_file(filename, moddirlist)
192n/a for filename in ext.depends]
193n/a else:
194n/a ext.depends = []
195n/a # re-compile extensions if a header file has been changed
196n/a ext.depends.extend(headers)
197n/a
198n/a # If a module has already been built statically,
199n/a # don't build it here
200n/a if ext.name in sys.builtin_module_names:
201n/a self.extensions.remove(ext)
202n/a
203n/a # Parse Modules/Setup and Modules/Setup.local to figure out which
204n/a # modules are turned on in the file.
205n/a remove_modules = []
206n/a for filename in ('Modules/Setup', 'Modules/Setup.local'):
207n/a input = text_file.TextFile(filename, join_lines=1)
208n/a while 1:
209n/a line = input.readline()
210n/a if not line: break
211n/a line = line.split()
212n/a remove_modules.append(line[0])
213n/a input.close()
214n/a
215n/a for ext in self.extensions[:]:
216n/a if ext.name in remove_modules:
217n/a self.extensions.remove(ext)
218n/a
219n/a # When you run "make CC=altcc" or something similar, you really want
220n/a # those environment variables passed into the setup.py phase. Here's
221n/a # a small set of useful ones.
222n/a compiler = os.environ.get('CC')
223n/a args = {}
224n/a # unfortunately, distutils doesn't let us provide separate C and C++
225n/a # compilers
226n/a if compiler is not None:
227n/a (ccshared,cflags) = sysconfig.get_config_vars('CCSHARED','CFLAGS')
228n/a args['compiler_so'] = compiler + ' ' + ccshared + ' ' + cflags
229n/a self.compiler.set_executables(**args)
230n/a
231n/a # Not only do we write the builddir cookie, but we manually install
232n/a # the shared modules directory if it isn't already in sys.path.
233n/a # Otherwise trying to import the extensions after building them
234n/a # will fail.
235n/a with open(_BUILDDIR_COOKIE, "wb") as f:
236n/a f.write(self.build_lib.encode('utf-8', 'surrogateescape'))
237n/a abs_build_lib = os.path.join(os.getcwd(), self.build_lib)
238n/a if abs_build_lib not in sys.path:
239n/a sys.path.append(abs_build_lib)
240n/a
241n/a build_ext.build_extensions(self)
242n/a
243n/a longest = max([len(e.name) for e in self.extensions])
244n/a if self.failed:
245n/a longest = max(longest, max([len(name) for name in self.failed]))
246n/a
247n/a def print_three_column(lst):
248n/a lst.sort(key=str.lower)
249n/a # guarantee zip() doesn't drop anything
250n/a while len(lst) % 3:
251n/a lst.append("")
252n/a for e, f, g in zip(lst[::3], lst[1::3], lst[2::3]):
253n/a print("%-*s %-*s %-*s" % (longest, e, longest, f,
254n/a longest, g))
255n/a
256n/a if missing:
257n/a print()
258n/a print("Python build finished, but the necessary bits to build "
259n/a "these modules were not found:")
260n/a print_three_column(missing)
261n/a print("To find the necessary bits, look in setup.py in"
262n/a " detect_modules() for the module's name.")
263n/a print()
264n/a
265n/a if self.failed:
266n/a failed = self.failed[:]
267n/a print()
268n/a print("Failed to build these modules:")
269n/a print_three_column(failed)
270n/a print()
271n/a
272n/a def build_extension(self, ext):
273n/a
274n/a if ext.name == '_ctypes':
275n/a if not self.configure_ctypes(ext):
276n/a return
277n/a
278n/a try:
279n/a build_ext.build_extension(self, ext)
280n/a except (CCompilerError, DistutilsError) as why:
281n/a self.announce('WARNING: building of extension "%s" failed: %s' %
282n/a (ext.name, sys.exc_info()[1]))
283n/a self.failed.append(ext.name)
284n/a return
285n/a # Workaround for Mac OS X: The Carbon-based modules cannot be
286n/a # reliably imported into a command-line Python
287n/a if 'Carbon' in ext.extra_link_args:
288n/a self.announce(
289n/a 'WARNING: skipping import check for Carbon-based "%s"' %
290n/a ext.name)
291n/a return
292n/a
293n/a if self.get_platform() == 'darwin' and (
294n/a sys.maxsize > 2**32 and '-arch' in ext.extra_link_args):
295n/a # Don't bother doing an import check when an extension was
296n/a # build with an explicit '-arch' flag on OSX. That's currently
297n/a # only used to build 32-bit only extensions in a 4-way
298n/a # universal build and loading 32-bit code into a 64-bit
299n/a # process will fail.
300n/a self.announce(
301n/a 'WARNING: skipping import check for "%s"' %
302n/a ext.name)
303n/a return
304n/a
305n/a # Workaround for Cygwin: Cygwin currently has fork issues when many
306n/a # modules have been imported
307n/a if self.get_platform() == 'cygwin':
308n/a self.announce('WARNING: skipping import check for Cygwin-based "%s"'
309n/a % ext.name)
310n/a return
311n/a ext_filename = os.path.join(
312n/a self.build_lib,
313n/a self.get_ext_filename(self.get_ext_fullname(ext.name)))
314n/a
315n/a # If the build directory didn't exist when setup.py was
316n/a # started, sys.path_importer_cache has a negative result
317n/a # cached. Clear that cache before trying to import.
318n/a sys.path_importer_cache.clear()
319n/a
320n/a try:
321n/a imp.load_dynamic(ext.name, ext_filename)
322n/a except ImportError as why:
323n/a self.failed.append(ext.name)
324n/a self.announce('*** WARNING: renaming "%s" since importing it'
325n/a ' failed: %s' % (ext.name, why), level=3)
326n/a assert not self.inplace
327n/a basename, tail = os.path.splitext(ext_filename)
328n/a newname = basename + "_failed" + tail
329n/a if os.path.exists(newname):
330n/a os.remove(newname)
331n/a os.rename(ext_filename, newname)
332n/a
333n/a # XXX -- This relies on a Vile HACK in
334n/a # distutils.command.build_ext.build_extension(). The
335n/a # _built_objects attribute is stored there strictly for
336n/a # use here.
337n/a # If there is a failure, _built_objects may not be there,
338n/a # so catch the AttributeError and move on.
339n/a try:
340n/a for filename in self._built_objects:
341n/a os.remove(filename)
342n/a except AttributeError:
343n/a self.announce('unable to remove files (ignored)')
344n/a except:
345n/a exc_type, why, tb = sys.exc_info()
346n/a self.announce('*** WARNING: importing extension "%s" '
347n/a 'failed with %s: %s' % (ext.name, exc_type, why),
348n/a level=3)
349n/a self.failed.append(ext.name)
350n/a
351n/a def get_platform(self):
352n/a # Get value of sys.platform
353n/a for platform in ['cygwin', 'darwin', 'osf1']:
354n/a if sys.platform.startswith(platform):
355n/a return platform
356n/a return sys.platform
357n/a
358n/a def detect_modules(self):
359n/a # Ensure that /usr/local is always used
360n/a add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
361n/a add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
362n/a
363n/a # Add paths specified in the environment variables LDFLAGS and
364n/a # CPPFLAGS for header and library files.
365n/a # We must get the values from the Makefile and not the environment
366n/a # directly since an inconsistently reproducible issue comes up where
367n/a # the environment variable is not set even though the value were passed
368n/a # into configure and stored in the Makefile (issue found on OS X 10.3).
369n/a for env_var, arg_name, dir_list in (
370n/a ('LDFLAGS', '-R', self.compiler.runtime_library_dirs),
371n/a ('LDFLAGS', '-L', self.compiler.library_dirs),
372n/a ('CPPFLAGS', '-I', self.compiler.include_dirs)):
373n/a env_val = sysconfig.get_config_var(env_var)
374n/a if env_val:
375n/a # To prevent optparse from raising an exception about any
376n/a # options in env_val that it doesn't know about we strip out
377n/a # all double dashes and any dashes followed by a character
378n/a # that is not for the option we are dealing with.
379n/a #
380n/a # Please note that order of the regex is important! We must
381n/a # strip out double-dashes first so that we don't end up with
382n/a # substituting "--Long" to "-Long" and thus lead to "ong" being
383n/a # used for a library directory.
384n/a env_val = re.sub(r'(^|\s+)-(-|(?!%s))' % arg_name[1],
385n/a ' ', env_val)
386n/a parser = optparse.OptionParser()
387n/a # Make sure that allowing args interspersed with options is
388n/a # allowed
389n/a parser.allow_interspersed_args = True
390n/a parser.error = lambda msg: None
391n/a parser.add_option(arg_name, dest="dirs", action="append")
392n/a options = parser.parse_args(env_val.split())[0]
393n/a if options.dirs:
394n/a for directory in reversed(options.dirs):
395n/a add_dir_to_list(dir_list, directory)
396n/a
397n/a if os.path.normpath(sys.prefix) != '/usr':
398n/a add_dir_to_list(self.compiler.library_dirs,
399n/a sysconfig.get_config_var("LIBDIR"))
400n/a add_dir_to_list(self.compiler.include_dirs,
401n/a sysconfig.get_config_var("INCLUDEDIR"))
402n/a
403n/a # lib_dirs and inc_dirs are used to search for files;
404n/a # if a file is found in one of those directories, it can
405n/a # be assumed that no additional -I,-L directives are needed.
406n/a lib_dirs = self.compiler.library_dirs + [
407n/a '/lib64', '/usr/lib64',
408n/a '/lib', '/usr/lib',
409n/a ]
410n/a inc_dirs = self.compiler.include_dirs + ['/usr/include']
411n/a exts = []
412n/a missing = []
413n/a
414n/a config_h = sysconfig.get_config_h_filename()
415n/a config_h_vars = sysconfig.parse_config_h(open(config_h))
416n/a
417n/a platform = self.get_platform()
418n/a srcdir = sysconfig.get_config_var('srcdir')
419n/a
420n/a # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
421n/a if platform in ['osf1', 'unixware7', 'openunix8']:
422n/a lib_dirs += ['/usr/ccs/lib']
423n/a
424n/a if platform == 'darwin':
425n/a # This should work on any unixy platform ;-)
426n/a # If the user has bothered specifying additional -I and -L flags
427n/a # in OPT and LDFLAGS we might as well use them here.
428n/a # NOTE: using shlex.split would technically be more correct, but
429n/a # also gives a bootstrap problem. Let's hope nobody uses directories
430n/a # with whitespace in the name to store libraries.
431n/a cflags, ldflags = sysconfig.get_config_vars(
432n/a 'CFLAGS', 'LDFLAGS')
433n/a for item in cflags.split():
434n/a if item.startswith('-I'):
435n/a inc_dirs.append(item[2:])
436n/a
437n/a for item in ldflags.split():
438n/a if item.startswith('-L'):
439n/a lib_dirs.append(item[2:])
440n/a
441n/a # Check for MacOS X, which doesn't need libm.a at all
442n/a math_libs = ['m']
443n/a if platform == 'darwin':
444n/a math_libs = []
445n/a
446n/a # XXX Omitted modules: gl, pure, dl, SGI-specific modules
447n/a
448n/a #
449n/a # The following modules are all pretty straightforward, and compile
450n/a # on pretty much any POSIXish platform.
451n/a #
452n/a
453n/a # Some modules that are normally always on:
454n/a exts.append( Extension('_weakref', ['_weakref.c']) )
455n/a
456n/a # array objects
457n/a exts.append( Extension('array', ['arraymodule.c']) )
458n/a # complex math library functions
459n/a exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'],
460n/a depends=['_math.h'],
461n/a libraries=math_libs) )
462n/a # math library functions, e.g. sin()
463n/a exts.append( Extension('math', ['mathmodule.c', '_math.c'],
464n/a depends=['_math.h'],
465n/a libraries=math_libs) )
466n/a # time operations and variables
467n/a exts.append( Extension('time', ['timemodule.c', '_time.c'],
468n/a libraries=math_libs) )
469n/a exts.append( Extension('_datetime', ['_datetimemodule.c', '_time.c'],
470n/a libraries=math_libs) )
471n/a # random number generator implemented in C
472n/a exts.append( Extension("_random", ["_randommodule.c"]) )
473n/a # bisect
474n/a exts.append( Extension("_bisect", ["_bisectmodule.c"]) )
475n/a # heapq
476n/a exts.append( Extension("_heapq", ["_heapqmodule.c"]) )
477n/a # C-optimized pickle replacement
478n/a exts.append( Extension("_pickle", ["_pickle.c"]) )
479n/a # atexit
480n/a exts.append( Extension("atexit", ["atexitmodule.c"]) )
481n/a # _json speedups
482n/a exts.append( Extension("_json", ["_json.c"]) )
483n/a # Python C API test module
484n/a exts.append( Extension('_testcapi', ['_testcapimodule.c'],
485n/a depends=['testcapi_long.h']) )
486n/a # profiler (_lsprof is for cProfile.py)
487n/a exts.append( Extension('_lsprof', ['_lsprof.c', 'rotatingtree.c']) )
488n/a # static Unicode character database
489n/a exts.append( Extension('unicodedata', ['unicodedata.c']) )
490n/a
491n/a # Modules with some UNIX dependencies -- on by default:
492n/a # (If you have a really backward UNIX, select and socket may not be
493n/a # supported...)
494n/a
495n/a # fcntl(2) and ioctl(2)
496n/a exts.append( Extension('fcntl', ['fcntlmodule.c']) )
497n/a # pwd(3)
498n/a exts.append( Extension('pwd', ['pwdmodule.c']) )
499n/a # grp(3)
500n/a exts.append( Extension('grp', ['grpmodule.c']) )
501n/a # spwd, shadow passwords
502n/a if (config_h_vars.get('HAVE_GETSPNAM', False) or
503n/a config_h_vars.get('HAVE_GETSPENT', False)):
504n/a exts.append( Extension('spwd', ['spwdmodule.c']) )
505n/a else:
506n/a missing.append('spwd')
507n/a
508n/a # select(2); not on ancient System V
509n/a exts.append( Extension('select', ['selectmodule.c']) )
510n/a
511n/a # Fred Drake's interface to the Python parser
512n/a exts.append( Extension('parser', ['parsermodule.c']) )
513n/a
514n/a # Memory-mapped files (also works on Win32).
515n/a exts.append( Extension('mmap', ['mmapmodule.c']) )
516n/a
517n/a # Lance Ellinghaus's syslog module
518n/a # syslog daemon interface
519n/a exts.append( Extension('syslog', ['syslogmodule.c']) )
520n/a
521n/a #
522n/a # Here ends the simple stuff. From here on, modules need certain
523n/a # libraries, are platform-specific, or present other surprises.
524n/a #
525n/a
526n/a # Multimedia modules
527n/a # These don't work for 64-bit platforms!!!
528n/a # These represent audio samples or images as strings:
529n/a
530n/a # Operations on audio samples
531n/a # According to #993173, this one should actually work fine on
532n/a # 64-bit platforms.
533n/a exts.append( Extension('audioop', ['audioop.c']) )
534n/a
535n/a # readline
536n/a do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
537n/a readline_termcap_library = ""
538n/a curses_library = ""
539n/a # Determine if readline is already linked against curses or tinfo.
540n/a if do_readline and find_executable('ldd'):
541n/a # Cannot use os.popen here in py3k.
542n/a tmpfile = os.path.join(self.build_temp, 'readline_termcap_lib')
543n/a if not os.path.exists(self.build_temp):
544n/a os.makedirs(self.build_temp)
545n/a ret = os.system("ldd %s > %s" % (do_readline, tmpfile))
546n/a if ret >> 8 == 0:
547n/a fp = open(tmpfile)
548n/a for ln in fp:
549n/a if 'curses' in ln:
550n/a readline_termcap_library = re.sub(
551n/a r'.*lib(n?cursesw?)\.so.*', r'\1', ln
552n/a ).rstrip()
553n/a break
554n/a if 'tinfo' in ln: # termcap interface split out from ncurses
555n/a readline_termcap_library = 'tinfo'
556n/a break
557n/a fp.close()
558n/a os.unlink(tmpfile)
559n/a # Issue 7384: If readline is already linked against curses,
560n/a # use the same library for the readline and curses modules.
561n/a if 'curses' in readline_termcap_library:
562n/a curses_library = readline_termcap_library
563n/a elif self.compiler.find_library_file(lib_dirs, 'ncursesw'):
564n/a curses_library = 'ncursesw'
565n/a elif self.compiler.find_library_file(lib_dirs, 'ncurses'):
566n/a curses_library = 'ncurses'
567n/a elif self.compiler.find_library_file(lib_dirs, 'curses'):
568n/a curses_library = 'curses'
569n/a
570n/a if platform == 'darwin':
571n/a os_release = int(os.uname()[2].split('.')[0])
572n/a dep_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
573n/a if dep_target and dep_target.split('.') < ['10', '5']:
574n/a os_release = 8
575n/a if os_release < 9:
576n/a # MacOSX 10.4 has a broken readline. Don't try to build
577n/a # the readline module unless the user has installed a fixed
578n/a # readline package
579n/a if find_file('readline/rlconf.h', inc_dirs, []) is None:
580n/a do_readline = False
581n/a if do_readline:
582n/a if platform == 'darwin' and os_release < 9:
583n/a # In every directory on the search path search for a dynamic
584n/a # library and then a static library, instead of first looking
585n/a # for dynamic libraries on the entire path.
586n/a # This way a staticly linked custom readline gets picked up
587n/a # before the (possibly broken) dynamic library in /usr/lib.
588n/a readline_extra_link_args = ('-Wl,-search_paths_first',)
589n/a else:
590n/a readline_extra_link_args = ()
591n/a
592n/a readline_libs = ['readline']
593n/a if readline_termcap_library:
594n/a pass # Issue 7384: Already linked against curses or tinfo.
595n/a elif curses_library:
596n/a readline_libs.append(curses_library)
597n/a elif self.compiler.find_library_file(lib_dirs +
598n/a ['/usr/lib/termcap'],
599n/a 'termcap'):
600n/a readline_libs.append('termcap')
601n/a exts.append( Extension('readline', ['readline.c'],
602n/a library_dirs=['/usr/lib/termcap'],
603n/a extra_link_args=readline_extra_link_args,
604n/a libraries=readline_libs) )
605n/a else:
606n/a missing.append('readline')
607n/a
608n/a # crypt module.
609n/a
610n/a if self.compiler.find_library_file(lib_dirs, 'crypt'):
611n/a libs = ['crypt']
612n/a else:
613n/a libs = []
614n/a exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
615n/a
616n/a # CSV files
617n/a exts.append( Extension('_csv', ['_csv.c']) )
618n/a
619n/a # POSIX subprocess module helper.
620n/a exts.append( Extension('_posixsubprocess', ['_posixsubprocess.c']) )
621n/a
622n/a # socket(2)
623n/a exts.append( Extension('_socket', ['socketmodule.c'],
624n/a depends = ['socketmodule.h']) )
625n/a # Detect SSL support for the socket module (via _ssl)
626n/a search_for_ssl_incs_in = [
627n/a '/usr/local/ssl/include',
628n/a '/usr/contrib/ssl/include/'
629n/a ]
630n/a ssl_incs = find_file('openssl/ssl.h', inc_dirs,
631n/a search_for_ssl_incs_in
632n/a )
633n/a if ssl_incs is not None:
634n/a krb5_h = find_file('krb5.h', inc_dirs,
635n/a ['/usr/kerberos/include'])
636n/a if krb5_h:
637n/a ssl_incs += krb5_h
638n/a ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
639n/a ['/usr/local/ssl/lib',
640n/a '/usr/contrib/ssl/lib/'
641n/a ] )
642n/a
643n/a if (ssl_incs is not None and
644n/a ssl_libs is not None):
645n/a exts.append( Extension('_ssl', ['_ssl.c'],
646n/a include_dirs = ssl_incs,
647n/a library_dirs = ssl_libs,
648n/a libraries = ['ssl', 'crypto'],
649n/a depends = ['socketmodule.h']), )
650n/a else:
651n/a missing.append('_ssl')
652n/a
653n/a # find out which version of OpenSSL we have
654n/a openssl_ver = 0
655n/a openssl_ver_re = re.compile(
656n/a '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' )
657n/a
658n/a # look for the openssl version header on the compiler search path.
659n/a opensslv_h = find_file('openssl/opensslv.h', [],
660n/a inc_dirs + search_for_ssl_incs_in)
661n/a if opensslv_h:
662n/a name = os.path.join(opensslv_h[0], 'openssl/opensslv.h')
663n/a if sys.platform == 'darwin' and is_macosx_sdk_path(name):
664n/a name = os.path.join(macosx_sdk_root(), name[1:])
665n/a try:
666n/a incfile = open(name, 'r')
667n/a for line in incfile:
668n/a m = openssl_ver_re.match(line)
669n/a if m:
670n/a openssl_ver = eval(m.group(1))
671n/a except IOError as msg:
672n/a print("IOError while reading opensshv.h:", msg)
673n/a pass
674n/a
675n/a #print('openssl_ver = 0x%08x' % openssl_ver)
676n/a min_openssl_ver = 0x00907000
677n/a have_any_openssl = ssl_incs is not None and ssl_libs is not None
678n/a have_usable_openssl = (have_any_openssl and
679n/a openssl_ver >= min_openssl_ver)
680n/a
681n/a if have_any_openssl:
682n/a if have_usable_openssl:
683n/a # The _hashlib module wraps optimized implementations
684n/a # of hash functions from the OpenSSL library.
685n/a exts.append( Extension('_hashlib', ['_hashopenssl.c'],
686n/a depends = ['hashlib.h'],
687n/a include_dirs = ssl_incs,
688n/a library_dirs = ssl_libs,
689n/a libraries = ['ssl', 'crypto']) )
690n/a else:
691n/a print("warning: openssl 0x%08x is too old for _hashlib" %
692n/a openssl_ver)
693n/a missing.append('_hashlib')
694n/a
695n/a min_sha2_openssl_ver = 0x00908000
696n/a if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
697n/a # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
698n/a exts.append( Extension('_sha256', ['sha256module.c'],
699n/a depends=['hashlib.h']) )
700n/a exts.append( Extension('_sha512', ['sha512module.c'],
701n/a depends=['hashlib.h']) )
702n/a
703n/a if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
704n/a # no openssl at all, use our own md5 and sha1
705n/a exts.append( Extension('_md5', ['md5module.c'],
706n/a depends=['hashlib.h']) )
707n/a exts.append( Extension('_sha1', ['sha1module.c'],
708n/a depends=['hashlib.h']) )
709n/a
710n/a # Modules that provide persistent dictionary-like semantics. You will
711n/a # probably want to arrange for at least one of them to be available on
712n/a # your machine, though none are defined by default because of library
713n/a # dependencies. The Python module dbm/__init__.py provides an
714n/a # implementation independent wrapper for these; dbm/dumb.py provides
715n/a # similar functionality (but slower of course) implemented in Python.
716n/a
717n/a # Sleepycat^WOracle Berkeley DB interface.
718n/a # http://www.oracle.com/database/berkeley-db/db/index.html
719n/a #
720n/a # This requires the Sleepycat^WOracle DB code. The supported versions
721n/a # are set below. Visit the URL above to download
722n/a # a release. Most open source OSes come with one or more
723n/a # versions of BerkeleyDB already installed.
724n/a
725n/a max_db_ver = (4, 8)
726n/a min_db_ver = (3, 3)
727n/a db_setup_debug = False # verbose debug prints from this script?
728n/a
729n/a def allow_db_ver(db_ver):
730n/a """Returns a boolean if the given BerkeleyDB version is acceptable.
731n/a
732n/a Args:
733n/a db_ver: A tuple of the version to verify.
734n/a """
735n/a if not (min_db_ver <= db_ver <= max_db_ver):
736n/a return False
737n/a return True
738n/a
739n/a def gen_db_minor_ver_nums(major):
740n/a if major == 4:
741n/a for x in range(max_db_ver[1]+1):
742n/a if allow_db_ver((4, x)):
743n/a yield x
744n/a elif major == 3:
745n/a for x in (3,):
746n/a if allow_db_ver((3, x)):
747n/a yield x
748n/a else:
749n/a raise ValueError("unknown major BerkeleyDB version", major)
750n/a
751n/a # construct a list of paths to look for the header file in on
752n/a # top of the normal inc_dirs.
753n/a db_inc_paths = [
754n/a '/usr/include/db4',
755n/a '/usr/local/include/db4',
756n/a '/opt/sfw/include/db4',
757n/a '/usr/include/db3',
758n/a '/usr/local/include/db3',
759n/a '/opt/sfw/include/db3',
760n/a # Fink defaults (http://fink.sourceforge.net/)
761n/a '/sw/include/db4',
762n/a '/sw/include/db3',
763n/a ]
764n/a # 4.x minor number specific paths
765n/a for x in gen_db_minor_ver_nums(4):
766n/a db_inc_paths.append('/usr/include/db4%d' % x)
767n/a db_inc_paths.append('/usr/include/db4.%d' % x)
768n/a db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x)
769n/a db_inc_paths.append('/usr/local/include/db4%d' % x)
770n/a db_inc_paths.append('/pkg/db-4.%d/include' % x)
771n/a db_inc_paths.append('/opt/db-4.%d/include' % x)
772n/a # MacPorts default (http://www.macports.org/)
773n/a db_inc_paths.append('/opt/local/include/db4%d' % x)
774n/a # 3.x minor number specific paths
775n/a for x in gen_db_minor_ver_nums(3):
776n/a db_inc_paths.append('/usr/include/db3%d' % x)
777n/a db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x)
778n/a db_inc_paths.append('/usr/local/include/db3%d' % x)
779n/a db_inc_paths.append('/pkg/db-3.%d/include' % x)
780n/a db_inc_paths.append('/opt/db-3.%d/include' % x)
781n/a
782n/a # Add some common subdirectories for Sleepycat DB to the list,
783n/a # based on the standard include directories. This way DB3/4 gets
784n/a # picked up when it is installed in a non-standard prefix and
785n/a # the user has added that prefix into inc_dirs.
786n/a std_variants = []
787n/a for dn in inc_dirs:
788n/a std_variants.append(os.path.join(dn, 'db3'))
789n/a std_variants.append(os.path.join(dn, 'db4'))
790n/a for x in gen_db_minor_ver_nums(4):
791n/a std_variants.append(os.path.join(dn, "db4%d"%x))
792n/a std_variants.append(os.path.join(dn, "db4.%d"%x))
793n/a for x in gen_db_minor_ver_nums(3):
794n/a std_variants.append(os.path.join(dn, "db3%d"%x))
795n/a std_variants.append(os.path.join(dn, "db3.%d"%x))
796n/a
797n/a db_inc_paths = std_variants + db_inc_paths
798n/a db_inc_paths = [p for p in db_inc_paths if os.path.exists(p)]
799n/a
800n/a db_ver_inc_map = {}
801n/a
802n/a if sys.platform == 'darwin':
803n/a sysroot = macosx_sdk_root()
804n/a
805n/a class db_found(Exception): pass
806n/a try:
807n/a # See whether there is a Sleepycat header in the standard
808n/a # search path.
809n/a for d in inc_dirs + db_inc_paths:
810n/a f = os.path.join(d, "db.h")
811n/a if sys.platform == 'darwin' and is_macosx_sdk_path(d):
812n/a f = os.path.join(sysroot, d[1:], "db.h")
813n/a
814n/a if db_setup_debug: print("db: looking for db.h in", f)
815n/a if os.path.exists(f):
816n/a f = open(f, "rb").read()
817n/a m = re.search(br"#define\WDB_VERSION_MAJOR\W(\d+)", f)
818n/a if m:
819n/a db_major = int(m.group(1))
820n/a m = re.search(br"#define\WDB_VERSION_MINOR\W(\d+)", f)
821n/a db_minor = int(m.group(1))
822n/a db_ver = (db_major, db_minor)
823n/a
824n/a # Avoid 4.6 prior to 4.6.21 due to a BerkeleyDB bug
825n/a if db_ver == (4, 6):
826n/a m = re.search(br"#define\WDB_VERSION_PATCH\W(\d+)", f)
827n/a db_patch = int(m.group(1))
828n/a if db_patch < 21:
829n/a print("db.h:", db_ver, "patch", db_patch,
830n/a "being ignored (4.6.x must be >= 4.6.21)")
831n/a continue
832n/a
833n/a if ( (db_ver not in db_ver_inc_map) and
834n/a allow_db_ver(db_ver) ):
835n/a # save the include directory with the db.h version
836n/a # (first occurrence only)
837n/a db_ver_inc_map[db_ver] = d
838n/a if db_setup_debug:
839n/a print("db.h: found", db_ver, "in", d)
840n/a else:
841n/a # we already found a header for this library version
842n/a if db_setup_debug: print("db.h: ignoring", d)
843n/a else:
844n/a # ignore this header, it didn't contain a version number
845n/a if db_setup_debug:
846n/a print("db.h: no version number version in", d)
847n/a
848n/a db_found_vers = list(db_ver_inc_map.keys())
849n/a db_found_vers.sort()
850n/a
851n/a while db_found_vers:
852n/a db_ver = db_found_vers.pop()
853n/a db_incdir = db_ver_inc_map[db_ver]
854n/a
855n/a # check lib directories parallel to the location of the header
856n/a db_dirs_to_check = [
857n/a db_incdir.replace("include", 'lib64'),
858n/a db_incdir.replace("include", 'lib'),
859n/a ]
860n/a
861n/a if sys.platform != 'darwin':
862n/a db_dirs_to_check = list(filter(os.path.isdir, db_dirs_to_check))
863n/a
864n/a else:
865n/a # Same as other branch, but takes OSX SDK into account
866n/a tmp = []
867n/a for dn in db_dirs_to_check:
868n/a if is_macosx_sdk_path(dn):
869n/a if os.path.isdir(os.path.join(sysroot, dn[1:])):
870n/a tmp.append(dn)
871n/a else:
872n/a if os.path.isdir(dn):
873n/a tmp.append(dn)
874n/a db_dirs_to_check = tmp
875n/a
876n/a db_dirs_to_check = tmp
877n/a
878n/a # Look for a version specific db-X.Y before an ambiguoius dbX
879n/a # XXX should we -ever- look for a dbX name? Do any
880n/a # systems really not name their library by version and
881n/a # symlink to more general names?
882n/a for dblib in (('db-%d.%d' % db_ver),
883n/a ('db%d%d' % db_ver),
884n/a ('db%d' % db_ver[0])):
885n/a dblib_file = self.compiler.find_library_file(
886n/a db_dirs_to_check + lib_dirs, dblib )
887n/a if dblib_file:
888n/a dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ]
889n/a raise db_found
890n/a else:
891n/a if db_setup_debug: print("db lib: ", dblib, "not found")
892n/a
893n/a except db_found:
894n/a if db_setup_debug:
895n/a print("bsddb using BerkeleyDB lib:", db_ver, dblib)
896n/a print("bsddb lib dir:", dblib_dir, " inc dir:", db_incdir)
897n/a db_incs = [db_incdir]
898n/a dblibs = [dblib]
899n/a else:
900n/a if db_setup_debug: print("db: no appropriate library found")
901n/a db_incs = None
902n/a dblibs = []
903n/a dblib_dir = None
904n/a
905n/a # The sqlite interface
906n/a sqlite_setup_debug = False # verbose debug prints from this script?
907n/a
908n/a # We hunt for #define SQLITE_VERSION "n.n.n"
909n/a # We need to find >= sqlite version 3.0.8
910n/a sqlite_incdir = sqlite_libdir = None
911n/a sqlite_inc_paths = [ '/usr/include',
912n/a '/usr/include/sqlite',
913n/a '/usr/include/sqlite3',
914n/a '/usr/local/include',
915n/a '/usr/local/include/sqlite',
916n/a '/usr/local/include/sqlite3',
917n/a ]
918n/a MIN_SQLITE_VERSION_NUMBER = (3, 0, 8)
919n/a MIN_SQLITE_VERSION = ".".join([str(x)
920n/a for x in MIN_SQLITE_VERSION_NUMBER])
921n/a
922n/a # Scan the default include directories before the SQLite specific
923n/a # ones. This allows one to override the copy of sqlite on OSX,
924n/a # where /usr/include contains an old version of sqlite.
925n/a if sys.platform == 'darwin':
926n/a sysroot = macosx_sdk_root()
927n/a
928n/a for d in inc_dirs + sqlite_inc_paths:
929n/a f = os.path.join(d, "sqlite3.h")
930n/a
931n/a if sys.platform == 'darwin' and is_macosx_sdk_path(d):
932n/a f = os.path.join(sysroot, d[1:], "sqlite3.h")
933n/a
934n/a if os.path.exists(f):
935n/a if sqlite_setup_debug: print("sqlite: found %s"%f)
936n/a incf = open(f).read()
937n/a m = re.search(
938n/a r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf)
939n/a if m:
940n/a sqlite_version = m.group(1)
941n/a sqlite_version_tuple = tuple([int(x)
942n/a for x in sqlite_version.split(".")])
943n/a if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER:
944n/a # we win!
945n/a if sqlite_setup_debug:
946n/a print("%s/sqlite3.h: version %s"%(d, sqlite_version))
947n/a sqlite_incdir = d
948n/a break
949n/a else:
950n/a if sqlite_setup_debug:
951n/a print("%s: version %d is too old, need >= %s"%(d,
952n/a sqlite_version, MIN_SQLITE_VERSION))
953n/a elif sqlite_setup_debug:
954n/a print("sqlite: %s had no SQLITE_VERSION"%(f,))
955n/a
956n/a if sqlite_incdir:
957n/a sqlite_dirs_to_check = [
958n/a os.path.join(sqlite_incdir, '..', 'lib64'),
959n/a os.path.join(sqlite_incdir, '..', 'lib'),
960n/a os.path.join(sqlite_incdir, '..', '..', 'lib64'),
961n/a os.path.join(sqlite_incdir, '..', '..', 'lib'),
962n/a ]
963n/a sqlite_libfile = self.compiler.find_library_file(
964n/a sqlite_dirs_to_check + lib_dirs, 'sqlite3')
965n/a if sqlite_libfile:
966n/a sqlite_libdir = [os.path.abspath(os.path.dirname(sqlite_libfile))]
967n/a
968n/a if sqlite_incdir and sqlite_libdir:
969n/a sqlite_srcs = ['_sqlite/cache.c',
970n/a '_sqlite/connection.c',
971n/a '_sqlite/cursor.c',
972n/a '_sqlite/microprotocols.c',
973n/a '_sqlite/module.c',
974n/a '_sqlite/prepare_protocol.c',
975n/a '_sqlite/row.c',
976n/a '_sqlite/statement.c',
977n/a '_sqlite/util.c', ]
978n/a
979n/a sqlite_defines = []
980n/a if sys.platform != "win32":
981n/a sqlite_defines.append(('MODULE_NAME', '"sqlite3"'))
982n/a else:
983n/a sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"'))
984n/a
985n/a # Comment this out if you want the sqlite3 module to be able to load extensions.
986n/a sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))
987n/a
988n/a if sys.platform == 'darwin':
989n/a # In every directory on the search path search for a dynamic
990n/a # library and then a static library, instead of first looking
991n/a # for dynamic libraries on the entiry path.
992n/a # This way a staticly linked custom sqlite gets picked up
993n/a # before the dynamic library in /usr/lib.
994n/a sqlite_extra_link_args = ('-Wl,-search_paths_first',)
995n/a else:
996n/a sqlite_extra_link_args = ()
997n/a
998n/a exts.append(Extension('_sqlite3', sqlite_srcs,
999n/a define_macros=sqlite_defines,
1000n/a include_dirs=["Modules/_sqlite",
1001n/a sqlite_incdir],
1002n/a library_dirs=sqlite_libdir,
1003n/a runtime_library_dirs=sqlite_libdir,
1004n/a extra_link_args=sqlite_extra_link_args,
1005n/a libraries=["sqlite3",]))
1006n/a else:
1007n/a missing.append('_sqlite3')
1008n/a
1009n/a dbm_order = ['gdbm']
1010n/a # The standard Unix dbm module:
1011n/a if platform not in ['cygwin']:
1012n/a config_args = [arg.strip("'")
1013n/a for arg in sysconfig.get_config_var("CONFIG_ARGS").split()]
1014n/a dbm_args = [arg for arg in config_args
1015n/a if arg.startswith('--with-dbmliborder=')]
1016n/a if dbm_args:
1017n/a dbm_order = [arg.split('=')[-1] for arg in dbm_args][-1].split(":")
1018n/a else:
1019n/a dbm_order = "ndbm:gdbm:bdb".split(":")
1020n/a dbmext = None
1021n/a for cand in dbm_order:
1022n/a if cand == "ndbm":
1023n/a if find_file("ndbm.h", inc_dirs, []) is not None:
1024n/a # Some systems have -lndbm, others don't
1025n/a if self.compiler.find_library_file(lib_dirs,
1026n/a 'ndbm'):
1027n/a ndbm_libs = ['ndbm']
1028n/a else:
1029n/a ndbm_libs = []
1030n/a print("building dbm using ndbm")
1031n/a dbmext = Extension('_dbm', ['_dbmmodule.c'],
1032n/a define_macros=[
1033n/a ('HAVE_NDBM_H',None),
1034n/a ],
1035n/a libraries=ndbm_libs)
1036n/a break
1037n/a
1038n/a elif cand == "gdbm":
1039n/a if self.compiler.find_library_file(lib_dirs, 'gdbm'):
1040n/a gdbm_libs = ['gdbm']
1041n/a if self.compiler.find_library_file(lib_dirs,
1042n/a 'gdbm_compat'):
1043n/a gdbm_libs.append('gdbm_compat')
1044n/a if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
1045n/a print("building dbm using gdbm")
1046n/a dbmext = Extension(
1047n/a '_dbm', ['_dbmmodule.c'],
1048n/a define_macros=[
1049n/a ('HAVE_GDBM_NDBM_H', None),
1050n/a ],
1051n/a libraries = gdbm_libs)
1052n/a break
1053n/a if find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
1054n/a print("building dbm using gdbm")
1055n/a dbmext = Extension(
1056n/a '_dbm', ['_dbmmodule.c'],
1057n/a define_macros=[
1058n/a ('HAVE_GDBM_DASH_NDBM_H', None),
1059n/a ],
1060n/a libraries = gdbm_libs)
1061n/a break
1062n/a elif cand == "bdb":
1063n/a if db_incs is not None:
1064n/a print("building dbm using bdb")
1065n/a dbmext = Extension('_dbm', ['_dbmmodule.c'],
1066n/a library_dirs=dblib_dir,
1067n/a runtime_library_dirs=dblib_dir,
1068n/a include_dirs=db_incs,
1069n/a define_macros=[
1070n/a ('HAVE_BERKDB_H', None),
1071n/a ('DB_DBM_HSEARCH', None),
1072n/a ],
1073n/a libraries=dblibs)
1074n/a break
1075n/a if dbmext is not None:
1076n/a exts.append(dbmext)
1077n/a else:
1078n/a missing.append('_dbm')
1079n/a
1080n/a # Anthony Baxter's gdbm module. GNU dbm(3) will require -lgdbm:
1081n/a if ('gdbm' in dbm_order and
1082n/a self.compiler.find_library_file(lib_dirs, 'gdbm')):
1083n/a exts.append( Extension('_gdbm', ['_gdbmmodule.c'],
1084n/a libraries = ['gdbm'] ) )
1085n/a else:
1086n/a missing.append('_gdbm')
1087n/a
1088n/a # Unix-only modules
1089n/a if platform != 'win32':
1090n/a # Steen Lumholt's termios module
1091n/a exts.append( Extension('termios', ['termios.c']) )
1092n/a # Jeremy Hylton's rlimit interface
1093n/a exts.append( Extension('resource', ['resource.c']) )
1094n/a
1095n/a # Sun yellow pages. Some systems have the functions in libc.
1096n/a if (platform not in ['cygwin', 'qnx6'] and
1097n/a find_file('rpcsvc/yp_prot.h', inc_dirs, []) is not None):
1098n/a if (self.compiler.find_library_file(lib_dirs, 'nsl')):
1099n/a libs = ['nsl']
1100n/a else:
1101n/a libs = []
1102n/a exts.append( Extension('nis', ['nismodule.c'],
1103n/a libraries = libs) )
1104n/a else:
1105n/a missing.append('nis')
1106n/a else:
1107n/a missing.extend(['nis', 'resource', 'termios'])
1108n/a
1109n/a # Curses support, requiring the System V version of curses, often
1110n/a # provided by the ncurses library.
1111n/a panel_library = 'panel'
1112n/a if curses_library.startswith('ncurses'):
1113n/a if curses_library == 'ncursesw':
1114n/a # Bug 1464056: If _curses.so links with ncursesw,
1115n/a # _curses_panel.so must link with panelw.
1116n/a panel_library = 'panelw'
1117n/a curses_libs = [curses_library]
1118n/a exts.append( Extension('_curses', ['_cursesmodule.c'],
1119n/a libraries = curses_libs) )
1120n/a elif curses_library == 'curses' and platform != 'darwin':
1121n/a # OSX has an old Berkeley curses, not good enough for
1122n/a # the _curses module.
1123n/a if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
1124n/a curses_libs = ['curses', 'terminfo']
1125n/a elif (self.compiler.find_library_file(lib_dirs, 'termcap')):
1126n/a curses_libs = ['curses', 'termcap']
1127n/a else:
1128n/a curses_libs = ['curses']
1129n/a
1130n/a exts.append( Extension('_curses', ['_cursesmodule.c'],
1131n/a libraries = curses_libs) )
1132n/a else:
1133n/a missing.append('_curses')
1134n/a
1135n/a # If the curses module is enabled, check for the panel module
1136n/a if (module_enabled(exts, '_curses') and
1137n/a self.compiler.find_library_file(lib_dirs, panel_library)):
1138n/a exts.append( Extension('_curses_panel', ['_curses_panel.c'],
1139n/a libraries = [panel_library] + curses_libs) )
1140n/a else:
1141n/a missing.append('_curses_panel')
1142n/a
1143n/a # Andrew Kuchling's zlib module. Note that some versions of zlib
1144n/a # 1.1.3 have security problems. See CERT Advisory CA-2002-07:
1145n/a # http://www.cert.org/advisories/CA-2002-07.html
1146n/a #
1147n/a # zlib 1.1.4 is fixed, but at least one vendor (RedHat) has decided to
1148n/a # patch its zlib 1.1.3 package instead of upgrading to 1.1.4. For
1149n/a # now, we still accept 1.1.3, because we think it's difficult to
1150n/a # exploit this in Python, and we'd rather make it RedHat's problem
1151n/a # than our problem <wink>.
1152n/a #
1153n/a # You can upgrade zlib to version 1.1.4 yourself by going to
1154n/a # http://www.gzip.org/zlib/
1155n/a zlib_inc = find_file('zlib.h', [], inc_dirs)
1156n/a have_zlib = False
1157n/a if zlib_inc is not None:
1158n/a zlib_h = zlib_inc[0] + '/zlib.h'
1159n/a version = '"0.0.0"'
1160n/a version_req = '"1.1.3"'
1161n/a fp = open(zlib_h)
1162n/a while 1:
1163n/a line = fp.readline()
1164n/a if not line:
1165n/a break
1166n/a if line.startswith('#define ZLIB_VERSION'):
1167n/a version = line.split()[2]
1168n/a break
1169n/a if version >= version_req:
1170n/a if (self.compiler.find_library_file(lib_dirs, 'z')):
1171n/a if sys.platform == "darwin":
1172n/a zlib_extra_link_args = ('-Wl,-search_paths_first',)
1173n/a else:
1174n/a zlib_extra_link_args = ()
1175n/a exts.append( Extension('zlib', ['zlibmodule.c'],
1176n/a libraries = ['z'],
1177n/a extra_link_args = zlib_extra_link_args))
1178n/a have_zlib = True
1179n/a else:
1180n/a missing.append('zlib')
1181n/a else:
1182n/a missing.append('zlib')
1183n/a else:
1184n/a missing.append('zlib')
1185n/a
1186n/a # Helper module for various ascii-encoders. Uses zlib for an optimized
1187n/a # crc32 if we have it. Otherwise binascii uses its own.
1188n/a if have_zlib:
1189n/a extra_compile_args = ['-DUSE_ZLIB_CRC32']
1190n/a libraries = ['z']
1191n/a extra_link_args = zlib_extra_link_args
1192n/a else:
1193n/a extra_compile_args = []
1194n/a libraries = []
1195n/a extra_link_args = []
1196n/a exts.append( Extension('binascii', ['binascii.c'],
1197n/a extra_compile_args = extra_compile_args,
1198n/a libraries = libraries,
1199n/a extra_link_args = extra_link_args) )
1200n/a
1201n/a # Gustavo Niemeyer's bz2 module.
1202n/a if (self.compiler.find_library_file(lib_dirs, 'bz2')):
1203n/a if sys.platform == "darwin":
1204n/a bz2_extra_link_args = ('-Wl,-search_paths_first',)
1205n/a else:
1206n/a bz2_extra_link_args = ()
1207n/a exts.append( Extension('bz2', ['bz2module.c'],
1208n/a libraries = ['bz2'],
1209n/a extra_link_args = bz2_extra_link_args) )
1210n/a else:
1211n/a missing.append('bz2')
1212n/a
1213n/a # Interface to the Expat XML parser
1214n/a #
1215n/a # Expat was written by James Clark and is now maintained by a group of
1216n/a # developers on SourceForge; see www.libexpat.org for more information.
1217n/a # The pyexpat module was written by Paul Prescod after a prototype by
1218n/a # Jack Jansen. The Expat source is included in Modules/expat/. Usage
1219n/a # of a system shared libexpat.so is possible with --with-system-expat
1220n/a # cofigure option.
1221n/a #
1222n/a # More information on Expat can be found at www.libexpat.org.
1223n/a #
1224n/a if '--with-system-expat' in sysconfig.get_config_var("CONFIG_ARGS"):
1225n/a expat_inc = []
1226n/a define_macros = []
1227n/a expat_lib = ['expat']
1228n/a expat_sources = []
1229n/a else:
1230n/a expat_inc = [os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')]
1231n/a define_macros = [
1232n/a ('HAVE_EXPAT_CONFIG_H', '1'),
1233n/a ]
1234n/a expat_lib = []
1235n/a expat_sources = ['expat/xmlparse.c',
1236n/a 'expat/xmlrole.c',
1237n/a 'expat/xmltok.c']
1238n/a
1239n/a exts.append(Extension('pyexpat',
1240n/a define_macros = define_macros,
1241n/a include_dirs = expat_inc,
1242n/a libraries = expat_lib,
1243n/a sources = ['pyexpat.c'] + expat_sources
1244n/a ))
1245n/a
1246n/a # Fredrik Lundh's cElementTree module. Note that this also
1247n/a # uses expat (via the CAPI hook in pyexpat).
1248n/a
1249n/a if os.path.isfile(os.path.join(srcdir, 'Modules', '_elementtree.c')):
1250n/a define_macros.append(('USE_PYEXPAT_CAPI', None))
1251n/a exts.append(Extension('_elementtree',
1252n/a define_macros = define_macros,
1253n/a include_dirs = expat_inc,
1254n/a libraries = expat_lib,
1255n/a sources = ['_elementtree.c'],
1256n/a ))
1257n/a else:
1258n/a missing.append('_elementtree')
1259n/a
1260n/a # Hye-Shik Chang's CJKCodecs modules.
1261n/a exts.append(Extension('_multibytecodec',
1262n/a ['cjkcodecs/multibytecodec.c']))
1263n/a for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
1264n/a exts.append(Extension('_codecs_%s' % loc,
1265n/a ['cjkcodecs/_codecs_%s.c' % loc]))
1266n/a
1267n/a # Thomas Heller's _ctypes module
1268n/a self.detect_ctypes(inc_dirs, lib_dirs)
1269n/a
1270n/a # Richard Oudkerk's multiprocessing module
1271n/a if platform == 'win32': # Windows
1272n/a macros = dict()
1273n/a libraries = ['ws2_32']
1274n/a
1275n/a elif platform == 'darwin': # Mac OSX
1276n/a macros = dict()
1277n/a libraries = []
1278n/a
1279n/a elif platform == 'cygwin': # Cygwin
1280n/a macros = dict()
1281n/a libraries = []
1282n/a
1283n/a elif platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
1284n/a # FreeBSD's P1003.1b semaphore support is very experimental
1285n/a # and has many known problems. (as of June 2008)
1286n/a macros = dict()
1287n/a libraries = []
1288n/a
1289n/a elif platform.startswith('openbsd'):
1290n/a macros = dict()
1291n/a libraries = []
1292n/a
1293n/a elif platform.startswith('netbsd'):
1294n/a macros = dict()
1295n/a libraries = []
1296n/a
1297n/a else: # Linux and other unices
1298n/a macros = dict()
1299n/a libraries = ['rt']
1300n/a
1301n/a if platform == 'win32':
1302n/a multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
1303n/a '_multiprocessing/semaphore.c',
1304n/a '_multiprocessing/pipe_connection.c',
1305n/a '_multiprocessing/socket_connection.c',
1306n/a '_multiprocessing/win32_functions.c'
1307n/a ]
1308n/a
1309n/a else:
1310n/a multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
1311n/a '_multiprocessing/socket_connection.c'
1312n/a ]
1313n/a if (sysconfig.get_config_var('HAVE_SEM_OPEN') and not
1314n/a sysconfig.get_config_var('POSIX_SEMAPHORES_NOT_ENABLED')):
1315n/a multiprocessing_srcs.append('_multiprocessing/semaphore.c')
1316n/a
1317n/a if sysconfig.get_config_var('WITH_THREAD'):
1318n/a exts.append ( Extension('_multiprocessing', multiprocessing_srcs,
1319n/a define_macros=list(macros.items()),
1320n/a include_dirs=["Modules/_multiprocessing"]))
1321n/a else:
1322n/a missing.append('_multiprocessing')
1323n/a # End multiprocessing
1324n/a
1325n/a # Platform-specific libraries
1326n/a if (platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
1327n/a 'freebsd7', 'freebsd8')
1328n/a or platform.startswith("gnukfreebsd")):
1329n/a exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
1330n/a else:
1331n/a missing.append('ossaudiodev')
1332n/a
1333n/a if sys.platform == 'darwin':
1334n/a exts.append(
1335n/a Extension('_gestalt', ['_gestalt.c'],
1336n/a extra_link_args=['-framework', 'Carbon'])
1337n/a )
1338n/a exts.append(
1339n/a Extension('_scproxy', ['_scproxy.c'],
1340n/a extra_link_args=[
1341n/a '-framework', 'SystemConfiguration',
1342n/a '-framework', 'CoreFoundation',
1343n/a ]))
1344n/a
1345n/a self.extensions.extend(exts)
1346n/a
1347n/a # Call the method for detecting whether _tkinter can be compiled
1348n/a self.detect_tkinter(inc_dirs, lib_dirs)
1349n/a
1350n/a if '_tkinter' not in [e.name for e in self.extensions]:
1351n/a missing.append('_tkinter')
1352n/a
1353n/a return missing
1354n/a
1355n/a def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
1356n/a # The _tkinter module, using frameworks. Since frameworks are quite
1357n/a # different the UNIX search logic is not sharable.
1358n/a from os.path import join, exists
1359n/a framework_dirs = [
1360n/a '/Library/Frameworks',
1361n/a '/System/Library/Frameworks/',
1362n/a join(os.getenv('HOME'), '/Library/Frameworks')
1363n/a ]
1364n/a
1365n/a sysroot = macosx_sdk_root()
1366n/a
1367n/a # Find the directory that contains the Tcl.framework and Tk.framework
1368n/a # bundles.
1369n/a # XXX distutils should support -F!
1370n/a for F in framework_dirs:
1371n/a # both Tcl.framework and Tk.framework should be present
1372n/a
1373n/a
1374n/a for fw in 'Tcl', 'Tk':
1375n/a if is_macosx_sdk_path(F):
1376n/a if not exists(join(sysroot, F[1:], fw + '.framework')):
1377n/a break
1378n/a else:
1379n/a if not exists(join(F, fw + '.framework')):
1380n/a break
1381n/a else:
1382n/a # ok, F is now directory with both frameworks. Continure
1383n/a # building
1384n/a break
1385n/a else:
1386n/a # Tk and Tcl frameworks not found. Normal "unix" tkinter search
1387n/a # will now resume.
1388n/a return 0
1389n/a
1390n/a # For 8.4a2, we must add -I options that point inside the Tcl and Tk
1391n/a # frameworks. In later release we should hopefully be able to pass
1392n/a # the -F option to gcc, which specifies a framework lookup path.
1393n/a #
1394n/a include_dirs = [
1395n/a join(F, fw + '.framework', H)
1396n/a for fw in ('Tcl', 'Tk')
1397n/a for H in ('Headers', 'Versions/Current/PrivateHeaders')
1398n/a ]
1399n/a
1400n/a # For 8.4a2, the X11 headers are not included. Rather than include a
1401n/a # complicated search, this is a hard-coded path. It could bail out
1402n/a # if X11 libs are not found...
1403n/a include_dirs.append('/usr/X11R6/include')
1404n/a frameworks = ['-framework', 'Tcl', '-framework', 'Tk']
1405n/a
1406n/a # All existing framework builds of Tcl/Tk don't support 64-bit
1407n/a # architectures.
1408n/a cflags = sysconfig.get_config_vars('CFLAGS')[0]
1409n/a archs = re.findall('-arch\s+(\w+)', cflags)
1410n/a
1411n/a tmpfile = os.path.join(self.build_temp, 'tk.arch')
1412n/a if not os.path.exists(self.build_temp):
1413n/a os.makedirs(self.build_temp)
1414n/a
1415n/a # Note: cannot use os.popen or subprocess here, that
1416n/a # requires extensions that are not available here.
1417n/a if is_macosx_sdk_path(F):
1418n/a os.system("file %s/Tk.framework/Tk | grep 'for architecture' > %s"%(os.path.join(sysroot, F[1:]), tmpfile))
1419n/a else:
1420n/a os.system("file %s/Tk.framework/Tk | grep 'for architecture' > %s"%(F, tmpfile))
1421n/a fp = open(tmpfile)
1422n/a
1423n/a detected_archs = []
1424n/a for ln in fp:
1425n/a a = ln.split()[-1]
1426n/a if a in archs:
1427n/a detected_archs.append(ln.split()[-1])
1428n/a fp.close()
1429n/a os.unlink(tmpfile)
1430n/a
1431n/a for a in detected_archs:
1432n/a frameworks.append('-arch')
1433n/a frameworks.append(a)
1434n/a
1435n/a ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
1436n/a define_macros=[('WITH_APPINIT', 1)],
1437n/a include_dirs = include_dirs,
1438n/a libraries = [],
1439n/a extra_compile_args = frameworks[2:],
1440n/a extra_link_args = frameworks,
1441n/a )
1442n/a self.extensions.append(ext)
1443n/a return 1
1444n/a
1445n/a
1446n/a def detect_tkinter(self, inc_dirs, lib_dirs):
1447n/a # The _tkinter module.
1448n/a
1449n/a # Rather than complicate the code below, detecting and building
1450n/a # AquaTk is a separate method. Only one Tkinter will be built on
1451n/a # Darwin - either AquaTk, if it is found, or X11 based Tk.
1452n/a platform = self.get_platform()
1453n/a if (platform == 'darwin' and
1454n/a self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
1455n/a return
1456n/a
1457n/a # Assume we haven't found any of the libraries or include files
1458n/a # The versions with dots are used on Unix, and the versions without
1459n/a # dots on Windows, for detection by cygwin.
1460n/a tcllib = tklib = tcl_includes = tk_includes = None
1461n/a for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
1462n/a '8.2', '82', '8.1', '81', '8.0', '80']:
1463n/a tklib = self.compiler.find_library_file(lib_dirs,
1464n/a 'tk' + version)
1465n/a tcllib = self.compiler.find_library_file(lib_dirs,
1466n/a 'tcl' + version)
1467n/a if tklib and tcllib:
1468n/a # Exit the loop when we've found the Tcl/Tk libraries
1469n/a break
1470n/a
1471n/a # Now check for the header files
1472n/a if tklib and tcllib:
1473n/a # Check for the include files on Debian and {Free,Open}BSD, where
1474n/a # they're put in /usr/include/{tcl,tk}X.Y
1475n/a dotversion = version
1476n/a if '.' not in dotversion and "bsd" in sys.platform.lower():
1477n/a # OpenBSD and FreeBSD use Tcl/Tk library names like libtcl83.a,
1478n/a # but the include subdirs are named like .../include/tcl8.3.
1479n/a dotversion = dotversion[:-1] + '.' + dotversion[-1]
1480n/a tcl_include_sub = []
1481n/a tk_include_sub = []
1482n/a for dir in inc_dirs:
1483n/a tcl_include_sub += [dir + os.sep + "tcl" + dotversion]
1484n/a tk_include_sub += [dir + os.sep + "tk" + dotversion]
1485n/a tk_include_sub += tcl_include_sub
1486n/a tcl_includes = find_file('tcl.h', inc_dirs, tcl_include_sub)
1487n/a tk_includes = find_file('tk.h', inc_dirs, tk_include_sub)
1488n/a
1489n/a if (tcllib is None or tklib is None or
1490n/a tcl_includes is None or tk_includes is None):
1491n/a self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2)
1492n/a return
1493n/a
1494n/a # OK... everything seems to be present for Tcl/Tk.
1495n/a
1496n/a include_dirs = [] ; libs = [] ; defs = [] ; added_lib_dirs = []
1497n/a for dir in tcl_includes + tk_includes:
1498n/a if dir not in include_dirs:
1499n/a include_dirs.append(dir)
1500n/a
1501n/a # Check for various platform-specific directories
1502n/a if platform == 'sunos5':
1503n/a include_dirs.append('/usr/openwin/include')
1504n/a added_lib_dirs.append('/usr/openwin/lib')
1505n/a elif os.path.exists('/usr/X11R6/include'):
1506n/a include_dirs.append('/usr/X11R6/include')
1507n/a added_lib_dirs.append('/usr/X11R6/lib64')
1508n/a added_lib_dirs.append('/usr/X11R6/lib')
1509n/a elif os.path.exists('/usr/X11R5/include'):
1510n/a include_dirs.append('/usr/X11R5/include')
1511n/a added_lib_dirs.append('/usr/X11R5/lib')
1512n/a else:
1513n/a # Assume default location for X11
1514n/a include_dirs.append('/usr/X11/include')
1515n/a added_lib_dirs.append('/usr/X11/lib')
1516n/a
1517n/a # If Cygwin, then verify that X is installed before proceeding
1518n/a if platform == 'cygwin':
1519n/a x11_inc = find_file('X11/Xlib.h', [], include_dirs)
1520n/a if x11_inc is None:
1521n/a return
1522n/a
1523n/a # Check for BLT extension
1524n/a if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
1525n/a 'BLT8.0'):
1526n/a defs.append( ('WITH_BLT', 1) )
1527n/a libs.append('BLT8.0')
1528n/a elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
1529n/a 'BLT'):
1530n/a defs.append( ('WITH_BLT', 1) )
1531n/a libs.append('BLT')
1532n/a
1533n/a # Add the Tcl/Tk libraries
1534n/a libs.append('tk'+ version)
1535n/a libs.append('tcl'+ version)
1536n/a
1537n/a if platform in ['aix3', 'aix4']:
1538n/a libs.append('ld')
1539n/a
1540n/a # Finally, link with the X11 libraries (not appropriate on cygwin)
1541n/a if platform != "cygwin":
1542n/a libs.append('X11')
1543n/a
1544n/a ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
1545n/a define_macros=[('WITH_APPINIT', 1)] + defs,
1546n/a include_dirs = include_dirs,
1547n/a libraries = libs,
1548n/a library_dirs = added_lib_dirs,
1549n/a )
1550n/a self.extensions.append(ext)
1551n/a
1552n/a## # Uncomment these lines if you want to play with xxmodule.c
1553n/a## ext = Extension('xx', ['xxmodule.c'])
1554n/a## self.extensions.append(ext)
1555n/a
1556n/a # XXX handle these, but how to detect?
1557n/a # *** Uncomment and edit for PIL (TkImaging) extension only:
1558n/a # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \
1559n/a # *** Uncomment and edit for TOGL extension only:
1560n/a # -DWITH_TOGL togl.c \
1561n/a # *** Uncomment these for TOGL extension only:
1562n/a # -lGL -lGLU -lXext -lXmu \
1563n/a
1564n/a def configure_ctypes_darwin(self, ext):
1565n/a # Darwin (OS X) uses preconfigured files, in
1566n/a # the Modules/_ctypes/libffi_osx directory.
1567n/a srcdir = sysconfig.get_config_var('srcdir')
1568n/a ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
1569n/a '_ctypes', 'libffi_osx'))
1570n/a sources = [os.path.join(ffi_srcdir, p)
1571n/a for p in ['ffi.c',
1572n/a 'x86/darwin64.S',
1573n/a 'x86/x86-darwin.S',
1574n/a 'x86/x86-ffi_darwin.c',
1575n/a 'x86/x86-ffi64.c',
1576n/a 'powerpc/ppc-darwin.S',
1577n/a 'powerpc/ppc-darwin_closure.S',
1578n/a 'powerpc/ppc-ffi_darwin.c',
1579n/a 'powerpc/ppc64-darwin_closure.S',
1580n/a ]]
1581n/a
1582n/a # Add .S (preprocessed assembly) to C compiler source extensions.
1583n/a self.compiler.src_extensions.append('.S')
1584n/a
1585n/a include_dirs = [os.path.join(ffi_srcdir, 'include'),
1586n/a os.path.join(ffi_srcdir, 'powerpc')]
1587n/a ext.include_dirs.extend(include_dirs)
1588n/a ext.sources.extend(sources)
1589n/a return True
1590n/a
1591n/a def configure_ctypes(self, ext):
1592n/a if not self.use_system_libffi:
1593n/a if sys.platform == 'darwin':
1594n/a return self.configure_ctypes_darwin(ext)
1595n/a
1596n/a srcdir = sysconfig.get_config_var('srcdir')
1597n/a ffi_builddir = os.path.join(self.build_temp, 'libffi')
1598n/a ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
1599n/a '_ctypes', 'libffi'))
1600n/a ffi_configfile = os.path.join(ffi_builddir, 'fficonfig.py')
1601n/a
1602n/a from distutils.dep_util import newer_group
1603n/a
1604n/a config_sources = [os.path.join(ffi_srcdir, fname)
1605n/a for fname in os.listdir(ffi_srcdir)
1606n/a if os.path.isfile(os.path.join(ffi_srcdir, fname))]
1607n/a if self.force or newer_group(config_sources,
1608n/a ffi_configfile):
1609n/a from distutils.dir_util import mkpath
1610n/a mkpath(ffi_builddir)
1611n/a config_args = []
1612n/a
1613n/a # Pass empty CFLAGS because we'll just append the resulting
1614n/a # CFLAGS to Python's; -g or -O2 is to be avoided.
1615n/a cmd = "cd %s && env CFLAGS='' '%s/configure' %s" \
1616n/a % (ffi_builddir, ffi_srcdir, " ".join(config_args))
1617n/a
1618n/a res = os.system(cmd)
1619n/a if res or not os.path.exists(ffi_configfile):
1620n/a print("Failed to configure _ctypes module")
1621n/a return False
1622n/a
1623n/a fficonfig = {}
1624n/a with open(ffi_configfile) as f:
1625n/a exec(f.read(), globals(), fficonfig)
1626n/a
1627n/a # Add .S (preprocessed assembly) to C compiler source extensions.
1628n/a self.compiler.src_extensions.append('.S')
1629n/a
1630n/a include_dirs = [os.path.join(ffi_builddir, 'include'),
1631n/a ffi_builddir,
1632n/a os.path.join(ffi_srcdir, 'src')]
1633n/a extra_compile_args = fficonfig['ffi_cflags'].split()
1634n/a
1635n/a ext.sources.extend(os.path.join(ffi_srcdir, f) for f in
1636n/a fficonfig['ffi_sources'])
1637n/a ext.include_dirs.extend(include_dirs)
1638n/a ext.extra_compile_args.extend(extra_compile_args)
1639n/a return True
1640n/a
1641n/a def detect_ctypes(self, inc_dirs, lib_dirs):
1642n/a self.use_system_libffi = False
1643n/a include_dirs = []
1644n/a extra_compile_args = []
1645n/a extra_link_args = []
1646n/a sources = ['_ctypes/_ctypes.c',
1647n/a '_ctypes/callbacks.c',
1648n/a '_ctypes/callproc.c',
1649n/a '_ctypes/stgdict.c',
1650n/a '_ctypes/cfield.c']
1651n/a depends = ['_ctypes/ctypes.h']
1652n/a
1653n/a if sys.platform == 'darwin':
1654n/a sources.append('_ctypes/darwin/dlfcn_simple.c')
1655n/a extra_compile_args.append('-DMACOSX')
1656n/a include_dirs.append('_ctypes/darwin')
1657n/a# XXX Is this still needed?
1658n/a## extra_link_args.extend(['-read_only_relocs', 'warning'])
1659n/a
1660n/a elif sys.platform == 'sunos5':
1661n/a # XXX This shouldn't be necessary; it appears that some
1662n/a # of the assembler code is non-PIC (i.e. it has relocations
1663n/a # when it shouldn't. The proper fix would be to rewrite
1664n/a # the assembler code to be PIC.
1665n/a # This only works with GCC; the Sun compiler likely refuses
1666n/a # this option. If you want to compile ctypes with the Sun
1667n/a # compiler, please research a proper solution, instead of
1668n/a # finding some -z option for the Sun compiler.
1669n/a extra_link_args.append('-mimpure-text')
1670n/a
1671n/a elif sys.platform.startswith('hp-ux'):
1672n/a extra_link_args.append('-fPIC')
1673n/a
1674n/a ext = Extension('_ctypes',
1675n/a include_dirs=include_dirs,
1676n/a extra_compile_args=extra_compile_args,
1677n/a extra_link_args=extra_link_args,
1678n/a libraries=[],
1679n/a sources=sources,
1680n/a depends=depends)
1681n/a ext_test = Extension('_ctypes_test',
1682n/a sources=['_ctypes/_ctypes_test.c'])
1683n/a self.extensions.extend([ext, ext_test])
1684n/a
1685n/a if not '--with-system-ffi' in sysconfig.get_config_var("CONFIG_ARGS"):
1686n/a return
1687n/a
1688n/a if sys.platform == 'darwin':
1689n/a # OS X 10.5 comes with libffi.dylib; the include files are
1690n/a # in /usr/include/ffi
1691n/a inc_dirs.append('/usr/include/ffi')
1692n/a
1693n/a ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
1694n/a if not ffi_inc or ffi_inc[0] == '':
1695n/a ffi_inc = find_file('ffi.h', [], inc_dirs)
1696n/a if ffi_inc is not None:
1697n/a ffi_h = ffi_inc[0] + '/ffi.h'
1698n/a fp = open(ffi_h)
1699n/a while 1:
1700n/a line = fp.readline()
1701n/a if not line:
1702n/a ffi_inc = None
1703n/a break
1704n/a if line.startswith('#define LIBFFI_H'):
1705n/a break
1706n/a ffi_lib = None
1707n/a if ffi_inc is not None:
1708n/a for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'):
1709n/a if (self.compiler.find_library_file(lib_dirs, lib_name)):
1710n/a ffi_lib = lib_name
1711n/a break
1712n/a
1713n/a if ffi_inc and ffi_lib:
1714n/a ext.include_dirs.extend(ffi_inc)
1715n/a ext.libraries.append(ffi_lib)
1716n/a self.use_system_libffi = True
1717n/a
1718n/a
1719n/aclass PyBuildInstall(install):
1720n/a # Suppress the warning about installation into the lib_dynload
1721n/a # directory, which is not in sys.path when running Python during
1722n/a # installation:
1723n/a def initialize_options (self):
1724n/a install.initialize_options(self)
1725n/a self.warn_dir=0
1726n/a
1727n/aclass PyBuildInstallLib(install_lib):
1728n/a # Do exactly what install_lib does but make sure correct access modes get
1729n/a # set on installed directories and files. All installed files with get
1730n/a # mode 644 unless they are a shared library in which case they will get
1731n/a # mode 755. All installed directories will get mode 755.
1732n/a
1733n/a so_ext = sysconfig.get_config_var("SO")
1734n/a
1735n/a def install(self):
1736n/a outfiles = install_lib.install(self)
1737n/a self.set_file_modes(outfiles, 0o644, 0o755)
1738n/a self.set_dir_modes(self.install_dir, 0o755)
1739n/a return outfiles
1740n/a
1741n/a def set_file_modes(self, files, defaultMode, sharedLibMode):
1742n/a if not self.is_chmod_supported(): return
1743n/a if not files: return
1744n/a
1745n/a for filename in files:
1746n/a if os.path.islink(filename): continue
1747n/a mode = defaultMode
1748n/a if filename.endswith(self.so_ext): mode = sharedLibMode
1749n/a log.info("changing mode of %s to %o", filename, mode)
1750n/a if not self.dry_run: os.chmod(filename, mode)
1751n/a
1752n/a def set_dir_modes(self, dirname, mode):
1753n/a if not self.is_chmod_supported(): return
1754n/a for dirpath, dirnames, fnames in os.walk(dirname):
1755n/a if os.path.islink(dirpath):
1756n/a continue
1757n/a log.info("changing mode of %s to %o", dirpath, mode)
1758n/a if not self.dry_run: os.chmod(dirpath, mode)
1759n/a
1760n/a def is_chmod_supported(self):
1761n/a return hasattr(os, 'chmod')
1762n/a
1763n/aSUMMARY = """
1764n/aPython is an interpreted, interactive, object-oriented programming
1765n/alanguage. It is often compared to Tcl, Perl, Scheme or Java.
1766n/a
1767n/aPython combines remarkable power with very clear syntax. It has
1768n/amodules, classes, exceptions, very high level dynamic data types, and
1769n/adynamic typing. There are interfaces to many system calls and
1770n/alibraries, as well as to various windowing systems (X11, Motif, Tk,
1771n/aMac, MFC). New built-in modules are easily written in C or C++. Python
1772n/ais also usable as an extension language for applications that need a
1773n/aprogrammable interface.
1774n/a
1775n/aThe Python implementation is portable: it runs on many brands of UNIX,
1776n/aon Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't
1777n/alisted here, it may still be supported, if there's a C compiler for
1778n/ait. Ask around on comp.lang.python -- or just try compiling Python
1779n/ayourself.
1780n/a"""
1781n/a
1782n/aCLASSIFIERS = """
1783n/aDevelopment Status :: 6 - Mature
1784n/aLicense :: OSI Approved :: Python Software Foundation License
1785n/aNatural Language :: English
1786n/aProgramming Language :: C
1787n/aProgramming Language :: Python
1788n/aTopic :: Software Development
1789n/a"""
1790n/a
1791n/adef main():
1792n/a # turn off warnings when deprecated modules are imported
1793n/a import warnings
1794n/a warnings.filterwarnings("ignore",category=DeprecationWarning)
1795n/a setup(# PyPI Metadata (PEP 301)
1796n/a name = "Python",
1797n/a version = sys.version.split()[0],
1798n/a url = "http://www.python.org/%s" % sys.version[:3],
1799n/a maintainer = "Guido van Rossum and the Python community",
1800n/a maintainer_email = "python-dev@python.org",
1801n/a description = "A high-level object-oriented programming language",
1802n/a long_description = SUMMARY.strip(),
1803n/a license = "PSF license",
1804n/a classifiers = [x for x in CLASSIFIERS.split("\n") if x],
1805n/a platforms = ["Many"],
1806n/a
1807n/a # Build info
1808n/a cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall,
1809n/a 'install_lib':PyBuildInstallLib},
1810n/a # The struct module is defined here, because build_ext won't be
1811n/a # called unless there's at least one extension module defined.
1812n/a ext_modules=[Extension('_struct', ['_struct.c'])],
1813n/a
1814n/a scripts = ["Tools/scripts/pydoc3", "Tools/scripts/idle3",
1815n/a "Tools/scripts/2to3"]
1816n/a )
1817n/a
1818n/a# --install-platlib
1819n/aif __name__ == '__main__':
1820n/a main()