Skip to content

Visual Studio Code, rebuilt in Rust

Rust

build(windows): compile files, exthost and storage for Windows

rokartur2e7697b1c9e5
diff --git a/native/crates/exthost/Cargo.toml b/native/crates/exthost/Cargo.toml
index 2b72968bb9b..d41629d8665 100644
--- a/native/crates/exthost/Cargo.toml
+++ b/native/crates/exthost/Cargo.toml
@@ -33,5 +33,8 @@ futures = "0.3"
# The features gpui_linux enables, so one oo7 and one zbus build.
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"] }
+
[target.'cfg(target_os = "linux")'.dev-dependencies]
async-lock = "3"
diff --git a/native/crates/exthost/src/extension_management.rs b/native/crates/exthost/src/extension_management.rs
index e44e9cf7c49..1e546afac41 100644
--- a/native/crates/exthost/src/extension_management.rs
+++ b/native/crates/exthost/src/extension_management.rs
@@ -571,7 +571,15 @@ fn copy_folder(from: &Path, to: &Path) -> anyhow::Result<()> {
let target = to.join(child.file_name());
let kind = child.file_type()?;
if kind.is_symlink() {
- std::os::unix::fs::symlink(std::fs::read_link(child.path())?, &target)?;
+ let link = std::fs::read_link(child.path())?;
+ #[cfg(unix)]
+ std::os::unix::fs::symlink(link, &target)?;
+ // Node's `fs.symlink` without a type on Windows: a directory link when the target is a directory.
+ #[cfg(windows)]
+ match child.path().is_dir() {
+ true => std::os::windows::fs::symlink_dir(link, &target)?,
+ false => std::os::windows::fs::symlink_file(link, &target)?,
+ }
} else if kind.is_dir() {
std::fs::create_dir_all(&target)?;
copy_folder(&child.path(), &target)?;
diff --git a/native/crates/exthost/src/gallery.rs b/native/crates/exthost/src/gallery.rs
index 6b8d030ba8a..3f81a7ab881 100644
--- a/native/crates/exthost/src/gallery.rs
+++ b/native/crates/exthost/src/gallery.rs
@@ -34,6 +34,8 @@ const BLOCKED_MESSAGE: &str = "This extension has been blocked by the Extension
pub const CURRENT_TARGET_PLATFORM: &str = if cfg!(target_arch = "aarch64") { "darwin-arm64" } else { "darwin-x64" };
#[cfg(target_os = "linux")]
pub const CURRENT_TARGET_PLATFORM: &str = if cfg!(target_arch = "aarch64") { "linux-arm64" } else { "linux-x64" };
+#[cfg(target_os = "windows")]
+pub const CURRENT_TARGET_PLATFORM: &str = if cfg!(target_arch = "aarch64") { "win32-arm64" } else { "win32-x64" };
pub const UNDEFINED: &str = "undefined";
pub const UNIVERSAL: &str = "universal";
pub const UNKNOWN: &str = "unknown";
diff --git a/native/crates/exthost/src/lib.rs b/native/crates/exthost/src/lib.rs
index 4b762abd2cf..34301c55da0 100644
--- a/native/crates/exthost/src/lib.rs
+++ b/native/crates/exthost/src/lib.rs
@@ -26,9 +26,12 @@ pub mod settings_file_system;
pub mod sign;
pub mod utc;
pub mod zip;
+#[cfg(windows)]
+mod pipe;
use std::io::{Read, Write};
-use std::os::unix::net::{UnixListener, UnixStream};
+#[cfg(unix)]
+use std::os::unix::net::{UnixListener as Listener, UnixStream as Stream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use std::sync::mpsc::{Receiver, Sender, channel};
@@ -36,6 +39,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use frame::{Frame, FrameReader, FrameType, encode_frame};
+#[cfg(windows)]
+use pipe::{Listener, 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 {
@@ -93,7 +98,7 @@ pub enum Incoming {
}
struct WriterState {
- stream: UnixStream,
+ stream: Stream,
outgoing_id: u32,
incoming_id: u32,
}
@@ -120,7 +125,7 @@ impl ExtensionHost {
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.
let _ = std::fs::remove_file(&socket_path);
- let listener = UnixListener::bind(&socket_path)?;
+ let listener = Listener::bind(&socket_path)?;
let mut command = Command::new(options.runtime.executable());
command
@@ -179,8 +184,8 @@ impl ExtensionHost {
/// A host that never sends anything, over a socket pair whose other end is `peer`.
#[cfg(test)]
- pub(crate) fn silent() -> (Self, UnixStream) {
- let (stream, peer) = UnixStream::pair().unwrap();
+ pub(crate) fn silent() -> (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 (sender, incoming) = channel();
spawn_reader(stream, writer.clone(), sender);
@@ -198,7 +203,7 @@ impl Drop for ExtensionHost {
}
}
-fn spawn_reader(mut stream: UnixStream, writer: Arc<Mutex<WriterState>>, sender: Sender<Incoming>) {
+fn spawn_reader(mut stream: Stream, writer: Arc<Mutex<WriterState>>, sender: Sender<Incoming>) {
std::thread::Builder::new()
.name("exthost-reader".into())
.spawn(move || {
@@ -238,14 +243,14 @@ fn spawn_reader(mut stream: UnixStream, writer: Arc<Mutex<WriterState>>, sender:
.expect("spawn exthost reader thread");
}
-fn write_frame(stream: &mut UnixStream, frame: &Frame) {
+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);
}
-fn accept_with_timeout(listener: &UnixListener, timeout: Duration) -> anyhow::Result<UnixStream> {
+fn accept_with_timeout(listener: &Listener, timeout: Duration) -> anyhow::Result<Stream> {
listener.set_nonblocking(true)?;
let deadline = std::time::Instant::now() + timeout;
loop {
diff --git a/native/crates/exthost/src/main_thread_secret_state.rs b/native/crates/exthost/src/main_thread_secret_state.rs
index 53bbec518fb..071bd71ef06 100644
--- a/native/crates/exthost/src/main_thread_secret_state.rs
+++ b/native/crates/exthost/src/main_thread_secret_state.rs
@@ -2,7 +2,8 @@
//! whose key lives in the Keychain, and keeps it in application storage under `secret://<key>`. The port stores
//! each secret as a generic password item instead: service `Code - OSS Secret Storage`, account the same
//! `{"extensionId","key"}` key, so the Keychain encrypts it and no key handling is needed here. On Linux each
-//! secret is a Secret Service item with the same `service` and `account` attributes (keytar's layout).
+//! secret is a Secret Service item with the same `service` and `account` attributes (keytar's layout), on Windows a
+//! Credential Manager credential (windows.rs).
use std::collections::BTreeMap;
@@ -20,6 +21,11 @@ use crate::rpc::{Arg, Message, Reply};
use futures::executor::block_on;
#[cfg(target_os = "linux")]
use oo7::Error as KeychainError;
+#[cfg(target_os = "windows")]
+use std::io::Error as KeychainError;
+
+#[cfg(target_os = "windows")]
+mod windows;
const SERVICE: &str = "Code - OSS Secret Storage";
/// errSecItemNotFound.
@@ -35,6 +41,8 @@ enum Secrets {
Keychain(SecKeychain),
#[cfg(target_os = "linux")]
Keyring(oo7::Keyring),
+ #[cfg(target_os = "windows")]
+ CredentialManager,
/// Extension tests: application storage is in memory, and so are the secrets kept in it.
Memory(BTreeMap<String, String>),
}
@@ -53,6 +61,11 @@ impl MainThreadSecretState {
Ok(MainThreadSecretState { secrets: Secrets::Keychain(SecKeychain::default()?) })
}
+ #[cfg(target_os = "windows")]
+ pub fn keychain() -> Result<Self, KeychainError> {
+ Ok(MainThreadSecretState { secrets: Secrets::CredentialManager })
+ }
+
pub fn in_memory() -> Self {
MainThreadSecretState { secrets: Secrets::Memory(BTreeMap::new()) }
}
@@ -121,6 +134,8 @@ impl MainThreadSecretState {
let Some(item) = block_on(keyring.search_items(&[("service", SERVICE), ("account", account)]))?.into_iter().next() else { return Ok(None) };
Ok(Some(String::from_utf8_lossy(&block_on(item.secret())?).into_owned()))
}
+ #[cfg(target_os = "windows")]
+ Secrets::CredentialManager => windows::get(SERVICE, account),
}
}
@@ -134,6 +149,8 @@ impl MainThreadSecretState {
Secrets::Keychain(keychain) => keychain.set_generic_password(SERVICE, account, value.as_bytes()),
#[cfg(target_os = "linux")]
Secrets::Keyring(keyring) => block_on(keyring.create_item(SERVICE, &[("service", SERVICE), ("account", account)], value, true)),
+ #[cfg(target_os = "windows")]
+ Secrets::CredentialManager => windows::set(SERVICE, account, value),
}
}
@@ -158,6 +175,8 @@ impl MainThreadSecretState {
}
Ok(!items.is_empty())
}
+ #[cfg(target_os = "windows")]
+ Secrets::CredentialManager => windows::delete(SERVICE, account),
}
}
@@ -175,6 +194,15 @@ impl MainThreadSecretState {
Ok(accounts)
}
+ /// The account of every secret, for `secretStorageService.keys()`.
+ #[cfg(target_os = "windows")]
+ fn accounts(&self) -> Result<Vec<String>, KeychainError> {
+ match &self.secrets {
+ Secrets::Memory(secrets) => Ok(secrets.keys().cloned().collect()),
+ Secrets::CredentialManager => windows::accounts(SERVICE),
+ }
+ }
+
/// The account of every secret, for `secretStorageService.keys()`.
#[cfg(target_os = "macos")]
fn accounts(&self) -> Result<Vec<String>, KeychainError> {
diff --git a/native/crates/exthost/src/main_thread_secret_state/windows.rs b/native/crates/exthost/src/main_thread_secret_state/windows.rs
new file mode 100644
index 00000000000..7c28d5352cb
--- /dev/null
+++ b/native/crates/exthost/src/main_thread_secret_state/windows.rs
@@ -0,0 +1,96 @@
+//! The secrets in Windows Credential Manager with keytar's layout: a generic credential whose target is
+//! `<service>/<account>`, user name the account and blob the UTF-8 secret.
+
+use std::io::{Error, Result};
+
+use windows_sys::Win32::Foundation::{ERROR_NOT_FOUND, FILETIME};
+use windows_sys::Win32::Security::Credentials::{
+ CRED_PERSIST_ENTERPRISE, CRED_TYPE_GENERIC, CREDENTIALW, CredDeleteW, CredEnumerateW, CredFree, CredReadW, CredWriteW,
+};
+
+pub fn get(service: &str, account: &str) -> Result<Option<String>> {
+ let target = wide(&format!("{service}/{account}"));
+ let mut credential = std::ptr::null_mut::<CREDENTIALW>();
+ if unsafe { CredReadW(target.as_ptr(), CRED_TYPE_GENERIC, 0, &mut credential) } == 0 {
+ return not_found_as(None);
+ }
+ let secret = unsafe { blob(&*credential) };
+ unsafe { CredFree(credential.cast()) };
+ Ok(Some(secret))
+}
+
+pub fn set(service: &str, account: &str, value: &str) -> Result<()> {
+ let mut target = wide(&format!("{service}/{account}"));
+ let mut user_name = wide(account);
+ let credential = CREDENTIALW {
+ Flags: 0,
+ Type: CRED_TYPE_GENERIC,
+ TargetName: target.as_mut_ptr(),
+ Comment: std::ptr::null_mut(),
+ LastWritten: FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 },
+ CredentialBlobSize: value.len() as u32,
+ CredentialBlob: value.as_ptr().cast_mut(),
+ Persist: CRED_PERSIST_ENTERPRISE,
+ AttributeCount: 0,
+ Attributes: std::ptr::null_mut(),
+ TargetAlias: std::ptr::null_mut(),
+ UserName: user_name.as_mut_ptr(),
+ };
+ match unsafe { CredWriteW(&credential, 0) } {
+ 0 => Err(Error::last_os_error()),
+ _ => Ok(()),
+ }
+}
+
+/// Whether a secret was there to delete.
+pub fn delete(service: &str, account: &str) -> Result<bool> {
+ let target = wide(&format!("{service}/{account}"));
+ match unsafe { CredDeleteW(target.as_ptr(), CRED_TYPE_GENERIC, 0) } {
+ 0 => not_found_as(false),
+ _ => Ok(true),
+ }
+}
+
+/// keytar's `findCredentials`: the user name of every credential whose target starts with `<service>`.
+pub fn accounts(service: &str) -> Result<Vec<String>> {
+ let filter = wide(&format!("{service}*"));
+ let mut count = 0;
+ let mut credentials = std::ptr::null_mut::<*mut CREDENTIALW>();
+ if unsafe { CredEnumerateW(filter.as_ptr(), 0, &mut count, &mut credentials) } == 0 {
+ return not_found_as(Vec::new());
+ }
+ let mut accounts = Vec::new();
+ for credential in unsafe { std::slice::from_raw_parts(credentials, count as usize) } {
+ let user_name = unsafe { (**credential).UserName };
+ if !user_name.is_null() {
+ accounts.push(unsafe { from_wide(user_name) });
+ }
+ }
+ unsafe { CredFree(credentials.cast()) };
+ Ok(accounts)
+}
+
+fn not_found_as<T>(value: T) -> Result<T> {
+ let error = Error::last_os_error();
+ match error.raw_os_error() == Some(ERROR_NOT_FOUND as i32) {
+ true => Ok(value),
+ false => Err(error),
+ }
+}
+
+unsafe fn blob(credential: &CREDENTIALW) -> String {
+ if credential.CredentialBlobSize == 0 {
+ return String::new();
+ }
+ let bytes = unsafe { std::slice::from_raw_parts(credential.CredentialBlob, credential.CredentialBlobSize as usize) };
+ String::from_utf8_lossy(bytes).into_owned()
+}
+
+unsafe fn from_wide(text: *const u16) -> String {
+ let length = (0..).take_while(|&index| unsafe { *text.add(index) } != 0).count();
+ String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(text, length) })
+}
+
+fn wide(text: &str) -> Vec<u16> {
+ text.encode_utf16().chain(std::iter::once(0)).collect()
+}
diff --git a/native/crates/exthost/src/pipe.rs b/native/crates/exthost/src/pipe.rs
new file mode 100644
index 00000000000..6606bbcc0b6
--- /dev/null
+++ b/native/crates/exthost/src/pipe.rs
@@ -0,0 +1,54 @@
+//! 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.
+
+use std::io::{Error, ErrorKind, Read, Result, Write};
+use std::path::Path;
+
+pub enum Listener {}
+
+pub enum Stream {}
+
+impl Listener {
+ pub fn bind(_path: &Path) -> Result<Listener> {
+ Err(Error::new(ErrorKind::Unsupported, "the extension host does not run on Windows yet"))
+ }
+
+ pub fn set_nonblocking(&self, _nonblocking: bool) -> Result<()> {
+ match *self {}
+ }
+
+ pub fn accept(&self) -> Result<(Stream, ())> {
+ match *self {}
+ }
+}
+
+impl Stream {
+ #[cfg(test)]
+ pub fn pair() -> Result<(Stream, Stream)> {
+ Err(Error::new(ErrorKind::Unsupported, "no named pipe pair on Windows yet"))
+ }
+
+ pub fn try_clone(&self) -> Result<Stream> {
+ match *self {}
+ }
+
+ pub fn set_nonblocking(&self, _nonblocking: bool) -> Result<()> {
+ match *self {}
+ }
+}
+
+impl Read for Stream {
+ fn read(&mut self, _buf: &mut [u8]) -> Result<usize> {
+ match *self {}
+ }
+}
+
+impl Write for Stream {
+ fn write(&mut self, _buf: &[u8]) -> Result<usize> {
+ match *self {}
+ }
+
+ fn flush(&mut self) -> Result<()> {
+ match *self {}
+ }
+}
diff --git a/native/crates/exthost/src/request.rs b/native/crates/exthost/src/request.rs
index fafff9c98cb..60305580a62 100644
--- a/native/crates/exthost/src/request.rs
+++ b/native/crates/exthost/src/request.rs
@@ -6,12 +6,18 @@ use std::time::Duration;
use anyhow::bail;
-#[cfg(target_os = "linux")]
+#[cfg(any(target_os = "linux", target_os = "windows"))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
+#[cfg(target_os = "windows")]
+mod windows;
#[cfg(target_os = "linux")]
use linux::{lookup_kerberos_authorization, resolve_proxy_with, send};
+#[cfg(target_os = "windows")]
+use linux::send;
+#[cfg(target_os = "windows")]
+use windows::{lookup_kerberos_authorization, resolve_proxy_with};
#[cfg(target_os = "macos")]
use macos::{lookup_kerberos_authorization, resolve_proxy_with, send};
diff --git a/native/crates/exthost/src/request/linux.rs b/native/crates/exthost/src/request/linux.rs
index 4de2edcab19..d7cbda7ebd2 100644
--- a/native/crates/exthost/src/request/linux.rs
+++ b/native/crates/exthost/src/request/linux.rs
@@ -10,11 +10,13 @@ use super::{Request, Response, SessionProxy};
/// proxy-agent asks only when neither `http.proxy` nor the proxy variables name a proxy, the sources of the session
/// proxy and of Chromium's Linux system proxy outside GNOME and KDE.
+#[cfg(target_os = "linux")]
pub(super) fn resolve_proxy_with(_url: &str, _proxy: Option<&SessionProxy>) -> Option<String> {
Some("DIRECT".to_owned())
}
// shortcut: no GSS-API binding on Linux, so proxies that need Kerberos fail; link libgssapi_krb5 as macos.rs links GSS.
+#[cfg(target_os = "linux")]
pub(super) fn lookup_kerberos_authorization(_spn: &str) -> anyhow::Result<String> {
bail!("Kerberos is not available on Linux")
}
diff --git a/native/crates/exthost/src/request/windows.rs b/native/crates/exthost/src/request/windows.rs
new file mode 100644
index 00000000000..fb69975ef2e
--- /dev/null
+++ b/native/crates/exthost/src/request/windows.rs
@@ -0,0 +1,13 @@
+//! request.rs on Windows: `send` is linux.rs's curl, the curl.exe Windows 10 1803 and later ship in System32.
+
+use super::SessionProxy;
+
+// shortcut: no system proxy, curl reads only the proxy variables; read WinHTTP's IE proxy settings (port/ledger.md M24 row exthost/src/request.rs:9).
+pub(super) fn resolve_proxy_with(_url: &str, _proxy: Option<&SessionProxy>) -> Option<String> {
+ Some("DIRECT".to_owned())
+}
+
+// shortcut: no SSPI binding, so proxies that need Kerberos fail; call InitializeSecurityContextW as macos.rs calls GSS.
+pub(super) fn lookup_kerberos_authorization(_spn: &str) -> anyhow::Result<String> {
+ anyhow::bail!("Kerberos is not available on Windows")
+}
diff --git a/native/crates/exthost/src/zip.rs b/native/crates/exthost/src/zip.rs
index 3f1b97adf7a..61882ff5fa2 100644
--- a/native/crates/exthost/src/zip.rs
+++ b/native/crates/exthost/src/zip.rs
@@ -131,7 +131,15 @@ impl Archive {
}
std::fs::create_dir_all(path.parent().expect("a joined file name has a parent"))?;
std::fs::write(&path, self.read(entry)?)?;
+ #[cfg(unix)]
std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(entry.mode))?;
+ // libuv's open on Windows keeps only the owner write bit of the mode, as the read-only attribute.
+ #[cfg(windows)]
+ if entry.mode & 0o200 == 0 {
+ let mut permissions = std::fs::metadata(&path)?.permissions();
+ permissions.set_readonly(true);
+ std::fs::set_permissions(&path, permissions)?;
+ }
}
Ok(())
}
diff --git a/native/crates/files/src/disk.rs b/native/crates/files/src/disk.rs
index b292d11ac55..24e6f53d356 100644
--- a/native/crates/files/src/disk.rs
+++ b/native/crates/files/src/disk.rs
@@ -5,7 +5,9 @@ use std::io::ErrorKind;
use std::path::Path;
use std::time::SystemTime;
-use crate::{DIRECTORY, EXECUTABLE, FILE, FileSystem, LOCKED, Resource, Result, SYMBOLIC_LINK, Stat};
+#[cfg(unix)]
+use crate::EXECUTABLE;
+use crate::{DIRECTORY, FILE, FileSystem, LOCKED, Resource, Result, SYMBOLIC_LINK, Stat};
use crate::{FILE_EXISTS, FILE_IS_A_DIRECTORY, FILE_NOT_A_DIRECTORY, FILE_NOT_FOUND, NO_PERMISSIONS, UNAVAILABLE, UNKNOWN, provider_error};
/// diskFileSystemProviderClient.ts on macOS: FileReadWrite, FileOpenReadWriteClose, FileReadStream, FileFolderCopy,
@@ -55,17 +57,37 @@ pub fn stat_path(path: &Path) -> Result<Stat> {
if is_link {
file_type |= SYMBOLIC_LINK;
}
+ let permissions = permissions(&metadata);
+ let millis = |time: std::io::Result<SystemTime>| time.ok().and_then(|time| time.duration_since(SystemTime::UNIX_EPOCH).ok()).map_or(0, |since| since.as_millis() as u64);
+ Ok(Stat { file_type, ctime: millis(metadata.created()), mtime: millis(metadata.modified()), size: metadata.len(), permissions })
+}
+
+#[cfg(unix)]
+fn permissions(metadata: &std::fs::Metadata) -> Option<u32> {
use std::os::unix::fs::PermissionsExt;
let mode = metadata.permissions().mode();
let mut permissions = None;
- if mode & 0o200 == 0 {
+ if write_locked(metadata) {
permissions = Some(LOCKED);
}
if mode & 0o111 != 0 {
permissions = Some(permissions.unwrap_or(0) | EXECUTABLE);
}
- let millis = |time: std::io::Result<SystemTime>| time.ok().and_then(|time| time.duration_since(SystemTime::UNIX_EPOCH).ok()).map_or(0, |since| since.as_millis() as u64);
- Ok(Stat { file_type, ctime: millis(metadata.created()), mtime: millis(metadata.modified()), size: metadata.len(), permissions })
+ permissions
+}
+
+/// libuv maps only the read-only attribute into `mode`, and Node's `S_IX*` are undefined on win32: never Executable.
+#[cfg(windows)]
+fn permissions(metadata: &std::fs::Metadata) -> Option<u32> {
+ write_locked(metadata).then_some(LOCKED)
+}
+
+/// diskFileSystemProvider.ts `stat`'s Locked: no owner write bit, on Windows the read-only attribute.
+pub fn write_locked(metadata: &std::fs::Metadata) -> bool {
+ #[cfg(unix)]
+ return std::os::unix::fs::PermissionsExt::mode(&metadata.permissions()) & 0o200 == 0;
+ #[cfg(windows)]
+ return metadata.permissions().readonly();
}
/// `writeFile`'s checks of the `create` and `overwrite` options.
@@ -101,7 +123,7 @@ fn copy_entry(source: &Path, target: &Path) -> Result<()> {
let metadata = std::fs::symlink_metadata(source).map_err(|err| io_error(err, "lstat", source))?;
if metadata.file_type().is_symlink() {
let link = std::fs::read_link(source).map_err(|err| io_error(err, "readlink", source))?;
- return std::os::unix::fs::symlink(link, target).map_err(|err| io_error(err, "symlink", target));
+ return symlink(&link, source, target).map_err(|err| io_error(err, "symlink", target));
}
if !metadata.is_dir() {
return std::fs::copy(source, target).map(|_| ()).map_err(|err| io_error(err, "copyfile", source));
@@ -117,6 +139,20 @@ fn copy_entry(source: &Path, target: &Path) -> Result<()> {
Ok(())
}
+#[cfg(unix)]
+fn symlink(link: &Path, _source: &Path, target: &Path) -> std::io::Result<()> {
+ std::os::unix::fs::symlink(link, target)
+}
+
+/// Node's `fs.symlink` without a type on Windows: a directory link when the target is a directory.
+#[cfg(windows)]
+fn symlink(link: &Path, source: &Path, target: &Path) -> std::io::Result<()> {
+ match std::fs::metadata(source).is_ok_and(|metadata| metadata.is_dir()) {
+ true => std::os::windows::fs::symlink_dir(link, target),
+ false => std::os::windows::fs::symlink_file(link, target),
+ }
+}
+
impl FileSystem for Disk {
fn capabilities(&mut self, scheme: &str) -> Option<u32> {
(scheme == "file").then_some(CAPABILITIES)
diff --git a/native/crates/storage/Cargo.toml b/native/crates/storage/Cargo.toml
index 937605dbfee..6b00612924b 100644
--- a/native/crates/storage/Cargo.toml
+++ b/native/crates/storage/Cargo.toml
@@ -9,3 +9,7 @@ license.workspace = true
rusqlite = "0.37"
serde.workspace = true
serde_json.workspace = true
+
+# Windows ships no SQLite library to link; upstream's @vscode/sqlite3 builds its own copy there too.
+[target.'cfg(target_os = "windows")'.dependencies]
+rusqlite = { version = "0.37", features = ["bundled"] }
diff --git a/port/tools/windows-build b/port/tools/windows-build
new file mode 100755
index 00000000000..0745445f7fc
--- /dev/null
+++ b/port/tools/windows-build
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Syncs this checkout to its Mac Studio mirror (port/tools/studio) and runs a command in native/ with the Windows cross
+# toolchain on PATH: cargo-xwin, Homebrew llvm (clang-cl) and lld (lld-link). Compile checks only; Windows runs are windows.yml.
+# Usage: port/tools/windows-build 'cargo gc xwin build -p app --target x86_64-pc-windows-msvc'
+set -euo pipefail
+exec "$(dirname "$0")/studio" "cd native && PATH=/opt/homebrew/opt/llvm/bin:/opt/homebrew/opt/lld/bin:\$PATH bash -c $(printf '%q' "$1")"