#!/usr/bin/env python3 """Portable native builder for curl-wasm via wasm2c + WASI 0.2 C host shim.""" import os import re import shlex import shutil import subprocess import sys 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 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] = [] prefixes: 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) brew_wabt = capture_cmd(["brew", "--prefix", "wabt"]) if shutil.which("brew") else None if brew_wabt: prefixes.append(brew_wabt) 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): 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"), ]) 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) 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: 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 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." ) def discover_openssl() -> 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"]) 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"] 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"]) try: rt_inc, rt_src, rt_lib = discover_wasm2c_runtime(wasm2c) except RuntimeError as e: sys.stderr.write(f"Error: {e}\n") return 1 openssl_cflags, openssl_libs = discover_openssl() 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())