build_ext.py 12 KB

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