build_ext.py 12 KB

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