Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/setup.py

    r2 r388  
    22#
    33
    4 __version__ = "$Revision: 78785 $"
     4__version__ = "$Revision$"
    55
    66import sys, os, imp, re, optparse
    77from glob import glob
    88from platform import machine as platform_machine
     9import sysconfig
    910
    1011from distutils import log
    11 from distutils import sysconfig
    1212from distutils import text_file
    1313from distutils.errors import *
     
    1616from distutils.command.install import install
    1717from distutils.command.install_lib import install_lib
     18from distutils.spawn import find_executable
     19
     20cross_compiling = "_PYTHON_HOST_PLATFORM" in os.environ
     21
     22def 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
     30host_platform = get_platform()
     31
     32# Were we compiled --with-pydebug or with #define Py_DEBUG?
     33COMPILED_WITH_PYDEBUG = ('--with-pydebug' in sysconfig.get_config_var("CONFIG_ARGS"))
    1834
    1935# This global variable is used to hold the list of modules to be disabled.
     
    2743        dirlist.insert(0, dir)
    2844
     45def macosx_sdk_root():
     46    """
     47    Return the directory of the current OSX SDK,
     48    or '/' if no SDK was specified.
     49    """
     50    cflags = sysconfig.get_config_var('CFLAGS')
     51    m = re.search(r'-isysroot\s+(\S+)', cflags)
     52    if m is None:
     53        sysroot = '/'
     54    else:
     55        sysroot = m.group(1)
     56    return sysroot
     57
     58def is_macosx_sdk_path(path):
     59    """
     60    Returns True if 'path' can be located in an OSX SDK
     61    """
     62    return ( (path.startswith('/usr/') and not path.startswith('/usr/local'))
     63                or path.startswith('/System/')
     64                or path.startswith('/Library/') )
     65
    2966def find_file(filename, std_dirs, paths):
    3067    """Searches for the directory where a given file is located,
     
    3875        found in one of them, the resulting list will contain the directory.
    3976    """
     77    if host_platform == 'darwin':
     78        # Honor the MacOSX SDK setting when one was specified.
     79        # An SDK is a directory with the same structure as a real
     80        # system, but with only header files and libraries.
     81        sysroot = macosx_sdk_root()
    4082
    4183    # Check the standard locations
    4284    for dir in std_dirs:
    4385        f = os.path.join(dir, filename)
     86
     87        if host_platform == 'darwin' and is_macosx_sdk_path(dir):
     88            f = os.path.join(sysroot, dir[1:], filename)
     89
    4490        if os.path.exists(f): return []
    4591
     
    4793    for dir in paths:
    4894        f = os.path.join(dir, filename)
     95
     96        if host_platform == 'darwin' and is_macosx_sdk_path(dir):
     97            f = os.path.join(sysroot, dir[1:], filename)
     98
    4999        if os.path.exists(f):
    50100            return [dir]
     
    57107    if result is None:
    58108        return None
     109
     110    if host_platform == 'darwin':
     111        sysroot = macosx_sdk_root()
    59112
    60113    # Check whether the found file is in one of the standard directories
     
    63116        # Ensure path doesn't end with path separator
    64117        p = p.rstrip(os.sep)
     118
     119        if host_platform == 'darwin' and is_macosx_sdk_path(p):
     120            if os.path.join(sysroot, p[1:]) == dirname:
     121                return [ ]
     122
    65123        if p == dirname:
    66124            return [ ]
     
    71129        # Ensure path doesn't end with path separator
    72130        p = p.rstrip(os.sep)
     131
     132        if host_platform == 'darwin' and is_macosx_sdk_path(p):
     133            if os.path.join(sysroot, p[1:]) == dirname:
     134                return [ p ]
     135
    73136        if p == dirname:
    74137            return [p]
     
    119182            # Maybe running on Windows but not using CYGWIN?
    120183            raise ValueError("No source directory; cannot proceed.")
    121 
    122         # Figure out the location of the source code for extension modules
    123         # (This logic is copied in distutils.test.test_sysconfig,
    124         # so building in a separate directory does not break test_distutils.)
    125         moddir = os.path.join(os.getcwd(), srcdir, 'Modules')
    126         moddir = os.path.normpath(moddir)
    127         srcdir, tail = os.path.split(moddir)
    128         srcdir = os.path.normpath(srcdir)
    129         moddir = os.path.normpath(moddir)
    130 
    131         moddirlist = [moddir]
    132         incdirlist = ['./Include']
     184        srcdir = os.path.abspath(srcdir)
     185        moddirlist = [os.path.join(srcdir, 'Modules')]
    133186
    134187        # Platform-dependent module source and include directories
    135         platform = self.get_platform()
    136         if platform in ('darwin', 'mac') and ("--disable-toolbox-glue" not in
     188        incdirlist = []
     189
     190        if host_platform == 'darwin' and ("--disable-toolbox-glue" not in
    137191            sysconfig.get_config_var("CONFIG_ARGS")):
    138192            # Mac OS X also includes some mac-specific modules
    139             macmoddir = os.path.join(os.getcwd(), srcdir, 'Mac/Modules')
     193            macmoddir = os.path.join(srcdir, 'Mac/Modules')
    140194            moddirlist.append(macmoddir)
    141             incdirlist.append('./Mac/Include')
    142 
    143         alldirlist = moddirlist + incdirlist
     195            incdirlist.append(os.path.join(srcdir, 'Mac/Include'))
    144196
    145197        # Fix up the paths for scripts, too
     
    148200
    149201        # Python header files
    150         headers = glob("Include/*.h") + ["pyconfig.h"]
    151 
     202        headers = [sysconfig.get_config_h_filename()]
     203        headers += glob(os.path.join(sysconfig.get_path('include'), "*.h"))
    152204        for ext in self.extensions[:]:
    153205            ext.sources = [ find_module_file(filename, moddirlist)
    154206                            for filename in ext.sources ]
    155207            if ext.depends is not None:
    156                 ext.depends = [find_module_file(filename, alldirlist)
     208                ext.depends = [find_module_file(filename, moddirlist)
    157209                               for filename in ext.depends]
    158210            else:
     
    161213            ext.depends.extend(headers)
    162214
    163             ext.include_dirs.append( '.' ) # to get config.h
    164             for incdir in incdirlist:
    165                 ext.include_dirs.append( os.path.join(srcdir, incdir) )
     215            # platform specific include directories
     216            ext.include_dirs.extend(incdirlist)
    166217
    167218            # If a module has already been built statically,
     
    170221                self.extensions.remove(ext)
    171222
    172         if platform != 'mac':
    173             # Parse Modules/Setup and Modules/Setup.local to figure out which
    174             # modules are turned on in the file.
    175             remove_modules = []
    176             for filename in ('Modules/Setup', 'Modules/Setup.local'):
    177                 input = text_file.TextFile(filename, join_lines=1)
    178                 while 1:
    179                     line = input.readline()
    180                     if not line: break
    181                     line = line.split()
    182                     remove_modules.append(line[0])
    183                 input.close()
    184 
    185             for ext in self.extensions[:]:
    186                 if ext.name in remove_modules:
    187                     self.extensions.remove(ext)
     223        # Parse Modules/Setup and Modules/Setup.local to figure out which
     224        # modules are turned on in the file.
     225        remove_modules = []
     226        for filename in ('Modules/Setup', 'Modules/Setup.local'):
     227            input = text_file.TextFile(filename, join_lines=1)
     228            while 1:
     229                line = input.readline()
     230                if not line: break
     231                line = line.split()
     232                remove_modules.append(line[0])
     233            input.close()
     234
     235        for ext in self.extensions[:]:
     236            if ext.name in remove_modules:
     237                self.extensions.remove(ext)
    188238
    189239        # When you run "make CC=altcc" or something similar, you really want
     
    216266        if missing:
    217267            print
    218             print "Failed to find the necessary bits to build these modules:"
     268            print ("Python build finished, but the necessary bits to build "
     269                   "these modules were not found:")
    219270            print_three_column(missing)
    220271            print ("To find the necessary bits, look in setup.py in"
     
    250301            return
    251302
    252         if self.get_platform() == 'darwin' and (
     303        if host_platform == 'darwin' and (
    253304                sys.maxint > 2**32 and '-arch' in ext.extra_link_args):
    254305            # Don't bother doing an import check when an extension was
     
    264315        # Workaround for Cygwin: Cygwin currently has fork issues when many
    265316        # modules have been imported
    266         if self.get_platform() == 'cygwin':
     317        if host_platform == 'cygwin':
    267318            self.announce('WARNING: skipping import check for Cygwin-based "%s"'
    268319                % ext.name)
     
    271322            self.build_lib,
    272323            self.get_ext_filename(self.get_ext_fullname(ext.name)))
     324
     325        # Don't try to load extensions for cross builds
     326        if cross_compiling:
     327            return
     328
    273329        try:
    274330            imp.load_dynamic(ext.name, ext_filename)
     
    302358            self.failed.append(ext.name)
    303359
    304     def get_platform(self):
    305         # Get value of sys.platform
    306         for platform in ['cygwin', 'beos', 'darwin', 'atheos', 'osf1']:
    307             if sys.platform.startswith(platform):
    308                 return platform
    309         return sys.platform
     360    def add_multiarch_paths(self):
     361        # Debian/Ubuntu multiarch support.
     362        # https://wiki.ubuntu.com/MultiarchSpec
     363        cc = sysconfig.get_config_var('CC')
     364        tmpfile = os.path.join(self.build_temp, 'multiarch')
     365        if not os.path.exists(self.build_temp):
     366            os.makedirs(self.build_temp)
     367        ret = os.system(
     368            '%s -print-multiarch > %s 2> /dev/null' % (cc, tmpfile))
     369        multiarch_path_component = ''
     370        try:
     371            if ret >> 8 == 0:
     372                with open(tmpfile) as fp:
     373                    multiarch_path_component = fp.readline().strip()
     374        finally:
     375            os.unlink(tmpfile)
     376
     377        if multiarch_path_component != '':
     378            add_dir_to_list(self.compiler.library_dirs,
     379                            '/usr/lib/' + multiarch_path_component)
     380            add_dir_to_list(self.compiler.include_dirs,
     381                            '/usr/include/' + multiarch_path_component)
     382            return
     383
     384        if not find_executable('dpkg-architecture'):
     385            return
     386        opt = ''
     387        if cross_compiling:
     388            opt = '-t' + sysconfig.get_config_var('HOST_GNU_TYPE')
     389        tmpfile = os.path.join(self.build_temp, 'multiarch')
     390        if not os.path.exists(self.build_temp):
     391            os.makedirs(self.build_temp)
     392        ret = os.system(
     393            'dpkg-architecture %s -qDEB_HOST_MULTIARCH > %s 2> /dev/null' %
     394            (opt, tmpfile))
     395        try:
     396            if ret >> 8 == 0:
     397                with open(tmpfile) as fp:
     398                    multiarch_path_component = fp.readline().strip()
     399                add_dir_to_list(self.compiler.library_dirs,
     400                                '/usr/lib/' + multiarch_path_component)
     401                add_dir_to_list(self.compiler.include_dirs,
     402                                '/usr/include/' + multiarch_path_component)
     403        finally:
     404            os.unlink(tmpfile)
     405
     406    def add_gcc_paths(self):
     407        gcc = sysconfig.get_config_var('CC')
     408        tmpfile = os.path.join(self.build_temp, 'gccpaths')
     409        if not os.path.exists(self.build_temp):
     410            os.makedirs(self.build_temp)
     411        ret = os.system('%s -E -v - </dev/null 2>%s 1>/dev/null' % (gcc, tmpfile))
     412        is_gcc = False
     413        in_incdirs = False
     414        inc_dirs = []
     415        lib_dirs = []
     416        try:
     417            if ret >> 8 == 0:
     418                with open(tmpfile) as fp:
     419                    for line in fp.readlines():
     420                        if line.startswith("gcc version"):
     421                            is_gcc = True
     422                        elif line.startswith("#include <...>"):
     423                            in_incdirs = True
     424                        elif line.startswith("End of search list"):
     425                            in_incdirs = False
     426                        elif is_gcc and line.startswith("LIBRARY_PATH"):
     427                            for d in line.strip().split("=")[1].split(":"):
     428                                d = os.path.normpath(d)
     429                                if '/gcc/' not in d:
     430                                    add_dir_to_list(self.compiler.library_dirs,
     431                                                    d)
     432                        elif is_gcc and in_incdirs and '/gcc/' not in line:
     433                            add_dir_to_list(self.compiler.include_dirs,
     434                                            line.strip())
     435        finally:
     436            os.unlink(tmpfile)
    310437
    311438    def detect_modules(self):
    312439        # Ensure that /usr/local is always used
    313         add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
    314         add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
     440        if not cross_compiling:
     441            add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
     442            add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
     443        if cross_compiling:
     444            self.add_gcc_paths()
     445        self.add_multiarch_paths()
    315446
    316447        # Add paths specified in the environment variables LDFLAGS and
     
    348479                        add_dir_to_list(dir_list, directory)
    349480
    350         if os.path.normpath(sys.prefix) != '/usr':
     481        if os.path.normpath(sys.prefix) != '/usr' \
     482                and not sysconfig.get_config_var('PYTHONFRAMEWORK'):
     483            # OSX note: Don't add LIBDIR and INCLUDEDIR to building a framework
     484            # (PYTHONFRAMEWORK is set) to avoid # linking problems when
     485            # building a framework with different architectures than
     486            # the one that is currently installed (issue #7473)
    351487            add_dir_to_list(self.compiler.library_dirs,
    352488                            sysconfig.get_config_var("LIBDIR"))
     
    362498        # if a file is found in one of those directories, it can
    363499        # be assumed that no additional -I,-L directives are needed.
    364         lib_dirs = self.compiler.library_dirs + [
    365             '/lib64', '/usr/lib64',
    366             '/lib', '/usr/lib',
    367             ]
    368         inc_dirs = self.compiler.include_dirs + ['/usr/include']
     500        inc_dirs = self.compiler.include_dirs[:]
     501        lib_dirs = self.compiler.library_dirs[:]
     502        if not cross_compiling:
     503            for d in (
     504                '/usr/include',
     505                ):
     506                add_dir_to_list(inc_dirs, d)
     507            for d in (
     508                '/lib64', '/usr/lib64',
     509                '/lib', '/usr/lib',
     510                ):
     511                add_dir_to_list(lib_dirs, d)
    369512        exts = []
    370513        missing = []
     
    373516        config_h_vars = sysconfig.parse_config_h(open(config_h))
    374517
    375         platform = self.get_platform()
    376         (srcdir,) = sysconfig.get_config_vars('srcdir')
     518        srcdir = sysconfig.get_config_var('srcdir')
    377519
    378520        # Check for AtheOS which has libraries in non-standard locations
    379         if platform == 'atheos':
     521        if host_platform == 'atheos':
    380522            lib_dirs += ['/system/libs', '/atheos/autolnk/lib']
    381523            lib_dirs += os.getenv('LIBRARY_PATH', '').split(os.pathsep)
     
    384526
    385527        # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
    386         if platform in ['osf1', 'unixware7', 'openunix8']:
     528        if host_platform in ['osf1', 'unixware7', 'openunix8']:
    387529            lib_dirs += ['/usr/ccs/lib']
    388530
    389         if platform == 'darwin':
     531        # HP-UX11iv3 keeps files in lib/hpux folders.
     532        if host_platform == 'hp-ux11':
     533            lib_dirs += ['/usr/lib/hpux64', '/usr/lib/hpux32']
     534
     535        if host_platform == 'darwin':
    390536            # This should work on any unixy platform ;-)
    391537            # If the user has bothered specifying additional -I and -L flags
     
    406552        # Check for MacOS X, which doesn't need libm.a at all
    407553        math_libs = ['m']
    408         if platform in ['darwin', 'beos', 'mac']:
     554        if host_platform in ['darwin', 'beos']:
    409555            math_libs = []
    410556
     
    417563
    418564        # Some modules that are normally always on:
    419         exts.append( Extension('_weakref', ['_weakref.c']) )
     565        #exts.append( Extension('_weakref', ['_weakref.c']) )
    420566
    421567        # array objects
    422568        exts.append( Extension('array', ['arraymodule.c']) )
    423569        # complex math library functions
    424         exts.append( Extension('cmath', ['cmathmodule.c'],
     570        exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'],
     571                               depends=['_math.h'],
    425572                               libraries=math_libs) )
    426 
    427573        # math library functions, e.g. sin()
    428         exts.append( Extension('math',  ['mathmodule.c'],
     574        exts.append( Extension('math',  ['mathmodule.c', '_math.c'],
     575                               depends=['_math.h'],
    429576                               libraries=math_libs) )
    430577        # fast string operations implemented in C
     
    450597        # operator.add() and similar goodies
    451598        exts.append( Extension('operator', ['operator.c']) )
    452         # Python 3.0 _fileio module
    453         exts.append( Extension("_fileio", ["_fileio.c"]) )
    454         # Python 3.0 _bytesio module
    455         exts.append( Extension("_bytesio", ["_bytesio.c"]) )
     599        # Python 3.1 _io library
     600        exts.append( Extension("_io",
     601            ["_io/bufferedio.c", "_io/bytesio.c", "_io/fileio.c",
     602             "_io/iobase.c", "_io/_iomodule.c", "_io/stringio.c", "_io/textio.c"],
     603             depends=["_io/_iomodule.h"], include_dirs=["Modules/_io"]))
    456604        # _functools
    457605        exts.append( Extension("_functools", ["_functoolsmodule.c"]) )
     
    476624        else:
    477625            locale_libs = []
    478         if platform == 'darwin':
     626        if host_platform == 'darwin':
    479627            locale_extra_link_args = ['-framework', 'CoreFoundation']
    480628        else:
     
    491639
    492640        # fcntl(2) and ioctl(2)
    493         exts.append( Extension('fcntl', ['fcntlmodule.c']) )
    494         if platform not in ['mac']:
    495             # pwd(3)
    496             exts.append( Extension('pwd', ['pwdmodule.c']) )
    497             # grp(3)
    498             exts.append( Extension('grp', ['grpmodule.c']) )
    499             # spwd, shadow passwords
    500             if (config_h_vars.get('HAVE_GETSPNAM', False) or
    501                     config_h_vars.get('HAVE_GETSPENT', False)):
    502                 exts.append( Extension('spwd', ['spwdmodule.c']) )
    503             else:
    504                 missing.append('spwd')
    505         else:
    506             missing.extend(['pwd', 'grp', 'spwd'])
     641        libs = []
     642        if (config_h_vars.get('FLOCK_NEEDS_LIBBSD', False)):
     643            # May be necessary on AIX for flock function
     644            libs = ['bsd']
     645        exts.append( Extension('fcntl', ['fcntlmodule.c'], libraries=libs) )
     646        # pwd(3)
     647        exts.append( Extension('pwd', ['pwdmodule.c']) )
     648        # grp(3)
     649        exts.append( Extension('grp', ['grpmodule.c']) )
     650        # spwd, shadow passwords
     651        if (config_h_vars.get('HAVE_GETSPNAM', False) or
     652                config_h_vars.get('HAVE_GETSPENT', False)):
     653            exts.append( Extension('spwd', ['spwdmodule.c']) )
     654        else:
     655            missing.append('spwd')
    507656
    508657        # select(2); not on ancient System V
     
    517666
    518667        # Memory-mapped files (also works on Win32).
    519         if platform not in ['atheos', 'mac']:
     668        if host_platform not in ['atheos']:
    520669            exts.append( Extension('mmap', ['mmapmodule.c']) )
    521670        else:
     
    523672
    524673        # Lance Ellinghaus's syslog module
    525         if platform not in ['mac']:
    526             # syslog daemon interface
    527             exts.append( Extension('syslog', ['syslogmodule.c']) )
    528         else:
    529             missing.append('syslog')
     674        # syslog daemon interface
     675        exts.append( Extension('syslog', ['syslogmodule.c']) )
    530676
    531677        # George Neville-Neil's timing module:
     
    557703        # readline
    558704        do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
    559         if platform == 'darwin':
     705        readline_termcap_library = ""
     706        curses_library = ""
     707        # Determine if readline is already linked against curses or tinfo.
     708        if do_readline and find_executable('ldd'):
     709            fp = os.popen("ldd %s" % do_readline)
     710            ldd_output = fp.readlines()
     711            ret = fp.close()
     712            if ret is None or ret >> 8 == 0:
     713                for ln in ldd_output:
     714                    if 'curses' in ln:
     715                        readline_termcap_library = re.sub(
     716                            r'.*lib(n?cursesw?)\.so.*', r'\1', ln
     717                        ).rstrip()
     718                        break
     719                    if 'tinfo' in ln: # termcap interface split out from ncurses
     720                        readline_termcap_library = 'tinfo'
     721                        break
     722        # Issue 7384: If readline is already linked against curses,
     723        # use the same library for the readline and curses modules.
     724        if 'curses' in readline_termcap_library:
     725            curses_library = readline_termcap_library
     726        elif self.compiler.find_library_file(lib_dirs, 'ncursesw'):
     727            curses_library = 'ncursesw'
     728        elif self.compiler.find_library_file(lib_dirs, 'ncurses'):
     729            curses_library = 'ncurses'
     730        elif self.compiler.find_library_file(lib_dirs, 'curses'):
     731            curses_library = 'curses'
     732
     733        if host_platform == 'darwin':
    560734            os_release = int(os.uname()[2].split('.')[0])
    561735            dep_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
     
    569743                    do_readline = False
    570744        if do_readline:
    571             if platform == 'darwin' and os_release < 9:
     745            if host_platform == 'darwin' and os_release < 9:
    572746                # In every directory on the search path search for a dynamic
    573747                # library and then a static library, instead of first looking
    574748                # for dynamic libraries on the entiry path.
    575749                # This way a staticly linked custom readline gets picked up
    576                 # before the (broken) dynamic library in /usr/lib.
     750                # before the (possibly broken) dynamic library in /usr/lib.
    577751                readline_extra_link_args = ('-Wl,-search_paths_first',)
    578752            else:
     
    580754
    581755            readline_libs = ['readline']
    582             if self.compiler.find_library_file(lib_dirs,
    583                                                  'ncursesw'):
    584                 readline_libs.append('ncursesw')
    585             elif self.compiler.find_library_file(lib_dirs,
    586                                                  'ncurses'):
    587                 readline_libs.append('ncurses')
    588             elif self.compiler.find_library_file(lib_dirs, 'curses'):
    589                 readline_libs.append('curses')
     756            if readline_termcap_library:
     757                pass # Issue 7384: Already linked against curses or tinfo.
     758            elif curses_library:
     759                readline_libs.append(curses_library)
    590760            elif self.compiler.find_library_file(lib_dirs +
    591                                                ['/usr/lib/termcap'],
    592                                                'termcap'):
     761                                                     ['/usr/lib/termcap'],
     762                                                     'termcap'):
    593763                readline_libs.append('termcap')
    594764            exts.append( Extension('readline', ['readline.c'],
     
    599769            missing.append('readline')
    600770
    601         if platform not in ['mac']:
    602             # crypt module.
    603 
    604             if self.compiler.find_library_file(lib_dirs, 'crypt'):
    605                 libs = ['crypt']
    606             else:
    607                 libs = []
    608             exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
    609         else:
    610             missing.append('crypt')
     771        # crypt module.
     772
     773        if self.compiler.find_library_file(lib_dirs, 'crypt'):
     774            libs = ['crypt']
     775        else:
     776            libs = []
     777        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
    611778
    612779        # CSV files
     
    614781
    615782        # socket(2)
    616         exts.append( Extension('_socket', ['socketmodule.c'],
    617                                depends = ['socketmodule.h']) )
     783        exts.append( Extension('_socket', ['socketmodule.c', 'timemodule.c'],
     784                               depends=['socketmodule.h'],
     785                               libraries=math_libs) )
    618786        # Detect SSL support for the socket module (via _ssl)
    619787        search_for_ssl_incs_in = [
     
    648816        openssl_ver_re = re.compile(
    649817            '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' )
    650         for ssl_inc_dir in inc_dirs + search_for_ssl_incs_in:
    651             name = os.path.join(ssl_inc_dir, 'openssl', 'opensslv.h')
    652             if os.path.isfile(name):
    653                 try:
    654                     incfile = open(name, 'r')
    655                     for line in incfile:
    656                         m = openssl_ver_re.match(line)
    657                         if m:
    658                             openssl_ver = eval(m.group(1))
    659                             break
    660                 except IOError:
    661                     pass
    662 
    663             # first version found is what we'll use (as the compiler should)
    664             if openssl_ver:
    665                 break
    666 
    667         #print 'openssl_ver = 0x%08x' % openssl_ver
    668 
    669         if (ssl_incs is not None and
    670             ssl_libs is not None and
    671             openssl_ver >= 0x00907000):
    672             # The _hashlib module wraps optimized implementations
    673             # of hash functions from the OpenSSL library.
    674             exts.append( Extension('_hashlib', ['_hashopenssl.c'],
    675                                    include_dirs = ssl_incs,
    676                                    library_dirs = ssl_libs,
    677                                    libraries = ['ssl', 'crypto']) )
    678             # these aren't strictly missing since they are unneeded.
    679             #missing.extend(['_sha', '_md5'])
    680         else:
     818
     819        # look for the openssl version header on the compiler search path.
     820        opensslv_h = find_file('openssl/opensslv.h', [],
     821                inc_dirs + search_for_ssl_incs_in)
     822        if opensslv_h:
     823            name = os.path.join(opensslv_h[0], 'openssl/opensslv.h')
     824            if host_platform == 'darwin' and is_macosx_sdk_path(name):
     825                name = os.path.join(macosx_sdk_root(), name[1:])
     826            try:
     827                incfile = open(name, 'r')
     828                for line in incfile:
     829                    m = openssl_ver_re.match(line)
     830                    if m:
     831                        openssl_ver = eval(m.group(1))
     832            except IOError, msg:
     833                print "IOError while reading opensshv.h:", msg
     834                pass
     835
     836        min_openssl_ver = 0x00907000
     837        have_any_openssl = ssl_incs is not None and ssl_libs is not None
     838        have_usable_openssl = (have_any_openssl and
     839                               openssl_ver >= min_openssl_ver)
     840
     841        if have_any_openssl:
     842            if have_usable_openssl:
     843                # The _hashlib module wraps optimized implementations
     844                # of hash functions from the OpenSSL library.
     845                exts.append( Extension('_hashlib', ['_hashopenssl.c'],
     846                                       include_dirs = ssl_incs,
     847                                       library_dirs = ssl_libs,
     848                                       libraries = ['ssl', 'crypto']) )
     849            else:
     850                print ("warning: openssl 0x%08x is too old for _hashlib" %
     851                       openssl_ver)
     852                missing.append('_hashlib')
     853        if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
    681854            # The _sha module implements the SHA1 hash algorithm.
    682855            exts.append( Extension('_sha', ['shamodule.c']) )
     
    687860                            sources = ['md5module.c', 'md5.c'],
    688861                            depends = ['md5.h']) )
    689             missing.append('_hashlib')
    690 
    691         if (openssl_ver < 0x00908000):
     862
     863        min_sha2_openssl_ver = 0x00908000
     864        if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
    692865            # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
    693866            exts.append( Extension('_sha256', ['sha256module.c']) )
     
    709882        # versions of BerkeleyDB already installed.
    710883
    711         max_db_ver = (4, 7)
    712         min_db_ver = (3, 3)
     884        max_db_ver = (5, 3)
     885        min_db_ver = (4, 3)
    713886        db_setup_debug = False   # verbose debug prints from this script?
    714887
     
    731904
    732905        def gen_db_minor_ver_nums(major):
    733             if major == 4:
     906            if major == 5:
    734907                for x in range(max_db_ver[1]+1):
     908                    if allow_db_ver((5, x)):
     909                        yield x
     910            elif major == 4:
     911                for x in range(9):
    735912                    if allow_db_ver((4, x)):
    736913                        yield x
     
    773950            db_inc_paths.append('/opt/db-3.%d/include' % x)
    774951
     952        if cross_compiling:
     953            db_inc_paths = []
     954
    775955        # Add some common subdirectories for Sleepycat DB to the list,
    776956        # based on the standard include directories. This way DB3/4 gets
     
    793973        db_ver_inc_map = {}
    794974
     975        if host_platform == 'darwin':
     976            sysroot = macosx_sdk_root()
     977
    795978        class db_found(Exception): pass
    796979        try:
     
    799982            for d in inc_dirs + db_inc_paths:
    800983                f = os.path.join(d, "db.h")
     984
     985                if host_platform == 'darwin' and is_macosx_sdk_path(d):
     986                    f = os.path.join(sysroot, d[1:], "db.h")
     987
    801988                if db_setup_debug: print "db: looking for db.h in", f
    802989                if os.path.exists(f):
     
    8451032                    db_incdir.replace("include", 'lib'),
    8461033                ]
    847                 db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
    848 
    849                 # Look for a version specific db-X.Y before an ambiguoius dbX
     1034
     1035                if host_platform != 'darwin':
     1036                    db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
     1037
     1038                else:
     1039                    # Same as other branch, but takes OSX SDK into account
     1040                    tmp = []
     1041                    for dn in db_dirs_to_check:
     1042                        if is_macosx_sdk_path(dn):
     1043                            if os.path.isdir(os.path.join(sysroot, dn[1:])):
     1044                                tmp.append(dn)
     1045                        else:
     1046                            if os.path.isdir(dn):
     1047                                tmp.append(dn)
     1048                    db_dirs_to_check = tmp
     1049
     1050                # Look for a version specific db-X.Y before an ambiguous dbX
    8501051                # XXX should we -ever- look for a dbX name?  Do any
    8511052                # systems really not name their library by version and
     
    9001101                             '/usr/local/include/sqlite3',
    9011102                           ]
     1103        if cross_compiling:
     1104            sqlite_inc_paths = []
    9021105        MIN_SQLITE_VERSION_NUMBER = (3, 0, 8)
    9031106        MIN_SQLITE_VERSION = ".".join([str(x)
     
    9071110        # ones. This allows one to override the copy of sqlite on OSX,
    9081111        # where /usr/include contains an old version of sqlite.
    909         for d in inc_dirs + sqlite_inc_paths:
     1112        if host_platform == 'darwin':
     1113            sysroot = macosx_sdk_root()
     1114
     1115        for d_ in inc_dirs + sqlite_inc_paths:
     1116            d = d_
     1117            if host_platform == 'darwin' and is_macosx_sdk_path(d):
     1118                d = os.path.join(sysroot, d[1:])
     1119
    9101120            f = os.path.join(d, "sqlite3.h")
    9111121            if os.path.exists(f):
     
    9131123                incf = open(f).read()
    9141124                m = re.search(
    915                     r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf)
     1125                    r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"([\d\.]*)"', incf)
    9161126                if m:
    9171127                    sqlite_version = m.group(1)
     
    9551165
    9561166            sqlite_defines = []
    957             if sys.platform != "win32":
     1167            if host_platform != "win32":
    9581168                sqlite_defines.append(('MODULE_NAME', '"sqlite3"'))
    9591169            else:
    9601170                sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"'))
    9611171
    962 
    963             if sys.platform == 'darwin':
     1172            # Comment this out if you want the sqlite3 module to be able to load extensions.
     1173            sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))
     1174
     1175            if host_platform == 'darwin':
    9641176                # In every directory on the search path search for a dynamic
    9651177                # library and then a static library, instead of first looking
    966                 # for dynamic libraries on the entiry path.
    967                 # This way a staticly linked custom sqlite gets picked up
     1178                # for dynamic libraries on the entire path.
     1179                # This way a statically linked custom sqlite gets picked up
    9681180                # before the dynamic library in /usr/lib.
    9691181                sqlite_extra_link_args = ('-Wl,-search_paths_first',)
     
    9941206        # when attempting to compile and it will fail.
    9951207        f = "/usr/include/db.h"
     1208
     1209        if host_platform == 'darwin':
     1210            if is_macosx_sdk_path(f):
     1211                sysroot = macosx_sdk_root()
     1212                f = os.path.join(sysroot, f[1:])
     1213
    9961214        if os.path.exists(f) and not db_incs:
    9971215            data = open(f).read()
     
    10021220                ### but I don't have direct access to an osf1 platform and
    10031221                ### seemed to be muffing the search somehow
    1004                 libraries = platform == "osf1" and ['db'] or None
     1222                libraries = host_platform == "osf1" and ['db'] or None
    10051223                if libraries is not None:
    10061224                    exts.append(Extension('bsddb185', ['bsddbmodule.c'],
     
    10131231            missing.append('bsddb185')
    10141232
     1233        dbm_order = ['gdbm']
    10151234        # The standard Unix dbm module:
    1016         if platform not in ['cygwin']:
    1017             if find_file("ndbm.h", inc_dirs, []) is not None:
    1018                 # Some systems have -lndbm, others don't
    1019                 if self.compiler.find_library_file(lib_dirs, 'ndbm'):
    1020                     ndbm_libs = ['ndbm']
    1021                 else:
    1022                     ndbm_libs = []
    1023                 exts.append( Extension('dbm', ['dbmmodule.c'],
    1024                                        define_macros=[('HAVE_NDBM_H',None)],
    1025                                        libraries = ndbm_libs ) )
    1026             elif self.compiler.find_library_file(lib_dirs, 'gdbm'):
    1027                 gdbm_libs = ['gdbm']
    1028                 if self.compiler.find_library_file(lib_dirs, 'gdbm_compat'):
    1029                     gdbm_libs.append('gdbm_compat')
    1030                 if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
    1031                     exts.append( Extension(
    1032                         'dbm', ['dbmmodule.c'],
    1033                         define_macros=[('HAVE_GDBM_NDBM_H',None)],
    1034                         libraries = gdbm_libs ) )
    1035                 elif find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
    1036                     exts.append( Extension(
    1037                         'dbm', ['dbmmodule.c'],
    1038                         define_macros=[('HAVE_GDBM_DASH_NDBM_H',None)],
    1039                         libraries = gdbm_libs ) )
    1040                 else:
    1041                     missing.append('dbm')
    1042             elif db_incs is not None:
    1043                 exts.append( Extension('dbm', ['dbmmodule.c'],
    1044                                        library_dirs=dblib_dir,
    1045                                        runtime_library_dirs=dblib_dir,
    1046                                        include_dirs=db_incs,
    1047                                        define_macros=[('HAVE_BERKDB_H',None),
    1048                                                       ('DB_DBM_HSEARCH',None)],
    1049                                        libraries=dblibs))
     1235        if host_platform not in ['cygwin']:
     1236            config_args = [arg.strip("'")
     1237                           for arg in sysconfig.get_config_var("CONFIG_ARGS").split()]
     1238            dbm_args = [arg for arg in config_args
     1239                        if arg.startswith('--with-dbmliborder=')]
     1240            if dbm_args:
     1241                dbm_order = [arg.split('=')[-1] for arg in dbm_args][-1].split(":")
     1242            else:
     1243                dbm_order = "ndbm:gdbm:bdb".split(":")
     1244            dbmext = None
     1245            for cand in dbm_order:
     1246                if cand == "ndbm":
     1247                    if find_file("ndbm.h", inc_dirs, []) is not None:
     1248                        # Some systems have -lndbm, others have -lgdbm_compat,
     1249                        # others don't have either
     1250                        if self.compiler.find_library_file(lib_dirs,
     1251                                                               'ndbm'):
     1252                            ndbm_libs = ['ndbm']
     1253                        elif self.compiler.find_library_file(lib_dirs,
     1254                                                             'gdbm_compat'):
     1255                            ndbm_libs = ['gdbm_compat']
     1256                        else:
     1257                            ndbm_libs = []
     1258                        print "building dbm using ndbm"
     1259                        dbmext = Extension('dbm', ['dbmmodule.c'],
     1260                                           define_macros=[
     1261                                               ('HAVE_NDBM_H',None),
     1262                                               ],
     1263                                           libraries=ndbm_libs)
     1264                        break
     1265
     1266                elif cand == "gdbm":
     1267                    if self.compiler.find_library_file(lib_dirs, 'gdbm'):
     1268                        gdbm_libs = ['gdbm']
     1269                        if self.compiler.find_library_file(lib_dirs,
     1270                                                               'gdbm_compat'):
     1271                            gdbm_libs.append('gdbm_compat')
     1272                        if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
     1273                            print "building dbm using gdbm"
     1274                            dbmext = Extension(
     1275                                'dbm', ['dbmmodule.c'],
     1276                                define_macros=[
     1277                                    ('HAVE_GDBM_NDBM_H', None),
     1278                                    ],
     1279                                libraries = gdbm_libs)
     1280                            break
     1281                        if find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
     1282                            print "building dbm using gdbm"
     1283                            dbmext = Extension(
     1284                                'dbm', ['dbmmodule.c'],
     1285                                define_macros=[
     1286                                    ('HAVE_GDBM_DASH_NDBM_H', None),
     1287                                    ],
     1288                                libraries = gdbm_libs)
     1289                            break
     1290                elif cand == "bdb":
     1291                    if db_incs is not None:
     1292                        print "building dbm using bdb"
     1293                        dbmext = Extension('dbm', ['dbmmodule.c'],
     1294                                           library_dirs=dblib_dir,
     1295                                           runtime_library_dirs=dblib_dir,
     1296                                           include_dirs=db_incs,
     1297                                           define_macros=[
     1298                                               ('HAVE_BERKDB_H', None),
     1299                                               ('DB_DBM_HSEARCH', None),
     1300                                               ],
     1301                                           libraries=dblibs)
     1302                        break
     1303            if dbmext is not None:
     1304                exts.append(dbmext)
    10501305            else:
    10511306                missing.append('dbm')
    10521307
    10531308        # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
    1054         if (self.compiler.find_library_file(lib_dirs, 'gdbm')):
     1309        if ('gdbm' in dbm_order and
     1310            self.compiler.find_library_file(lib_dirs, 'gdbm')):
    10551311            exts.append( Extension('gdbm', ['gdbmmodule.c'],
    10561312                                   libraries = ['gdbm'] ) )
     
    10591315
    10601316        # Unix-only modules
    1061         if platform not in ['mac', 'win32']:
     1317        if host_platform not in ['win32']:
    10621318            # Steen Lumholt's termios module
    10631319            exts.append( Extension('termios', ['termios.c']) )
    10641320            # Jeremy Hylton's rlimit interface
    1065             if platform not in ['atheos']:
     1321            if host_platform not in ['atheos']:
    10661322                exts.append( Extension('resource', ['resource.c']) )
    10671323            else:
     
    10691325
    10701326            # Sun yellow pages. Some systems have the functions in libc.
    1071             if (platform not in ['cygwin', 'atheos', 'qnx6'] and
     1327            if (host_platform not in ['cygwin', 'atheos', 'qnx6'] and
    10721328                find_file('rpcsvc/yp_prot.h', inc_dirs, []) is not None):
    10731329                if (self.compiler.find_library_file(lib_dirs, 'nsl')):
     
    10851341        # provided by the ncurses library.
    10861342        panel_library = 'panel'
    1087         if (self.compiler.find_library_file(lib_dirs, 'ncursesw')):
    1088             curses_libs = ['ncursesw']
    1089             # Bug 1464056: If _curses.so links with ncursesw,
    1090             # _curses_panel.so must link with panelw.
    1091             panel_library = 'panelw'
     1343        if curses_library.startswith('ncurses'):
     1344            if curses_library == 'ncursesw':
     1345                # Bug 1464056: If _curses.so links with ncursesw,
     1346                # _curses_panel.so must link with panelw.
     1347                panel_library = 'panelw'
     1348            curses_libs = [curses_library]
    10921349            exts.append( Extension('_curses', ['_cursesmodule.c'],
    10931350                                   libraries = curses_libs) )
    1094         elif (self.compiler.find_library_file(lib_dirs, 'ncurses')):
    1095             curses_libs = ['ncurses']
    1096             exts.append( Extension('_curses', ['_cursesmodule.c'],
    1097                                    libraries = curses_libs) )
    1098         elif (self.compiler.find_library_file(lib_dirs, 'curses')
    1099               and platform != 'darwin'):
     1351        elif curses_library == 'curses' and host_platform != 'darwin':
    11001352                # OSX has an old Berkeley curses, not good enough for
    11011353                # the _curses module.
     
    11381390            version = '"0.0.0"'
    11391391            version_req = '"1.1.3"'
     1392            if host_platform == 'darwin' and is_macosx_sdk_path(zlib_h):
     1393                zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:])
    11401394            fp = open(zlib_h)
    11411395            while 1:
     
    11481402            if version >= version_req:
    11491403                if (self.compiler.find_library_file(lib_dirs, 'z')):
    1150                     if sys.platform == "darwin":
     1404                    if host_platform == "darwin":
    11511405                        zlib_extra_link_args = ('-Wl,-search_paths_first',)
    11521406                    else:
     
    11801434        # Gustavo Niemeyer's bz2 module.
    11811435        if (self.compiler.find_library_file(lib_dirs, 'bz2')):
    1182             if sys.platform == "darwin":
     1436            if host_platform == "darwin":
    11831437                bz2_extra_link_args = ('-Wl,-search_paths_first',)
    11841438            else:
     
    11921446        # Interface to the Expat XML parser
    11931447        #
    1194         # Expat was written by James Clark and is now maintained by a
    1195         # group of developers on SourceForge; see www.libexpat.org for
    1196         # more information.  The pyexpat module was written by Paul
    1197         # Prescod after a prototype by Jack Jansen.  The Expat source
    1198         # is included in Modules/expat/.  Usage of a system
    1199         # shared libexpat.so/expat.dll is not advised.
     1448        # Expat was written by James Clark and is now maintained by a group of
     1449        # developers on SourceForge; see www.libexpat.org for more information.
     1450        # The pyexpat module was written by Paul Prescod after a prototype by
     1451        # Jack Jansen.  The Expat source is included in Modules/expat/.  Usage
     1452        # of a system shared libexpat.so is possible with --with-system-expat
     1453        # configure option.
    12001454        #
    12011455        # More information on Expat can be found at www.libexpat.org.
    12021456        #
    1203         expatinc = os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')
    1204         define_macros = [
    1205             ('HAVE_EXPAT_CONFIG_H', '1'),
    1206         ]
     1457        if '--with-system-expat' in sysconfig.get_config_var("CONFIG_ARGS"):
     1458            expat_inc = []
     1459            define_macros = []
     1460            expat_lib = ['expat']
     1461            expat_sources = []
     1462            expat_depends = []
     1463        else:
     1464            expat_inc = [os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')]
     1465            define_macros = [
     1466                ('HAVE_EXPAT_CONFIG_H', '1'),
     1467            ]
     1468            expat_lib = []
     1469            expat_sources = ['expat/xmlparse.c',
     1470                             'expat/xmlrole.c',
     1471                             'expat/xmltok.c']
     1472            expat_depends = ['expat/ascii.h',
     1473                             'expat/asciitab.h',
     1474                             'expat/expat.h',
     1475                             'expat/expat_config.h',
     1476                             'expat/expat_external.h',
     1477                             'expat/internal.h',
     1478                             'expat/latin1tab.h',
     1479                             'expat/utf8tab.h',
     1480                             'expat/xmlrole.h',
     1481                             'expat/xmltok.h',
     1482                             'expat/xmltok_impl.h'
     1483                             ]
    12071484
    12081485        exts.append(Extension('pyexpat',
    12091486                              define_macros = define_macros,
    1210                               include_dirs = [expatinc],
    1211                               sources = ['pyexpat.c',
    1212                                          'expat/xmlparse.c',
    1213                                          'expat/xmlrole.c',
    1214                                          'expat/xmltok.c',
    1215                                          ],
     1487                              include_dirs = expat_inc,
     1488                              libraries = expat_lib,
     1489                              sources = ['pyexpat.c'] + expat_sources,
     1490                              depends = expat_depends,
    12161491                              ))
    12171492
     
    12231498            exts.append(Extension('_elementtree',
    12241499                                  define_macros = define_macros,
    1225                                   include_dirs = [expatinc],
     1500                                  include_dirs = expat_inc,
     1501                                  libraries = expat_lib,
    12261502                                  sources = ['_elementtree.c'],
     1503                                  depends = ['pyexpat.c'] + expat_sources +
     1504                                      expat_depends,
    12271505                                  ))
    12281506        else:
     
    12451523            # This requires sizeof(int) == sizeof(long) == sizeof(char*)
    12461524            dl_inc = find_file('dlfcn.h', [], inc_dirs)
    1247             if (dl_inc is not None) and (platform not in ['atheos']):
     1525            if (dl_inc is not None) and (host_platform not in ['atheos']):
    12481526                exts.append( Extension('dl', ['dlmodule.c']) )
    12491527            else:
     
    12561534
    12571535        # Richard Oudkerk's multiprocessing module
    1258         if platform == 'win32':             # Windows
     1536        if host_platform == 'win32':             # Windows
    12591537            macros = dict()
    12601538            libraries = ['ws2_32']
    12611539
    1262         elif platform == 'darwin':          # Mac OSX
    1263             macros = dict(
    1264                 HAVE_SEM_OPEN=1,
    1265                 HAVE_SEM_TIMEDWAIT=0,
    1266                 HAVE_FD_TRANSFER=1,
    1267                 HAVE_BROKEN_SEM_GETVALUE=1
    1268                 )
     1540        elif host_platform == 'darwin':          # Mac OSX
     1541            macros = dict()
    12691542            libraries = []
    12701543
    1271         elif platform == 'cygwin':          # Cygwin
    1272             macros = dict(
    1273                 HAVE_SEM_OPEN=1,
    1274                 HAVE_SEM_TIMEDWAIT=1,
    1275                 HAVE_FD_TRANSFER=0,
    1276                 HAVE_BROKEN_SEM_UNLINK=1
    1277                 )
     1544        elif host_platform == 'cygwin':          # Cygwin
     1545            macros = dict()
    12781546            libraries = []
    12791547
    1280         elif platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
     1548        elif host_platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
    12811549            # FreeBSD's P1003.1b semaphore support is very experimental
    12821550            # and has many known problems. (as of June 2008)
    1283             macros = dict(                  # FreeBSD
    1284                 HAVE_SEM_OPEN=0,
    1285                 HAVE_SEM_TIMEDWAIT=0,
    1286                 HAVE_FD_TRANSFER=1,
    1287                 )
     1551            macros = dict()
    12881552            libraries = []
    12891553
    1290         elif platform.startswith('openbsd'):
    1291             macros = dict(                  # OpenBSD
    1292                 HAVE_SEM_OPEN=0,            # Not implemented
    1293                 HAVE_SEM_TIMEDWAIT=0,
    1294                 HAVE_FD_TRANSFER=1,
    1295                 )
     1554        elif host_platform.startswith('openbsd'):
     1555            macros = dict()
    12961556            libraries = []
    12971557
    1298         elif platform.startswith('netbsd'):
    1299             macros = dict(                  # at least NetBSD 5
    1300                 HAVE_SEM_OPEN=1,
    1301                 HAVE_SEM_TIMEDWAIT=0,
    1302                 HAVE_FD_TRANSFER=1,
    1303                 HAVE_BROKEN_SEM_GETVALUE=1
    1304                 )
     1558        elif host_platform.startswith('netbsd'):
     1559            macros = dict()
    13051560            libraries = []
    13061561
    13071562        else:                                   # Linux and other unices
    1308             macros = dict(
    1309                 HAVE_SEM_OPEN=1,
    1310                 HAVE_SEM_TIMEDWAIT=1,
    1311                 HAVE_FD_TRANSFER=1
    1312                 )
     1563            macros = dict()
    13131564            libraries = ['rt']
    13141565
    1315         if platform == 'win32':
     1566        if host_platform == 'win32':
    13161567            multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
    13171568                                     '_multiprocessing/semaphore.c',
     
    13251576                                     '_multiprocessing/socket_connection.c'
    13261577                                   ]
    1327 
    1328             if macros.get('HAVE_SEM_OPEN', False):
     1578            if (sysconfig.get_config_var('HAVE_SEM_OPEN') and not
     1579                sysconfig.get_config_var('POSIX_SEMAPHORES_NOT_ENABLED')):
    13291580                multiprocessing_srcs.append('_multiprocessing/semaphore.c')
    13301581
     
    13401591
    13411592        # Platform-specific libraries
    1342         if platform == 'linux2':
     1593        if host_platform == 'linux2':
    13431594            # Linux-specific modules
    13441595            exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
     
    13461597            missing.append('linuxaudiodev')
    13471598
    1348         if platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
    1349                         'freebsd7', 'freebsd8'):
     1599        if (host_platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
     1600                        'freebsd7', 'freebsd8')
     1601            or host_platform.startswith("gnukfreebsd")):
    13501602            exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
    13511603        else:
    13521604            missing.append('ossaudiodev')
    13531605
    1354         if platform == 'sunos5':
     1606        if host_platform == 'sunos5':
    13551607            # SunOS specific modules
    13561608            exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
     
    13581610            missing.append('sunaudiodev')
    13591611
    1360         if platform == 'darwin':
     1612        if host_platform == 'darwin':
    13611613            # _scproxy
    13621614            exts.append(Extension("_scproxy", [os.path.join(srcdir, "Mac/Modules/_scproxy.c")],
     
    13671619
    13681620
    1369         if platform == 'darwin' and ("--disable-toolbox-glue" not in
     1621        if host_platform == 'darwin' and ("--disable-toolbox-glue" not in
    13701622                sysconfig.get_config_var("CONFIG_ARGS")):
    13711623
     
    14721724            missing.append('_tkinter')
    14731725
     1726##         # Uncomment these lines if you want to play with xxmodule.c
     1727##         ext = Extension('xx', ['xxmodule.c'])
     1728##         self.extensions.append(ext)
     1729
    14741730        return missing
     1731
     1732    def detect_tkinter_explicitly(self):
     1733        # Build _tkinter using explicit locations for Tcl/Tk.
     1734        #
     1735        # This is enabled when both arguments are given to ./configure:
     1736        #
     1737        #     --with-tcltk-includes="-I/path/to/tclincludes \
     1738        #                            -I/path/to/tkincludes"
     1739        #     --with-tcltk-libs="-L/path/to/tcllibs -ltclm.n \
     1740        #                        -L/path/to/tklibs -ltkm.n"
     1741        #
     1742        # These values can also be specified or overriden via make:
     1743        #    make TCLTK_INCLUDES="..." TCLTK_LIBS="..."
     1744        #
     1745        # This can be useful for building and testing tkinter with multiple
     1746        # versions of Tcl/Tk.  Note that a build of Tk depends on a particular
     1747        # build of Tcl so you need to specify both arguments and use care when
     1748        # overriding.
     1749
     1750        # The _TCLTK variables are created in the Makefile sharedmods target.
     1751        tcltk_includes = os.environ.get('_TCLTK_INCLUDES')
     1752        tcltk_libs = os.environ.get('_TCLTK_LIBS')
     1753        if not (tcltk_includes and tcltk_libs):
     1754            # Resume default configuration search.
     1755            return 0
     1756
     1757        extra_compile_args = tcltk_includes.split()
     1758        extra_link_args = tcltk_libs.split()
     1759        ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
     1760                        define_macros=[('WITH_APPINIT', 1)],
     1761                        extra_compile_args = extra_compile_args,
     1762                        extra_link_args = extra_link_args,
     1763                        )
     1764        self.extensions.append(ext)
     1765        return 1
    14751766
    14761767    def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
     
    14841775        ]
    14851776
     1777        sysroot = macosx_sdk_root()
     1778
    14861779        # Find the directory that contains the Tcl.framework and Tk.framework
    14871780        # bundles.
     
    14891782        for F in framework_dirs:
    14901783            # both Tcl.framework and Tk.framework should be present
     1784
     1785
    14911786            for fw in 'Tcl', 'Tk':
    1492                 if not exists(join(F, fw + '.framework')):
    1493                     break
     1787                if is_macosx_sdk_path(F):
     1788                    if not exists(join(sysroot, F[1:], fw + '.framework')):
     1789                        break
     1790                else:
     1791                    if not exists(join(F, fw + '.framework')):
     1792                        break
    14941793            else:
    14951794                # ok, F is now directory with both frameworks. Continure
     
    15211820        cflags = sysconfig.get_config_vars('CFLAGS')[0]
    15221821        archs = re.findall('-arch\s+(\w+)', cflags)
    1523         fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,))
     1822
     1823        if is_macosx_sdk_path(F):
     1824            fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(os.path.join(sysroot, F[1:]),))
     1825        else:
     1826            fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,))
     1827
    15241828        detected_archs = []
    15251829        for ln in fp:
     
    15431847        return 1
    15441848
    1545 
    15461849    def detect_tkinter(self, inc_dirs, lib_dirs):
    15471850        # The _tkinter module.
     1851
     1852        # Check whether --with-tcltk-includes and --with-tcltk-libs were
     1853        # configured or passed into the make target.  If so, use these values
     1854        # to build tkinter and bypass the searches for Tcl and TK in standard
     1855        # locations.
     1856        if self.detect_tkinter_explicitly():
     1857            return
    15481858
    15491859        # Rather than complicate the code below, detecting and building
    15501860        # AquaTk is a separate method. Only one Tkinter will be built on
    15511861        # Darwin - either AquaTk, if it is found, or X11 based Tk.
    1552         platform = self.get_platform()
    1553         if (platform == 'darwin' and
     1862        if (host_platform == 'darwin' and
    15541863            self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
    15551864            return
     
    15591868        # dots on Windows, for detection by cygwin.
    15601869        tcllib = tklib = tcl_includes = tk_includes = None
    1561         for version in ['8.5', '85', '8.4', '84', '8.3', '83', '8.2',
    1562                         '82', '8.1', '81', '8.0', '80']:
    1563             tklib = self.compiler.find_library_file(lib_dirs, 'tk' + version)
    1564             tcllib = self.compiler.find_library_file(lib_dirs, 'tcl' + version)
     1870        for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
     1871                        '8.2', '82', '8.1', '81', '8.0', '80']:
     1872            tklib = self.compiler.find_library_file(lib_dirs,
     1873                                                        'tk' + version)
     1874            tcllib = self.compiler.find_library_file(lib_dirs,
     1875                                                         'tcl' + version)
    15651876            if tklib and tcllib:
    15661877                # Exit the loop when we've found the Tcl/Tk libraries
     
    15721883            # they're put in /usr/include/{tcl,tk}X.Y
    15731884            dotversion = version
    1574             if '.' not in dotversion and "bsd" in sys.platform.lower():
     1885            if '.' not in dotversion and "bsd" in host_platform.lower():
    15751886                # OpenBSD and FreeBSD use Tcl/Tk library names like libtcl83.a,
    15761887                # but the include subdirs are named like .../include/tcl8.3.
     
    15981909
    15991910        # Check for various platform-specific directories
    1600         if platform == 'sunos5':
     1911        if host_platform == 'sunos5':
    16011912            include_dirs.append('/usr/openwin/include')
    16021913            added_lib_dirs.append('/usr/openwin/lib')
     
    16141925
    16151926        # If Cygwin, then verify that X is installed before proceeding
    1616         if platform == 'cygwin':
     1927        if host_platform == 'cygwin':
    16171928            x11_inc = find_file('X11/Xlib.h', [], include_dirs)
    16181929            if x11_inc is None:
     
    16211932        # Check for BLT extension
    16221933        if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
    1623                                            'BLT8.0'):
     1934                                               'BLT8.0'):
    16241935            defs.append( ('WITH_BLT', 1) )
    16251936            libs.append('BLT8.0')
    16261937        elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
    1627                                            'BLT'):
     1938                                                'BLT'):
    16281939            defs.append( ('WITH_BLT', 1) )
    16291940            libs.append('BLT')
     
    16331944        libs.append('tcl'+ version)
    16341945
    1635         if platform in ['aix3', 'aix4']:
     1946        if host_platform in ['aix3', 'aix4']:
    16361947            libs.append('ld')
    16371948
    16381949        # Finally, link with the X11 libraries (not appropriate on cygwin)
    1639         if platform != "cygwin":
     1950        if host_platform != "cygwin":
    16401951            libs.append('X11')
    16411952
     
    16481959        self.extensions.append(ext)
    16491960
    1650 ##         # Uncomment these lines if you want to play with xxmodule.c
    1651 ##         ext = Extension('xx', ['xxmodule.c'])
    1652 ##         self.extensions.append(ext)
    1653 
    16541961        # XXX handle these, but how to detect?
    16551962        # *** Uncomment and edit for PIL (TkImaging) extension only:
     
    16631970        # Darwin (OS X) uses preconfigured files, in
    16641971        # the Modules/_ctypes/libffi_osx directory.
    1665         (srcdir,) = sysconfig.get_config_vars('srcdir')
     1972        srcdir = sysconfig.get_config_var('srcdir')
    16661973        ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
    16671974                                                  '_ctypes', 'libffi_osx'))
     
    16891996    def configure_ctypes(self, ext):
    16901997        if not self.use_system_libffi:
    1691             if sys.platform == 'darwin':
     1998            if host_platform == 'darwin':
    16921999                return self.configure_ctypes_darwin(ext)
    16932000
    1694             (srcdir,) = sysconfig.get_config_vars('srcdir')
     2001            srcdir = sysconfig.get_config_var('srcdir')
    16952002            ffi_builddir = os.path.join(self.build_temp, 'libffi')
    16962003            ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
     
    17072014                from distutils.dir_util import mkpath
    17082015                mkpath(ffi_builddir)
    1709                 config_args = []
     2016                config_args = [arg for arg in sysconfig.get_config_var("CONFIG_ARGS").split()
     2017                               if (('--host=' in arg) or ('--build=' in arg))]
     2018                if not self.verbose:
     2019                    config_args.append("-q")
    17102020
    17112021                # Pass empty CFLAGS because we'll just append the resulting
     
    17202030
    17212031            fficonfig = {}
    1722             exec open(ffi_configfile) in fficonfig
     2032            with open(ffi_configfile) as f:
     2033                exec f in fficonfig
    17232034
    17242035            # Add .S (preprocessed assembly) to C compiler source extensions.
     
    17452056                   '_ctypes/callproc.c',
    17462057                   '_ctypes/stgdict.c',
    1747                    '_ctypes/cfield.c',
    1748                    '_ctypes/malloc_closure.c']
     2058                   '_ctypes/cfield.c']
    17492059        depends = ['_ctypes/ctypes.h']
    17502060
    1751         if sys.platform == 'darwin':
     2061        if host_platform == 'darwin':
     2062            sources.append('_ctypes/malloc_closure.c')
    17522063            sources.append('_ctypes/darwin/dlfcn_simple.c')
    17532064            extra_compile_args.append('-DMACOSX')
     
    17562067##            extra_link_args.extend(['-read_only_relocs', 'warning'])
    17572068
    1758         elif sys.platform == 'sunos5':
     2069        elif host_platform == 'sunos5':
    17592070            # XXX This shouldn't be necessary; it appears that some
    17602071            # of the assembler code is non-PIC (i.e. it has relocations
     
    17672078            extra_link_args.append('-mimpure-text')
    17682079
    1769         elif sys.platform.startswith('hp-ux'):
     2080        elif host_platform.startswith('hp-ux'):
    17702081            extra_link_args.append('-fPIC')
    17712082
     
    17842095            return
    17852096
    1786         if sys.platform == 'darwin':
     2097        if host_platform == 'darwin':
    17872098            # OS X 10.5 comes with libffi.dylib; the include files are
    17882099            # in /usr/include/ffi
    17892100            inc_dirs.append('/usr/include/ffi')
    17902101
    1791         ffi_inc = find_file('ffi.h', [], inc_dirs)
     2102        ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
     2103        if not ffi_inc or ffi_inc[0] == '':
     2104            ffi_inc = find_file('ffi.h', [], inc_dirs)
    17922105        if ffi_inc is not None:
    17932106            ffi_h = ffi_inc[0] + '/ffi.h'
Note: See TracChangeset for help on using the changeset viewer.