PageRenderTime 53ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/distutils/command/build_ext.py

https://bitbucket.org/pypy/pypy/
Python | 781 lines | 594 code | 61 blank | 126 comment | 68 complexity | 80a3e166cc31ef1046821ef080de32af MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  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. # This module should be kept compatible with Python 2.1.
  6. __revision__ = "$Id$"
  7. import sys, os, string, re, imp
  8. from types import *
  9. from site import USER_BASE, USER_SITE
  10. from distutils.core import Command
  11. from distutils.errors import *
  12. from distutils.sysconfig import customize_compiler, get_python_version
  13. from distutils.dep_util import newer_group
  14. from distutils.extension import Extension
  15. from distutils.util import get_platform
  16. from distutils import log
  17. if os.name == 'nt':
  18. from distutils.msvccompiler import get_build_version
  19. MSVC_VERSION = int(get_build_version())
  20. # An extension name is just a dot-separated list of Python NAMEs (ie.
  21. # the same as a fully-qualified module name).
  22. extension_name_re = re.compile \
  23. (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
  24. def show_compilers ():
  25. from distutils.ccompiler import show_compilers
  26. show_compilers()
  27. def _get_c_extension_suffix():
  28. for ext, mod, typ in imp.get_suffixes():
  29. if typ == imp.C_EXTENSION:
  30. return ext
  31. class build_ext (Command):
  32. description = "build C/C++ extensions (compile/link to build directory)"
  33. # XXX thoughts on how to deal with complex command-line options like
  34. # these, i.e. how to make it so fancy_getopt can suck them off the
  35. # command line and make it look like setup.py defined the appropriate
  36. # lists of tuples of what-have-you.
  37. # - each command needs a callback to process its command-line options
  38. # - Command.__init__() needs access to its share of the whole
  39. # command line (must ultimately come from
  40. # Distribution.parse_command_line())
  41. # - it then calls the current command class' option-parsing
  42. # callback to deal with weird options like -D, which have to
  43. # parse the option text and churn out some custom data
  44. # structure
  45. # - that data structure (in this case, a list of 2-tuples)
  46. # will then be present in the command object by the time
  47. # we get to finalize_options() (i.e. the constructor
  48. # takes care of both command-line and client options
  49. # in between initialize_options() and finalize_options())
  50. sep_by = " (separated by '%s')" % os.pathsep
  51. user_options = [
  52. ('build-lib=', 'b',
  53. "directory for compiled extension modules"),
  54. ('build-temp=', 't',
  55. "directory for temporary files (build by-products)"),
  56. ('plat-name=', 'p',
  57. "platform name to cross-compile for, if supported "
  58. "(default: %s)" % get_platform()),
  59. ('inplace', 'i',
  60. "ignore build-lib and put compiled extensions into the source " +
  61. "directory alongside your pure Python modules"),
  62. ('include-dirs=', 'I',
  63. "list of directories to search for header files" + sep_by),
  64. ('define=', 'D',
  65. "C preprocessor macros to define"),
  66. ('undef=', 'U',
  67. "C preprocessor macros to undefine"),
  68. ('libraries=', 'l',
  69. "external C libraries to link with"),
  70. ('library-dirs=', 'L',
  71. "directories to search for external C libraries" + sep_by),
  72. ('rpath=', 'R',
  73. "directories to search for shared C libraries at runtime"),
  74. ('link-objects=', 'O',
  75. "extra explicit link objects to include in the link"),
  76. ('debug', 'g',
  77. "compile/link with debugging information"),
  78. ('force', 'f',
  79. "forcibly build everything (ignore file timestamps)"),
  80. ('compiler=', 'c',
  81. "specify the compiler type"),
  82. ('swig-cpp', None,
  83. "make SWIG create C++ files (default is C)"),
  84. ('swig-opts=', None,
  85. "list of SWIG command line options"),
  86. ('swig=', None,
  87. "path to the SWIG executable"),
  88. ('user', None,
  89. "add user include, library and rpath"),
  90. ]
  91. boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
  92. help_options = [
  93. ('help-compiler', None,
  94. "list available compilers", show_compilers),
  95. ]
  96. def initialize_options (self):
  97. self.extensions = None
  98. self.build_lib = None
  99. self.plat_name = None
  100. self.build_temp = None
  101. self.inplace = 0
  102. self.package = None
  103. self.include_dirs = None
  104. self.define = None
  105. self.undef = None
  106. self.libraries = None
  107. self.library_dirs = None
  108. self.rpath = None
  109. self.link_objects = None
  110. self.debug = None
  111. self.force = None
  112. self.compiler = None
  113. self.swig = None
  114. self.swig_cpp = None
  115. self.swig_opts = None
  116. self.user = None
  117. def finalize_options(self):
  118. from distutils import sysconfig
  119. self.set_undefined_options('build',
  120. ('build_lib', 'build_lib'),
  121. ('build_temp', 'build_temp'),
  122. ('compiler', 'compiler'),
  123. ('debug', 'debug'),
  124. ('force', 'force'),
  125. ('plat_name', 'plat_name'),
  126. )
  127. if self.package is None:
  128. self.package = self.distribution.ext_package
  129. self.extensions = self.distribution.ext_modules
  130. # Make sure Python's include directories (for Python.h, pyconfig.h,
  131. # etc.) are in the include search path.
  132. py_include = sysconfig.get_python_inc()
  133. plat_py_include = sysconfig.get_python_inc(plat_specific=1)
  134. if self.include_dirs is None:
  135. self.include_dirs = self.distribution.include_dirs or []
  136. if isinstance(self.include_dirs, str):
  137. self.include_dirs = self.include_dirs.split(os.pathsep)
  138. # Put the Python "system" include dir at the end, so that
  139. # any local include dirs take precedence.
  140. self.include_dirs.append(py_include)
  141. if plat_py_include != py_include:
  142. self.include_dirs.append(plat_py_include)
  143. self.ensure_string_list('libraries')
  144. # Life is easier if we're not forever checking for None, so
  145. # simplify these options to empty lists if unset
  146. if self.libraries is None:
  147. self.libraries = []
  148. if self.library_dirs is None:
  149. self.library_dirs = []
  150. elif type(self.library_dirs) is StringType:
  151. self.library_dirs = string.split(self.library_dirs, os.pathsep)
  152. if self.rpath is None:
  153. self.rpath = []
  154. elif type(self.rpath) is StringType:
  155. self.rpath = string.split(self.rpath, os.pathsep)
  156. # for extensions under windows use different directories
  157. # for Release and Debug builds.
  158. # also Python's library directory must be appended to library_dirs
  159. if os.name == 'nt':
  160. # the 'libs' directory is for binary installs - we assume that
  161. # must be the *native* platform. But we don't really support
  162. # cross-compiling via a binary install anyway, so we let it go.
  163. self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
  164. if self.debug:
  165. self.build_temp = os.path.join(self.build_temp, "Debug")
  166. else:
  167. self.build_temp = os.path.join(self.build_temp, "Release")
  168. # Append the source distribution include and library directories,
  169. # this allows distutils on windows to work in the source tree
  170. if 0:
  171. # pypy has no PC directory
  172. self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
  173. if 1:
  174. # pypy has no PCBuild directory
  175. pass
  176. elif MSVC_VERSION == 9:
  177. # Use the .lib files for the correct architecture
  178. if self.plat_name == 'win32':
  179. suffix = ''
  180. else:
  181. # win-amd64 or win-ia64
  182. suffix = self.plat_name[4:]
  183. new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
  184. if suffix:
  185. new_lib = os.path.join(new_lib, suffix)
  186. self.library_dirs.append(new_lib)
  187. elif MSVC_VERSION == 8:
  188. self.library_dirs.append(os.path.join(sys.exec_prefix,
  189. 'PC', 'VS8.0'))
  190. elif MSVC_VERSION == 7:
  191. self.library_dirs.append(os.path.join(sys.exec_prefix,
  192. 'PC', 'VS7.1'))
  193. else:
  194. self.library_dirs.append(os.path.join(sys.exec_prefix,
  195. 'PC', 'VC6'))
  196. # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
  197. # import libraries in its "Config" subdirectory
  198. if os.name == 'os2':
  199. self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
  200. # for extensions under Cygwin and AtheOS Python's library directory must be
  201. # appended to library_dirs
  202. if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
  203. if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
  204. # building third party extensions
  205. self.library_dirs.append(os.path.join(sys.prefix, "lib",
  206. "python" + get_python_version(),
  207. "config"))
  208. else:
  209. # building python standard extensions
  210. self.library_dirs.append('.')
  211. # For building extensions with a shared Python library,
  212. # Python's library directory must be appended to library_dirs
  213. # See Issues: #1600860, #4366
  214. if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
  215. if not sysconfig.python_build:
  216. # building third party extensions
  217. self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
  218. else:
  219. # building python standard extensions
  220. self.library_dirs.append('.')
  221. # The argument parsing will result in self.define being a string, but
  222. # it has to be a list of 2-tuples. All the preprocessor symbols
  223. # specified by the 'define' option will be set to '1'. Multiple
  224. # symbols can be separated with commas.
  225. if self.define:
  226. defines = self.define.split(',')
  227. self.define = map(lambda symbol: (symbol, '1'), defines)
  228. # The option for macros to undefine is also a string from the
  229. # option parsing, but has to be a list. Multiple symbols can also
  230. # be separated with commas here.
  231. if self.undef:
  232. self.undef = self.undef.split(',')
  233. if self.swig_opts is None:
  234. self.swig_opts = []
  235. else:
  236. self.swig_opts = self.swig_opts.split(' ')
  237. # Finally add the user include and library directories if requested
  238. if self.user:
  239. user_include = os.path.join(USER_BASE, "include")
  240. user_lib = os.path.join(USER_BASE, "lib")
  241. if os.path.isdir(user_include):
  242. self.include_dirs.append(user_include)
  243. if os.path.isdir(user_lib):
  244. self.library_dirs.append(user_lib)
  245. self.rpath.append(user_lib)
  246. def run(self):
  247. from distutils.ccompiler import new_compiler
  248. # 'self.extensions', as supplied by setup.py, is a list of
  249. # Extension instances. See the documentation for Extension (in
  250. # distutils.extension) for details.
  251. #
  252. # For backwards compatibility with Distutils 0.8.2 and earlier, we
  253. # also allow the 'extensions' list to be a list of tuples:
  254. # (ext_name, build_info)
  255. # where build_info is a dictionary containing everything that
  256. # Extension instances do except the name, with a few things being
  257. # differently named. We convert these 2-tuples to Extension
  258. # instances as needed.
  259. if not self.extensions:
  260. return
  261. # If we were asked to build any C/C++ libraries, make sure that the
  262. # directory where we put them is in the library search path for
  263. # linking extensions.
  264. if self.distribution.has_c_libraries():
  265. build_clib = self.get_finalized_command('build_clib')
  266. self.libraries.extend(build_clib.get_library_names() or [])
  267. self.library_dirs.append(build_clib.build_clib)
  268. # Setup the CCompiler object that we'll use to do all the
  269. # compiling and linking
  270. self.compiler = new_compiler(compiler=self.compiler,
  271. verbose=self.verbose,
  272. dry_run=self.dry_run,
  273. force=self.force)
  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):
  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. for i, ext in enumerate(extensions):
  316. if isinstance(ext, Extension):
  317. continue # OK! (assume type-checking done
  318. # by Extension constructor)
  319. if not isinstance(ext, tuple) or len(ext) != 2:
  320. raise DistutilsSetupError, \
  321. ("each element of 'ext_modules' option must be an "
  322. "Extension instance or 2-tuple")
  323. ext_name, build_info = ext
  324. log.warn(("old-style (ext_name, build_info) tuple found in "
  325. "ext_modules for extension '%s'"
  326. "-- please convert to Extension instance" % ext_name))
  327. if not (isinstance(ext_name, str) and
  328. extension_name_re.match(ext_name)):
  329. raise DistutilsSetupError, \
  330. ("first element of each tuple in 'ext_modules' "
  331. "must be the extension name (a string)")
  332. if not isinstance(build_info, dict):
  333. raise DistutilsSetupError, \
  334. ("second element of each tuple in 'ext_modules' "
  335. "must be a dictionary (build info)")
  336. # OK, the (ext_name, build_info) dict is type-safe: convert it
  337. # to an Extension instance.
  338. ext = Extension(ext_name, build_info['sources'])
  339. # Easy stuff: one-to-one mapping from dict elements to
  340. # instance attributes.
  341. for key in ('include_dirs', 'library_dirs', 'libraries',
  342. 'extra_objects', 'extra_compile_args',
  343. 'extra_link_args'):
  344. val = build_info.get(key)
  345. if val is not None:
  346. setattr(ext, key, val)
  347. # Medium-easy stuff: same syntax/semantics, different names.
  348. ext.runtime_library_dirs = build_info.get('rpath')
  349. if 'def_file' in build_info:
  350. log.warn("'def_file' element of build info dict "
  351. "no longer supported")
  352. # Non-trivial stuff: 'macros' split into 'define_macros'
  353. # and 'undef_macros'.
  354. macros = build_info.get('macros')
  355. if macros:
  356. ext.define_macros = []
  357. ext.undef_macros = []
  358. for macro in macros:
  359. if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
  360. raise DistutilsSetupError, \
  361. ("'macros' element of build info dict "
  362. "must be 1- or 2-tuple")
  363. if len(macro) == 1:
  364. ext.undef_macros.append(macro[0])
  365. elif len(macro) == 2:
  366. ext.define_macros.append(macro)
  367. extensions[i] = ext
  368. def get_source_files(self):
  369. self.check_extensions_list(self.extensions)
  370. filenames = []
  371. # Wouldn't it be neat if we knew the names of header files too...
  372. for ext in self.extensions:
  373. filenames.extend(ext.sources)
  374. return filenames
  375. def get_outputs(self):
  376. # Sanity check the 'extensions' list -- can't assume this is being
  377. # done in the same run as a 'build_extensions()' call (in fact, we
  378. # can probably assume that it *isn't*!).
  379. self.check_extensions_list(self.extensions)
  380. # And build the list of output (built) filenames. Note that this
  381. # ignores the 'inplace' flag, and assumes everything goes in the
  382. # "build" tree.
  383. outputs = []
  384. for ext in self.extensions:
  385. outputs.append(self.get_ext_fullpath(ext.name))
  386. return outputs
  387. def build_extensions(self):
  388. # First, sanity-check the 'extensions' list
  389. self.check_extensions_list(self.extensions)
  390. for ext in self.extensions:
  391. self.build_extension(ext)
  392. def build_extension(self, ext):
  393. sources = ext.sources
  394. if sources is None or type(sources) not in (ListType, TupleType):
  395. raise DistutilsSetupError, \
  396. ("in 'ext_modules' option (extension '%s'), " +
  397. "'sources' must be present and must be " +
  398. "a list of source filenames") % ext.name
  399. sources = list(sources)
  400. ext_path = self.get_ext_fullpath(ext.name)
  401. depends = sources + ext.depends
  402. if not (self.force or newer_group(depends, ext_path, 'newer')):
  403. log.debug("skipping '%s' extension (up-to-date)", ext.name)
  404. return
  405. else:
  406. log.info("building '%s' extension", ext.name)
  407. # First, scan the sources for SWIG definition files (.i), run
  408. # SWIG on 'em to create .c files, and modify the sources list
  409. # accordingly.
  410. sources = self.swig_sources(sources, ext)
  411. # Next, compile the source code to object files.
  412. # XXX not honouring 'define_macros' or 'undef_macros' -- the
  413. # CCompiler API needs to change to accommodate this, and I
  414. # want to do one thing at a time!
  415. # Two possible sources for extra compiler arguments:
  416. # - 'extra_compile_args' in Extension object
  417. # - CFLAGS environment variable (not particularly
  418. # elegant, but people seem to expect it and I
  419. # guess it's useful)
  420. # The environment variable should take precedence, and
  421. # any sensible compiler will give precedence to later
  422. # command line args. Hence we combine them in order:
  423. extra_args = ext.extra_compile_args or []
  424. macros = ext.define_macros[:]
  425. for undef in ext.undef_macros:
  426. macros.append((undef,))
  427. objects = self.compiler.compile(sources,
  428. output_dir=self.build_temp,
  429. macros=macros,
  430. include_dirs=ext.include_dirs,
  431. debug=self.debug,
  432. extra_postargs=extra_args,
  433. depends=ext.depends)
  434. # XXX -- this is a Vile HACK!
  435. #
  436. # The setup.py script for Python on Unix needs to be able to
  437. # get this list so it can perform all the clean up needed to
  438. # avoid keeping object files around when cleaning out a failed
  439. # build of an extension module. Since Distutils does not
  440. # track dependencies, we have to get rid of intermediates to
  441. # ensure all the intermediates will be properly re-built.
  442. #
  443. self._built_objects = objects[:]
  444. # Now link the object files together into a "shared object" --
  445. # of course, first we have to figure out all the other things
  446. # that go into the mix.
  447. if ext.extra_objects:
  448. objects.extend(ext.extra_objects)
  449. extra_args = ext.extra_link_args or []
  450. # Detect target language, if not provided
  451. language = ext.language or self.compiler.detect_language(sources)
  452. self.compiler.link_shared_object(
  453. objects, ext_path,
  454. libraries=self.get_libraries(ext),
  455. library_dirs=ext.library_dirs,
  456. runtime_library_dirs=ext.runtime_library_dirs,
  457. extra_postargs=extra_args,
  458. export_symbols=self.get_export_symbols(ext),
  459. debug=self.debug,
  460. build_temp=self.build_temp,
  461. target_lang=language)
  462. def swig_sources (self, sources, extension):
  463. """Walk the list of source files in 'sources', looking for SWIG
  464. interface (.i) files. Run SWIG on all that are found, and
  465. return a modified 'sources' list with SWIG source files replaced
  466. by the generated C (or C++) files.
  467. """
  468. new_sources = []
  469. swig_sources = []
  470. swig_targets = {}
  471. # XXX this drops generated C/C++ files into the source tree, which
  472. # is fine for developers who want to distribute the generated
  473. # source -- but there should be an option to put SWIG output in
  474. # the temp dir.
  475. if self.swig_cpp:
  476. log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
  477. if self.swig_cpp or ('-c++' in self.swig_opts) or \
  478. ('-c++' in extension.swig_opts):
  479. target_ext = '.cpp'
  480. else:
  481. target_ext = '.c'
  482. for source in sources:
  483. (base, ext) = os.path.splitext(source)
  484. if ext == ".i": # SWIG interface file
  485. new_sources.append(base + '_wrap' + target_ext)
  486. swig_sources.append(source)
  487. swig_targets[source] = new_sources[-1]
  488. else:
  489. new_sources.append(source)
  490. if not swig_sources:
  491. return new_sources
  492. swig = self.swig or self.find_swig()
  493. swig_cmd = [swig, "-python"]
  494. swig_cmd.extend(self.swig_opts)
  495. if self.swig_cpp:
  496. swig_cmd.append("-c++")
  497. # Do not override commandline arguments
  498. if not self.swig_opts:
  499. for o in extension.swig_opts:
  500. swig_cmd.append(o)
  501. for source in swig_sources:
  502. target = swig_targets[source]
  503. log.info("swigging %s to %s", source, target)
  504. self.spawn(swig_cmd + ["-o", target, source])
  505. return new_sources
  506. # swig_sources ()
  507. def find_swig (self):
  508. """Return the name of the SWIG executable. On Unix, this is
  509. just "swig" -- it should be in the PATH. Tries a bit harder on
  510. Windows.
  511. """
  512. if os.name == "posix":
  513. return "swig"
  514. elif os.name == "nt":
  515. # Look for SWIG in its standard installation directory on
  516. # Windows (or so I presume!). If we find it there, great;
  517. # if not, act like Unix and assume it's in the PATH.
  518. for vers in ("1.3", "1.2", "1.1"):
  519. fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  520. if os.path.isfile(fn):
  521. return fn
  522. else:
  523. return "swig.exe"
  524. elif os.name == "os2":
  525. # assume swig available in the PATH.
  526. return "swig.exe"
  527. else:
  528. raise DistutilsPlatformError, \
  529. ("I don't know how to find (much less run) SWIG "
  530. "on platform '%s'") % os.name
  531. # find_swig ()
  532. # -- Name generators -----------------------------------------------
  533. # (extension names, filenames, whatever)
  534. def get_ext_fullpath(self, ext_name):
  535. """Returns the path of the filename for a given extension.
  536. The file is located in `build_lib` or directly in the package
  537. (inplace option).
  538. """
  539. # makes sure the extension name is only using dots
  540. all_dots = string.maketrans('/'+os.sep, '..')
  541. ext_name = ext_name.translate(all_dots)
  542. fullname = self.get_ext_fullname(ext_name)
  543. modpath = fullname.split('.')
  544. filename = self.get_ext_filename(ext_name)
  545. filename = os.path.split(filename)[-1]
  546. if not self.inplace:
  547. # no further work needed
  548. # returning :
  549. # build_dir/package/path/filename
  550. filename = os.path.join(*modpath[:-1]+[filename])
  551. return os.path.join(self.build_lib, filename)
  552. # the inplace option requires to find the package directory
  553. # using the build_py command for that
  554. package = '.'.join(modpath[0:-1])
  555. build_py = self.get_finalized_command('build_py')
  556. package_dir = os.path.abspath(build_py.get_package_dir(package))
  557. # returning
  558. # package_dir/filename
  559. return os.path.join(package_dir, filename)
  560. def get_ext_fullname(self, ext_name):
  561. """Returns the fullname of a given extension name.
  562. Adds the `package.` prefix"""
  563. if self.package is None:
  564. return ext_name
  565. else:
  566. return self.package + '.' + ext_name
  567. def get_ext_filename(self, ext_name):
  568. r"""Convert the name of an extension (eg. "foo.bar") into the name
  569. of the file from which it will be loaded (eg. "foo/bar.so", or
  570. "foo\bar.pyd").
  571. """
  572. from distutils.sysconfig import get_config_var
  573. ext_path = string.split(ext_name, '.')
  574. # OS/2 has an 8 character module (extension) limit :-(
  575. if os.name == "os2":
  576. ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
  577. # PyPy tweak: first try to get the C extension suffix from
  578. # 'imp'. If it fails we fall back to the 'SO' config var, like
  579. # the previous version of this code did. This should work for
  580. # CPython too. The point is that on PyPy with cpyext, the
  581. # config var 'SO' is just ".so" but we want to return
  582. # ".pypy-VERSION.so" instead. Note a further tweak for cffi's
  583. # embedding mode: if EXT_SUFFIX is also defined, use that
  584. # directly.
  585. so_ext = get_config_var('EXT_SUFFIX')
  586. if so_ext is None:
  587. so_ext = _get_c_extension_suffix()
  588. if so_ext is None:
  589. so_ext = get_config_var('SO') # fall-back
  590. # extensions in debug_mode are named 'module_d.pyd' under windows
  591. if os.name == 'nt' and self.debug:
  592. so_ext = '_d.pyd'
  593. return os.path.join(*ext_path) + so_ext
  594. def get_export_symbols (self, ext):
  595. """Return the list of symbols that a shared extension has to
  596. export. This either uses 'ext.export_symbols' or, if it's not
  597. provided, "init" + module_name. Only relevant on Windows, where
  598. the .pyd file (DLL) must export the module "init" function.
  599. """
  600. initfunc_name = "init" + ext.name.split('.')[-1]
  601. if initfunc_name not in ext.export_symbols:
  602. ext.export_symbols.append(initfunc_name)
  603. return ext.export_symbols
  604. def get_libraries (self, ext):
  605. """Return the list of libraries to link against when building a
  606. shared extension. On most platforms, this is just 'ext.libraries';
  607. on Windows and OS/2, we add the Python library (eg. python20.dll).
  608. """
  609. # For PyPy, we must not add any such Python library, on any platform
  610. if "__pypy__" in sys.builtin_module_names:
  611. return ext.libraries
  612. # The python library is always needed on Windows.
  613. if sys.platform == "win32":
  614. template = "python%d%d"
  615. pythonlib = (template %
  616. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  617. # don't extend ext.libraries, it may be shared with other
  618. # extensions, it is a reference to the original list
  619. return ext.libraries + [pythonlib]
  620. elif sys.platform == "os2emx":
  621. # EMX/GCC requires the python library explicitly, and I
  622. # believe VACPP does as well (though not confirmed) - AIM Apr01
  623. template = "python%d%d"
  624. # debug versions of the main DLL aren't supported, at least
  625. # not at this time - AIM Apr01
  626. #if self.debug:
  627. # template = template + '_d'
  628. pythonlib = (template %
  629. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  630. # don't extend ext.libraries, it may be shared with other
  631. # extensions, it is a reference to the original list
  632. return ext.libraries + [pythonlib]
  633. elif sys.platform[:6] == "cygwin":
  634. template = "python%d.%d"
  635. pythonlib = (template %
  636. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  637. # don't extend ext.libraries, it may be shared with other
  638. # extensions, it is a reference to the original list
  639. return ext.libraries + [pythonlib]
  640. elif sys.platform[:6] == "atheos":
  641. from distutils import sysconfig
  642. template = "python%d.%d"
  643. pythonlib = (template %
  644. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  645. # Get SHLIBS from Makefile
  646. extra = []
  647. for lib in sysconfig.get_config_var('SHLIBS').split():
  648. if lib.startswith('-l'):
  649. extra.append(lib[2:])
  650. else:
  651. extra.append(lib)
  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, "m"] + extra
  655. elif sys.platform == 'darwin':
  656. # Don't use the default code below
  657. return ext.libraries
  658. elif sys.platform[:3] == 'aix':
  659. # Don't use the default code below
  660. return ext.libraries
  661. else:
  662. from distutils import sysconfig
  663. if sysconfig.get_config_var('Py_ENABLE_SHARED'):
  664. template = "python%d.%d"
  665. pythonlib = (template %
  666. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  667. return ext.libraries + [pythonlib]
  668. else:
  669. return ext.libraries
  670. # class build_ext