Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(windows): hide console children and fall back to USERPROFILE (#83)

Artur Rokeac6e824bd62
diff --git a/native/crates/app/src/encoding_guess.rs b/native/crates/app/src/encoding_guess.rs
index 0972caafad3..494b0107754 100644
--- a/native/crates/app/src/encoding_guess.rs
+++ b/native/crates/app/src/encoding_guess.rs
@@ -63,14 +63,16 @@ fn guess(bytes: &[u8], candidates: Option<Value>) -> Option<String> {
}
fn start_worker(app_root: &Path) -> std::io::Result<Worker> {
- let mut child = Command::new(exthost::Runtime::Bun.executable())
+ let mut command = Command::new(exthost::Runtime::Bun.executable());
+ command
.args(["--eval", include_str!("encoding_guess/worker.mjs")])
.env("VSCODE_NODE_MODULES", app_root.join("node_modules"))
.env("DO_NOT_TRACK", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()?;
+ .stderr(Stdio::null());
+ exthost::hide_console(&mut command);
+ let mut child = command.spawn()?;
Ok(Worker { stdin: child.stdin.take().expect("piped"), stdout: BufReader::new(child.stdout.take().expect("piped")) })
}
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index 9547a30b850..26e67facc90 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -243,7 +243,7 @@ fn main() -> anyhow::Result<()> {
flag_value("--export-default-keybindings").filter(|folder| !folder.starts_with("--")).map_or_else(|| app_root.join("doc"), |folder| working_dir.join(folder))
});
// Before any scan: the display language decides the manifests' messages.
- let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
+ let home = home_dir().unwrap_or_default();
let locale = nls::user_locale(flag_value("--locale").as_deref(), &output::log_levels::argv_file(&home));
perf::mark("code/willGenerateNls");
let resolved = exthost::language_packs::resolve_nls(&user_data, &locale);
@@ -550,7 +550,7 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul
workbench.apply_proxy_settings();
let window_logs = exthost::session::window_logs_path(&user_data);
workbench.register_window_log(window_logs.join("renderer.log"));
- let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
+ let home = home_dir().unwrap_or_default();
workbench.start_logs(output::log_levels::argv_file(&home), window_logs.parent().expect("a session folder").to_path_buf(), cx);
workbench.skip_dialogs = development.as_ref().is_some_and(|development| development.tests_path.is_some());
workbench.refresh_keyboard_mapper();
@@ -844,7 +844,7 @@ fn add_recently_opened<'a>(shared: &mut storage::Storage, workspace: Option<&Wor
fn open_shared_storage(shared_data: Option<PathBuf>) -> anyhow::Result<storage::Storage> {
let shared_data = match shared_data {
Some(dir) => dir,
- None => PathBuf::from(std::env::var_os("HOME").context("HOME is not set")?).join(".vscode-gpui-shared"),
+ None => home_dir().context("HOME or USERPROFILE is not set")?.join(".vscode-gpui-shared"),
};
let dir = shared_data.join("sharedStorage");
std::fs::create_dir_all(&dir)?;
@@ -903,10 +903,15 @@ pub(crate) fn scan_system_extensions(app_root: &Path) -> anyhow::Result<Vec<Scan
Ok(extensions)
}
+/// `os.homedir()`: a Windows session started from Explorer has `USERPROFILE` but no `HOME`.
+pub(crate) fn home_dir() -> Option<PathBuf> {
+ std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
+}
+
fn default_user_data() -> anyhow::Result<PathBuf> {
- let home = std::env::var_os("HOME").ok_or_else(|| anyhow::anyhow!("HOME is not set"))?;
+ let home = home_dir().ok_or_else(|| anyhow::anyhow!("HOME or USERPROFILE is not set"))?;
// Artur: all user data lives in ~/.vsrustium, product.json `dataFolderName`.
- let dir = PathBuf::from(home).join(".vsrustium");
+ let dir = home.join(".vsrustium");
std::fs::create_dir_all(&dir)?;
Ok(dir)
}
diff --git a/native/crates/app/src/workbench/language_detection.rs b/native/crates/app/src/workbench/language_detection.rs
index 666536d9c5a..88516e9b5d7 100644
--- a/native/crates/app/src/workbench/language_detection.rs
+++ b/native/crates/app/src/workbench/language_detection.rs
@@ -229,14 +229,16 @@ impl Workbench {
/// the waiting requests.
fn start_worker(app_root: &Path) -> std::io::Result<Worker> {
let root = app_root.join("node_modules/@vscode/vscode-languagedetection");
- let mut child = Command::new(exthost::Runtime::Bun.executable())
+ let mut command = Command::new(exthost::Runtime::Bun.executable());
+ command
.args(["--eval", include_str!("../language_detection/worker.mjs")])
.env("VSCODE_LANGUAGE_DETECTION_ROOT", &root)
.env("DO_NOT_TRACK", "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
- .stderr(Stdio::null())
- .spawn()?;
+ .stderr(Stdio::null());
+ exthost::hide_console(&mut command);
+ let mut child = command.spawn()?;
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let pending: Pending = Arc::default();
diff --git a/native/crates/app/src/workbench/localization.rs b/native/crates/app/src/workbench/localization.rs
index 8ec9cca60b4..a36fce20848 100644
--- a/native/crates/app/src/workbench/localization.rs
+++ b/native/crates/app/src/workbench/localization.rs
@@ -180,7 +180,7 @@ impl Workbench {
/// `writeLocaleValue` into argv.json.
fn write_locale(&self, locale: Option<&str>) -> std::io::Result<()> {
- let home = PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
+ let home = crate::home_dir().unwrap_or_default();
let argv_file = crate::output::log_levels::argv_file(&home);
let configuration = self.settings.lock().unwrap().configuration.clone();
crate::nls::write_argv_locale(&argv_file, locale, |content| config::service::formatting_options(content, &configuration, &argv_file))
diff --git a/native/crates/exthost/src/lib.rs b/native/crates/exthost/src/lib.rs
index 24da821ba1c..ad8b8ddae22 100644
--- a/native/crates/exthost/src/lib.rs
+++ b/native/crates/exthost/src/lib.rs
@@ -32,6 +32,8 @@ 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};
@@ -42,6 +44,15 @@ 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;
@@ -212,6 +223,7 @@ impl ExtensionHost {
// 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))?;
diff --git a/native/crates/search/src/ripgrep.rs b/native/crates/search/src/ripgrep.rs
index 7bc4bc39a5e..2cf68c8d155 100644
--- a/native/crates/search/src/ripgrep.rs
+++ b/native/crates/search/src/ripgrep.rs
@@ -2,6 +2,8 @@
//! share (search/node/ripgrepTextSearchEngine.ts).
use std::io::{BufRead, BufReader, Read};
+#[cfg(windows)]
+use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
@@ -60,7 +62,12 @@ pub struct Finished {
/// Runs ripgrep in `cwd` and hands each stdout line (without the newline) to `on_line` until it returns false, which
/// kills ripgrep. With `count_symlink_loops` (a run with `--follow`), too many reported loops kill it too.
pub fn run(rg: &Path, args: &[String], cwd: &Path, cancellation: &Cancellation, count_symlink_loops: bool, on_line: &mut dyn FnMut(&str) -> bool) -> std::io::Result<Finished> {
- let mut child = Command::new(rg).args(args).current_dir(cwd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
+ let mut command = Command::new(rg);
+ command.args(args).current_dir(cwd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
+ // CREATE_NO_WINDOW: rg.exe is a console program, each search would flash a console window on Windows.
+ #[cfg(windows)]
+ command.creation_flags(0x0800_0000);
+ let mut child = command.spawn()?;
let stdout = child.stdout.take().expect("stdout is piped");
let stderr = child.stderr.take().expect("stderr is piped");
*cancellation.child.lock().unwrap() = Some(child);
diff --git a/port/notes.md b/port/notes.md
index ef9ba2faa66..19fa3e03f99 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -1050,6 +1050,7 @@ What to do (milestone 21, in order):
- Webview seam: `webview.rs` holds the one `Webview` (the message queue before `webview-ready`, focus, find, the clipboard choice) and `Resources` (`serve` answers the host page and resource hosts, `receive` the bridge messages); each backend is a `Native` with creation, keyboard, inspector and `evaluate`, plus its own request hook calling `serve`: WKURLSchemeHandler on `https`, the WebResourceRequested filter, the Linux TLS proxy. A `file` resource is read at its `fsPath` on every platform, the path `is_contained` checked. Rechecked against wry 0.58.2 (Tauri's webview crate): WebView2 custom protocols cover only `https://<name>.*` hosts, WKWebView takes an `https` handler only through our `allow_https_scheme_handler` swizzle, and WebKitGTK refuses an `https` handler, so the `https://*.vscode-cdn.net` hosts the host page and its CSP need would keep all three hooks beside wry, which also pins webview2-com 0.39 and windows 0.62 against our 0.38 and 0.61. The decision "Windows webview" stands.
- 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.
+- Console children: a console program (Bun, rg.exe) started by a GUI-subsystem parent gets a new console window, so the extension host, the encoding and language detection workers and ripgrep spawn with `CREATE_NO_WINDOW` (`exthost::hide_console`, `search::ripgrep::run`), Node's `windowsHide`. The home folder is `HOME`, else `USERPROFILE` (`home_dir` in app/src/main.rs, `os.homedir()`), since a start from Explorer has no `HOME`. Both from PR #78 by vikasdeshmukh63.
- Proxy: `request/windows.rs` sends through curl.exe as Linux does, with the proxy picked first: the session proxy, else the IE settings, auto-detect and the PAC URL through WinHTTP's resolver where Chromium runs the script in its own V8 (same answer, other engine), then the manual proxy. The rule and bypass parsing is Chromium's (`request/proxy_rules.rs`, built on every platform for its host tests). Difference: curl takes one proxy, so a PAC list's later entries are no fallback. `WinHttpGetProxyForUrl` runs without `fAutoLogonIfChallenged` first and with it only after `ERROR_WINHTTP_LOGIN_FAILURE`, as Chromium's proxy_resolver_winhttp.cc, so the logon credentials go to a WPAD or PAC server only when it asks.
- File URIs: `uri.rs` `Uri::file` and `fs_path` are uri.ts `URI.file` and `uriToFsPath`, with the platform a parameter so the host tests check the Windows branches. The editor's model URIs take them on Windows only: elsewhere the port keeps a `//host/a` model path in the URI path (editor.rs `a_non_file_uri_keeps_its_authority`) where upstream makes `host` the authority.
- UNC hosts: `files/src/unc.rs` is base/node/unc.ts with the allowlist Electron's Node checks on every `fs` call (`ERR_UNC_HOST_NOT_ALLOWED`). The port has no patched `fs`, so the check sits on its file seams: disk.rs `path` (the file service, with diskFileSystemProvider.ts's "Please update the 'security.allowedUNCHosts' setting" suffix), the text file models, editor reads and webview resources. Node checks the namespaced path, so `//host/share` counts as UNC and `\\.\` and `\\?\` paths without a host it understands fail closed. main.rs `configure_unc_access` reads `security.restrictUNCAccess` and `security.allowedUNCHosts` once at start as app.ts (a restart applies a change, as upstream's setting text says) and allows the extensions folder's host as main.ts `allowWindowsUNCPath`. The settings register on Windows only (workbench/common/configuration.ts). The extension host is Node's own `fs` upstream, so `src-uncFsGuard.patch` wraps `fs`, `fs.promises` and `fs/promises` on Windows from the `NODE_UNC_HOST_ALLOWLIST` or `NODE_DISABLE_UNC_ACCESS_CHECKS` the app sets as utilityProcess.ts; Bun's ESM named imports of a builtin do not see changes to its module object, so build-exthost routes the bundle's `fs` imports through `createRequire`. In the app the gate sits before each probe of a path the user did not open (terminal links, problem matcher, quick open's absolute path); Open, Open Recent and `vscode://file` URLs ask with windowsMainService.ts `onUNCHostNotAllowed`. Left as gaps: command line paths, reads inside an opened folder and child process cwds (ledger row `app/src/editor_history.rs:59`).