Debian Codegraph @

Tools/wasm/wasi/__main__.py

raw
1 #!/usr/bin/env python3
2
3 import argparse
4 import contextlib
5 import functools
6 import os
7
8 try:
9 from os import process_cpu_count as cpu_count
10 except ImportError:
11 from os import cpu_count
12 import pathlib
13 import shutil
14 import subprocess
15 import sys
16 import sysconfig
17 import tempfile
18
19 CHECKOUT = pathlib.Path(__file__).parent.parent.parent.parent
20 assert (CHECKOUT / "configure").is_file(), (
21 "Please update the location of the file"
22 )
23
24 CROSS_BUILD_DIR = CHECKOUT / "cross-build"
25 # Build platform can also be found via `config.guess`.
26 BUILD_DIR = CROSS_BUILD_DIR / sysconfig.get_config_var("BUILD_GNU_TYPE")
27
28 LOCAL_SETUP = CHECKOUT / "Modules" / "Setup.local"
29 LOCAL_SETUP_MARKER = (
30 b"# Generated by Tools/wasm/wasi .\n"
31 b"# Required to statically build extension modules."
32 )
33
34 WASI_SDK_VERSION = 24
35
36 WASMTIME_VAR_NAME = "WASMTIME"
37 WASMTIME_HOST_RUNNER_VAR = f"{{{WASMTIME_VAR_NAME}}}"
38
39
40 def separator():
41 """Print a separator line across the terminal width."""
42 try:
43 tput_output = subprocess.check_output(
44 ["tput", "cols"], encoding="utf-8"
45 )
46 except subprocess.CalledProcessError:
47 terminal_width = 80
48 else:
49 terminal_width = int(tput_output.strip())
50 print("โŽฏ" * terminal_width)
51
52
53 def log(emoji, message, *, spacing=None):
54 """Print a notification with an emoji.
55
56 If 'spacing' is None, calculate the spacing based on the number of code points
57 in the emoji as terminals "eat" a space when the emoji has multiple code points.
58 """
59 if spacing is None:
60 spacing = " " if len(emoji) == 1 else " "
61 print("".join([emoji, spacing, message]))
62
63
64 def updated_env(updates={}):
65 """Create a new dict representing the environment to use.
66
67 The changes made to the execution environment are printed out.
68 """
69 env_defaults = {}
70 # https://reproducible-builds.org/docs/source-date-epoch/
71 git_epoch_cmd = ["git", "log", "-1", "--pretty=%ct"]
72 try:
73 epoch = subprocess.check_output(
74 git_epoch_cmd, encoding="utf-8"
75 ).strip()
76 env_defaults["SOURCE_DATE_EPOCH"] = epoch
77 except subprocess.CalledProcessError:
78 pass # Might be building from a tarball.
79 # This layering lets SOURCE_DATE_EPOCH from os.environ takes precedence.
80 environment = env_defaults | os.environ | updates
81
82 env_diff = {}
83 for key, value in environment.items():
84 if os.environ.get(key) != value:
85 env_diff[key] = value
86
87 env_vars = (
88 f"\n {key}={item}" for key, item in sorted(env_diff.items())
89 )
90 log("๐ŸŒŽ", f"Environment changes:{''.join(env_vars)}")
91
92 return environment
93
94
95 def subdir(working_dir, *, clean_ok=False):
96 """Decorator to change to a working directory."""
97
98 def decorator(func):
99 @functools.wraps(func)
100 def wrapper(context):
101 nonlocal working_dir
102
103 if callable(working_dir):
104 working_dir = working_dir(context)
105 separator()
106 log("๐Ÿ“", os.fsdecode(working_dir))
107 if (
108 clean_ok
109 and getattr(context, "clean", False)
110 and working_dir.exists()
111 ):
112 log("๐Ÿšฎ", "Deleting directory (--clean)...")
113 shutil.rmtree(working_dir)
114
115 working_dir.mkdir(parents=True, exist_ok=True)
116
117 with contextlib.chdir(working_dir):
118 return func(context, working_dir)
119
120 return wrapper
121
122 return decorator
123
124
125 def call(command, *, context=None, quiet=False, logdir=None, **kwargs):
126 """Execute a command.
127
128 If 'quiet' is true, then redirect stdout and stderr to a temporary file.
129 """
130 if context is not None:
131 quiet = context.quiet
132 logdir = context.logdir
133 elif quiet and logdir is None:
134 raise ValueError("When quiet is True, logdir must be specified")
135
136 log("โฏ", " ".join(map(str, command)), spacing=" ")
137 if not quiet:
138 stdout = None
139 stderr = None
140 else:
141 stdout = tempfile.NamedTemporaryFile(
142 "w",
143 encoding="utf-8",
144 delete=False,
145 dir=logdir,
146 prefix="cpython-wasi-",
147 suffix=".log",
148 )
149 stderr = subprocess.STDOUT
150 log("๐Ÿ“", f"Logging output to {stdout.name} (--quiet)...")
151
152 subprocess.check_call(command, **kwargs, stdout=stdout, stderr=stderr)
153
154
155 def build_python_path():
156 """The path to the build Python binary."""
157 binary = BUILD_DIR / "python"
158 if not binary.is_file():
159 binary = binary.with_suffix(".exe")
160 if not binary.is_file():
161 raise FileNotFoundError(
162 f"Unable to find `python(.exe)` in {BUILD_DIR}"
163 )
164
165 return binary
166
167
168 def build_python_is_pydebug():
169 """Find out if the build Python is a pydebug build."""
170 test = "import sys, test.support; sys.exit(test.support.Py_DEBUG)"
171 result = subprocess.run(
172 [build_python_path(), "-c", test],
173 capture_output=True,
174 )
175 return bool(result.returncode)
176
177
178 @subdir(BUILD_DIR, clean_ok=True)
179 def configure_build_python(context, working_dir):
180 """Configure the build/host Python."""
181 if LOCAL_SETUP.exists():
182 if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER:
183 log("๐Ÿ‘", f"{LOCAL_SETUP} exists ...")
184 else:
185 log("โš ๏ธ", f"{LOCAL_SETUP} exists, but has unexpected contents")
186 else:
187 log("๐Ÿ“", f"Creating {LOCAL_SETUP} ...")
188 LOCAL_SETUP.write_bytes(LOCAL_SETUP_MARKER)
189
190 configure = [os.path.relpath(CHECKOUT / "configure", working_dir)]
191 if context.args:
192 configure.extend(context.args)
193
194 call(configure, context=context)
195
196
197 @subdir(BUILD_DIR)
198 def make_build_python(context, working_dir):
199 """Make/build the build Python."""
200 call(["make", "--jobs", str(cpu_count()), "all"], context=context)
201
202 binary = build_python_path()
203 cmd = [
204 binary,
205 "-c",
206 "import sys; "
207 "print(f'{sys.version_info.major}.{sys.version_info.minor}')",
208 ]
209 version = subprocess.check_output(cmd, encoding="utf-8").strip()
210
211 log("๐ŸŽ‰", f"{binary} {version}")
212
213
214 @subdir(BUILD_DIR)
215 def pythoninfo_build_python(context, working_dir):
216 """Display build info of the build Python."""
217 call(["make", "pythoninfo"], context=context)
218
219
220 def find_wasi_sdk():
221 """Find the path to the WASI SDK."""
222 wasi_sdk_path = None
223
224 if wasi_sdk_path_env_var := os.environ.get("WASI_SDK_PATH"):
225 wasi_sdk_path = pathlib.Path(wasi_sdk_path_env_var)
226 else:
227 opt_path = pathlib.Path("/opt")
228 # WASI SDK versions have a ``.0`` suffix, but it's a constant; the WASI SDK team
229 # has said they don't plan to ever do a point release and all of their Git tags
230 # lack the ``.0`` suffix.
231 # Starting with WASI SDK 23, the tarballs went from containing a directory named
232 # ``wasi-sdk-{WASI_SDK_VERSION}.0`` to e.g.
233 # ``wasi-sdk-{WASI_SDK_VERSION}.0-x86_64-linux``.
234 potential_sdks = [
235 path
236 for path in opt_path.glob(f"wasi-sdk-{WASI_SDK_VERSION}.0*")
237 if path.is_dir()
238 ]
239 if len(potential_sdks) == 1:
240 wasi_sdk_path = potential_sdks[0]
241 elif (default_path := opt_path / "wasi-sdk").is_dir():
242 wasi_sdk_path = default_path
243
244 # Starting with WASI SDK 25, a VERSION file is included in the root
245 # of the SDK directory that we can read to warn folks when they are using
246 # an unsupported version.
247 if wasi_sdk_path and (version_file := wasi_sdk_path / "VERSION").is_file():
248 version_details = version_file.read_text(encoding="utf-8")
249 found_version = version_details.splitlines()[0]
250 # Make sure there's a trailing dot to avoid false positives if somehow the
251 # supported version is a prefix of the found version (e.g. `25` and `2567`).
252 if not found_version.startswith(f"{WASI_SDK_VERSION}."):
253 major_version = found_version.partition(".")[0]
254 log(
255 "โš ๏ธ",
256 f" Found WASI SDK {major_version}, "
257 f"but WASI SDK {WASI_SDK_VERSION} is the supported version",
258 )
259
260 return wasi_sdk_path
261
262
263 def wasi_sdk_env(context):
264 """Calculate environment variables for building with wasi-sdk."""
265 wasi_sdk_path = context.wasi_sdk_path
266 sysroot = wasi_sdk_path / "share" / "wasi-sysroot"
267 env = {
268 "CC": "clang",
269 "CPP": "clang-cpp",
270 "CXX": "clang++",
271 "AR": "llvm-ar",
272 "RANLIB": "ranlib",
273 }
274
275 for env_var, binary_name in list(env.items()):
276 env[env_var] = os.fsdecode(wasi_sdk_path / "bin" / binary_name)
277
278 if not wasi_sdk_path.name.startswith("wasi-sdk"):
279 for compiler in ["CC", "CPP", "CXX"]:
280 env[compiler] += f" --sysroot={sysroot}"
281
282 env["PKG_CONFIG_PATH"] = ""
283 env["PKG_CONFIG_LIBDIR"] = os.pathsep.join(
284 map(
285 os.fsdecode,
286 [sysroot / "lib" / "pkgconfig", sysroot / "share" / "pkgconfig"],
287 )
288 )
289 env["PKG_CONFIG_SYSROOT_DIR"] = os.fsdecode(sysroot)
290
291 env["WASI_SDK_PATH"] = os.fsdecode(wasi_sdk_path)
292 env["WASI_SYSROOT"] = os.fsdecode(sysroot)
293
294 env["PATH"] = os.pathsep.join([
295 os.fsdecode(wasi_sdk_path / "bin"),
296 os.environ["PATH"],
297 ])
298
299 return env
300
301
302 @subdir(lambda context: CROSS_BUILD_DIR / context.host_triple, clean_ok=True)
303 def configure_wasi_python(context, working_dir):
304 """Configure the WASI/host build."""
305 if not context.wasi_sdk_path or not context.wasi_sdk_path.exists():
306 raise ValueError(
307 "WASI-SDK not found; "
308 "download from "
309 "https://github.com/WebAssembly/wasi-sdk and/or "
310 "specify via $WASI_SDK_PATH or --wasi-sdk"
311 )
312
313 config_site = os.fsdecode(
314 CHECKOUT / "Tools" / "wasm" / "wasi" / "config.site-wasm32-wasi"
315 )
316
317 wasi_build_dir = working_dir.relative_to(CHECKOUT)
318
319 python_build_dir = BUILD_DIR / "build"
320 lib_dirs = list(python_build_dir.glob("lib.*"))
321 assert len(lib_dirs) == 1, (
322 f"Expected a single lib.* directory in {python_build_dir}"
323 )
324 lib_dir = os.fsdecode(lib_dirs[0])
325 python_version = lib_dir.rpartition("-")[-1]
326 sysconfig_data_dir = (
327 f"{wasi_build_dir}/build/lib.wasi-wasm32-{python_version}"
328 )
329
330 # Use PYTHONPATH to include sysconfig data which must be anchored to the
331 # WASI guest's `/` directory.
332 args = {
333 "GUEST_DIR": "/",
334 "HOST_DIR": CHECKOUT,
335 "ENV_VAR_NAME": "PYTHONPATH",
336 "ENV_VAR_VALUE": f"/{sysconfig_data_dir}",
337 "PYTHON_WASM": working_dir / "python.wasm",
338 "ARGV0": wasi_build_dir / "python.wasm",
339 }
340 # Check dynamically for wasmtime in case it was specified manually via
341 # `--host-runner`.
342 if WASMTIME_HOST_RUNNER_VAR in context.host_runner:
343 if wasmtime := shutil.which("wasmtime"):
344 args[WASMTIME_VAR_NAME] = wasmtime
345 else:
346 raise FileNotFoundError(
347 "wasmtime not found; download from "
348 "https://github.com/bytecodealliance/wasmtime"
349 )
350 host_runner = context.host_runner.format_map(args)
351 env_additions = {"CONFIG_SITE": config_site, "HOSTRUNNER": host_runner}
352 build_python = os.fsdecode(build_python_path())
353 # The path to `configure` MUST be relative, else `python.wasm` is unable
354 # to find the stdlib due to Python not recognizing that it's being
355 # executed from within a checkout.
356 configure = [
357 os.path.relpath(CHECKOUT / "configure", working_dir),
358 f"--host={context.host_triple}",
359 f"--build={BUILD_DIR.name}",
360 f"--with-build-python={build_python}",
361 ]
362 if build_python_is_pydebug():
363 configure.append("--with-pydebug")
364 if context.args:
365 configure.extend(context.args)
366 call(
367 configure,
368 env=updated_env(env_additions | wasi_sdk_env(context)),
369 context=context,
370 )
371
372 python_wasm = working_dir / "python.wasm"
373 exec_script = working_dir / "python.sh"
374 with exec_script.open("w", encoding="utf-8") as file:
375 file.write(f'#!/bin/sh\nexec {host_runner} {python_wasm} "$@"\n')
376 exec_script.chmod(0o755)
377 log("๐Ÿƒ", f"Created {exec_script} (--host-runner)... ")
378 sys.stdout.flush()
379
380
381 @subdir(lambda context: CROSS_BUILD_DIR / context.host_triple)
382 def make_wasi_python(context, working_dir):
383 """Run `make` for the WASI/host build."""
384 call(
385 ["make", "--jobs", str(cpu_count()), "all"],
386 env=updated_env(),
387 context=context,
388 )
389
390 exec_script = working_dir / "python.sh"
391 call([exec_script, "--version"], quiet=False)
392 log(
393 "๐ŸŽ‰",
394 f"Use `{exec_script.relative_to(context.init_dir)}` "
395 "to run CPython w/ the WASI host specified by --host-runner",
396 )
397
398
399 @subdir(lambda context: CROSS_BUILD_DIR / context.host_triple)
400 def pythoninfo_wasi_python(context, working_dir):
401 """Display build info of the host/WASI Python."""
402 call(["make", "pythoninfo"], context=context)
403
404
405 def clean_contents(context):
406 """Delete all files created by this script."""
407 if CROSS_BUILD_DIR.exists():
408 log("๐Ÿงน", f"Deleting {CROSS_BUILD_DIR} ...")
409 shutil.rmtree(CROSS_BUILD_DIR)
410
411 if LOCAL_SETUP.exists():
412 if LOCAL_SETUP.read_bytes() == LOCAL_SETUP_MARKER:
413 log("๐Ÿงน", f"Deleting generated {LOCAL_SETUP} ...")
414
415
416 def build_steps(*steps):
417 """Construct a command from other steps."""
418
419 def builder(context):
420 for step in steps:
421 step(context)
422
423 return builder
424
425
426 def main():
427 default_host_triple = "wasm32-wasip1"
428 default_wasi_sdk = find_wasi_sdk()
429 default_host_runner = (
430 f"{WASMTIME_HOST_RUNNER_VAR} run "
431 # Make sure the stack size will work for a pydebug
432 # build.
433 # Use 16 MiB stack.
434 "--wasm max-wasm-stack=16777216 "
435 # Enable thread support; causes use of preview1.
436 # "--wasm threads=y --wasi threads=y "
437 # Explicitly set the argv[0] value
438 "--argv0 {ARGV0} "
439 # Map the checkout to / to load the stdlib from /Lib.
440 "--dir {HOST_DIR}::{GUEST_DIR} "
441 # Set PYTHONPATH to the sysconfig data.
442 "--env {ENV_VAR_NAME}={ENV_VAR_VALUE}"
443 )
444 default_logdir = pathlib.Path(tempfile.gettempdir())
445
446 parser = argparse.ArgumentParser()
447 subcommands = parser.add_subparsers(dest="subcommand")
448 build = subcommands.add_parser("build", help="Build everything")
449 configure_build = subcommands.add_parser(
450 "configure-build-python", help="Run `configure` for the build Python"
451 )
452 make_build = subcommands.add_parser(
453 "make-build-python", help="Run `make` for the build Python"
454 )
455 build_python = subcommands.add_parser(
456 "build-python", help="Build the build Python"
457 )
458 pythoninfo_build = subcommands.add_parser(
459 "pythoninfo-build", help="Display build info of the build Python"
460 )
461 configure_host = subcommands.add_parser(
462 "configure-host",
463 help="Run `configure` for the "
464 "host/WASI (pydebug builds "
465 "are inferred from the build "
466 "Python)",
467 )
468 make_host = subcommands.add_parser(
469 "make-host", help="Run `make` for the host/WASI"
470 )
471 build_host = subcommands.add_parser(
472 "build-host", help="Build the host/WASI Python"
473 )
474 pythoninfo_host = subcommands.add_parser(
475 "pythoninfo-host", help="Display build info of the host/WASI Python"
476 )
477 subcommands.add_parser(
478 "clean", help="Delete files and directories created by this script"
479 )
480 for subcommand in (
481 build,
482 configure_build,
483 make_build,
484 build_python,
485 pythoninfo_build,
486 configure_host,
487 make_host,
488 pythoninfo_host,
489 build_host,
490 ):
491 subcommand.add_argument(
492 "--quiet",
493 action="store_true",
494 default=False,
495 dest="quiet",
496 help="Redirect output from subprocesses to a log file",
497 )
498 subcommand.add_argument(
499 "--logdir",
500 type=pathlib.Path,
501 default=default_logdir,
502 help=f"Directory to store log files; defaults to {default_logdir}",
503 )
504 for subcommand in (
505 configure_build,
506 configure_host,
507 build_python,
508 build_host,
509 ):
510 subcommand.add_argument(
511 "--clean",
512 action="store_true",
513 default=False,
514 dest="clean",
515 help="Delete any relevant directories before building",
516 )
517 for subcommand in (
518 build,
519 configure_build,
520 configure_host,
521 build_python,
522 build_host,
523 ):
524 subcommand.add_argument(
525 "args", nargs="*", help="Extra arguments to pass to `configure`"
526 )
527 for subcommand in build, configure_host, build_host:
528 subcommand.add_argument(
529 "--wasi-sdk",
530 type=pathlib.Path,
531 dest="wasi_sdk_path",
532 default=default_wasi_sdk,
533 help=f"Path to the WASI SDK; defaults to {default_wasi_sdk}",
534 )
535 subcommand.add_argument(
536 "--host-runner",
537 action="store",
538 default=default_host_runner,
539 dest="host_runner",
540 help="Command template for running the WASI host; defaults to "
541 f"`{default_host_runner}`",
542 )
543 for subcommand in (
544 build,
545 configure_host,
546 make_host,
547 build_host,
548 pythoninfo_host,
549 ):
550 subcommand.add_argument(
551 "--host-triple",
552 action="store",
553 default=default_host_triple,
554 help="The target triple for the WASI host build; "
555 f"defaults to {default_host_triple}",
556 )
557
558 context = parser.parse_args()
559 context.init_dir = pathlib.Path().absolute()
560
561 build_build_python = build_steps(
562 configure_build_python,
563 make_build_python,
564 pythoninfo_build_python,
565 )
566 build_wasi_python = build_steps(
567 configure_wasi_python,
568 make_wasi_python,
569 pythoninfo_wasi_python,
570 )
571
572 dispatch = {
573 "configure-build-python": configure_build_python,
574 "make-build-python": make_build_python,
575 "build-python": build_build_python,
576 "pythoninfo-build": pythoninfo_build_python,
577 "configure-host": configure_wasi_python,
578 "make-host": make_wasi_python,
579 "build-host": build_wasi_python,
580 "pythoninfo-host": pythoninfo_wasi_python,
581 "build": build_steps(build_build_python, build_wasi_python),
582 "clean": clean_contents,
583 None: lambda args: parser.print_help(),
584 }
585 dispatch[context.subcommand](context)
586
587
588 if __name__ == "__main__":
589 main()