Visual Studio Code, rebuilt in Rust
Rust
docs: add the memory safety rules and the unsafe inventory
rokartur66598571a6ed
diff --git a/docs/memory-safety.md b/docs/memory-safety.mdnew file mode 100644index 00000000000..0df354d7c60--- /dev/null+++ b/docs/memory-safety.md@@ -0,0 +1,109 @@+# Memory safety++VSRustium is Rust, so memory safety is the default. It stops being the default in two places: `unsafe` blocks in the port's own code, and code the port links but does not own (GPUI, the OS frameworks, Oniguruma, SQLite). This file sets the rules for the first place, lists every file that has `unsafe` code, and names the checks that fail on a violation. [ARCHITECTURE.md](../ARCHITECTURE.md) has the map of the code.++## The rules++1. `unsafe` code is allowed for one purpose: a call across a boundary that Rust cannot check. That is FFI to the OS (libc, AppKit and WebKit through `objc2`, Win32 and COM through `windows`, GTK), and the process calls that Rust marks unsafe (`pre_exec`, `set_var`).+2. `unsafe` code is not allowed for speed, for a borrow the compiler rejects, or to silence the compiler: no unchecked indexing, no `transmute` between Rust types, no `static mut`, no `unsafe impl Send` or `Sync` for a port type.+3. `unsafe` code sits in the platform glue of `app` and `exthost`: the file named after the OS beside the portable module (ARCHITECTURE.md, "Platform glue per OS"), or one small function with `cfg` in the module that needs it. The crates `config`, `diff`, `files`, `pixeldiff`, `search`, `storage` and `textmate` have none.+4. Each `unsafe` block and each `unsafe impl` has a `// SAFETY:` comment on the line before it. The comment states the fact that makes the block sound: why each pointer is valid, who owns and frees the object, which thread runs the call, how long a buffer lives. It does not repeat what the call does.+5. The function around the block is safe to call. Its signature and its body make the `SAFETY` fact true for every caller. If that is not possible, the function is an `unsafe fn` and each caller states the fact.++## Add an unsafe block++1. Look for a safe API first: `std`, a safe method of `objc2` or `windows`, a helper that is already in the port.+2. Put the code in the OS file of the feature. If the feature has no OS file, add one beside the portable module.+3. Keep the block small: one call, or one group of calls that share one fact.+4. Write the `// SAFETY:` comment. If the fact needs more than two lines, the block does too much.+5. Check each value that comes from outside the process before the call: a pid, a length, a string from a file or from a terminal.+6. If the file is new to `unsafe` code, add a row to the [inventory](#inventory).+7. Add a test that runs the path on its OS.+8. Run the checks of [The checks](#the-checks).++## What a reviewer checks++- The `SAFETY` comment is true, and the code near the block shows it. A fact that depends on a distant caller is a defect.+- Ownership: an object from a Create or Copy function has exactly one release. A leak on purpose (`Box::into_raw` for a callback that lives as long as the app) says so.+- Threads: an API that needs the main thread takes a `MainThreadMarker` or runs in a GPUI main thread callback.+- Lifetimes across the call: a buffer, a block or an `OVERLAPPED` that the OS uses after the call returns must outlive that use.+- Input: a value from outside the process cannot select a wider effect. `kill` with pid 0 or -1 signals many processes.+- The diff adds no file to the inventory without a reason in the review.++## Inventory++Every file of `native/crates` that has `unsafe` code, with what it calls and the facts its blocks rely on. The per-block fact is the `SAFETY` comment in the file. If this table and the code disagree on the set of files, `bun port/tools/docs-check.ts` fails.++| File | Calls | Relies on |+|---|---|---|+| `app/src/app_icon.rs` | AppKit: the Dock icon | Main thread. |+| `app/src/cli.rs` | Win32 console: attach, handles, screen buffer | NUL-terminated strings and local structs that live for the call. |+| `app/src/clipboard.rs` | AppKit pasteboard name constants | The constants are set before `main`. |+| `app/src/diagnostics.rs` | libc `getloadavg`, `getifaddrs` | Fixed-size buffers. The interface list is read before `freeifaddrs`. |+| `app/src/dialog.rs` | The `NSView` behind a GPUI window handle | The view lives as long as the window. |+| `app/src/dialog/linux.rs` | GTK dialog destroy, an X display query | The dialog and the display are the port's own and are not used after. |+| `app/src/dialog/windows.rs` | `TaskDialogIndirect` | Strings and the button array outlive the modal call. |+| `app/src/file_dialog/macos.rs` | An Objective-C class for the format popup | The class declares NSObject as its superclass. |+| `app/src/file_dialog/windows.rs` | COM file dialogs | Main thread, where GPUI initialized COM. Shell strings are freed once. |+| `app/src/keyboard_layout/macos.rs` | Text Input Sources, `UCKeyTranslate` | The input source is released once. Layout data lives while its source does. |+| `app/src/launch.rs` | `AllowSetForegroundWindow` | A process id, no pointers. |+| `app/src/main.rs` | `std::env::set_var` at startup | No other thread reads the environment yet: only the `launch` thread exists, and it reads none. See [Known weak points](#known-weak-points). |+| `app/src/metered_connection.rs` | Network.framework path monitor | The monitor is never released. It copies the handler block. |+| `app/src/policy/macos.rs` | CFPreferences, FSEvents | CF objects are released once. The callback box is leaked for the life of the app. |+| `app/src/power/macos.rs` | IOKit power, notifications, `notify_register_dispatch` | Copy-rule objects go into owning wrappers. Blocks are copied by the centers. |+| `app/src/power/windows.rs` | Power requests | The request handle is closed once. |+| `app/src/ps.rs` | Toolhelp process snapshot, `OpenProcess` | Each handle is closed once. Entry structs have their size set. |+| `app/src/shell_env.rs` | `pre_exec` with `setsid` | Only async-signal-safe calls between fork and exec. |+| `app/src/system_wide_keybindings/macos.rs` | Carbon hot keys | The sender box is leaked for the life of the app. A hot key is unregistered once. |+| `app/src/terminal/profiles.rs` | `getpwuid_r` | The buffer belongs to the caller, so the call is safe on any thread. |+| `app/src/terminal/pty.rs` | `openpty`, termios, `ioctl`, `kill`, `proc_pidinfo`, `pre_exec` | The fds are owned once. Kernel structs are valid when zeroed. Only async-signal-safe calls between fork and exec. |+| `app/src/terminal/pty/conpty.rs` | ConPTY, pipes, `CreateProcessW` | Each handle is closed once. The attribute list outlives the process start. |+| `app/src/update.rs` | `NSProcessInfo` activity token | The token is the one `beginActivity` returned. |+| `app/src/update/install.rs` | libc `access`, `kill` with signal 0 | A NUL-terminated path. Signal 0 only tests for the process. |+| `app/src/webview/linux.rs` | WebKitGTK and GTK through `ffi`, X11 | GTK calls on the GTK thread. Boxed callback data is taken back once. |+| `app/src/webview/macos.rs` | WKWebView, its scheme and message handlers, three Objective-C classes, a method swizzle | Main thread. WebKit retains the handlers. A scheme task is answered only before WebKit stops it. The swizzled method keeps the original signature. |+| `app/src/webview/windows.rs` | WebView2 through COM, child windows | The controller and its window are used on their thread while the webview lives. |+| `app/src/win32.rs` | Window style and z-order of an `HWND` | The window is alive. |+| `app/src/workbench/accessibility.rs` | Two `NSApplication` accessibility methods replaced at run time | The replacements have the signatures of the originals and call them for other attributes. |+| `app/src/workbench/dialogs.rs` | libc `uname` | A zeroed struct that the call fills with NUL-terminated strings. |+| `app/src/workbench/menubar.rs` | `NSMenuItem` with a selector | The selectors are ones AppKit answers. Main thread. |+| `app/src/workbench/process_explorer.rs` | libc `kill`, `sysconf` | The pid is a row of the process list. |+| `app/src/workbench/terminal_quick_fix.rs` | libc `kill` | The pid is a field of digits from `lsof`, never 0 or negative (`capture_pid`). |+| `exthost/src/main_thread_secret_state/windows.rs` | Credential Manager | Credentials that the system allocates are freed once with `CredFree`. |+| `exthost/src/pipe.rs` | Named pipes with overlapped I/O | A buffer and its `OVERLAPPED` outlive the operation: the function returns only after the operation ends. |+| `exthost/src/request/macos.rs` | NSURLSession, CFNetwork proxies and PAC, GSS | Copy-rule objects are released once. The PAC callback writes into a slot that outlives its run loop. |+| `exthost/src/request/windows.rs` | WinHTTP proxy settings | Strings that WinHTTP allocates are freed once. |++## The checks++Each check fails on a violation. "Shown red" names the planted violation that proved it.++| Rule | Check | Runs | Shown red |+|---|---|---|---|+| No `unsafe` in the seven pure crates | `#![forbid(unsafe_code)]` at each crate root | Every build | An `unsafe` block added to `diff/src/lib.rs` stops the build. |+| An unsafe operation in an `unsafe fn` needs its own block | `unsafe_op_in_unsafe_fn = "deny"` in `native/Cargo.toml` | Every build | A raw pointer read without a block in an `unsafe fn` of `exthost` stops the build. |+| Each block has a `SAFETY` comment | `clippy::undocumented_unsafe_blocks = "deny"` in `native/Cargo.toml` | `cargo clippy --workspace --all-targets --locked -- -A clippy::all` | A block without a comment in `exthost/src/utc.rs` fails clippy. |+| `unsafe` only in the listed files | `bun port/tools/docs-check.ts` | Seconds, anywhere | A file with `unsafe` that is not in the inventory fails the check. |+| No known vulnerable dependency | `cargo deny --locked check advisories` with `native/deny.toml` | Seconds, needs the advisory database | The first run on the lock file failed on four advisories. |++Notes on the checks:++- Clippy sees only the code of the OS it builds for, so the gate is one run per OS. `-A clippy::all` turns the other clippy lints off: the run is only the memory safety gate. All three run from a laptop through the Studio:+ - macOS: `port/tools/studio 'cd native && cargo clippy --workspace --all-targets --locked -- -A clippy::all'`+ - Windows: `port/tools/windows-build 'cargo xwin clippy -p app -p exthost --all-targets --target x86_64-pc-windows-msvc --locked -- -A clippy::all'`+ - Linux: `port/tools/linux-build 'cd native && rustup component add clippy && cargo clippy --workspace --all-targets --locked -- -A clippy::all'`. The image of `port/tools/linux/Dockerfile` has no clippy, so each run adds it.+- An ignored advisory in `native/deny.toml` has a reason. If the reason no longer holds, remove the entry.+- The clippy and deny runs are not in a CI workflow yet. They belong in the workflow that runs on every push, one clippy run per OS.++## What the checks do not prove++- A `SAFETY` comment is a claim. The lint proves that the comment exists, not that it is true. The reviewer does that.+- FFI code cannot run under Miri. Miri on the pure crates was tried and dropped: those crates have no `unsafe` code, and one test binary of `diff` did not finish in 17 minutes.+- AddressSanitizer on the test suites of `textmate` and `storage` (the two crates over C libraries) is not set up. It needs a nightly toolchain and a C build with the sanitizer.+- The lints do not reach dependencies. GPUI, `native/vendor` and the C libraries are trusted as they are.++## Known weak points++- `app/src/main.rs::apply_shell_env` calls `set_var` while the `launch` thread already runs. The thread reads no environment variable, so there is no race today. The fact is fragile: a later change to `app/src/launch.rs::listen` can break it without a compile error.+- `app/src/terminal/pty.rs::kill` signals the stored pid. After the shell exits, the OS can give that pid to a different process.+- `app/src/workbench/accessibility.rs` sends `boolValue` to the value an accessibility client sets. A client that sends an object without that method stops the app with an exception.