build_ext.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import os
  2. import sys
  3. import itertools
  4. from distutils.command.build_ext import build_ext as _du_build_ext
  5. from distutils.file_util import copy_file
  6. from distutils.ccompiler import new_compiler
  7. from distutils.sysconfig import customize_compiler, get_config_var
  8. from distutils.errors import DistutilsError
  9. from distutils import log
  10. from setuptools.extension import Library
  11. from setuptools.extern import six
  12. if six.PY2:
  13. import imp
  14. EXTENSION_SUFFIXES = [s for s, _, tp in imp.get_suffixes() if tp == imp.C_EXTENSION]
  15. else:
  16. from importlib.machinery import EXTENSION_SUFFIXES
  17. try:
  18. # Attempt to use Cython for building extensions, if available
  19. from Cython.Distutils.build_ext import build_ext as _build_ext
  20. # Additionally, assert that the compiler module will load
  21. # also. Ref #1229.
  22. __import__('Cython.Compiler.Main')
  23. except ImportError:
  24. _build_ext = _du_build_ext
  25. # make sure _config_vars is initialized
  26. get_config_var("LDSHARED")
  27. from distutils.sysconfig import _config_vars as _CONFIG_VARS
  28. def _customize_compiler_for_shlib(compiler):
  29. if sys.platform == "darwin":
  30. # building .dylib requires additional compiler flags on OSX; here we
  31. # temporarily substitute the pyconfig.h variables so that distutils'
  32. # 'customize_compiler' uses them before we build the shared libraries.
  33. tmp = _CONFIG_VARS.copy()
  34. try:
  35. # XXX Help! I don't have any idea whether these are right...
  36. _CONFIG_VARS['LDSHARED'] = (
  37. "gcc -Wl,-x -dynamiclib -undefined dynamic_lookup")
  38. _CONFIG_VARS['CCSHARED'] = " -dynamiclib"
  39. _CONFIG_VARS['SO'] = ".dylib"
  40. customize_compiler(compiler)
  41. finally:
  42. _CONFIG_VARS.clear()
  43. _CONFIG_VARS.update(tmp)
  44. else:
  45. customize_compiler(compiler)
  46. have_rtld = False
  47. use_stubs = False
  48. libtype = 'shared'
  49. if sys.platform == "darwin":
  50. use_stubs = True
  51. elif os.name != 'nt':
  52. try:
  53. import dl
  54. use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
  55. except ImportError:
  56. pass
  57. if_dl = lambda s: s if have_rtld else ''
  58. def get_abi3_suffix():
  59. """Return the file extension for an abi3-compliant Extension()"""
  60. for suffix in EXTENSION_SUFFIXES:
  61. if '.abi3' in suffix: # Unix
  62. return suffix
  63. elif suffix == '.pyd': # Windows
  64. return suffix
  65. class build_ext(_build_ext):
  66. def run(self):
  67. """Build extensions in build directory, then copy if --inplace"""
  68. old_inplace, self.inplace = self.inplace, 0
  69. _build_ext.run(self)
  70. self.inplace = old_inplace
  71. if old_inplace:
  72. self.copy_extensions_to_source()
  73. def copy_extensions_to_source(self):
  74. build_py = self.get_finalized_command('build_py')
  75. for ext in self.extensions:
  76. fullname = self.get_ext_fullname(ext.name)
  77. filename = self.get_ext_filename(fullname)
  78. modpath = fullname.split('.')
  79. package = '.'.join(modpath[:-1])
  80. package_dir = build_py.get_package_dir(package)
  81. dest_filename = os.path.join(package_dir,
  82. os.path.basename(filename))
  83. src_filename = os.path.join(self.build_lib, filename)
  84. # Always copy, even if source is older than destination, to ensure
  85. # that the right extensions for the current Python/platform are
  86. # used.
  87. copy_file(
  88. src_filename, dest_filename, verbose=self.verbose,
  89. dry_run=self.dry_run
  90. )
  91. if ext._needs_stub:
  92. self.write_stub(package_dir or os.curdir, ext, True)
  93. def get_ext_filename(self, fullname):
  94. filename = _build_ext.get_ext_filename(self, fullname)
  95. if fullname in self.ext_map:
  96. ext = self.ext_map[fullname]
  97. use_abi3 = (
  98. not six.PY2
  99. and getattr(ext, 'py_limited_api')
  100. and get_abi3_suffix()
  101. )
  102. if use_abi3:
  103. so_ext = get_config_var('EXT_SUFFIX')
  104. filename = filename[:-len(so_ext)]
  105. filename = filename + get_abi3_suffix()
  106. if isinstance(ext, Library):
  107. fn, ext = os.path.splitext(filename)
  108. return self.shlib_compiler.library_filename(fn, libtype)
  109. elif use_stubs and ext._links_to_dynamic:
  110. d, fn = os.path.split(filename)
  111. return os.path.join(d, 'dl-' + fn)
  112. return filename
  113. def initialize_options(self):
  114. _build_ext.initialize_options(self)
  115. self.shlib_compiler = None
  116. self.shlibs = []
  117. self.ext_map = {}
  118. def finalize_options(self):
  119. _build_ext.finalize_options(self)
  120. self.extensions = self.extensions or []
  121. self.check_extensions_list(self.extensions)
  122. self.shlibs = [ext for ext in self.extensions
  123. if isinstance(ext, Library)]
  124. if self.shlibs:
  125. self.setup_shlib_compiler()
  126. for ext in self.extensions:
  127. ext._full_name = self.get_ext_fullname(ext.name)
  128. for ext in self.extensions:
  129. fullname = ext._full_name
  130. self.ext_map[fullname] = ext
  131. # distutils 3.1 will also ask for module names
  132. # XXX what to do with conflicts?
  133. self.ext_map[fullname.split('.')[-1]] = ext
  134. ltd = self.shlibs and self.links_to_dynamic(ext) or False
  135. ns = ltd and use_stubs and not isinstance(ext, Library)
  136. ext._links_to_dynamic = ltd
  137. ext._needs_stub = ns
  138. filename = ext._file_name = self.get_ext_filename(fullname)
  139. libdir = os.path.dirname(os.path.join(self.build_lib, filename))
  140. if ltd and libdir not in ext.library_dirs:
  141. ext.library_dirs.append(libdir)
  142. if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
  143. ext.runtime_library_dirs.append(os.curdir)
  144. def setup_shlib_compiler(self):
  145. compiler = self.shlib_compiler = new_compiler(
  146. compiler=self.compiler, dry_run=self.dry_run, force=self.force
  147. )
  148. _customize_compiler_for_shlib(compiler)
  149. if self.include_dirs is not None:
  150. compiler.set_include_dirs(self.include_dirs)
  151. if self.define is not None:
  152. # 'define' option is a list of (name,value) tuples
  153. for (name, value) in self.define:
  154. compiler.define_macro(name, value)
  155. if self.undef is not None:
  156. for macro in self.undef:
  157. compiler.undefine_macro(macro)
  158. if self.libraries is not None:
  159. compiler.set_libraries(self.libraries)
  160. if self.library_dirs is not None:
  161. compiler.set_library_dirs(self.library_dirs)
  162. if self.rpath is not None:
  163. compiler.set_runtime_library_dirs(self.rpath)
  164. if self.link_objects is not None:
  165. compiler.set_link_objects(self.link_objects)
  166. # hack so distutils' build_extension() builds a library instead
  167. compiler.link_shared_object = link_shared_object.__get__(compiler)
  168. def get_export_symbols(self, ext):
  169. if isinstance(ext, Library):
  170. return ext.export_symbols
  171. return _build_ext.get_export_symbols(self, ext)
  172. def build_extension(self, ext):
  173. ext._convert_pyx_sources_to_lang()
  174. _compiler = self.compiler
  175. try:
  176. if isinstance(ext, Library):
  177. self.compiler = self.shlib_compiler
  178. _build_ext.build_extension(self, ext)
  179. if ext._needs_stub:
  180. cmd = self.get_finalized_command('build_py').build_lib
  181. self.write_stub(cmd, ext)
  182. finally:
  183. self.compiler = _compiler
  184. def links_to_dynamic(self, ext):
  185. """Return true if 'ext' links to a dynamic lib in the same package"""
  186. # XXX this should check to ensure the lib is actually being built
  187. # XXX as dynamic, and not just using a locally-found version or a
  188. # XXX static-compiled version
  189. libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
  190. pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
  191. return any(pkg + libname in libnames for libname in ext.libraries)
  192. def get_outputs(self):
  193. return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
  194. def __get_stubs_outputs(self):
  195. # assemble the base name for each extension that needs a stub
  196. ns_ext_bases = (
  197. os.path.join(self.build_lib, *ext._full_name.split('.'))
  198. for ext in self.extensions
  199. if ext._needs_stub
  200. )
  201. # pair each base with the extension
  202. pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
  203. return list(base + fnext for base, fnext in pairs)
  204. def __get_output_extensions(self):
  205. yield '.py'
  206. yield '.pyc'
  207. if self.get_finalized_command('build_py').optimize:
  208. yield '.pyo'
  209. def write_stub(self, output_dir, ext, compile=False):
  210. log.info("writing stub loader for %s to %s", ext._full_name,
  211. output_dir)
  212. stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
  213. '.py')
  214. if compile and os.path.exists(stub_file):
  215. raise DistutilsError(stub_file + " already exists! Please delete.")
  216. if not self.dry_run:
  217. f = open(stub_file, 'w')
  218. f.write(
  219. '\n'.join([
  220. "def __bootstrap__():",
  221. " global __bootstrap__, __file__, __loader__",
  222. " import sys, os, pkg_resources, imp" + if_dl(", dl"),
  223. " __file__ = pkg_resources.resource_filename"
  224. "(__name__,%r)"
  225. % os.path.basename(ext._file_name),
  226. " del __bootstrap__",
  227. " if '__loader__' in globals():",
  228. " del __loader__",
  229. if_dl(" old_flags = sys.getdlopenflags()"),
  230. " old_dir = os.getcwd()",
  231. " try:",
  232. " os.chdir(os.path.dirname(__file__))",
  233. if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
  234. " imp.load_dynamic(__name__,__file__)",
  235. " finally:",
  236. if_dl(" sys.setdlopenflags(old_flags)"),
  237. " os.chdir(old_dir)",
  238. "__bootstrap__()",
  239. "" # terminal \n
  240. ])
  241. )
  242. f.close()
  243. if compile:
  244. from distutils.util import byte_compile
  245. byte_compile([stub_file], optimize=0,
  246. force=True, dry_run=self.dry_run)
  247. optimize = self.get_finalized_command('install_lib').optimize
  248. if optimize > 0:
  249. byte_compile([stub_file], optimize=optimize,
  250. force=True, dry_run=self.dry_run)
  251. if os.path.exists(stub_file) and not self.dry_run:
  252. os.unlink(stub_file)
  253. if use_stubs or os.name == 'nt':
  254. # Build shared libraries
  255. #
  256. def link_shared_object(
  257. self, objects, output_libname, output_dir=None, libraries=None,
  258. library_dirs=None, runtime_library_dirs=None, export_symbols=None,
  259. debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
  260. target_lang=None):
  261. self.link(
  262. self.SHARED_LIBRARY, objects, output_libname,
  263. output_dir, libraries, library_dirs, runtime_library_dirs,
  264. export_symbols, debug, extra_preargs, extra_postargs,
  265. build_temp, target_lang
  266. )
  267. else:
  268. # Build static libraries everywhere else
  269. libtype = 'static'
  270. def link_shared_object(
  271. self, objects, output_libname, output_dir=None, libraries=None,
  272. library_dirs=None, runtime_library_dirs=None, export_symbols=None,
  273. debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
  274. target_lang=None):
  275. # XXX we need to either disallow these attrs on Library instances,
  276. # or warn/abort here if set, or something...
  277. # libraries=None, library_dirs=None, runtime_library_dirs=None,
  278. # export_symbols=None, extra_preargs=None, extra_postargs=None,
  279. # build_temp=None
  280. assert output_dir is None # distutils build_ext doesn't pass this
  281. output_dir, filename = os.path.split(output_libname)
  282. basename, ext = os.path.splitext(filename)
  283. if self.library_filename("x").startswith('lib'):
  284. # strip 'lib' prefix; this is kludgy if some platform uses
  285. # a different prefix
  286. basename = basename[3:]
  287. self.create_static_lib(
  288. objects, basename, output_dir, debug, target_lang
  289. )