setup.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import sys, os
  2. import subprocess
  3. import errno
  4. # on Windows we give up and always import setuptools early to fix things for us
  5. if sys.platform == "win32":
  6. import setuptools
  7. sources = ['c/_cffi_backend.c']
  8. libraries = ['ffi']
  9. include_dirs = ['/usr/include/ffi',
  10. '/usr/include/libffi'] # may be changed by pkg-config
  11. define_macros = []
  12. library_dirs = []
  13. extra_compile_args = []
  14. extra_link_args = []
  15. def _ask_pkg_config(resultlist, option, result_prefix='', sysroot=False):
  16. pkg_config = os.environ.get('PKG_CONFIG','pkg-config')
  17. try:
  18. p = subprocess.Popen([pkg_config, option, 'libffi'],
  19. stdout=subprocess.PIPE)
  20. except OSError as e:
  21. if e.errno not in [errno.ENOENT, errno.EACCES]:
  22. raise
  23. else:
  24. t = p.stdout.read().decode().strip()
  25. p.stdout.close()
  26. if p.wait() == 0:
  27. res = t.split()
  28. # '-I/usr/...' -> '/usr/...'
  29. for x in res:
  30. assert x.startswith(result_prefix)
  31. res = [x[len(result_prefix):] for x in res]
  32. #print 'PKG_CONFIG:', option, res
  33. #
  34. sysroot = sysroot and os.environ.get('PKG_CONFIG_SYSROOT_DIR', '')
  35. if sysroot:
  36. # old versions of pkg-config don't support this env var,
  37. # so here we emulate its effect if needed
  38. res = [path if path.startswith(sysroot)
  39. else sysroot + path
  40. for path in res]
  41. #
  42. resultlist[:] = res
  43. def no_working_compiler_found():
  44. sys.stderr.write("""
  45. No working compiler found, or bogus compiler options passed to
  46. the compiler from Python's standard "distutils" module. See
  47. the error messages above. Likely, the problem is not related
  48. to CFFI but generic to the setup.py of any Python package that
  49. tries to compile C code. (Hints: on OS/X 10.8, for errors about
  50. -mno-fused-madd see http://stackoverflow.com/questions/22313407/
  51. Otherwise, see https://wiki.python.org/moin/CompLangPython or
  52. the IRC channel #python on irc.freenode.net.)\n""")
  53. sys.exit(1)
  54. def get_config():
  55. from distutils.core import Distribution
  56. from distutils.sysconfig import get_config_vars
  57. get_config_vars() # workaround for a bug of distutils, e.g. on OS/X
  58. config = Distribution().get_command_obj('config')
  59. return config
  60. def ask_supports_thread():
  61. config = get_config()
  62. ok = (sys.platform != 'win32' and
  63. config.try_compile('__thread int some_threadlocal_variable_42;'))
  64. if ok:
  65. define_macros.append(('USE__THREAD', None))
  66. else:
  67. ok1 = config.try_compile('int some_regular_variable_42;')
  68. if not ok1:
  69. no_working_compiler_found()
  70. sys.stderr.write("Note: will not use '__thread' in the C code\n")
  71. _safe_to_ignore()
  72. def ask_supports_sync_synchronize():
  73. if sys.platform == 'win32':
  74. return
  75. config = get_config()
  76. ok = config.try_link('int main(void) { __sync_synchronize(); return 0; }')
  77. if ok:
  78. define_macros.append(('HAVE_SYNC_SYNCHRONIZE', None))
  79. else:
  80. sys.stderr.write("Note: will not use '__sync_synchronize()'"
  81. " in the C code\n")
  82. _safe_to_ignore()
  83. def _safe_to_ignore():
  84. sys.stderr.write("***** The above error message can be safely ignored.\n\n")
  85. def uses_msvc():
  86. config = get_config()
  87. return config.try_compile('#ifndef _MSC_VER\n#error "not MSVC"\n#endif')
  88. def use_pkg_config():
  89. if sys.platform == 'darwin' and os.path.exists('/usr/local/bin/brew'):
  90. use_homebrew_for_libffi()
  91. _ask_pkg_config(include_dirs, '--cflags-only-I', '-I', sysroot=True)
  92. _ask_pkg_config(extra_compile_args, '--cflags-only-other')
  93. _ask_pkg_config(library_dirs, '--libs-only-L', '-L', sysroot=True)
  94. _ask_pkg_config(extra_link_args, '--libs-only-other')
  95. _ask_pkg_config(libraries, '--libs-only-l', '-l')
  96. def use_homebrew_for_libffi():
  97. # We can build by setting:
  98. # PKG_CONFIG_PATH = $(brew --prefix libffi)/lib/pkgconfig
  99. with os.popen('brew --prefix libffi') as brew_prefix_cmd:
  100. prefix = brew_prefix_cmd.read().strip()
  101. pkgconfig = os.path.join(prefix, 'lib', 'pkgconfig')
  102. os.environ['PKG_CONFIG_PATH'] = (
  103. os.environ.get('PKG_CONFIG_PATH', '') + ':' + pkgconfig)
  104. if sys.platform == 'win32' and uses_msvc():
  105. COMPILE_LIBFFI = 'c/libffi_msvc' # from the CPython distribution
  106. else:
  107. COMPILE_LIBFFI = None
  108. if COMPILE_LIBFFI:
  109. assert os.path.isdir(COMPILE_LIBFFI), "directory not found!"
  110. include_dirs[:] = [COMPILE_LIBFFI]
  111. libraries[:] = []
  112. _filenames = [filename.lower() for filename in os.listdir(COMPILE_LIBFFI)]
  113. _filenames = [filename for filename in _filenames
  114. if filename.endswith('.c')]
  115. if sys.maxsize > 2**32:
  116. # 64-bit: unlist win32.c, and add instead win64.obj. If the obj
  117. # happens to get outdated at some point in the future, you need to
  118. # rebuild it manually from win64.asm.
  119. _filenames.remove('win32.c')
  120. extra_link_args.append(os.path.join(COMPILE_LIBFFI, 'win64.obj'))
  121. sources.extend(os.path.join(COMPILE_LIBFFI, filename)
  122. for filename in _filenames)
  123. else:
  124. use_pkg_config()
  125. ask_supports_thread()
  126. ask_supports_sync_synchronize()
  127. if 'freebsd' in sys.platform:
  128. include_dirs.append('/usr/local/include')
  129. if 'darwin' in sys.platform:
  130. try:
  131. p = subprocess.Popen(['xcrun', '--show-sdk-path'],
  132. stdout=subprocess.PIPE)
  133. except OSError as e:
  134. if e.errno not in [errno.ENOENT, errno.EACCES]:
  135. raise
  136. else:
  137. t = p.stdout.read().decode().strip()
  138. p.stdout.close()
  139. if p.wait() == 0:
  140. include_dirs.append(t + '/usr/include/ffi')
  141. if __name__ == '__main__':
  142. from setuptools import setup, Distribution, Extension
  143. class CFFIDistribution(Distribution):
  144. def has_ext_modules(self):
  145. # Event if we don't have extension modules (e.g. on PyPy) we want to
  146. # claim that we do so that wheels get properly tagged as Python
  147. # specific. (thanks dstufft!)
  148. return True
  149. # On PyPy, cffi is preinstalled and it is not possible, at least for now,
  150. # to install a different version. We work around it by making the setup()
  151. # arguments mostly empty in this case.
  152. cpython = ('_cffi_backend' not in sys.builtin_module_names)
  153. setup(
  154. name='cffi',
  155. description='Foreign Function Interface for Python calling C code.',
  156. long_description="""
  157. CFFI
  158. ====
  159. Foreign Function Interface for Python calling C code.
  160. Please see the `Documentation <http://cffi.readthedocs.org/>`_.
  161. Contact
  162. -------
  163. `Mailing list <https://groups.google.com/forum/#!forum/python-cffi>`_
  164. """,
  165. version='1.11.5',
  166. packages=['cffi'] if cpython else [],
  167. package_data={'cffi': ['_cffi_include.h', 'parse_c_type.h',
  168. '_embedding.h', '_cffi_errors.h']}
  169. if cpython else {},
  170. zip_safe=False,
  171. url='http://cffi.readthedocs.org',
  172. author='Armin Rigo, Maciej Fijalkowski',
  173. author_email='python-cffi@googlegroups.com',
  174. license='MIT',
  175. distclass=CFFIDistribution,
  176. ext_modules=[Extension(
  177. name='_cffi_backend',
  178. include_dirs=include_dirs,
  179. sources=sources,
  180. libraries=libraries,
  181. define_macros=define_macros,
  182. library_dirs=library_dirs,
  183. extra_compile_args=extra_compile_args,
  184. extra_link_args=extra_link_args,
  185. )] if cpython else [],
  186. install_requires=[
  187. 'pycparser',
  188. ] if cpython else [],
  189. entry_points = {
  190. "distutils.setup_keywords": [
  191. "cffi_modules = cffi.setuptools_ext:cffi_modules",
  192. ],
  193. } if cpython else {},
  194. classifiers=[
  195. 'Programming Language :: Python',
  196. 'Programming Language :: Python :: 2',
  197. 'Programming Language :: Python :: 2.6',
  198. 'Programming Language :: Python :: 2.7',
  199. 'Programming Language :: Python :: 3',
  200. 'Programming Language :: Python :: 3.2',
  201. 'Programming Language :: Python :: 3.3',
  202. 'Programming Language :: Python :: 3.4',
  203. 'Programming Language :: Python :: 3.5',
  204. 'Programming Language :: Python :: 3.6',
  205. 'Programming Language :: Python :: Implementation :: CPython',
  206. 'Programming Language :: Python :: Implementation :: PyPy',
  207. ],
  208. )