build_ext.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 ..core import Command
  10. from ..errors import (
  11. DistutilsOptionError,
  12. DistutilsSetupError,
  13. CCompilerError,
  14. DistutilsError,
  15. CompileError,
  16. DistutilsPlatformError,
  17. )
  18. from ..sysconfig import customize_compiler, get_python_version
  19. from ..sysconfig import get_config_h_filename
  20. from .._modified import newer_group
  21. from ..extension import Extension
  22. from ..util import get_platform
  23. from distutils._log 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 ..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 ..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.warning(
  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.warning(
  362. "'def_file' element of build info dict " "no longer supported"
  363. )
  364. # Non-trivial stuff: 'macros' split into 'define_macros'
  365. # and 'undef_macros'.
  366. macros = build_info.get('macros')
  367. if macros:
  368. ext.define_macros = []
  369. ext.undef_macros = []
  370. for macro in macros:
  371. if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
  372. raise DistutilsSetupError(
  373. "'macros' element of build info dict "
  374. "must be 1- or 2-tuple"
  375. )
  376. if len(macro) == 1:
  377. ext.undef_macros.append(macro[0])
  378. elif len(macro) == 2:
  379. ext.define_macros.append(macro)
  380. extensions[i] = ext
  381. def get_source_files(self):
  382. self.check_extensions_list(self.extensions)
  383. filenames = []
  384. # Wouldn't it be neat if we knew the names of header files too...
  385. for ext in self.extensions:
  386. filenames.extend(ext.sources)
  387. return filenames
  388. def get_outputs(self):
  389. # Sanity check the 'extensions' list -- can't assume this is being
  390. # done in the same run as a 'build_extensions()' call (in fact, we
  391. # can probably assume that it *isn't*!).
  392. self.check_extensions_list(self.extensions)
  393. # And build the list of output (built) filenames. Note that this
  394. # ignores the 'inplace' flag, and assumes everything goes in the
  395. # "build" tree.
  396. outputs = []
  397. for ext in self.extensions:
  398. outputs.append(self.get_ext_fullpath(ext.name))
  399. return outputs
  400. def build_extensions(self):
  401. # First, sanity-check the 'extensions' list
  402. self.check_extensions_list(self.extensions)
  403. if self.parallel:
  404. self._build_extensions_parallel()
  405. else:
  406. self._build_extensions_serial()
  407. def _build_extensions_parallel(self):
  408. workers = self.parallel
  409. if self.parallel is True:
  410. workers = os.cpu_count() # may return None
  411. try:
  412. from concurrent.futures import ThreadPoolExecutor
  413. except ImportError:
  414. workers = None
  415. if workers is None:
  416. self._build_extensions_serial()
  417. return
  418. with ThreadPoolExecutor(max_workers=workers) as executor:
  419. futures = [
  420. executor.submit(self.build_extension, ext) for ext in self.extensions
  421. ]
  422. for ext, fut in zip(self.extensions, futures):
  423. with self._filter_build_errors(ext):
  424. fut.result()
  425. def _build_extensions_serial(self):
  426. for ext in self.extensions:
  427. with self._filter_build_errors(ext):
  428. self.build_extension(ext)
  429. @contextlib.contextmanager
  430. def _filter_build_errors(self, ext):
  431. try:
  432. yield
  433. except (CCompilerError, DistutilsError, CompileError) as e:
  434. if not ext.optional:
  435. raise
  436. self.warn('building extension "{}" failed: {}'.format(ext.name, e))
  437. def build_extension(self, ext):
  438. sources = ext.sources
  439. if sources is None or not isinstance(sources, (list, tuple)):
  440. raise DistutilsSetupError(
  441. "in 'ext_modules' option (extension '%s'), "
  442. "'sources' must be present and must be "
  443. "a list of source filenames" % ext.name
  444. )
  445. # sort to make the resulting .so file build reproducible
  446. sources = sorted(sources)
  447. ext_path = self.get_ext_fullpath(ext.name)
  448. depends = sources + ext.depends
  449. if not (self.force or newer_group(depends, ext_path, 'newer')):
  450. log.debug("skipping '%s' extension (up-to-date)", ext.name)
  451. return
  452. else:
  453. log.info("building '%s' extension", ext.name)
  454. # First, scan the sources for SWIG definition files (.i), run
  455. # SWIG on 'em to create .c files, and modify the sources list
  456. # accordingly.
  457. sources = self.swig_sources(sources, ext)
  458. # Next, compile the source code to object files.
  459. # XXX not honouring 'define_macros' or 'undef_macros' -- the
  460. # CCompiler API needs to change to accommodate this, and I
  461. # want to do one thing at a time!
  462. # Two possible sources for extra compiler arguments:
  463. # - 'extra_compile_args' in Extension object
  464. # - CFLAGS environment variable (not particularly
  465. # elegant, but people seem to expect it and I
  466. # guess it's useful)
  467. # The environment variable should take precedence, and
  468. # any sensible compiler will give precedence to later
  469. # command line args. Hence we combine them in order:
  470. extra_args = ext.extra_compile_args or []
  471. macros = ext.define_macros[:]
  472. for undef in ext.undef_macros:
  473. macros.append((undef,))
  474. objects = self.compiler.compile(
  475. sources,
  476. output_dir=self.build_temp,
  477. macros=macros,
  478. include_dirs=ext.include_dirs,
  479. debug=self.debug,
  480. extra_postargs=extra_args,
  481. depends=ext.depends,
  482. )
  483. # XXX outdated variable, kept here in case third-part code
  484. # needs it.
  485. self._built_objects = objects[:]
  486. # Now link the object files together into a "shared object" --
  487. # of course, first we have to figure out all the other things
  488. # that go into the mix.
  489. if ext.extra_objects:
  490. objects.extend(ext.extra_objects)
  491. extra_args = ext.extra_link_args or []
  492. # Detect target language, if not provided
  493. language = ext.language or self.compiler.detect_language(sources)
  494. self.compiler.link_shared_object(
  495. objects,
  496. ext_path,
  497. libraries=self.get_libraries(ext),
  498. library_dirs=ext.library_dirs,
  499. runtime_library_dirs=ext.runtime_library_dirs,
  500. extra_postargs=extra_args,
  501. export_symbols=self.get_export_symbols(ext),
  502. debug=self.debug,
  503. build_temp=self.build_temp,
  504. target_lang=language,
  505. )
  506. def swig_sources(self, sources, extension):
  507. """Walk the list of source files in 'sources', looking for SWIG
  508. interface (.i) files. Run SWIG on all that are found, and
  509. return a modified 'sources' list with SWIG source files replaced
  510. by the generated C (or C++) files.
  511. """
  512. new_sources = []
  513. swig_sources = []
  514. swig_targets = {}
  515. # XXX this drops generated C/C++ files into the source tree, which
  516. # is fine for developers who want to distribute the generated
  517. # source -- but there should be an option to put SWIG output in
  518. # the temp dir.
  519. if self.swig_cpp:
  520. log.warning("--swig-cpp is deprecated - use --swig-opts=-c++")
  521. if (
  522. self.swig_cpp
  523. or ('-c++' in self.swig_opts)
  524. or ('-c++' in extension.swig_opts)
  525. ):
  526. target_ext = '.cpp'
  527. else:
  528. target_ext = '.c'
  529. for source in sources:
  530. (base, ext) = os.path.splitext(source)
  531. if ext == ".i": # SWIG interface file
  532. new_sources.append(base + '_wrap' + target_ext)
  533. swig_sources.append(source)
  534. swig_targets[source] = new_sources[-1]
  535. else:
  536. new_sources.append(source)
  537. if not swig_sources:
  538. return new_sources
  539. swig = self.swig or self.find_swig()
  540. swig_cmd = [swig, "-python"]
  541. swig_cmd.extend(self.swig_opts)
  542. if self.swig_cpp:
  543. swig_cmd.append("-c++")
  544. # Do not override commandline arguments
  545. if not self.swig_opts:
  546. for o in extension.swig_opts:
  547. swig_cmd.append(o)
  548. for source in swig_sources:
  549. target = swig_targets[source]
  550. log.info("swigging %s to %s", source, target)
  551. self.spawn(swig_cmd + ["-o", target, source])
  552. return new_sources
  553. def find_swig(self):
  554. """Return the name of the SWIG executable. On Unix, this is
  555. just "swig" -- it should be in the PATH. Tries a bit harder on
  556. Windows.
  557. """
  558. if os.name == "posix":
  559. return "swig"
  560. elif os.name == "nt":
  561. # Look for SWIG in its standard installation directory on
  562. # Windows (or so I presume!). If we find it there, great;
  563. # if not, act like Unix and assume it's in the PATH.
  564. for vers in ("1.3", "1.2", "1.1"):
  565. fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  566. if os.path.isfile(fn):
  567. return fn
  568. else:
  569. return "swig.exe"
  570. else:
  571. raise DistutilsPlatformError(
  572. "I don't know how to find (much less run) SWIG "
  573. "on platform '%s'" % os.name
  574. )
  575. # -- Name generators -----------------------------------------------
  576. # (extension names, filenames, whatever)
  577. def get_ext_fullpath(self, ext_name):
  578. """Returns the path of the filename for a given extension.
  579. The file is located in `build_lib` or directly in the package
  580. (inplace option).
  581. """
  582. fullname = self.get_ext_fullname(ext_name)
  583. modpath = fullname.split('.')
  584. filename = self.get_ext_filename(modpath[-1])
  585. if not self.inplace:
  586. # no further work needed
  587. # returning :
  588. # build_dir/package/path/filename
  589. filename = os.path.join(*modpath[:-1] + [filename])
  590. return os.path.join(self.build_lib, filename)
  591. # the inplace option requires to find the package directory
  592. # using the build_py command for that
  593. package = '.'.join(modpath[0:-1])
  594. build_py = self.get_finalized_command('build_py')
  595. package_dir = os.path.abspath(build_py.get_package_dir(package))
  596. # returning
  597. # package_dir/filename
  598. return os.path.join(package_dir, filename)
  599. def get_ext_fullname(self, ext_name):
  600. """Returns the fullname of a given extension name.
  601. Adds the `package.` prefix"""
  602. if self.package is None:
  603. return ext_name
  604. else:
  605. return self.package + '.' + ext_name
  606. def get_ext_filename(self, ext_name):
  607. r"""Convert the name of an extension (eg. "foo.bar") into the name
  608. of the file from which it will be loaded (eg. "foo/bar.so", or
  609. "foo\bar.pyd").
  610. """
  611. from ..sysconfig import get_config_var
  612. ext_path = ext_name.split('.')
  613. ext_suffix = get_config_var('EXT_SUFFIX')
  614. return os.path.join(*ext_path) + ext_suffix
  615. def get_export_symbols(self, ext):
  616. """Return the list of symbols that a shared extension has to
  617. export. This either uses 'ext.export_symbols' or, if it's not
  618. provided, "PyInit_" + module_name. Only relevant on Windows, where
  619. the .pyd file (DLL) must export the module "PyInit_" function.
  620. """
  621. name = ext.name.split('.')[-1]
  622. try:
  623. # Unicode module name support as defined in PEP-489
  624. # https://peps.python.org/pep-0489/#export-hook-name
  625. name.encode('ascii')
  626. except UnicodeEncodeError:
  627. suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')
  628. else:
  629. suffix = "_" + name
  630. initfunc_name = "PyInit" + suffix
  631. if initfunc_name not in ext.export_symbols:
  632. ext.export_symbols.append(initfunc_name)
  633. return ext.export_symbols
  634. def get_libraries(self, ext): # noqa: C901
  635. """Return the list of libraries to link against when building a
  636. shared extension. On most platforms, this is just 'ext.libraries';
  637. on Windows, we add the Python library (eg. python20.dll).
  638. """
  639. # The python library is always needed on Windows. For MSVC, this
  640. # is redundant, since the library is mentioned in a pragma in
  641. # pyconfig.h that MSVC groks. The other Windows compilers all seem
  642. # to need it mentioned explicitly, though, so that's what we do.
  643. # Append '_d' to the python import library on debug builds.
  644. if sys.platform == "win32":
  645. from .._msvccompiler import MSVCCompiler
  646. if not isinstance(self.compiler, MSVCCompiler):
  647. template = "python%d%d"
  648. if self.debug:
  649. template = template + '_d'
  650. pythonlib = template % (
  651. sys.hexversion >> 24,
  652. (sys.hexversion >> 16) & 0xFF,
  653. )
  654. # don't extend ext.libraries, it may be shared with other
  655. # extensions, it is a reference to the original list
  656. return ext.libraries + [pythonlib]
  657. else:
  658. # On Android only the main executable and LD_PRELOADs are considered
  659. # to be RTLD_GLOBAL, all the dependencies of the main executable
  660. # remain RTLD_LOCAL and so the shared libraries must be linked with
  661. # libpython when python is built with a shared python library (issue
  662. # bpo-21536).
  663. # On Cygwin (and if required, other POSIX-like platforms based on
  664. # Windows like MinGW) it is simply necessary that all symbols in
  665. # shared libraries are resolved at link time.
  666. from ..sysconfig import get_config_var
  667. link_libpython = False
  668. if get_config_var('Py_ENABLE_SHARED'):
  669. # A native build on an Android device or on Cygwin
  670. if hasattr(sys, 'getandroidapilevel'):
  671. link_libpython = True
  672. elif sys.platform == 'cygwin':
  673. link_libpython = True
  674. elif '_PYTHON_HOST_PLATFORM' in os.environ:
  675. # We are cross-compiling for one of the relevant platforms
  676. if get_config_var('ANDROID_API_LEVEL') != 0:
  677. link_libpython = True
  678. elif get_config_var('MACHDEP') == 'cygwin':
  679. link_libpython = True
  680. if link_libpython:
  681. ldversion = get_config_var('LDVERSION')
  682. return ext.libraries + ['python' + ldversion]
  683. return ext.libraries + py37compat.pythonlib()