#!/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: print(" ".join(shlex.quote(c) for c in cmd), flush=True) subprocess.run(cmd, check=True) def capture_cmd(cmd: list[str]) -> str | None: try: res = subprocess.run(cmd, check=True, capture_output=True, text=True) return res.stdout.strip() except (OSError, subprocess.CalledProcessError): return None def unique_dirs(dirs: list[str]) -> list[str]: seen: set[str] = set() out: list[str] = [] for d in dirs: if not d: continue norm = os.path.normpath(d) if norm not in seen: seen.add(norm) out.append(norm) return out def has_all_inc(rt_dir: str) -> bool: for fname in ("wasm-rt-impl.c", "wasm-rt-mem-impl.c", "wasm-rt-exceptions-impl.c"): fpath = os.path.join(rt_dir, fname) if not os.path.isfile(fpath): continue with open(fpath, "r", encoding="utf-8", errors="ignore") as f: txt = f.read() for inc in re.findall(r'#\s*include\s+"([^"]+\.inc)"', txt): if not os.path.isfile(os.path.join(rt_dir, inc)): return False return True def is_complete_src_dir(d: str) -> bool: return ( os.path.isfile(os.path.join(d, "wasm-rt-impl.c")) and os.path.isfile(os.path.join(d, "wasm-rt-impl.h")) and has_all_inc(d) ) 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 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] = [] 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([ "/usr/src/wasm2c", "/opt/homebrew/share/wabt/wasm2c", "/usr/local/share/wabt/wasm2c", "/usr/share/wabt/wasm2c", "/usr/share/wasm2c", ]) candidates = unique_dirs(candidates) # 1. Prefer a single complete directory containing wasm-rt.h, wasm-rt-impl.c, and all .inc files. for d in candidates: if os.path.isfile(os.path.join(d, "wasm-rt.h")) and is_complete_src_dir(d): return d, d, None # 2. Fallback: locate header dir and either a complete source dir or libwasm-rt-impl.a. header_candidates = unique_dirs( candidates + [os.path.join(p, "include") for p in prefixes] + ["/usr/include", "/opt/homebrew/include", "/usr/local/include"] ) inc_dir = next((d for d in header_candidates if os.path.isfile(os.path.join(d, "wasm-rt.h"))), None) if inc_dir: src_dir = next((d for d in candidates if is_complete_src_dir(d)), None) if src_dir: return inc_dir, src_dir, None lib_dirs = unique_dirs( [os.path.join(p, "lib") for p in prefixes] + [ "/usr/lib", "/usr/lib/x86_64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/usr/local/lib", "/opt/homebrew/lib", ] ) for ld in lib_dirs: a_path = os.path.join(ld, "libwasm-rt-impl.a") if os.path.isfile(a_path): return inc_dir, None, a_path # 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(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: return shlex.split(env_cflags), (shlex.split(env_libs) if env_libs else ["-lssl", "-lcrypto"]) if shutil.which("pkg-config"): cflags = capture_cmd(["pkg-config", "--cflags", "openssl"]) libs = capture_cmd(["pkg-config", "--libs", "openssl"]) if libs is not None: return shlex.split(cflags or ""), shlex.split(libs) prefixes: list[str] = [] if shutil.which("brew"): for pkg in ("openssl@3", "openssl"): p = capture_cmd(["brew", "--prefix", pkg]) 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")): 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"] def main() -> int: wasm2c = shutil.which("wasm2c") if not wasm2c: sys.stderr.write("Error: 'wasm2c' not found in PATH. Install WABT (wabt) first.\n") return 1 os.makedirs("build", exist_ok=True) run_cmd([sys.executable, "native/extract_core.py", "curl.wasm", "build"]) 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, env_prefixes, "build") except RuntimeError as e: sys.stderr.write(f"Error: {e}\n") return 1 openssl_cflags, openssl_libs = discover_openssl(env_prefixes) cc = shlex.split(os.environ.get("CC", "cc")) rt_inc_flags = [f"-I{rt_inc}"] if rt_src and rt_src != rt_inc: rt_inc_flags.append(f"-I{rt_src}") objs: list[str] = [] for name in ("mem_mod", "curl_core"): c_file = os.path.join("build", f"{name}.c") o_file = os.path.join("build", f"{name}.o") run_cmd(cc + ["-O2", "-w", "-Ibuild"] + rt_inc_flags + ["-c", c_file, "-o", o_file]) objs.append(o_file) if rt_src: for rt_name in ("wasm-rt-impl.c", "wasm-rt-mem-impl.c", "wasm-rt-exceptions-impl.c"): rt_c = os.path.join(rt_src, rt_name) if os.path.isfile(rt_c): rt_o = os.path.join("build", rt_name[:-2] + ".o") run_cmd(cc + ["-O2", "-w"] + rt_inc_flags + ["-c", rt_c, "-o", rt_o]) objs.append(rt_o) host_o = os.path.join("build", "wasi_host.o") run_cmd( cc + ["-O2", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-Ibuild"] + rt_inc_flags + openssl_cflags + ["-c", "native/wasi_host.c", "-o", host_o] ) objs.append(host_o) link_cmd = cc + ["-O2"] + objs if rt_lib: link_cmd.append(rt_lib) link_cmd.extend(openssl_libs) link_cmd.extend(["-lm", "-pthread", "-o", "curl-native"]) run_cmd(link_cmd) return 0 if __name__ == "__main__": sys.exit(main())