Skip to content

Visual Studio Code, rebuilt in Rust

Rust
13.0 KB
Raw Blame
//! Parent side of the extension host connection: starts the host process on Bun or Node,
//! speaks `PersistentProtocol` over a Unix socket (a named pipe on Windows), and runs the Ready / init data / Initialized handshake.

pub mod activation_events;
pub mod console;
pub mod extension_development;
pub mod extension_management;
pub mod extension_validator;
pub mod frame;
pub mod gallery;
pub mod language_packs;
pub mod main_thread_bulk_edits;
pub mod main_thread_configuration;
pub mod main_thread_files;
pub mod main_thread_secret_state;
pub mod main_thread_storage;
pub mod main_thread_workspace;
pub mod proposed_api;
pub mod proxy_ids;
pub mod request;
pub mod rpc;
pub mod scan;
pub mod main_thread;
pub mod session;
pub mod settings_file_system;
pub mod sign;
pub mod utc;
pub mod zip;
#[cfg(windows)]
pub mod pipe;

use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::net::{UnixListener as Listener, UnixStream as Stream};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use frame::{Frame, FrameReader, FrameType, encode_frame};
#[cfg(windows)]
use pipe::{Listener, Stream};

/// Stops a console child (Bun, ripgrep) of the GUI-subsystem app from opening a console window on Windows.
pub fn hide_console(command: &mut Command) {
    // CREATE_NO_WINDOW
    #[cfg(windows)]
    command.creation_flags(0x0800_0000);
    #[cfg(not(windows))]
    let _ = command;
}

/// The test's end of an `ExtensionHost::silent` socket.
#[cfg(any(test, feature = "test-support"))]
pub type SilentPeer = Stream;

/// port/product.json's `nameLong`, the name every message shows (the app's product.rs reads the same overlay).
pub fn product_name() -> &'static str {
    static NAME: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
        let overlay: serde_json::Value = serde_json::from_str(include_str!("../../../../port/product.json")).expect("port/product.json is JSON");
        overlay["nameLong"].as_str().expect("port/product.json has nameLong").to_owned()
    });
    &NAME
}

/// The JavaScript runtime the extension host runs on. Node is the control for Bun.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runtime {
    Bun,
    Node,
}

impl Runtime {
    /// The runtime next to the running executable (VSRustium.app ships bun in Contents/MacOS), else the one on PATH.
    pub fn executable(self) -> PathBuf {
        let name = match self {
            Runtime::Bun => "bun",
            Runtime::Node => "node",
        };
        let bundled = std::env::current_exe().ok().and_then(|exe| exe.parent().map(|dir| dir.join(name))).filter(|path| path.is_file());
        bundled.unwrap_or_else(|| PathBuf::from(name))
    }

    fn runtime_args(self) -> &'static [&'static str] {
        match self {
            // Node 22.10+ resolves require() of ESM-only packages through "module-sync" (git needs file-type); Bun 1.4.5 only with the flag.
            Runtime::Bun => &["--conditions=module-sync"],
            Runtime::Node => &[],
        }
    }
}

/// One-byte messages of extensionHostProtocol.ts.
const MESSAGE_INITIALIZED: u8 = 1;
const MESSAGE_READY: u8 = 2;
const MESSAGE_TERMINATE: u8 = 3;

pub fn proxy_id(name: &str) -> u8 {
    let index = proxy_ids::PROXY_NAMES.iter().position(|n| *n == name).unwrap_or_else(|| panic!("unknown proxy {name}"));
    u8::try_from(index + 1).expect("more than 255 proxies")
}

pub fn proxy_name(rpc_id: u8) -> &'static str {
    proxy_ids::PROXY_NAMES.get(rpc_id as usize - 1).copied().unwrap_or("<unknown proxy>")
}

pub enum Incoming {
    Message(Vec<u8>),
    Closed,
    /// Work for the session that came from elsewhere (`Waker::wake`).
    Wake,
}

/// What a session waits on: its host's messages and the wakes of its `Waker`s. Made before the host starts, so the
/// workbench can queue work for a session that is not up yet.
pub struct Inbox {
    sender: Sender<Incoming>,
    receiver: Receiver<Incoming>,
}

impl Default for Inbox {
    fn default() -> Self {
        let (sender, receiver) = channel();
        Inbox { sender, receiver }
    }
}

impl Inbox {
    pub fn waker(&self) -> Waker {
        Waker(self.sender.clone())
    }
}

/// Ends the session's wait for its host after work for it was queued elsewhere: by the workbench, a file watcher or a
/// search.
#[derive(Clone)]
pub struct Waker(Sender<Incoming>);

impl Waker {
    pub fn wake(&self) {
        let _ = self.0.send(Incoming::Wake);
    }
}

/// A queue's sender whose items wake the session that reads the queue; one from a bare `Sender` wakes nothing.
pub struct WakingSender<T> {
    sender: Sender<T>,
    waker: Option<Waker>,
}

impl<T> WakingSender<T> {
    pub fn new(sender: Sender<T>, waker: Waker) -> Self {
        WakingSender { sender, waker: Some(waker) }
    }

    pub fn send(&self, item: T) -> Result<(), std::sync::mpsc::SendError<T>> {
        self.sender.send(item)?;
        if let Some(waker) = &self.waker {
            waker.wake();
        }
        Ok(())
    }
}

impl<T> Clone for WakingSender<T> {
    fn clone(&self) -> Self {
        WakingSender { sender: self.sender.clone(), waker: self.waker.clone() }
    }
}

impl<T> From<Sender<T>> for WakingSender<T> {
    fn from(sender: Sender<T>) -> Self {
        WakingSender { sender, waker: None }
    }
}

struct WriterState {
    stream: Stream,
    outgoing_id: u32,
    incoming_id: u32,
}

/// A started extension host. Dropping it sends Terminate and kills the process.
pub struct ExtensionHost {
    pub child: Child,
    writer: Arc<Mutex<WriterState>>,
    incoming: Receiver<Incoming>,
    socket_path: PathBuf,
}

pub struct HostOptions<'a> {
    pub runtime: Runtime,
    /// out-exthost/bootstrap-exthost.js
    pub entry: &'a Path,
    pub extra_env: Vec<(String, String)>,
    pub extra_args: Vec<String>,
    pub inbox: Inbox,
}

impl ExtensionHost {
    /// Starts the host and completes the handshake with `init_data` (an `IExtensionHostInitData`).
    pub fn start(options: HostOptions, init_data: &serde_json::Value) -> anyhow::Result<Self> {
        #[cfg(unix)]
        let socket_path = std::env::temp_dir().join(format!("vscode-gpui-exthost-{}-{}.sock", std::process::id(), unique()));
        // A killed earlier process with the same (reused) pid leaves its socket file; bind fails with EADDRINUSE.
        #[cfg(unix)]
        let _ = std::fs::remove_file(&socket_path);
        #[cfg(windows)]
        let socket_path = PathBuf::from(pipe::random_ipc_handle());
        let mut listener = Listener::bind(&socket_path)?;

        let mut command = Command::new(options.runtime.executable());
        command
            .args(options.runtime.runtime_args())
            .args(options.extra_args)
            .arg(options.entry)
            .arg("--skipWorkspaceStorageLock")
            .env("VSCODE_EXTHOST_IPC_HOOK", &socket_path)
            .env("VSCODE_HANDLES_UNCAUGHT_ERRORS", "true")
            // Bun uploads crash reports to bun.report unless DO_NOT_TRACK is set; the port sends nothing.
            .env("DO_NOT_TRACK", "1")
            .envs(options.extra_env);
        hide_console(&mut command);
        let child = command.spawn()?;

        let stream = accept_with_timeout(&mut listener, Duration::from_secs(30))?;
        let reader_stream = stream.try_clone()?;
        let writer = Arc::new(Mutex::new(WriterState { stream, outgoing_id: 0, incoming_id: 0 }));
        let Inbox { sender, receiver: incoming } = options.inbox;
        spawn_reader(reader_stream, writer.clone(), sender);

        let host = ExtensionHost { child, writer, incoming, socket_path };
        host.expect_one_byte(MESSAGE_READY)?;
        host.send(serde_json::to_vec(init_data)?);
        host.expect_one_byte(MESSAGE_INITIALIZED)?;
        Ok(host)
    }

    fn expect_one_byte(&self, expected: u8) -> anyhow::Result<()> {
        let deadline = Instant::now() + Duration::from_secs(30);
        loop {
            match self.incoming.recv_timeout(deadline.saturating_duration_since(Instant::now()))? {
                Incoming::Message(bytes) if bytes == [expected] => return Ok(()),
                Incoming::Message(bytes) => anyhow::bail!("expected handshake message {expected}, got {bytes:?}"),
                Incoming::Closed => anyhow::bail!("extension host closed the socket during the handshake"),
                // The work stays queued for the session's first look after the handshake.
                Incoming::Wake => {}
            }
        }
    }

    /// Sends one Regular message (an RPC message after the handshake).
    pub fn send(&self, data: Vec<u8>) {
        let mut writer = self.writer.lock().unwrap();
        writer.outgoing_id += 1;
        let frame = Frame { kind: FrameType::Regular, id: writer.outgoing_id, ack: writer.incoming_id, data };
        write_frame(&mut writer.stream, &frame);
    }

    pub fn recv_timeout(&self, timeout: Duration) -> Option<Incoming> {
        self.incoming.recv_timeout(timeout).ok()
    }

    pub fn try_recv(&self) -> Option<Incoming> {
        self.incoming.try_recv().ok()
    }

    /// `MessageType.Terminate`: the host deactivates its extensions (at most 5 s) and exits.
    pub fn terminate(&self) {
        self.send(vec![MESSAGE_TERMINATE]);
    }

    /// A host that never sends anything, over a socket pair whose other end is `peer`.
    #[cfg(any(test, feature = "test-support"))]
    pub fn silent(inbox: Inbox) -> (Self, Stream) {
        let (stream, peer) = Stream::pair().unwrap();
        let writer = Arc::new(Mutex::new(WriterState { stream: stream.try_clone().unwrap(), outgoing_id: 0, incoming_id: 0 }));
        let Inbox { sender, receiver: incoming } = inbox;
        spawn_reader(stream, writer.clone(), sender);
        let child = Command::new("sleep").arg("60").spawn().unwrap();
        (ExtensionHost { child, writer, incoming, socket_path: PathBuf::new() }, peer)
    }
}

impl Drop for ExtensionHost {
    fn drop(&mut self) {
        self.terminate();
        let _ = self.child.kill();
        let _ = self.child.wait();
        let _ = std::fs::remove_file(&self.socket_path);
    }
}

fn spawn_reader(mut stream: Stream, writer: Arc<Mutex<WriterState>>, sender: Sender<Incoming>) {
    std::thread::Builder::new()
        .name("exthost-reader".into())
        .spawn(move || {
            let mut reader = FrameReader::default();
            let mut chunk = vec![0u8; 64 * 1024];
            loop {
                let n = match stream.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => n,
                };
                reader.push(&chunk[..n]);
                let mut received_regular = false;
                while let Ok(Some(frame)) = reader.next_frame() {
                    if frame.kind != FrameType::Regular {
                        continue;
                    }
                    let mut state = writer.lock().unwrap();
                    if frame.id != state.incoming_id + 1 {
                        continue;
                    }
                    state.incoming_id = frame.id;
                    drop(state);
                    received_regular = true;
                    if sender.send(Incoming::Message(frame.data)).is_err() {
                        return;
                    }
                }
                // Upstream acks within 2 s; on a local socket an immediate ack per read costs nothing.
                if received_regular {
                    let mut state = writer.lock().unwrap();
                    let ack = Frame { kind: FrameType::Ack, id: 0, ack: state.incoming_id, data: Vec::new() };
                    write_frame(&mut state.stream, &ack);
                }
            }
            let _ = sender.send(Incoming::Closed);
        })
        .expect("spawn exthost reader thread");
}

fn write_frame(stream: &mut Stream, frame: &Frame) {
    let mut bytes = Vec::with_capacity(frame::HEADER_LENGTH + frame.data.len());
    encode_frame(frame, &mut bytes);
    // A failed write means the host is gone; the reader thread reports Closed.
    let _ = stream.write_all(&bytes);
}

#[cfg(windows)]
fn accept_with_timeout(listener: &mut Listener, timeout: Duration) -> anyhow::Result<Stream> {
    Ok(listener.accept(Some(timeout))?)
}

#[cfg(unix)]
fn accept_with_timeout(listener: &mut Listener, timeout: Duration) -> anyhow::Result<Stream> {
    listener.set_nonblocking(true)?;
    let deadline = std::time::Instant::now() + timeout;
    loop {
        match listener.accept() {
            Ok((stream, _)) => {
                stream.set_nonblocking(false)?;
                return Ok(stream);
            }
            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                anyhow::ensure!(std::time::Instant::now() < deadline, "extension host did not connect within {timeout:?}");
                std::thread::sleep(Duration::from_millis(5));
            }
            Err(error) => return Err(error.into()),
        }
    }
}

#[cfg(unix)]
fn unique() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static NEXT: AtomicU64 = AtomicU64::new(0);
    NEXT.fetch_add(1, Ordering::Relaxed)
}