build_ext.py 15 KB

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