Debian Codegraph @

cpython27/setup.py

raw symbols SCIP
1 # Autodetecting setup.py script for building the Python extensions
2 #
3
4 __version__ = "$Revision$"
5
6 import sys, os, imp, re, optparse
7 from glob import glob
8 from platform import machine as platform_machine
9 import sysconfig
10
11 from distutils import log
12 from distutils import text_file
13 from distutils.errors import *
14 from distutils.core import Extension, setup
15 from distutils.command.build_ext import build_ext
16 from distutils.command.install import install
17 from distutils.command.install_lib import install_lib
18 from distutils.spawn import find_executable
19
20 cross_compiling = "_PYTHON_HOST_PLATFORM" in os.environ
21
22 def get_platform():
23 # cross build
24 if "_PYTHON_HOST_PLATFORM" in os.environ:
25 return os.environ["_PYTHON_HOST_PLATFORM"]
26 # Get value of sys.platform
27 if sys.platform.startswith('osf1'):
28 return 'osf1'
29 return sys.platform
30 host_platform = get_platform()
31
32 # Were we compiled --with-pydebug or with #define Py_DEBUG?
33 COMPILED_WITH_PYDEBUG = ('--with-pydebug' in sysconfig.get_config_var("CONFIG_ARGS"))
34
35 # This global variable is used to hold the list of modules to be disabled.
36 disabled_module_list = []
37
38 def add_dir_to_list(dirlist, dir):
39 """Add the directory 'dir' to the list 'dirlist' (at the front) if
40 1) 'dir' is not already in 'dirlist'
41 2) 'dir' actually exists, and is a directory."""
42 if dir is not None and dir not in dirlist:
43 if host_platform == 'darwin' and is_macosx_sdk_path(dir):
44 # If in a macOS SDK path, check relative to the SDK root
45 dir_exists = os.path.isdir(
46 os.path.join(macosx_sdk_root(), dir[1:]))
47 else:
48 dir_exists = os.path.isdir(dir)
49 if dir_exists:
50 dirlist.insert(0, dir)
51
52 MACOS_SDK_ROOT = None
53
54 def macosx_sdk_root():
55 """Return the directory of the current macOS SDK.
56
57 If no SDK was explicitly configured, call the compiler to find which
58 include files paths are being searched by default. Use '/' if the
59 compiler is searching /usr/include (meaning system header files are
60 installed) or use the root of an SDK if that is being searched.
61 (The SDK may be supplied via Xcode or via the Command Line Tools).
62 The SDK paths used by Apple-supplied tool chains depend on the
63 setting of various variables; see the xcrun man page for more info.
64 """
65 global MACOS_SDK_ROOT
66
67 # If already called, return cached result.
68 if MACOS_SDK_ROOT:
69 return MACOS_SDK_ROOT
70
71 cflags = sysconfig.get_config_var('CFLAGS')
72 m = re.search(r'-isysroot\s+(\S+)', cflags)
73 if m is not None:
74 MACOS_SDK_ROOT = m.group(1)
75 else:
76 MACOS_SDK_ROOT = '/'
77 cc = sysconfig.get_config_var('CC')
78 tmpfile = '/tmp/setup_sdk_root.%d' % os.getpid()
79 try:
80 os.unlink(tmpfile)
81 except:
82 pass
83 ret = os.system('%s -E -v - </dev/null 2>%s 1>/dev/null' % (cc, tmpfile))
84 in_incdirs = False
85 try:
86 if ret >> 8 == 0:
87 with open(tmpfile) as fp:
88 for line in fp.readlines():
89 if line.startswith("#include <...>"):
90 in_incdirs = True
91 elif line.startswith("End of search list"):
92 in_incdirs = False
93 elif in_incdirs:
94 line = line.strip()
95 if line == '/usr/include':
96 MACOS_SDK_ROOT = '/'
97 elif line.endswith(".sdk/usr/include"):
98 MACOS_SDK_ROOT = line[:-12]
99 finally:
100 os.unlink(tmpfile)
101
102 return MACOS_SDK_ROOT
103
104 def is_macosx_sdk_path(path):
105 """
106 Returns True if 'path' can be located in an OSX SDK
107 """
108 return ( (path.startswith('/usr/') and not path.startswith('/usr/local'))
109 or path.startswith('/System/')
110 or path.startswith('/Library/') )
111
112 def find_file(filename, std_dirs, paths):
113 """Searches for the directory where a given file is located,
114 and returns a possibly-empty list of additional directories, or None
115 if the file couldn't be found at all.
116
117 'filename' is the name of a file, such as readline.h or libcrypto.a.
118 'std_dirs' is the list of standard system directories; if the
119 file is found in one of them, no additional directives are needed.
120 'paths' is a list of additional locations to check; if the file is
121 found in one of them, the resulting list will contain the directory.
122 """
123 if host_platform == 'darwin':
124 # Honor the MacOSX SDK setting when one was specified.
125 # An SDK is a directory with the same structure as a real
126 # system, but with only header files and libraries.
127 sysroot = macosx_sdk_root()
128
129 # Check the standard locations
130 for dir in std_dirs:
131 f = os.path.join(dir, filename)
132
133 if host_platform == 'darwin' and is_macosx_sdk_path(dir):
134 f = os.path.join(sysroot, dir[1:], filename)
135
136 if os.path.exists(f): return []
137
138 # Check the additional directories
139 for dir in paths:
140 f = os.path.join(dir, filename)
141
142 if host_platform == 'darwin' and is_macosx_sdk_path(dir):
143 f = os.path.join(sysroot, dir[1:], filename)
144
145 if os.path.exists(f):
146 return [dir]
147
148 # Not found anywhere
149 return None
150
151 def find_library_file(compiler, libname, std_dirs, paths):
152 result = compiler.find_library_file(std_dirs + paths, libname)
153 if result is None:
154 return None
155
156 if host_platform == 'darwin':
157 sysroot = macosx_sdk_root()
158
159 # Check whether the found file is in one of the standard directories
160 dirname = os.path.dirname(result)
161 for p in std_dirs:
162 # Ensure path doesn't end with path separator
163 p = p.rstrip(os.sep)
164
165 if host_platform == 'darwin' and is_macosx_sdk_path(p):
166 # Note that, as of Xcode 7, Apple SDKs may contain textual stub
167 # libraries with .tbd extensions rather than the normal .dylib
168 # shared libraries installed in /. The Apple compiler tool
169 # chain handles this transparently but it can cause problems
170 # for programs that are being built with an SDK and searching
171 # for specific libraries. Distutils find_library_file() now
172 # knows to also search for and return .tbd files. But callers
173 # of find_library_file need to keep in mind that the base filename
174 # of the returned SDK library file might have a different extension
175 # from that of the library file installed on the running system,
176 # for example:
177 # /Applications/Xcode.app/Contents/Developer/Platforms/
178 # MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
179 # usr/lib/libedit.tbd
180 # vs
181 # /usr/lib/libedit.dylib
182 if os.path.join(sysroot, p[1:]) == dirname:
183 return [ ]
184
185 if p == dirname:
186 return [ ]
187
188 # Otherwise, it must have been in one of the additional directories,
189 # so we have to figure out which one.
190 for p in paths:
191 # Ensure path doesn't end with path separator
192 p = p.rstrip(os.sep)
193
194 if host_platform == 'darwin' and is_macosx_sdk_path(p):
195 if os.path.join(sysroot, p[1:]) == dirname:
196 return [ p ]
197
198 if p == dirname:
199 return [p]
200 else:
201 assert False, "Internal error: Path not found in std_dirs or paths"
202
203 def module_enabled(extlist, modname):
204 """Returns whether the module 'modname' is present in the list
205 of extensions 'extlist'."""
206 extlist = [ext for ext in extlist if ext.name == modname]
207 return len(extlist)
208
209 def find_module_file(module, dirlist):
210 """Find a module in a set of possible folders. If it is not found
211 return the unadorned filename"""
212 list = find_file(module, [], dirlist)
213 if not list:
214 return module
215 if len(list) > 1:
216 log.info("WARNING: multiple copies of %s found"%module)
217 return os.path.join(list[0], module)
218
219 class PyBuildExt(build_ext):
220
221 def __init__(self, dist):
222 build_ext.__init__(self, dist)
223 self.failed = []
224
225 def build_extensions(self):
226
227 # Detect which modules should be compiled
228 missing = self.detect_modules()
229
230 # Remove modules that are present on the disabled list
231 extensions = [ext for ext in self.extensions
232 if ext.name not in disabled_module_list]
233 # move ctypes to the end, it depends on other modules
234 ext_map = dict((ext.name, i) for i, ext in enumerate(extensions))
235 if "_ctypes" in ext_map:
236 ctypes = extensions.pop(ext_map["_ctypes"])
237 extensions.append(ctypes)
238 self.extensions = extensions
239
240 # Fix up the autodetected modules, prefixing all the source files
241 # with Modules/ and adding Python's include directory to the path.
242 (srcdir,) = sysconfig.get_config_vars('srcdir')
243 if not srcdir:
244 # Maybe running on Windows but not using CYGWIN?
245 raise ValueError("No source directory; cannot proceed.")
246 srcdir = os.path.abspath(srcdir)
247 moddirlist = [os.path.join(srcdir, 'Modules')]
248
249 # Platform-dependent module source and include directories
250 incdirlist = []
251
252 if host_platform == 'darwin' and ("--disable-toolbox-glue" not in
253 sysconfig.get_config_var("CONFIG_ARGS")):
254 # Mac OS X also includes some mac-specific modules
255 macmoddir = os.path.join(srcdir, 'Mac/Modules')
256 moddirlist.append(macmoddir)
257 incdirlist.append(os.path.join(srcdir, 'Mac/Include'))
258
259 # Fix up the paths for scripts, too
260 self.distribution.scripts = [os.path.join(srcdir, filename)
261 for filename in self.distribution.scripts]
262
263 # Python header files
264 headers = [sysconfig.get_config_h_filename()]
265 headers += glob(os.path.join(sysconfig.get_path('include'), "*.h"))
266 for ext in self.extensions[:]:
267 ext.sources = [ find_module_file(filename, moddirlist)
268 for filename in ext.sources ]
269 if ext.depends is not None:
270 ext.depends = [find_module_file(filename, moddirlist)
271 for filename in ext.depends]
272 else:
273 ext.depends = []
274 # re-compile extensions if a header file has been changed
275 ext.depends.extend(headers)
276
277 # platform specific include directories
278 ext.include_dirs.extend(incdirlist)
279
280 # If a module has already been built statically,
281 # don't build it here
282 if ext.name in sys.builtin_module_names:
283 self.extensions.remove(ext)
284
285 # Parse Modules/Setup and Modules/Setup.local to figure out which
286 # modules are turned on in the file.
287 remove_modules = []
288 for filename in ('Modules/Setup', 'Modules/Setup.local'):
289 input = text_file.TextFile(filename, join_lines=1)
290 while 1:
291 line = input.readline()
292 if not line: break
293 line = line.split()
294 remove_modules.append(line[0])
295 input.close()
296
297 for ext in self.extensions[:]:
298 if ext.name in remove_modules:
299 self.extensions.remove(ext)
300
301 # When you run "make CC=altcc" or something similar, you really want
302 # those environment variables passed into the setup.py phase. Here's
303 # a small set of useful ones.
304 compiler = os.environ.get('CC')
305 args = {}
306 # unfortunately, distutils doesn't let us provide separate C and C++
307 # compilers
308 if compiler is not None:
309 (ccshared,cflags) = sysconfig.get_config_vars('CCSHARED','CFLAGS')
310 args['compiler_so'] = compiler + ' ' + ccshared + ' ' + cflags
311 self.compiler.set_executables(**args)
312
313 build_ext.build_extensions(self)
314
315 longest = 0
316 if self.extensions:
317 longest = max([len(e.name) for e in self.extensions])
318 if self.failed:
319 longest = max(longest, max([len(name) for name in self.failed]))
320
321 def print_three_column(lst):
322 lst.sort(key=str.lower)
323 # guarantee zip() doesn't drop anything
324 while len(lst) % 3:
325 lst.append("")
326 for e, f, g in zip(lst[::3], lst[1::3], lst[2::3]):
327 print "%-*s %-*s %-*s" % (longest, e, longest, f,
328 longest, g)
329
330 if missing:
331 print
332 print ("Python build finished, but the necessary bits to build "
333 "these modules were not found:")
334 print_three_column(missing)
335 print ("To find the necessary bits, look in setup.py in"
336 " detect_modules() for the module's name.")
337 print
338
339 if self.failed:
340 failed = self.failed[:]
341 print
342 print "Failed to build these modules:"
343 print_three_column(failed)
344 print
345
346 def build_extension(self, ext):
347
348 if ext.name == '_ctypes':
349 if not self.configure_ctypes(ext):
350 return
351
352 try:
353 build_ext.build_extension(self, ext)
354 except (CCompilerError, DistutilsError), why:
355 self.announce('WARNING: building of extension "%s" failed: %s' %
356 (ext.name, sys.exc_info()[1]))
357 self.failed.append(ext.name)
358 return
359 # Workaround for Mac OS X: The Carbon-based modules cannot be
360 # reliably imported into a command-line Python
361 if 'Carbon' in ext.extra_link_args:
362 self.announce(
363 'WARNING: skipping import check for Carbon-based "%s"' %
364 ext.name)
365 return
366
367 if host_platform == 'darwin' and (
368 sys.maxint > 2**32 and '-arch' in ext.extra_link_args):
369 # Don't bother doing an import check when an extension was
370 # build with an explicit '-arch' flag on OSX. That's currently
371 # only used to build 32-bit only extensions in a 4-way
372 # universal build and loading 32-bit code into a 64-bit
373 # process will fail.
374 self.announce(
375 'WARNING: skipping import check for "%s"' %
376 ext.name)
377 return
378
379 # Workaround for Cygwin: Cygwin currently has fork issues when many
380 # modules have been imported
381 if host_platform == 'cygwin':
382 self.announce('WARNING: skipping import check for Cygwin-based "%s"'
383 % ext.name)
384 return
385 ext_filename = os.path.join(
386 self.build_lib,
387 self.get_ext_filename(self.get_ext_fullname(ext.name)))
388
389 # Don't try to load extensions for cross builds
390 if cross_compiling:
391 return
392
393 try:
394 imp.load_dynamic(ext.name, ext_filename)
395 except ImportError, why:
396 self.failed.append(ext.name)
397 self.announce('*** WARNING: renaming "%s" since importing it'
398 ' failed: %s' % (ext.name, why), level=3)
399 assert not self.inplace
400 basename, tail = os.path.splitext(ext_filename)
401 newname = basename + "_failed" + tail
402 if os.path.exists(newname):
403 os.remove(newname)
404 os.rename(ext_filename, newname)
405
406 # XXX -- This relies on a Vile HACK in
407 # distutils.command.build_ext.build_extension(). The
408 # _built_objects attribute is stored there strictly for
409 # use here.
410 # If there is a failure, _built_objects may not be there,
411 # so catch the AttributeError and move on.
412 try:
413 for filename in self._built_objects:
414 os.remove(filename)
415 except AttributeError:
416 self.announce('unable to remove files (ignored)')
417 except:
418 exc_type, why, tb = sys.exc_info()
419 self.announce('*** WARNING: importing extension "%s" '
420 'failed with %s: %s' % (ext.name, exc_type, why),
421 level=3)
422 self.failed.append(ext.name)
423
424 def add_multiarch_paths(self):
425 # Debian/Ubuntu multiarch support.
426 # https://wiki.ubuntu.com/MultiarchSpec
427 cc = sysconfig.get_config_var('CC')
428 tmpfile = os.path.join(self.build_temp, 'multiarch')
429 if not os.path.exists(self.build_temp):
430 os.makedirs(self.build_temp)
431 ret = os.system(
432 '%s -print-multiarch > %s 2> /dev/null' % (cc, tmpfile))
433 multiarch_path_component = ''
434 try:
435 if ret >> 8 == 0:
436 with open(tmpfile) as fp:
437 multiarch_path_component = fp.readline().strip()
438 finally:
439 os.unlink(tmpfile)
440
441 if multiarch_path_component != '':
442 add_dir_to_list(self.compiler.library_dirs,
443 '/usr/lib/' + multiarch_path_component)
444 add_dir_to_list(self.compiler.include_dirs,
445 '/usr/include/' + multiarch_path_component)
446 return
447
448 if not find_executable('dpkg-architecture'):
449 return
450 opt = ''
451 if cross_compiling:
452 opt = '-t' + sysconfig.get_config_var('HOST_GNU_TYPE')
453 tmpfile = os.path.join(self.build_temp, 'multiarch')
454 if not os.path.exists(self.build_temp):
455 os.makedirs(self.build_temp)
456 ret = os.system(
457 'dpkg-architecture %s -qDEB_HOST_MULTIARCH > %s 2> /dev/null' %
458 (opt, tmpfile))
459 try:
460 if ret >> 8 == 0:
461 with open(tmpfile) as fp:
462 multiarch_path_component = fp.readline().strip()
463 add_dir_to_list(self.compiler.library_dirs,
464 '/usr/lib/' + multiarch_path_component)
465 add_dir_to_list(self.compiler.include_dirs,
466 '/usr/include/' + multiarch_path_component)
467 finally:
468 os.unlink(tmpfile)
469
470 def add_gcc_paths(self):
471 gcc = sysconfig.get_config_var('CC')
472 tmpfile = os.path.join(self.build_temp, 'gccpaths')
473 if not os.path.exists(self.build_temp):
474 os.makedirs(self.build_temp)
475 ret = os.system('%s -E -v - </dev/null 2>%s 1>/dev/null' % (gcc, tmpfile))
476 is_gcc = False
477 in_incdirs = False
478 inc_dirs = []
479 lib_dirs = []
480 try:
481 if ret >> 8 == 0:
482 with open(tmpfile) as fp:
483 for line in fp.readlines():
484 if line.startswith("gcc version"):
485 is_gcc = True
486 elif line.startswith("#include <...>"):
487 in_incdirs = True
488 elif line.startswith("End of search list"):
489 in_incdirs = False
490 elif is_gcc and line.startswith("LIBRARY_PATH"):
491 for d in line.strip().split("=")[1].split(":"):
492 d = os.path.normpath(d)
493 if '/gcc/' not in d:
494 add_dir_to_list(self.compiler.library_dirs,
495 d)
496 elif is_gcc and in_incdirs and '/gcc/' not in line:
497 add_dir_to_list(self.compiler.include_dirs,
498 line.strip())
499 finally:
500 os.unlink(tmpfile)
501
502 def detect_modules(self):
503 # Ensure that /usr/local is always used
504 if not cross_compiling:
505 add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
506 add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
507 if cross_compiling:
508 self.add_gcc_paths()
509 self.add_multiarch_paths()
510
511 # Add paths specified in the environment variables LDFLAGS and
512 # CPPFLAGS for header and library files.
513 # We must get the values from the Makefile and not the environment
514 # directly since an inconsistently reproducible issue comes up where
515 # the environment variable is not set even though the value were passed
516 # into configure and stored in the Makefile (issue found on OS X 10.3).
517 for env_var, arg_name, dir_list in (
518 ('LDFLAGS', '-R', self.compiler.runtime_library_dirs),
519 ('LDFLAGS', '-L', self.compiler.library_dirs),
520 ('CPPFLAGS', '-I', self.compiler.include_dirs)):
521 env_val = sysconfig.get_config_var(env_var)
522 if env_val:
523 # To prevent optparse from raising an exception about any
524 # options in env_val that it doesn't know about we strip out
525 # all double dashes and any dashes followed by a character
526 # that is not for the option we are dealing with.
527 #
528 # Please note that order of the regex is important! We must
529 # strip out double-dashes first so that we don't end up with
530 # substituting "--Long" to "-Long" and thus lead to "ong" being
531 # used for a library directory.
532 env_val = re.sub(r'(^|\s+)-(-|(?!%s))' % arg_name[1],
533 ' ', env_val)
534 parser = optparse.OptionParser()
535 # Make sure that allowing args interspersed with options is
536 # allowed
537 parser.allow_interspersed_args = True
538 parser.error = lambda msg: None
539 parser.add_option(arg_name, dest="dirs", action="append")
540 options = parser.parse_args(env_val.split())[0]
541 if options.dirs:
542 for directory in reversed(options.dirs):
543 add_dir_to_list(dir_list, directory)
544
545 if os.path.normpath(sys.prefix) != '/usr' \
546 and not sysconfig.get_config_var('PYTHONFRAMEWORK'):
547 # OSX note: Don't add LIBDIR and INCLUDEDIR to building a framework
548 # (PYTHONFRAMEWORK is set) to avoid # linking problems when
549 # building a framework with different architectures than
550 # the one that is currently installed (issue #7473)
551 add_dir_to_list(self.compiler.library_dirs,
552 sysconfig.get_config_var("LIBDIR"))
553 add_dir_to_list(self.compiler.include_dirs,
554 sysconfig.get_config_var("INCLUDEDIR"))
555
556 try:
557 have_unicode = unicode
558 except NameError:
559 have_unicode = 0
560
561 # lib_dirs and inc_dirs are used to search for files;
562 # if a file is found in one of those directories, it can
563 # be assumed that no additional -I,-L directives are needed.
564 inc_dirs = self.compiler.include_dirs[:]
565 lib_dirs = self.compiler.library_dirs[:]
566 if not cross_compiling:
567 for d in (
568 '/usr/include',
569 ):
570 add_dir_to_list(inc_dirs, d)
571 for d in (
572 '/lib64', '/usr/lib64',
573 '/lib', '/usr/lib',
574 ):
575 add_dir_to_list(lib_dirs, d)
576 exts = []
577 missing = []
578
579 config_h = sysconfig.get_config_h_filename()
580 config_h_vars = sysconfig.parse_config_h(open(config_h))
581
582 srcdir = sysconfig.get_config_var('srcdir')
583
584 # Check for AtheOS which has libraries in non-standard locations
585 if host_platform == 'atheos':
586 lib_dirs += ['/system/libs', '/atheos/autolnk/lib']
587 lib_dirs += os.getenv('LIBRARY_PATH', '').split(os.pathsep)
588 inc_dirs += ['/system/include', '/atheos/autolnk/include']
589 inc_dirs += os.getenv('C_INCLUDE_PATH', '').split(os.pathsep)
590
591 # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
592 if host_platform in ['osf1', 'unixware7', 'openunix8']:
593 lib_dirs += ['/usr/ccs/lib']
594
595 # HP-UX11iv3 keeps files in lib/hpux folders.
596 if host_platform == 'hp-ux11':
597 lib_dirs += ['/usr/lib/hpux64', '/usr/lib/hpux32']
598
599 if host_platform == 'darwin':
600 # This should work on any unixy platform ;-)
601 # If the user has bothered specifying additional -I and -L flags
602 # in OPT and LDFLAGS we might as well use them here.
603 # NOTE: using shlex.split would technically be more correct, but
604 # also gives a bootstrap problem. Let's hope nobody uses directories
605 # with whitespace in the name to store libraries.
606 cflags, ldflags = sysconfig.get_config_vars(
607 'CFLAGS', 'LDFLAGS')
608 for item in cflags.split():
609 if item.startswith('-I'):
610 inc_dirs.append(item[2:])
611
612 for item in ldflags.split():
613 if item.startswith('-L'):
614 lib_dirs.append(item[2:])
615
616 # Check for MacOS X, which doesn't need libm.a at all
617 math_libs = ['m']
618 if host_platform in ['darwin', 'beos']:
619 math_libs = []
620
621 # XXX Omitted modules: gl, pure, dl, SGI-specific modules
622
623 #
624 # The following modules are all pretty straightforward, and compile
625 # on pretty much any POSIXish platform.
626 #
627
628 # Some modules that are normally always on:
629 #exts.append( Extension('_weakref', ['_weakref.c']) )
630
631 # array objects
632 exts.append( Extension('array', ['arraymodule.c']) )
633
634 shared_math = 'Modules/_math.o'
635 # complex math library functions
636 exts.append( Extension('cmath', ['cmathmodule.c'],
637 extra_objects=[shared_math],
638 depends=['_math.h', shared_math],
639 libraries=math_libs) )
640 # math library functions, e.g. sin()
641 exts.append( Extension('math', ['mathmodule.c'],
642 extra_objects=[shared_math],
643 depends=['_math.h', shared_math],
644 libraries=math_libs) )
645 # fast string operations implemented in C
646 exts.append( Extension('strop', ['stropmodule.c']) )
647 # time operations and variables
648 exts.append( Extension('time', ['timemodule.c'],
649 libraries=math_libs) )
650 exts.append( Extension('datetime', ['datetimemodule.c', 'timemodule.c'],
651 libraries=math_libs) )
652 # fast iterator tools implemented in C
653 exts.append( Extension("itertools", ["itertoolsmodule.c"]) )
654 # code that will be builtins in the future, but conflict with the
655 # current builtins
656 exts.append( Extension('future_builtins', ['future_builtins.c']) )
657 # random number generator implemented in C
658 exts.append( Extension("_random", ["_randommodule.c"]) )
659 # high-performance collections
660 exts.append( Extension("_collections", ["_collectionsmodule.c"]) )
661 # bisect
662 exts.append( Extension("_bisect", ["_bisectmodule.c"]) )
663 # heapq
664 exts.append( Extension("_heapq", ["_heapqmodule.c"]) )
665 # operator.add() and similar goodies
666 exts.append( Extension('operator', ['operator.c']) )
667 # Python 3.1 _io library
668 exts.append( Extension("_io",
669 ["_io/bufferedio.c", "_io/bytesio.c", "_io/fileio.c",
670 "_io/iobase.c", "_io/_iomodule.c", "_io/stringio.c", "_io/textio.c"],
671 depends=["_io/_iomodule.h"], include_dirs=["Modules/_io"]))
672 # _functools
673 exts.append( Extension("_functools", ["_functoolsmodule.c"]) )
674 # _json speedups
675 exts.append( Extension("_json", ["_json.c"]) )
676 # Python C API test module
677 exts.append( Extension('_testcapi', ['_testcapimodule.c'],
678 depends=['testcapi_long.h']) )
679 # profilers (_lsprof is for cProfile.py)
680 exts.append( Extension('_hotshot', ['_hotshot.c']) )
681 exts.append( Extension('_lsprof', ['_lsprof.c', 'rotatingtree.c']) )
682 # static Unicode character database
683 if have_unicode:
684 exts.append( Extension('unicodedata', ['unicodedata.c']) )
685 else:
686 missing.append('unicodedata')
687 # access to ISO C locale support
688 data = open('pyconfig.h').read()
689 m = re.search(r"#s*define\s+WITH_LIBINTL\s+1\s*", data)
690 if m is not None:
691 locale_libs = ['intl']
692 else:
693 locale_libs = []
694 if host_platform == 'darwin':
695 locale_extra_link_args = ['-framework', 'CoreFoundation']
696 else:
697 locale_extra_link_args = []
698
699
700 exts.append( Extension('_locale', ['_localemodule.c'],
701 libraries=locale_libs,
702 extra_link_args=locale_extra_link_args) )
703
704 # Modules with some UNIX dependencies -- on by default:
705 # (If you have a really backward UNIX, select and socket may not be
706 # supported...)
707
708 # fcntl(2) and ioctl(2)
709 libs = []
710 if (config_h_vars.get('FLOCK_NEEDS_LIBBSD', False)):
711 # May be necessary on AIX for flock function
712 libs = ['bsd']
713 exts.append( Extension('fcntl', ['fcntlmodule.c'], libraries=libs) )
714 # pwd(3)
715 exts.append( Extension('pwd', ['pwdmodule.c']) )
716 # grp(3)
717 exts.append( Extension('grp', ['grpmodule.c']) )
718 # spwd, shadow passwords
719 if (config_h_vars.get('HAVE_GETSPNAM', False) or
720 config_h_vars.get('HAVE_GETSPENT', False)):
721 exts.append( Extension('spwd', ['spwdmodule.c']) )
722 else:
723 missing.append('spwd')
724
725 # select(2); not on ancient System V
726 exts.append( Extension('select', ['selectmodule.c']) )
727
728 # Fred Drake's interface to the Python parser
729 exts.append( Extension('parser', ['parsermodule.c']) )
730
731 # cStringIO and cPickle
732 exts.append( Extension('cStringIO', ['cStringIO.c']) )
733 exts.append( Extension('cPickle', ['cPickle.c']) )
734
735 # Memory-mapped files (also works on Win32).
736 if host_platform not in ['atheos']:
737 exts.append( Extension('mmap', ['mmapmodule.c']) )
738 else:
739 missing.append('mmap')
740
741 # Lance Ellinghaus's syslog module
742 # syslog daemon interface
743 exts.append( Extension('syslog', ['syslogmodule.c']) )
744
745 # George Neville-Neil's timing module:
746 # Deprecated in PEP 4 http://www.python.org/peps/pep-0004.html
747 # http://mail.python.org/pipermail/python-dev/2006-January/060023.html
748 #exts.append( Extension('timing', ['timingmodule.c']) )
749
750 #
751 # Here ends the simple stuff. From here on, modules need certain
752 # libraries, are platform-specific, or present other surprises.
753 #
754
755 # Multimedia modules
756 # These don't work for 64-bit platforms!!!
757 # These represent audio samples or images as strings:
758
759 # Operations on audio samples
760 # According to #993173, this one should actually work fine on
761 # 64-bit platforms.
762 exts.append( Extension('audioop', ['audioop.c']) )
763
764 # Disabled on 64-bit platforms
765 if sys.maxsize != 9223372036854775807L:
766 # Operations on images
767 exts.append( Extension('imageop', ['imageop.c']) )
768 else:
769 missing.extend(['imageop'])
770
771 # readline
772 do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
773 readline_termcap_library = ""
774 curses_library = ""
775 # Determine if readline is already linked against curses or tinfo.
776 if do_readline and find_executable('ldd'):
777 fp = os.popen("ldd %s" % do_readline)
778 ldd_output = fp.readlines()
779 ret = fp.close()
780 if ret is None or ret >> 8 == 0:
781 for ln in ldd_output:
782 if 'curses' in ln:
783 readline_termcap_library = re.sub(
784 r'.*lib(n?cursesw?)\.so.*', r'\1', ln
785 ).rstrip()
786 break
787 if 'tinfo' in ln: # termcap interface split out from ncurses
788 readline_termcap_library = 'tinfo'
789 break
790 # Issue 7384: If readline is already linked against curses,
791 # use the same library for the readline and curses modules.
792 if 'curses' in readline_termcap_library:
793 curses_library = readline_termcap_library
794 elif self.compiler.find_library_file(lib_dirs, 'ncursesw'):
795 curses_library = 'ncursesw'
796 elif self.compiler.find_library_file(lib_dirs, 'ncurses'):
797 curses_library = 'ncurses'
798 elif self.compiler.find_library_file(lib_dirs, 'curses'):
799 curses_library = 'curses'
800
801 if host_platform == 'darwin':
802 os_release = int(os.uname()[2].split('.')[0])
803 dep_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
804 if (dep_target and
805 (tuple(int(n) for n in dep_target.split('.')[0:2])
806 < (10, 5) ) ):
807 os_release = 8
808 if os_release < 9:
809 # MacOSX 10.4 has a broken readline. Don't try to build
810 # the readline module unless the user has installed a fixed
811 # readline package
812 if find_file('readline/rlconf.h', inc_dirs, []) is None:
813 do_readline = False
814 if do_readline:
815 if host_platform == 'darwin' and os_release < 9:
816 # In every directory on the search path search for a dynamic
817 # library and then a static library, instead of first looking
818 # for dynamic libraries on the entire path.
819 # This way a statically linked custom readline gets picked up
820 # before the (possibly broken) dynamic library in /usr/lib.
821 readline_extra_link_args = ('-Wl,-search_paths_first',)
822 else:
823 readline_extra_link_args = ()
824
825 readline_libs = ['readline']
826 if readline_termcap_library:
827 pass # Issue 7384: Already linked against curses or tinfo.
828 elif curses_library:
829 readline_libs.append(curses_library)
830 elif self.compiler.find_library_file(lib_dirs +
831 ['/usr/lib/termcap'],
832 'termcap'):
833 readline_libs.append('termcap')
834 exts.append( Extension('readline', ['readline.c'],
835 library_dirs=['/usr/lib/termcap'],
836 extra_link_args=readline_extra_link_args,
837 libraries=readline_libs) )
838 else:
839 missing.append('readline')
840
841 # crypt module.
842
843 if self.compiler.find_library_file(lib_dirs, 'crypt'):
844 libs = ['crypt']
845 else:
846 libs = []
847 exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
848
849 # CSV files
850 exts.append( Extension('_csv', ['_csv.c']) )
851
852 # socket(2)
853 exts.append( Extension('_socket', ['socketmodule.c', 'timemodule.c'],
854 depends=['socketmodule.h'],
855 libraries=math_libs) )
856 # Detect SSL support for the socket module (via _ssl)
857 search_for_ssl_incs_in = [
858 '/usr/local/ssl/include',
859 '/usr/contrib/ssl/include/'
860 ]
861 ssl_incs = find_file('openssl/ssl.h', inc_dirs,
862 search_for_ssl_incs_in
863 )
864 if ssl_incs is not None:
865 krb5_h = find_file('krb5.h', inc_dirs,
866 ['/usr/kerberos/include'])
867 if krb5_h:
868 ssl_incs += krb5_h
869 ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
870 ['/usr/local/ssl/lib',
871 '/usr/contrib/ssl/lib/'
872 ] )
873
874 if (ssl_incs is not None and
875 ssl_libs is not None):
876 exts.append( Extension('_ssl', ['_ssl.c'],
877 include_dirs = ssl_incs,
878 library_dirs = ssl_libs,
879 libraries = ['ssl', 'crypto'],
880 depends = ['socketmodule.h']), )
881 else:
882 missing.append('_ssl')
883
884 # find out which version of OpenSSL we have
885 openssl_ver = 0
886 openssl_ver_re = re.compile(
887 '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' )
888
889 # look for the openssl version header on the compiler search path.
890 opensslv_h = find_file('openssl/opensslv.h', [],
891 inc_dirs + search_for_ssl_incs_in)
892 if opensslv_h:
893 name = os.path.join(opensslv_h[0], 'openssl/opensslv.h')
894 if host_platform == 'darwin' and is_macosx_sdk_path(name):
895 name = os.path.join(macosx_sdk_root(), name[1:])
896 try:
897 incfile = open(name, 'r')
898 for line in incfile:
899 m = openssl_ver_re.match(line)
900 if m:
901 openssl_ver = eval(m.group(1))
902 except IOError, msg:
903 print "IOError while reading opensshv.h:", msg
904 pass
905
906 min_openssl_ver = 0x00907000
907 have_any_openssl = ssl_incs is not None and ssl_libs is not None
908 have_usable_openssl = (have_any_openssl and
909 openssl_ver >= min_openssl_ver)
910
911 if have_any_openssl:
912 if have_usable_openssl:
913 # The _hashlib module wraps optimized implementations
914 # of hash functions from the OpenSSL library.
915 exts.append( Extension('_hashlib', ['_hashopenssl.c'],
916 include_dirs = ssl_incs,
917 library_dirs = ssl_libs,
918 libraries = ['ssl', 'crypto']) )
919 else:
920 print ("warning: openssl 0x%08x is too old for _hashlib" %
921 openssl_ver)
922 missing.append('_hashlib')
923 if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
924 # The _sha module implements the SHA1 hash algorithm.
925 exts.append( Extension('_sha', ['shamodule.c']) )
926 # The _md5 module implements the RSA Data Security, Inc. MD5
927 # Message-Digest Algorithm, described in RFC 1321. The
928 # necessary files md5.c and md5.h are included here.
929 exts.append( Extension('_md5',
930 sources = ['md5module.c', 'md5.c'],
931 depends = ['md5.h']) )
932
933 min_sha2_openssl_ver = 0x00908000
934 if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
935 # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
936 exts.append( Extension('_sha256', ['sha256module.c']) )
937 exts.append( Extension('_sha512', ['sha512module.c']) )
938
939 # Modules that provide persistent dictionary-like semantics. You will
940 # probably want to arrange for at least one of them to be available on
941 # your machine, though none are defined by default because of library
942 # dependencies. The Python module anydbm.py provides an
943 # implementation independent wrapper for these; dumbdbm.py provides
944 # similar functionality (but slower of course) implemented in Python.
945
946 # Sleepycat^WOracle Berkeley DB interface.
947 # http://www.oracle.com/database/berkeley-db/db/index.html
948 #
949 # This requires the Sleepycat^WOracle DB code. The supported versions
950 # are set below. Visit the URL above to download
951 # a release. Most open source OSes come with one or more
952 # versions of BerkeleyDB already installed.
953
954 max_db_ver = (5, 3)
955 min_db_ver = (4, 3)
956 db_setup_debug = False # verbose debug prints from this script?
957
958 def allow_db_ver(db_ver):
959 """Returns a boolean if the given BerkeleyDB version is acceptable.
960
961 Args:
962 db_ver: A tuple of the version to verify.
963 """
964 if not (min_db_ver <= db_ver <= max_db_ver):
965 return False
966 # Use this function to filter out known bad configurations.
967 if (4, 6) == db_ver[:2]:
968 # BerkeleyDB 4.6.x is not stable on many architectures.
969 arch = platform_machine()
970 if arch not in ('i386', 'i486', 'i586', 'i686',
971 'x86_64', 'ia64'):
972 return False
973 return True
974
975 def gen_db_minor_ver_nums(major):
976 if major == 5:
977 for x in range(max_db_ver[1]+1):
978 if allow_db_ver((5, x)):
979 yield x
980 elif major == 4:
981 for x in range(9):
982 if allow_db_ver((4, x)):
983 yield x
984 elif major == 3:
985 for x in (3,):
986 if allow_db_ver((3, x)):
987 yield x
988 else:
989 raise ValueError("unknown major BerkeleyDB version", major)
990
991 # construct a list of paths to look for the header file in on
992 # top of the normal inc_dirs.
993 db_inc_paths = [
994 '/usr/include/db4',
995 '/usr/local/include/db4',
996 '/opt/sfw/include/db4',
997 '/usr/include/db3',
998 '/usr/local/include/db3',
999 '/opt/sfw/include/db3',
1000 # Fink defaults (http://fink.sourceforge.net/)
1001 '/sw/include/db4',
1002 '/sw/include/db3',
1003 ]
1004 # 4.x minor number specific paths
1005 for x in gen_db_minor_ver_nums(4):
1006 db_inc_paths.append('/usr/include/db4%d' % x)
1007 db_inc_paths.append('/usr/include/db4.%d' % x)
1008 db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x)
1009 db_inc_paths.append('/usr/local/include/db4%d' % x)
1010 db_inc_paths.append('/pkg/db-4.%d/include' % x)
1011 db_inc_paths.append('/opt/db-4.%d/include' % x)
1012 # MacPorts default (http://www.macports.org/)
1013 db_inc_paths.append('/opt/local/include/db4%d' % x)
1014 # 3.x minor number specific paths
1015 for x in gen_db_minor_ver_nums(3):
1016 db_inc_paths.append('/usr/include/db3%d' % x)
1017 db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x)
1018 db_inc_paths.append('/usr/local/include/db3%d' % x)
1019 db_inc_paths.append('/pkg/db-3.%d/include' % x)
1020 db_inc_paths.append('/opt/db-3.%d/include' % x)
1021
1022 if cross_compiling:
1023 db_inc_paths = []
1024
1025 # Add some common subdirectories for Sleepycat DB to the list,
1026 # based on the standard include directories. This way DB3/4 gets
1027 # picked up when it is installed in a non-standard prefix and
1028 # the user has added that prefix into inc_dirs.
1029 std_variants = []
1030 for dn in inc_dirs:
1031 std_variants.append(os.path.join(dn, 'db3'))
1032 std_variants.append(os.path.join(dn, 'db4'))
1033 for x in gen_db_minor_ver_nums(4):
1034 std_variants.append(os.path.join(dn, "db4%d"%x))
1035 std_variants.append(os.path.join(dn, "db4.%d"%x))
1036 for x in gen_db_minor_ver_nums(3):
1037 std_variants.append(os.path.join(dn, "db3%d"%x))
1038 std_variants.append(os.path.join(dn, "db3.%d"%x))
1039
1040 db_inc_paths = std_variants + db_inc_paths
1041 db_inc_paths = [p for p in db_inc_paths if os.path.exists(p)]
1042
1043 db_ver_inc_map = {}
1044
1045 if host_platform == 'darwin':
1046 sysroot = macosx_sdk_root()
1047
1048 class db_found(Exception): pass
1049 try:
1050 # See whether there is a Sleepycat header in the standard
1051 # search path.
1052 for d in inc_dirs + db_inc_paths:
1053 f = os.path.join(d, "db.h")
1054
1055 if host_platform == 'darwin' and is_macosx_sdk_path(d):
1056 f = os.path.join(sysroot, d[1:], "db.h")
1057
1058 if db_setup_debug: print "db: looking for db.h in", f
1059 if os.path.exists(f):
1060 f = open(f).read()
1061 m = re.search(r"#define\WDB_VERSION_MAJOR\W(\d+)", f)
1062 if m:
1063 db_major = int(m.group(1))
1064 m = re.search(r"#define\WDB_VERSION_MINOR\W(\d+)", f)
1065 db_minor = int(m.group(1))
1066 db_ver = (db_major, db_minor)
1067
1068 # Avoid 4.6 prior to 4.6.21 due to a BerkeleyDB bug
1069 if db_ver == (4, 6):
1070 m = re.search(r"#define\WDB_VERSION_PATCH\W(\d+)", f)
1071 db_patch = int(m.group(1))
1072 if db_patch < 21:
1073 print "db.h:", db_ver, "patch", db_patch,
1074 print "being ignored (4.6.x must be >= 4.6.21)"
1075 continue
1076
1077 if ( (db_ver not in db_ver_inc_map) and
1078 allow_db_ver(db_ver) ):
1079 # save the include directory with the db.h version
1080 # (first occurrence only)
1081 db_ver_inc_map[db_ver] = d
1082 if db_setup_debug:
1083 print "db.h: found", db_ver, "in", d
1084 else:
1085 # we already found a header for this library version
1086 if db_setup_debug: print "db.h: ignoring", d
1087 else:
1088 # ignore this header, it didn't contain a version number
1089 if db_setup_debug:
1090 print "db.h: no version number version in", d
1091
1092 db_found_vers = db_ver_inc_map.keys()
1093 db_found_vers.sort()
1094
1095 while db_found_vers:
1096 db_ver = db_found_vers.pop()
1097 db_incdir = db_ver_inc_map[db_ver]
1098
1099 # check lib directories parallel to the location of the header
1100 db_dirs_to_check = [
1101 db_incdir.replace("include", 'lib64'),
1102 db_incdir.replace("include", 'lib'),
1103 ]
1104
1105 if host_platform != 'darwin':
1106 db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
1107
1108 else:
1109 # Same as other branch, but takes OSX SDK into account
1110 tmp = []
1111 for dn in db_dirs_to_check:
1112 if is_macosx_sdk_path(dn):
1113 if os.path.isdir(os.path.join(sysroot, dn[1:])):
1114 tmp.append(dn)
1115 else:
1116 if os.path.isdir(dn):
1117 tmp.append(dn)
1118 db_dirs_to_check = tmp
1119
1120 # Look for a version specific db-X.Y before an ambiguous dbX
1121 # XXX should we -ever- look for a dbX name? Do any
1122 # systems really not name their library by version and
1123 # symlink to more general names?
1124 for dblib in (('db-%d.%d' % db_ver),
1125 ('db%d%d' % db_ver),
1126 ('db%d' % db_ver[0])):
1127 dblib_file = self.compiler.find_library_file(
1128 db_dirs_to_check + lib_dirs, dblib )
1129 if dblib_file:
1130 dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ]
1131 raise db_found
1132 else:
1133 if db_setup_debug: print "db lib: ", dblib, "not found"
1134
1135 except db_found:
1136 if db_setup_debug:
1137 print "bsddb using BerkeleyDB lib:", db_ver, dblib
1138 print "bsddb lib dir:", dblib_dir, " inc dir:", db_incdir
1139 db_incs = [db_incdir]
1140 dblibs = [dblib]
1141 # We add the runtime_library_dirs argument because the
1142 # BerkeleyDB lib we're linking against often isn't in the
1143 # system dynamic library search path. This is usually
1144 # correct and most trouble free, but may cause problems in
1145 # some unusual system configurations (e.g. the directory
1146 # is on an NFS server that goes away).
1147 exts.append(Extension('_bsddb', ['_bsddb.c'],
1148 depends = ['bsddb.h'],
1149 library_dirs=dblib_dir,
1150 runtime_library_dirs=dblib_dir,
1151 include_dirs=db_incs,
1152 libraries=dblibs))
1153 else:
1154 if db_setup_debug: print "db: no appropriate library found"
1155 db_incs = None
1156 dblibs = []
1157 dblib_dir = None
1158 missing.append('_bsddb')
1159
1160 # The sqlite interface
1161 sqlite_setup_debug = False # verbose debug prints from this script?
1162
1163 # We hunt for #define SQLITE_VERSION "n.n.n"
1164 # We need to find >= sqlite version 3.0.8
1165 sqlite_incdir = sqlite_libdir = None
1166 sqlite_inc_paths = [ '/usr/include',
1167 '/usr/include/sqlite',
1168 '/usr/include/sqlite3',
1169 '/usr/local/include',
1170 '/usr/local/include/sqlite',
1171 '/usr/local/include/sqlite3',
1172 ]
1173 if cross_compiling:
1174 sqlite_inc_paths = []
1175 MIN_SQLITE_VERSION_NUMBER = (3, 0, 8)
1176 MIN_SQLITE_VERSION = ".".join([str(x)
1177 for x in MIN_SQLITE_VERSION_NUMBER])
1178
1179 # Scan the default include directories before the SQLite specific
1180 # ones. This allows one to override the copy of sqlite on OSX,
1181 # where /usr/include contains an old version of sqlite.
1182 if host_platform == 'darwin':
1183 sysroot = macosx_sdk_root()
1184
1185 for d_ in inc_dirs + sqlite_inc_paths:
1186 d = d_
1187 if host_platform == 'darwin' and is_macosx_sdk_path(d):
1188 d = os.path.join(sysroot, d[1:])
1189
1190 f = os.path.join(d, "sqlite3.h")
1191 if os.path.exists(f):
1192 if sqlite_setup_debug: print "sqlite: found %s"%f
1193 incf = open(f).read()
1194 m = re.search(
1195 r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"([\d\.]*)"', incf)
1196 if m:
1197 sqlite_version = m.group(1)
1198 sqlite_version_tuple = tuple([int(x)
1199 for x in sqlite_version.split(".")])
1200 if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER:
1201 # we win!
1202 if sqlite_setup_debug:
1203 print "%s/sqlite3.h: version %s"%(d, sqlite_version)
1204 sqlite_incdir = d
1205 break
1206 else:
1207 if sqlite_setup_debug:
1208 print "%s: version %d is too old, need >= %s"%(d,
1209 sqlite_version, MIN_SQLITE_VERSION)
1210 elif sqlite_setup_debug:
1211 print "sqlite: %s had no SQLITE_VERSION"%(f,)
1212
1213 if sqlite_incdir:
1214 sqlite_dirs_to_check = [
1215 os.path.join(sqlite_incdir, '..', 'lib64'),
1216 os.path.join(sqlite_incdir, '..', 'lib'),
1217 os.path.join(sqlite_incdir, '..', '..', 'lib64'),
1218 os.path.join(sqlite_incdir, '..', '..', 'lib'),
1219 ]
1220 sqlite_libfile = self.compiler.find_library_file(
1221 sqlite_dirs_to_check + lib_dirs, 'sqlite3')
1222 if sqlite_libfile:
1223 sqlite_libdir = [os.path.abspath(os.path.dirname(sqlite_libfile))]
1224
1225 if sqlite_incdir and sqlite_libdir:
1226 sqlite_srcs = ['_sqlite/cache.c',
1227 '_sqlite/connection.c',
1228 '_sqlite/cursor.c',
1229 '_sqlite/microprotocols.c',
1230 '_sqlite/module.c',
1231 '_sqlite/prepare_protocol.c',
1232 '_sqlite/row.c',
1233 '_sqlite/statement.c',
1234 '_sqlite/util.c', ]
1235
1236 sqlite_defines = []
1237 if host_platform != "win32":
1238 sqlite_defines.append(('MODULE_NAME', '"sqlite3"'))
1239 else:
1240 sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"'))
1241
1242 # Comment this out if you want the sqlite3 module to be able to load extensions.
1243 sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))
1244
1245 if host_platform == 'darwin':
1246 # In every directory on the search path search for a dynamic
1247 # library and then a static library, instead of first looking
1248 # for dynamic libraries on the entire path.
1249 # This way a statically linked custom sqlite gets picked up
1250 # before the dynamic library in /usr/lib.
1251 sqlite_extra_link_args = ('-Wl,-search_paths_first',)
1252 else:
1253 sqlite_extra_link_args = ()
1254
1255 exts.append(Extension('_sqlite3', sqlite_srcs,
1256 define_macros=sqlite_defines,
1257 include_dirs=["Modules/_sqlite",
1258 sqlite_incdir],
1259 library_dirs=sqlite_libdir,
1260 extra_link_args=sqlite_extra_link_args,
1261 libraries=["sqlite3",]))
1262 else:
1263 missing.append('_sqlite3')
1264
1265 # Look for Berkeley db 1.85. Note that it is built as a different
1266 # module name so it can be included even when later versions are
1267 # available. A very restrictive search is performed to avoid
1268 # accidentally building this module with a later version of the
1269 # underlying db library. May BSD-ish Unixes incorporate db 1.85
1270 # symbols into libc and place the include file in /usr/include.
1271 #
1272 # If the better bsddb library can be built (db_incs is defined)
1273 # we do not build this one. Otherwise this build will pick up
1274 # the more recent berkeleydb's db.h file first in the include path
1275 # when attempting to compile and it will fail.
1276 f = "/usr/include/db.h"
1277
1278 if host_platform == 'darwin':
1279 if is_macosx_sdk_path(f):
1280 sysroot = macosx_sdk_root()
1281 f = os.path.join(sysroot, f[1:])
1282
1283 if os.path.exists(f) and not db_incs:
1284 data = open(f).read()
1285 m = re.search(r"#s*define\s+HASHVERSION\s+2\s*", data)
1286 if m is not None:
1287 # bingo - old version used hash file format version 2
1288 ### XXX this should be fixed to not be platform-dependent
1289 ### but I don't have direct access to an osf1 platform and
1290 ### seemed to be muffing the search somehow
1291 libraries = host_platform == "osf1" and ['db'] or None
1292 if libraries is not None:
1293 exts.append(Extension('bsddb185', ['bsddbmodule.c'],
1294 libraries=libraries))
1295 else:
1296 exts.append(Extension('bsddb185', ['bsddbmodule.c']))
1297 else:
1298 missing.append('bsddb185')
1299 else:
1300 missing.append('bsddb185')
1301
1302 dbm_order = ['gdbm']
1303 # The standard Unix dbm module:
1304 if host_platform not in ['cygwin']:
1305 config_args = [arg.strip("'")
1306 for arg in sysconfig.get_config_var("CONFIG_ARGS").split()]
1307 dbm_args = [arg for arg in config_args
1308 if arg.startswith('--with-dbmliborder=')]
1309 if dbm_args:
1310 dbm_order = [arg.split('=')[-1] for arg in dbm_args][-1].split(":")
1311 else:
1312 dbm_order = "ndbm:gdbm:bdb".split(":")
1313 dbmext = None
1314 for cand in dbm_order:
1315 if cand == "ndbm":
1316 if find_file("ndbm.h", inc_dirs, []) is not None:
1317 # Some systems have -lndbm, others have -lgdbm_compat,
1318 # others don't have either
1319 if self.compiler.find_library_file(lib_dirs,
1320 'ndbm'):
1321 ndbm_libs = ['ndbm']
1322 elif self.compiler.find_library_file(lib_dirs,
1323 'gdbm_compat'):
1324 ndbm_libs = ['gdbm_compat']
1325 else:
1326 ndbm_libs = []
1327 print "building dbm using ndbm"
1328 dbmext = Extension('dbm', ['dbmmodule.c'],
1329 define_macros=[
1330 ('HAVE_NDBM_H',None),
1331 ],
1332 libraries=ndbm_libs)
1333 break
1334
1335 elif cand == "gdbm":
1336 if self.compiler.find_library_file(lib_dirs, 'gdbm'):
1337 gdbm_libs = ['gdbm']
1338 if self.compiler.find_library_file(lib_dirs,
1339 'gdbm_compat'):
1340 gdbm_libs.append('gdbm_compat')
1341 if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
1342 print "building dbm using gdbm"
1343 dbmext = Extension(
1344 'dbm', ['dbmmodule.c'],
1345 define_macros=[
1346 ('HAVE_GDBM_NDBM_H', None),
1347 ],
1348 libraries = gdbm_libs)
1349 break
1350 if find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
1351 print "building dbm using gdbm"
1352 dbmext = Extension(
1353 'dbm', ['dbmmodule.c'],
1354 define_macros=[
1355 ('HAVE_GDBM_DASH_NDBM_H', None),
1356 ],
1357 libraries = gdbm_libs)
1358 break
1359 elif cand == "bdb":
1360 if db_incs is not None:
1361 print "building dbm using bdb"
1362 dbmext = Extension('dbm', ['dbmmodule.c'],
1363 library_dirs=dblib_dir,
1364 runtime_library_dirs=dblib_dir,
1365 include_dirs=db_incs,
1366 define_macros=[
1367 ('HAVE_BERKDB_H', None),
1368 ('DB_DBM_HSEARCH', None),
1369 ],
1370 libraries=dblibs)
1371 break
1372 if dbmext is not None:
1373 exts.append(dbmext)
1374 else:
1375 missing.append('dbm')
1376
1377 # Anthony Baxter's gdbm module. GNU dbm(3) will require -lgdbm:
1378 if ('gdbm' in dbm_order and
1379 self.compiler.find_library_file(lib_dirs, 'gdbm')):
1380 exts.append( Extension('gdbm', ['gdbmmodule.c'],
1381 libraries = ['gdbm'] ) )
1382 else:
1383 missing.append('gdbm')
1384
1385 # Unix-only modules
1386 if host_platform not in ['win32']:
1387 # Steen Lumholt's termios module
1388 exts.append( Extension('termios', ['termios.c']) )
1389 # Jeremy Hylton's rlimit interface
1390 if host_platform not in ['atheos']:
1391 exts.append( Extension('resource', ['resource.c']) )
1392 else:
1393 missing.append('resource')
1394
1395 nis = self._detect_nis(inc_dirs, lib_dirs)
1396 if nis is not None:
1397 exts.append(nis)
1398 else:
1399 missing.append('nis')
1400
1401 # Curses support, requiring the System V version of curses, often
1402 # provided by the ncurses library.
1403 panel_library = 'panel'
1404 curses_incs = None
1405 if curses_library.startswith('ncurses'):
1406 if curses_library == 'ncursesw':
1407 # Bug 1464056: If _curses.so links with ncursesw,
1408 # _curses_panel.so must link with panelw.
1409 panel_library = 'panelw'
1410 curses_libs = [curses_library]
1411 curses_incs = find_file('curses.h', inc_dirs,
1412 [os.path.join(d, 'ncursesw') for d in inc_dirs])
1413 exts.append( Extension('_curses', ['_cursesmodule.c'],
1414 include_dirs = curses_incs,
1415 libraries = curses_libs) )
1416 elif curses_library == 'curses' and host_platform != 'darwin':
1417 # OSX has an old Berkeley curses, not good enough for
1418 # the _curses module.
1419 if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
1420 curses_libs = ['curses', 'terminfo']
1421 elif (self.compiler.find_library_file(lib_dirs, 'termcap')):
1422 curses_libs = ['curses', 'termcap']
1423 else:
1424 curses_libs = ['curses']
1425
1426 exts.append( Extension('_curses', ['_cursesmodule.c'],
1427 libraries = curses_libs) )
1428 else:
1429 missing.append('_curses')
1430
1431 # If the curses module is enabled, check for the panel module
1432 if (module_enabled(exts, '_curses') and
1433 self.compiler.find_library_file(lib_dirs, panel_library)):
1434 exts.append( Extension('_curses_panel', ['_curses_panel.c'],
1435 include_dirs = curses_incs,
1436 libraries = [panel_library] + curses_libs) )
1437 else:
1438 missing.append('_curses_panel')
1439
1440 # Andrew Kuchling's zlib module. Note that some versions of zlib
1441 # 1.1.3 have security problems. See CERT Advisory CA-2002-07:
1442 # http://www.cert.org/advisories/CA-2002-07.html
1443 #
1444 # zlib 1.1.4 is fixed, but at least one vendor (RedHat) has decided to
1445 # patch its zlib 1.1.3 package instead of upgrading to 1.1.4. For
1446 # now, we still accept 1.1.3, because we think it's difficult to
1447 # exploit this in Python, and we'd rather make it RedHat's problem
1448 # than our problem <wink>.
1449 #
1450 # You can upgrade zlib to version 1.1.4 yourself by going to
1451 # http://www.gzip.org/zlib/
1452 zlib_inc = find_file('zlib.h', [], inc_dirs)
1453 have_zlib = False
1454 if zlib_inc is not None:
1455 zlib_h = zlib_inc[0] + '/zlib.h'
1456 version = '"0.0.0"'
1457 version_req = '"1.1.3"'
1458 if host_platform == 'darwin' and is_macosx_sdk_path(zlib_h):
1459 zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:])
1460 fp = open(zlib_h)
1461 while 1:
1462 line = fp.readline()
1463 if not line:
1464 break
1465 if line.startswith('#define ZLIB_VERSION'):
1466 version = line.split()[2]
1467 break
1468 if version >= version_req:
1469 if (self.compiler.find_library_file(lib_dirs, 'z')):
1470 if host_platform == "darwin":
1471 zlib_extra_link_args = ('-Wl,-search_paths_first',)
1472 else:
1473 zlib_extra_link_args = ()
1474 exts.append( Extension('zlib', ['zlibmodule.c'],
1475 libraries = ['z'],
1476 extra_link_args = zlib_extra_link_args))
1477 have_zlib = True
1478 else:
1479 missing.append('zlib')
1480 else:
1481 missing.append('zlib')
1482 else:
1483 missing.append('zlib')
1484
1485 # Helper module for various ascii-encoders. Uses zlib for an optimized
1486 # crc32 if we have it. Otherwise binascii uses its own.
1487 if have_zlib:
1488 extra_compile_args = ['-DUSE_ZLIB_CRC32']
1489 libraries = ['z']
1490 extra_link_args = zlib_extra_link_args
1491 else:
1492 extra_compile_args = []
1493 libraries = []
1494 extra_link_args = []
1495 exts.append( Extension('binascii', ['binascii.c'],
1496 extra_compile_args = extra_compile_args,
1497 libraries = libraries,
1498 extra_link_args = extra_link_args) )
1499
1500 # Gustavo Niemeyer's bz2 module.
1501 if (self.compiler.find_library_file(lib_dirs, 'bz2')):
1502 if host_platform == "darwin":
1503 bz2_extra_link_args = ('-Wl,-search_paths_first',)
1504 else:
1505 bz2_extra_link_args = ()
1506 exts.append( Extension('bz2', ['bz2module.c'],
1507 libraries = ['bz2'],
1508 extra_link_args = bz2_extra_link_args) )
1509 else:
1510 missing.append('bz2')
1511
1512 # Interface to the Expat XML parser
1513 #
1514 # Expat was written by James Clark and is now maintained by a group of
1515 # developers on SourceForge; see www.libexpat.org for more information.
1516 # The pyexpat module was written by Paul Prescod after a prototype by
1517 # Jack Jansen. The Expat source is included in Modules/expat/. Usage
1518 # of a system shared libexpat.so is possible with --with-system-expat
1519 # configure option.
1520 #
1521 # More information on Expat can be found at www.libexpat.org.
1522 #
1523 if '--with-system-expat' in sysconfig.get_config_var("CONFIG_ARGS"):
1524 expat_inc = []
1525 define_macros = []
1526 expat_lib = ['expat']
1527 expat_sources = []
1528 expat_depends = []
1529 else:
1530 expat_inc = [os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')]
1531 define_macros = [
1532 ('HAVE_EXPAT_CONFIG_H', '1'),
1533 # bpo-30947: Python uses best available entropy sources to
1534 # call XML_SetHashSalt(), expat entropy sources are not needed
1535 ('XML_POOR_ENTROPY', '1'),
1536 ]
1537 expat_lib = []
1538 expat_sources = ['expat/xmlparse.c',
1539 'expat/xmlrole.c',
1540 'expat/xmltok.c']
1541 expat_depends = ['expat/ascii.h',
1542 'expat/asciitab.h',
1543 'expat/expat.h',
1544 'expat/expat_config.h',
1545 'expat/expat_external.h',
1546 'expat/internal.h',
1547 'expat/latin1tab.h',
1548 'expat/utf8tab.h',
1549 'expat/xmlrole.h',
1550 'expat/xmltok.h',
1551 'expat/xmltok_impl.h'
1552 ]
1553
1554 exts.append(Extension('pyexpat',
1555 define_macros = define_macros,
1556 include_dirs = expat_inc,
1557 libraries = expat_lib,
1558 sources = ['pyexpat.c'] + expat_sources,
1559 depends = expat_depends,
1560 ))
1561
1562 # Fredrik Lundh's cElementTree module. Note that this also
1563 # uses expat (via the CAPI hook in pyexpat).
1564
1565 if os.path.isfile(os.path.join(srcdir, 'Modules', '_elementtree.c')):
1566 define_macros.append(('USE_PYEXPAT_CAPI', None))
1567 exts.append(Extension('_elementtree',
1568 define_macros = define_macros,
1569 include_dirs = expat_inc,
1570 libraries = expat_lib,
1571 sources = ['_elementtree.c'],
1572 depends = ['pyexpat.c'] + expat_sources +
1573 expat_depends,
1574 ))
1575 else:
1576 missing.append('_elementtree')
1577
1578 # Hye-Shik Chang's CJKCodecs modules.
1579 if have_unicode:
1580 exts.append(Extension('_multibytecodec',
1581 ['cjkcodecs/multibytecodec.c']))
1582 for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
1583 exts.append(Extension('_codecs_%s' % loc,
1584 ['cjkcodecs/_codecs_%s.c' % loc]))
1585 else:
1586 missing.append('_multibytecodec')
1587 for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
1588 missing.append('_codecs_%s' % loc)
1589
1590 # Dynamic loading module
1591 if sys.maxint == 0x7fffffff:
1592 # This requires sizeof(int) == sizeof(long) == sizeof(char*)
1593 dl_inc = find_file('dlfcn.h', [], inc_dirs)
1594 if (dl_inc is not None) and (host_platform not in ['atheos']):
1595 exts.append( Extension('dl', ['dlmodule.c']) )
1596 else:
1597 missing.append('dl')
1598 else:
1599 missing.append('dl')
1600
1601 # Thomas Heller's _ctypes module
1602 self.detect_ctypes(inc_dirs, lib_dirs)
1603
1604 # Richard Oudkerk's multiprocessing module
1605 if host_platform == 'win32': # Windows
1606 macros = dict()
1607 libraries = ['ws2_32']
1608
1609 elif host_platform == 'darwin': # Mac OSX
1610 macros = dict()
1611 libraries = []
1612
1613 elif host_platform == 'cygwin': # Cygwin
1614 macros = dict()
1615 libraries = []
1616
1617 elif host_platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
1618 # FreeBSD's P1003.1b semaphore support is very experimental
1619 # and has many known problems. (as of June 2008)
1620 macros = dict()
1621 libraries = []
1622
1623 elif host_platform.startswith('openbsd'):
1624 macros = dict()
1625 libraries = []
1626
1627 elif host_platform.startswith('netbsd'):
1628 macros = dict()
1629 libraries = []
1630
1631 else: # Linux and other unices
1632 macros = dict()
1633 libraries = ['rt']
1634
1635 if host_platform == 'win32':
1636 multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
1637 '_multiprocessing/semaphore.c',
1638 '_multiprocessing/pipe_connection.c',
1639 '_multiprocessing/socket_connection.c',
1640 '_multiprocessing/win32_functions.c'
1641 ]
1642
1643 else:
1644 multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
1645 '_multiprocessing/socket_connection.c'
1646 ]
1647 if (sysconfig.get_config_var('HAVE_SEM_OPEN') and not
1648 sysconfig.get_config_var('POSIX_SEMAPHORES_NOT_ENABLED')):
1649 multiprocessing_srcs.append('_multiprocessing/semaphore.c')
1650
1651 if sysconfig.get_config_var('WITH_THREAD'):
1652 exts.append ( Extension('_multiprocessing', multiprocessing_srcs,
1653 define_macros=macros.items(),
1654 include_dirs=["Modules/_multiprocessing"]))
1655 else:
1656 missing.append('_multiprocessing')
1657
1658 # End multiprocessing
1659
1660
1661 # Platform-specific libraries
1662 if host_platform == 'linux2':
1663 # Linux-specific modules
1664 exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
1665 else:
1666 missing.append('linuxaudiodev')
1667
1668 if (host_platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
1669 'freebsd7', 'freebsd8')
1670 or host_platform.startswith("gnukfreebsd")):
1671 exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
1672 else:
1673 missing.append('ossaudiodev')
1674
1675 if host_platform == 'sunos5':
1676 # SunOS specific modules
1677 exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
1678 else:
1679 missing.append('sunaudiodev')
1680
1681 if host_platform == 'darwin':
1682 # _scproxy
1683 exts.append(Extension("_scproxy", [os.path.join(srcdir, "Mac/Modules/_scproxy.c")],
1684 extra_link_args= [
1685 '-framework', 'SystemConfiguration',
1686 '-framework', 'CoreFoundation'
1687 ]))
1688
1689
1690 if host_platform == 'darwin' and ("--disable-toolbox-glue" not in
1691 sysconfig.get_config_var("CONFIG_ARGS")):
1692
1693 if int(os.uname()[2].split('.')[0]) >= 8:
1694 # We're on Mac OS X 10.4 or later, the compiler should
1695 # support '-Wno-deprecated-declarations'. This will
1696 # suppress deprecation warnings for the Carbon extensions,
1697 # these extensions wrap the Carbon APIs and even those
1698 # parts that are deprecated.
1699 carbon_extra_compile_args = ['-Wno-deprecated-declarations']
1700 else:
1701 carbon_extra_compile_args = []
1702
1703 # Mac OS X specific modules.
1704 def macSrcExists(name1, name2=''):
1705 if not name1:
1706 return None
1707 names = (name1,)
1708 if name2:
1709 names = (name1, name2)
1710 path = os.path.join(srcdir, 'Mac', 'Modules', *names)
1711 return os.path.exists(path)
1712
1713 def addMacExtension(name, kwds, extra_srcs=[]):
1714 dirname = ''
1715 if name[0] == '_':
1716 dirname = name[1:].lower()
1717 cname = name + '.c'
1718 cmodulename = name + 'module.c'
1719 # Check for NNN.c, NNNmodule.c, _nnn/NNN.c, _nnn/NNNmodule.c
1720 if macSrcExists(cname):
1721 srcs = [cname]
1722 elif macSrcExists(cmodulename):
1723 srcs = [cmodulename]
1724 elif macSrcExists(dirname, cname):
1725 # XXX(nnorwitz): If all the names ended with module, we
1726 # wouldn't need this condition. ibcarbon is the only one.
1727 srcs = [os.path.join(dirname, cname)]
1728 elif macSrcExists(dirname, cmodulename):
1729 srcs = [os.path.join(dirname, cmodulename)]
1730 else:
1731 raise RuntimeError("%s not found" % name)
1732
1733 # Here's the whole point: add the extension with sources
1734 exts.append(Extension(name, srcs + extra_srcs, **kwds))
1735
1736 # Core Foundation
1737 core_kwds = {'extra_compile_args': carbon_extra_compile_args,
1738 'extra_link_args': ['-framework', 'CoreFoundation'],
1739 }
1740 addMacExtension('_CF', core_kwds, ['cf/pycfbridge.c'])
1741 addMacExtension('autoGIL', core_kwds)
1742
1743
1744
1745 # Carbon
1746 carbon_kwds = {'extra_compile_args': carbon_extra_compile_args,
1747 'extra_link_args': ['-framework', 'Carbon'],
1748 }
1749 CARBON_EXTS = ['ColorPicker', 'gestalt', 'MacOS', 'Nav',
1750 'OSATerminology', 'icglue',
1751 # All these are in subdirs
1752 '_AE', '_AH', '_App', '_CarbonEvt', '_Cm', '_Ctl',
1753 '_Dlg', '_Drag', '_Evt', '_File', '_Folder', '_Fm',
1754 '_Help', '_Icn', '_IBCarbon', '_List',
1755 '_Menu', '_Mlte', '_OSA', '_Res', '_Qd', '_Qdoffs',
1756 '_Scrap', '_Snd', '_TE',
1757 ]
1758 for name in CARBON_EXTS:
1759 addMacExtension(name, carbon_kwds)
1760
1761 # Workaround for a bug in the version of gcc shipped with Xcode 3.
1762 # The _Win extension should build just like the other Carbon extensions, but
1763 # this actually results in a hard crash of the linker.
1764 #
1765 if '-arch ppc64' in cflags and '-arch ppc' in cflags:
1766 win_kwds = {'extra_compile_args': carbon_extra_compile_args + ['-arch', 'i386', '-arch', 'ppc'],
1767 'extra_link_args': ['-framework', 'Carbon', '-arch', 'i386', '-arch', 'ppc'],
1768 }
1769 addMacExtension('_Win', win_kwds)
1770 else:
1771 addMacExtension('_Win', carbon_kwds)
1772
1773
1774 # Application Services & QuickTime
1775 app_kwds = {'extra_compile_args': carbon_extra_compile_args,
1776 'extra_link_args': ['-framework','ApplicationServices'],
1777 }
1778 addMacExtension('_Launch', app_kwds)
1779 addMacExtension('_CG', app_kwds)
1780
1781 exts.append( Extension('_Qt', ['qt/_Qtmodule.c'],
1782 extra_compile_args=carbon_extra_compile_args,
1783 extra_link_args=['-framework', 'QuickTime',
1784 '-framework', 'Carbon']) )
1785
1786
1787 self.extensions.extend(exts)
1788
1789 # Call the method for detecting whether _tkinter can be compiled
1790 self.detect_tkinter(inc_dirs, lib_dirs)
1791
1792 if '_tkinter' not in [e.name for e in self.extensions]:
1793 missing.append('_tkinter')
1794
1795 ## # Uncomment these lines if you want to play with xxmodule.c
1796 ## ext = Extension('xx', ['xxmodule.c'])
1797 ## self.extensions.append(ext)
1798
1799 return missing
1800
1801 def detect_tkinter_explicitly(self):
1802 # Build _tkinter using explicit locations for Tcl/Tk.
1803 #
1804 # This is enabled when both arguments are given to ./configure:
1805 #
1806 # --with-tcltk-includes="-I/path/to/tclincludes \
1807 # -I/path/to/tkincludes"
1808 # --with-tcltk-libs="-L/path/to/tcllibs -ltclm.n \
1809 # -L/path/to/tklibs -ltkm.n"
1810 #
1811 # These values can also be specified or overridden via make:
1812 # make TCLTK_INCLUDES="..." TCLTK_LIBS="..."
1813 #
1814 # This can be useful for building and testing tkinter with multiple
1815 # versions of Tcl/Tk. Note that a build of Tk depends on a particular
1816 # build of Tcl so you need to specify both arguments and use care when
1817 # overriding.
1818
1819 # The _TCLTK variables are created in the Makefile sharedmods target.
1820 tcltk_includes = os.environ.get('_TCLTK_INCLUDES')
1821 tcltk_libs = os.environ.get('_TCLTK_LIBS')
1822 if not (tcltk_includes and tcltk_libs):
1823 # Resume default configuration search.
1824 return 0
1825
1826 extra_compile_args = tcltk_includes.split()
1827 extra_link_args = tcltk_libs.split()
1828 ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
1829 define_macros=[('WITH_APPINIT', 1)],
1830 extra_compile_args = extra_compile_args,
1831 extra_link_args = extra_link_args,
1832 )
1833 self.extensions.append(ext)
1834 return 1
1835
1836 def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
1837 # The _tkinter module, using frameworks. Since frameworks are quite
1838 # different the UNIX search logic is not sharable.
1839 from os.path import join, exists
1840 framework_dirs = [
1841 '/Library/Frameworks',
1842 '/System/Library/Frameworks/',
1843 join(os.getenv('HOME'), '/Library/Frameworks')
1844 ]
1845
1846 sysroot = macosx_sdk_root()
1847
1848 # Find the directory that contains the Tcl.framework and Tk.framework
1849 # bundles.
1850 # XXX distutils should support -F!
1851 for F in framework_dirs:
1852 # both Tcl.framework and Tk.framework should be present
1853
1854
1855 for fw in 'Tcl', 'Tk':
1856 if is_macosx_sdk_path(F):
1857 if not exists(join(sysroot, F[1:], fw + '.framework')):
1858 break
1859 else:
1860 if not exists(join(F, fw + '.framework')):
1861 break
1862 else:
1863 # ok, F is now directory with both frameworks. Continure
1864 # building
1865 break
1866 else:
1867 # Tk and Tcl frameworks not found. Normal "unix" tkinter search
1868 # will now resume.
1869 return 0
1870
1871 # For 8.4a2, we must add -I options that point inside the Tcl and Tk
1872 # frameworks. In later release we should hopefully be able to pass
1873 # the -F option to gcc, which specifies a framework lookup path.
1874 #
1875 include_dirs = [
1876 join(F, fw + '.framework', H)
1877 for fw in 'Tcl', 'Tk'
1878 for H in 'Headers', 'Versions/Current/PrivateHeaders'
1879 ]
1880
1881 # For 8.4a2, the X11 headers are not included. Rather than include a
1882 # complicated search, this is a hard-coded path. It could bail out
1883 # if X11 libs are not found...
1884 include_dirs.append('/usr/X11R6/include')
1885 frameworks = ['-framework', 'Tcl', '-framework', 'Tk']
1886
1887 # All existing framework builds of Tcl/Tk don't support 64-bit
1888 # architectures.
1889 cflags = sysconfig.get_config_vars('CFLAGS')[0]
1890 archs = re.findall('-arch\s+(\w+)', cflags)
1891
1892 if is_macosx_sdk_path(F):
1893 fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(os.path.join(sysroot, F[1:]),))
1894 else:
1895 fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,))
1896
1897 detected_archs = []
1898 for ln in fp:
1899 a = ln.split()[-1]
1900 if a in archs:
1901 detected_archs.append(ln.split()[-1])
1902 fp.close()
1903
1904 for a in detected_archs:
1905 frameworks.append('-arch')
1906 frameworks.append(a)
1907
1908 ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
1909 define_macros=[('WITH_APPINIT', 1)],
1910 include_dirs = include_dirs,
1911 libraries = [],
1912 extra_compile_args = frameworks[2:],
1913 extra_link_args = frameworks,
1914 )
1915 self.extensions.append(ext)
1916 return 1
1917
1918 def detect_tkinter(self, inc_dirs, lib_dirs):
1919 # The _tkinter module.
1920
1921 # Check whether --with-tcltk-includes and --with-tcltk-libs were
1922 # configured or passed into the make target. If so, use these values
1923 # to build tkinter and bypass the searches for Tcl and TK in standard
1924 # locations.
1925 if self.detect_tkinter_explicitly():
1926 return
1927
1928 # Rather than complicate the code below, detecting and building
1929 # AquaTk is a separate method. Only one Tkinter will be built on
1930 # Darwin - either AquaTk, if it is found, or X11 based Tk.
1931 if (host_platform == 'darwin' and
1932 self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
1933 return
1934
1935 # Assume we haven't found any of the libraries or include files
1936 # The versions with dots are used on Unix, and the versions without
1937 # dots on Windows, for detection by cygwin.
1938 tcllib = tklib = tcl_includes = tk_includes = None
1939 for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
1940 '8.2', '82', '8.1', '81', '8.0', '80']:
1941 tklib = self.compiler.find_library_file(lib_dirs,
1942 'tk' + version)
1943 tcllib = self.compiler.find_library_file(lib_dirs,
1944 'tcl' + version)
1945 if tklib and tcllib:
1946 # Exit the loop when we've found the Tcl/Tk libraries
1947 break
1948
1949 # Now check for the header files
1950 if tklib and tcllib:
1951 # Check for the include files on Debian and {Free,Open}BSD, where
1952 # they're put in /usr/include/{tcl,tk}X.Y
1953 dotversion = version
1954 if '.' not in dotversion and "bsd" in host_platform.lower():
1955 # OpenBSD and FreeBSD use Tcl/Tk library names like libtcl83.a,
1956 # but the include subdirs are named like .../include/tcl8.3.
1957 dotversion = dotversion[:-1] + '.' + dotversion[-1]
1958 tcl_include_sub = []
1959 tk_include_sub = []
1960 for dir in inc_dirs:
1961 tcl_include_sub += [dir + os.sep + "tcl" + dotversion]
1962 tk_include_sub += [dir + os.sep + "tk" + dotversion]
1963 tk_include_sub += tcl_include_sub
1964 tcl_includes = find_file('tcl.h', inc_dirs, tcl_include_sub)
1965 tk_includes = find_file('tk.h', inc_dirs, tk_include_sub)
1966
1967 if (tcllib is None or tklib is None or
1968 tcl_includes is None or tk_includes is None):
1969 self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2)
1970 return
1971
1972 # OK... everything seems to be present for Tcl/Tk.
1973
1974 include_dirs = [] ; libs = [] ; defs = [] ; added_lib_dirs = []
1975 for dir in tcl_includes + tk_includes:
1976 if dir not in include_dirs:
1977 include_dirs.append(dir)
1978
1979 # Check for various platform-specific directories
1980 if host_platform == 'sunos5':
1981 include_dirs.append('/usr/openwin/include')
1982 added_lib_dirs.append('/usr/openwin/lib')
1983 elif os.path.exists('/usr/X11R6/include'):
1984 include_dirs.append('/usr/X11R6/include')
1985 added_lib_dirs.append('/usr/X11R6/lib64')
1986 added_lib_dirs.append('/usr/X11R6/lib')
1987 elif os.path.exists('/usr/X11R5/include'):
1988 include_dirs.append('/usr/X11R5/include')
1989 added_lib_dirs.append('/usr/X11R5/lib')
1990 else:
1991 # Assume default location for X11
1992 include_dirs.append('/usr/X11/include')
1993 added_lib_dirs.append('/usr/X11/lib')
1994
1995 # If Cygwin, then verify that X is installed before proceeding
1996 if host_platform == 'cygwin':
1997 x11_inc = find_file('X11/Xlib.h', [], include_dirs)
1998 if x11_inc is None:
1999 return
2000
2001 # Check for BLT extension
2002 if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
2003 'BLT8.0'):
2004 defs.append( ('WITH_BLT', 1) )
2005 libs.append('BLT8.0')
2006 elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
2007 'BLT'):
2008 defs.append( ('WITH_BLT', 1) )
2009 libs.append('BLT')
2010
2011 # Add the Tcl/Tk libraries
2012 libs.append('tk'+ version)
2013 libs.append('tcl'+ version)
2014
2015 if host_platform in ['aix3', 'aix4']:
2016 libs.append('ld')
2017
2018 # Finally, link with the X11 libraries (not appropriate on cygwin)
2019 if host_platform != "cygwin":
2020 libs.append('X11')
2021
2022 ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
2023 define_macros=[('WITH_APPINIT', 1)] + defs,
2024 include_dirs = include_dirs,
2025 libraries = libs,
2026 library_dirs = added_lib_dirs,
2027 )
2028 self.extensions.append(ext)
2029
2030 # XXX handle these, but how to detect?
2031 # *** Uncomment and edit for PIL (TkImaging) extension only:
2032 # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \
2033 # *** Uncomment and edit for TOGL extension only:
2034 # -DWITH_TOGL togl.c \
2035 # *** Uncomment these for TOGL extension only:
2036 # -lGL -lGLU -lXext -lXmu \
2037
2038 def configure_ctypes_darwin(self, ext):
2039 # Darwin (OS X) uses preconfigured files, in
2040 # the Modules/_ctypes/libffi_osx directory.
2041 srcdir = sysconfig.get_config_var('srcdir')
2042 ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
2043 '_ctypes', 'libffi_osx'))
2044 sources = [os.path.join(ffi_srcdir, p)
2045 for p in ['ffi.c',
2046 'x86/darwin64.S',
2047 'x86/x86-darwin.S',
2048 'x86/x86-ffi_darwin.c',
2049 'x86/x86-ffi64.c',
2050 'powerpc/ppc-darwin.S',
2051 'powerpc/ppc-darwin_closure.S',
2052 'powerpc/ppc-ffi_darwin.c',
2053 'powerpc/ppc64-darwin_closure.S',
2054 ]]
2055
2056 # Add .S (preprocessed assembly) to C compiler source extensions.
2057 self.compiler.src_extensions.append('.S')
2058
2059 include_dirs = [os.path.join(ffi_srcdir, 'include'),
2060 os.path.join(ffi_srcdir, 'powerpc')]
2061 ext.include_dirs.extend(include_dirs)
2062 ext.sources.extend(sources)
2063 return True
2064
2065 def configure_ctypes(self, ext):
2066 if not self.use_system_libffi:
2067 if host_platform == 'darwin':
2068 return self.configure_ctypes_darwin(ext)
2069
2070 srcdir = sysconfig.get_config_var('srcdir')
2071 ffi_builddir = os.path.join(self.build_temp, 'libffi')
2072 ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
2073 '_ctypes', 'libffi'))
2074 ffi_configfile = os.path.join(ffi_builddir, 'fficonfig.py')
2075
2076 from distutils.dep_util import newer_group
2077
2078 config_sources = [os.path.join(ffi_srcdir, fname)
2079 for fname in os.listdir(ffi_srcdir)
2080 if os.path.isfile(os.path.join(ffi_srcdir, fname))]
2081 if self.force or newer_group(config_sources,
2082 ffi_configfile):
2083 from distutils.dir_util import mkpath
2084 mkpath(ffi_builddir)
2085 config_args = [arg for arg in sysconfig.get_config_var("CONFIG_ARGS").split()
2086 if (('--host=' in arg) or ('--build=' in arg))]
2087 if not self.verbose:
2088 config_args.append("-q")
2089
2090 # Pass empty CFLAGS because we'll just append the resulting
2091 # CFLAGS to Python's; -g or -O2 is to be avoided.
2092 cmd = "cd %s && env CFLAGS='' '%s/configure' %s" \
2093 % (ffi_builddir, ffi_srcdir, " ".join(config_args))
2094
2095 res = os.system(cmd)
2096 if res or not os.path.exists(ffi_configfile):
2097 print "Failed to configure _ctypes module"
2098 return False
2099
2100 fficonfig = {}
2101 with open(ffi_configfile) as f:
2102 exec f in fficonfig
2103
2104 # Add .S (preprocessed assembly) to C compiler source extensions.
2105 self.compiler.src_extensions.append('.S')
2106
2107 include_dirs = [os.path.join(ffi_builddir, 'include'),
2108 ffi_builddir,
2109 os.path.join(ffi_srcdir, 'src')]
2110 extra_compile_args = fficonfig['ffi_cflags'].split()
2111
2112 ext.sources.extend(os.path.join(ffi_srcdir, f) for f in
2113 fficonfig['ffi_sources'])
2114 ext.include_dirs.extend(include_dirs)
2115 ext.extra_compile_args.extend(extra_compile_args)
2116 return True
2117
2118 def detect_ctypes(self, inc_dirs, lib_dirs):
2119 self.use_system_libffi = False
2120 include_dirs = []
2121 extra_compile_args = []
2122 extra_link_args = []
2123 sources = ['_ctypes/_ctypes.c',
2124 '_ctypes/callbacks.c',
2125 '_ctypes/callproc.c',
2126 '_ctypes/stgdict.c',
2127 '_ctypes/cfield.c']
2128 depends = ['_ctypes/ctypes.h']
2129
2130 if host_platform == 'darwin':
2131 sources.append('_ctypes/malloc_closure.c')
2132 sources.append('_ctypes/darwin/dlfcn_simple.c')
2133 extra_compile_args.append('-DMACOSX')
2134 include_dirs.append('_ctypes/darwin')
2135 # XXX Is this still needed?
2136 ## extra_link_args.extend(['-read_only_relocs', 'warning'])
2137
2138 elif host_platform == 'sunos5':
2139 # XXX This shouldn't be necessary; it appears that some
2140 # of the assembler code is non-PIC (i.e. it has relocations
2141 # when it shouldn't. The proper fix would be to rewrite
2142 # the assembler code to be PIC.
2143 # This only works with GCC; the Sun compiler likely refuses
2144 # this option. If you want to compile ctypes with the Sun
2145 # compiler, please research a proper solution, instead of
2146 # finding some -z option for the Sun compiler.
2147 extra_link_args.append('-mimpure-text')
2148
2149 elif host_platform.startswith('hp-ux'):
2150 extra_link_args.append('-fPIC')
2151
2152 ext = Extension('_ctypes',
2153 include_dirs=include_dirs,
2154 extra_compile_args=extra_compile_args,
2155 extra_link_args=extra_link_args,
2156 libraries=[],
2157 sources=sources,
2158 depends=depends)
2159 ext_test = Extension('_ctypes_test',
2160 sources=['_ctypes/_ctypes_test.c'])
2161 self.extensions.extend([ext, ext_test])
2162
2163 if not '--with-system-ffi' in sysconfig.get_config_var("CONFIG_ARGS"):
2164 return
2165
2166 if host_platform == 'darwin':
2167 # OS X 10.5 comes with libffi.dylib; the include files are
2168 # in /usr/include/ffi
2169 inc_dirs.append('/usr/include/ffi')
2170
2171 ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
2172 if not ffi_inc or ffi_inc[0] == '':
2173 ffi_inc = find_file('ffi.h', [], inc_dirs)
2174 if ffi_inc is not None:
2175 ffi_h = ffi_inc[0] + '/ffi.h'
2176 with open(ffi_h) as f:
2177 for line in f:
2178 line = line.strip()
2179 if line.startswith(('#define LIBFFI_H',
2180 '#define ffi_wrapper_h')):
2181 break
2182 else:
2183 ffi_inc = None
2184 print('Header file {} does not define LIBFFI_H or '
2185 'ffi_wrapper_h'.format(ffi_h))
2186 ffi_lib = None
2187 if ffi_inc is not None:
2188 for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'):
2189 if (self.compiler.find_library_file(lib_dirs, lib_name)):
2190 ffi_lib = lib_name
2191 break
2192
2193 if ffi_inc and ffi_lib:
2194 ext.include_dirs.extend(ffi_inc)
2195 ext.libraries.append(ffi_lib)
2196 self.use_system_libffi = True
2197
2198 if sysconfig.get_config_var('HAVE_LIBDL'):
2199 # for dlopen, see bpo-32647
2200 ext.libraries.append('dl')
2201
2202 def _detect_nis(self, inc_dirs, lib_dirs):
2203 if host_platform in {'win32', 'cygwin', 'qnx6'}:
2204 return None
2205
2206 libs = []
2207 library_dirs = []
2208 includes_dirs = []
2209
2210 # bpo-32521: glibc has deprecated Sun RPC for some time. Fedora 28
2211 # moved headers and libraries to libtirpc and libnsl. The headers
2212 # are in tircp and nsl sub directories.
2213 rpcsvc_inc = find_file(
2214 'rpcsvc/yp_prot.h', inc_dirs,
2215 [os.path.join(inc_dir, 'nsl') for inc_dir in inc_dirs]
2216 )
2217 rpc_inc = find_file(
2218 'rpc/rpc.h', inc_dirs,
2219 [os.path.join(inc_dir, 'tirpc') for inc_dir in inc_dirs]
2220 )
2221 if rpcsvc_inc is None or rpc_inc is None:
2222 # not found
2223 return None
2224 includes_dirs.extend(rpcsvc_inc)
2225 includes_dirs.extend(rpc_inc)
2226
2227 if self.compiler.find_library_file(lib_dirs, 'nsl'):
2228 libs.append('nsl')
2229 else:
2230 # libnsl-devel: check for libnsl in nsl/ subdirectory
2231 nsl_dirs = [os.path.join(lib_dir, 'nsl') for lib_dir in lib_dirs]
2232 libnsl = self.compiler.find_library_file(nsl_dirs, 'nsl')
2233 if libnsl is not None:
2234 library_dirs.append(os.path.dirname(libnsl))
2235 libs.append('nsl')
2236
2237 if self.compiler.find_library_file(lib_dirs, 'tirpc'):
2238 libs.append('tirpc')
2239
2240 return Extension(
2241 'nis', ['nismodule.c'],
2242 libraries=libs,
2243 library_dirs=library_dirs,
2244 include_dirs=includes_dirs
2245 )
2246
2247
2248 class PyBuildInstall(install):
2249 # Suppress the warning about installation into the lib_dynload
2250 # directory, which is not in sys.path when running Python during
2251 # installation:
2252 def initialize_options (self):
2253 install.initialize_options(self)
2254 self.warn_dir=0
2255
2256 class PyBuildInstallLib(install_lib):
2257 # Do exactly what install_lib does but make sure correct access modes get
2258 # set on installed directories and files. All installed files with get
2259 # mode 644 unless they are a shared library in which case they will get
2260 # mode 755. All installed directories will get mode 755.
2261
2262 so_ext = sysconfig.get_config_var("SO")
2263
2264 def install(self):
2265 outfiles = install_lib.install(self)
2266 self.set_file_modes(outfiles, 0644, 0755)
2267 self.set_dir_modes(self.install_dir, 0755)
2268 return outfiles
2269
2270 def set_file_modes(self, files, defaultMode, sharedLibMode):
2271 if not self.is_chmod_supported(): return
2272 if not files: return
2273
2274 for filename in files:
2275 if os.path.islink(filename): continue
2276 mode = defaultMode
2277 if filename.endswith(self.so_ext): mode = sharedLibMode
2278 log.info("changing mode of %s to %o", filename, mode)
2279 if not self.dry_run: os.chmod(filename, mode)
2280
2281 def set_dir_modes(self, dirname, mode):
2282 if not self.is_chmod_supported(): return
2283 os.path.walk(dirname, self.set_dir_modes_visitor, mode)
2284
2285 def set_dir_modes_visitor(self, mode, dirname, names):
2286 if os.path.islink(dirname): return
2287 log.info("changing mode of %s to %o", dirname, mode)
2288 if not self.dry_run: os.chmod(dirname, mode)
2289
2290 def is_chmod_supported(self):
2291 return hasattr(os, 'chmod')
2292
2293 SUMMARY = """
2294 Python is an interpreted, interactive, object-oriented programming
2295 language. It is often compared to Tcl, Perl, Scheme or Java.
2296
2297 Python combines remarkable power with very clear syntax. It has
2298 modules, classes, exceptions, very high level dynamic data types, and
2299 dynamic typing. There are interfaces to many system calls and
2300 libraries, as well as to various windowing systems (X11, Motif, Tk,
2301 Mac, MFC). New built-in modules are easily written in C or C++. Python
2302 is also usable as an extension language for applications that need a
2303 programmable interface.
2304
2305 The Python implementation is portable: it runs on many brands of UNIX,
2306 on Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't
2307 listed here, it may still be supported, if there's a C compiler for
2308 it. Ask around on comp.lang.python -- or just try compiling Python
2309 yourself.
2310 """
2311
2312 CLASSIFIERS = """
2313 Development Status :: 6 - Mature
2314 License :: OSI Approved :: Python Software Foundation License
2315 Natural Language :: English
2316 Programming Language :: C
2317 Programming Language :: Python
2318 Topic :: Software Development
2319 """
2320
2321 def main():
2322 # turn off warnings when deprecated modules are imported
2323 import warnings
2324 warnings.filterwarnings("ignore",category=DeprecationWarning)
2325 setup(# PyPI Metadata (PEP 301)
2326 name = "Python",
2327 version = sys.version.split()[0],
2328 url = "http://www.python.org/%s" % sys.version[:3],
2329 maintainer = "Guido van Rossum and the Python community",
2330 maintainer_email = "[email protected]",
2331 description = "A high-level object-oriented programming language",
2332 long_description = SUMMARY.strip(),
2333 license = "PSF license",
2334 classifiers = filter(None, CLASSIFIERS.split("\n")),
2335 platforms = ["Many"],
2336
2337 # Build info
2338 cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall,
2339 'install_lib':PyBuildInstallLib},
2340 # The struct module is defined here, because build_ext won't be
2341 # called unless there's at least one extension module defined.
2342 ext_modules=[Extension('_struct', ['_struct.c'])],
2343
2344 # Scripts to install
2345 scripts = ['Tools/scripts/pydoc', 'Tools/scripts/idle',
2346 'Tools/scripts/2to3',
2347 'Lib/smtpd.py']
2348 )
2349
2350 # --install-platlib
2351 if __name__ == '__main__':
2352 main()