build_ext.py 13 KB

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