Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
keewenaw
GitHub Repository: keewenaw/ethereum-wallet-cracker
Path: blob/main/test/lib/python3.9/site-packages/setuptools/command/build_ext.py
4799 views
1
import os
2
import sys
3
import itertools
4
from importlib.machinery import EXTENSION_SUFFIXES
5
from distutils.command.build_ext import build_ext as _du_build_ext
6
from distutils.file_util import copy_file
7
from distutils.ccompiler import new_compiler
8
from distutils.sysconfig import customize_compiler, get_config_var
9
from distutils.errors import DistutilsError
10
from distutils import log
11
12
from setuptools.extension import Library
13
14
try:
15
# Attempt to use Cython for building extensions, if available
16
from Cython.Distutils.build_ext import build_ext as _build_ext
17
# Additionally, assert that the compiler module will load
18
# also. Ref #1229.
19
__import__('Cython.Compiler.Main')
20
except ImportError:
21
_build_ext = _du_build_ext
22
23
# make sure _config_vars is initialized
24
get_config_var("LDSHARED")
25
from distutils.sysconfig import _config_vars as _CONFIG_VARS # noqa
26
27
28
def _customize_compiler_for_shlib(compiler):
29
if sys.platform == "darwin":
30
# building .dylib requires additional compiler flags on OSX; here we
31
# temporarily substitute the pyconfig.h variables so that distutils'
32
# 'customize_compiler' uses them before we build the shared libraries.
33
tmp = _CONFIG_VARS.copy()
34
try:
35
# XXX Help! I don't have any idea whether these are right...
36
_CONFIG_VARS['LDSHARED'] = (
37
"gcc -Wl,-x -dynamiclib -undefined dynamic_lookup")
38
_CONFIG_VARS['CCSHARED'] = " -dynamiclib"
39
_CONFIG_VARS['SO'] = ".dylib"
40
customize_compiler(compiler)
41
finally:
42
_CONFIG_VARS.clear()
43
_CONFIG_VARS.update(tmp)
44
else:
45
customize_compiler(compiler)
46
47
48
have_rtld = False
49
use_stubs = False
50
libtype = 'shared'
51
52
if sys.platform == "darwin":
53
use_stubs = True
54
elif os.name != 'nt':
55
try:
56
import dl
57
use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')
58
except ImportError:
59
pass
60
61
62
def if_dl(s):
63
return s if have_rtld else ''
64
65
66
def get_abi3_suffix():
67
"""Return the file extension for an abi3-compliant Extension()"""
68
for suffix in EXTENSION_SUFFIXES:
69
if '.abi3' in suffix: # Unix
70
return suffix
71
elif suffix == '.pyd': # Windows
72
return suffix
73
74
75
class build_ext(_build_ext):
76
def run(self):
77
"""Build extensions in build directory, then copy if --inplace"""
78
old_inplace, self.inplace = self.inplace, 0
79
_build_ext.run(self)
80
self.inplace = old_inplace
81
if old_inplace:
82
self.copy_extensions_to_source()
83
84
def copy_extensions_to_source(self):
85
build_py = self.get_finalized_command('build_py')
86
for ext in self.extensions:
87
fullname = self.get_ext_fullname(ext.name)
88
filename = self.get_ext_filename(fullname)
89
modpath = fullname.split('.')
90
package = '.'.join(modpath[:-1])
91
package_dir = build_py.get_package_dir(package)
92
dest_filename = os.path.join(package_dir,
93
os.path.basename(filename))
94
src_filename = os.path.join(self.build_lib, filename)
95
96
# Always copy, even if source is older than destination, to ensure
97
# that the right extensions for the current Python/platform are
98
# used.
99
copy_file(
100
src_filename, dest_filename, verbose=self.verbose,
101
dry_run=self.dry_run
102
)
103
if ext._needs_stub:
104
self.write_stub(package_dir or os.curdir, ext, True)
105
106
def get_ext_filename(self, fullname):
107
so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')
108
if so_ext:
109
filename = os.path.join(*fullname.split('.')) + so_ext
110
else:
111
filename = _build_ext.get_ext_filename(self, fullname)
112
so_ext = get_config_var('EXT_SUFFIX')
113
114
if fullname in self.ext_map:
115
ext = self.ext_map[fullname]
116
use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix()
117
if use_abi3:
118
filename = filename[:-len(so_ext)]
119
so_ext = get_abi3_suffix()
120
filename = filename + so_ext
121
if isinstance(ext, Library):
122
fn, ext = os.path.splitext(filename)
123
return self.shlib_compiler.library_filename(fn, libtype)
124
elif use_stubs and ext._links_to_dynamic:
125
d, fn = os.path.split(filename)
126
return os.path.join(d, 'dl-' + fn)
127
return filename
128
129
def initialize_options(self):
130
_build_ext.initialize_options(self)
131
self.shlib_compiler = None
132
self.shlibs = []
133
self.ext_map = {}
134
135
def finalize_options(self):
136
_build_ext.finalize_options(self)
137
self.extensions = self.extensions or []
138
self.check_extensions_list(self.extensions)
139
self.shlibs = [ext for ext in self.extensions
140
if isinstance(ext, Library)]
141
if self.shlibs:
142
self.setup_shlib_compiler()
143
for ext in self.extensions:
144
ext._full_name = self.get_ext_fullname(ext.name)
145
for ext in self.extensions:
146
fullname = ext._full_name
147
self.ext_map[fullname] = ext
148
149
# distutils 3.1 will also ask for module names
150
# XXX what to do with conflicts?
151
self.ext_map[fullname.split('.')[-1]] = ext
152
153
ltd = self.shlibs and self.links_to_dynamic(ext) or False
154
ns = ltd and use_stubs and not isinstance(ext, Library)
155
ext._links_to_dynamic = ltd
156
ext._needs_stub = ns
157
filename = ext._file_name = self.get_ext_filename(fullname)
158
libdir = os.path.dirname(os.path.join(self.build_lib, filename))
159
if ltd and libdir not in ext.library_dirs:
160
ext.library_dirs.append(libdir)
161
if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:
162
ext.runtime_library_dirs.append(os.curdir)
163
164
def setup_shlib_compiler(self):
165
compiler = self.shlib_compiler = new_compiler(
166
compiler=self.compiler, dry_run=self.dry_run, force=self.force
167
)
168
_customize_compiler_for_shlib(compiler)
169
170
if self.include_dirs is not None:
171
compiler.set_include_dirs(self.include_dirs)
172
if self.define is not None:
173
# 'define' option is a list of (name,value) tuples
174
for (name, value) in self.define:
175
compiler.define_macro(name, value)
176
if self.undef is not None:
177
for macro in self.undef:
178
compiler.undefine_macro(macro)
179
if self.libraries is not None:
180
compiler.set_libraries(self.libraries)
181
if self.library_dirs is not None:
182
compiler.set_library_dirs(self.library_dirs)
183
if self.rpath is not None:
184
compiler.set_runtime_library_dirs(self.rpath)
185
if self.link_objects is not None:
186
compiler.set_link_objects(self.link_objects)
187
188
# hack so distutils' build_extension() builds a library instead
189
compiler.link_shared_object = link_shared_object.__get__(compiler)
190
191
def get_export_symbols(self, ext):
192
if isinstance(ext, Library):
193
return ext.export_symbols
194
return _build_ext.get_export_symbols(self, ext)
195
196
def build_extension(self, ext):
197
ext._convert_pyx_sources_to_lang()
198
_compiler = self.compiler
199
try:
200
if isinstance(ext, Library):
201
self.compiler = self.shlib_compiler
202
_build_ext.build_extension(self, ext)
203
if ext._needs_stub:
204
cmd = self.get_finalized_command('build_py').build_lib
205
self.write_stub(cmd, ext)
206
finally:
207
self.compiler = _compiler
208
209
def links_to_dynamic(self, ext):
210
"""Return true if 'ext' links to a dynamic lib in the same package"""
211
# XXX this should check to ensure the lib is actually being built
212
# XXX as dynamic, and not just using a locally-found version or a
213
# XXX static-compiled version
214
libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
215
pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])
216
return any(pkg + libname in libnames for libname in ext.libraries)
217
218
def get_outputs(self):
219
return _build_ext.get_outputs(self) + self.__get_stubs_outputs()
220
221
def __get_stubs_outputs(self):
222
# assemble the base name for each extension that needs a stub
223
ns_ext_bases = (
224
os.path.join(self.build_lib, *ext._full_name.split('.'))
225
for ext in self.extensions
226
if ext._needs_stub
227
)
228
# pair each base with the extension
229
pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())
230
return list(base + fnext for base, fnext in pairs)
231
232
def __get_output_extensions(self):
233
yield '.py'
234
yield '.pyc'
235
if self.get_finalized_command('build_py').optimize:
236
yield '.pyo'
237
238
def write_stub(self, output_dir, ext, compile=False):
239
log.info("writing stub loader for %s to %s", ext._full_name,
240
output_dir)
241
stub_file = (os.path.join(output_dir, *ext._full_name.split('.')) +
242
'.py')
243
if compile and os.path.exists(stub_file):
244
raise DistutilsError(stub_file + " already exists! Please delete.")
245
if not self.dry_run:
246
f = open(stub_file, 'w')
247
f.write(
248
'\n'.join([
249
"def __bootstrap__():",
250
" global __bootstrap__, __file__, __loader__",
251
" import sys, os, pkg_resources, importlib.util" +
252
if_dl(", dl"),
253
" __file__ = pkg_resources.resource_filename"
254
"(__name__,%r)"
255
% os.path.basename(ext._file_name),
256
" del __bootstrap__",
257
" if '__loader__' in globals():",
258
" del __loader__",
259
if_dl(" old_flags = sys.getdlopenflags()"),
260
" old_dir = os.getcwd()",
261
" try:",
262
" os.chdir(os.path.dirname(__file__))",
263
if_dl(" sys.setdlopenflags(dl.RTLD_NOW)"),
264
" spec = importlib.util.spec_from_file_location(",
265
" __name__, __file__)",
266
" mod = importlib.util.module_from_spec(spec)",
267
" spec.loader.exec_module(mod)",
268
" finally:",
269
if_dl(" sys.setdlopenflags(old_flags)"),
270
" os.chdir(old_dir)",
271
"__bootstrap__()",
272
"" # terminal \n
273
])
274
)
275
f.close()
276
if compile:
277
from distutils.util import byte_compile
278
279
byte_compile([stub_file], optimize=0,
280
force=True, dry_run=self.dry_run)
281
optimize = self.get_finalized_command('install_lib').optimize
282
if optimize > 0:
283
byte_compile([stub_file], optimize=optimize,
284
force=True, dry_run=self.dry_run)
285
if os.path.exists(stub_file) and not self.dry_run:
286
os.unlink(stub_file)
287
288
289
if use_stubs or os.name == 'nt':
290
# Build shared libraries
291
#
292
def link_shared_object(
293
self, objects, output_libname, output_dir=None, libraries=None,
294
library_dirs=None, runtime_library_dirs=None, export_symbols=None,
295
debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
296
target_lang=None):
297
self.link(
298
self.SHARED_LIBRARY, objects, output_libname,
299
output_dir, libraries, library_dirs, runtime_library_dirs,
300
export_symbols, debug, extra_preargs, extra_postargs,
301
build_temp, target_lang
302
)
303
else:
304
# Build static libraries everywhere else
305
libtype = 'static'
306
307
def link_shared_object(
308
self, objects, output_libname, output_dir=None, libraries=None,
309
library_dirs=None, runtime_library_dirs=None, export_symbols=None,
310
debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,
311
target_lang=None):
312
# XXX we need to either disallow these attrs on Library instances,
313
# or warn/abort here if set, or something...
314
# libraries=None, library_dirs=None, runtime_library_dirs=None,
315
# export_symbols=None, extra_preargs=None, extra_postargs=None,
316
# build_temp=None
317
318
assert output_dir is None # distutils build_ext doesn't pass this
319
output_dir, filename = os.path.split(output_libname)
320
basename, ext = os.path.splitext(filename)
321
if self.library_filename("x").startswith('lib'):
322
# strip 'lib' prefix; this is kludgy if some platform uses
323
# a different prefix
324
basename = basename[3:]
325
326
self.create_static_lib(
327
objects, basename, output_dir, debug, target_lang
328
)
329
330