Debian Codegraph @

Tools/wasm/wasi.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
20
21 CROSS_BUILD_DIR = CHECKOUT / "cross-build"
22 BUILD_DIR = CROSS_BUILD_DIR / "build"
23
24 LOCAL_SETUP = CHECKOUT / "Modules" / "Setup.local"
25 LOCAL_SETUP_MARKER = b"# Generated by Tools/wasm/wasi.py\n"
26
27 WASMTIME_VAR_NAME = "WASMTIME"
28 WASMTIME_HOST_RUNNER_VAR = f"{{{WASMTIME_VAR_NAME}}}"
29
30
31 def updated_env(updates={}):
32 """Create a new dict representing the environment to use.
33
34 The changes made to the execution environment are printed out.
35 """
36 env_defaults = {}
37 # https://reproducible-builds.org/docs/source-date-epoch/
38 git_epoch_cmd = ["git", "log", "-1", "--pretty=%ct"]
39 try:
40 epoch = subprocess.check_output(
41 git_epoch_cmd, encoding="utf-8"
42 ).strip()
43 env_defaults["SOURCE_DATE_EPOCH"] = epoch
44 except subprocess.CalledProcessError:
45 pass # Might be building from a tarball.
46 # This layering lets SOURCE_DATE_EPOCH from os.environ takes precedence.
47 environment = env_defaults | os.environ | updates
48
49 env_diff = {}
50 for key, value in environment.items():
51 if os.environ.get(key) != value:
52 env_diff[key] = value
53
54 print("๐ŸŒŽ Environment changes:")
55 for key in sorted(env_diff.keys()):
56 print(f" {key}={env_diff[key]}")
57
58 return environment
59
60
61 def subdir(working_dir, *, clean_ok=False):
62 """Decorator to change to a working directory."""
63
64 def decorator(func):
65 @functools.wraps(func)
66 def wrapper(context):
67 nonlocal working_dir
68
69 if callable(working_dir):
70 working_dir = working_dir(context)
71 try:
72 tput_output = subprocess.check_output(
73 ["tput", "cols"], encoding="utf-8"
74 )
75 except subprocess.CalledProcessError:
76 terminal_width = 80
77 else:
78 terminal_width = int(tput_output.strip())
79 print("โŽฏ" * terminal_width)
80 print("๐Ÿ“", working_dir)
81 if (
82 clean_ok
83 and getattr(context, "clean", False)
84 and working_dir.exists()
85 ):
86 print("๐Ÿšฎ Deleting directory (--clean)...")
87 shutil.rmtree(working_dir)
88
89 working_dir.mkdir(parents=True, exist_ok=True)
90
91 with contextlib.chdir(working_dir):
92 return func(context, working_dir)
93
94 return wrapper
95
96 return decorator
97
98
99 def call(command, *, quiet, **kwargs):
100 """Execute a command.
101
102 If 'quiet' is true, then redirect stdout and stderr to a temporary file.
103 """
104 print("โฏ", " ".join(map(str, command)))
105 if not quiet:
106 stdout = None
107 stderr = None
108 else:
109 stdout = tempfile.NamedTemporaryFile(
110 "w",
111 encoding="utf-8",
112 delete=False,
113 prefix="cpython-wasi-",
114 suffix=".log",
115 )
116 stderr = subprocess.STDOUT
117 print(f"๐Ÿ“ Logging output to {stdout.name} (--quiet)...")
118
119 subprocess.check_call(command, **kwargs, stdout=stdout, stderr=stderr)
120
121
122 def build_platform():
123 """The name of the build/host platform."""
124 # Can also be found via `config.guess`.`
125 return sysconfig.get_config_var("BUILD_GNU_TYPE")
126
127
128 def build_python_path():
129 """The path to the build Python binary."""
130 binary = BUILD_DIR / "python"
131 if not binary.is_file():
132 binary = binary.with_suffix(".exe")
133 if not binary.is_file():
134 raise FileNotFoundError(
135 f"Unable to find `python(.exe)` in {BUILD_DIR}"
136 )
137
138 return binary
139
140
141 @subdir(BUILD_DIR, clean_ok=True)
142 def configure_build_python(context, working_dir):
143 """Configure the build/host Python."""
144 if LOCAL_SETUP.exists():
145 print(f"๐Ÿ‘ {LOCAL_SETUP} exists ...")
146 else:
147 print(f"๐Ÿ“ Touching {LOCAL_SETUP} ...")
148 LOCAL_SETUP.write_bytes(LOCAL_SETUP_MARKER)
149
150 configure = [os.path.relpath(CHECKOUT / "configure", working_dir)]
151 if context.args:
152 configure.extend(context.args)
153
154 call(configure, quiet=context.quiet)
155
156
157 @subdir(BUILD_DIR)
158 def make_build_python(context, working_dir):
159 """Make/build the build Python."""
160 call(["make", "--jobs", str(cpu_count()), "all"], quiet=context.quiet)
161
162 binary = build_python_path()
163 cmd = [
164 binary,
165 "-c",
166 "import sys; "
167 "print(f'{sys.version_info.major}.{sys.version_info.minor}')",
168 ]
169 version = subprocess.check_output(cmd, encoding="utf-8").strip()
170
171 print(f"๐ŸŽ‰ {binary} {version}")
172
173
174 def find_wasi_sdk():
175 """Find the path to wasi-sdk."""
176 if wasi_sdk_path := os.environ.get("WASI_SDK_PATH"):
177 return pathlib.Path(wasi_sdk_path)
178 elif (default_path := pathlib.Path("/opt/wasi-sdk")).exists():
179 return default_path
180
181
182 def wasi_sdk_env(context):
183 """Calculate environment variables for building with wasi-sdk."""
184 wasi_sdk_path = context.wasi_sdk_path
185 sysroot = wasi_sdk_path / "share" / "wasi-sysroot"
186 env = {
187 "CC": "clang",
188 "CPP": "clang-cpp",
189 "CXX": "clang++",
190 "AR": "llvm-ar",
191 "RANLIB": "ranlib",
192 }
193
194 for env_var, binary_name in list(env.items()):
195 env[env_var] = os.fsdecode(wasi_sdk_path / "bin" / binary_name)
196
197 if wasi_sdk_path != pathlib.Path("/opt/wasi-sdk"):
198 for compiler in ["CC", "CPP", "CXX"]:
199 env[compiler] += f" --sysroot={sysroot}"
200
201 env["PKG_CONFIG_PATH"] = ""
202 env["PKG_CONFIG_LIBDIR"] = os.pathsep.join(
203 map(
204 os.fsdecode,
205 [sysroot / "lib" / "pkgconfig", sysroot / "share" / "pkgconfig"],
206 )
207 )
208 env["PKG_CONFIG_SYSROOT_DIR"] = os.fsdecode(sysroot)
209
210 env["WASI_SDK_PATH"] = os.fsdecode(wasi_sdk_path)
211 env["WASI_SYSROOT"] = os.fsdecode(sysroot)
212
213 env["PATH"] = os.pathsep.join([
214 os.fsdecode(wasi_sdk_path / "bin"),
215 os.environ["PATH"],
216 ])
217
218 return env
219
220
221 @subdir(lambda context: CROSS_BUILD_DIR / context.host_triple, clean_ok=True)
222 def configure_wasi_python(context, working_dir):
223 """Configure the WASI/host build."""
224 if not context.wasi_sdk_path or not context.wasi_sdk_path.exists():
225 raise ValueError(
226 "WASI-SDK not found; "
227 "download from "
228 "https://github.com/WebAssembly/wasi-sdk and/or "
229 "specify via $WASI_SDK_PATH or --wasi-sdk"
230 )
231
232 config_site = os.fsdecode(
233 CHECKOUT / "Tools" / "wasm" / "config.site-wasm32-wasi"
234 )
235
236 wasi_build_dir = working_dir.relative_to(CHECKOUT)
237
238 python_build_dir = BUILD_DIR / "build"
239 lib_dirs = list(python_build_dir.glob("lib.*"))
240 assert len(lib_dirs) == 1, (
241 f"Expected a single lib.* directory in {python_build_dir}"
242 )
243 lib_dir = os.fsdecode(lib_dirs[0])
244 pydebug = lib_dir.endswith("-pydebug")
245 python_version = lib_dir.removesuffix("-pydebug").rpartition("-")[-1]
246 sysconfig_data = f"{wasi_build_dir}/build/lib.wasi-wasm32-{python_version}"
247 if pydebug:
248 sysconfig_data += "-pydebug"
249
250 # Use PYTHONPATH to include sysconfig data which must be anchored to the
251 # WASI guest's `/` directory.
252 args = {
253 "GUEST_DIR": "/",
254 "HOST_DIR": CHECKOUT,
255 "ENV_VAR_NAME": "PYTHONPATH",
256 "ENV_VAR_VALUE": f"/{sysconfig_data}",
257 "PYTHON_WASM": working_dir / "python.wasm",
258 }
259 # Check dynamically for wasmtime in case it was specified manually via
260 # `--host-runner`.
261 if WASMTIME_HOST_RUNNER_VAR in context.host_runner:
262 if wasmtime := shutil.which("wasmtime"):
263 args[WASMTIME_VAR_NAME] = wasmtime
264 else:
265 raise FileNotFoundError(
266 "wasmtime not found; download from "
267 "https://github.com/bytecodealliance/wasmtime"
268 )
269 host_runner = context.host_runner.format_map(args)
270 env_additions = {"CONFIG_SITE": config_site, "HOSTRUNNER": host_runner}
271 build_python = os.fsdecode(build_python_path())
272 # The path to `configure` MUST be relative, else `python.wasm` is unable
273 # to find the stdlib due to Python not recognizing that it's being
274 # executed from within a checkout.
275 configure = [
276 os.path.relpath(CHECKOUT / "configure", working_dir),
277 f"--host={context.host_triple}",
278 f"--build={build_platform()}",
279 f"--with-build-python={build_python}",
280 ]
281 if pydebug:
282 configure.append("--with-pydebug")
283 if context.args:
284 configure.extend(context.args)
285 call(
286 configure,
287 env=updated_env(env_additions | wasi_sdk_env(context)),
288 quiet=context.quiet,
289 )
290
291 python_wasm = working_dir / "python.wasm"
292 exec_script = working_dir / "python.sh"
293 with exec_script.open("w", encoding="utf-8") as file:
294 file.write(f'#!/bin/sh\nexec {host_runner} {python_wasm} "$@"\n')
295 exec_script.chmod(0o755)
296 print(f"๐Ÿƒโ€โ™€๏ธ Created {exec_script} ... ")
297 sys.stdout.flush()
298
299
300 @subdir(lambda context: CROSS_BUILD_DIR / context.host_triple)
301 def make_wasi_python(context, working_dir):
302 """Run `make` for the WASI/host build."""
303 call(
304 ["make", "--jobs", str(cpu_count()), "all"],
305 env=updated_env(),
306 quiet=context.quiet,
307 )
308
309 exec_script = working_dir / "python.sh"
310 subprocess.check_call([exec_script, "--version"])
311
312
313 def build_all(context):
314 """Build everything."""
315 steps = [
316 configure_build_python,
317 make_build_python,
318 configure_wasi_python,
319 make_wasi_python,
320 ]
321 for step in steps:
322 step(context)
323
324
325 def clean_contents(context):
326 """Delete all files created by this script."""
327 if CROSS_BUILD_DIR.exists():
328 print(f"๐Ÿงน Deleting {CROSS_BUILD_DIR} ...")
329 shutil.rmtree(CROSS_BUILD_DIR)
330
331 if LOCAL_SETUP.exists():
332 with LOCAL_SETUP.open("rb") as file:
333 if file.read(len(LOCAL_SETUP_MARKER)) == LOCAL_SETUP_MARKER:
334 print(f"๐Ÿงน Deleting generated {LOCAL_SETUP} ...")
335
336
337 def main():
338 default_host_runner = (
339 f"{WASMTIME_HOST_RUNNER_VAR} run "
340 # Make sure the stack size will work for a pydebug
341 # build.
342 # The 8388608 value comes from `ulimit -s` under Linux
343 # which equates to 8291 KiB.
344 "--wasm max-wasm-stack=8388608 "
345 # Use WASI 0.2 primitives.
346 "--wasi preview2 "
347 # Enable thread support; causes use of preview1.
348 # "--wasm threads=y --wasi threads=y "
349 # Map the checkout to / to load the stdlib from /Lib.
350 "--dir {HOST_DIR}::{GUEST_DIR} "
351 # Set PYTHONPATH to the sysconfig data.
352 "--env {ENV_VAR_NAME}={ENV_VAR_VALUE}"
353 )
354
355 parser = argparse.ArgumentParser()
356 subcommands = parser.add_subparsers(dest="subcommand")
357 build = subcommands.add_parser("build", help="Build everything")
358 configure_build = subcommands.add_parser(
359 "configure-build-python", help="Run `configure` for the build Python"
360 )
361 make_build = subcommands.add_parser(
362 "make-build-python", help="Run `make` for the build Python"
363 )
364 configure_host = subcommands.add_parser(
365 "configure-host",
366 help="Run `configure` for the "
367 "host/WASI (pydebug builds "
368 "are inferred from the build "
369 "Python)",
370 )
371 make_host = subcommands.add_parser(
372 "make-host", help="Run `make` for the host/WASI"
373 )
374 subcommands.add_parser(
375 "clean", help="Delete files and directories created by this script"
376 )
377 for subcommand in (
378 build,
379 configure_build,
380 make_build,
381 configure_host,
382 make_host,
383 ):
384 subcommand.add_argument(
385 "--quiet",
386 action="store_true",
387 default=False,
388 dest="quiet",
389 help="Redirect output from subprocesses to a log file",
390 )
391 for subcommand in configure_build, configure_host:
392 subcommand.add_argument(
393 "--clean",
394 action="store_true",
395 default=False,
396 dest="clean",
397 help="Delete any relevant directories before building",
398 )
399 for subcommand in build, configure_build, configure_host:
400 subcommand.add_argument(
401 "args", nargs="*", help="Extra arguments to pass to `configure`"
402 )
403 for subcommand in build, configure_host:
404 subcommand.add_argument(
405 "--wasi-sdk",
406 type=pathlib.Path,
407 dest="wasi_sdk_path",
408 default=find_wasi_sdk(),
409 help="Path to wasi-sdk; defaults to "
410 "$WASI_SDK_PATH or /opt/wasi-sdk",
411 )
412 subcommand.add_argument(
413 "--host-runner",
414 action="store",
415 default=default_host_runner,
416 dest="host_runner",
417 help="Command template for running the WASI host "
418 "(default designed for wasmtime 14 or newer: "
419 f"`{default_host_runner}`)",
420 )
421 for subcommand in build, configure_host, make_host:
422 subcommand.add_argument(
423 "--host-triple",
424 action="store",
425 default="wasm32-wasip1",
426 help="The target triple for the WASI host build",
427 )
428
429 context = parser.parse_args()
430
431 dispatch = {
432 "configure-build-python": configure_build_python,
433 "make-build-python": make_build_python,
434 "configure-host": configure_wasi_python,
435 "make-host": make_wasi_python,
436 "build": build_all,
437 "clean": clean_contents,
438 }
439 dispatch[context.subcommand](context)
440
441
442 if __name__ == "__main__":
443 main()