Changeset 391 for python/trunk/setup.py


Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/setup.py

    r384 r391  
    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)
     
    390532            inc_dirs += os.getenv('C_INCLUDE_PATH', '').split(os.pathsep)
    391533        # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
    392         if platform in ['osf1', 'unixware7', 'openunix8']:
     534        if host_platform in ['osf1', 'unixware7', 'openunix8']:
    393535            lib_dirs += ['/usr/ccs/lib']
    394536
    395         if platform == 'darwin':
     537        # HP-UX11iv3 keeps files in lib/hpux folders.
     538        if host_platform == 'hp-ux11':
     539            lib_dirs += ['/usr/lib/hpux64', '/usr/lib/hpux32']
     540
     541        if host_platform == 'darwin':
    396542            # This should work on any unixy platform ;-)
    397543            # If the user has bothered specifying additional -I and -L flags
     
    412558        # Check for MacOS X, which doesn't need libm.a at all
    413559        math_libs = ['m']
    414         if platform in ['darwin', 'beos', 'mac']:
     560        if host_platform in ['darwin', 'beos']:
    415561            math_libs = []
    416562
     
    423569
    424570        # Some modules that are normally always on:
    425         exts.append( Extension('_weakref', ['_weakref.c']) )
     571        #exts.append( Extension('_weakref', ['_weakref.c']) )
    426572
    427573        # array objects
    428574        exts.append( Extension('array', ['arraymodule.c']) )
    429575        # complex math library functions
    430         exts.append( Extension('cmath', ['cmathmodule.c'],
     576        exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'],
     577                               depends=['_math.h'],
    431578                               libraries=math_libs) )
    432 
    433579        # math library functions, e.g. sin()
    434         exts.append( Extension('math',  ['mathmodule.c'],
     580        exts.append( Extension('math',  ['mathmodule.c', '_math.c'],
     581                               depends=['_math.h'],
    435582                               libraries=math_libs) )
    436583        # fast string operations implemented in C
     
    456603        # operator.add() and similar goodies
    457604        exts.append( Extension('operator', ['operator.c']) )
    458         # Python 3.0 _fileio module
    459         exts.append( Extension("_fileio", ["_fileio.c"]) )
    460         # Python 3.0 _bytesio module
    461         exts.append( Extension("_bytesio", ["_bytesio.c"]) )
     605        # Python 3.1 _io library
     606        exts.append( Extension("_io",
     607            ["_io/bufferedio.c", "_io/bytesio.c", "_io/fileio.c",
     608             "_io/iobase.c", "_io/_iomodule.c", "_io/stringio.c", "_io/textio.c"],
     609             depends=["_io/_iomodule.h"], include_dirs=["Modules/_io"]))
    462610        # _functools
    463611        exts.append( Extension("_functools", ["_functoolsmodule.c"]) )
     
    482630        else:
    483631            locale_libs = []
    484         if platform == 'darwin':
     632        if host_platform == 'darwin':
    485633            locale_extra_link_args = ['-framework', 'CoreFoundation']
    486634        else:
     
    497645
    498646        # fcntl(2) and ioctl(2)
    499         exts.append( Extension('fcntl', ['fcntlmodule.c']) )
    500         if platform not in ['mac']:
    501             # pwd(3)
    502             exts.append( Extension('pwd', ['pwdmodule.c']) )
    503             # grp(3)
    504             exts.append( Extension('grp', ['grpmodule.c']) )
    505             # spwd, shadow passwords
    506             if (config_h_vars.get('HAVE_GETSPNAM', False) or
    507                     config_h_vars.get('HAVE_GETSPENT', False)):
    508                 exts.append( Extension('spwd', ['spwdmodule.c']) )
    509             else:
    510                 missing.append('spwd')
    511         else:
    512             missing.extend(['pwd', 'grp', 'spwd'])
     647        libs = []
     648        if (config_h_vars.get('FLOCK_NEEDS_LIBBSD', False)):
     649            # May be necessary on AIX for flock function
     650            libs = ['bsd']
     651        exts.append( Extension('fcntl', ['fcntlmodule.c'], libraries=libs) )
     652        # pwd(3)
     653        exts.append( Extension('pwd', ['pwdmodule.c']) )
     654        # grp(3)
     655        exts.append( Extension('grp', ['grpmodule.c']) )
     656        # spwd, shadow passwords
     657        if (config_h_vars.get('HAVE_GETSPNAM', False) or
     658                config_h_vars.get('HAVE_GETSPENT', False)):
     659            exts.append( Extension('spwd', ['spwdmodule.c']) )
     660        else:
     661            missing.append('spwd')
    513662
    514663        # select(2); not on ancient System V
     
    523672
    524673        # Memory-mapped files (also works on Win32).
    525         if platform not in ['atheos', 'mac', 'os2knix']:
     674        if host_platform not in ['atheos', 'os2knix']:
    526675            exts.append( Extension('mmap', ['mmapmodule.c']) )
    527676        else:
     
    529678
    530679        # Lance Ellinghaus's syslog module
    531         if platform not in ['mac']:
    532             # syslog daemon interface
    533             exts.append( Extension('syslog', ['syslogmodule.c']) )
    534         else:
    535             missing.append('syslog')
     680        # syslog daemon interface
     681        exts.append( Extension('syslog', ['syslogmodule.c']) )
    536682
    537683        # George Neville-Neil's timing module:
     
    563709        # readline
    564710        do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
    565         if platform == 'darwin':
     711        readline_termcap_library = ""
     712        curses_library = ""
     713        # Determine if readline is already linked against curses or tinfo.
     714        if do_readline and find_executable('ldd'):
     715            fp = os.popen("ldd %s" % do_readline)
     716            ldd_output = fp.readlines()
     717            ret = fp.close()
     718            if ret is None or ret >> 8 == 0:
     719                for ln in ldd_output:
     720                    if 'curses' in ln:
     721                        readline_termcap_library = re.sub(
     722                            r'.*lib(n?cursesw?)\.so.*', r'\1', ln
     723                        ).rstrip()
     724                        break
     725                    if 'tinfo' in ln: # termcap interface split out from ncurses
     726                        readline_termcap_library = 'tinfo'
     727                        break
     728        # Issue 7384: If readline is already linked against curses,
     729        # use the same library for the readline and curses modules.
     730        if 'curses' in readline_termcap_library:
     731            curses_library = readline_termcap_library
     732        elif self.compiler.find_library_file(lib_dirs, 'ncursesw'):
     733            curses_library = 'ncursesw'
     734        elif self.compiler.find_library_file(lib_dirs, 'ncurses'):
     735            curses_library = 'ncurses'
     736        elif self.compiler.find_library_file(lib_dirs, 'curses'):
     737            curses_library = 'curses'
     738
     739        if host_platform == 'darwin':
    566740            os_release = int(os.uname()[2].split('.')[0])
    567741            dep_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
     
    575749                    do_readline = False
    576750        if do_readline:
    577             if platform == 'darwin' and os_release < 9:
     751            if host_platform == 'darwin' and os_release < 9:
    578752                # In every directory on the search path search for a dynamic
    579753                # library and then a static library, instead of first looking
    580754                # for dynamic libraries on the entiry path.
    581755                # This way a staticly linked custom readline gets picked up
    582                 # before the (broken) dynamic library in /usr/lib.
     756                # before the (possibly broken) dynamic library in /usr/lib.
    583757                readline_extra_link_args = ('-Wl,-search_paths_first',)
    584758            else:
     
    586760
    587761            readline_libs = ['readline']
    588             if self.compiler.find_library_file(lib_dirs,
    589                                                  'ncursesw'):
    590                 readline_libs.append('ncursesw')
    591             elif self.compiler.find_library_file(lib_dirs,
    592                                                  'ncurses'):
    593                 readline_libs.append('ncurses')
    594             elif self.compiler.find_library_file(lib_dirs, 'curses'):
    595                 readline_libs.append('curses')
     762            if readline_termcap_library:
     763                pass # Issue 7384: Already linked against curses or tinfo.
     764            elif curses_library:
     765                readline_libs.append(curses_library)
    596766            elif self.compiler.find_library_file(lib_dirs +
    597                                                ['/usr/lib/termcap'],
    598                                                'termcap'):
     767                                                     ['/usr/lib/termcap'],
     768                                                     'termcap'):
    599769                readline_libs.append('termcap')
    600770            exts.append( Extension('readline', ['readline.c'],
     
    605775            missing.append('readline')
    606776
    607         if platform not in ['mac']:
    608             # crypt module.
    609 
    610             if self.compiler.find_library_file(lib_dirs, 'crypt'):
    611                 libs = ['crypt']
    612             else:
    613                 libs = []
    614             exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
    615         else:
    616             missing.append('crypt')
     777        # crypt module.
     778
     779        if self.compiler.find_library_file(lib_dirs, 'crypt'):
     780            libs = ['crypt']
     781        else:
     782            libs = []
     783        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
    617784
    618785        # CSV files
     
    620787
    621788        # socket(2)
    622         exts.append( Extension('_socket', ['socketmodule.c'],
    623                                depends = ['socketmodule.h']) )
     789        exts.append( Extension('_socket', ['socketmodule.c', 'timemodule.c'],
     790                               depends=['socketmodule.h'],
     791                               libraries=math_libs) )
    624792        # Detect SSL support for the socket module (via _ssl)
    625793        search_for_ssl_incs_in = [
     
    654822        openssl_ver_re = re.compile(
    655823            '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' )
    656         for ssl_inc_dir in inc_dirs + search_for_ssl_incs_in:
    657             name = os.path.join(ssl_inc_dir, 'openssl', 'opensslv.h')
    658             if os.path.isfile(name):
    659                 try:
    660                     incfile = open(name, 'r')
    661                     for line in incfile:
    662                         m = openssl_ver_re.match(line)
    663                         if m:
    664                             openssl_ver = eval(m.group(1))
    665                             break
    666                 except IOError:
    667                     pass
    668 
    669             # first version found is what we'll use (as the compiler should)
    670             if openssl_ver:
    671                 break
    672 
    673         #print 'openssl_ver = 0x%08x' % openssl_ver
    674 
    675         if (ssl_incs is not None and
    676             ssl_libs is not None and
    677             openssl_ver >= 0x00907000):
    678             # The _hashlib module wraps optimized implementations
    679             # of hash functions from the OpenSSL library.
    680             exts.append( Extension('_hashlib', ['_hashopenssl.c'],
    681                                    include_dirs = ssl_incs,
    682                                    library_dirs = ssl_libs,
    683                                    libraries = ['ssl', 'crypto']) )
    684             # these aren't strictly missing since they are unneeded.
    685             #missing.extend(['_sha', '_md5'])
    686         else:
     824
     825        # look for the openssl version header on the compiler search path.
     826        opensslv_h = find_file('openssl/opensslv.h', [],
     827                inc_dirs + search_for_ssl_incs_in)
     828        if opensslv_h:
     829            name = os.path.join(opensslv_h[0], 'openssl/opensslv.h')
     830            if host_platform == 'darwin' and is_macosx_sdk_path(name):
     831                name = os.path.join(macosx_sdk_root(), name[1:])
     832            try:
     833                incfile = open(name, 'r')
     834                for line in incfile:
     835                    m = openssl_ver_re.match(line)
     836                    if m:
     837                        openssl_ver = eval(m.group(1))
     838            except IOError, msg:
     839                print "IOError while reading opensshv.h:", msg
     840                pass
     841
     842        min_openssl_ver = 0x00907000
     843        have_any_openssl = ssl_incs is not None and ssl_libs is not None
     844        have_usable_openssl = (have_any_openssl and
     845                               openssl_ver >= min_openssl_ver)
     846
     847        if have_any_openssl:
     848            if have_usable_openssl:
     849                # The _hashlib module wraps optimized implementations
     850                # of hash functions from the OpenSSL library.
     851                exts.append( Extension('_hashlib', ['_hashopenssl.c'],
     852                                       include_dirs = ssl_incs,
     853                                       library_dirs = ssl_libs,
     854                                       libraries = ['ssl', 'crypto']) )
     855            else:
     856                print ("warning: openssl 0x%08x is too old for _hashlib" %
     857                       openssl_ver)
     858                missing.append('_hashlib')
     859        if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
    687860            # The _sha module implements the SHA1 hash algorithm.
    688861            exts.append( Extension('_sha', ['shamodule.c']) )
     
    693866                            sources = ['md5module.c', 'md5.c'],
    694867                            depends = ['md5.h']) )
    695             missing.append('_hashlib')
    696 
    697         if (openssl_ver < 0x00908000):
     868
     869        min_sha2_openssl_ver = 0x00908000
     870        if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
    698871            # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
    699872            exts.append( Extension('_sha256', ['sha256module.c']) )
     
    715888        # versions of BerkeleyDB already installed.
    716889
    717         max_db_ver = (4, 8)
    718         min_db_ver = (3, 3)
     890        max_db_ver = (5, 3)
     891        min_db_ver = (4, 3)
    719892        db_setup_debug = True   # verbose debug prints from this script?
    720893
     
    737910
    738911        def gen_db_minor_ver_nums(major):
    739             if major == 4:
     912            if major == 5:
    740913                for x in range(max_db_ver[1]+1):
     914                    if allow_db_ver((5, x)):
     915                        yield x
     916            elif major == 4:
     917                for x in range(9):
    741918                    if allow_db_ver((4, x)):
    742919                        yield x
     
    779956            db_inc_paths.append('/opt/db-3.%d/include' % x)
    780957
     958        if cross_compiling:
     959            db_inc_paths = []
     960
    781961        # Add some common subdirectories for Sleepycat DB to the list,
    782962        # based on the standard include directories. This way DB3/4 gets
     
    799979        db_ver_inc_map = {}
    800980
     981        if host_platform == 'darwin':
     982            sysroot = macosx_sdk_root()
     983
    801984        class db_found(Exception): pass
    802985        try:
     
    805988            for d in inc_dirs + db_inc_paths:
    806989                f = os.path.join(d, "db.h")
     990
     991                if host_platform == 'darwin' and is_macosx_sdk_path(d):
     992                    f = os.path.join(sysroot, d[1:], "db.h")
     993
    807994                if db_setup_debug: print "db: looking for db.h in", f
    808995                if os.path.exists(f):
     
    8511038                    db_incdir.replace("include", 'lib'),
    8521039                ]
    853                 db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
    854 
    855                 # Look for a version specific db-X.Y before an ambiguoius dbX
     1040
     1041                if host_platform != 'darwin':
     1042                    db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
     1043
     1044                else:
     1045                    # Same as other branch, but takes OSX SDK into account
     1046                    tmp = []
     1047                    for dn in db_dirs_to_check:
     1048                        if is_macosx_sdk_path(dn):
     1049                            if os.path.isdir(os.path.join(sysroot, dn[1:])):
     1050                                tmp.append(dn)
     1051                        else:
     1052                            if os.path.isdir(dn):
     1053                                tmp.append(dn)
     1054                    db_dirs_to_check = tmp
     1055
     1056                # Look for a version specific db-X.Y before an ambiguous dbX
    8561057                # XXX should we -ever- look for a dbX name?  Do any
    8571058                # systems really not name their library by version and
     
    9091110                             '/usr/local/include/sqlite3',
    9101111                           ]
     1112        if cross_compiling:
     1113            sqlite_inc_paths = []
    9111114        MIN_SQLITE_VERSION_NUMBER = (3, 0, 8)
    9121115        MIN_SQLITE_VERSION = ".".join([str(x)
     
    9161119        # ones. This allows one to override the copy of sqlite on OSX,
    9171120        # where /usr/include contains an old version of sqlite.
    918         for d in inc_dirs + sqlite_inc_paths:
     1121        if host_platform == 'darwin':
     1122            sysroot = macosx_sdk_root()
     1123
     1124        for d_ in inc_dirs + sqlite_inc_paths:
     1125            d = d_
     1126            if host_platform == 'darwin' and is_macosx_sdk_path(d):
     1127                d = os.path.join(sysroot, d[1:])
     1128
    9191129            f = os.path.join(d, "sqlite3.h")
    9201130            if os.path.exists(f):
     
    9221132                incf = open(f).read()
    9231133                m = re.search(
    924                     r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf)
     1134                    r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"([\d\.]*)"', incf)
    9251135                if m:
    9261136                    sqlite_version = m.group(1)
     
    9641174
    9651175            sqlite_defines = []
    966             if sys.platform != "win32":
     1176            if host_platform != "win32":
    9671177                sqlite_defines.append(('MODULE_NAME', '"sqlite3"'))
    9681178            else:
    9691179                sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"'))
    9701180
    971 
    972             if sys.platform == 'darwin':
     1181            # Comment this out if you want the sqlite3 module to be able to load extensions.
     1182            sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))
     1183
     1184            if host_platform == 'darwin':
    9731185                # In every directory on the search path search for a dynamic
    9741186                # library and then a static library, instead of first looking
    975                 # for dynamic libraries on the entiry path.
    976                 # This way a staticly linked custom sqlite gets picked up
     1187                # for dynamic libraries on the entire path.
     1188                # This way a statically linked custom sqlite gets picked up
    9771189                # before the dynamic library in /usr/lib.
    9781190                sqlite_extra_link_args = ('-Wl,-search_paths_first',)
     
    10031215        # when attempting to compile and it will fail.
    10041216        f = "/usr/include/db.h"
     1217
     1218        if host_platform == 'darwin':
     1219            if is_macosx_sdk_path(f):
     1220                sysroot = macosx_sdk_root()
     1221                f = os.path.join(sysroot, f[1:])
     1222
    10051223        if os.path.exists(f) and not db_incs:
    10061224            data = open(f).read()
     
    10111229                ### but I don't have direct access to an osf1 platform and
    10121230                ### seemed to be muffing the search somehow
    1013                 libraries = platform == "osf1" and ['db'] or None
     1231                libraries = host_platform == "osf1" and ['db'] or None
    10141232                if libraries is not None:
    10151233                    exts.append(Extension('bsddb185', ['bsddbmodule.c'],
     
    10221240            missing.append('bsddb185')
    10231241
     1242        dbm_order = ['gdbm']
    10241243        # The standard Unix dbm module:
    1025         if platform not in ['cygwin']:
    1026             if find_file("ndbm.h", inc_dirs, []) is not None:
    1027                 # Some systems have -lndbm, others don't
    1028                 if self.compiler.find_library_file(lib_dirs, 'ndbm'):
    1029                     ndbm_libs = ['ndbm']
    1030                 else:
    1031                     ndbm_libs = []
    1032                 exts.append( Extension('dbm', ['dbmmodule.c'],
    1033                                        define_macros=[('HAVE_NDBM_H',None)],
    1034                                        libraries = ndbm_libs ) )
    1035             elif self.compiler.find_library_file(lib_dirs, 'gdbm'):
    1036                 gdbm_libs = ['gdbm']
    1037                 if self.compiler.find_library_file(lib_dirs, 'gdbm_compat'):
    1038                     gdbm_libs.append('gdbm_compat')
    1039                 if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
    1040                     exts.append( Extension(
    1041                         'dbm', ['dbmmodule.c'],
    1042                         define_macros=[('HAVE_GDBM_NDBM_H',None)],
    1043                         libraries = gdbm_libs ) )
    1044                 elif find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
    1045                     exts.append( Extension(
    1046                         'dbm', ['dbmmodule.c'],
    1047                         define_macros=[('HAVE_GDBM_DASH_NDBM_H',None)],
    1048                         libraries = gdbm_libs ) )
    1049                 else:
    1050                     missing.append('dbm')
    1051             elif db_incs is not None:
    1052                 exts.append( Extension('dbm', ['dbmmodule.c'],
    1053                                        library_dirs=dblib_dir,
    1054                                        runtime_library_dirs=dblib_dir,
    1055                                        include_dirs=db_incs,
    1056                                        define_macros=[('HAVE_BERKDB_H',None),
    1057                                                       ('DB_DBM_HSEARCH',None)],
    1058                                        libraries=dblibs))
     1244        if host_platform not in ['cygwin']:
     1245            config_args = [arg.strip("'")
     1246                           for arg in sysconfig.get_config_var("CONFIG_ARGS").split()]
     1247            dbm_args = [arg for arg in config_args
     1248                        if arg.startswith('--with-dbmliborder=')]
     1249            if dbm_args:
     1250                dbm_order = [arg.split('=')[-1] for arg in dbm_args][-1].split(":")
     1251            else:
     1252                dbm_order = "ndbm:gdbm:bdb".split(":")
     1253            dbmext = None
     1254            for cand in dbm_order:
     1255                if cand == "ndbm":
     1256                    if find_file("ndbm.h", inc_dirs, []) is not None:
     1257                        # Some systems have -lndbm, others have -lgdbm_compat,
     1258                        # others don't have either
     1259                        if self.compiler.find_library_file(lib_dirs,
     1260                                                               'ndbm'):
     1261                            ndbm_libs = ['ndbm']
     1262                        elif self.compiler.find_library_file(lib_dirs,
     1263                                                             'gdbm_compat'):
     1264                            ndbm_libs = ['gdbm_compat']
     1265                        else:
     1266                            ndbm_libs = []
     1267                        print "building dbm using ndbm"
     1268                        dbmext = Extension('dbm', ['dbmmodule.c'],
     1269                                           define_macros=[
     1270                                               ('HAVE_NDBM_H',None),
     1271                                               ],
     1272                                           libraries=ndbm_libs)
     1273                        break
     1274
     1275                elif cand == "gdbm":
     1276                    if self.compiler.find_library_file(lib_dirs, 'gdbm'):
     1277                        gdbm_libs = ['gdbm']
     1278                        if self.compiler.find_library_file(lib_dirs,
     1279                                                               'gdbm_compat'):
     1280                            gdbm_libs.append('gdbm_compat')
     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_NDBM_H', None),
     1287                                    ],
     1288                                libraries = gdbm_libs)
     1289                            break
     1290                        if find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
     1291                            print "building dbm using gdbm"
     1292                            dbmext = Extension(
     1293                                'dbm', ['dbmmodule.c'],
     1294                                define_macros=[
     1295                                    ('HAVE_GDBM_DASH_NDBM_H', None),
     1296                                    ],
     1297                                libraries = gdbm_libs)
     1298                            break
     1299                elif cand == "bdb":
     1300                    if db_incs is not None:
     1301                        print "building dbm using bdb"
     1302                        dbmext = Extension('dbm', ['dbmmodule.c'],
     1303                                           library_dirs=dblib_dir,
     1304                                           runtime_library_dirs=dblib_dir,
     1305                                           include_dirs=db_incs,
     1306                                           define_macros=[
     1307                                               ('HAVE_BERKDB_H', None),
     1308                                               ('DB_DBM_HSEARCH', None),
     1309                                               ],
     1310                                           libraries=dblibs)
     1311                        break
     1312            if dbmext is not None:
     1313                exts.append(dbmext)
    10591314            else:
    10601315                missing.append('dbm')
    10611316
    10621317        # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
    1063         if (self.compiler.find_library_file(lib_dirs, 'gdbm')):
     1318        if ('gdbm' in dbm_order and
     1319            self.compiler.find_library_file(lib_dirs, 'gdbm')):
    10641320            exts.append( Extension('gdbm', ['gdbmmodule.c'],
    10651321                                   libraries = ['gdbm'] ) )
     
    10681324
    10691325        # Unix-only modules
    1070         if platform not in ['mac', 'win32']:
     1326        if host_platform not in ['win32']:
    10711327            # Steen Lumholt's termios module
    10721328            exts.append( Extension('termios', ['termios.c']) )
    10731329            # Jeremy Hylton's rlimit interface
    1074             if platform not in ['atheos']:
     1330            if host_platform not in ['atheos']:
    10751331                exts.append( Extension('resource', ['resource.c']) )
    10761332            else:
     
    10781334
    10791335            # Sun yellow pages. Some systems have the functions in libc.
    1080             if (platform not in ['cygwin', 'atheos', 'qnx6', 'os2knix'] and
     1336            if (host_platform not in ['cygwin', 'atheos', 'qnx6', 'os2knix'] and
    10811337                find_file('rpcsvc/yp_prot.h', inc_dirs, []) is not None):
    10821338                if (self.compiler.find_library_file(lib_dirs, 'nsl')):
     
    10941350        # provided by the ncurses library.
    10951351        panel_library = 'panel'
    1096         if (self.compiler.find_library_file(lib_dirs, 'ncursesw')):
    1097             curses_libs = ['ncursesw']
    1098             # Bug 1464056: If _curses.so links with ncursesw,
    1099             # _curses_panel.so must link with panelw.
    1100             panel_library = 'panelw'
     1352        if curses_library.startswith('ncurses'):
     1353            if curses_library == 'ncursesw':
     1354                # Bug 1464056: If _curses.so links with ncursesw,
     1355                # _curses_panel.so must link with panelw.
     1356                panel_library = 'panelw'
     1357            curses_libs = [curses_library]
     1358            if host_platform in ['os2emx', 'os2knix']:
     1359                curses_libs.append('tinfo')
    11011360            exts.append( Extension('_curses', ['_cursesmodule.c'],
    11021361                                   libraries = curses_libs) )
    1103         elif (self.compiler.find_library_file(lib_dirs, 'ncurses')):
    1104             curses_libs = ['ncurses', 'tinfo']
    1105             exts.append( Extension('_curses', ['_cursesmodule.c'],
    1106                                    libraries = curses_libs) )
    1107         elif (self.compiler.find_library_file(lib_dirs, 'curses')
    1108               and platform != 'darwin'):
     1362        elif curses_library == 'curses' and host_platform != 'darwin':
    11091363                # OSX has an old Berkeley curses, not good enough for
    11101364                # the _curses module.
     
    11471401            version = '"0.0.0"'
    11481402            version_req = '"1.1.3"'
     1403            if host_platform == 'darwin' and is_macosx_sdk_path(zlib_h):
     1404                zlib_h = os.path.join(macosx_sdk_root(), zlib_h[1:])
    11491405            fp = open(zlib_h)
    11501406            while 1:
     
    11571413            if version >= version_req:
    11581414                if (self.compiler.find_library_file(lib_dirs, 'z')):
    1159                     if sys.platform == "darwin":
     1415                    if host_platform == "darwin":
    11601416                        zlib_extra_link_args = ('-Wl,-search_paths_first',)
    11611417                    else:
     
    11891445        # Gustavo Niemeyer's bz2 module.
    11901446        if (self.compiler.find_library_file(lib_dirs, 'bz2')):
    1191             if sys.platform == "darwin":
     1447            if host_platform == "darwin":
    11921448                bz2_extra_link_args = ('-Wl,-search_paths_first',)
    11931449            else:
     
    12011457        # Interface to the Expat XML parser
    12021458        #
    1203         # Expat was written by James Clark and is now maintained by a
    1204         # group of developers on SourceForge; see www.libexpat.org for
    1205         # more information.  The pyexpat module was written by Paul
    1206         # Prescod after a prototype by Jack Jansen.  The Expat source
    1207         # is included in Modules/expat/.  Usage of a system
    1208         # shared libexpat.so/expat.dll is not advised.
     1459        # Expat was written by James Clark and is now maintained by a group of
     1460        # developers on SourceForge; see www.libexpat.org for more information.
     1461        # The pyexpat module was written by Paul Prescod after a prototype by
     1462        # Jack Jansen.  The Expat source is included in Modules/expat/.  Usage
     1463        # of a system shared libexpat.so is possible with --with-system-expat
     1464        # configure option.
    12091465        #
    12101466        # More information on Expat can be found at www.libexpat.org.
    12111467        #
    1212         expatinc = os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')
    1213         define_macros = [
    1214             ('HAVE_EXPAT_CONFIG_H', '1'),
    1215         ]
     1468        if '--with-system-expat' in sysconfig.get_config_var("CONFIG_ARGS"):
     1469            expat_inc = []
     1470            define_macros = []
     1471            expat_lib = ['expat']
     1472            expat_sources = []
     1473            expat_depends = []
     1474        else:
     1475            expat_inc = [os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')]
     1476            define_macros = [
     1477                ('HAVE_EXPAT_CONFIG_H', '1'),
     1478            ]
     1479            expat_lib = []
     1480            expat_sources = ['expat/xmlparse.c',
     1481                             'expat/xmlrole.c',
     1482                             'expat/xmltok.c']
     1483            expat_depends = ['expat/ascii.h',
     1484                             'expat/asciitab.h',
     1485                             'expat/expat.h',
     1486                             'expat/expat_config.h',
     1487                             'expat/expat_external.h',
     1488                             'expat/internal.h',
     1489                             'expat/latin1tab.h',
     1490                             'expat/utf8tab.h',
     1491                             'expat/xmlrole.h',
     1492                             'expat/xmltok.h',
     1493                             'expat/xmltok_impl.h'
     1494                             ]
    12161495
    12171496        exts.append(Extension('pyexpat',
    12181497                              define_macros = define_macros,
    1219                               include_dirs = [expatinc],
    1220                               sources = ['pyexpat.c',
    1221                                          'expat/xmlparse.c',
    1222                                          'expat/xmlrole.c',
    1223                                          'expat/xmltok.c',
    1224                                          ],
     1498                              include_dirs = expat_inc,
     1499                              libraries = expat_lib,
     1500                              sources = ['pyexpat.c'] + expat_sources,
     1501                              depends = expat_depends,
    12251502                              ))
    12261503
     
    12321509            exts.append(Extension('_elementtree',
    12331510                                  define_macros = define_macros,
    1234                                   include_dirs = [expatinc],
     1511                                  include_dirs = expat_inc,
     1512                                  libraries = expat_lib,
    12351513                                  sources = ['_elementtree.c'],
     1514                                  depends = ['pyexpat.c'] + expat_sources +
     1515                                      expat_depends,
    12361516                                  ))
    12371517        else:
     
    12541534            # This requires sizeof(int) == sizeof(long) == sizeof(char*)
    12551535            dl_inc = find_file('dlfcn.h', [], inc_dirs)
    1256             if (dl_inc is not None) and (platform not in ['atheos']):
     1536            if (dl_inc is not None) and (host_platform not in ['atheos']):
    12571537                exts.append( Extension('dl', ['dlmodule.c']) )
    12581538            else:
     
    12651545
    12661546        # Richard Oudkerk's multiprocessing module
    1267         if platform == 'win32':             # Windows
     1547        if host_platform == 'win32':             # Windows
    12681548            macros = dict()
    12691549            libraries = ['ws2_32']
    12701550
    1271         elif platform == 'darwin':          # Mac OSX
    1272             macros = dict(
    1273                 HAVE_SEM_OPEN=1,
    1274                 HAVE_SEM_TIMEDWAIT=0,
    1275                 HAVE_FD_TRANSFER=1,
    1276                 HAVE_BROKEN_SEM_GETVALUE=1
    1277                 )
     1551        elif host_platform == 'darwin':          # Mac OSX
     1552            macros = dict()
    12781553            libraries = []
    12791554
    1280         elif platform == 'cygwin':          # Cygwin
    1281             macros = dict(
    1282                 HAVE_SEM_OPEN=1,
    1283                 HAVE_SEM_TIMEDWAIT=1,
    1284                 HAVE_FD_TRANSFER=0,
    1285                 HAVE_BROKEN_SEM_UNLINK=1
    1286                 )
     1555        elif host_platform == 'cygwin':          # Cygwin
     1556            macros = dict()
    12871557            libraries = []
    12881558
    1289         elif platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
     1559        elif host_platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
    12901560            # FreeBSD's P1003.1b semaphore support is very experimental
    12911561            # and has many known problems. (as of June 2008)
    1292             macros = dict(                  # FreeBSD
    1293                 HAVE_SEM_OPEN=0,
    1294                 HAVE_SEM_TIMEDWAIT=0,
    1295                 HAVE_FD_TRANSFER=1,
    1296                 )
     1562            macros = dict()
    12971563            libraries = []
    12981564
    1299         elif platform in ('os2knix'):
    1300             # FreeBSD's P1003.1b semaphore support is very experimental
    1301             # and has many known problems. (as of June 2008)
    1302             macros = dict(                  # FreeBSD
    1303                 HAVE_SEM_OPEN=0,
    1304                 HAVE_SEM_TIMEDWAIT=0,
    1305                 )
     1565        elif host_platform.startswith('openbsd'):
     1566            macros = dict()
    13061567            libraries = []
    1307         elif platform.startswith('openbsd'):
    1308             macros = dict(                  # OpenBSD
    1309                 HAVE_SEM_OPEN=0,            # Not implemented
    1310                 HAVE_SEM_TIMEDWAIT=0,
    1311                 HAVE_FD_TRANSFER=1,
    1312                 )
     1568
     1569        elif host_platform.startswith('netbsd'):
     1570            macros = dict()
    13131571            libraries = []
    13141572
    1315         elif platform.startswith('netbsd'):
    1316             macros = dict(                  # at least NetBSD 5
    1317                 HAVE_SEM_OPEN=1,
    1318                 HAVE_SEM_TIMEDWAIT=0,
    1319                 HAVE_FD_TRANSFER=1,
    1320                 HAVE_BROKEN_SEM_GETVALUE=1
    1321                 )
    1322             libraries = []
    1323 
    13241573        else:                                   # Linux and other unices
    1325             macros = dict(
    1326                 HAVE_SEM_OPEN=1,
    1327                 HAVE_SEM_TIMEDWAIT=1,
    1328                 HAVE_FD_TRANSFER=1
    1329                 )
     1574            macros = dict()
    13301575            libraries = ['rt']
    13311576
    1332         if platform == 'win32':
     1577        if host_platform == 'win32':
    13331578            multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
    13341579                                     '_multiprocessing/semaphore.c',
     
    13421587                                     '_multiprocessing/socket_connection.c'
    13431588                                   ]
    1344 
    1345             if macros.get('HAVE_SEM_OPEN', False):
     1589            if (sysconfig.get_config_var('HAVE_SEM_OPEN') and not
     1590                sysconfig.get_config_var('POSIX_SEMAPHORES_NOT_ENABLED')):
    13461591                multiprocessing_srcs.append('_multiprocessing/semaphore.c')
    13471592
     
    13571602
    13581603        # Platform-specific libraries
    1359         if platform == 'linux2':
     1604        if host_platform == 'linux2':
    13601605            # Linux-specific modules
    13611606            exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
     
    13631608            missing.append('linuxaudiodev')
    13641609
    1365         if platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
    1366                         'freebsd7', 'freebsd8'):
     1610        if (host_platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
     1611                        'freebsd7', 'freebsd8')
     1612            or host_platform.startswith("gnukfreebsd")):
    13671613            exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
    13681614        else:
    13691615            missing.append('ossaudiodev')
    13701616
    1371         if platform == 'sunos5':
     1617        if host_platform == 'sunos5':
    13721618            # SunOS specific modules
    13731619            exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
     
    13751621            missing.append('sunaudiodev')
    13761622
    1377         if platform == 'darwin':
     1623        if host_platform == 'darwin':
    13781624            # _scproxy
    13791625            exts.append(Extension("_scproxy", [os.path.join(srcdir, "Mac/Modules/_scproxy.c")],
     
    13841630
    13851631
    1386         if platform == 'darwin' and ("--disable-toolbox-glue" not in
     1632        if host_platform == 'darwin' and ("--disable-toolbox-glue" not in
    13871633                sysconfig.get_config_var("CONFIG_ARGS")):
    13881634
     
    14891735            missing.append('_tkinter')
    14901736
     1737##         # Uncomment these lines if you want to play with xxmodule.c
     1738##         ext = Extension('xx', ['xxmodule.c'])
     1739##         self.extensions.append(ext)
     1740
    14911741        return missing
     1742
     1743    def detect_tkinter_explicitly(self):
     1744        # Build _tkinter using explicit locations for Tcl/Tk.
     1745        #
     1746        # This is enabled when both arguments are given to ./configure:
     1747        #
     1748        #     --with-tcltk-includes="-I/path/to/tclincludes \
     1749        #                            -I/path/to/tkincludes"
     1750        #     --with-tcltk-libs="-L/path/to/tcllibs -ltclm.n \
     1751        #                        -L/path/to/tklibs -ltkm.n"
     1752        #
     1753        # These values can also be specified or overriden via make:
     1754        #    make TCLTK_INCLUDES="..." TCLTK_LIBS="..."
     1755        #
     1756        # This can be useful for building and testing tkinter with multiple
     1757        # versions of Tcl/Tk.  Note that a build of Tk depends on a particular
     1758        # build of Tcl so you need to specify both arguments and use care when
     1759        # overriding.
     1760
     1761        # The _TCLTK variables are created in the Makefile sharedmods target.
     1762        tcltk_includes = os.environ.get('_TCLTK_INCLUDES')
     1763        tcltk_libs = os.environ.get('_TCLTK_LIBS')
     1764        if not (tcltk_includes and tcltk_libs):
     1765            # Resume default configuration search.
     1766            return 0
     1767
     1768        extra_compile_args = tcltk_includes.split()
     1769        extra_link_args = tcltk_libs.split()
     1770        ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
     1771                        define_macros=[('WITH_APPINIT', 1)],
     1772                        extra_compile_args = extra_compile_args,
     1773                        extra_link_args = extra_link_args,
     1774                        )
     1775        self.extensions.append(ext)
     1776        return 1
    14921777
    14931778    def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
     
    15011786        ]
    15021787
     1788        sysroot = macosx_sdk_root()
     1789
    15031790        # Find the directory that contains the Tcl.framework and Tk.framework
    15041791        # bundles.
     
    15061793        for F in framework_dirs:
    15071794            # both Tcl.framework and Tk.framework should be present
     1795
     1796
    15081797            for fw in 'Tcl', 'Tk':
    1509                 if not exists(join(F, fw + '.framework')):
    1510                     break
     1798                if is_macosx_sdk_path(F):
     1799                    if not exists(join(sysroot, F[1:], fw + '.framework')):
     1800                        break
     1801                else:
     1802                    if not exists(join(F, fw + '.framework')):
     1803                        break
    15111804            else:
    15121805                # ok, F is now directory with both frameworks. Continure
     
    15381831        cflags = sysconfig.get_config_vars('CFLAGS')[0]
    15391832        archs = re.findall('-arch\s+(\w+)', cflags)
    1540         fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,))
     1833
     1834        if is_macosx_sdk_path(F):
     1835            fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(os.path.join(sysroot, F[1:]),))
     1836        else:
     1837            fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,))
     1838
    15411839        detected_archs = []
    15421840        for ln in fp:
     
    15601858        return 1
    15611859
    1562 
    15631860    def detect_tkinter(self, inc_dirs, lib_dirs):
    15641861        # The _tkinter module.
     1862
     1863        # Check whether --with-tcltk-includes and --with-tcltk-libs were
     1864        # configured or passed into the make target.  If so, use these values
     1865        # to build tkinter and bypass the searches for Tcl and TK in standard
     1866        # locations.
     1867        if self.detect_tkinter_explicitly():
     1868            return
    15651869
    15661870        # Rather than complicate the code below, detecting and building
    15671871        # AquaTk is a separate method. Only one Tkinter will be built on
    15681872        # Darwin - either AquaTk, if it is found, or X11 based Tk.
    1569         platform = self.get_platform()
    1570         if (platform == 'darwin' and
     1873        if (host_platform == 'darwin' and
    15711874            self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
    15721875            return
     
    15761879        # dots on Windows, for detection by cygwin.
    15771880        tcllib = tklib = tcl_includes = tk_includes = None
    1578         for version in ['8.5', '85', '8.4', '84', '8.3', '83', '8.2',
    1579                         '82', '8.1', '81', '8.0', '80']:
    1580             tklib = self.compiler.find_library_file(lib_dirs, 'tk' + version)
    1581             tcllib = self.compiler.find_library_file(lib_dirs, 'tcl' + version)
     1881        for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
     1882                        '8.2', '82', '8.1', '81', '8.0', '80']:
     1883            tklib = self.compiler.find_library_file(lib_dirs,
     1884                                                        'tk' + version)
     1885            tcllib = self.compiler.find_library_file(lib_dirs,
     1886                                                         'tcl' + version)
    15821887            if tklib and tcllib:
    15831888                # Exit the loop when we've found the Tcl/Tk libraries
     
    15891894            # they're put in /usr/include/{tcl,tk}X.Y
    15901895            dotversion = version
    1591             if '.' not in dotversion and "bsd" in sys.platform.lower():
     1896            if '.' not in dotversion and "bsd" in host_platform.lower():
    15921897                # OpenBSD and FreeBSD use Tcl/Tk library names like libtcl83.a,
    15931898                # but the include subdirs are named like .../include/tcl8.3.
     
    16151920
    16161921        # Check for various platform-specific directories
    1617         if platform == 'sunos5':
     1922        if host_platform == 'sunos5':
    16181923            include_dirs.append('/usr/openwin/include')
    16191924            added_lib_dirs.append('/usr/openwin/lib')
     
    16311936
    16321937        # If Cygwin, then verify that X is installed before proceeding
    1633         if platform == 'cygwin':
     1938        if host_platform == 'cygwin':
    16341939            x11_inc = find_file('X11/Xlib.h', [], include_dirs)
    16351940            if x11_inc is None:
     
    16381943        # Check for BLT extension
    16391944        if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
    1640                                            'BLT8.0'):
     1945                                               'BLT8.0'):
    16411946            defs.append( ('WITH_BLT', 1) )
    16421947            libs.append('BLT8.0')
    16431948        elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
    1644                                            'BLT'):
     1949                                                'BLT'):
    16451950            defs.append( ('WITH_BLT', 1) )
    16461951            libs.append('BLT')
     
    16501955        libs.append('tcl'+ version)
    16511956
    1652         if platform in ['aix3', 'aix4']:
     1957        if host_platform in ['aix3', 'aix4']:
    16531958            libs.append('ld')
    16541959
    16551960        # Finally, link with the X11 libraries (not appropriate on cygwin)
    1656         if platform != "cygwin":
     1961        if host_platform != "cygwin":
    16571962            libs.append('X11')
    16581963
     
    16651970        self.extensions.append(ext)
    16661971
    1667 ##         # Uncomment these lines if you want to play with xxmodule.c
    1668 ##         ext = Extension('xx', ['xxmodule.c'])
    1669 ##         self.extensions.append(ext)
    1670 
    16711972        # XXX handle these, but how to detect?
    16721973        # *** Uncomment and edit for PIL (TkImaging) extension only:
     
    16801981        # Darwin (OS X) uses preconfigured files, in
    16811982        # the Modules/_ctypes/libffi_osx directory.
    1682         (srcdir,) = sysconfig.get_config_vars('srcdir')
     1983        srcdir = sysconfig.get_config_var('srcdir')
    16831984        ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
    16841985                                                  '_ctypes', 'libffi_osx'))
     
    17062007    def configure_ctypes(self, ext):
    17072008        if not self.use_system_libffi:
    1708             if sys.platform == 'darwin':
     2009            if host_platform == 'darwin':
    17092010                return self.configure_ctypes_darwin(ext)
    17102011
    1711             (srcdir,) = sysconfig.get_config_vars('srcdir')
     2012            srcdir = sysconfig.get_config_var('srcdir')
    17122013            ffi_builddir = os.path.join(self.build_temp, 'libffi')
    17132014            ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
     
    17242025                from distutils.dir_util import mkpath
    17252026                mkpath(ffi_builddir)
    1726                 config_args = []
     2027                config_args = [arg for arg in sysconfig.get_config_var("CONFIG_ARGS").split()
     2028                               if (('--host=' in arg) or ('--build=' in arg))]
     2029                if not self.verbose:
     2030                    config_args.append("-q")
    17272031
    17282032                # Pass empty CFLAGS because we'll just append the resulting
     
    17372041
    17382042            fficonfig = {}
    1739             exec open(ffi_configfile) in fficonfig
     2043            with open(ffi_configfile) as f:
     2044                exec f in fficonfig
    17402045
    17412046            # Add .S (preprocessed assembly) to C compiler source extensions.
     
    17622067                   '_ctypes/callproc.c',
    17632068                   '_ctypes/stgdict.c',
    1764                    '_ctypes/cfield.c',
    1765                    '_ctypes/malloc_closure.c']
     2069                   '_ctypes/cfield.c']
    17662070        depends = ['_ctypes/ctypes.h']
    17672071
    1768         if sys.platform == 'darwin':
     2072        if host_platform == 'darwin':
     2073            sources.append('_ctypes/malloc_closure.c')
    17692074            sources.append('_ctypes/darwin/dlfcn_simple.c')
    17702075            extra_compile_args.append('-DMACOSX')
     
    17732078##            extra_link_args.extend(['-read_only_relocs', 'warning'])
    17742079
    1775         elif sys.platform == 'sunos5':
     2080        elif host_platform == 'sunos5':
    17762081            # XXX This shouldn't be necessary; it appears that some
    17772082            # of the assembler code is non-PIC (i.e. it has relocations
     
    17842089            extra_link_args.append('-mimpure-text')
    17852090
    1786         elif sys.platform.startswith('hp-ux'):
     2091        elif host_platform.startswith('hp-ux'):
    17872092            extra_link_args.append('-fPIC')
    17882093
     
    18012106            return
    18022107
    1803         if sys.platform == 'darwin':
     2108        if host_platform == 'darwin':
    18042109            # OS X 10.5 comes with libffi.dylib; the include files are
    18052110            # in /usr/include/ffi
    18062111            inc_dirs.append('/usr/include/ffi')
    18072112
    1808         ffi_inc = find_file('ffi.h', [], inc_dirs)
     2113        ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
     2114        if not ffi_inc or ffi_inc[0] == '':
     2115            ffi_inc = find_file('ffi.h', [], inc_dirs)
    18092116        if ffi_inc is not None:
    18102117            ffi_h = ffi_inc[0] + '/ffi.h'
Note: See TracChangeset for help on using the changeset viewer.