build_ext.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. """distutils.command.build_ext
  2. Implements the Distutils 'build_ext' command, for building extension
  3. modules (currently limited to C extensions, should accommodate C++
  4. extensions ASAP)."""
  5. import contextlib
  6. import os
  7. import re
  8. import sys
  9. from distutils.core import Command
  10. from distutils.errors import (
  11. DistutilsOptionError,
  12. DistutilsSetupError,
  13. CCompilerError,
  14. DistutilsError,
  15. CompileError,
  16. DistutilsPlatformError,
  17. )
  18. from distutils.sysconfig import customize_compiler, get_python_version
  19. from distutils.sysconfig import get_config_h_filename
  20. from distutils.dep_util import newer_group
  21. from distutils.extension import Extension
  22. from distutils.util import get_platform
  23. from distutils import log
  24. from . import py37compat
  25. from site import USER_BASE
  26. # An extension name is just a dot-separated list of Python NAMEs (ie.
  27. # the same as a fully-qualified module name).
  28. extension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
  29. def show_compilers():
  30. from distutils.ccompiler import show_compilers
  31. show_compilers()
  32. class build_ext(Command):
  33. description = "build C/C++ extensions (compile/link to build directory)"
  34. # XXX thoughts on how to deal with complex command-line options like
  35. # these, i.e. how to make it so fancy_getopt can suck them off the
  36. # command line and make it look like setup.py defined the appropriate
  37. # lists of tuples of what-have-you.
  38. # - each command needs a callback to process its command-line options
  39. # - Command.__init__() needs access to its share of the whole
  40. # command line (must ultimately come from
  41. # Distribution.parse_command_line())
  42. # - it then calls the current command class' option-parsing
  43. # callback to deal with weird options like -D, which have to
  44. # parse the option text and churn out some custom data
  45. # structure
  46. # - that data structure (in this case, a list of 2-tuples)
  47. # will then be present in the command object by the time
  48. # we get to finalize_options() (i.e. the constructor
  49. # takes care of both command-line and client options
  50. # in between initialize_options() and finalize_options())
  51. sep_by = " (separated by '%s')" % os.pathsep
  52. user_options = [
  53. ('build-lib=', 'b', "directory for compiled extension modules"),
  54. ('build-temp=', 't', "directory for temporary files (build by-products)"),
  55. (
  56. 'plat-name=',
  57. 'p',
  58. "platform name to cross-compile for, if supported "
  59. "(default: %s)" % get_platform(),
  60. ),
  61. (
  62. 'inplace',
  63. 'i',
  64. "ignore build-lib and put compiled extensions into the source "
  65. + "directory alongside your pure Python modules",
  66. ),
  67. (
  68. 'include-dirs=',
  69. 'I',
  70. "list of directories to search for header files" + sep_by,
  71. ),
  72. ('define=', 'D', "C preprocessor macros to define"),
  73. ('undef=', 'U', "C preprocessor macros to undefine"),
  74. ('libraries=', 'l', "external C libraries to link with"),
  75. (
  76. 'library-dirs=',
  77. 'L',
  78. "directories to search for external C libraries" + sep_by,
  79. ),
  80. ('rpath=', 'R', "directories to search for shared C libraries at runtime"),
  81. ('link-objects=', 'O', "extra explicit link objects to include in the link"),
  82. ('debug', 'g', "compile/link with debugging information"),
  83. ('force', 'f', "forcibly build everything (ignore file timestamps)"),
  84. ('compiler=', 'c', "specify the compiler type"),
  85. ('parallel=', 'j', "number of parallel build jobs"),
  86. ('swig-cpp', None, "make SWIG create C++ files (default is C)"),
  87. ('swig-opts=', None, "list of SWIG command line options"),
  88. ('swig=', None, "path to the SWIG executable"),
  89. ('user', None, "add user include, library and rpath"),
  90. ]
  91. boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
  92. help_options = [
  93. ('help-compiler', None, "list available compilers", show_compilers),
  94. ]
  95. def initialize_options(self):
  96. self.extensions = None
  97. self.build_lib = None
  98. self.plat_name = None
  99. self.build_temp = None
  100. self.inplace = 0
  101. self.package = None
  102. self.include_dirs = None
  103. self.define = None
  104. self.undef = None
  105. self.libraries = None
  106. self.library_dirs = None
  107. self.rpath = None
  108. self.link_objects = None
  109. self.debug = None
  110. self.force = None
  111. self.compiler = None
  112. self.swig = None
  113. self.swig_cpp = None
  114. self.swig_opts = None
  115. self.user = None
  116. self.parallel = None
  117. def finalize_options(self): # noqa: C901
  118. from distutils import sysconfig
  119. self.set_undefined_options(
  120. 'build',
  121. ('build_lib', 'build_lib'),
  122. ('build_temp', 'build_temp'),
  123. ('compiler', 'compiler'),
  124. ('debug', 'debug'),
  125. ('force', 'force'),
  126. ('parallel', 'parallel'),
  127. ('plat_name', 'plat_name'),
  128. )
  129. if self.package is None:
  130. self.package = self.distribution.ext_package
  131. self.extensions = self.distribution.ext_modules
  132. # Make sure Python's include directories (for Python.h, pyconfig.h,
  133. # etc.) are in the include search path.
  134. py_include = sysconfig.get_python_inc()
  135. plat_py_include = sysconfig.get_python_inc(plat_specific=1)
  136. if self.include_dirs is None:
  137. self.include_dirs = self.distribution.include_dirs or []
  138. if isinstance(self.include_dirs, str):
  139. self.include_dirs = self.include_dirs.split(os.pathsep)
  140. # If in a virtualenv, add its include directory
  141. # Issue 16116
  142. if sys.exec_prefix != sys.base_exec_prefix:
  143. self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))
  144. # Put the Python "system" include dir at the end, so that
  145. # any local include dirs take precedence.
  146. self.include_dirs.extend(py_include.split(os.path.pathsep))
  147. if plat_py_include != py_include:
  148. self.include_dirs.extend(plat_py_include.split(os.path.pathsep))
  149. self.ensure_string_list('libraries')
  150. self.ensure_string_list('link_objects')
  151. # Life is easier if we're not forever checking for None, so
  152. # simplify these options to empty lists if unset
  153. if self.libraries is None:
  154. self.libraries = []
  155. if self.library_dirs is None:
  156. self.library_dirs = []
  157. elif isinstance(self.library_dirs, str):
  158. self.library_dirs = self.library_dirs.split(os.pathsep)
  159. if self.rpath is None:
  160. self.rpath = []
  161. elif isinstance(self.rpath, str):
  162. self.rpath = self.rpath.split(os.pathsep)
  163. # for extensions under windows use different directories
  164. # for Release and Debug builds.
  165. # also Python's library directory must be appended to library_dirs
  166. if os.name == 'nt':
  167. # the 'libs' directory is for binary installs - we assume that
  168. # must be the *native* platform. But we don't really support
  169. # cross-compiling via a binary install anyway, so we let it go.
  170. self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
  171. if sys.base_exec_prefix != sys.prefix: # Issue 16116
  172. self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))
  173. if self.debug:
  174. self.build_temp = os.path.join(self.build_temp, "Debug")
  175. else:
  176. self.build_temp = os.path.join(self.build_temp, "Release")
  177. # Append the source distribution include and library directories,
  178. # this allows distutils on windows to work in the source tree
  179. self.include_dirs.append(os.path.dirname(get_config_h_filename()))
  180. self.library_dirs.append(sys.base_exec_prefix)
  181. # Use the .lib files for the correct architecture
  182. if self.plat_name == 'win32':
  183. suffix = 'win32'
  184. else:
  185. # win-amd64
  186. suffix = self.plat_name[4:]
  187. new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
  188. if suffix:
  189. new_lib = os.path.join(new_lib, suffix)
  190. self.library_dirs.append(new_lib)
  191. # For extensions under Cygwin, Python's library directory must be
  192. # appended to library_dirs
  193. if sys.platform[:6] == 'cygwin':
  194. if not sysconfig.python_build:
  195. # building third party extensions
  196. self.library_dirs.append(
  197. os.path.join(
  198. sys.prefix, "lib", "python" + get_python_version(), "config"
  199. )
  200. )
  201. else:
  202. # building python standard extensions
  203. self.library_dirs.append('.')
  204. # For building extensions with a shared Python library,
  205. # Python's library directory must be appended to library_dirs
  206. # See Issues: #1600860, #4366
  207. if sysconfig.get_config_var('Py_ENABLE_SHARED'):
  208. if not sysconfig.python_build:
  209. # building third party extensions
  210. self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
  211. else:
  212. # building python standard extensions
  213. self.library_dirs.append('.')
  214. # The argument parsing will result in self.define being a string, but
  215. # it has to be a list of 2-tuples. All the preprocessor symbols
  216. # specified by the 'define' option will be set to '1'. Multiple
  217. # symbols can be separated with commas.
  218. if self.define:
  219. defines = self.define.split(',')
  220. self.define = [(symbol, '1') for symbol in defines]
  221. # The option for macros to undefine is also a string from the
  222. # option parsing, but has to be a list. Multiple symbols can also
  223. # be separated with commas here.
  224. if self.undef:
  225. self.undef = self.undef.split(',')
  226. if self.swig_opts is None:
  227. self.swig_opts = []
  228. else:
  229. self.swig_opts = self.swig_opts.split(' ')
  230. # Finally add the user include and library directories if requested
  231. if self.user:
  232. user_include = os.path.join(USER_BASE, "include")
  233. user_lib = os.path.join(USER_BASE, "lib")
  234. if os.path.isdir(user_include):
  235. self.include_dirs.append(user_include)
  236. if os.path.isdir(user_lib):
  237. self.library_dirs.append(user_lib)
  238. self.rpath.append(user_lib)
  239. if isinstance(self.parallel, str):
  240. try:
  241. self.parallel = int(self.parallel)
  242. except ValueError:
  243. raise DistutilsOptionError("parallel should be an integer")
  244. def run(self): # noqa: C901
  245. from distutils.ccompiler import new_compiler
  246. # 'self.extensions', as supplied by setup.py, is a list of
  247. # Extension instances. See the documentation for Extension (in
  248. # distutils.extension) for details.
  249. #
  250. # For backwards compatibility with Distutils 0.8.2 and earlier, we
  251. # also allow the 'extensions' list to be a list of tuples:
  252. # (ext_name, build_info)
  253. # where build_info is a dictionary containing everything that
  254. # Extension instances do except the name, with a few things being
  255. # differently named. We convert these 2-tuples to Extension
  256. # instances as needed.
  257. if not self.extensions:
  258. return
  259. # If we were asked to build any C/C++ libraries, make sure that the
  260. # directory where we put them is in the library search path for
  261. # linking extensions.
  262. if self.distribution.has_c_libraries():
  263. build_clib = self.get_finalized_command('build_clib')
  264. self.libraries.extend(build_clib.get_library_names() or [])
  265. self.library_dirs.append(build_clib.build_clib)
  266. # Setup the CCompiler object that we'll use to do all the
  267. # compiling and linking
  268. self.compiler = new_compiler(
  269. compiler=self.compiler,
  270. verbose=self.verbose,
  271. dry_run=self.dry_run,
  272. force=self.force,
  273. )
  274. customize_compiler(self.compiler)
  275. # If we are cross-compiling, init the compiler now (if we are not
  276. # cross-compiling, init would not hurt, but people may rely on
  277. # late initialization of compiler even if they shouldn't...)
  278. if os.name == 'nt' and self.plat_name != get_platform():
  279. self.compiler.initialize(self.plat_name)
  280. # And make sure that any compile/link-related options (which might
  281. # come from the command-line or from the setup script) are set in
  282. # that CCompiler object -- that way, they automatically apply to
  283. # all compiling and linking done here.
  284. if self.include_dirs is not None:
  285. self.compiler.set_include_dirs(self.include_dirs)
  286. if self.define is not None:
  287. # 'define' option is a list of (name,value) tuples
  288. for (name, value) in self.define:
  289. self.compiler.define_macro(name, value)
  290. if self.undef is not None:
  291. for macro in self.undef:
  292. self.compiler.undefine_macro(macro)
  293. if self.libraries is not None:
  294. self.compiler.set_libraries(self.libraries)
  295. if self.library_dirs is not None:
  296. self.compiler.set_library_dirs(self.library_dirs)
  297. if self.rpath is not None:
  298. self.compiler.set_runtime_library_dirs(self.rpath)
  299. if self.link_objects is not None:
  300. self.compiler.set_link_objects(self.link_objects)
  301. # Now actually compile and link everything.
  302. self.build_extensions()
  303. def check_extensions_list(self, extensions): # noqa: C901
  304. """Ensure that the list of extensions (presumably provided as a
  305. command option 'extensions') is valid, i.e. it is a list of
  306. Extension objects. We also support the old-style list of 2-tuples,
  307. where the tuples are (ext_name, build_info), which are converted to
  308. Extension instances here.
  309. Raise DistutilsSetupError if the structure is invalid anywhere;
  310. just returns otherwise.
  311. """
  312. if not isinstance(extensions, list):
  313. raise DistutilsSetupError(
  314. "'ext_modules' option must be a list of Extension instances"
  315. )
  316. for i, ext in enumerate(extensions):
  317. if isinstance(ext, Extension):
  318. continue # OK! (assume type-checking done
  319. # by Extension constructor)
  320. if not isinstance(ext, tuple) or len(ext) != 2:
  321. raise DistutilsSetupError(
  322. "each element of 'ext_modules' option must be an "
  323. "Extension instance or 2-tuple"
  324. )
  325. ext_name, build_info = ext
  326. log.warn(
  327. "old-style (ext_name, build_info) tuple found in "
  328. "ext_modules for extension '%s' "
  329. "-- please convert to Extension instance",
  330. ext_name,
  331. )
  332. if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)):
  333. raise DistutilsSetupError(
  334. "first element of each tuple in 'ext_modules' "
  335. "must be the extension name (a string)"
  336. )
  337. if not isinstance(build_info, dict):
  338. raise DistutilsSetupError(
  339. "second element of each tuple in 'ext_modules' "
  340. "must be a dictionary (build info)"
  341. )
  342. # OK, the (ext_name, build_info) dict is type-safe: convert it
  343. # to an Extension instance.
  344. ext = Extension(ext_name, build_info['sources'])
  345. # Easy stuff: one-to-one mapping from dict elements to
  346. # instance attributes.
  347. for key in (
  348. 'include_dirs',
  349. 'library_dirs',
  350. 'libraries',
  351. 'extra_objects',
  352. 'extra_compile_args',
  353. 'extra_link_args',
  354. ):
  355. val = build_info.get(key)
  356. if val is not None:
  357. setattr(ext, key, val)
  358. # Medium-easy stuff: same syntax/semantics, different names.
  359. ext.runtime_library_dirs = build_info.get('rpath')
  360. if 'def_file' in build_info:
  361. log.warn("'def_file' element of build info dict " "no longer supported")
  362. # Non-trivial stuff: 'macros' split into 'define_macros'
  363. # and 'undef_macros'.
  364. macros = build_info.get('macros')
  365. if macros:
  366. ext.define_macros = []
  367. ext.undef_macros = []
  368. for macro in macros:
  369. if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
  370. raise DistutilsSetupError(
  371. "'macros' element of build info dict "
  372. "must be 1- or 2-tuple"
  373. )
  374. if len(macro) == 1:
  375. ext.undef_macros.append(macro[0])
  376. elif len(macro) == 2:
  377. ext.define_macros.append(macro)
  378. extensions[i] = ext
  379. def get_source_files(self):
  380. self.check_extensions_list(self.extensions)
  381. filenames = []
  382. # Wouldn't it be neat if we knew the names of header files too...
  383. for ext in self.extensions:
  384. filenames.extend(ext.sources)
  385. return filenames
  386. def get_outputs(self):
  387. # Sanity check the 'extensions' list -- can't assume this is being
  388. # done in the same run as a 'build_extensions()' call (in fact, we
  389. # can probably assume that it *isn't*!).
  390. self.check_extensions_list(self.extensions)
  391. # And build the list of output (built) filenames. Note that this
  392. # ignores the 'inplace' flag, and assumes everything goes in the
  393. # "build" tree.
  394. outputs = []
  395. for ext in self.extensions:
  396. outputs.append(self.get_ext_fullpath(ext.name))
  397. return outputs
  398. def build_extensions(self):
  399. # First, sanity-check the 'extensions' list
  400. self.check_extensions_list(self.extensions)
  401. if self.parallel:
  402. self._build_extensions_parallel()
  403. else:
  404. self._build_extensions_serial()
  405. def _build_extensions_parallel(self):
  406. workers = self.parallel
  407. if self.parallel is True:
  408. workers = os.cpu_count() # may return None
  409. try:
  410. from concurrent.futures import ThreadPoolExecutor
  411. except ImportError:
  412. workers = None
  413. if workers is None:
  414. self._build_extensions_serial()
  415. return
  416. with ThreadPoolExecutor(max_workers=workers) as executor:
  417. futures = [
  418. executor.submit(self.build_extension, ext) for ext in self.extensions
  419. ]
  420. for ext, fut in zip(self.extensions, futures):
  421. with self._filter_build_errors(ext):
  422. fut.result()
  423. def _build_extensions_serial(self):
  424. for ext in self.extensions:
  425. with self._filter_build_errors(ext):
  426. self.build_extension(ext)
  427. @contextlib.contextmanager
  428. def _filter_build_errors(self, ext):
  429. try:
  430. yield
  431. except (CCompilerError, DistutilsError, CompileError) as e:
  432. if not ext.optional:
  433. raise
  434. self.warn('building extension "{}" failed: {}'.format(ext.name, e))
  435. def build_extension(self, ext):
  436. sources = ext.sources
  437. if sources is None or not isinstance(sources, (list, tuple)):
  438. raise DistutilsSetupError(
  439. "in 'ext_modules' option (extension '%s'), "
  440. "'sources' must be present and must be "
  441. "a list of source filenames" % ext.name
  442. )
  443. # sort to make the resulting .so file build reproducible
  444. sources = sorted(sources)
  445. ext_path = self.get_ext_fullpath(ext.name)
  446. depends = sources + ext.depends
  447. if not (self.force or newer_group(depends, ext_path, 'newer')):
  448. log.debug("skipping '%s' extension (up-to-date)", ext.name)
  449. return
  450. else:
  451. log.info("building '%s' extension", ext.name)
  452. # First, scan the sources for SWIG definition files (.i), run
  453. # SWIG on 'em to create .c files, and modify the sources list
  454. # accordingly.
  455. sources = self.swig_sources(sources, ext)
  456. # Next, compile the source code to object files.
  457. # XXX not honouring 'define_macros' or 'undef_macros' -- the
  458. # CCompiler API needs to change to accommodate this, and I
  459. # want to do one thing at a time!
  460. # Two possible sources for extra compiler arguments:
  461. # - 'extra_compile_args' in Extension object
  462. # - CFLAGS environment variable (not particularly
  463. # elegant, but people seem to expect it and I
  464. # guess it's useful)
  465. # The environment variable should take precedence, and
  466. # any sensible compiler will give precedence to later
  467. # command line args. Hence we combine them in order:
  468. extra_args = ext.extra_compile_args or []
  469. macros = ext.define_macros[:]
  470. for undef in ext.undef_macros:
  471. macros.append((undef,))
  472. objects = self.compiler.compile(
  473. sources,
  474. output_dir=self.build_temp,
  475. macros=macros,
  476. include_dirs=ext.include_dirs,
  477. debug=self.debug,
  478. extra_postargs=extra_args,
  479. depends=ext.depends,
  480. )
  481. # XXX outdated variable, kept here in case third-part code
  482. # needs it.
  483. self._built_objects = objects[:]
  484. # Now link the object files together into a "shared object" --
  485. # of course, first we have to figure out all the other things
  486. # that go into the mix.
  487. if ext.extra_objects:
  488. objects.extend(ext.extra_objects)
  489. extra_args = ext.extra_link_args or []
  490. # Detect target language, if not provided
  491. language = ext.language or self.compiler.detect_language(sources)
  492. self.compiler.link_shared_object(
  493. objects,
  494. ext_path,
  495. libraries=self.get_libraries(ext),
  496. library_dirs=ext.library_dirs,
  497. runtime_library_dirs=ext.runtime_library_dirs,
  498. extra_postargs=extra_args,
  499. export_symbols=self.get_export_symbols(ext),
  500. debug=self.debug,
  501. build_temp=self.build_temp,
  502. target_lang=language,
  503. )
  504. def swig_sources(self, sources, extension):
  505. """Walk the list of source files in 'sources', looking for SWIG
  506. interface (.i) files. Run SWIG on all that are found, and
  507. return a modified 'sources' list with SWIG source files replaced
  508. by the generated C (or C++) files.
  509. """
  510. new_sources = []
  511. swig_sources = []
  512. swig_targets = {}
  513. # XXX this drops generated C/C++ files into the source tree, which
  514. # is fine for developers who want to distribute the generated
  515. # source -- but there should be an option to put SWIG output in
  516. # the temp dir.
  517. if self.swig_cpp:
  518. log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
  519. if (
  520. self.swig_cpp
  521. or ('-c++' in self.swig_opts)
  522. or ('-c++' in extension.swig_opts)
  523. ):
  524. target_ext = '.cpp'
  525. else:
  526. target_ext = '.c'
  527. for source in sources:
  528. (base, ext) = os.path.splitext(source)
  529. if ext == ".i": # SWIG interface file
  530. new_sources.append(base + '_wrap' + target_ext)
  531. swig_sources.append(source)
  532. swig_targets[source] = new_sources[-1]
  533. else:
  534. new_sources.append(source)
  535. if not swig_sources:
  536. return new_sources
  537. swig = self.swig or self.find_swig()
  538. swig_cmd = [swig, "-python"]
  539. swig_cmd.extend(self.swig_opts)
  540. if self.swig_cpp:
  541. swig_cmd.append("-c++")
  542. # Do not override commandline arguments
  543. if not self.swig_opts:
  544. for o in extension.swig_opts:
  545. swig_cmd.append(o)
  546. for source in swig_sources:
  547. target = swig_targets[source]
  548. log.info("swigging %s to %s", source, target)
  549. self.spawn(swig_cmd + ["-o", target, source])
  550. return new_sources
  551. def find_swig(self):
  552. """Return the name of the SWIG executable. On Unix, this is
  553. just "swig" -- it should be in the PATH. Tries a bit harder on
  554. Windows.
  555. """
  556. if os.name == "posix":
  557. return "swig"
  558. elif os.name == "nt":
  559. # Look for SWIG in its standard installation directory on
  560. # Windows (or so I presume!). If we find it there, great;
  561. # if not, act like Unix and assume it's in the PATH.
  562. for vers in ("1.3", "1.2", "1.1"):
  563. fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  564. if os.path.isfile(fn):
  565. return fn
  566. else:
  567. return "swig.exe"
  568. else:
  569. raise DistutilsPlatformError(
  570. "I don't know how to find (much less run) SWIG "
  571. "on platform '%s'" % os.name
  572. )
  573. # -- Name generators -----------------------------------------------
  574. # (extension names, filenames, whatever)
  575. def get_ext_fullpath(self, ext_name):
  576. """Returns the path of the filename for a given extension.
  577. The file is located in `build_lib` or directly in the package
  578. (inplace option).
  579. """
  580. fullname = self.get_ext_fullname(ext_name)
  581. modpath = fullname.split('.')
  582. filename = self.get_ext_filename(modpath[-1])
  583. if not self.inplace:
  584. # no further work needed
  585. # returning :
  586. # build_dir/package/path/filename
  587. filename = os.path.join(*modpath[:-1] + [filename])
  588. return os.path.join(self.build_lib, filename)
  589. # the inplace option requires to find the package directory
  590. # using the build_py command for that
  591. package = '.'.join(modpath[0:-1])
  592. build_py = self.get_finalized_command('build_py')
  593. package_dir = os.path.abspath(build_py.get_package_dir(package))
  594. # returning
  595. # package_dir/filename
  596. return os.path.join(package_dir, filename)
  597. def get_ext_fullname(self, ext_name):
  598. """Returns the fullname of a given extension name.
  599. Adds the `package.` prefix"""
  600. if self.package is None:
  601. return ext_name
  602. else:
  603. return self.package + '.' + ext_name
  604. def get_ext_filename(self, ext_name):
  605. r"""Convert the name of an extension (eg. "foo.bar") into the name
  606. of the file from which it will be loaded (eg. "foo/bar.so", or
  607. "foo\bar.pyd").
  608. """
  609. from distutils.sysconfig import get_config_var
  610. ext_path = ext_name.split('.')
  611. ext_suffix = get_config_var('EXT_SUFFIX')
  612. return os.path.join(*ext_path) + ext_suffix
  613. def get_export_symbols(self, ext):
  614. """Return the list of symbols that a shared extension has to
  615. export. This either uses 'ext.export_symbols' or, if it's not
  616. provided, "PyInit_" + module_name. Only relevant on Windows, where
  617. the .pyd file (DLL) must export the module "PyInit_" function.
  618. """
  619. name = ext.name.split('.')[-1]
  620. try:
  621. # Unicode module name support as defined in PEP-489
  622. # https://www.python.org/dev/peps/pep-0489/#export-hook-name
  623. name.encode('ascii')
  624. except UnicodeEncodeError:
  625. suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')
  626. else:
  627. suffix = "_" + name
  628. initfunc_name = "PyInit" + suffix
  629. if initfunc_name not in ext.export_symbols:
  630. ext.export_symbols.append(initfunc_name)
  631. return ext.export_symbols
  632. def get_libraries(self, ext): # noqa: C901
  633. """Return the list of libraries to link against when building a
  634. shared extension. On most platforms, this is just 'ext.libraries';
  635. on Windows, we add the Python library (eg. python20.dll).
  636. """
  637. # The python library is always needed on Windows. For MSVC, this
  638. # is redundant, since the library is mentioned in a pragma in
  639. # pyconfig.h that MSVC groks. The other Windows compilers all seem
  640. # to need it mentioned explicitly, though, so that's what we do.
  641. # Append '_d' to the python import library on debug builds.
  642. if sys.platform == "win32":
  643. from distutils._msvccompiler import MSVCCompiler
  644. if not isinstance(self.compiler, MSVCCompiler):
  645. template = "python%d%d"
  646. if self.debug:
  647. template = template + '_d'
  648. pythonlib = template % (
  649. sys.hexversion >> 24,
  650. (sys.hexversion >> 16) & 0xFF,
  651. )
  652. # don't extend ext.libraries, it may be shared with other
  653. # extensions, it is a reference to the original list
  654. return ext.libraries + [pythonlib]
  655. else:
  656. # On Android only the main executable and LD_PRELOADs are considered
  657. # to be RTLD_GLOBAL, all the dependencies of the main executable
  658. # remain RTLD_LOCAL and so the shared libraries must be linked with
  659. # libpython when python is built with a shared python library (issue
  660. # bpo-21536).
  661. # On Cygwin (and if required, other POSIX-like platforms based on
  662. # Windows like MinGW) it is simply necessary that all symbols in
  663. # shared libraries are resolved at link time.
  664. from distutils.sysconfig import get_config_var
  665. link_libpython = False
  666. if get_config_var('Py_ENABLE_SHARED'):
  667. # A native build on an Android device or on Cygwin
  668. if hasattr(sys, 'getandroidapilevel'):
  669. link_libpython = True
  670. elif sys.platform == 'cygwin':
  671. link_libpython = True
  672. elif '_PYTHON_HOST_PLATFORM' in os.environ:
  673. # We are cross-compiling for one of the relevant platforms
  674. if get_config_var('ANDROID_API_LEVEL') != 0:
  675. link_libpython = True
  676. elif get_config_var('MACHDEP') == 'cygwin':
  677. link_libpython = True
  678. if link_libpython:
  679. ldversion = get_config_var('LDVERSION')
  680. return ext.libraries + ['python' + ldversion]
  681. return ext.libraries + py37compat.pythonlib()