Debian Codegraph @

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

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