Debian Codegraph @

lib_pypy/pypy_tools/build_cffi_imports.py

raw symbols SCIP
1 from __future__ import print_function
2 import os
3 import platform
4 import shutil
5 import sys
6 import sysconfig
7 import tempfile
8 from os.path import join
9
10 try:
11 import _multiprocessing
12 except ImportError:
13 # The only function we need from multiprocessing is cpu_count(), which is
14 # written in the pure Python part of multiprocessing. We can make it work
15 # in environments that don't have _multiprocessing by adding an empty
16 # module in place of _multiprocessing.
17 import types
18 sys.modules['_multiprocessing'] = types.ModuleType('fake _multiprocessing')
19 import multiprocessing
20
21 # do not use the long-running runsubprocess._run here, since building some of
22 # the extensions enable importing them later
23 os.environ['PYPY_DONT_RUN_SUBPROCESS'] = '1'
24
25 class MissingDependenciesError(Exception):
26 pass
27
28
29 cffi_build_scripts = [
30 ("_ctypes._ctypes_cffi",
31 "_ctypes/_ctypes_build.py" if sys.platform == 'darwin' else None),
32 ("_pypy_util_cffi_inner", "_pypy_util_build.py"), # this needs to come before ssl
33 ("_blake2", "_blake2/_blake2_build.py"),
34 ("_sha3", "_sha3/_sha3_build.py"),
35 ("_ssl", "_ssl_build.py"),
36 ("sqlite3", "_sqlite3_build.py"),
37 ("audioop", "_audioop_build.py"),
38 ("_tkinter", "_tkinter/tklib_build.py"),
39 ("curses", "_curses_build.py" if sys.platform != "win32" else None),
40 ("syslog", "_syslog_build.py" if sys.platform != "win32" else None),
41 ("_gdbm", "_gdbm_build.py" if sys.platform != "win32" else None),
42 ("grp", "_pwdgrp_build.py" if sys.platform != "win32" else None),
43 ("resource", "_resource_build.py" if sys.platform != "win32" else None),
44 ("lzma", "_lzma_build.py"),
45 # ("_decimal", "_decimal_build.py"), # issue 3024
46 ("xx", None), # for testing: 'None' should be completely ignored
47 ("_posixshmem", "_posixshmem_build.py" if sys.platform != "win32" else None),
48 ]
49
50 # for distribution, we may want to fetch dependencies not provided by
51 # the OS, such as a recent openssl/libressl.
52 curdir = os.path.abspath(os.path.dirname(__file__))
53 deps_destdir = os.path.join(curdir, 'dest')
54 configure_args = ['./configure',
55 '--prefix=/usr',
56 '--disable-shared',
57 '--enable-silent-rules',
58 '--disable-dependency-tracking',
59 ]
60 cffi_dependencies = {
61 '_ssl': ('https://www.openssl.org/source/openssl-3.3.1.tar.gz',
62 '777cd596284c883375a2a7a11bf5d2786fc5413255efab20c50d6ffe6d020b7e',
63 [
64 ['./config', '--prefix=/usr', 'no-shared', 'enable-fips'],
65 ['make', '-s', '-j', str(multiprocessing.cpu_count())],
66 ['make', 'install', 'DESTDIR={}/'.format(deps_destdir)],
67 ]),
68 'lzma': ('https://sourceforge.net/projects/lzmautils/files/xz-5.4.6.tar.bz2/download',
69 '913851b274e8e1d31781ec949f1c23e8dbcf0ecf6e73a2436dc21769dd3e6f49',
70 [configure_args,
71 ['make', '-s', '-j', str(multiprocessing.cpu_count())],
72 ['make', 'install', 'DESTDIR={}/'.format(deps_destdir)],
73 ]),
74 '_gdbm': ('http://distfiles.macports.org/gdbm/gdbm-1.23.tar.gz',
75 '74b1081d21fff13ae4bd7c16e5d6e504a4c26f7cde1dca0d963a484174bbcacd',
76 [configure_args + ['--without-readline'],
77 ['make', '-s', '-j', str(multiprocessing.cpu_count())],
78 ['make', 'install', 'DESTDIR={}/'.format(deps_destdir)],
79 ]),
80 }
81
82 def _unpack_tarfile(filename, extract_dir):
83 """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir`
84 """
85 import tarfile # late import for breaking circular dependency
86 try:
87 tarobj = tarfile.open(filename)
88 except tarfile.TarError:
89 raise ReadError(
90 "%s is not a compressed or uncompressed tar file" % filename)
91 try:
92 tarobj.extractall(extract_dir)
93 finally:
94 tarobj.close()
95
96 def _sha256(filename):
97 import hashlib
98 dgst = hashlib.sha256()
99
100 with open(filename, 'rb') as fp:
101 dgst.update(fp.read())
102 return dgst.hexdigest()
103
104
105 def _build_dependency(name, patches=[]):
106 import shutil
107 from rpython.tool.runsubprocess import run_subprocess
108
109 try:
110 url, dgst, build_cmds = cffi_dependencies[name]
111 except KeyError:
112 return 0, None, None
113
114 archive_dir = os.path.join(tempfile.gettempdir(), 'pypy-archives')
115
116 if not os.path.isdir(archive_dir):
117 os.makedirs(archive_dir)
118
119 archive = os.path.join(archive_dir, url.rsplit('/', 1)[-1])
120
121 # next, fetch the archive to disk, if needed
122 if not os.path.exists(archive) or _sha256(archive) != dgst:
123 # Since we do not have a functioning ssl module, we cannot use urllib
124 # On one of the buildbots, wget is broken
125 if os.environ.get("USE_CURL", False):
126 print('fetching archive via curl', url, file=sys.stderr)
127 status, stdout, stderr = run_subprocess('curl', ['-sSLo', archive, url])
128 else:
129 print('fetching archive via wget', url, file=sys.stderr)
130 status, stdout, stderr = run_subprocess('wget', ['-O', archive, url])
131 if status != 0:
132 return status, stdout, stderr
133
134 # make sure the hash matches
135 if _sha256(archive) != dgst:
136 return (
137 1,
138 '{} archive {} hash mismatch'.format(name, archive).encode('utf8'),
139 b'')
140
141 shutil.rmtree(deps_destdir, ignore_errors=True)
142 os.makedirs(deps_destdir)
143
144 # extract the into our destination directory
145 print('unpacking archive', archive, file=sys.stderr)
146 _unpack_tarfile(archive, deps_destdir)
147
148 sources = os.path.join(
149 deps_destdir,
150 os.listdir(deps_destdir)[0],
151 )
152
153 # apply any patches
154 if patches:
155 for patch in patches:
156 print('applying patch', patch, file=sys.stderr)
157 status, stdout, stderr = run_subprocess(
158 '/usr/bin/patch', ['-p1', '-i', patch], cwd=sources,
159 )
160
161 if status != 0:
162 return status, stdout, stderr
163 env = os.environ
164 if sys.platform == 'darwin':
165 target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
166 if target:
167 # override the value for building support libraries
168 env = os.environ.copy()
169 env['MACOSX_DEPLOYMENT_TARGET'] = target
170 print('setting MACOSX_DEPLOYMENT_TARGET to "{}"'.format(target))
171
172 for args in build_cmds:
173 print('running', ' '.join(args), 'in', sources, file=sys.stderr)
174 status, stdout, stderr = run_subprocess(args[0], args[1:],
175 cwd=sources, env=env)
176 if status != 0:
177 break
178 return status, stdout, stderr
179
180 def create_cffi_import_libraries(pypy_c, options, basedir, only=None,
181 embed_dependencies=False, rebuild=False):
182 """
183 Entry point for building the cffi c-extension modules.
184 pypy_c is a pypy3 interpreter
185 options is the parsed options
186 basedir is the pypy-source base directory
187 embed_dependencies will download and build the external libraries in
188 cffi_dependencies and link to them statically
189 rebuild will force rebuilding a module
190 only will only build the modules in that list rather than all in cffi_build_scripts
191 """
192 from rpython.tool.runsubprocess import run_subprocess
193 print('calling create_cffi_import_libraries with "embed_dependencies"', embed_dependencies)
194
195 shutil.rmtree(str(join(basedir,'lib_pypy','__pycache__')),
196 ignore_errors=True)
197 pypy3 = str(pypy_c)
198 env = os.environ
199 if sys.platform == 'win32':
200 externals_path = os.path.abspath(os.path.join(basedir, 'externals'))
201 # Needed for buildbot builds. On conda this is not needed.
202 if os.path.exists(externals_path):
203 env = os.environ.copy()
204 env['INCLUDE'] = externals_path + r'\include;' + env.get('INCLUDE', '')
205 env['LIB'] = externals_path + r'\lib;' + env.get('LIB', '')
206 env['PATH'] = externals_path + r'\bin;' + env.get('PATH', '')
207 else:
208 # normally, this would be correctly added by setuptools/distutils, but
209 # we moved this for python3.8, and the ensurepip setuptools has not
210 # caught up yet. It needs at least setuptools-58.2 in ensurepip
211 status, stdout, stderr = run_subprocess(str(pypy_c), ['-c', 'from sysconfig import get_config_var as gcv; print(gcv("INCLUDEPY"))'])
212 stdout = stdout.decode('utf-8')
213 if status != 0:
214 print("stdout:")
215 print(stdout)
216 print("stderr:")
217 print(stderr.decode('utf-8'))
218 return list(cffi_build_scripts.items())
219 include_path = stdout.strip()
220 env['CFLAGS'] = ' '.join(('-fPIC', '-I' + include_path, env.get('CFLAGS', '')))
221 status, stdout, stderr = run_subprocess(pypy3, ['-c', 'import setuptools'])
222 if status != 0:
223 status, stdout, stderr = run_subprocess(pypy3, ['-m', 'ensurepip'])
224 failures = []
225
226 for key, module in cffi_build_scripts:
227 if only and key not in only:
228 print("* SKIPPING", key, '(not specified in --only)')
229 continue
230 if module is None or getattr(options, 'no_' + key, False):
231 continue
232 if not rebuild:
233 # the key is the module name, has it already been built?
234 status, stdout, stderr = run_subprocess(pypy3,
235 ['-c', 'import %s' % key], env=env)
236 if status == 0:
237 print('*', ' %s already built' % key, file=sys.stderr)
238 continue
239
240 if module.endswith('.py'):
241 args = [module]
242 cwd = str(join(basedir,'lib_pypy'))
243 else:
244 args = ['-c', 'import ' + module]
245 cwd = None
246
247 print('*', ' '.join(args), file=sys.stderr)
248 if embed_dependencies and key in cffi_dependencies:
249 status, stdout, stderr = _build_dependency(key)
250 if status != 0: # or key in ("_ssl"):
251 print("stdout:")
252 print(stdout.decode('utf-8'))
253 print("stderr:")
254 print(stderr.decode('utf-8'))
255 if status != 0:
256 failures.append((key, module))
257 continue
258
259 env['CPPFLAGS'] = '-I{}/usr/include {}'.format(
260 deps_destdir, env.get('CPPFLAGS', ''))
261 env['LDFLAGS'] = '-L{}/usr/lib64 -L{}/usr/lib {}'.format(
262 deps_destdir, deps_destdir, env.get('LDFLAGS', ''))
263
264 try:
265 status, bld_stdout, bld_stderr = run_subprocess(str(pypy_c), args,
266 cwd=cwd, env=env)
267 try:
268 bld_stdout = bld_stdout.decode('utf-8')
269 except Exception:
270 pass
271 try:
272 _bld_stderr = bld_stderr
273 bld_stderr = bld_stderr.decode('utf-8')
274 except Exception:
275 pass
276 if status != 0 or key in ("_ssl"):
277 print("stdout:")
278 print(bld_stdout)
279 print("stderr:")
280 try:
281 print(bld_stderr)
282 except Exception:
283 # the linux64 buildbot chokes on printing non-ascii unicode?
284 print(_bld_stderr)
285 if status != 0:
286 raise RuntimeError('building {} failed'.format(key))
287 except:
288 import traceback;traceback.print_exc()
289 failures.append((key, module))
290 else:
291 # Make sure it worked
292 test_script = "print('testing {0}'); import {0}".format(key)
293 if sys.platform == 'win32':
294 externals_path = os.path.abspath(os.path.join(basedir, 'externals'))
295 test_script = ("import os; os.add_dll_directory(r'" +
296 externals_path + r'\bin' + "');" + test_script)
297 status, stdout, stderr = run_subprocess(pypy3, ['-c', test_script],
298 env=env)
299 if status != 0:
300 try:
301 stdout = stdout.decode('utf-8')
302 except Exception:
303 pass
304 try:
305 stderr = stderr.decode('utf-8')
306 except Exception:
307 pass
308 failures.append((key, module))
309 print("build stdout:")
310 print(bld_stdout)
311 print("build stderr:")
312 print(bld_stderr)
313 print("test stdout:")
314 print(stdout)
315 print("test stderr:")
316 print(stderr)
317 if os.path.exists(deps_destdir):
318 shutil.rmtree(deps_destdir, ignore_errors=True)
319 return failures
320
321 if __name__ == '__main__':
322 import argparse
323 parser = argparse.ArgumentParser(description='Build all cffi backends in lib_pypy')
324 parser.add_argument('--exefile', dest='exefile', default=sys.executable,
325 help='instead of executing sys.executable' \
326 ' you can specify an alternative pypy vm here')
327 parser.add_argument('--rebuild', dest='rebuild', action='store_true',
328 help='Rebuild the module even if it already appears to have been built.')
329 parser.add_argument('--only', dest='only', default=None,
330 help='Only build the modules delimited by a comma e.g. _ssl,sqlite')
331 parser.add_argument('--embed-dependencies', dest='embed_dependencies', action='store_true',
332 help='embed dependencies for distribution')
333 args = parser.parse_args()
334
335 if '__pypy__' not in sys.builtin_module_names:
336 print('Call with a pypy interpreter', file=sys.stderr)
337 sys.exit(1)
338
339 tool_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
340 lib_pypy_dir = os.path.dirname(os.path.dirname(tool_dir))
341 sys.path.insert(0, lib_pypy_dir)
342
343 class Options(object):
344 pass
345
346 exename = join(os.getcwd(), args.exefile)
347 basedir = exename
348
349 while not os.path.exists(join(basedir,'lib_pypy')):
350 _basedir = os.path.dirname(basedir)
351 if _basedir == basedir:
352 raise ValueError('interpreter %s not inside pypy repo',
353 str(exename))
354 basedir = _basedir
355 options = Options()
356 if args.only is None:
357 only = None
358 else:
359 only = set(args.only.split(','))
360 olddir = os.getcwd()
361 os.chdir(lib_pypy_dir)
362 try:
363 failures = create_cffi_import_libraries(exename, options, basedir,
364 only=only, embed_dependencies=args.embed_dependencies,
365 rebuild=args.rebuild)
366 finally:
367 os.chdir(olddir)
368 if len(failures) > 0:
369 print('*** failed to build the CFFI modules %r' % (
370 [f[1] for f in failures],), file=sys.stderr)
371 print('''
372 PyPy can still be used as long as you don't need the corresponding
373 modules. If you do need them, please install the missing headers and
374 libraries (see error messages just above) and then re-run the command:
375
376 %s %s
377 ''' % (sys.executable, ' '.join(sys.argv)), file=sys.stderr)
378 sys.exit(1)
379
380 if len(sys.argv) > 1 and sys.argv[1] == '--test':
381 # monkey patch a failure, just to test
382 print('This line should be followed by a traceback', file=sys.stderr)
383 for k, m in cffi_build_scripts:
384 setattr(options, 'no_' + k, True)
385 must_fail = '_missing_build_script.py'
386 assert not os.path.exists(str(join(join(basedir,'lib_pypy'),must_fail)))
387 cffi_build_scripts.append('should_fail', must_fail)
388 failures = create_cffi_import_libraries(exename, options, basedir, only=only)
389 assert len(failures) == 1