Skip to content

Visual Studio Code, rebuilt in Rust

Rust

docs(safety): state the invariant of every unsafe block

rokarturcfd6edb5170d
diff --git a/native/crates/app/src/cli.rs b/native/crates/app/src/cli.rs
index b527488c83b..b18140765ab 100644
--- a/native/crates/app/src/cli.rs
+++ b/native/crates/app/src/cli.rs
@@ -311,16 +311,19 @@ pub fn route_stdio_to_console() {
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| {
+ // SAFETY: GetStdHandle takes a handle id and returns a handle or null; no pointers pass.
let handle = unsafe { GetStdHandle(id) };
!handle.is_null() && handle != INVALID_HANDLE_VALUE
};
if redirected(STD_OUTPUT_HANDLE) || redirected(STD_ERROR_HANDLE) {
return;
}
+ // SAFETY: AttachConsole takes a process id constant; no pointers pass.
if unsafe { AttachConsole(ATTACH_PARENT_PROCESS) } == 0 {
return;
}
let name: Vec<u16> = "CONOUT$".encode_utf16().chain([0]).collect();
+ // SAFETY: `name` is NUL-terminated UTF-16, alive for the call; the security and template arguments may be null.
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;
@@ -336,6 +339,7 @@ pub fn route_stdio_to_console() {
#[cfg(windows)]
fn terminal_columns() -> usize {
use windows_sys::Win32::System::Console::{CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo, GetStdHandle, STD_OUTPUT_HANDLE};
+ // SAFETY: CONSOLE_SCREEN_BUFFER_INFO is plain integers, valid when zeroed.
let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { std::mem::zeroed() };
// SAFETY: the standard output handle and one info struct for the call to fill.
let ok = unsafe { GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) } != 0;
diff --git a/native/crates/app/src/file_dialog/macos.rs b/native/crates/app/src/file_dialog/macos.rs
index 39a67f1ec76..3b7c15a27b0 100644
--- a/native/crates/app/src/file_dialog/macos.rs
+++ b/native/crates/app/src/file_dialog/macos.rs
@@ -176,6 +176,7 @@ define_class!(
#[ivars = FormatState]
struct FormatHandler;
+ // SAFETY: the superclass is NSObject, which implements NSObjectProtocol.
unsafe impl NSObjectProtocol for FormatHandler {}
impl FormatHandler {
@@ -192,6 +193,7 @@ define_class!(
impl FormatHandler {
fn new(mtm: MainThreadMarker, state: FormatState) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(state);
+ // SAFETY: `init` of NSObject on the object allocated above, whose ivars are set.
unsafe { msg_send![super(this), init] }
}
}
diff --git a/native/crates/app/src/keyboard_layout/macos.rs b/native/crates/app/src/keyboard_layout/macos.rs
index a2f6701cf16..fc908397c79 100644
--- a/native/crates/app/src/keyboard_layout/macos.rs
+++ b/native/crates/app/src/keyboard_layout/macos.rs
@@ -44,6 +44,7 @@ unsafe extern "C" {
/// `getCurrentKeyboardLayout()`: `{ id, localizedName, lang }` of the current input source (IMacKeyboardLayoutInfo).
pub fn current_layout_info() -> Value {
let mut info = Map::new();
+ // SAFETY: TIS calls on the copied input source, released once below; each property is null or the type it is cast to (TextInputSources.h).
unsafe {
let source = TISCopyCurrentKeyboardInputSource();
let string = |key| (TISGetInputSourceProperty(source, key) as *const NSString).as_ref().map(|value| Value::from(value.to_string()));
@@ -66,6 +67,7 @@ pub fn current_layout_info() -> Value {
/// has no Unicode layout data.
pub fn current_raw_mapping() -> Value {
let mut mapping = Map::new();
+ // SAFETY: as above; `layout` points into the layout data, which `source` keeps alive until its release below.
unsafe {
let mut source = TISCopyCurrentKeyboardInputSource();
let mut data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData);
@@ -95,14 +97,17 @@ pub fn current_raw_mapping() -> Value {
/// `ConvertKeyCodeToText`: a dead key gives the character of pressing it twice. native-keymap passes
/// `kUCKeyTranslateNoDeadKeysBit` (0) as the options, so dead keys are processed.
unsafe fn key_code_to_text(layout: *const c_void, key_code: u16, modifiers: u32) -> (bool, String) {
+ // SAFETY: LMGetKbdLast reads a system global and takes no arguments.
let keyboard_type = unsafe { LMGetKbdLast() } as u32;
let mut dead_key_state = 0;
let mut length = 0;
let mut unit = 0u16;
+ // SAFETY: `layout` is the caller's UCKeyboardLayout; the out pointers are locals, and `unit` holds the 1 unit asked for.
let mut status = unsafe { UCKeyTranslate(layout, key_code, 0, modifiers, keyboard_type, 0, &mut dead_key_state, 1, &mut length, &mut unit) };
let mut is_dead_key = false;
if status == 0 && length == 0 && dead_key_state != 0 {
is_dead_key = true;
+ // SAFETY: as the call above.
status = unsafe { UCKeyTranslate(layout, key_code, 0, modifiers, keyboard_type, 0, &mut dead_key_state, 1, &mut length, &mut unit) };
}
match char::from_u32(unit as u32) {
diff --git a/native/crates/app/src/launch.rs b/native/crates/app/src/launch.rs
index 29cbf68ef03..940ddb341c2 100644
--- a/native/crates/app/src/launch.rs
+++ b/native/crates/app/src/launch.rs
@@ -49,6 +49,7 @@ pub fn send_to_running_instance(socket: &Path, args: &[String], cwd: &Path) -> b
// main.ts `windowsAllowSetForegroundWindow`: the running instance may bring its window to the front.
#[cfg(windows)]
if let Ok(pid) = stream.server_process_id() {
+ // SAFETY: takes a process id; no pointers pass.
unsafe { windows_sys::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(pid) };
}
let launched_from_cli = std::env::var("VSCODE_CLI").is_ok_and(|cli| cli == "1");
diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rs
index 73b53257356..9ecb08293a3 100644
--- a/native/crates/app/src/main.rs
+++ b/native/crates/app/src/main.rs
@@ -1005,7 +1005,7 @@ fn configure_unc_access(user_data: &Path, extensions_folder: &Path) {
}
/// main.ts `resolveShellEnv` merged into `process.env`: a Dock launch gets the login shell's PATH for the host,
-/// terminals and tasks. Runs before any thread starts, so changing the environment is sound.
+/// terminals and tasks. Runs before the host and the UI start.
#[cfg(unix)]
fn apply_shell_env(force_disable: bool, user_data: &Path) -> Option<String> {
let env: std::collections::HashMap<String, String> = std::env::vars_os().filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?))).collect();
@@ -1014,7 +1014,7 @@ fn apply_shell_env(force_disable: bool, user_data: &Path) -> Option<String> {
match shell_env::resolve_shell_env(&env, force_disable, timeout) {
Some(Ok(resolved)) => {
for (key, value) in resolved {
- // SAFETY: called from main before the host, the UI or any other thread starts.
+ // SAFETY: the host and the UI start later; the one other thread, `launch` (launch::listen), reads no environment variable.
unsafe { std::env::set_var(key, value) };
}
None
diff --git a/native/crates/app/src/metered_connection.rs b/native/crates/app/src/metered_connection.rs
index 2734cbe915c..b622209e732 100644
--- a/native/crates/app/src/metered_connection.rs
+++ b/native/crates/app/src/metered_connection.rs
@@ -38,11 +38,13 @@ pub fn watch(updates: UnboundedSender<bool>) {
return;
}
let handler = RcBlock::new(|path: *mut c_void| {
+ // SAFETY: Network.framework passes the handler a valid nw_path_t for the length of the call.
let metered = unsafe { nw_path_is_expensive(path) || nw_path_is_constrained(path) };
if let Some(updates) = UPDATES.get() {
let _ = updates.unbounded_send(metered);
}
});
+ // SAFETY: the monitor is created here and never released; the main queue is a static, and the monitor copies the block.
unsafe {
let monitor = nw_path_monitor_create();
nw_path_monitor_set_queue(monitor, &_dispatch_main_q as *const _);
diff --git a/native/crates/app/src/policy/macos.rs b/native/crates/app/src/policy/macos.rs
index 9ac80dd9afa..5dae369b206 100644
--- a/native/crates/app/src/policy/macos.rs
+++ b/native/crates/app/src/policy/macos.rs
@@ -29,7 +29,9 @@ unsafe extern "C" {
pub(super) fn read_preference(application: &str, name: &str, kind: Kind) -> Option<Value> {
let application = cf_string(application);
let key = cf_string(name);
+ // SAFETY: `key` and `application` are the CFStrings made above, alive until their release below.
let value = unsafe { CFPreferencesCopyAppValue(key, application) };
+ // SAFETY: both came from cf_string and are not used after this.
unsafe {
CFRelease(key);
CFRelease(application);
@@ -37,6 +39,7 @@ pub(super) fn read_preference(application: &str, name: &str, kind: Kind) -> Opti
if value.is_null() {
return None;
}
+ // SAFETY: `value` is non-null and owned (Copy rule); each typed call follows a CFGetTypeID check, and the buffers are locals of the sizes given.
let result = unsafe {
let type_id = CFGetTypeID(value);
match kind {
@@ -56,12 +59,14 @@ pub(super) fn read_preference(application: &str, name: &str, kind: Kind) -> Opti
_ => None,
}
};
+ // SAFETY: `value` is owned and not used after this.
unsafe { CFRelease(value) };
result
}
fn cf_string(text: &str) -> *const c_void {
let text = CString::new(text).expect("policy names and bundle ids have no NUL");
+ // SAFETY: `text` is a NUL-terminated C string alive for the call; the caller releases the result.
unsafe { CFStringCreateWithCString(std::ptr::null(), text.as_ptr(), UTF8) }
}
@@ -73,11 +78,13 @@ pub const WATCHED_PATH: &str = "/Library/Managed Preferences/";
pub fn watch_policy_changes(path: &str, on_change: impl Fn() + Send + 'static) {
type Callback = Box<dyn Fn() + Send>;
extern "C" fn fs_events(_stream: *const c_void, info: *mut c_void, _count: usize, _paths: *mut c_void, _flags: *const u32, _ids: *const u64) {
+ // SAFETY: `info` is the Callback watch_policy_changes leaked, never freed.
let on_change = unsafe { &*(info as *const Callback) };
on_change();
}
let info: *mut Callback = Box::into_raw(Box::new(Box::new(on_change)));
let label = CString::new(format!("{BUNDLE_IDENTIFIER}.policy-watcher")).expect("no NUL");
+ // SAFETY: the stream copies `paths` and the context; `info` is leaked, so it outlives the stream, which runs until the app quits.
unsafe {
let path = cf_string(path);
let paths = CFArrayCreate(std::ptr::null(), &path, 1, std::ptr::null());
diff --git a/native/crates/app/src/power/macos.rs b/native/crates/app/src/power/macos.rs
index b2e4e21e25e..048e82e2c06 100644
--- a/native/crates/app/src/power/macos.rs
+++ b/native/crates/app/src/power/macos.rs
@@ -52,14 +52,17 @@ const ASSERTION_LEVEL_ON: u32 = 255;
/// powerMonitor.getSystemIdleTime: whole seconds since the last input event.
pub fn system_idle_time() -> u64 {
+ // SAFETY: takes two constants and returns seconds; no pointers pass.
unsafe { CGEventSourceSecondsSinceLastEventType(COMBINED_SESSION_STATE, ANY_INPUT_EVENT) as u64 }
}
pub(super) fn screen_locked() -> bool {
+ // SAFETY: returns an owned dictionary or null, checked below.
let dictionary = unsafe { CGSessionCopyCurrentDictionary() };
if dictionary.is_null() {
return false;
}
+ // SAFETY: non-null and owned (Copy rule), so the wrapper releases it once.
let dictionary: CFDictionary<CFString, CFType> = unsafe { CFDictionary::wrap_under_create_rule(dictionary) };
dictionary.find(CFString::new("CGSSessionScreenIsLocked")).and_then(|value| value.downcast::<CFBoolean>()).is_some_and(bool::from)
}
@@ -71,6 +74,7 @@ pub fn thermal_state() -> &'static str {
/// powerMonitor.isOnBatteryPower: the providing power source is the battery (kIOPMBatteryPowerKey).
pub fn on_battery_power() -> bool {
+ // SAFETY: `snapshot` is non-null and owned, released by its wrapper at the end; `source` follows the Get rule, and its wrapper retains it.
unsafe {
let snapshot = IOPSCopyPowerSourcesInfo();
if snapshot.is_null() {
@@ -86,9 +90,11 @@ pub fn on_battery_power() -> bool {
/// The macOS CPU speed limit in percent (Electron's `speed-limit-change`), 100 when the system reports none.
fn speed_limit() -> i64 {
let mut status: CFDictionaryRef = std::ptr::null();
+ // SAFETY: `status` is a local the call fills with an owned dictionary.
if unsafe { IOPMCopyCPUPowerStatus(&mut status) } != 0 || status.is_null() {
return 100;
}
+ // SAFETY: non-null and owned (Copy rule), so the wrapper releases it once.
let status: CFDictionary<CFString, CFType> = unsafe { CFDictionary::wrap_under_create_rule(status) };
status.find(CFString::new("CPU_Speed_Limit")).and_then(|value| value.downcast::<CFNumber>()).and_then(|number| number.to_i64()).unwrap_or(100)
}
@@ -103,11 +109,13 @@ pub(super) fn create_assertion(blocker_type: &str) -> Option<Assertion> {
};
let mut assertion = 0;
let name = CFString::new("Electron");
+ // SAFETY: both CFStrings live to the end of the statement; `assertion` is a local the call fills.
let created = unsafe { IOPMAssertionCreateWithName(CFString::new(assertion_type).as_concrete_TypeRef(), ASSERTION_LEVEL_ON, name.as_concrete_TypeRef(), &mut assertion) };
(created == 0).then_some(assertion)
}
pub(super) fn release_assertion(assertion: u32) {
+ // SAFETY: takes the assertion id IOPMAssertionCreateWithName returned; no pointers pass.
unsafe { IOPMAssertionRelease(assertion) };
}
@@ -130,26 +138,33 @@ fn observe_power_events() {
let queue = NSOperationQueue::mainQueue();
let observe = |center: &NSNotificationCenter, name: &NSString, event: fn() -> PowerEvent| {
let block = RcBlock::new(move |_: NonNull<NSNotification>| send(event()));
+ // SAFETY: the center copies the block; `name` and `queue` are alive for the call.
let observer = unsafe { center.addObserverForName_object_queue_usingBlock(Some(name), None, Some(&queue), &block) };
// The center keeps the block; the token is never removed, the app observes until it quits.
std::mem::forget(observer);
};
let workspace = NSWorkspace::sharedWorkspace().notificationCenter();
+ // SAFETY: an AppKit constant, set before any app code runs.
observe(&workspace, unsafe { NSWorkspaceWillSleepNotification }, || ("$onDidSuspend", Vec::new()));
+ // SAFETY: an AppKit constant, set before any app code runs.
observe(&workspace, unsafe { NSWorkspaceDidWakeNotification }, || ("$onDidResume", Vec::new()));
+ // SAFETY: an AppKit constant, set before any app code runs.
observe(&workspace, unsafe { NSWorkspaceWillPowerOffNotification }, || ("$onWillShutdown", Vec::new()));
let distributed = NSDistributedNotificationCenter::defaultCenter();
observe(&distributed, &NSString::from_str("com.apple.screenIsLocked"), || ("$onDidLockScreen", Vec::new()));
observe(&distributed, &NSString::from_str("com.apple.screenIsUnlocked"), || ("$onDidUnlockScreen", Vec::new()));
+ // SAFETY: a Foundation constant, set before any app code runs.
observe(&NSNotificationCenter::defaultCenter(), unsafe { NSProcessInfoThermalStateDidChangeNotification }, || ("$onDidChangeThermalState", vec![json!(thermal_state())]));
*ON_BATTERY.lock().unwrap() = Some(on_battery_power());
+ // SAFETY: the callback is a static fn that reads no context; the source is added to the main run loop and never removed.
unsafe {
let source = IOPSNotificationCreateRunLoopSource(power_sources_changed, std::ptr::null_mut());
CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);
}
let mut token = 0;
let handler = RcBlock::new(move |_: i32| send(("$onDidChangeSpeedLimit", vec![json!(speed_limit())])));
+ // SAFETY: the name is a C literal, `token` a local and the main queue a static; libnotify copies the block.
unsafe { notify_register_dispatch(c"com.apple.system.power.CPU".as_ptr(), &mut token, &_dispatch_main_q as *const _, &handler) };
}
@@ -158,6 +173,7 @@ fn observe_power_events() {
pub fn watch_accessibility_display(changed: UnboundedSender<()>) {
let block = RcBlock::new(move |_: NonNull<NSNotification>| drop(changed.unbounded_send(())));
let center = NSWorkspace::sharedWorkspace().notificationCenter();
+ // SAFETY: the center copies the block; the name is an AppKit constant, and the queue is alive for the call.
let observer = unsafe { center.addObserverForName_object_queue_usingBlock(Some(NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification), None, Some(&NSOperationQueue::mainQueue()), &block) };
std::mem::forget(observer);
}
diff --git a/native/crates/app/src/power/windows.rs b/native/crates/app/src/power/windows.rs
index 8e09104fa4e..2eee6a5d7ba 100644
--- a/native/crates/app/src/power/windows.rs
+++ b/native/crates/app/src/power/windows.rs
@@ -38,11 +38,14 @@ pub(super) fn create_assertion(blocker_type: &str) -> Option<Assertion> {
};
let mut reason: Vec<u16> = "Electron".encode_utf16().chain([0]).collect();
let context = REASON_CONTEXT { Version: POWER_REQUEST_CONTEXT_VERSION, Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING, Reason: REASON_CONTEXT_0 { SimpleReasonString: reason.as_mut_ptr() } };
+ // SAFETY: `context` and the `reason` buffer it points at are alive for the call.
let request = unsafe { PowerCreateRequest(&context) };
if request == INVALID_HANDLE_VALUE {
return None;
}
+ // SAFETY: `request` is the valid handle made above.
if unsafe { PowerSetRequest(request, request_type) } == 0 {
+ // SAFETY: `request` is valid and not used after this.
unsafe { CloseHandle(request) };
return None;
}
@@ -50,6 +53,7 @@ pub(super) fn create_assertion(blocker_type: &str) -> Option<Assertion> {
}
pub(super) fn release_assertion((request, request_type): Assertion) {
+ // SAFETY: `request` is the handle create_assertion returned, closed once here.
unsafe {
PowerClearRequest(request as HANDLE, request_type);
CloseHandle(request as HANDLE);
diff --git a/native/crates/app/src/system_wide_keybindings/macos.rs b/native/crates/app/src/system_wide_keybindings/macos.rs
index 6acca1476d9..91a4558fbd4 100644
--- a/native/crates/app/src/system_wide_keybindings/macos.rs
+++ b/native/crates/app/src/system_wide_keybindings/macos.rs
@@ -53,6 +53,7 @@ impl HotKeys {
pub fn new(presses: UnboundedSender<u32>) -> HotKeys {
let spec = EventTypeSpec { event_class: EVENT_CLASS_KEYBOARD, event_kind: EVENT_HOT_KEY_PRESSED };
let presses = Box::into_raw(Box::new(presses)) as *mut c_void;
+ // SAFETY: `spec` is read during the call; `presses` is leaked, so the handler can read it for the life of the app.
let status = unsafe { InstallEventHandler(GetApplicationEventTarget(), hot_key_pressed, 1, &spec, presses, std::ptr::null_mut()) };
assert_eq!(status, 0, "InstallEventHandler");
HotKeys { hot_keys: HashMap::new(), next_id: 1 }
@@ -73,6 +74,7 @@ impl ShortcutRegistry for HotKeys {
let id = self.next_id;
self.next_id += 1;
let mut hot_key = std::ptr::null_mut();
+ // SAFETY: `hot_key` is a local the call fills; the other arguments are values.
let status = unsafe { RegisterEventHotKey(key_code as u32, modifiers, EventHotKeyId { signature: SIGNATURE, id }, GetApplicationEventTarget(), 0, &mut hot_key) };
if status != 0 {
return false;
@@ -83,6 +85,7 @@ impl ShortcutRegistry for HotKeys {
fn unregister(&mut self, accelerator: &str) {
if let Some((_, hot_key)) = self.hot_keys.remove(accelerator) {
+ // SAFETY: `hot_key` came from RegisterEventHotKey and leaves the map here, so it is unregistered once.
unsafe { UnregisterEventHotKey(hot_key) };
}
}
@@ -90,8 +93,10 @@ impl ShortcutRegistry for HotKeys {
extern "C" fn hot_key_pressed(_call: *mut c_void, event: *mut c_void, presses: *mut c_void) -> i32 {
let mut id = EventHotKeyId::default();
+ // SAFETY: Carbon passes a valid event; `id` is a local of the size given.
let status = unsafe { GetEventParameter(event, EVENT_PARAM_DIRECT_OBJECT, TYPE_EVENT_HOT_KEY_ID, std::ptr::null_mut(), size_of::<EventHotKeyId>(), std::ptr::null_mut(), &mut id as *mut EventHotKeyId as *mut c_void) };
if status == 0 && id.signature == SIGNATURE {
+ // SAFETY: `presses` is the sender HotKeys::new leaked.
let presses = unsafe { &*(presses as *const UnboundedSender<u32>) };
let _ = presses.unbounded_send(id.id);
}
diff --git a/native/crates/app/src/terminal/pty.rs b/native/crates/app/src/terminal/pty.rs
index 94aa7c960f1..5572e74ee63 100644
--- a/native/crates/app/src/terminal/pty.rs
+++ b/native/crates/app/src/terminal/pty.rs
@@ -47,6 +47,7 @@ impl Pty {
// node-pty unixTerminal.ts sets PWD, so the shell shows the path as given, not the resolved /private/var one.
command.args(args).env_clear().envs(env).env("PWD", cwd).current_dir(cwd);
command.stdin(Stdio::from(slave.try_clone()?)).stdout(Stdio::from(slave.try_clone()?)).stderr(Stdio::from(slave));
+ // SAFETY: the closure runs between fork and exec and only makes async-signal-safe calls (setsid, ioctl, close, signal).
unsafe {
command.pre_exec(move || {
if libc::setsid() == -1 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
@@ -97,11 +98,13 @@ impl Pty {
pub fn resize(&self, cols: u16, rows: u16) {
let size = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
+ // SAFETY: the master fd is open while `self` lives; `size` is read during the call.
unsafe { libc::ioctl(self.master.as_raw_fd(), libc::TIOCSWINSZ, &size) };
}
/// node-pty `kill(signal)`, SIGHUP by default.
pub fn kill(&self, signal: i32) {
+ // SAFETY: kill takes a pid and a signal number; no pointers pass.
unsafe { libc::kill(self.pid, signal) };
}
@@ -111,6 +114,7 @@ impl Pty {
pub fn has_child_processes(&self) -> bool {
let mut children = [0 as libc::pid_t; 16];
let size = std::mem::size_of_val(&children) as i32;
+ // SAFETY: `children` is writable for `size` bytes.
unsafe { libc::proc_listchildpids(self.pid, children.as_mut_ptr().cast(), size) > 0 }
}
@@ -123,6 +127,7 @@ impl Pty {
/// node-pty `process` (pty.cc `pty_getproc` on Linux): the first argument of the foreground process group leader.
#[cfg(target_os = "linux")]
pub fn foreground_process(&self) -> Option<String> {
+ // SAFETY: the master fd is open while `self` lives.
let group = unsafe { libc::tcgetpgrp(self.master.as_raw_fd()) };
if group <= 0 {
return None;
@@ -135,16 +140,20 @@ impl Pty {
/// node-pty `process` (pty.cc `pty_getproc`): the name of the terminal's foreground process group leader.
#[cfg(target_os = "macos")]
pub fn foreground_process(&self) -> Option<String> {
+ // SAFETY: the master fd is open while `self` lives.
let group = unsafe { libc::tcgetpgrp(self.master.as_raw_fd()) };
if group <= 0 {
return None;
}
+ // SAFETY: proc_bsdinfo is integers and byte arrays, valid when zeroed.
let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_bsdinfo>() as i32;
+ // SAFETY: `info` is writable for `size` bytes.
let read = unsafe { libc::proc_pidinfo(group, libc::PROC_PIDTBSDINFO, 0, (&mut info as *mut libc::proc_bsdinfo).cast(), size) };
if read != size {
return None;
}
+ // SAFETY: the kernel NUL-terminates `pbi_comm` (proc_pidbsdinfo), and `read == size` says it filled `info`.
let name = unsafe { CStr::from_ptr(info.pbi_comm.as_ptr()) };
Some(name.to_string_lossy().into_owned())
}
@@ -158,12 +167,15 @@ impl Pty {
/// The current directory of the shell (terminalProcess.ts `getCwd`, which asks `lsof` on macOS).
#[cfg(target_os = "macos")]
pub fn cwd(&self) -> Option<String> {
+ // SAFETY: proc_vnodepathinfo is integers and byte arrays, valid when zeroed.
let mut info: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<libc::proc_vnodepathinfo>() as i32;
+ // SAFETY: `info` is writable for `size` bytes.
let read = unsafe { libc::proc_pidinfo(self.pid, libc::PROC_PIDVNODEPATHINFO, 0, (&mut info as *mut libc::proc_vnodepathinfo).cast(), size) };
if read != size {
return None;
}
+ // SAFETY: `vip_path` is MAXPATHLEN bytes, zeroed above, which the kernel filled with a NUL-terminated path.
let path = unsafe { CStr::from_ptr(info.pvi_cdir.vip_path.as_ptr().cast()) };
Some(path.to_string_lossy().into_owned())
}
@@ -180,17 +192,23 @@ impl Drop for Pty {
fn open_pty(cols: u16, rows: u16) -> io::Result<(OwnedFd, OwnedFd)> {
let (mut master, mut slave) = (0, 0);
let mut size = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 };
+ // SAFETY: the fd and size pointers are locals; the name and termios arguments may be null.
if unsafe { libc::openpty(&mut master, &mut slave, std::ptr::null_mut(), std::ptr::null_mut(), &mut size) } == -1 {
return Err(io::Error::last_os_error());
}
+ // SAFETY: openpty succeeded, so both are open fds that nothing else owns.
let (master, slave) = unsafe { (OwnedFd::from_raw_fd(master), OwnedFd::from_raw_fd(slave)) };
// pty.cc sets IUTF8 so the line discipline erases whole UTF-8 characters.
+ // SAFETY: termios is integers and a byte array, valid when zeroed.
let mut termios: libc::termios = unsafe { std::mem::zeroed() };
+ // SAFETY: the master fd is open; `termios` is a local the call fills.
if unsafe { libc::tcgetattr(master.as_raw_fd(), &mut termios) } == 0 {
termios.c_iflag |= libc::IUTF8;
+ // SAFETY: the master fd is open; tcgetattr filled `termios`.
unsafe { libc::tcsetattr(master.as_raw_fd(), libc::TCSANOW, &termios) };
}
for fd in [master.as_raw_fd(), slave.as_raw_fd()] {
+ // SAFETY: both fds are open; F_SETFD takes an integer.
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
}
Ok((master, slave))
diff --git a/native/crates/app/src/terminal/pty/conpty.rs b/native/crates/app/src/terminal/pty/conpty.rs
index df4d5e522e0..c8ae76ac100 100644
--- a/native/crates/app/src/terminal/pty/conpty.rs
+++ b/native/crates/app/src/terminal/pty/conpty.rs
@@ -163,6 +163,7 @@ fn start_process(console: HPCON, executable: &Path, args: &[String], cwd: &Path,
// SAFETY: the size query with a null list, as documented.
unsafe { InitializeProcThreadAttributeList(std::ptr::null_mut(), 1, 0, &mut list_size) };
let mut list = vec![0u8; list_size];
+ // SAFETY: STARTUPINFOEXW is integers and pointers, valid when zeroed.
let mut startup: STARTUPINFOEXW = unsafe { std::mem::zeroed() };
startup.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;
startup.lpAttributeList = list.as_mut_ptr().cast();
@@ -174,6 +175,7 @@ fn start_process(console: HPCON, executable: &Path, args: &[String], cwd: &Path,
let updated = unsafe {
UpdateProcThreadAttribute(startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE as usize, console as *const _, std::mem::size_of::<HPCON>(), std::ptr::null_mut(), std::ptr::null())
};
+ // SAFETY: PROCESS_INFORMATION is handles and integers, valid when zeroed.
let mut info: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: every pointer is valid for the call; the command line buffer is mutable as CreateProcessW requires.
let created = updated != 0
diff --git a/native/crates/app/src/update/install.rs b/native/crates/app/src/update/install.rs
index cbc2e2b01ba..6fb84e3be45 100644
--- a/native/crates/app/src/update/install.rs
+++ b/native/crates/app/src/update/install.rs
@@ -37,6 +37,7 @@ pub fn shipit_dir() -> PathBuf {
pub fn check_writable(bundle: &Path) -> anyhow::Result<()> {
let writable = |path: &Path| {
let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).expect("a path without NUL");
+ // SAFETY: `path` is a NUL-terminated C string alive for the call.
unsafe { libc::access(path.as_ptr(), libc::W_OK) == 0 }
};
let translocated = bundle.components().any(|part| part.as_os_str() == "AppTranslocation");
@@ -170,6 +171,7 @@ fn wait_for_exit(_pid: u32) -> anyhow::Result<()> {
#[cfg(unix)]
fn wait_for_exit(pid: libc::pid_t) -> anyhow::Result<()> {
for _ in 0..3000 {
+ // SAFETY: signal 0 only asks whether the process exists; no pointers pass.
if unsafe { libc::kill(pid, 0) } != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
return Ok(());
}
diff --git a/native/crates/app/src/webview/linux.rs b/native/crates/app/src/webview/linux.rs
index 1861aa9c9e6..11952cd16f9 100644
--- a/native/crates/app/src/webview/linux.rs
+++ b/native/crates/app/src/webview/linux.rs
@@ -235,8 +235,11 @@ fn load_with_http_rules(view: &webkit2gtk::WebView, content: &UserContentManager
// SAFETY: `data` is the box made below, `store` the filter store it saved to.
let (view, content, url) = *unsafe { Box::from_raw(data as *mut (webkit2gtk::WebView, UserContentManager, String)) };
let mut error = std::ptr::null_mut();
+ // SAFETY: `store` and `result` are what GIO passed this callback; `error` is a local the call fills.
let filter = unsafe { webkit2gtk::ffi::webkit_user_content_filter_store_save_finish(store.cast(), result, &mut error) };
+ // SAFETY: a null filter means the call set `error`, owned by us.
assert!(!filter.is_null(), "HTTP_LOOPBACK_ONLY_RULES: {}", unsafe { glib::Error::from_glib_full(error) });
+ // SAFETY: `filter` is non-null (asserted above); the manager takes its own reference, so ours is dropped here.
unsafe {
webkit2gtk::ffi::webkit_user_content_manager_add_filter(content.to_glib_none().0, filter);
webkit2gtk::ffi::webkit_user_content_filter_unref(filter);
diff --git a/native/crates/app/src/webview/macos.rs b/native/crates/app/src/webview/macos.rs
index a24df85c5c9..9e955b437ab 100644
--- a/native/crates/app/src/webview/macos.rs
+++ b/native/crates/app/src/webview/macos.rs
@@ -42,24 +42,30 @@ impl Webview {
let mtm = MainThreadMarker::new().expect("webviews live on the main thread");
allow_https_scheme_handler();
let roots = Rc::new(RefCell::new(roots));
+ // SAFETY: `mtm` proves the main thread, where WebKit objects are made.
let configuration = unsafe { WKWebViewConfiguration::new(mtm) };
let handler = SchemeHandler::new(mtm, SchemeState { id: id.to_string(), pre_dir, roots: roots.clone(), events: events.clone(), tasks: RefCell::default(), session: OnceLock::new() });
+ // SAFETY: allow_https_scheme_handler ran, so WebKit takes a handler for https instead of raising; the configuration retains `handler`.
unsafe { configuration.setURLSchemeHandler_forURLScheme(Some(ProtocolObject::from_ref(&*handler)), &NSString::from_str("https")) };
// SAFETY: WKProcessPoolPrivate.h, macOS 10.13+. HTTP_LOOPBACK_ONLY_RULES keep http to loopback.
unsafe {
let pool: *mut objc2::runtime::AnyObject = msg_send![&*configuration, processPool];
let _: () = msg_send![pool, _registerURLSchemeAsSecure: &*NSString::from_str("http")];
}
+ // SAFETY: a getter on the configuration made above, on the main thread.
let content = unsafe { configuration.userContentController() };
let bridge = MessageHandler::new(mtm, MessageState { id: id.to_string(), events });
+ // SAFETY: main thread; the controller retains `bridge` and the script, and MESSAGE_HANDLER is added once per configuration.
unsafe {
content.addScriptMessageHandler_name(ProtocolObject::from_ref(&*bridge), &NSString::from_str(MESSAGE_HANDLER));
let script = WKUserScript::initWithSource_injectionTime_forMainFrameOnly(WKUserScript::alloc(mtm), &NSString::from_str(BRIDGE_SCRIPT), WKUserScriptInjectionTime::AtDocumentStart, true);
content.addUserScript(&script);
}
+ // SAFETY: main thread; the view copies `configuration`.
let view = unsafe { WKWebView::initWithFrame_configuration(WKWebView::alloc(mtm), NSRect::ZERO, &configuration) };
let no = objc2_foundation::NSNumber::new_bool(false);
let no: &objc2::runtime::AnyObject = &no;
+ // SAFETY: `drawsBackground` is a key WKWebView answers (private, macOS 10.12+) with an NSNumber; main thread.
unsafe {
// The page background shows until the host page paints, as the transparent iframe does upstream.
view.setValue_forKey(Some(no), &NSString::from_str("drawsBackground"));
@@ -74,12 +80,15 @@ impl Webview {
let loaded = RcBlock::new(move |rules: *mut WKContentRuleList, error: *mut NSError| {
// SAFETY: WebKit passes a rule list or an error.
let rules = unsafe { rules.as_ref() }.unwrap_or_else(|| panic!("HTTP_LOOPBACK_ONLY_RULES: {:?}", unsafe { error.as_ref() }));
+ // SAFETY: WebKit calls this on the main thread with `rules` non-null (checked above).
unsafe {
content.addContentRuleList(rules);
loading.loadRequest(&request);
}
});
+ // SAFETY: `mtm` proves the main thread.
let store = unsafe { WKContentRuleListStore::defaultStore(mtm) }.expect("a default content rule list store");
+ // SAFETY: the store copies the block; the strings are alive for the call.
unsafe { store.compileContentRuleListForIdentifier_encodedContentRuleList_completionHandler(Some(&NSString::from_str("http-loopback-only")), Some(&NSString::from_str(HTTP_LOOPBACK_ONLY_RULES)), Some(&loaded)) };
// The scheme and message handlers are retained by the configuration the view copied.
Webview { view, roots, pending: Some(Vec::new()) }
@@ -152,6 +161,7 @@ impl Webview {
// SAFETY: the view is alive; its superview is GPUI's view or none.
let (Some(window), Some(mut parent)) = (self.view.window(), unsafe { self.view.superview() }) else { return };
if let Some(clip) = parent.downcast_ref::<ClipView>() {
+ // SAFETY: the clip view is alive; its superview is GPUI's view or none.
let Some(gpui) = (unsafe { clip.superview() }) else { return };
parent = gpui;
}
@@ -203,13 +213,16 @@ impl Webview {
}
fn evaluate(&self, script: &str) {
+ // SAFETY: main thread (the view is MainThreadOnly); no completion handler to keep alive.
unsafe { self.view.evaluateJavaScript_completionHandler(&NSString::from_str(script), None) };
}
}
impl Drop for Webview {
fn drop(&mut self) {
+ // SAFETY: the view is alive in its own drop, on the main thread.
let content = unsafe { self.view.configuration().userContentController() };
+ // SAFETY: removing a handler name is valid whether or not it is still registered.
unsafe { content.removeScriptMessageHandlerForName(&NSString::from_str(MESSAGE_HANDLER)) };
self.release_keyboard();
self.view.removeFromSuperview();
@@ -262,6 +275,7 @@ define_class!(
if !self.ivars().hit_rects.borrow().iter().any(inside) || self.ivars().hole.get().is_some_and(|(hole, _)| inside(&hole)) {
return std::ptr::null_mut();
}
+ // SAFETY: NSView implements hitTest:, and `point` is in the superview's coordinates, as it takes it.
unsafe { msg_send![super(self), hitTest: point] }
}
}
@@ -280,6 +294,7 @@ impl ClipView {
pub fn new(window: &Window, webview: &Webview) -> Retained<Self> {
let mtm = MainThreadMarker::new().expect("webviews live on the main thread");
let this = Self::alloc(mtm).set_ivars(ClipState { hit_rects: RefCell::default(), hole: std::cell::Cell::new(None) });
+ // SAFETY: initWithFrame: is NSView's designated initializer, on the object allocated above with its ivars set.
let this: Retained<Self> = unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] };
this.setClipsToBounds(true);
this.setHidden(true);
@@ -381,11 +396,14 @@ define_class!(
#[ivars = MessageState]
struct MessageHandler;
+ // SAFETY: the superclass is NSObject, which implements NSObjectProtocol.
unsafe impl NSObjectProtocol for MessageHandler {}
+ // SAFETY: the method below has the selector and signature WKScriptMessageHandler declares.
unsafe impl WKScriptMessageHandler for MessageHandler {
#[unsafe(method(userContentController:didReceiveScriptMessage:))]
fn did_receive(&self, _controller: &WKUserContentController, message: &WKScriptMessage) {
+ // SAFETY: WebKit passes a valid message; `body` returns a retained object.
let body = unsafe { message.body() };
let Ok(text) = body.downcast::<NSString>() else { return };
let state = self.ivars();
@@ -399,6 +417,7 @@ define_class!(
impl MessageHandler {
fn new(mtm: MainThreadMarker, state: MessageState) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(state);
+ // SAFETY: `init` of NSObject on the object allocated above, whose ivars are set.
unsafe { msg_send![super(this), init] }
}
}
@@ -422,8 +441,10 @@ define_class!(
#[ivars = SchemeState]
struct SchemeHandler;
+ // SAFETY: the superclass is NSObject, which implements NSObjectProtocol.
unsafe impl NSObjectProtocol for SchemeHandler {}
+ // SAFETY: the methods below have the selectors and signatures WKURLSchemeHandler declares.
unsafe impl WKURLSchemeHandler for SchemeHandler {
#[unsafe(method(webView:startURLSchemeTask:))]
fn start_task(&self, _web_view: &WKWebView, task: &ProtocolObject<dyn WKURLSchemeTask>) {
@@ -440,10 +461,12 @@ define_class!(
impl SchemeHandler {
fn new(mtm: MainThreadMarker, state: SchemeState) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(state);
+ // SAFETY: `init` of NSObject on the object allocated above, whose ivars are set.
unsafe { msg_send![super(this), init] }
}
fn start(&self, task: &ProtocolObject<dyn WKURLSchemeTask>) {
+ // SAFETY: WebKit passes a valid task, on the main thread.
let request = unsafe { task.request() };
let Some(url) = request.URL() else { return respond(task, 404, &[], Vec::new()) };
let host = url.host().map(|host| host.to_string().to_ascii_lowercase()).unwrap_or_default();
@@ -491,6 +514,7 @@ impl SchemeHandler {
/// Requests to the network, which the service worker leaves to the browser upstream.
fn fetch(&self, task: &ProtocolObject<dyn WKURLSchemeTask>) {
let state = self.ivars();
+ // SAFETY: main thread; the session retains the configuration and the main queue.
let session = state.session.get_or_init(|| unsafe {
NSURLSession::sessionWithConfiguration_delegate_delegateQueue(&NSURLSessionConfiguration::defaultSessionConfiguration(), None, Some(&NSOperationQueue::mainQueue()))
});
@@ -514,7 +538,9 @@ impl SchemeHandler {
}
}
});
+ // SAFETY: `task` is still in `tasks`, so WebKit has not stopped it.
let request = unsafe { task.request() };
+ // SAFETY: the session copies `completion`; `request` is alive for the call.
let data_task = unsafe { session.dataTaskWithRequest_completionHandler(&request, &completion) };
data_task.resume();
}
@@ -527,6 +553,7 @@ fn respond_with_resource(task: &ProtocolObject<dyn WKURLSchemeTask>, path: &str,
}
fn respond(task: &ProtocolObject<dyn WKURLSchemeTask>, status: isize, headers: &[(&str, &str)], body: Vec<u8>) {
+ // SAFETY: the caller holds a task WebKit has not stopped.
let request = unsafe { task.request() };
let url = request.URL().expect("a scheme task has a URL");
let length = body.len().to_string();
@@ -534,6 +561,7 @@ fn respond(task: &ProtocolObject<dyn WKURLSchemeTask>, status: isize, headers: &
let values: Vec<Retained<NSString>> = headers.iter().map(|(_, value)| NSString::from_str(value)).chain([NSString::from_str(&length)]).collect();
let fields = NSDictionary::from_slices(&keys.iter().map(|key| &**key).collect::<Vec<_>>(), &values.iter().map(|value| &**value).collect::<Vec<_>>());
let response = NSHTTPURLResponse::initWithURL_statusCode_HTTPVersion_headerFields(NSHTTPURLResponse::alloc(), &url, status, Some(&NSString::from_str("HTTP/1.1")), Some(&fields)).expect("an HTTP response");
+ // SAFETY: response, data, finish in the order WKURLSchemeTask requires, on a task WebKit has not stopped (it raises on a stopped one).
unsafe {
task.didReceiveResponse(&response);
task.didReceiveData(&NSData::from_vec(body));
diff --git a/native/crates/app/src/workbench/menubar.rs b/native/crates/app/src/workbench/menubar.rs
index ad411136e24..15cb094ac33 100644
--- a/native/crates/app/src/workbench/menubar.rs
+++ b/native/crates/app/src/workbench/menubar.rs
@@ -476,6 +476,7 @@ fn fix_up_app_kit_menus() {
}
// menubar.ts `setMacWindowMenu` roles. AppKit adds its Move & Resize and tiling items after `performZoom:`.
let Some(window_menu) = app.windowsMenu() else { return };
+ // SAFETY: each `action` is a selector NSWindow or NSApplication answers; `mtm` proves the main thread.
let item = |title: &str, action, key: &str| unsafe {
NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str(title), Some(action), &NSString::from_str(key))
};
diff --git a/native/crates/app/src/workbench/process_explorer.rs b/native/crates/app/src/workbench/process_explorer.rs
index 3276b0ad19b..6f283201acf 100644
--- a/native/crates/app/src/workbench/process_explorer.rs
+++ b/native/crates/app/src/workbench/process_explorer.rs
@@ -252,6 +252,7 @@ fn kill(pid: u32, _signal: i32) {
/// nativeHostMainService.ts `killProcess`: `process.kill(pid, signal)`.
#[cfg(unix)]
fn kill(pid: u32, signal: i32) {
+ // SAFETY: kill takes a pid and a signal number; no pointers pass.
if unsafe { libc::kill(pid as i32, signal) } != 0 {
eprintln!("[processExplorer] kill {pid}: {}", std::io::Error::last_os_error());
}
@@ -305,6 +306,7 @@ impl ProcessExplorer {
#[cfg(target_os = "macos")]
let total_memory = NSProcessInfo::processInfo().physicalMemory() as f64;
#[cfg(target_os = "linux")]
+ // SAFETY: sysconf takes a name constant; no pointers pass.
let total_memory = unsafe { libc::sysconf(libc::_SC_PHYS_PAGES) as f64 * libc::sysconf(libc::_SC_PAGESIZE) as f64 };
// ps::list_processes on Windows reads no memory yet.
#[cfg(target_os = "windows")]
diff --git a/native/crates/exthost/src/main_thread_secret_state/windows.rs b/native/crates/exthost/src/main_thread_secret_state/windows.rs
index 4c85b4fd577..9ec9f20bae0 100644
--- a/native/crates/exthost/src/main_thread_secret_state/windows.rs
+++ b/native/crates/exthost/src/main_thread_secret_state/windows.rs
@@ -11,10 +11,13 @@ use windows_sys::Win32::Security::Credentials::{
pub fn get(service: &str, account: &str) -> Result<Option<String>> {
let target = wide(&format!("{service}/{account}"));
let mut credential = std::ptr::null_mut::<CREDENTIALW>();
+ // SAFETY: `target` is NUL-terminated UTF-16; `credential` is a local the call fills.
if unsafe { CredReadW(target.as_ptr(), CRED_TYPE_GENERIC, 0, &mut credential) } == 0 {
return not_found_as(None);
}
+ // SAFETY: CredReadW succeeded, so `credential` points at a CREDENTIALW with a blob of the size it names.
let secret = unsafe { blob(&*credential) };
+ // SAFETY: allocated by CredReadW and not used after this.
unsafe { CredFree(credential.cast()) };
Ok(Some(secret))
}
@@ -40,6 +43,7 @@ pub fn set(service: &str, account: &str, value: &str) -> Result<()> {
TargetAlias: std::ptr::null_mut(),
UserName: user_name.as_mut_ptr(),
};
+ // SAFETY: the strings and the blob `credential` points at are alive for the call, which only reads them.
match unsafe { CredWriteW(&credential, 0) } {
0 => Err(Error::last_os_error()),
_ => Ok(()),
@@ -49,6 +53,7 @@ pub fn set(service: &str, account: &str, value: &str) -> Result<()> {
/// Whether a secret was there to delete.
pub fn delete(service: &str, account: &str) -> Result<bool> {
let target = wide(&format!("{service}/{account}"));
+ // SAFETY: `target` is NUL-terminated UTF-16, alive for the call.
match unsafe { CredDeleteW(target.as_ptr(), CRED_TYPE_GENERIC, 0) } {
0 => not_found_as(false),
_ => Ok(true),
@@ -61,16 +66,21 @@ 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>();
+ // SAFETY: `filter` is NUL-terminated UTF-16; `count` and `credentials` are locals the call fills.
if unsafe { CredEnumerateW(filter.as_ptr(), 0, &mut count, &mut credentials) } == 0 {
return not_found_as(Vec::new());
}
let mut accounts = Vec::new();
+ // SAFETY: CredEnumerateW succeeded, so `credentials` is an array of `count` valid pointers, alive until CredFree below.
for credential in unsafe { std::slice::from_raw_parts(credentials, count as usize) } {
+ // SAFETY: each pointer of the array is a valid CREDENTIALW.
let user_name = unsafe { (**credential).UserName };
if !user_name.is_null() {
+ // SAFETY: a non-null `UserName` is a NUL-terminated UTF-16 string.
accounts.push(unsafe { from_wide(user_name) });
}
}
+ // SAFETY: allocated by CredEnumerateW and not used after this.
unsafe { CredFree(credentials.cast()) };
Ok(accounts)
}
@@ -87,12 +97,15 @@ unsafe fn blob(credential: &CREDENTIALW) -> String {
if credential.CredentialBlobSize == 0 {
return String::new();
}
+ // SAFETY: the caller passes a CREDENTIALW the system filled: `CredentialBlob` holds `CredentialBlobSize` bytes.
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 {
+ // SAFETY: the caller passes a NUL-terminated string, read up to its NUL.
let length = (0..).take_while(|&index| unsafe { *text.add(index) } != 0).count();
+ // SAFETY: `length` units before the NUL were just read.
String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(text, length) })
}
diff --git a/native/crates/exthost/src/pipe.rs b/native/crates/exthost/src/pipe.rs
index 7ee6139e957..59a2f01d032 100644
--- a/native/crates/exthost/src/pipe.rs
+++ b/native/crates/exthost/src/pipe.rs
@@ -35,6 +35,7 @@ impl Listener {
/// 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();
+ // SAFETY: `handle` is the pending instance, open while `self` lives; `overlapped` stays valid until the operation ends (overlapped()).
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.
@@ -61,14 +62,17 @@ impl Stream {
loop {
// SECURITY_IDENTIFICATION: the server learns who connects but cannot act as this process.
let flags = FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION;
+ // SAFETY: `name` is NUL-terminated UTF-16, alive for the call; the security and template arguments may be null.
let handle = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, null(), OPEN_EXISTING, flags, null_mut()) };
if handle != INVALID_HANDLE_VALUE {
+ // SAFETY: a valid handle (checked above) that nothing else owns.
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);
}
+ // SAFETY: `name` is NUL-terminated UTF-16, alive for the call.
if unsafe { WaitNamedPipeW(name.as_ptr(), 5000) } == 0 {
return Err(Error::last_os_error());
}
@@ -90,6 +94,7 @@ impl Stream {
/// The process that listens on the pipe this client connected to.
pub fn server_process_id(&self) -> Result<u32> {
let mut pid = 0;
+ // SAFETY: the handle is open while `self` lives; `pid` is a local the call fills.
if unsafe { GetNamedPipeServerProcessId(self.0.as_raw_handle(), &mut pid) } == 0 {
return Err(Error::last_os_error());
}
@@ -106,6 +111,7 @@ 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);
+ // SAFETY: `buf` is writable for `length` bytes and outlives the operation: overlapped() returns only once it ended.
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),
@@ -118,6 +124,7 @@ 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);
+ // SAFETY: `buf` is readable for `length` bytes and outlives the operation: overlapped() returns only once it ended.
overlapped(handle, None, |overlapped| unsafe { WriteFile(handle, buf.as_ptr(), length, null_mut(), overlapped) }).map(|written| written as usize)
}
@@ -150,20 +157,25 @@ fn wide(name: &Path) -> Vec<u16> {
/// 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;
+ // SAFETY: `name` is NUL-terminated UTF-16, alive for the call; null security attributes are allowed.
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());
}
+ // SAFETY: a valid handle (checked above) that nothing else owns.
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> {
+ // SAFETY: null arguments make an unnamed manual-reset event.
let event = unsafe { CreateEventW(null(), 1, 0, null()) };
if event.is_null() {
return Err(Error::last_os_error());
}
+ // SAFETY: a non-null event handle (checked above) that nothing else owns.
let event = unsafe { OwnedHandle::from_raw_handle(event) };
+ // SAFETY: OVERLAPPED is integers and pointers, valid when zeroed.
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
overlapped.hEvent = event.as_raw_handle();
if start(&mut overlapped) == 0 {
@@ -174,12 +186,13 @@ fn overlapped(handle: HANDLE, timeout: Option<Duration>, start: impl FnOnce(*mut
}
let milliseconds = timeout.map_or(INFINITE, |timeout| u32::try_from(timeout.as_millis()).unwrap_or(INFINITE - 1));
let mut transferred = 0;
+ // SAFETY: `overlapped` is the structure the operation started with; `transferred` is a local.
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.
+ // SAFETY: the OVERLAPPED lives on this stack: the cancelled operation must end before it goes.
unsafe {
CancelIoEx(handle, &overlapped);
GetOverlappedResult(handle, &overlapped, &mut transferred, 1);