Skip to content

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

leftLeaderboard

juicewrld-desktopsrc-taurihostmain.rs

1.4.2Released Nov 21, 2026

main.rs

247 lines11.4 KBRust
//! juicewrld-plugins.exe: the process that runs people's own VST 3 plugins for the app, so a plugin that crashes or//! hangs takes down only this process, never the app or its window. The app starts it and talks to it over its stdin//! and stdout (src/plugins/proto.rs); a page's audio reaches it through shared memory (src/plugins/ring.rs).//!//!   juicewrld-plugins --host           serve the app until it closes the pipe//!   juicewrld-plugins --scan <module>  load one module, print its classes as JSON, exit (the scan's short-lived child)//!//! Before any plugin loads, the process keeps private copies of the three pipes it was started with and gives up its//! standard handles: plugins see none (the C runtime's stdin, stdout and stderr read and write NUL), as in a DAW//! started from Explorer, so a plugin printing or reading can't touch the protocol, and none sees, or hands a helper//! process of its own, a pipe to the app. Our own lines go to the app on the private copy of stderr (`log!`): an//! unhandled crash with the instance and module it happened in (which the app passes on to the page), the scan's//! steps, and, should a plugin end the process itself, the modules on the stack that did (the shim's exit report).#![windows_subsystem = "windows"]/// One line to the app's log, on the process's private copy of its stderr pipe (`log_line`).macro_rules! log {    ($($arg:tt)*) => { $crate::log_line(&format!($($arg)*)) };}// Shared with the app (src/plugins), so each binary uses part of them.#[path = "../src/plugins/proto.rs"]#[allow(dead_code)]mod proto;#[path = "../src/plugins/ring.rs"]#[allow(dead_code)]mod ring;mod audio;mod server;mod shim;use serde_json::json;use std::fs::File;use std::io::Write;use std::os::windows::io::FromRawHandle;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE, HMODULE};use windows::Win32::System::Console::{GetStdHandle, SetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE};use windows::Win32::System::Diagnostics::Debug::{SetErrorMode, SetUnhandledExceptionFilter, EXCEPTION_POINTERS, SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX};use windows::Win32::System::LibraryLoader::{GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT};use windows::Win32::System::Ole::OleInitialize;use windows::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};use windows::Win32::UI::HiDpi::{SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2};fn main() {    let args: Vec<String> = std::env::args().collect();    let code = match (args.get(1).map(String::as_str), args.len()) {        (Some("--scan"), 3) => scan(&args[2]),        (Some("--host"), 2) => host(),        _ => {            eprintln!("juicewrld-plugins runs plugins for juicewrld.io; the app starts it");            2        }    };    exit(code);}/// Ends the process now, without unloading plugins (some crash or hang in their DLL teardown).fn exit(code: i32) -> ! {    let _ = std::io::stderr().flush();    // SAFETY: terminating our own process.    unsafe {        let _ = TerminateProcess(GetCurrentProcess(), code as u32);    }    std::process::exit(code)}/// The private copy of the stderr pipe the app reads our lines from (take_stdio); 0 until then, or when there's none.static LOG: AtomicUsize = AtomicUsize::new(0);/// One line to the app's log: on the private copy of the stderr pipe once take_stdio has made it (the line and its/// newline in one write, which a blocking pipe takes whole, so lines from different threads never mix), on stderr/// itself before.pub fn log_line(line: &str) {    let h = LOG.load(Ordering::Acquire);    if h == 0 {        eprintln!("{line}");        return;    }    let mut bytes = Vec::with_capacity(line.len() + 1);    bytes.extend_from_slice(line.as_bytes());    bytes.push(b'\n');    // SAFETY: our own handle, open for the life of the process; borrowed here, never closed (ManuallyDrop).    let log = std::mem::ManuallyDrop::new(unsafe { File::from_raw_handle(h as *mut std::ffi::c_void) });    let _ = (&*log).write_all(&bytes);}/// Takes the pipes the app started us with: private copies of stdin and stdout for the protocol and of stderr for our/// log, none of them inheritable. Then the process gives up its standard handles (the C runtime's go to NUL, which/// closes the ones we were started with, and Windows' are left empty), so a plugin sees what a DAW started from/// Explorer gives it: no standard handles, and no pipe of ours to write to, read from or pass to a process of its own.fn take_stdio() -> (File, File) {    // SAFETY: duplicating our own standard handles, then giving them up; nothing else holds them yet.    unsafe {        let me = GetCurrentProcess();        let dup = |h: HANDLE| {            let mut out = HANDLE::default();            DuplicateHandle(me, h, me, &mut out, 0, false, DUPLICATE_SAME_ACCESS).map(|_| out)        };        let out = GetStdHandle(STD_OUTPUT_HANDLE).and_then(dup).expect("stdout");        let inp = GetStdHandle(STD_INPUT_HANDLE).and_then(dup).expect("stdin");        if let Ok(err) = GetStdHandle(STD_ERROR_HANDLE).and_then(dup) {            LOG.store(err.0 as usize, Ordering::Release);            shim::jw_set_log(err.0);        }        shim::jw_redirect_stdio();        for which in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {            let _ = SetStdHandle(which, HANDLE::default());        }        (File::from_raw_handle(inp.0), File::from_raw_handle(out.0))    }}/// An unhandled crash: one line to the app's log naming where it happened, then the process ends (the app notices).unsafe extern "system" fn crashed(info: *const EXCEPTION_POINTERS) -> i32 {    let (code, address) = match info.as_ref().and_then(|i| i.ExceptionRecord.as_ref()) {        Some(r) => (r.ExceptionCode.0 as u32, r.ExceptionAddress as usize),        None => (0, 0),    };    let mut module = HMODULE::default();    let mut path = [0u16; 512];    let name = if GetModuleHandleExW(        GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,        windows::core::PCWSTR(address as *const u16),        &mut module,    )    .is_ok()    {        let n = GetModuleFileNameW(Some(module), &mut path) as usize;        String::from_utf16_lossy(&path[..n])    } else {        String::new()    };    let inst = audio::CURRENT.with(|c| c.get());    let thread = std::thread::current().name().unwrap_or("main").to_string();    let line = json!({ "code": format!("0x{code:08X}"), "inst": inst, "module": name, "thread": thread });    log_line(&format!("[crash] {line}"));    1 // EXCEPTION_EXECUTE_HANDLER: end the process}fn guard() {    // SAFETY: process-wide settings for this process alone: no error dialogs, crashes reported and ended.    unsafe {        SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);        SetUnhandledExceptionFilter(Some(crashed));    }    // A panic of ours goes to the app's log too (stderr is gone).    std::panic::set_hook(Box::new(|info| {        let thread = std::thread::current();        log_line(&format!("[host] thread '{}' {info}", thread.name().unwrap_or("<unnamed>")));    }));}fn host() -> i32 {    let (input, output) = take_stdio();    guard();    // SAFETY: process setup before any window or plugin exists.    unsafe {        let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);        // Plugins expect an STA with OLE on their UI thread (drag and drop, clipboard).        let _ = OleInitialize(None);        shim::jw_init(&server::callbacks());        // A test run's editors open without taking focus, behind everything (debug builds, JW_NO_FOCUS).        if quiet_windows() {            shim::jw_set_quiet_windows(1);        }    }    server::run(input, Arc::new(server::Writer::new(output)));    0}/// Debug builds, for test runs (JW_NO_FOCUS, set by the run): plugin editors open without taking focus and at the/// back of the other windows, so a scripted run never gets in the way of the person at the PC. Release builds always/// bring an editor forward, as the user asked for it.fn quiet_windows() -> bool {    cfg!(debug_assertions) && std::env::var_os("JW_NO_FOCUS").is_some_and(|v| !v.is_empty() && v != "0")}/// Every module this process is about to load. Debug builds, for test runs that must prove they never touch the PC's/// own plugins: the path goes to the file JW_PLUGINS_LOAD_LOG names (when set), and a module outside every folder in/// JW_PLUGINS_ONLY_UNDER (`;`-separated, when set) is refused before it loads. Release builds load what the app's/// checks allowed (proto::module_allowed) and log the path on stderr only.pub fn before_load(path: &str, mode: &str) -> Result<(), String> {    log!("[host] {mode} {} loading {path}", std::process::id());    #[cfg(debug_assertions)]    {        if let Ok(only) = std::env::var("JW_PLUGINS_ONLY_UNDER") {            let roots: Vec<String> = only.split(';').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect();            if !proto::module_allowed(path, &roots) {                log!("[host] refused {path}: outside JW_PLUGINS_ONLY_UNDER");                return Err("outside the folders this test run allows".into());            }        }        if let Ok(log) = std::env::var("JW_PLUGINS_LOAD_LOG") {            if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(log) {                let ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis());                // One write per line, so lines from processes logging at once never interleave.                let line = format!("{ms} {mode} pid {} {path}", std::process::id());                let _ = f.write_all(line.as_bytes());            }        }    }    let _ = mode;    Ok(())}/// The scan's child: the classes of one module, as JSON on the protocol's stdout. Each step goes to the log as it/// starts ("[stage] ..."), so when a module ends the process the app can say at which (src/plugins/scan.rs).fn scan(path: &str) -> i32 {    let (_input, mut output) = take_stdio();    guard();    if let Err(e) = before_load(path, "scan") {        let _ = writeln!(output, "{}", json!({ "error": e }));        return 0;    }    // SAFETY: as in host(); a module's factory may want COM.    unsafe {        let _ = OleInitialize(None);        shim::jw_init(std::ptr::null());        shim::jw_set_stages(1);    }    let result = match shim::Module::load(path) {        Ok(m) => {            // The factory's own info (its vendor), then the answer.            log!("[stage] answer");            let classes: Vec<_> = m                .classes()                .into_iter()                .map(|c| {                    json!({                        "cid": c.cid, "category": c.category, "name": c.name, "vendor": c.vendor, "version": c.version,                        "sdkVersion": c.sdk_version, "subCategories": c.sub_categories, "classFlags": c.class_flags,                        "cardinality": c.cardinality,                    })                })                .collect();            json!({ "vendor": m.vendor(), "classes": classes })        }        Err(e) => json!({ "error": e }),    };    let _ = writeln!(output, "{result}");    let _ = output.flush();    0}