#[path = "build_fetch.rs"]
mod fetch;
#[path = "build_icu.rs"]
mod icu;
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
const BUN_HOOKS: [&str; 8] = [
"Bun__reportUnhandledError",
"Bun__thisThreadHasVM",
"WTFTimer__cancel",
"WTFTimer__create",
"WTFTimer__deinit",
"WTFTimer__isActive",
"WTFTimer__secondsUntilTimer",
"WTFTimer__update",
];
const WINDOWS_WEBKIT_LIBS: &[&str] = &["JavaScriptCore", "WTF", "bmalloc", "sicudt", "sicuin", "sicuuc"];
const WINDOWS_SYSTEM_LIBS: &[&str] = &[
"user32",
"ole32",
"oleaut32",
"advapi32",
"shell32",
"shlwapi",
"winmm",
"bcrypt",
"dbghelp",
"userenv",
"ws2_32",
"synchronization",
"usp10",
"rpcrt4",
"crypt32",
"ntdll",
];
const ENGINE_IMPORTERS: &[&str] = &["aot.rs", "capi.rs", "glue.rs", "icu.rs", "profiling.rs", "web.rs"];
const TRAMPOLINE_COUNT: usize = 2048;
fn main() {
let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let windows = target_os == "windows";
let platform = match (target_os.as_str(), target_arch.as_str()) {
("windows", "x86_64") => "windows-amd64",
("linux", "x86_64") => "linux-amd64",
("macos", "x86_64") => "macos-amd64",
("macos", "aarch64") => "macos-arm64",
_ => panic!("redjs has no pinned prebuilt for {target_os}/{target_arch}"),
};
generate_trampolines(&out_dir);
let pins_path = manifest.join("pins.txt");
let pins = read_pins(&pins_path);
println!("cargo:rerun-if-changed={}", pins_path.display());
println!("cargo:webkit_version={}", pin(&pins, "webkit.version"));
println!("cargo:rustc-check-cfg=cfg(redjs_icu_root)");
if env::var_os("DOCS_RS").is_some() {
println!("cargo:rustc-check-cfg=cfg(redjs_engine_dll)");
return;
}
if windows && !env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or_default().split(',').any(|f| f == "crt-static") {
panic!(
"\n\nredjs links the static CRT on Windows: the JavaScriptCore prebuilt and its C++ glue are /MT,\n\
and mixing them with the dynamic CRT gives two heaps in one process. Add to .cargo/config.toml:\n\n\
[target.x86_64-pc-windows-msvc]\n\
rustflags = [\"-C\", \"target-feature=+crt-static\"]\n"
);
}
println!("cargo:rerun-if-env-changed=REDJS_ENGINE_DLL");
println!("cargo:rustc-check-cfg=cfg(redjs_engine_dll)");
let engine_dll = env::var("REDJS_ENGINE_DLL").ok().filter(|name| windows && !name.is_empty());
if let Some(name) = &engine_dll {
assert!(
name.ends_with(".dll") && !name.contains(['/', '\\', ':', '"']),
"REDJS_ENGINE_DLL must be a file name ending in .dll"
);
println!("cargo:rustc-cfg=redjs_engine_dll");
}
let webkit = fetch::webkit(&manifest, platform, windows, &pins);
let lib = webkit.join("lib");
let inc = webkit.join("include");
check_prebuilt(&webkit, &pins);
println!("cargo:webkit_dir={}", webkit.display());
let mimalloc = fetch::mimalloc(&manifest, &pins);
let mut glue = native_build(true, windows);
glue.file("cpp/glue.cpp")
.include(&inc)
.include("cpp/compat") .define("NDEBUG", None)
.define("STATICALLY_LINKED_WITH_JavaScriptCore", "1")
.define("STATICALLY_LINKED_WITH_WTF", "1")
.define("STATICALLY_LINKED_WITH_BMALLOC", "1")
.define("BUILDING_WITH_CMAKE", "1");
if windows {
glue.flag("/std:c++23preview")
.flag("/W0")
.flag("-Wno-inconsistent-dllimport")
.flag("/FIcmakeconfig.h")
.define("NOMINMAX", None)
.define("WIN32", None)
.define("_WINDOWS", None)
.define("WIN32_LEAN_AND_MEAN", "1")
.define("_CRT_SECURE_NO_WARNINGS", None);
} else {
glue.opt_level(2)
.flag("-std=c++23")
.flag("-include")
.flag("cmakeconfig.h")
.flag("-fno-exceptions")
.flag("-fno-rtti")
.flag("-w")
.define("BUILDING_JSCONLY__", None);
}
let configuration = fs::read_to_string(inc.join("cmakeconfig.h"))
.expect("the checked WebKit configuration is readable");
if configuration
.lines()
.any(|line| line.trim() == "#define BUN_WEBKIT_ENABLE_AOT 1")
{
let generated = inc.join("JavaScriptCore").join("aot");
let native_aot = std::env::var_os("CARGO_FEATURE_NATIVE_AOT").is_some();
println!("cargo:rerun-if-env-changed=REDJS_AOT_BUILTIN_TABLE_DIR");
let table = if native_aot {
let table = PathBuf::from(std::env::var_os("REDJS_AOT_BUILTIN_TABLE_DIR").expect(
"the native-aot feature needs REDJS_AOT_BUILTIN_TABLE_DIR: the builtin table generated by the \
AOT frontend at Bun 237bba51e for this engine. Build without native-aot otherwise.",
));
let receipt = fs::read_to_string(table.join(".redjs-aot-table"))
.expect("native-aot table lacks its pinned generation receipt");
assert!(
receipt.contains("237bba51e98a8b3d5b62d2d6c33853c2e83820a7")
&& receipt.contains(pin(&pins, "webkit.version")),
"AOT frontend/engine receipt mismatch"
);
table
} else {
generated.clone()
};
if native_aot {
println!("cargo:rustc-env=REDJS_AOT_TARGET_ARCH={target_arch}");
println!("cargo:rustc-env=REDJS_AOT_TARGET_OS={target_os}");
println!(
"cargo:rustc-env=REDJS_AOT_ENGINE_VERSION={}",
pin(&pins, "webkit.version")
);
use sha2::{Digest, Sha256};
let mut hash = Sha256::new();
for file in [
".redjs-aot-table",
"AOTBuiltinTableArrays.h",
"AOTBuiltinTableAttachments.cpp",
"AOTBuiltinTableBuiltins.cpp",
"AOTBuiltinTableNames.cpp",
"AOTBuiltinTableOverloads.cpp",
"AOTBuiltinTableTypes.cpp",
] {
let path = table.join(file);
println!("cargo:rerun-if-changed={}", path.display());
hash.update(file.as_bytes());
hash.update(fs::read(path).expect("AOT table input missing"));
}
hash.update(
fs::read(inc.join("JavaScriptCore/aot/AOTWire.cpp"))
.expect("AOT schema hash missing"),
);
println!("cargo:rustc-env=REDJS_AOT_TABLE_ID={:x}", hash.finalize());
glue.file("cpp/aot.cpp");
}
glue.include(inc.join("JavaScriptCore"))
.include(&generated)
.include("cpp/aot")
.file("cpp/aot_support.cpp");
for name in [
"AOTBuiltinTableAttachments.cpp",
"AOTBuiltinTableBuiltins.cpp",
"AOTBuiltinTableEngineBindings.cpp",
"AOTBuiltinTableNames.cpp",
"AOTBuiltinTableOverloads.cpp",
"AOTBuiltinTableTypes.cpp",
"AOTSchemaInlineBuiltins.cpp",
] {
if !windows
&& (name == "AOTBuiltinTableEngineBindings.cpp"
|| name == "AOTSchemaInlineBuiltins.cpp")
{
continue;
}
let source = if name == "AOTBuiltinTableEngineBindings.cpp"
|| name == "AOTSchemaInlineBuiltins.cpp"
{
generated.join(name)
} else {
table.join(name)
};
assert!(
source.is_file(),
"AOT prebuilt lacks generated source {}",
source.display()
);
println!("cargo:rerun-if-changed={}", source.display());
glue.file(source);
}
println!("cargo:rerun-if-changed=cpp/aot_support.cpp");
println!("cargo:rerun-if-changed=cpp/aot.cpp");
println!("cargo:rerun-if-changed=cpp/aot");
}
if engine_dll.is_some() {
glue.file("cpp/engine_dll.cpp");
println!("cargo:rerun-if-changed=cpp/engine_dll.cpp");
}
let mut allocator = native_build(true, windows);
if windows {
allocator.flag("/TP");
} else {
allocator.flag("-x").flag("c++");
}
allocator
.file(mimalloc.join("src").join("static.c"))
.include(mimalloc.join("include"))
.flag("-w")
.define("MI_STATIC_LIB", None)
.define("MI_SKIP_COLLECT_ON_EXIT", "1")
.define("MI_NO_PROCESS_DETACH", "1")
.define("MI_FREE_USE_PAGEMAP", "1")
.define("MI_BUILD_RELEASE", None)
.define("MI_CMAKE_BUILD_TYPE", "release");
let sqlite = env::var_os("CARGO_FEATURE_INDEXEDDB_SQLITE").is_some().then(|| {
let mc = fetch::sqlite3mc(&manifest, &pins);
let mut sqlite = native_build(false, windows);
if windows {
sqlite
.flag("/Gy")
.flag("/Gw")
.define("_CRT_SECURE_NO_WARNINGS", None);
} else {
sqlite.flag("-ffunction-sections").flag("-fdata-sections");
}
sqlite
.file("cpp/idb_sqlite.c")
.include(&mc)
.opt_level_str("s")
.flag("-w")
.define("NDEBUG", None);
println!("cargo:rerun-if-changed=cpp/idb_sqlite.c");
println!("cargo:rerun-if-changed={}", mc.join(".redjs-pin").display());
sqlite
});
let (glue_objects, allocator_objects, sqlite_objects) = std::thread::scope(|s| {
let allocator = s.spawn(|| allocator.compile_intermediates());
let sqlite = s.spawn(|| sqlite.as_ref().map(cc::Build::compile_intermediates));
let glue = glue.compile_intermediates();
(glue, allocator.join().unwrap(), sqlite.join().unwrap())
});
let archive = |cpp: bool, objects: Vec<PathBuf>, metadata: bool, name: &str| {
native_build(cpp, windows).objects(objects).cargo_metadata(metadata).compile(name);
};
archive(true, glue_objects, engine_dll.is_none(), "redjs_glue");
archive(true, allocator_objects, engine_dll.is_none(), "redjs_mimalloc");
if let Some(objects) = sqlite_objects {
archive(false, objects, true, "redjs_sqlite");
}
let icu_root = (env::var_os("CARGO_FEATURE_ICU_ROOT").is_some() && target_os != "macos")
.then(|| link_icu_root(&manifest, &out_dir, &lib, windows, &target_arch, platform, &pins));
if let Some(name) = &engine_dll {
link_engine_dll(&manifest, &out_dir, &lib, name, icu_root.as_deref());
} else {
if windows {
if let Some(stripped) = webkit_without_debug_info(&out_dir, &lib) {
println!("cargo:rustc-link-search=native={}", stripped.display());
}
}
println!("cargo:rustc-link-search=native={}", lib.display());
}
let libraries: &[&str] = if engine_dll.is_some() {
&[]
} else if windows {
WINDOWS_WEBKIT_LIBS
} else if target_os == "linux" {
for name in ["icui18n", "icuuc", "icudata"] {
let alias = out_dir.join(format!("libredjs_{name}.a"));
let _ = std::fs::remove_file(&alias);
link_alias(&lib.join(format!("lib{name}.a")), &alias)
.unwrap_or_else(|e| panic!("linking {} to Bun's lib{name}.a: {e}", alias.display()));
}
println!("cargo:rustc-link-search=native={}", out_dir.display());
&[
"JavaScriptCore",
"WTF",
"bmalloc",
"redjs_icui18n",
"redjs_icuuc",
"redjs_icudata",
]
} else {
&["JavaScriptCore", "WTF", "bmalloc"]
};
for l in libraries {
let l = match *l {
"sicudt" | "redjs_icudata" if icu_root.is_some() => ICU_ROOT_LIB,
l => l,
};
println!("cargo:rustc-link-lib=static:-bundle={l}");
}
if windows {
if engine_dll.is_none() {
for l in WINDOWS_SYSTEM_LIBS {
println!("cargo:rustc-link-lib=dylib={l}");
}
}
} else if target_os == "linux" {
for library in ["dl", "pthread", "m", "rt", "atomic"] {
println!("cargo:rustc-link-lib=dylib={library}");
}
} else {
println!("cargo:rustc-link-lib=dylib=icucore");
for framework in ["CoreFoundation", "Foundation", "Security"] {
println!("cargo:rustc-link-lib=framework={framework}");
}
if target_os == "macos" {
for symbol in BUN_HOOKS {
println!("cargo:rustc-link-arg=-Wl,-U,_{symbol}");
}
}
}
if windows {
println!("cargo:rustc-link-arg=/OPT:NOICF");
}
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=cpp/glue.cpp");
println!("cargo:rerun-if-changed=cpp/compat/wtf/PlatformEnableWin.h");
println!(
"cargo:rerun-if-changed={}",
mimalloc.join(".redjs-pin").display()
);
println!(
"cargo:rerun-if-changed={}",
inc.join("cmakeconfig.h").display()
);
}
const ICU_ROOT_LIB: &str = "redjs_icudata_root";
fn link_icu_root(
manifest: &Path,
out_dir: &Path,
webkit_lib: &Path,
windows: bool,
arch: &str,
platform: &str,
pins: &[(String, String)],
) -> PathBuf {
let library = webkit_lib.join(if windows { "sicudt.lib" } else { "libicudata.a" });
let keep_path = manifest.join("icu-root.txt");
println!("cargo:rerun-if-changed={}", keep_path.display());
println!("cargo:rerun-if-changed=build_icu.rs");
let keep_text = fs::read_to_string(&keep_path).expect("icu-root.txt is readable");
let keep: Vec<&str> =
keep_text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).collect();
let full = icu::read(&library, windows);
let root = icu::subset(&full, &keep);
let hash = icu::sha256(&root);
let key = format!("icu.root.{platform}.sha256");
match pins.iter().find(|(k, _)| *k == key) {
Some((_, want)) => assert_eq!(
&hash, want,
"the root-only ICU data built from {} is not the one pins.txt names ({key}): \
the prebuilt or icu-root.txt changed. Check the change, then pin the new hash.",
library.display()
),
None => panic!("pins.txt has no `{key}`; the root-only ICU data built here is {hash}"),
}
let object = out_dir.join(if windows { "icudata_root.obj" } else { "icudata_root.o" });
fs::write(&object, icu::object(&full.symbol, &root, &full.dict, windows, arch)).unwrap();
native_build(false, windows).object(&object).cargo_metadata(false).compile(ICU_ROOT_LIB);
println!("cargo:rustc-cfg=redjs_icu_root");
let name = format!("{}.dat", full.package);
let dat = out_dir.join(&name);
fs::write(&dat, &full.data).unwrap();
println!("cargo:icu_full_data={}", dat.display());
println!("cargo:rustc-env=REDJS_ICU_FULL_DATA={}", dat.display());
if let Some(profile) = out_dir.ancestors().nth(3) {
fs::copy(&dat, profile.join(&name)).unwrap_or_else(|e| panic!("copying {name} to {}: {e}", profile.display()));
}
out_dir.join(if windows { format!("{ICU_ROOT_LIB}.lib") } else { format!("lib{ICU_ROOT_LIB}.a") })
}
fn webkit_without_debug_info(out_dir: &Path, webkit_lib: &Path) -> Option<PathBuf> {
println!("cargo:rerun-if-env-changed=REDJS_WEBKIT_DEBUG_INFO");
if env::var("REDJS_WEBKIT_DEBUG_INFO").is_ok_and(|v| v == "1") {
return None;
}
if out_dir.ancestors().nth(3)?.file_name()? != "debug" {
return None;
}
let sysroot = std::process::Command::new(env::var_os("RUSTC")?).args(["--print", "sysroot"]).output().ok()?;
let objcopy = PathBuf::from(String::from_utf8(sysroot.stdout).ok()?.trim())
.join("lib/rustlib")
.join(env::var("HOST").ok()?)
.join("bin")
.join(format!("rust-objcopy{}", env::consts::EXE_SUFFIX));
let dir = out_dir.join("webkit-no-debug-info");
fs::create_dir_all(&dir).ok()?;
for name in ["JavaScriptCore.lib", "WTF.lib"] {
let status = std::process::Command::new(&objcopy)
.arg("--strip-debug")
.arg(webkit_lib.join(name))
.arg(dir.join(name))
.status();
if !status.is_ok_and(|s| s.success()) {
return None;
}
}
Some(dir)
}
fn link_engine_dll(manifest: &Path, out_dir: &Path, webkit_lib: &Path, name: &str, icu_root: Option<&Path>) {
let target = env::var("TARGET").unwrap();
let tool = |name: &str| {
cc::windows_registry::find_tool(&target, "link.exe")
.unwrap_or_else(|| panic!("REDJS_ENGINE_DLL needs the MSVC linker ({name})"))
.to_command()
};
let mut libraries: Vec<PathBuf> = ["redjs_glue.lib", "redjs_mimalloc.lib"].iter().map(|l| out_dir.join(l)).collect();
libraries.extend(WINDOWS_WEBKIT_LIBS.iter().map(|l| match icu_root {
Some(root) if *l == "sicudt" => root.to_path_buf(),
_ => webkit_lib.join(format!("{l}.lib")),
}));
let mut defined = std::collections::HashSet::new();
let mut mimalloc = Vec::new();
for library in &libraries {
let output = tool("link /dump")
.args(["/dump", "/nologo", "/linkermember:1"])
.arg(library)
.output()
.unwrap_or_else(|e| panic!("link /dump {}: {e}", library.display()));
assert!(output.status.success(), "link /dump {} failed", library.display());
for line in String::from_utf8_lossy(&output.stdout).lines() {
let mut words = line.split_whitespace();
if let (Some(offset), Some(symbol), None) = (words.next(), words.next(), words.next()) {
if u64::from_str_radix(offset, 16).is_ok() {
if library.ends_with("redjs_mimalloc.lib") && symbol.starts_with("mi_") {
mimalloc.push(symbol.to_owned());
}
defined.insert(symbol.to_owned());
}
}
}
}
let mut exports = std::collections::BTreeSet::new();
for file in ENGINE_IMPORTERS {
let path = manifest.join("src").join(file);
println!("cargo:rerun-if-changed={}", path.display());
let text = fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
exports.extend(extern_c_names(&text).into_iter().filter(|n| defined.contains(n)));
}
exports.extend(mimalloc);
for required in ["rjs_init", "rjs_set_icu_decompress", "rjs_icu_zstd_dict", "JSGlobalContextCreate"] {
assert!(exports.contains(required), "the engine DLL would not export {required}");
}
let stem = name.trim_end_matches(".dll");
let def = out_dir.join(format!("{stem}.def"));
let mut text = format!("LIBRARY \"{name}\"\nEXPORTS\n");
for export in &exports {
writeln!(text, " {export}").unwrap();
}
fs::write(&def, text).unwrap();
let dll = out_dir.join(name);
let implib = out_dir.join("redjs_engine.lib");
let output = tool("link")
.args(["/nologo", "/DLL", "/MACHINE:X64", "/INCREMENTAL:NO", "/OPT:REF", "/OPT:NOICF", "/Brepro"])
.arg(format!("/OUT:{}", dll.display()))
.arg(format!("/IMPLIB:{}", implib.display()))
.arg(format!("/DEF:{}", def.display()))
.args(&libraries)
.args(WINDOWS_SYSTEM_LIBS.iter().map(|l| format!("{l}.lib")))
.output()
.expect("cannot run the MSVC linker for the engine DLL");
assert!(
output.status.success(),
"linking {name} failed:\n{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
println!("cargo:rustc-link-search=native={}", out_dir.display());
println!("cargo:rustc-link-lib=dylib=redjs_engine");
if let Some(profile) = out_dir.ancestors().nth(3) {
for directory in [profile.to_path_buf(), profile.join("deps")] {
if directory.is_dir() {
fs::copy(&dll, directory.join(name)).unwrap_or_else(|e| panic!("copying {name} to {}: {e}", directory.display()));
}
}
}
}
fn extern_c_names(text: &str) -> Vec<String> {
let mut names = Vec::new();
let mut rest = text;
while let Some(at) = rest.find("extern \"C\" {") {
let body = &rest[at + "extern \"C\" {".len()..];
let mut depth = 1;
let mut end = body.len();
for (i, c) in body.char_indices() {
match c {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
end = i;
break;
}
}
_ => {}
}
}
let block = &body[..end];
let words: Vec<&str> = block
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.filter(|w| !w.is_empty())
.collect();
for pair in words.windows(2) {
if pair[0] == "fn" || pair[0] == "static" {
let name = if pair[1] == "mut" { continue } else { pair[1] };
names.push(name.to_owned());
}
}
for triple in words.windows(3) {
if triple[0] == "static" && triple[1] == "mut" {
names.push(triple[2].to_owned());
}
}
rest = &body[end..];
}
names
}
fn native_build(cpp: bool, windows: bool) -> cc::Build {
let mut build = cc::Build::new();
build.cpp(cpp);
if windows {
build.compiler("clang-cl").static_crt(true);
} else {
let variable = if cpp { "CXX" } else { "CC" };
let compiler =
env::var(variable).unwrap_or_else(|_| if cpp { "clang++" } else { "clang" }.into());
build.compiler(compiler).pic(true);
}
build
}
fn read_pins(path: &Path) -> Vec<(String, String)> {
let text = fs::read_to_string(path).unwrap_or_else(|e| {
panic!(
"cannot read {}: {e} — it pins the prebuilt redjs builds against",
path.display()
)
});
text.lines()
.filter_map(|raw| {
let line = raw.split('#').next().unwrap().trim();
let (k, v) = line.split_once('=')?;
Some((k.trim().to_owned(), v.trim().to_owned()))
})
.collect()
}
fn pin<'a>(pins: &'a [(String, String)], key: &str) -> &'a str {
pins.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
.unwrap_or_else(|| panic!("pins.txt has no `{key}`"))
}
fn check_prebuilt(webkit: &Path, pins: &[(String, String)]) {
let want = pin(pins, "webkit.version");
let cfg = webkit.join("include").join("cmakeconfig.h");
let fix = "Point BUN_WEBKIT_DIR at an extraction of the pinned tarball, or unset it to let redjs \
fetch the pinned prebuilt.";
let Ok(text) = fs::read_to_string(&cfg) else {
panic!(
"\n\nno bun-webkit prebuilt at {} (missing include/cmakeconfig.h).\n{fix}\n\
pins.txt wants {want}.\n",
webkit.display()
);
};
let have = text
.lines()
.find_map(|l| l.trim().strip_prefix("#define BUN_WEBKIT_VERSION "))
.map(|v| v.trim().trim_matches('"').to_owned());
match have {
Some(have) if have == want => {}
have => panic!(
"\n\nthe bun-webkit prebuilt at {} is {}, but redjs pins {want} (pins.txt).\n\
Building would compile the glue against one engine's internal headers and link\n\
whatever is on disk — refusing.\n{fix}\n",
webkit.display(),
have.as_deref()
.unwrap_or("unidentified (no BUN_WEBKIT_VERSION)"),
),
}
let want_aot = pin(pins, "webkit.aot");
let have_aot = text
.lines()
.find_map(|line| line.trim().strip_prefix("#define BUN_WEBKIT_ENABLE_AOT "))
.map(str::trim);
assert_eq!(
have_aot,
Some(want_aot),
"JSC AOT variant mismatch at {}: wanted ENABLE_AOT={want_aot}. {fix}",
webkit.display()
);
let library = if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
"JavaScriptCore.lib"
} else {
"libJavaScriptCore.a"
};
if !webkit.join("lib").join(library).is_file() {
panic!(
"\n\n{} names the pinned build but has no lib/{library} — an interrupted \
extraction?\n{fix}\n",
webkit.display()
);
}
}
fn generate_trampolines(out_dir: &std::path::Path) {
let abi = if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
"sysv64"
} else {
"C"
};
let mut s = String::with_capacity(TRAMPOLINE_COUNT * 160);
let _ = writeln!(
s,
"// @generated by build.rs — SysV entry points for host functions.\n\
pub(crate) const TRAMPOLINE_COUNT: usize = {TRAMPOLINE_COUNT};\n"
);
for i in 0..TRAMPOLINE_COUNT {
let _ = writeln!(
s,
"unsafe extern \"{abi}\" fn t{i}(g: *mut core::ffi::c_void, cf: *mut core::ffi::c_void) -> u64 {{ crate::trampoline::dispatch({i}, g, cf) }}"
);
}
let _ = writeln!(
s,
"pub(crate) static TRAMPOLINES: [unsafe extern \"{abi}\" fn(*mut core::ffi::c_void, *mut core::ffi::c_void) -> u64; {TRAMPOLINE_COUNT}] = ["
);
for i in 0..TRAMPOLINE_COUNT {
let _ = writeln!(s, " t{i},");
}
let _ = writeln!(s, "];");
fs::write(out_dir.join("trampolines.rs"), s).unwrap();
}
fn link_alias(target: &std::path::Path, alias: &std::path::Path) -> std::io::Result<()> {
#[cfg(unix)]
return std::os::unix::fs::symlink(target, alias);
#[cfg(not(unix))]
return std::fs::copy(target, alias).map(|_| ());
}