Skip to main content

weirdnet_code_spaces/
native.rs

1//! Running cargo and loading libraries (the `native-plugins` feature; desktop only).
2use crate::error::Error;
3use crate::{Built, Env, Lang, Profile, Result, abi, build_key, cargo, generate, plugin_file, trust_hash_of, write_sdk};
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6use std::sync::{Mutex, OnceLock};
7
8fn copy_in(from: &Path, to: &Path) -> Result<()> {
9    let dir = to.parent().unwrap_or(Path::new("."));
10    std::fs::create_dir_all(dir)?;
11    let tmp = dir.join(format!(".{}.tmp{}", to.file_name().and_then(|n| n.to_str()).unwrap_or("plugin"), std::process::id()));
12    std::fs::copy(from, &tmp)?;
13    std::fs::rename(&tmp, to)?;
14    Ok(())
15}
16
17/// Build (or find in the cache) the plugin of a source. Cached libraries are content
18/// addressed and replaced by rename, never rewritten, so a loaded one stays valid. A
19/// `plugin` source is copied in under its trust hash. `log` gets cargo's output lines.
20pub fn build(p: &Profile, env: &Env, lang: Lang, source: &str, log: &mut dyn FnMut(&str)) -> Result<Built> {
21    if lang == Lang::Plugin {
22        let f = plugin_file(source);
23        let key = trust_hash_of(p, lang, source)?;
24        let out = env.plugin_path(&key);
25        let cached = out.exists();
26        if !cached {
27            copy_in(&f, &out)?;
28        }
29        return Ok(Built { path: out, key, cached });
30    }
31    let key = build_key(p, lang, source);
32    let out = env.plugin_path(&key);
33    if out.exists() {
34        return Ok(Built { path: out, key, cached: true });
35    }
36    let cargo = cargo(p)?;
37    write_sdk(p, &env.sdk_dir(p))?;
38    let dir = env.build_dir(&key);
39    generate(p, lang, source, &dir)?;
40    log(&format!("building {} code ({key})…", lang.as_str()));
41    let mut child = std::process::Command::new(&cargo)
42        .args(["build", "--release", "--color", "never", "--manifest-path"])
43        .arg(dir.join("Cargo.toml"))
44        .env("CARGO_TARGET_DIR", &env.target)
45        .stdin(std::process::Stdio::null())
46        .stdout(std::process::Stdio::null())
47        .stderr(std::process::Stdio::piped())
48        .spawn()
49        .map_err(|e| Error::missing("Rust toolchain", format!("could not run {}: {e}", cargo.display())))?;
50    let mut lines = vec![];
51    if let Some(err) = child.stderr.take() {
52        use std::io::BufRead;
53        for l in std::io::BufReader::new(err).lines().map_while(std::result::Result::ok) {
54            log(&l);
55            lines.push(l);
56        }
57    }
58    let status = child.wait()?;
59    if !status.success() {
60        let tail = lines.len().saturating_sub(80);
61        return Err(Error::Build(format!("build failed (lines refer to the generated crate in {}):\n{}", dir.display(), lines[tail..].join("\n"))));
62    }
63    let lib = env.target.join("release").join(format!("{}{}{key}{}", std::env::consts::DLL_PREFIX, p.crate_prefix, std::env::consts::DLL_SUFFIX));
64    copy_in(&lib, &out)?;
65    log(&format!("built {}", out.display()));
66    Ok(Built { path: out, key, cached: false })
67}
68
69/// A loaded plugin: its run function (call it with a host table) and its info JSON.
70#[derive(Clone, Copy)]
71pub struct Loaded {
72    pub run: abi::PluginRun,
73    pub info: &'static str,
74}
75
76impl std::fmt::Debug for Loaded {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        write!(f, "Loaded({})", self.info)
79    }
80}
81
82/// Loaded libraries by path, symbol name and ABI version (a profile with other symbols or
83/// another version checks the library again).
84type Libraries = Mutex<HashMap<(PathBuf, &'static str, u32), Loaded>>;
85static LOADED: OnceLock<Libraries> = OnceLock::new();
86
87/// Load a plugin (once per process and profile; libraries stay loaded) after checking it
88/// exports the profile's symbols and ABI version.
89///
90/// Loading runs the library's initializers with the process's rights: load only what the
91/// owner approved (see [`crate::approved`]), from the cache [`build`] fills.
92pub fn load(p: &Profile, path: &Path) -> Result<Loaded> {
93    let map = LOADED.get_or_init(Default::default);
94    let mut map = map.lock().unwrap_or_else(|e| e.into_inner());
95    let id = (path.to_path_buf(), p.symbols[0], p.abi_version);
96    if let Some(l) = map.get(&id) {
97        return Ok(*l);
98    }
99    let bad = |m: String| Error::invalid("plugin", format!("{}: {m}", path.display()));
100    let [sym_abi, sym_info, sym_run] = p.symbols;
101    // SAFETY: loading runs the library's initializers; the owner approved this code. The
102    // library is never unloaded, so its symbols stay valid.
103    let lib: &'static libloading::Library = Box::leak(Box::new(unsafe { libloading::Library::new(path) }.map_err(|e| bad(e.to_string()))?));
104    // SAFETY: the symbols are looked up with the ABI's signatures; the version is checked
105    // before info and run are used.
106    let loaded = unsafe {
107        let abi_fn = lib.get::<abi::PluginAbi>(sym_abi.as_bytes()).map_err(|_| bad(format!("not a {} plugin (no {sym_abi})", p.app)))?;
108        let v = abi_fn();
109        if v != p.abi_version {
110            return Err(bad(format!(
111                "built for plugin ABI {v}; this {} speaks ABI {} — rebuild it against {} {}",
112                p.app, p.abi_version, p.sdk_package, p.sdk_version
113            )));
114        }
115        let info_fn = lib.get::<abi::PluginInfo>(sym_info.as_bytes()).map_err(|_| bad(format!("no {sym_info}")))?;
116        let info = std::str::from_utf8(info_fn().as_bytes()).map_err(|_| bad("info is not UTF-8".into()))?;
117        let run = *lib.get::<abi::PluginRun>(sym_run.as_bytes()).map_err(|_| bad(format!("no {sym_run}")))?;
118        Loaded { run, info }
119    };
120    map.insert(id, loaded);
121    Ok(loaded)
122}
123
124/// Run a loaded plugin with `host` (a host table of the profile's ABI version). Returns the
125/// plugin's code ([`abi::RUN_OK`], `RUN_ERROR`, `RUN_PANIC`, or what else it returned).
126///
127/// The plugin runs as native code with the process's rights: run only what the owner
128/// approved ([`crate::approved`]); [`load`] has checked its ABI.
129pub fn run(p: &Profile, plugin: &Loaded, host: &mut dyn crate::Host) -> i32 {
130    // SAFETY: `plugin` was loaded with its ABI checked against this profile.
131    unsafe { crate::host::run_with(p.abi_version, plugin.run, host) }
132}