diff --git a/Cargo.lock b/Cargo.lock index d7d2699c5..ee8a1658a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4252,16 +4252,20 @@ name = "ide-core" version = "0.1.51" dependencies = [ "base64 0.22.1", + "dirs 6.0.0", "dunce", "encoding_rs", "libc", + "portable-pty", "serde", "serde_json", + "sha2 0.10.9", "specta", "specta-typescript", "tempfile", "thiserror 2.0.21", "tokio-util", + "tracing", "windows-sys 0.61.2", ] diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 4dfc450f4..27379cb10 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -6,6 +6,13 @@ [Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md). +## Microsoft ConPTY + +`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console +ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft +Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE) +and [package provenance](crates/ide-core/resources/conpty/README.md). + ## Project Lombok `java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox diff --git a/crates/ide-core/Cargo.toml b/crates/ide-core/Cargo.toml index 73559f241..29364ce7a 100644 --- a/crates/ide-core/Cargo.toml +++ b/crates/ide-core/Cargo.toml @@ -15,12 +15,16 @@ specta.workspace = true specta-typescript.workspace = true thiserror.workspace = true tokio-util.workspace = true +portable-pty.workspace = true [dev-dependencies] +sha2 = "0.10" tempfile.workspace = true [target.'cfg(unix)'.dependencies] libc = "0.2" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] } +dirs.workspace = true +tracing.workspace = true +windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] } diff --git a/crates/ide-core/resources/conpty/LICENSE b/crates/ide-core/resources/conpty/LICENSE new file mode 100644 index 000000000..8cb179cdb --- /dev/null +++ b/crates/ide-core/resources/conpty/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/ide-core/resources/conpty/README.md b/crates/ide-core/resources/conpty/README.md new file mode 100644 index 000000000..0d832c1db --- /dev/null +++ b/crates/ide-core/resources/conpty/README.md @@ -0,0 +1,39 @@ +# Bundled Windows console host + +Unmodified files from Microsoft's MIT-licensed +[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003). +The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then +puts full-screen applications' redraws in normal scrollback. A current console host +preserves those transitions, including while resizing and updating a running TUI. + +The package is pinned, checked in and embedded by `ide-core`, so desktop, server, +Run and debugger builds work offline and do not depend on another installed IDE. +Only the target architecture is embedded, along with its MIT license. `src/pty.rs` +extracts them atomically to a versioned user cache and preloads the DLL's absolute +path before portable-pty initializes. +Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading +failure is logged and falls back to the system backend. Windows builds before +19041 also retain the system backend. + +Source archive: +`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg` + +Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee` + +For each architecture, `conpty.dll` comes from +`runtimes/win-/native/conpty.dll`, and `OpenConsole.exe` from +`build/native/runtimes//OpenConsole.exe` in that archive. Preserve the pair and +the license when updating; update `VERSION` in `src/pty.rs` and these checksums too. + +| File | SHA-256 | +| --------------------- | ------------------------------------------------------------------ | +| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` | +| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` | +| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` | +| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` | +| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` | +| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` | + +Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child +console application and requires alternate-screen entry and exit to reach the +reader; a system ConPTY that consumes them fails this check. diff --git a/crates/ide-core/resources/conpty/arm64/OpenConsole.exe b/crates/ide-core/resources/conpty/arm64/OpenConsole.exe new file mode 100644 index 000000000..9aaab0310 Binary files /dev/null and b/crates/ide-core/resources/conpty/arm64/OpenConsole.exe differ diff --git a/crates/ide-core/resources/conpty/arm64/conpty.dll b/crates/ide-core/resources/conpty/arm64/conpty.dll new file mode 100644 index 000000000..fa63d77a4 Binary files /dev/null and b/crates/ide-core/resources/conpty/arm64/conpty.dll differ diff --git a/crates/ide-core/resources/conpty/x64/OpenConsole.exe b/crates/ide-core/resources/conpty/x64/OpenConsole.exe new file mode 100644 index 000000000..7abcd7696 Binary files /dev/null and b/crates/ide-core/resources/conpty/x64/OpenConsole.exe differ diff --git a/crates/ide-core/resources/conpty/x64/conpty.dll b/crates/ide-core/resources/conpty/x64/conpty.dll new file mode 100644 index 000000000..3230106e8 Binary files /dev/null and b/crates/ide-core/resources/conpty/x64/conpty.dll differ diff --git a/crates/ide-core/resources/conpty/x86/OpenConsole.exe b/crates/ide-core/resources/conpty/x86/OpenConsole.exe new file mode 100644 index 000000000..fe5c37624 Binary files /dev/null and b/crates/ide-core/resources/conpty/x86/OpenConsole.exe differ diff --git a/crates/ide-core/resources/conpty/x86/conpty.dll b/crates/ide-core/resources/conpty/x86/conpty.dll new file mode 100644 index 000000000..a07efd6aa Binary files /dev/null and b/crates/ide-core/resources/conpty/x86/conpty.dll differ diff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rs index 2932e667e..2101c12f9 100644 --- a/crates/ide-core/src/lib.rs +++ b/crates/ide-core/src/lib.rs @@ -25,6 +25,7 @@ pub mod project_dir; pub mod project_env; pub mod project_roots; pub mod proxy_settings; +pub mod pty; pub mod real_path; pub mod remote_settings; pub mod settings; diff --git a/crates/ide-core/src/pty.rs b/crates/ide-core/src/pty.rs new file mode 100644 index 000000000..32398d489 --- /dev/null +++ b/crates/ide-core/src/pty.rs @@ -0,0 +1,254 @@ +//! The PTY backend shared by terminals, Run consoles and debugger launchers. + +pub fn native_pty_system() -> Box { + #[cfg(windows)] + windows::initialize(); + portable_pty::native_pty_system() +} + +#[cfg(windows)] +mod windows { + use std::fs; + use std::io::{self, Write}; + use std::os::windows::ffi::OsStrExt; + use std::path::Path; + use std::sync::OnceLock; + use std::sync::atomic::{AtomicU64, Ordering}; + use windows_sys::Win32::Foundation::FreeLibrary; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + + const VERSION: &str = "1.25.260930003"; + #[cfg(target_arch = "x86_64")] + const RUNTIME: (&str, &[u8], &[u8]) = ( + "x64", + include_bytes!("../resources/conpty/x64/conpty.dll"), + include_bytes!("../resources/conpty/x64/OpenConsole.exe"), + ); + #[cfg(target_arch = "aarch64")] + const RUNTIME: (&str, &[u8], &[u8]) = ( + "arm64", + include_bytes!("../resources/conpty/arm64/conpty.dll"), + include_bytes!("../resources/conpty/arm64/OpenConsole.exe"), + ); + #[cfg(target_arch = "x86")] + const RUNTIME: (&str, &[u8], &[u8]) = ( + "x86", + include_bytes!("../resources/conpty/x86/conpty.dll"), + include_bytes!("../resources/conpty/x86/OpenConsole.exe"), + ); + + pub(super) fn initialize() -> bool { + static BUNDLED: OnceLock = OnceLock::new(); + *BUNDLED.get_or_init(|| { + if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) { + return false; + } + match load() { + Ok(()) => true, + Err(error) => { + tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend"); + false + } + } + }) + } + + fn load() -> io::Result<()> { + let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?; + let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0); + fs::create_dir_all(&directory)?; + install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?; + install(&directory.join("OpenConsole.exe"), RUNTIME.2)?; + let library = directory.join("conpty.dll"); + install(&library, RUNTIME.1)?; + let wide: Vec = library.as_os_str().encode_wide().chain(Some(0)).collect(); + // portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path: + // Windows reuses this module, without adding the project directory to DLL search. + // SAFETY: the path is terminated and the module is retained for the process lifetime. + let module = unsafe { + LoadLibraryExW( + wide.as_ptr(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return Err(io::Error::last_os_error()); + } + for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] { + // SAFETY: `module` is loaded and each name is a terminated export name. + if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() { + // SAFETY: no PTY uses this rejected module yet; release our load reference. + unsafe { FreeLibrary(module) }; + return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports")); + } + } + // Keep this reference for the process lifetime, including between PTY sessions. + tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY"); + Ok(()) + } + + fn install(path: &Path, data: &[u8]) -> io::Result<()> { + if fs::read(path).is_ok_and(|existing| existing == data) { + return Ok(()); + } + static NEXT: AtomicU64 = AtomicU64::new(0); + let pending = + path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let result = (|| { + let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?; + file.write_all(data)?; + file.sync_all()?; + drop(file); + match fs::rename(&pending, path) { + Ok(()) => Ok(()), + Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()), + Err(error) => Err(error), + } + })(); + let _ = fs::remove_file(pending); + result + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn installs_atomically_and_repairs_incomplete_files() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("conpty.dll"); + fs::write(&path, b"partial").unwrap(); + std::thread::scope(|scope| { + for _ in 0..8 { + let path = &path; + scope.spawn(move || install(path, b"complete runtime").unwrap()); + } + }); + assert_eq!(fs::read(&path).unwrap(), b"complete runtime"); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1); + } + + #[test] + fn loads_the_bundled_backend() { + assert!(initialize()); + } + + #[test] + fn conpty_output_child() { + if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() { + return; + } + use windows_sys::Win32::System::Console::{ + ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode, + }; + // SAFETY: the inherited console output handle and a local writable mode word. + unsafe { + let output = GetStdHandle(STD_OUTPUT_HANDLE); + let mut mode = 0; + assert_ne!(GetConsoleMode(output, &mut mode), 0); + assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0); + } + std::io::stdout() + .write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n") + .unwrap(); + std::io::stdout().flush().unwrap(); + } + + #[test] + fn conpty_preserves_alternate_screen_transitions() { + use std::io::Read; + use std::sync::mpsc; + use std::time::{Duration, Instant}; + let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap(); + let mut reader = pair.master.try_clone_reader().unwrap(); + let mut writer = pair.master.take_writer().unwrap(); + let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap()); + command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]); + command.env("OPENIDEA_CONPTY_TEST_CHILD", "1"); + let mut child = pair.slave.spawn_command(command).unwrap(); + drop(pair.slave); + let (tx, rx) = mpsc::channel(); + let reading = std::thread::spawn(move || { + let mut bytes = [0; 4096]; + while let Ok(count) = reader.read(&mut bytes) { + if count == 0 || tx.send(bytes[..count].to_vec()).is_err() { + break; + } + } + }); + let deadline = Instant::now() + Duration::from_secs(10); + let mut output = Vec::new(); + let mut cursor_replied = false; + while Instant::now() < deadline { + if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) { + output.extend_from_slice(&bytes); + if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") { + writer.write_all(b"\x1b[1;1R").unwrap(); + cursor_replied = true; + } + if output.windows(7).any(|s| s == b"VT_DONE") { + break; + } + } + } + let _ = child.kill(); + let _ = child.wait(); + drop(writer); + drop(pair.master); + reading.join().unwrap(); + let output = String::from_utf8_lossy(&output); + assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}"); + assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}"); + } + } +} + +/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`). +#[cfg(test)] +mod checksums { + use sha2::{Digest, Sha256}; + + const FILES: [(&str, &[u8], &str); 6] = [ + ( + "arm64/conpty.dll", + include_bytes!("../resources/conpty/arm64/conpty.dll"), + "151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf", + ), + ( + "arm64/OpenConsole.exe", + include_bytes!("../resources/conpty/arm64/OpenConsole.exe"), + "4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f", + ), + ( + "x64/conpty.dll", + include_bytes!("../resources/conpty/x64/conpty.dll"), + "feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a", + ), + ( + "x64/OpenConsole.exe", + include_bytes!("../resources/conpty/x64/OpenConsole.exe"), + "3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586", + ), + ( + "x86/conpty.dll", + include_bytes!("../resources/conpty/x86/conpty.dll"), + "d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93", + ), + ( + "x86/OpenConsole.exe", + include_bytes!("../resources/conpty/x86/OpenConsole.exe"), + "e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3", + ), + ]; + + #[test] + fn embedded_runtime_matches_the_pinned_package() { + for (name, bytes, expected) in FILES { + let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(actual, expected, "{name}"); + } + } +} diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index bcac6752e..b06d0f0dd 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -1061,7 +1061,8 @@ fn reap_on_exit(mut child: Box, exited: A /// starts a launcher that gives the program its terminal, and the program reads input only from /// a terminal), forwards its output to the console, and keeps the terminal for typed input. pub(crate) fn run_in_terminal(s: &Arc, args: &Value) -> Result { - use portable_pty::{CommandBuilder, PtySize, native_pty_system}; + use ide_core::pty::native_pty_system; + use portable_pty::{CommandBuilder, PtySize}; let argv: Vec = args .get("args") .and_then(Value::as_array) diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 917427fab..852a464e2 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -3,9 +3,10 @@ use crate::utf8::OutputDecoder; use crate::{OutputChunk, RunAttach, RunConfig, RunInfo}; +use ide_core::pty::native_pty_system; use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink}; use parking_lot::Mutex; -use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system}; +use portable_pty::{CommandBuilder, MasterPty, PtySize}; use std::collections::{BTreeMap, VecDeque}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; diff --git a/crates/ide-terminal/src/lib.rs b/crates/ide-terminal/src/lib.rs index 512b4d5e7..dcb443b37 100644 --- a/crates/ide-terminal/src/lib.rs +++ b/crates/ide-terminal/src/lib.rs @@ -4,10 +4,11 @@ mod integration; mod scrollback; +use ide_core::pty::native_pty_system; use ide_core::utf8::Utf8Decoder; use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink, TerminalId}; use parking_lot::{Condvar, Mutex}; -use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system}; +use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize}; use serde::{Deserialize, Serialize}; use specta::Type; use std::collections::{BTreeMap, HashMap};