Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-tauritestshost.rs

1.4.2Released Nov 21, 2026

host.rs

773 lines37.1 KBRust
//! The plugin host process end to end, driven over its pipe the way the app drives it, with the test plugin//! (host/testplug, built by build.rs in debug builds): the scan child, audio through a ring in shared memory, offline//! render, state, parameters, bypass, the editor window, a plugin that crashes, one that hangs, and modules outside the//! plugin folders. The page's side of the ring is played by ring.rs's own page_quantum, the worklet's twin.#![cfg(debug_assertions)]#[path = "../src/plugins/proto.rs"]#[allow(dead_code)]mod proto;#[path = "../src/plugins/ring.rs"]#[allow(dead_code)]mod ring;#[path = "../src/plugins/pe.rs"]#[allow(dead_code)]mod pe;#[path = "../src/plugins/scan.rs"]#[allow(dead_code)]mod scan;use proto::{Event, Frame, Reply, Request, KIND_EVENT, KIND_REQUEST, KIND_RESPONSE};use serde_json::{json, Value};use std::io::Read;use std::os::windows::io::AsRawHandle;use std::path::{Path, PathBuf};use std::process::{Child, ChildStdin, Command, Stdio};use std::sync::atomic::AtomicBool;use std::sync::mpsc::{self, Receiver};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use windows::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE, INVALID_HANDLE_VALUE};use windows::Win32::System::Memory::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, FILE_MAP_ALL_ACCESS, PAGE_READWRITE};use windows::Win32::System::Threading::GetCurrentProcess;const HOST: &str = env!("CARGO_BIN_EXE_juicewrld-plugins");const DLL: &str = env!("JW_TEST_PLUGIN");const GAIN: &str = "4A57544741494E50524F433100000001";const CRASH: &str = "4A574352415348310000000000000003";const SYNTH: &str = "4A5753594E5448310000000000000004";/// A folder of the test's own, under JW_TEST_DIR when set (a run on a PC with plugins keeps everything it builds and/// loads in one scratch folder), else the system's temp folder. Only the test plugin is ever put in it.fn folder(name: &str) -> PathBuf {    let base = std::env::var_os("JW_TEST_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir);    let d = base.join(format!("jw-host-{name}-{}", std::process::id()));    let _ = std::fs::remove_dir_all(&d);    std::fs::create_dir_all(&d).unwrap();    d}/// The test plugin as a bundle in `dir`, under `name`.fn bundle(dir: &Path, name: &str) -> PathBuf {    let b = dir.join(format!("{name}.vst3"));    let bin = b.join("Contents").join("x86_64-win");    std::fs::create_dir_all(&bin).unwrap();    std::fs::copy(DLL, bin.join(format!("{name}.vst3"))).unwrap();    b}struct Host {    child: Child,    stdin: ChildStdin,    frames: Receiver<Frame>,    events: Vec<Event>,    stderr: Arc<Mutex<String>>,    next: u32,}impl Host {    fn start(roots: &[&Path]) -> Host {        Host::start_owned(roots, 0)    }    /// The host told that `owner` (a window handle, as the app passes its main window's) owns its editors.    fn start_owned(roots: &[&Path], owner: u64) -> Host {        // Editors open without focus, behind every other window, however the tests are run (debug builds only).        let mut child = Command::new(HOST)            .arg("--host")            .env("JW_NO_FOCUS", "1")            .stdin(Stdio::piped())            .stdout(Stdio::piped())            .stderr(Stdio::piped())            .spawn()            .unwrap();        let stdin = child.stdin.take().unwrap();        let mut stdout = child.stdout.take().unwrap();        let mut err = child.stderr.take().unwrap();        let (tx, frames) = mpsc::channel();        std::thread::spawn(move || {            while let Ok(Some(f)) = proto::read_frame(&mut stdout) {                if tx.send(f).is_err() {                    break;                }            }        });        let stderr = Arc::new(Mutex::new(String::new()));        let log = stderr.clone();        std::thread::spawn(move || {            let mut buf = [0u8; 4096];            while let Ok(n) = err.read(&mut buf) {                if n == 0 {                    break;                }                log.lock().unwrap().push_str(&String::from_utf8_lossy(&buf[..n]));            }        });        let mut h = Host { child, stdin, frames, events: Vec::new(), stderr, next: 1 };        let roots = roots.iter().map(|r| r.to_string_lossy().to_string()).collect();        h.ask(&Request::Hello { version: proto::VERSION, roots, owner }, vec![]).unwrap();        h    }    fn ask(&mut self, req: &Request, bytes: Vec<u8>) -> Result<(Value, Vec<u8>), String> {        self.ask_within(req, bytes, Duration::from_secs(20))    }    fn ask_within(&mut self, req: &Request, bytes: Vec<u8>, limit: Duration) -> Result<(Value, Vec<u8>), String> {        let id = self.next;        self.next += 1;        proto::write_frame(&mut self.stdin, &Frame::new(KIND_REQUEST, id, req, bytes)).map_err(|e| e.to_string())?;        let t0 = Instant::now();        loop {            let f = self.frames.recv_timeout(limit.saturating_sub(t0.elapsed())).map_err(|_| "no answer".to_string())?;            match f.kind {                KIND_RESPONSE if f.id == id => {                    return match serde_json::from_slice::<Reply>(&f.json).unwrap() {                        Reply::Ok(v) => Ok((v, f.bytes)),                        Reply::Err(e) => Err(e),                    };                }                KIND_EVENT => self.events.push(serde_json::from_slice(&f.json).unwrap()),                _ => {}            }        }    }    /// Events that came in while waiting `wait`.    fn drain(&mut self, wait: Duration) {        let t0 = Instant::now();        while let Ok(f) = self.frames.recv_timeout(wait.saturating_sub(t0.elapsed())) {            if f.kind == KIND_EVENT {                self.events.push(serde_json::from_slice(&f.json).unwrap());            }        }    }    fn open(&mut self, module: &Path, cid: &str, block: u32, offline: bool) -> proto::Opened {        let req = Request::Open { module: module.to_string_lossy().to_string(), cid: cid.into(), rate: 48000.0, block, offline };        serde_json::from_value(self.ask(&req, vec![]).unwrap().0).unwrap()    }    fn render(&mut self, inst: u32, left: &[f32], right: &[f32]) -> (Vec<f32>, Vec<f32>) {        let mut body = Vec::with_capacity(left.len() * 8);        for x in left.iter().chain(right) {            body.extend_from_slice(&x.to_le_bytes());        }        let (_, out) = self.ask(&Request::Render { inst, frames: left.len() as u32 }, body).unwrap();        let f: Vec<f32> = out.chunks(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();        let (l, r) = f.split_at(left.len());        (l.to_vec(), r.to_vec())    }    /// Handles the host process holds now.    fn handles(&self) -> u32 {        let mut n = 0u32;        unsafe {            let _ = windows::Win32::System::Threading::GetProcessHandleCount(HANDLE(self.child.as_raw_handle()), &mut n);        }        n    }    fn exit(&mut self, within: Duration) -> Option<std::process::ExitStatus> {        let t0 = Instant::now();        while t0.elapsed() < within {            if let Ok(Some(s)) = self.child.try_wait() {                return Some(s);            }            std::thread::sleep(Duration::from_millis(20));        }        None    }}impl Drop for Host {    fn drop(&mut self) {        let _ = self.child.kill();    }}/// A ring in a file mapping of this process, shared with the host the way the app shares WebView2's.struct Shm {    mapping: HANDLE,    base: *mut u8,    len: usize,    ring: ring::Ring,    layout: ring::Layout,}impl Shm {    fn new(latency: u32, block: u32, mode: u32) -> Shm {        let capacity = ring::capacity_for(latency, block);        let len = ring::bytes_for(capacity);        unsafe {            let mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, None, PAGE_READWRITE, 0, len as u32, None).unwrap();            let base = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, len).Value as *mut u8;            let ring = ring::Ring::new(base, len);            let layout = ring::Layout { channels: 2, capacity, latency, mode, rate: 48000, max_block: block };            ring.init(layout).unwrap();            Shm { mapping, base, len, ring, layout }        }    }    fn give(&self, host: &Host) -> u64 {        let mut out = HANDLE::default();        unsafe { DuplicateHandle(GetCurrentProcess(), self.mapping, HANDLE(host.child.as_raw_handle()), &mut out, 0, false, DUPLICATE_SAME_ACCESS).unwrap() };        out.0 as usize as u64    }}impl Drop for Shm {    fn drop(&mut self) {        unsafe {            let _ = UnmapViewOfFile(windows::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: self.base as *mut _ });            let _ = CloseHandle(self.mapping);        }    }}/// Plays `seconds` of `signal` through the ring as Chromium's audio thread would (bursts of four quanta every 10.7 ms),/// returning what came back.fn play(shm: &Shm, seconds: f64, signal: impl Fn(usize) -> f32) -> Vec<f32> {    let quanta = (seconds * 48000.0 / 128.0) as usize;    let mut heard = Vec::with_capacity(quanta * 128);    let t0 = Instant::now();    for q in 0..quanta {        let input: Vec<f32> = (0..128).map(|i| signal(q * 128 + i)).collect();        let (mut l, mut r) = (vec![0f32; 128], vec![0f32; 128]);        shm.ring.page_quantum(&shm.layout, [&input, &input], [&mut l, &mut r]);        heard.extend_from_slice(&l);        if q % 4 == 3 {            let due = t0 + Duration::from_secs_f64((q + 1) as f64 * 128.0 / 48000.0);            if let Some(wait) = due.checked_duration_since(Instant::now()) {                std::thread::sleep(wait);            }        }    }    heard}#[test]fn the_scan_child_reads_modules_and_survives_bad_ones() {    let d = folder("scan");    let exe = Path::new(HOST);    let stop = AtomicBool::new(false);    let good = bundle(&d, "JW Test");    let (vendor, classes) = scan::load_in_child(exe, &good, Duration::from_secs(20), &stop).unwrap();    assert_eq!(vendor, "juicewrld.io tests");    let names: Vec<_> = classes.iter().map(|c| (c.name.as_str(), c.category.as_str())).collect();    assert_eq!(        names,        [            ("JW Test Gain", "Audio Module Class"),            ("JW Test Gain", "Component Controller Class"),            ("JW Test Crash", "Audio Module Class"),            ("JW Test Synth", "Audio Module Class"),        ]    );    assert_eq!(classes[0].cid, GAIN);    assert_eq!(classes[3].sub_categories, ["Instrument", "Synth"]);    // The older single-file layout loads the same.    let single = d.join("JW Single.vst3");    std::fs::copy(DLL, &single).unwrap();    assert_eq!(scan::load_in_child(exe, &single, Duration::from_secs(20), &stop).unwrap().1.len(), 4);    // A module that never finishes loading is stopped at the limit; one that crashes says so; one with no classes has none.    let t0 = Instant::now();    let hang = scan::load_in_child(exe, &bundle(&d, "JW scan-hang"), Duration::from_secs(3), &stop).unwrap_err();    assert_eq!(hang.problem, scan::Problem::Timeout);    assert!(hang.message.contains("within 3 s"), "{hang:?}");    assert!(t0.elapsed() < Duration::from_secs(6));    let crash = scan::load_in_child(exe, &bundle(&d, "JW scan-crash"), Duration::from_secs(20), &stop).unwrap_err();    assert_eq!(crash.problem, scan::Problem::Crashed);    assert!(crash.message.contains("crashed as it loaded") && crash.message.contains("0xC0000005"), "{crash:?}");    assert!(scan::load_in_child(exe, &bundle(&d, "JW noclasses"), Duration::from_secs(20), &stop).unwrap().1.is_empty());    // Not a DLL at all.    let fake = d.join("Fake.vst3");    std::fs::write(&fake, b"MZ not really").unwrap();    assert_eq!(scan::load_in_child(exe, &fake, Duration::from_secs(20), &stop).unwrap_err().problem, scan::Problem::Failed);    // The whole scan over that folder: bundles with a moduleinfo.json are read without loading.    let info = bundle(&d, "JW Info");    std::fs::create_dir_all(info.join("Contents").join("Resources")).unwrap();    std::fs::write(        scan::moduleinfo_path(&info),        r#"{"Factory Info": {"Vendor": "juicewrld.io tests",}, "Classes": [{"CID": "4A57544741494E50524F433100000001", "Category": "Audio Module Class", "Name": "JW Test Gain", "Version": "1.0.0", "Sub Categories": ["Fx", "Tools",],},],}"#,    )    .unwrap();    let mut load = |m: &Path| scan::load_in_child(exe, m, Duration::from_secs(3), &stop);    let (cache, stats) = scan::scan(&[d.clone()], &scan::Cache::default(), &Default::default(), &stop, &mut load, &mut |_| {});    assert_eq!(cache.modules[&info.to_string_lossy().to_string()].source, "moduleinfo");    assert_eq!(stats.modules, 7);    assert_eq!(stats.failed, 3, "{:?}", cache.modules.iter().filter(|(_, m)| m.error.is_some()).map(|(p, m)| (p, &m.error)).collect::<Vec<_>>());    let found = scan::plugins(&cache);    let kinds: Vec<_> = found.iter().map(|f| (f.plugin.name.as_str(), f.plugin.kind.as_str())).collect();    assert_eq!(kinds, [("JW Test Crash", "effect"), ("JW Test Gain", "effect"), ("JW Test Synth", "instrument")]);    let _ = std::fs::remove_dir_all(&d);}#[test]fn audio_through_the_ring_comes_back_gained_and_delayed_exactly() {    let d = folder("ring");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let o = host.open(&module, GAIN, 128, false);    assert_eq!((o.inputs, o.outputs, o.latency, o.params, o.bypass_param, o.has_editor), (2, 2, 64, 2, true, true));    // Gain 0.25 normalized is half (the plugin's gain is 2x the value): exact in floating point.    host.ask(&Request::SetParam { inst: o.inst, id: 0, value: 0.25 }, vec![]).unwrap();    let shm = Shm::new(1024, 128, ring::MODE_REALTIME);    host.ask(&Request::Attach { inst: o.inst, handle: shm.give(&host), size: shm.len as u64 }, vec![]).unwrap();    let signal = |i: usize| ((i as f64) * 0.013).sin() as f32;    let heard = play(&shm, 3.0, signal);    let delay = 1024 + 64;    for (i, &v) in heard.iter().enumerate() {        let want = if i < delay { 0.0 } else { signal(i - delay) * 0.5 };        assert_eq!(v, want, "frame {i}");    }    assert_eq!(shm.ring.get(ring::at::UNDERRUNS), 0);    assert_eq!(shm.ring.get(ring::at::STATE), ring::STATE_RUNNING);    assert_eq!(shm.ring.get(ring::at::PLUGIN_LATENCY), 64);    // Detached, it stops serving.    host.ask(&Request::Detach { inst: o.inst }, vec![]).unwrap();    std::thread::sleep(Duration::from_millis(100));    assert_eq!(shm.ring.get(ring::at::STATE), ring::STATE_STOPPED);    host.ask(&Request::Close { inst: o.inst }, vec![]).unwrap();}#[test]fn offline_render_state_parameters_and_bypass() {    let d = folder("render");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let o = host.open(&module, GAIN, 512, true);    let n = 48000;    let left: Vec<f32> = (0..n).map(|i| (i % 100) as f32 / 100.0).collect();    let right: Vec<f32> = left.iter().map(|x| -x).collect();    // Unity gain (the default 0.5): the input, 64 samples late.    let (l, r) = host.render(o.inst, &left, &right);    assert_eq!(l.len(), n);    for i in 0..n {        let (wl, wr) = if i < 64 { (0.0, 0.0) } else { (left[i - 64], right[i - 64]) };        assert_eq!((l[i], r[i]), (wl, wr), "frame {i}");    }    // Parameters, as the controller describes them.    let params: Vec<proto::Param> = serde_json::from_value(host.ask(&Request::Params { inst: o.inst }, vec![]).unwrap().0).unwrap();    assert_eq!(params.len(), 2);    assert_eq!((params[0].title.as_str(), params[0].display.as_str(), params[0].units.as_str()), ("Gain", "0.0 dB", "dB"));    assert!(params[1].bypass && params[1].steps == 1);    // State: saved at one gain, restored after another.    host.ask(&Request::SetParam { inst: o.inst, id: 0, value: 0.1 }, vec![]).unwrap();    host.render(o.inst, &left[..512], &right[..512]); // the processor takes the value with a block    let (info, saved) = host.ask(&Request::GetState { inst: o.inst }, vec![]).unwrap();    assert_eq!(info["component"], json!(12));    assert_eq!(info["controller"], json!(8));    host.ask(&Request::SetParam { inst: o.inst, id: 0, value: 0.9 }, vec![]).unwrap();    host.ask(&Request::SetState { inst: o.inst }, saved.clone()).unwrap();    let params: Vec<proto::Param> = serde_json::from_value(host.ask(&Request::Params { inst: o.inst }, vec![]).unwrap().0).unwrap();    assert!((params[0].value - 0.1).abs() < 1e-6, "{}", params[0].value);    let (l, _) = host.render(o.inst, &vec![1.0; 2048], &vec![1.0; 2048]);    assert!((l[2000] - 0.2).abs() < 1e-6, "gain 0.2 after the restore, got {}", l[2000]);    // The state names its plugin: another plugin refuses it, and so does a scrambled one.    let crash = host.open(&module, CRASH, 512, true);    assert!(host.ask(&Request::SetState { inst: crash.inst }, saved.clone()).unwrap_err().contains("another plugin"));    assert!(host.ask(&Request::SetState { inst: o.inst }, b"garbage".to_vec()).is_err());    // Bypass (the plugin's own parameter): the dry signal, still 64 samples late.    let (v, _) = host.ask(&Request::Bypass { inst: o.inst, on: true }, vec![]).unwrap();    assert_eq!(v["plugin"], json!(true));    let (l, _) = host.render(o.inst, &left[..4096], &right[..4096]);    assert_eq!(l[1000], left[1000 - 64]);    // Reset keeps the latency and clears the delay line.    let (v, _) = host.ask(&Request::Reset { inst: o.inst }, vec![]).unwrap();    assert_eq!(v["latency"], json!(64));    let (l, _) = host.render(o.inst, &vec![0.5; 64], &vec![0.5; 64]);    assert!(l.iter().all(|&x| x == 0.0), "the delay line was cleared");    // An instrument: no input, a sine out.    let synth = host.open(&module, SYNTH, 512, true);    let (l, _) = host.render(synth.inst, &vec![0.0; 4800], &vec![0.0; 4800]);    let peak = l.iter().fold(0f32, |m, x| m.max(x.abs()));    assert!((peak - 0.25).abs() < 0.01, "{peak}");}/// Parameter changes made while no audio flows (the studio stopped, no node yet): however many, they're all taken,/// the newest reaches the processor without a block (a parameter flush), so the state saved and the audio played after/// are what the controller shows.#[test]fn parameter_changes_while_no_audio_flows_reach_the_processor() {    let d = folder("params");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let o = host.open(&module, GAIN, 512, true);    // Far more moves than any queue would hold, ending at 0.1, then 0.25 (gain 0.5).    for i in 0..5000 {        let v = if i == 4999 { 0.1 } else { 0.05 + (i % 7) as f64 * 0.01 };        host.ask(&Request::SetParam { inst: o.inst, id: 0, value: v }, vec![]).unwrap();    }    host.ask(&Request::SetParam { inst: o.inst, id: 0, value: 0.25 }, vec![]).unwrap();    // The state, saved before any audio: the processor's gain is the newest (0.5, as an f32 after the magic).    let (_, saved) = host.ask(&Request::GetState { inst: o.inst }, vec![]).unwrap();    let (_, component, _) = proto::state::unpack(&saved).unwrap();    let gain = f32::from_le_bytes(component[4..8].try_into().unwrap());    assert_eq!(gain, 0.5, "the component's state has the newest value");    // And the audio plays it.    let (l, _) = host.render(o.inst, &vec![1.0; 1024], &vec![1.0; 1024]);    assert_eq!(l[1000], 0.5);    host.ask(&Request::Close { inst: o.inst }, vec![]).unwrap();}/// Opening and closing instances (each with a stream) leaves nothing behind in the host: no handle per instance (the/// audio thread's MMCSS registration is given back), no thread.#[test]fn instances_opened_and_closed_leave_no_handles_behind() {    let d = folder("leak");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let warm = host.open(&module, GAIN, 128, false);    host.ask(&Request::Close { inst: warm.inst }, vec![]).unwrap();    std::thread::sleep(Duration::from_millis(300));    let before = host.handles();    for _ in 0..60 {        let o = host.open(&module, GAIN, 128, false);        let shm = Shm::new(512, 128, ring::MODE_REALTIME);        host.ask(&Request::Attach { inst: o.inst, handle: shm.give(&host), size: shm.len as u64 }, vec![]).unwrap();        play(&shm, 0.02, |_| 0.0);        host.ask(&Request::Close { inst: o.inst }, vec![]).unwrap();    }    std::thread::sleep(Duration::from_millis(300));    let after = host.handles();    assert!(after <= before + 5, "60 instances opened and closed: {before} handles, then {after}");}#[test]fn the_editor_opens_in_its_own_window_and_closes() {    let d = folder("editor");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let o = host.open(&module, GAIN, 128, false);    let (v, _) = host.ask(&Request::Editor { inst: o.inst, show: true, title: "JW Test Gain (Insert 3)".into(), x: None, y: None }, vec![]).unwrap();    assert_eq!(v["open"], json!(true));    let window = find_window(host.child.id(), "JW Test Gain (Insert 3)");    assert!(window.is_some(), "no editor window");    // The heartbeat says an editor is open (the app watches the host more closely then).    host.events.clear();    host.drain(Duration::from_millis(700));    assert!(host.events.iter().any(|e| matches!(e, Event::Heartbeat { editors: 1, .. })), "{:?}", host.events.last());    let (v, _) = host.ask(&Request::Editor { inst: o.inst, show: false, title: String::new(), x: None, y: None }, vec![]).unwrap();    assert_eq!(v["open"], json!(false));    assert!(find_window(host.child.id(), "JW Test Gain (Insert 3)").is_none());    // Shown again at a remembered place.    host.ask(&Request::Editor { inst: o.inst, show: true, title: "JW Test Gain (Insert 3)".into(), x: Some(120), y: Some(140) }, vec![]).unwrap();    let (x, y) = find_window(host.child.id(), "JW Test Gain (Insert 3)").unwrap();    assert_eq!((x, y), (120, 140));    // Closing the instance closes its editor.    host.ask(&Request::Close { inst: o.inst }, vec![]).unwrap();    assert!(find_window(host.child.id(), "JW Test Gain (Insert 3)").is_none());}/// A visible top-level window of process `pid` titled `title`, and where it is.fn find_window(pid: u32, title: &str) -> Option<(i32, i32)> {    use windows::Win32::Foundation::{HWND, LPARAM, RECT};    use windows::Win32::UI::WindowsAndMessaging::{EnumWindows, GetWindowRect, GetWindowTextW, GetWindowThreadProcessId, IsWindowVisible};    struct Find {        pid: u32,        title: String,        at: Option<(i32, i32)>,    }    unsafe extern "system" fn each(hwnd: HWND, l: LPARAM) -> windows::core::BOOL {        let f = &mut *(l.0 as *mut Find);        let mut pid = 0;        GetWindowThreadProcessId(hwnd, Some(&mut pid));        let mut buf = [0u16; 256];        let n = GetWindowTextW(hwnd, &mut buf) as usize;        if pid == f.pid && IsWindowVisible(hwnd).as_bool() && String::from_utf16_lossy(&buf[..n]) == f.title {            let mut r = RECT::default();            let _ = GetWindowRect(hwnd, &mut r);            f.at = Some((r.left, r.top));        }        true.into()    }    let mut f = Find { pid, title: title.into(), at: None };    unsafe {        let _ = EnumWindows(Some(each), LPARAM(&mut f as *mut Find as isize));    }    f.at}/// What an editor owned by the app's window does to the two processes' input, measured without touching the screen./// Windows ties together the input of threads joined by a cross-thread owner/owned window: they share one input state/// (focus, activation, mouse capture, key states, the queue of input). The owner's thread here takes the mouse capture/// on its own hidden window (nothing is on the screen, so no mouse is taken from anyone) and asks what the host's/// thread sees as its capture. With the editor open, the host's thread sees the owner's capture: one input state. With/// the editor closed, it doesn't. A plugin window that hangs as it opens (an editor whose attached() never returns,/// its window made but never shown) keeps them tied until the host is ended, while the owner's thread goes on/// answering messages (it's input that a hung partner holds up, and nothing here makes any). So a hung plugin window/// can hold up the app's input once the user clicks or types, until the app's watchdog ends the host/// (src/plugins/host.rs; its tests time that).#[test]fn an_editor_owned_by_the_apps_window_shares_its_input_until_it_closes() {    let d = folder("owned");    let module = bundle(&d, "JW Test");    let owner = win::OwnerThread::start();    let mut host = Host::start_owned(&[&d], owner.hwnd as u64);    let gain = host.open(&module, GAIN, 128, false);    let title = "JW Test Gain (Insert 1)";    host.ask(&Request::Editor { inst: gain.inst, show: true, title: title.into(), x: None, y: None }, vec![]).unwrap();    let editor = win::window_of(host.child.id(), title).expect("the editor's window");    let host_thread = win::thread_of(editor);    let open = owner.probe(host_thread);    host.ask(&Request::Editor { inst: gain.inst, show: false, title: String::new(), x: None, y: None }, vec![]).unwrap();    let closed = owner.probe(host_thread);    // A plugin window that hangs as it opens: the host's main thread never comes back.    let crash = host.open(&module, CRASH, 128, false);    host.ask(&Request::SetParam { inst: crash.inst, id: 2, value: 1.0 }, vec![]).unwrap();    let hung_title = "JW Test Crash (Insert 2)";    let req = Request::Editor { inst: crash.inst, show: true, title: hung_title.into(), x: None, y: None };    assert!(host.ask_within(&req, vec![], Duration::from_secs(2)).is_err(), "the editor should hang as it opens");    assert!(win::window_of(host.child.id(), hung_title).is_some(), "the hung editor's window (made, never shown)");    let hung = owner.probe(host_thread);    let answered = owner.answers();    // Ended, as the app's watchdog would (before the owner's window goes: destroying it would wait on the hung thread).    let _ = host.child.kill();    host.exit(Duration::from_secs(5)).expect("the host should have ended");    eprintln!("[owned] editor open: {open:?}; closed: {closed:?}; hung: {hung:?}; the owner's thread answered in {answered:?}");    assert!(open.own_sees, "the probe works on the owner's own thread");    assert!(open.host_sees, "with the editor open, the host's thread shares the owner's input state");    assert!(!closed.host_sees, "with the editor closed, it doesn't");    assert!(hung.host_sees, "a hung editor keeps them tied");    assert!(answered.is_some_and(|t| t < Duration::from_millis(500)), "the owner's thread still answers messages: {answered:?}");}/// The Win32 calls the input test makes, declared here: the app's own `windows` features don't include mouse capture,/// and this is all the test needs.mod win {    use std::ffi::c_void;    use std::sync::mpsc;    use std::time::{Duration, Instant};    #[repr(C)]    #[derive(Default)]    struct GuiInfo {        cb: u32,        flags: u32,        active: isize,        focus: isize,        capture: isize,        menu_owner: isize,        move_size: isize,        caret: isize,        caret_rect: [i32; 4],    }    #[repr(C, align(8))]    struct Msg([u8; 48]);    #[link(name = "user32")]    extern "system" {        fn CreateWindowExW(ex: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: isize, menu: isize, instance: isize, param: *const c_void) -> isize;        fn DestroyWindow(hwnd: isize) -> i32;        fn PeekMessageW(msg: *mut Msg, hwnd: isize, min: u32, max: u32, remove: u32) -> i32;        fn TranslateMessage(msg: *const Msg) -> i32;        fn DispatchMessageW(msg: *const Msg) -> isize;        fn SetCapture(hwnd: isize) -> isize;        fn ReleaseCapture() -> i32;        fn GetGUIThreadInfo(thread: u32, info: *mut GuiInfo) -> i32;        fn GetWindowThreadProcessId(hwnd: isize, pid: *mut u32) -> u32;        fn EnumWindows(each: unsafe extern "system" fn(isize, isize) -> i32, l: isize) -> i32;        fn GetWindowTextW(hwnd: isize, text: *mut u16, max: i32) -> i32;        fn SendMessageTimeoutW(hwnd: isize, msg: u32, w: usize, l: isize, flags: u32, timeout: u32, result: *mut usize) -> isize;    }    #[link(name = "kernel32")]    extern "system" {        fn GetCurrentThreadId() -> u32;    }    const WS_POPUP: u32 = 0x8000_0000;    const PM_REMOVE: u32 = 1;    const SMTO_ABORTIFHUNG: u32 = 2;    /// What the owner's thread and the host's thread see as the mouse capture while the owner's thread holds it.    #[derive(Debug)]    pub struct Probe {        pub own_sees: bool,        pub host_sees: bool,    }    enum Ask {        Probe(u32, mpsc::Sender<Probe>),        Quit,    }    /// The app's window, played by a hidden popup (never on the screen) on a thread of its own that pumps its messages.    pub struct OwnerThread {        pub hwnd: isize,        ask: mpsc::Sender<Ask>,        thread: Option<std::thread::JoinHandle<()>>,    }    impl OwnerThread {        pub fn start() -> OwnerThread {            let (tx, rx) = mpsc::channel();            let (ask, asks) = mpsc::channel::<Ask>();            let thread = std::thread::spawn(move || unsafe {                let class: Vec<u16> = "STATIC".encode_utf16().chain(Some(0)).collect();                let title: Vec<u16> = "owner".encode_utf16().chain(Some(0)).collect();                // No WS_VISIBLE: it's never shown.                let hwnd = CreateWindowExW(0, class.as_ptr(), title.as_ptr(), WS_POPUP, 0, 0, 10, 10, 0, 0, 0, std::ptr::null());                let me = GetCurrentThreadId();                let _ = tx.send(hwnd);                loop {                    let mut m = Msg([0; 48]);                    while PeekMessageW(&mut m, 0, 0, 0, PM_REMOVE) != 0 {                        TranslateMessage(&m);                        DispatchMessageW(&m);                    }                    match asks.recv_timeout(Duration::from_millis(5)) {                        Ok(Ask::Probe(thread, reply)) => {                            let size = std::mem::size_of::<GuiInfo>() as u32;                            SetCapture(hwnd);                            let mut theirs = GuiInfo { cb: size, ..Default::default() };                            let theirs_ok = GetGUIThreadInfo(thread, &mut theirs) != 0;                            let mut mine = GuiInfo { cb: size, ..Default::default() };                            GetGUIThreadInfo(me, &mut mine);                            ReleaseCapture();                            let _ = reply.send(Probe { own_sees: mine.capture == hwnd, host_sees: theirs_ok && theirs.capture == hwnd });                        }                        Ok(Ask::Quit) | Err(mpsc::RecvTimeoutError::Disconnected) => break,                        Err(mpsc::RecvTimeoutError::Timeout) => {}                    }                }                DestroyWindow(hwnd);            });            let hwnd = rx.recv().unwrap();            assert!(hwnd != 0, "couldn't make the owner's window");            OwnerThread { hwnd, ask, thread: Some(thread) }        }        pub fn probe(&self, host_thread: u32) -> Probe {            let (tx, rx) = mpsc::channel();            self.ask.send(Ask::Probe(host_thread, tx)).unwrap();            rx.recv_timeout(Duration::from_secs(5)).expect("the owner's thread should answer")        }        /// How long the owner's thread takes to answer a message sent to its window, or None if it didn't in 2 s.        pub fn answers(&self) -> Option<Duration> {            let t0 = Instant::now();            let mut r = 0usize;            let ok = unsafe { SendMessageTimeoutW(self.hwnd, 0, 0, 0, SMTO_ABORTIFHUNG, 2000, &mut r) } != 0;            ok.then(|| t0.elapsed())        }    }    impl Drop for OwnerThread {        fn drop(&mut self) {            let _ = self.ask.send(Ask::Quit);            if let Some(t) = self.thread.take() {                let _ = t.join();            }        }    }    /// A top-level window of process `pid` titled `title`, shown or not.    pub fn window_of(pid: u32, title: &str) -> Option<isize> {        struct Find {            pid: u32,            title: Vec<u16>,            found: isize,        }        unsafe extern "system" fn each(hwnd: isize, l: isize) -> i32 {            let f = &mut *(l as *mut Find);            let mut pid = 0;            GetWindowThreadProcessId(hwnd, &mut pid);            let mut buf = [0u16; 256];            // Another process's window: its text is read without asking its thread (which may be hung).            let n = GetWindowTextW(hwnd, buf.as_mut_ptr(), buf.len() as i32).max(0) as usize;            if pid == f.pid && buf[..n] == f.title[..] {                f.found = hwnd;                return 0;            }            1        }        let mut f = Find { pid, title: title.encode_utf16().collect(), found: 0 };        unsafe {            EnumWindows(each, &mut f as *mut Find as isize);        }        (f.found != 0).then_some(f.found)    }    pub fn thread_of(hwnd: isize) -> u32 {        unsafe { GetWindowThreadProcessId(hwnd, std::ptr::null_mut()) }    }}#[test]fn a_plugin_that_crashes_takes_only_the_host_and_is_named() {    let d = folder("crash");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let gain = host.open(&module, GAIN, 128, false);    let crash = host.open(&module, CRASH, 128, false);    let shm = Shm::new(512, 128, ring::MODE_REALTIME);    host.ask(&Request::Attach { inst: crash.inst, handle: shm.give(&host), size: shm.len as u64 }, vec![]).unwrap();    play(&shm, 0.2, |_| 0.1);    host.ask(&Request::SetParam { inst: crash.inst, id: 0, value: 1.0 }, vec![]).unwrap();    // The next block crashes it.    play(&shm, 0.3, |_| 0.1);    let status = host.exit(Duration::from_secs(5)).expect("the host should have ended");    assert!(!status.success());    std::thread::sleep(Duration::from_millis(200));    let log = host.stderr.lock().unwrap().clone();    let report = log.lines().find_map(|l| l.strip_prefix("[crash] ")).expect("a crash report");    let report: Value = serde_json::from_str(report).unwrap();    assert_eq!(report["code"], json!("0xC0000005"));    assert_eq!(report["inst"], json!(crash.inst));    assert!(report["module"].as_str().unwrap().ends_with("JW Test.vst3"), "{report}");    assert!(report["thread"].as_str().unwrap().starts_with("audio"), "{report}");    let _ = gain;}#[test]fn a_plugin_that_hangs_shows_in_the_heartbeat_while_the_host_still_answers() {    let d = folder("hang");    let module = bundle(&d, "JW Test");    let mut host = Host::start(&[&d]);    let crash = host.open(&module, CRASH, 128, false);    let shm = Shm::new(512, 128, ring::MODE_REALTIME);    host.ask(&Request::Attach { inst: crash.inst, handle: shm.give(&host), size: shm.len as u64 }, vec![]).unwrap();    host.ask(&Request::SetParam { inst: crash.inst, id: 1, value: 1.0 }, vec![]).unwrap();    play(&shm, 0.5, |_| 0.1);    host.drain(Duration::from_millis(2500));    let stuck = host.events.iter().any(|e| matches!(e, Event::Heartbeat { stuck, .. } if stuck.contains(&crash.inst)));    assert!(stuck, "the heartbeat should name the stuck instance: {:?}", host.events.iter().rev().take(3).collect::<Vec<_>>());    // The main thread is fine: it answers, and refuses to tear down an instance whose audio thread is stuck in it.    host.ask(&Request::Ping {}, vec![]).unwrap();    let e = host.ask_within(&Request::Close { inst: crash.inst }, vec![], Duration::from_secs(10)).unwrap_err();    assert!(e.contains("stuck"), "{e}");    // Closed or not, it's still stuck: the heartbeat keeps naming it, so the app ends the host as for any hang.    host.events.clear();    host.drain(Duration::from_secs(2));    let beats: Vec<&Vec<u32>> = host.events.iter().filter_map(|e| if let Event::Heartbeat { stuck, .. } = e { Some(stuck) } else { None }).collect();    assert!(beats.len() >= 5 && beats.iter().all(|s| s.contains(&crash.inst)), "{beats:?}");}#[test]fn modules_outside_the_plugin_folders_never_load() {    let allowed = folder("allowed");    let elsewhere = folder("elsewhere");    let outside = bundle(&elsewhere, "JW Test");    bundle(&allowed, "JW Test");    let mut host = Host::start(&[&allowed]);    let try_open = |host: &mut Host, module: String| {        host.ask(&Request::Open { module, cid: GAIN.into(), rate: 48000.0, block: 128, offline: false }, vec![]).unwrap_err()    };    assert!(try_open(&mut host, outside.to_string_lossy().to_string()).contains("plugin folders"));    let sneaky = format!("{}\\..\\{}\\JW Test.vst3", allowed.display(), elsewhere.file_name().unwrap().to_string_lossy());    assert!(try_open(&mut host, sneaky).contains("plugin folders"));    assert!(try_open(&mut host, r"C:\Windows\System32\kernel32.dll".into()).contains("plugin folders"));    // Nor does a request the host doesn't know.    proto::write_frame(&mut host.stdin, &Frame { kind: KIND_REQUEST, id: 99, json: br#"{"op":"loadDll","path":"C:/x.dll"}"#.to_vec(), bytes: vec![] }).unwrap();    let f = host.frames.recv_timeout(Duration::from_secs(5)).unwrap();    assert!(matches!(serde_json::from_slice::<Reply>(&f.json).unwrap(), Reply::Err(e) if e.starts_with("bad request")));    // And a ring that doesn't fit its mapping is refused before the host touches it.    let o = host.open(&allowed.join("JW Test.vst3"), GAIN, 128, false);    let shm = Shm::new(512, 128, ring::MODE_REALTIME);    shm.ring.set(ring::at::CAPACITY, 1 << 24);    let e = host.ask(&Request::Attach { inst: o.inst, handle: shm.give(&host), size: shm.len as u64 }, vec![]).unwrap_err();    assert!(e.contains("layout"), "{e}");}