Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(windows): connect over named pipes, attach to the console

rokartur61d5bc7e02be
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 931c85e62fd..52e11c3fd72 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -241,6 +241,7 @@ dependencies = [
"files",
"futures",
"gdkx11",
+ "getrandom 0.3.4",
"gpui",
"gpui_platform",
"gtk",
@@ -1871,6 +1872,7 @@ dependencies = [
"files",
"flate2",
"futures",
+ "getrandom 0.3.4",
"md-5",
"objc2 0.6.5",
"objc2-foundation 0.3.2",
@@ -6132,6 +6134,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
name = "storage"
version = "0.1.0"
dependencies = [
+ "getrandom 0.3.4",
"rusqlite",
"serde",
"serde_json",
diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.toml
index 64c57bb6589..0f389aab7b2 100644
--- a/native/crates/app/Cargo.toml
+++ b/native/crates/app/Cargo.toml
@@ -19,6 +19,7 @@ diff = { path = "../diff" }
exthost = { path = "../exthost" }
files = { path = "../files" }
futures = "0.3"
+getrandom = "0.3"
icu_collator = "2"
icu_locale_core = "2"
icu_segmenter = "2"
@@ -68,6 +69,7 @@ webview2-com = "0.38"
windows-sys = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Security",
+ "Win32_Storage_FileSystem",
"Win32_System_Console",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Pipes",
diff --git a/native/crates/app/src/cli.rs b/native/crates/app/src/cli.rs
index df5a98b155a..b527488c83b 100644
--- a/native/crates/app/src/cli.rs
+++ b/native/crates/app/src/cli.rs
@@ -303,6 +303,35 @@ fn stdin_has_data_within(timeout: Duration) -> bool {
ready > 0 && std::io::stdin().read(&mut [0]).is_ok_and(|read| read > 0)
}
+/// Chromium's `base::RouteStdioToConsole(false)`: output not redirected goes to the console of the process that
+/// started this GUI binary, when it has one.
+#[cfg(windows)]
+pub fn route_stdio_to_console() {
+ use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE};
+ use windows_sys::Win32::Storage::FileSystem::{CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING};
+ use windows_sys::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_HANDLE, STD_OUTPUT_HANDLE, SetStdHandle};
+ let redirected = |id: STD_HANDLE| {
+ let handle = unsafe { GetStdHandle(id) };
+ !handle.is_null() && handle != INVALID_HANDLE_VALUE
+ };
+ if redirected(STD_OUTPUT_HANDLE) || redirected(STD_ERROR_HANDLE) {
+ return;
+ }
+ if unsafe { AttachConsole(ATTACH_PARENT_PROCESS) } == 0 {
+ return;
+ }
+ let name: Vec<u16> = "CONOUT$".encode_utf16().chain([0]).collect();
+ let console = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null(), OPEN_EXISTING, 0, std::ptr::null_mut()) };
+ if console == INVALID_HANDLE_VALUE {
+ return;
+ }
+ // SAFETY: a console handle that lives until the process ends.
+ unsafe {
+ SetStdHandle(STD_OUTPUT_HANDLE, console);
+ SetStdHandle(STD_ERROR_HANDLE, console);
+ }
+}
+
/// `process.stdout.columns` on a console (libuv's visible window width), else 80 (argv.ts `buildHelpMessage`).
#[cfg(windows)]
fn terminal_columns() -> usize {
diff --git a/native/crates/app/src/debug.rs b/native/crates/app/src/debug.rs
index 1aab2722f7d..6b00108d537 100644
--- a/native/crates/app/src/debug.rs
+++ b/native/crates/app/src/debug.rs
@@ -902,9 +902,8 @@ pub fn strip_nulls(value: &mut Value) {
/// `generateUuid()`: a version 4 UUID.
pub fn generate_uuid() -> String {
- use std::io::Read;
let mut bytes = [0u8; 16];
- std::fs::File::open("/dev/urandom").and_then(|mut random| random.read_exact(&mut bytes)).expect("/dev/urandom is readable");
+ getrandom::fill(&mut bytes).expect("the OS random source is readable");
bytes[6] = bytes[6] & 0x0f | 0x40;
bytes[8] = bytes[8] & 0x3f | 0x80;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
diff --git a/native/crates/app/src/launch.rs b/native/crates/app/src/launch.rs
index 8d9e34bf04e..29cbf68ef03 100644
--- a/native/crates/app/src/launch.rs
+++ b/native/crates/app/src/launch.rs
@@ -1,41 +1,56 @@
-//! launchMainService.ts and main.ts `claimInstance`: the first instance listens on `<user data>/<version>-main.sock`; a
-//! later start with the same user data hands its arguments and working directory to it and exits.
+//! launchMainService.ts and main.ts `claimInstance`: the first instance listens on `<user data>/<version>-main.sock`
+//! (on Windows the pipe `\\.\pipe\<hash>-<version>-main-sock`); a later start with the same user data hands its
+//! arguments and working directory to it and exits.
-#[cfg(unix)]
use std::io::{BufRead, BufReader, Write};
#[cfg(unix)]
-use std::os::unix::net::{UnixListener, UnixStream};
+use std::os::unix::net::{UnixListener as Listener, UnixStream as Stream};
use std::path::{Path, PathBuf};
+#[cfg(windows)]
+use exthost::pipe::{Listener, Stream};
use futures::StreamExt;
-use futures::channel::mpsc::UnboundedReceiver;
-#[cfg(unix)]
-use futures::channel::mpsc::unbounded;
+use futures::channel::mpsc::{UnboundedReceiver, unbounded};
use gpui::App;
-#[cfg(unix)]
use serde_json::{Value, json};
/// What a second instance sends: its command line, working directory and whether a terminal's `code` started it
/// (`isLaunchedFromCli` of its `userEnv`), or a `--status` request answered with the
/// main process diagnostics (main.ts asks the `diagnostics` channel of the same socket).
-#[cfg_attr(windows, expect(dead_code, reason = "shortcut: built only by the Unix socket until the named pipe lands, port/ledger.md M24 row app/src/launch.rs:5"))]
pub enum Launch {
Open { args: Vec<String>, cwd: PathBuf, launched_from_cli: bool },
Status(futures::channel::oneshot::Sender<crate::diagnostics::MainDiagnostics>),
}
+/// environmentMainService.ts `mainIPCHandle`: ipc.net.ts `createStaticIPCHandle(userDataPath, 'main', version)`.
pub fn socket_path(user_data: &Path) -> PathBuf {
+ if cfg!(windows) {
+ return windows_pipe_name(user_data, &crate::VERSION);
+ }
user_data.join(format!("{}-main.sock", *crate::VERSION))
}
+/// `createStaticIPCHandle` on Windows: the first 8 hex digits of the user data path's SHA-256.
+fn windows_pipe_name(user_data: &Path, version: &str) -> PathBuf {
+ use sha2::Digest;
+ let scope = sha2::Sha256::digest(user_data.to_string_lossy().as_bytes());
+ let scope: String = scope[..4].iter().map(|byte| format!("{byte:02x}")).collect();
+ PathBuf::from(format!(r"\\.\pipe\{scope}-{version}-main-sock"))
+}
+
/// A second instance: true once the running one took the arguments. False when no instance listens (a stale socket is
/// removed then, as main.ts does on `ECONNREFUSED`).
-#[cfg(unix)]
pub fn send_to_running_instance(socket: &Path, args: &[String], cwd: &Path) -> bool {
- let Ok(mut stream) = UnixStream::connect(socket) else {
+ let Ok(mut stream) = Stream::connect(socket) else {
+ #[cfg(unix)]
let _ = std::fs::remove_file(socket);
return false;
};
+ // main.ts `windowsAllowSetForegroundWindow`: the running instance may bring its window to the front.
+ #[cfg(windows)]
+ if let Ok(pid) = stream.server_process_id() {
+ unsafe { windows_sys::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(pid) };
+ }
let launched_from_cli = std::env::var("VSCODE_CLI").is_ok_and(|cli| cli == "1");
let message = json!({ "args": args, "cwd": cwd, "launchedFromCli": launched_from_cli });
if writeln!(stream, "{message}").is_err() {
@@ -46,9 +61,8 @@ pub fn send_to_running_instance(socket: &Path, args: &[String], cwd: &Path) -> b
}
/// `diagnosticsMainService.getMainDiagnostics` of the instance listening on `socket`; None when none listens.
-#[cfg(unix)]
pub fn request_main_diagnostics(socket: &Path) -> Option<crate::diagnostics::MainDiagnostics> {
- let mut stream = UnixStream::connect(socket).ok()?;
+ let mut stream = Stream::connect(socket).ok()?;
writeln!(stream, "{}", json!({ "status": true })).ok()?;
let mut answer = String::new();
BufReader::new(stream).read_line(&mut answer).ok()?;
@@ -56,14 +70,19 @@ pub fn request_main_diagnostics(socket: &Path) -> Option<crate::diagnostics::Mai
}
/// The first instance: each second instance's launch, answered once it is read.
-#[cfg(unix)]
pub fn listen(socket: &Path) -> Option<UnboundedReceiver<Launch>> {
- let listener = UnixListener::bind(socket).inspect_err(|error| eprintln!("[launch] listening on {}: {error}", socket.display())).ok()?;
+ #[cfg_attr(unix, expect(unused_mut, reason = "accept takes &mut on Windows"))]
+ let mut listener = Listener::bind(socket).inspect_err(|error| eprintln!("[launch] listening on {}: {error}", socket.display())).ok()?;
let (sender, receiver) = unbounded();
std::thread::Builder::new()
.name("launch".into())
.spawn(move || {
- for stream in listener.incoming().flatten() {
+ loop {
+ #[cfg(unix)]
+ let accepted = listener.accept().map(|(stream, _)| stream);
+ #[cfg(windows)]
+ let accepted = listener.accept(None);
+ let Ok(stream) = accepted else { continue };
let mut line = String::new();
let mut reader = BufReader::new(&stream);
if reader.read_line(&mut line).is_err() {
@@ -93,22 +112,6 @@ pub fn listen(socket: &Path) -> Option<UnboundedReceiver<Launch>> {
Some(receiver)
}
-// shortcut: every start is a first instance on Windows until main.ts `mainIPCHandle`'s named pipe is ported; port/ledger.md M24 row app/src/launch.rs:5.
-#[cfg(windows)]
-pub fn send_to_running_instance(_socket: &Path, _args: &[String], _cwd: &Path) -> bool {
- false
-}
-
-#[cfg(windows)]
-pub fn request_main_diagnostics(_socket: &Path) -> Option<crate::diagnostics::MainDiagnostics> {
- None
-}
-
-#[cfg(windows)]
-pub fn listen(_socket: &Path) -> Option<UnboundedReceiver<Launch>> {
- None
-}
-
/// Opens each launch until the app quits.
pub fn handle_launches(mut launches: UnboundedReceiver<Launch>, cx: &mut App) {
cx.spawn(async move |cx| {
@@ -144,15 +147,25 @@ fn main_diagnostics(cx: &mut App) -> crate::diagnostics::MainDiagnostics {
mod tests {
use super::*;
+ #[test]
+ fn the_windows_pipe_is_named_from_the_user_data_hash_as_create_static_ipc_handle() {
+ // Node: createHash('sha256').update('C:\\Users\\Ann\\AppData\\Roaming\\VSRustium').digest('hex').substr(0, 8)
+ let name = windows_pipe_name(Path::new(r"C:\Users\Ann\AppData\Roaming\VSRustium"), "1.147.0");
+ assert_eq!(name, PathBuf::from(r"\\.\pipe\8c531f1c-1.147.0-main-sock"));
+ }
+
#[test]
fn a_second_instance_hands_its_arguments_to_the_first() {
let dir = std::env::temp_dir().join(format!("vsrustium-launch-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let socket = socket_path(&dir);
assert!(!send_to_running_instance(&socket, &[], &dir), "nothing listens yet");
- std::fs::write(&socket, "").unwrap();
- assert!(!send_to_running_instance(&socket, &[], &dir));
- assert!(!socket.exists(), "a stale socket file is removed");
+ #[cfg(unix)]
+ {
+ std::fs::write(&socket, "").unwrap();
+ assert!(!send_to_running_instance(&socket, &[], &dir));
+ assert!(!socket.exists(), "a stale socket file is removed");
+ }
let mut launches = listen(&socket).unwrap();
let args = vec!["vsrustium".to_owned(), "folder".to_owned()];
assert!(send_to_running_instance(&socket, &args, Path::new("/tmp")));
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index 4d2ef6f8bea..fe818b2a60e 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -2,6 +2,8 @@
//! Usage: vsrustium [folder or .code-workspace file [file]] [--theme <settings id>] [--user-data-dir <dir>] [--screenshot <png>]
//! [--screenshot-keys "<keystroke> ..."] [--screenshot-input <steps>] [--node] [--export-default-keybindings [<folder>]]
//! [--extensionDevelopmentPath=<dir> [--extensionTestsPath=<path>]]: the app exits with the test runner's code.
+// A GUI binary as Electron's, so a start from Explorer opens no console; cli::route_stdio_to_console finds the terminal's.
+#![cfg_attr(windows, windows_subsystem = "windows")]
#[cfg_attr(not(test), expect(dead_code, reason = "the code action menu of milestone 13 is its first desktop caller"))]
mod action_list;
@@ -171,6 +173,11 @@ use workbench::Workbench;
fn main() -> anyhow::Result<()> {
perf::mark("code/didStartMain");
+ // electron_main_win.cc: `base::RouteStdioToConsole` unless the CLI started the app with ELECTRON_NO_ATTACH_CONSOLE.
+ #[cfg(windows)]
+ if std::env::var_os("ELECTRON_RUN_AS_NODE").is_some() || std::env::var_os("ELECTRON_NO_ATTACH_CONSOLE").is_none() {
+ cli::route_stdio_to_console();
+ }
let args: Vec<String> = std::env::args().collect();
if args.get(1).is_some_and(|arg| arg == update::install::APPLY_UPDATE) {
return update::install::apply_update(&args[2..]);
diff --git a/native/crates/exthost/Cargo.toml b/native/crates/exthost/Cargo.toml
index d41629d8665..523452ce77e 100644
--- a/native/crates/exthost/Cargo.toml
+++ b/native/crates/exthost/Cargo.toml
@@ -11,6 +11,7 @@ config = { path = "../config" }
ed25519-dalek = "2"
files = { path = "../files" }
flate2 = "1"
+getrandom = "0.3"
md5 = { package = "md-5", version = "0.10" }
search = { path = "../search" }
semver = "1"
@@ -34,7 +35,7 @@ futures = "0.3"
oo7 = { version = "0.6", default-features = false, features = ["async-std", "native_crypto"] }
[target.'cfg(target_os = "windows")'.dependencies]
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Credentials"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Credentials", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] }
[target.'cfg(target_os = "linux")'.dev-dependencies]
async-lock = "3"
diff --git a/native/crates/exthost/src/lib.rs b/native/crates/exthost/src/lib.rs
index 34301c55da0..a610b670619 100644
--- a/native/crates/exthost/src/lib.rs
+++ b/native/crates/exthost/src/lib.rs
@@ -1,5 +1,5 @@
//! Parent side of the extension host connection: starts the host process on Bun or Node,
-//! speaks `PersistentProtocol` over a Unix socket, and runs the Ready / init data / Initialized handshake.
+//! 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;
@@ -27,7 +27,7 @@ pub mod sign;
pub mod utc;
pub mod zip;
#[cfg(windows)]
-mod pipe;
+pub mod pipe;
use std::io::{Read, Write};
#[cfg(unix)]
@@ -122,10 +122,14 @@ pub struct HostOptions<'a> {
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);
- let listener = Listener::bind(&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
@@ -140,7 +144,7 @@ impl ExtensionHost {
.envs(options.extra_env);
let child = command.spawn()?;
- let stream = accept_with_timeout(&listener, Duration::from_secs(30))?;
+ 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 (sender, incoming) = channel();
@@ -250,7 +254,13 @@ fn write_frame(stream: &mut Stream, frame: &Frame) {
let _ = stream.write_all(&bytes);
}
-fn accept_with_timeout(listener: &Listener, timeout: Duration) -> anyhow::Result<Stream> {
+#[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 {
@@ -268,6 +278,7 @@ fn accept_with_timeout(listener: &Listener, timeout: Duration) -> anyhow::Result
}
}
+#[cfg(unix)]
fn unique() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
diff --git a/native/crates/exthost/src/main_thread_storage.rs b/native/crates/exthost/src/main_thread_storage.rs
index 9f52492e1ef..07941fb048c 100644
--- a/native/crates/exthost/src/main_thread_storage.rs
+++ b/native/crates/exthost/src/main_thread_storage.rs
@@ -3,7 +3,6 @@
//! Left out: `$acceptValue` for shared keys another window changed (the port has one window) and the
//! storage migration between extension ids.
-use std::io::Read;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
@@ -115,7 +114,7 @@ impl MainThreadStorage {
/// `generateUuid()`: a version 4 UUID.
pub fn generate_uuid() -> String {
let mut bytes = [0u8; 16];
- std::fs::File::open("/dev/urandom").and_then(|mut random| random.read_exact(&mut bytes)).expect("/dev/urandom is readable");
+ getrandom::fill(&mut bytes).expect("the OS random source is readable");
bytes[6] = bytes[6] & 0x0f | 0x40;
bytes[8] = bytes[8] & 0x3f | 0x80;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
diff --git a/native/crates/exthost/src/pipe.rs b/native/crates/exthost/src/pipe.rs
index 6606bbcc0b6..7ee6139e957 100644
--- a/native/crates/exthost/src/pipe.rs
+++ b/native/crates/exthost/src/pipe.rs
@@ -1,54 +1,190 @@
-//! The extension host transport on Windows, where ipc.net.ts listens on a named pipe.
-//! shortcut: no named pipe yet, so the extension host does not start on Windows; port/ledger.md M24 row exthost/src/lib.rs:31.
+//! Named pipes, the IPC handles ipc.net.ts uses on Windows (`createRandomIPCHandle`, `createStaticIPCHandle`): the
+//! extension host connection and the single instance pipe. The handles are overlapped, so one thread reads while
+//! another writes; synchronous I/O on one pipe handle is serialized by Windows.
use std::io::{Error, ErrorKind, Read, Result, Write};
+use std::os::windows::ffi::OsStrExt;
+use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::Path;
+use std::ptr::{null, null_mut};
+use std::time::Duration;
-pub enum Listener {}
+use windows_sys::Win32::Foundation::{ERROR_BROKEN_PIPE, ERROR_IO_PENDING, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE, WAIT_TIMEOUT};
+use windows_sys::Win32::Storage::FileSystem::{CreateFileW, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, FILE_FLAGS_AND_ATTRIBUTES, OPEN_EXISTING, PIPE_ACCESS_DUPLEX, ReadFile, SECURITY_IDENTIFICATION, SECURITY_SQOS_PRESENT, WriteFile};
+use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, GetOverlappedResultEx, OVERLAPPED};
+use windows_sys::Win32::System::Pipes::{ConnectNamedPipe, CreateNamedPipeW, GetNamedPipeServerProcessId, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, PIPE_WAIT, WaitNamedPipeW};
+use windows_sys::Win32::System::Threading::{CreateEventW, INFINITE};
-pub enum Stream {}
+/// libuv's pipe buffer size (uv_pipe_bind on Windows).
+const BUFFER_SIZE: u32 = 65536;
-impl Listener {
- pub fn bind(_path: &Path) -> Result<Listener> {
- Err(Error::new(ErrorKind::Unsupported, "the extension host does not run on Windows yet"))
- }
+pub struct Listener {
+ name: Vec<u16>,
+ pending: OwnedHandle,
+}
- pub fn set_nonblocking(&self, _nonblocking: bool) -> Result<()> {
- match *self {}
+impl Listener {
+ /// Fails when another process already listens on `name` (`FILE_FLAG_FIRST_PIPE_INSTANCE`), as Node's `listen` on a
+ /// taken pipe fails with EADDRINUSE.
+ pub fn bind(name: &Path) -> Result<Listener> {
+ let name = wide(name);
+ let pending = create_instance(&name, FILE_FLAG_FIRST_PIPE_INSTANCE)?;
+ Ok(Listener { name, pending })
}
- pub fn accept(&self) -> Result<(Stream, ())> {
- match *self {}
+ /// Waits for a client, then listens on a new instance for the next one.
+ pub fn accept(&mut self, timeout: Option<Duration>) -> Result<Stream> {
+ let handle = self.pending.as_raw_handle();
+ let connected = match overlapped(handle, timeout, |overlapped| unsafe { ConnectNamedPipe(handle, overlapped) }) {
+ Ok(_) => Ok(()),
+ // A client that connected before the call, or connected and closed: the stream reads its data or EOF.
+ Err(error) if [ERROR_PIPE_CONNECTED, ERROR_NO_DATA].map(|code| Some(code as i32)).contains(&error.raw_os_error()) => Ok(()),
+ Err(error) => Err(error),
+ };
+ if let Err(error) = connected {
+ if error.kind() != ErrorKind::TimedOut {
+ self.pending = create_instance(&self.name, 0)?;
+ }
+ return Err(error);
+ }
+ let next = create_instance(&self.name, 0)?;
+ Ok(Stream(std::mem::replace(&mut self.pending, next)))
}
}
+pub struct Stream(OwnedHandle);
+
impl Stream {
+ /// `net.connect` to a pipe: waits while every instance is busy, fails when none listens.
+ pub fn connect(name: &Path) -> Result<Stream> {
+ let name = wide(name);
+ loop {
+ // SECURITY_IDENTIFICATION: the server learns who connects but cannot act as this process.
+ let flags = FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION;
+ let handle = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, null(), OPEN_EXISTING, flags, null_mut()) };
+ if handle != INVALID_HANDLE_VALUE {
+ return Ok(Stream(unsafe { OwnedHandle::from_raw_handle(handle) }));
+ }
+ let error = Error::last_os_error();
+ if error.raw_os_error() != Some(ERROR_PIPE_BUSY as i32) {
+ return Err(error);
+ }
+ if unsafe { WaitNamedPipeW(name.as_ptr(), 5000) } == 0 {
+ return Err(Error::last_os_error());
+ }
+ }
+ }
+
#[cfg(test)]
pub fn pair() -> Result<(Stream, Stream)> {
- Err(Error::new(ErrorKind::Unsupported, "no named pipe pair on Windows yet"))
+ let name = random_ipc_handle();
+ let mut listener = Listener::bind(Path::new(&name))?;
+ let client = Stream::connect(Path::new(&name))?;
+ Ok((listener.accept(None)?, client))
}
pub fn try_clone(&self) -> Result<Stream> {
- match *self {}
+ self.0.try_clone().map(Stream)
}
- pub fn set_nonblocking(&self, _nonblocking: bool) -> Result<()> {
- match *self {}
+ /// The process that listens on the pipe this client connected to.
+ pub fn server_process_id(&self) -> Result<u32> {
+ let mut pid = 0;
+ if unsafe { GetNamedPipeServerProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
+ return Err(Error::last_os_error());
+ }
+ Ok(pid)
+ }
+}
+
+/// ipc.net.ts `createRandomIPCHandle` on Windows.
+pub fn random_ipc_handle() -> String {
+ format!(r"\\.\pipe\vscode-ipc-{}-sock", crate::main_thread_storage::generate_uuid())
+}
+
+impl Read for &Stream {
+ fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
+ let handle = self.0.as_raw_handle();
+ let length = u32::try_from(buf.len()).unwrap_or(u32::MAX);
+ match overlapped(handle, None, |overlapped| unsafe { ReadFile(handle, buf.as_mut_ptr(), length, null_mut(), overlapped) }) {
+ Ok(read) => Ok(read as usize),
+ Err(error) if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) => Ok(0),
+ Err(error) => Err(error),
+ }
+ }
+}
+
+impl Write for &Stream {
+ fn write(&mut self, buf: &[u8]) -> Result<usize> {
+ let handle = self.0.as_raw_handle();
+ let length = u32::try_from(buf.len()).unwrap_or(u32::MAX);
+ overlapped(handle, None, |overlapped| unsafe { WriteFile(handle, buf.as_ptr(), length, null_mut(), overlapped) }).map(|written| written as usize)
+ }
+
+ fn flush(&mut self) -> Result<()> {
+ Ok(())
}
}
impl Read for Stream {
- fn read(&mut self, _buf: &mut [u8]) -> Result<usize> {
- match *self {}
+ fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
+ (&*self).read(buf)
}
}
impl Write for Stream {
- fn write(&mut self, _buf: &[u8]) -> Result<usize> {
- match *self {}
+ fn write(&mut self, buf: &[u8]) -> Result<usize> {
+ (&*self).write(buf)
}
fn flush(&mut self) -> Result<()> {
- match *self {}
+ Ok(())
+ }
+}
+
+fn wide(name: &Path) -> Vec<u16> {
+ name.as_os_str().encode_wide().chain([0]).collect()
+}
+
+/// One pipe instance as libuv's server creates them (`uv_pipe_bind`, `pipe_alloc_accept`): duplex, byte mode, local
+/// clients only.
+fn create_instance(name: &[u16], flags: FILE_FLAGS_AND_ATTRIBUTES) -> Result<OwnedHandle> {
+ let mode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS;
+ let handle = unsafe { CreateNamedPipeW(name.as_ptr(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | flags, mode, PIPE_UNLIMITED_INSTANCES, BUFFER_SIZE, BUFFER_SIZE, 0, null()) };
+ if handle == INVALID_HANDLE_VALUE {
+ return Err(Error::last_os_error());
+ }
+ Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
+}
+
+/// Starts one overlapped operation and waits for it, at most `timeout`; the bytes it moved.
+fn overlapped(handle: HANDLE, timeout: Option<Duration>, start: impl FnOnce(*mut OVERLAPPED) -> i32) -> Result<u32> {
+ let event = unsafe { CreateEventW(null(), 1, 0, null()) };
+ if event.is_null() {
+ return Err(Error::last_os_error());
+ }
+ let event = unsafe { OwnedHandle::from_raw_handle(event) };
+ let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
+ overlapped.hEvent = event.as_raw_handle();
+ if start(&mut overlapped) == 0 {
+ let error = Error::last_os_error();
+ if error.raw_os_error() != Some(ERROR_IO_PENDING as i32) {
+ return Err(error);
+ }
+ }
+ let milliseconds = timeout.map_or(INFINITE, |timeout| u32::try_from(timeout.as_millis()).unwrap_or(INFINITE - 1));
+ let mut transferred = 0;
+ if unsafe { GetOverlappedResultEx(handle, &overlapped, &mut transferred, milliseconds, 0) } != 0 {
+ return Ok(transferred);
+ }
+ let error = Error::last_os_error();
+ if error.raw_os_error() == Some(WAIT_TIMEOUT as i32) {
+ // The OVERLAPPED lives on this stack: the cancelled operation must end before it goes.
+ unsafe {
+ CancelIoEx(handle, &overlapped);
+ GetOverlappedResult(handle, &overlapped, &mut transferred, 1);
+ }
+ return Err(Error::new(ErrorKind::TimedOut, "the pipe operation timed out"));
}
+ Err(error)
}
diff --git a/native/crates/exthost/src/zip.rs b/native/crates/exthost/src/zip.rs
index 61882ff5fa2..f4cc9ab046f 100644
--- a/native/crates/exthost/src/zip.rs
+++ b/native/crates/exthost/src/zip.rs
@@ -222,10 +222,12 @@ mod tests {
assert_eq!(archive.read(archive.entry("extension/package.json").unwrap()).unwrap(), b"{}");
let dir = std::env::temp_dir().join(format!("zip-extract-{}", std::process::id()));
archive.extract("extension", &dir).unwrap();
+ #[cfg(unix)]
let mode = std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(dir.join("bin/tool")).unwrap().permissions());
let listed = (dir.join("package.json").is_file(), dir.join("extension.vsixmanifest").exists());
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(listed, (true, false));
+ #[cfg(unix)]
assert_eq!(mode & 0o777, 0o755);
}
diff --git a/native/crates/storage/Cargo.toml b/native/crates/storage/Cargo.toml
index 6b00612924b..c78fb6e48f6 100644
--- a/native/crates/storage/Cargo.toml
+++ b/native/crates/storage/Cargo.toml
@@ -5,6 +5,7 @@ edition.workspace = true
license.workspace = true
[dependencies]
+getrandom = "0.3"
# SQLite as macOS ships it, like upstream's @vscode/sqlite3 behind base/parts/storage.
rusqlite = "0.37"
serde.workspace = true
diff --git a/native/crates/storage/src/profiles.rs b/native/crates/storage/src/profiles.rs
index 9ceb0196e65..60e9ca6159c 100644
--- a/native/crates/storage/src/profiles.rs
+++ b/native/crates/storage/src/profiles.rs
@@ -443,8 +443,7 @@ fn valid_stored_profile(stored: &Value, profiles_home: &Path) -> Option<(String,
/// hash.ts `hash(generateUuid()).toString(16)`.
fn new_profile_id() -> String {
let mut bytes = [0u8; 16];
- let random = fs::File::open("/dev/urandom").and_then(|mut random| std::io::Read::read_exact(&mut random, &mut bytes));
- random.expect("/dev/urandom is readable");
+ getrandom::fill(&mut bytes).expect("the OS random source is readable");
bytes[6] = bytes[6] & 0x0f | 0x40;
bytes[8] = bytes[8] & 0x3f | 0x80;
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
diff --git a/port/ledger.md b/port/ledger.md
index 4a941d6b0eb..a6327857847 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -67,14 +67,15 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,
| M23 Linux | .github/workflows/linux.yml:1 | done | [linux S] move actions/checkout, actions/setup-node and actions/upload-artifact from v4 to their Node 24 majors (pinned by SHA). | checkout v7.0.1, setup-node v7.1.0, upload-artifact v7.0.2 by SHA; the workflow not run yet |
| M23 Linux | port/tools/package-linux:1 | done | [linux M] Linux builds of the host's native modules (@vscode/spdlog, kerberos): package-linux rebuilds them with node-gyp; a dev run in the Studio container still loads the reference's macOS builds (its pnpm install ran on macOS), a Linux install of upstream builds them for Linux. | the extracted `VSRustium-1.147.0-linux-arm64.tar.gz` writes `logs/<session>/window1/exthost/exthost.log` (spdlog) and passes `port/tools/linux/smoke` |
| M24 Windows | port/tools/windows-build:1 | done | [windows M] cross build on the Studio: `cargo gc xwin` with Homebrew llvm and lld on PATH, for `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc`; the Unix-only std and libc calls (files/src/disk.rs:58, exthost/src/lib.rs:31, app/src/cli.rs:7, app/src/launch.rs:5, app/src/shell_env.rs:5, app/src/update/install.rs:39) behind `cfg(unix)` with a Windows counterpart or an M24 row naming what Windows shows meanwhile. | `port/tools/windows-build 'cargo gc xwin build -p app --target x86_64-pc-windows-msvc'` and the same for `aarch64-pc-windows-msvc` exit 0 |
+| M24 Windows | app/src/update/install/tests.rs:80 | open | [windows S] the app's tests compile for Windows, so the runner rows can run them: 15 errors in Unix-only test code (`std::os::unix` permissions in terminal/completion_service, workbench/readonly, explorer_actions, text_files; `libc::SIGKILL` in terminal_contrib; `check_writable` in update/install). The exthost and storage tests compile. | `port/tools/windows-build 'cargo gc xwin check -p app --tests --target x86_64-pc-windows-msvc'` exits 0 |
| M24 Windows | app/src/terminal/pty.rs:1 | in progress | [windows L] terminal through ConPTY (terminal/pty/conpty.rs, windows-sys), as node-pty's conpty.cc and windowsPtyAgent.ts: spawn with the command line `argsToCommandLine` builds, resize, kill (signals ignored, as node-pty on Windows), `hasChildProcesses` from a process snapshot, cwd as the initial cwd (terminalProcess.ts `getCwd` on Windows). Built, not yet run on Windows; the foreground process is the started file (windowsTerminal.ts `process`), not windowsShellHelper.ts's tracking. | `cargo gc test -p app pty` on the windows runner; `cargo gc test -p app args_to_command_line` on the host, with node-pty lib/windowsPtyAgent.js's output |
| M24 Windows | app/src/terminal/profiles.rs:133 | open | [windows M] Windows terminal profiles (terminalProfiles.ts `detectAvailableWindowsProfiles`): PowerShell (pwsh, then Windows PowerShell), Command Prompt, Git Bash, WSL distributions; `terminal.integrated.defaultProfile.windows`; shell integration for pwsh (shellIntegration.ps1). | `cargo gc test -p app terminal::profiles` on the windows runner |
| M24 Windows | app/src/file_dialog.rs:9 | in progress | [windows M] Win32 open and save dialogs (file_dialog/windows.rs, IFileOpenDialog, IFileSaveDialog) with title, button label (`&` mnemonic), filters, default path, folder pick and multi-select, as Electron's file_dialog_win.cc `ApplySettings` and `ConvertFilters` (filter specs `*.ts;*.js`, `All Files (*.*)`, the first specific filter selected), owned by the active window, with dialogMainService.ts's lock (shared with macOS). Built, not yet run on Windows. | `cargo gc test -p app file_dialog` on the host: `windows_filters_become_semicolon_specs_and_the_first_specific_one_is_selected`, `one_dialog_of_the_same_options_per_window`; [windows] the dialog on the windows runner |
| M24 Windows | app/src/dialog.rs:5 | in progress | [windows M] native message box through TaskDialogIndirect (dialog/windows.rs), as Electron's message_box_win.cc with `noLink`: buttons in the order dialogs.ts `massageMessageBoxOptions` gives Windows (the caller's, cancel last) with `&` mnemonics, the message as main instruction above a detail, the checkbox as the verification text, owner window modal, Esc and the close button answer cancel. Common Controls 6 comes from GPUI's manifest (`windows-manifest`). Built, not yet run on Windows. | `cargo gc test -p app dialog::tests` on the host: `windows_labels_take_ampersand_mnemonics`, `windows_task_dialog_keeps_the_callers_button_order_with_cancel_last`, `windows_task_dialog_message_is_the_main_instruction_only_with_a_detail`; [windows] the dialog on the windows runner |
| M24 Windows | app/src/webview.rs:11 | in progress | [windows L] webviews through WebView2 (webview2-com, decision "Windows webview") as child windows of GPUI's HWND (webview/windows.rs), with the host page, resource scheme and message bridge `webview.rs` shares with macOS and Linux: panels and views, editor insets, notebook outputs, extension details, release notes. The WebView2 runtime ships with Windows 10 and 11. GPUI's DirectComposition target is not topmost (vendored `gpui_windows`, port/notes.md milestone 24 "Webview"). Built, not yet run on Windows. | `cargo gc test -p app splits_https_urls` on the host; [windows] `FIXTURE=webview-tests` smoke on the windows runner; `cargo gc test -p app webview` there |
-| M24 Windows | exthost/src/lib.rs:31 | open | [windows L] extension host connection over a named pipe (`\\.\pipe\vscode-ipc-<uuid>-sock`, ipc.net.ts `createRandomIPCHandle` on Windows) instead of a Unix socket; Bun's `net.connect` takes the pipe path. | `cargo gc test -p exthost` on the windows runner: the handshake test |
-| M24 Windows | app/src/launch.rs:5 | open | [windows M] single instance and second-instance arguments over a named pipe (main.ts `mainIPCHandle` on Windows). | `cargo gc test -p app launch` on the windows runner |
-| M24 Windows | app/src/cli.rs:7 | in progress | [windows M] the command line on Windows: `bin\<applicationName>.cmd` from resources/win32/bin/code.cmd, stdin read and terminal width through the console API. | `cargo gc test -p app cli` on the windows runner |
+| M24 Windows | exthost/src/lib.rs:31 | in progress | [windows L] extension host connection over a named pipe (`\\.\pipe\vscode-ipc-<uuid>-sock`, ipc.net.ts `createRandomIPCHandle` on Windows) instead of a Unix socket; Bun's `net.connect` takes the pipe path. Done and cross-built, never run: exthost/src/pipe.rs (overlapped pipe instances as libuv's `uv_pipe_bind`, local clients only, first instance exclusive; `generateUuid` from the OS random source, no `/dev/urandom` on Windows). | `cargo gc test -p exthost` on the windows runner: the handshake test |
+| M24 Windows | app/src/launch.rs:5 | in progress | [windows M] single instance and second-instance arguments over a named pipe (main.ts `mainIPCHandle` on Windows). Done and cross-built, never run: the pipe `\\.\pipe\<sha256(user data)[..8]>-<version>-main-sock` (`createStaticIPCHandle`, host test `the_windows_pipe_is_named_from_the_user_data_hash_as_create_static_ipc_handle`), exthost/src/pipe.rs as the transport, `windowsAllowSetForegroundWindow` with the pipe server's pid. | `cargo gc test -p app launch` on the host for the pipe name; `cargo gc test -p app launch` on the windows runner |
+| M24 Windows | app/src/cli.rs:7 | in progress | [windows M] the command line on Windows: `bin\<applicationName>.cmd` from resources/win32/bin/code.cmd (written by port/tools/package-windows, its row). Done and cross-built, never run: stdin read and terminal width through the console API; a GUI-subsystem binary as Electron's that attaches to the starting console (electron_main_win.cc `RouteStdioToConsole` unless `ELECTRON_NO_ATTACH_CONSOLE`). | `cargo gc test -p app cli` on the windows runner |
| M24 Windows | exthost/src/main_thread_secret_state.rs:19 | open | [windows S] secrets in Credential Manager (keyring), with keytar's target name `<service>/<account>` so VS Code's stored secrets keep their keys. | `cargo gc test -p exthost secret` on the windows runner |
| M24 Windows | exthost/src/request.rs:9 | open | [windows M] extension and gallery HTTP with the system proxy (WinHTTP's IE proxy settings, Chromium's ProxyConfigServiceWin), `http.proxy` and the `<local>` bypass. | `cargo gc test -p exthost request` on the windows runner |
| M24 Windows | app/src/workbench/menubar.rs:173 | open | [windows L] menu bar in the custom title bar (menubarControl.ts `CustomMenubarControl`, `window.titleBarStyle: custom`, `window.menuBarVisibility`) and the window controls (minimize, maximize, close) titlebarPart.ts draws on Windows. The shared mechanism is M24's (decision "Menu bar and keybinding tables"); it unblocks the M23 Linux row app/src/workbench/menubar.rs:173. Windows shows now: no menu bar. | `cargo gc test -p app menubar` on the host; a ui-pair against the reference not possible (macOS reference) |
diff --git a/port/notes.md b/port/notes.md
index bf9da3edb03..2cace2c8051 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -1014,6 +1014,8 @@ What to do (milestone 21, in order):
- Cross build: the Studio has the `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc` Rust targets, cargo-xwin (it downloads the MSVC CRT and Windows SDK headers on first use) and Homebrew `llvm` and `lld` (clang-cl, lld-link). It checks that the Windows build compiles; tests that need Windows run on the `windows.yml` runners.
- Dialogs: file dialogs (`file_dialog/windows.rs`) follow Electron 43's file_dialog_win.cc (`ApplySettings`, `ConvertFilters`, the open and save `FOS_` options), message boxes (`dialog/windows.rs`) its message_box_win.cc with `noLink`, so custom buttons, not command links. Both use the `windows` crate at GPUI's version (0.61) for the COM interfaces. Difference: Electron runs both on its dialog thread (`dialog_thread::Run`); here they run on GPUI's main thread in the dialog's modal loop, as GPUI's own path prompts do, and the GPUI windows keep painting through it. TaskDialogIndirect needs Common Controls 6, which GPUI's embedded manifest (`windows-manifest` feature) declares; a second `/MANIFEST:EMBED` fails the link with a duplicate resource. The pure parts (filter specs, button ids and answers, `&` mnemonics, the main instruction) are host tests in file_dialog.rs and dialog.rs.
- Webview: `webview/windows.rs` is a WebView2 (webview2-com 0.38, the last on `windows` 0.61) in a child window of GPUI's HWND, loading the same host page as macOS and Linux. A WebResourceRequested filter on `https://*.vscode-webview.vscode-cdn.net/*` and `https://*.vscode-resource.vscode-cdn.net/*` (with `COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL` where `ICoreWebView2_22` exists, so the content iframe's loads reach it) answers what the service worker answers upstream; `file` resources are read in place, the rest through the workbench with a deferral. A `file` resource's path is the URI path (`/c:/proj/a.png`), which matches no root and reads nothing until the drive-letter row (app/src/editor_history.rs:59) gives one conversion to a disk path. The bridge script runs in the top frame only, with `window.webkit.messageHandlers.vscodeWebviewHost` mapped onto `chrome.webview.postMessage`; messages from any other origin are dropped. `window.open` is handled with no window, as WebKit without a UI delegate does. No HTTP_LOOPBACK_ONLY_RULES: WebView2 is Chromium, which blocks non-loopback http in the https page as Electron does. Profile in `%LOCALAPPDATA%\<nameShort>\WebView2`. GPUI's DirectComposition target was topmost (`CreateTargetForHwnd(hwnd, true)`), drawing over every child window; `native/vendor/wu/crates/gpui_windows` vendors the crate with that one argument `false`. The notebook back layer clip is one window region (hit rects minus the hole), where Linux has an input shape beside the drawn one. URL splitting (`https_url_parts`) is a host test in webview.rs; the rest needs the windows runner.
+- Named pipes: `exthost/src/pipe.rs` carries both the extension host connection (`\\.\pipe\vscode-ipc-<uuid>-sock`) and the single instance (`\\.\pipe\<sha256(user data)[..8]>-<version>-main-sock`, launch.rs), as ipc.net.ts names them. Instances are made as libuv's `uv_pipe_bind` makes them (duplex, byte mode, 64 KiB buffers, default security descriptor) plus `PIPE_REJECT_REMOTE_CLIENTS` and `FILE_FLAG_FIRST_PIPE_INSTANCE`, so a second listener fails as Node's `listen` does with EADDRINUSE. The handles are overlapped: synchronous I/O on one pipe handle is serialized by Windows, and the extension host reader thread blocks in a read while the main thread writes. Clients connect with `SECURITY_IDENTIFICATION`, so a pipe server cannot act as the client. The single instance name is fixed per user data folder in the machine-wide pipe namespace, as upstream's: another local user who creates it first receives a later start's arguments and working directory. A second instance calls `AllowSetForegroundWindow` with the pipe server's pid (`GetNamedPipeServerProcessId`) where main.ts asks the first instance for its pid over IPC. `generateUuid` and the profile ids read the OS random source (getrandom), not `/dev/urandom`.
+- Console: the app is a GUI-subsystem binary, as Electron's, so a start from Explorer or the Start menu opens no console window; at start it attaches to the console of the process that started it unless the output is redirected or the CLI set `ELECTRON_NO_ATTACH_CONSOLE` (electron_main_win.cc, Chromium's `RouteStdioToConsole`), so `bin\<applicationName>.cmd --help` prints in the terminal.
## Accepted platform differences