From ed06fa994acb48f0ed0585ef751d1c04f15d9f60 Mon Sep 17 00:00:00 2001 From: Sprite Date: Fri, 20 Nov 2026 00:28:24 +0000 Subject: [PATCH] Support Pixi/Conda wasm2c trampolines and runtime fetch fallback Resolve Pixi trampoline_configuration/wasm2c.json and Conda/Pixi env prefixes in native/build_native.py, add automatic version-matched runtime download from WebAssembly/wabt into build/wasm2c-rt-/ when binary-only packages (such as conda-forge wabt) omit wasm-rt.h/wasm-rt-impl.c, search Conda/Pixi prefixes for OpenSSL with rpath, and update README.md. --- README.md | 2 +- native/build_native.py | 191 +++++++++++++++++++++++++++++++++++------ 2 files changed, 167 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 48f853d..3750e02 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ just run-native -fsSI https://example.com just test-native ``` -If WABT's `wasm2c` runtime sources (`wasm-rt.h` and `wasm-rt-impl.c`) live in a non-standard path, set `WASM2C_RUNTIME_DIR=/path/to/wabt/wasm2c`. +If WABT's `wasm2c` runtime sources (`wasm-rt.h` and `wasm-rt-impl.c`) are not found locally (e.g. Pixi/Conda packages that omit headers), `just native` automatically fetches the version-matched runtime files from `WebAssembly/wabt` into `build/`, or honors `WASM2C_RUNTIME_DIR=/path/to/wabt/wasm2c`. ## Supported Options diff --git a/native/build_native.py b/native/build_native.py index fef03e9..9013d58 100755 --- a/native/build_native.py +++ b/native/build_native.py @@ -1,12 +1,16 @@ #!/usr/bin/env python3 """Portable native builder for curl-wasm via wasm2c + WASI 0.2 C host shim.""" +import glob +import json import os import re import shlex import shutil import subprocess import sys +import urllib.error +import urllib.request def run_cmd(cmd: list[str]) -> None: @@ -56,33 +60,158 @@ def is_complete_src_dir(d: str) -> bool: ) -def discover_wasm2c_runtime(wasm2c_path: str) -> tuple[str, str | None, str | None]: - """Return (include_dir, source_dir_or_None, static_lib_or_None).""" - searched: list[str] = [] +def _prefix_from_exe(exe_path: str) -> str: + parent = os.path.dirname(exe_path) + return os.path.dirname(parent) if os.path.basename(parent) == "bin" else parent + + +def resolve_env_prefixes(wasm2c_path: str) -> list[str]: prefixes: list[str] = [] + pixi_homes: list[str] = [] - for p in (wasm2c_path, os.path.realpath(wasm2c_path)): - bindir = os.path.dirname(p) - if os.path.basename(bindir) == "bin": - prefixes.append(os.path.dirname(bindir)) - else: - prefixes.append(bindir) + for candidate_bin in unique_dirs([wasm2c_path, os.path.realpath(wasm2c_path)]): + prefixes.append(_prefix_from_exe(candidate_bin)) + bindir = os.path.dirname(candidate_bin) + tc_dir = os.path.join(bindir, "trampoline_configuration") + for cfg_name in ("wasm2c.json", "wasm2c.exe.json"): + cfg_path = os.path.join(tc_dir, cfg_name) + if os.path.isfile(cfg_path): + try: + with open(cfg_path, "r", encoding="utf-8") as f: + cfg = json.load(f) + if isinstance(cfg, dict): + for key in ("exe", "original_exe"): + exe_val = cfg.get(key) + if isinstance(exe_val, str) and exe_val: + for base in (bindir, tc_dir): + resolved = os.path.normpath( + exe_val if os.path.isabs(exe_val) else os.path.join(base, exe_val) + ) + prefixes.append(_prefix_from_exe(resolved)) + except (OSError, ValueError): + pass + if os.path.basename(bindir) == "bin" and os.path.basename(os.path.dirname(bindir)) == ".pixi": + pixi_homes.append(os.path.dirname(bindir)) + + conda_prefix = os.environ.get("CONDA_PREFIX", "").strip() + if conda_prefix: + prefixes.append(conda_prefix) + + pixi_home_env = os.environ.get("PIXI_HOME", "").strip() + if pixi_home_env: + pixi_homes.append(pixi_home_env) + default_pixi = os.path.expanduser("~/.pixi") + if os.path.isdir(default_pixi): + pixi_homes.append(default_pixi) + + for ph in unique_dirs(pixi_homes): + wabt_env = os.path.join(ph, "envs", "wabt") + if os.path.isdir(wabt_env): + prefixes.append(wabt_env) + for env_dir in sorted(glob.glob(os.path.join(ph, "envs", "*"))): + if os.path.isdir(env_dir): + prefixes.append(env_dir) + + return unique_dirs(prefixes) + + +def fetch_wasm2c_runtime(wasm2c_path: str, cache_root: str) -> str: + ver_out = capture_cmd([wasm2c_path, "--version"]) + m = re.search(r"(\d+\.\d+\.\d+)", ver_out or "") + if not m: + raise RuntimeError(f"Could not determine wasm2c version from '{wasm2c_path} --version'") + ver = m.group(1) + + cache_dir = os.path.join(cache_root, f"wasm2c-rt-{ver}") + if os.path.isfile(os.path.join(cache_dir, "wasm-rt.h")) and is_complete_src_dir(cache_dir): + return cache_dir + + os.makedirs(cache_dir, exist_ok=True) + base_url = f"https://raw.githubusercontent.com/WebAssembly/wabt/{ver}/wasm2c/" + + def download_file(name: str, required: bool) -> bool: + dst = os.path.join(cache_dir, name) + url = base_url + name + try: + with urllib.request.urlopen(url, timeout=20) as resp: + data = resp.read() + with open(dst, "wb") as f: + f.write(data) + return True + except urllib.error.HTTPError as e: + if e.code == 404 and not required: + return False + raise RuntimeError(f"HTTP {e.code} fetching {url}") from e + except urllib.error.URLError as e: + raise RuntimeError(f"Failed fetching {url}: {e.reason}") from e + + required = ["wasm-rt.h", "wasm-rt-impl.h", "wasm-rt-impl.c"] + optional = [ + "wasm-rt-exceptions.h", + "wasm-rt-exceptions-impl.c", + "wasm-rt-mem-impl.c", + "wasm-rt-impl-tableops.inc", + "wasm-rt-mem-impl-helper.inc", + ] + + print(f"Downloading WABT {ver} wasm2c runtime from {base_url} -> {cache_dir}", flush=True) + downloaded: set[str] = set() + for fname in required: + download_file(fname, required=True) + downloaded.add(fname) + for fname in optional: + if download_file(fname, required=False): + downloaded.add(fname) + + # Fetch any additional local header/inc includes referenced by downloaded runtime files. + scanned: set[str] = set() + while scanned != downloaded: + pending = sorted(downloaded - scanned) + for fname in pending: + scanned.add(fname) + fpath = os.path.join(cache_dir, fname) + with open(fpath, "r", encoding="utf-8", errors="ignore") as f: + txt = f.read() + for inc in re.findall(r'#\s*include\s+"([^"]+\.(?:h|inc))"', txt): + inc_name = os.path.basename(inc) + if inc_name not in downloaded: + if download_file(inc_name, required=False): + downloaded.add(inc_name) + + if not os.path.isfile(os.path.join(cache_dir, "wasm-rt.h")) or not is_complete_src_dir(cache_dir): + raise RuntimeError(f"Downloaded WABT {ver} runtime in {cache_dir} is incomplete") + return cache_dir + + +def discover_wasm2c_runtime( + wasm2c_path: str, extra_prefixes: list[str], cache_root: str +) -> tuple[str, str | None, str | None]: + """Return (include_dir, source_dir_or_None, static_lib_or_None).""" + env_dir = os.environ.get("WASM2C_RUNTIME_DIR", "").strip() + if env_dir: + norm_env = os.path.normpath(env_dir) + if os.path.isfile(os.path.join(norm_env, "wasm-rt.h")) and is_complete_src_dir(norm_env): + return norm_env, norm_env, None + raise RuntimeError( + f"WASM2C_RUNTIME_DIR='{env_dir}' does not contain a complete wasm2c runtime " + "(expected wasm-rt.h, wasm-rt-impl.h, wasm-rt-impl.c, and referenced .inc files)." + ) + + prefixes = list(extra_prefixes) brew_wabt = capture_cmd(["brew", "--prefix", "wabt"]) if shutil.which("brew") else None if brew_wabt: prefixes.append(brew_wabt) + prefixes = unique_dirs(prefixes) candidates: list[str] = [] - env_dir = os.environ.get("WASM2C_RUNTIME_DIR", "").strip() - if env_dir: - candidates.append(env_dir) - - for pref in unique_dirs(prefixes): + for pref in prefixes: candidates.extend([ os.path.join(pref, "share", "wabt", "wasm2c"), os.path.join(pref, "share", "wasm2c"), os.path.join(pref, "wasm2c"), os.path.join(pref, "src", "wasm2c"), + os.path.join(pref, "include", "wasm2c"), ]) candidates.extend([ @@ -92,9 +221,7 @@ def discover_wasm2c_runtime(wasm2c_path: str) -> tuple[str, str | None, str | No "/usr/share/wabt/wasm2c", "/usr/share/wasm2c", ]) - candidates = unique_dirs(candidates) - searched.extend(candidates) # 1. Prefer a single complete directory containing wasm-rt.h, wasm-rt-impl.c, and all .inc files. for d in candidates: @@ -128,14 +255,20 @@ def discover_wasm2c_runtime(wasm2c_path: str) -> tuple[str, str | None, str | No if os.path.isfile(a_path): return inc_dir, None, a_path - raise RuntimeError( - "Could not locate WABT wasm2c runtime (wasm-rt.h and wasm-rt-impl.c).\n" - f"Searched: {', '.join(searched)}\n" - "Set WASM2C_RUNTIME_DIR=/path/to/wabt/wasm2c and retry." - ) + # 3. Package omitted runtime sources (e.g. conda-forge/pixi wabt): fetch version-matched WABT files. + try: + fetched_dir = fetch_wasm2c_runtime(wasm2c_path, cache_root) + return fetched_dir, fetched_dir, None + except RuntimeError as dl_err: + raise RuntimeError( + "Could not locate WABT wasm2c runtime (wasm-rt.h and wasm-rt-impl.c).\n" + f"Searched local paths: {', '.join(candidates)}\n" + f"Auto-download fallback failed: {dl_err}\n" + "Set WASM2C_RUNTIME_DIR=/path/to/wabt/wasm2c and retry." + ) from dl_err -def discover_openssl() -> tuple[list[str], list[str]]: +def discover_openssl(extra_prefixes: list[str]) -> tuple[list[str], list[str]]: env_cflags = os.environ.get("OPENSSL_CFLAGS", "").strip() env_libs = os.environ.get("OPENSSL_LIBS", "").strip() if env_cflags or env_libs: @@ -154,10 +287,17 @@ def discover_openssl() -> tuple[list[str], list[str]]: if p: prefixes.append(p) prefixes.extend(["/opt/homebrew/opt/openssl@3", "/usr/local/opt/openssl@3"]) + prefixes.extend(extra_prefixes) for p in unique_dirs(prefixes): if os.path.isfile(os.path.join(p, "include", "openssl", "ssl.h")): - return [f"-I{os.path.join(p, 'include')}"], [f"-L{os.path.join(p, 'lib')}", "-lssl", "-lcrypto"] + inc_flag = f"-I{os.path.join(p, 'include')}" + lib_dir = os.path.join(p, "lib") + libs = [f"-L{lib_dir}"] + if p not in ("/usr", "/usr/local") and sys.platform != "win32": + libs.append(f"-Wl,-rpath,{lib_dir}") + libs.extend(["-lssl", "-lcrypto"]) + return [inc_flag], libs return [], ["-lssl", "-lcrypto"] @@ -173,13 +313,14 @@ def main() -> int: run_cmd([wasm2c, "build/mem_mod.wasm", "-n", "mem_mod", "-o", "build/mem_mod.c"]) run_cmd([wasm2c, "build/curl_core.wasm", "-n", "curl_core", "-o", "build/curl_core.c"]) + env_prefixes = resolve_env_prefixes(wasm2c) try: - rt_inc, rt_src, rt_lib = discover_wasm2c_runtime(wasm2c) + rt_inc, rt_src, rt_lib = discover_wasm2c_runtime(wasm2c, env_prefixes, "build") except RuntimeError as e: sys.stderr.write(f"Error: {e}\n") return 1 - openssl_cflags, openssl_libs = discover_openssl() + openssl_cflags, openssl_libs = discover_openssl(env_prefixes) cc = shlex.split(os.environ.get("CC", "cc")) rt_inc_flags = [f"-I{rt_inc}"]