Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 100 additions & 22 deletions src/io/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,9 +427,12 @@
pub fn set_raw_mode(&mut self, value: bool) -> bun_sys::Result<()> {
match self {
Source::Tty(tty) => {
// Match `Source__setRawModeTty`: UV_TTY_MODE_RAW_VT so the
// terminal supplies VT input (bracketed paste etc.) regardless
// of whether raw mode was entered via fd 0 or a CONIN$ handle.
if let Some(err) = Self::tty_mut(tty)
.set_mode(if value {
uv::TtyMode::Raw
uv::TtyMode::Vt
} else {
uv::TtyMode::Normal
})
Expand Down Expand Up @@ -472,7 +475,7 @@
pub(super) fn get_stdin_tty(loop_: *mut uv::Loop) -> bun_sys::Result<bun_ptr::BackRef<Tty>> {
// bun_threading::Mutex::lock() returns `()` — must use lock_guard() for RAII
// unlock-on-drop, otherwise the mutex is held forever and the next call
// (e.g. Source__setRawModeStdin → open_tty(stdin)) deadlocks/UB-relocks.
// (e.g. Source__setRawModeTty → open_tty(stdin)) deadlocks/UB-relocks.
let _guard = LOCK.lock_guard();

if !INITIALIZED.swap(true, Ordering::Relaxed) {
Expand All @@ -491,33 +494,108 @@
}
}

/// The uv loop is taken as a parameter (reading it from the VM directly would
/// be a T6 dependency); the C++ caller
/// `node:tty` `setRawMode` for Windows. The uv loop is taken as a parameter
/// (reading it from the VM directly would be a T6 dependency); the C++ caller
/// (`ProcessBindingTTYWrap.cpp`) supplies `defaultGlobalObject()->uvLoop()`.
///
/// fd 0 resolves to the process-static `stdin_tty` singleton, so the mode
/// change goes through `uv_tty_set_mode` and is coordinated with any
/// in-flight libuv console read on that handle.
///
/// Other console fds have no libuv reader (fs.ReadStream reads via
/// `uv_fs_read`), and a transient `uv_tty_t` on them is unsafe:
/// `uv__tty_close` `_close()`s the caller's fd, and `SetConsoleMode` needs
/// `GENERIC_READ | GENERIC_WRITE` which an `O_RDONLY` CONIN$ handle lacks
/// (and `DuplicateHandle` cannot add access the source does not have). So the
/// fd is checked to be a console input handle and the same console-mode masks
/// `uv_tty_set_mode` would apply for `UV_TTY_MODE_RAW_VT` /
/// `UV_TTY_MODE_NORMAL` are written on a fresh CONIN$ handle. Console input
/// mode is a property of the input buffer, not the handle, so the mode
/// observed on fd 0 and on any CONIN$ handle is the same afterwards.
#[unsafe(no_mangle)]
pub(crate) extern "C" fn Source__setRawModeStdin(uv_loop: *mut uv::Loop, raw: bool) -> c_int {
let mut tty = match Source::open_tty(uv_loop, Fd::stdin()) {
bun_sys::Result::Ok(tty) => tty,
bun_sys::Result::Err(e) => return e.errno as c_int,
};
pub(crate) extern "C" fn Source__setRawModeTty(
uv_loop: *mut uv::Loop,
fd: c_int,
raw: bool,
) -> c_int {
// UV_TTY_MODE_RAW_VT is a variant of UV_TTY_MODE_RAW that enables control
// sequence processing on the TTY implementer side, rather than having libuv
// translate keypress events into control sequences, aligning behavior more
// closely with POSIX platforms. This is also required to support some
// control sequences at all on Windows, such as bracketed paste mode. The
// Node.js readline implementation handles differences between these modes.
// `tty` is the static stdin tty (fd 0 → `get_stdin_tty`), live for the
// process — same invariant the `Source::Tty` arm relies on, so reuse the
// shared `tty_mut` accessor.
if let Some(err) = Source::tty_mut(&mut tty)
.set_mode(if raw {
uv::TtyMode::Vt
} else {
uv::TtyMode::Normal
})
.to_error(bun_sys::Tag::uv_tty_set_mode)
let mode = if raw {
uv::TtyMode::Vt
} else {
uv::TtyMode::Normal
};

if fd == 0 {
let mut tty = match Source::open_tty(uv_loop, Fd::stdin()) {
bun_sys::Result::Ok(tty) => tty,
bun_sys::Result::Err(e) => return e.errno as c_int,
};
return match Source::tty_mut(&mut tty)
.set_mode(mode)
.to_error(bun_sys::Tag::uv_tty_set_mode)
{
Some(err) => err.errno as c_int,
None => 0,
};
}

use bun_sys::windows as w;
const ENABLE_WINDOW_INPUT: u32 = 0x0008;
Comment thread
robobun marked this conversation as resolved.
Resolved
const CONIN_W: [u16; 7] = [b'C' as _, b'O' as _, b'N' as _, b'I' as _, b'N' as _, b'$' as _, 0];

let src = Fd::from_uv(fd).native();
if src == w::INVALID_HANDLE_VALUE {
return bun_sys::E::BADF as c_int;
}
// Reject non-console-input fds with ENOTTY before touching the process
// console. `GetConsoleMode` only needs `GENERIC_READ`, which an O_RDONLY
// CONIN$ handle has.
let mut unused: u32 = 0;
// SAFETY: `src` is a live handle (`uv_get_osfhandle(fd)` for an open fd).
if unsafe { w::GetConsoleMode(src, &mut unused) } == 0 {
return bun_sys::E::NOTTY as c_int;
}

Check warning on line 562 in src/io/source.rs

View check run for this annotation

Claude / Claude Code Review

GetConsoleMode guard accepts console output handles

`GetConsoleMode` succeeds on console *output* handles too (it returns output-mode flags for screen-buffer handles), so this guard doesn't enforce the "non-console-input" invariant the comment claims. `new tty.ReadStream(1).setRawMode(true)` passes here, opens a fresh CONIN$, and silently raw-modes the process's console *input* buffer — pre-PR this errored, and Node/libuv returns EINVAL. Consider additionally requiring `GetNumberOfConsoleInputEvents(src, ...)` to succeed (only works on input hand
// `SetConsoleMode` on an input handle requires `GENERIC_READ|GENERIC_WRITE`
// and `DuplicateHandle` cannot add access the source lacks, so open a
// fresh CONIN$ handle. Console input mode is a property of the buffer, so
// the caller's read-only handle observes the new mode for its reads.
// SAFETY: `CONIN_W` is a NUL-terminated static wide string.
let conin = unsafe {
w::CreateFileW(
CONIN_W.as_ptr(),
w::GENERIC_READ | w::GENERIC_WRITE,
w::FILE_SHARE_READ | w::FILE_SHARE_WRITE,
core::ptr::null_mut(),
w::OPEN_EXISTING,
0,
core::ptr::null_mut(),
)
};
if conin == w::INVALID_HANDLE_VALUE {
return w::get_last_errno() as c_int;
}
// Same masks and fallback as libuv `uv_tty_set_mode` (src/win/tty.c).
let (flags, try_flags) = match mode {
uv::TtyMode::Vt => (ENABLE_WINDOW_INPUT, w::ENABLE_VIRTUAL_TERMINAL_INPUT),
_ => (
w::ENABLE_ECHO_INPUT | w::ENABLE_LINE_INPUT | w::ENABLE_PROCESSED_INPUT,
0,
),
};
// SAFETY: `conin` is a valid console handle we own for this block.
let rc = if unsafe { w::SetConsoleMode(conin, flags | try_flags) } != 0
|| (try_flags != 0 && unsafe { w::SetConsoleMode(conin, flags) } != 0)
{
return err.errno as c_int;
}
0
0
} else {

Check failure on line 595 in src/io/source.rs

View check run for this annotation

Claude / Claude Code Review

Direct SetConsoleMode desyncs libuv's cached mode on the stdin uv_tty_t

The `fd != 0` branch writes console mode via direct `SetConsoleMode`, but libuv caches the last-requested mode on the `stdin_tty` singleton (`tty.rd.mode.mode`) and `uv_tty_set_mode` short-circuits when requested==cached. So `process.stdin.setRawMode(true)` → CONIN$ stream `.setRawMode(false)` → `process.stdin.setRawMode(true)` no-ops, leaving the console cooked while `isRaw==true`. Since console input mode is per-buffer, routing every console-input fd through `uv_tty_set_mode` on the `stdin_tty
w::get_last_errno() as c_int
};
// SAFETY: `conin` was returned by CreateFileW; closed exactly once here.
unsafe { w::CloseHandle(conin) };
Comment thread
robobun marked this conversation as resolved.
Resolved
rc
}
34 changes: 7 additions & 27 deletions src/js/node/tty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,37 +56,17 @@ Object.defineProperty(ReadStream, "prototype", {
Prototype.setRawMode = function (flag) {
flag = !!flag;

// On windows, this goes through the stream handle itself, as it must call
// uv_tty_set_mode on the uv_tty_t.
// On Windows this calls uv_tty_set_mode (UV_TTY_MODE_RAW_VT) via
// Source__setRawModeTty; fd 0 resolves to the shared stdin uv_tty_t so
// the mode change is coordinated with any in-flight console read.
//
// On POSIX, I tried to use the same approach, but it didn't work reliably,
// so we just use the file descriptor and use termios APIs directly.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (process.platform === "win32") {
// Special case for stdin, as it has a shared uv_tty handle
// and it's stream is constructed differently
if (this.fd === 0) {
const err = ttySetMode(flag);
if (err) {
this.emit("error", new Error("setRawMode failed with errno: " + err));
return this;
}
} else {
const handle = this.$bunNativePtr;
if (!handle) {
this.emit("error", new Error("setRawMode failed because it was called on something that is not a TTY"));
return this;
}

// If you call setRawMode before you call on('data'), the stream will
// not be constructed, leading to EBADF
// This corresponds to the `ensureConstructed` function in `native-readable.ts`
this.$start();

const err = handle.setRawMode(flag);
if (err) {
this.emit("error", err);
return this;
}
const err = ttySetMode(this.fd, flag);
if (err) {
this.emit("error", new Error("setRawMode failed with errno: " + err));
return this;
}
} else {
const state = (this[kRawModeState] ??= new Uint8Array(rawModeStateSize));
Expand Down
10 changes: 5 additions & 5 deletions src/jsc/bindings/ProcessBindingTTYWrap.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

#if OS(WINDOWS)

extern "C" int Source__setRawModeStdin(uv_loop_t* uv_loop, bool raw);
extern "C" int Source__setRawModeTty(uv_loop_t* uv_loop, int fd, bool raw);

namespace UV {

Expand Down Expand Up @@ -195,13 +195,13 @@
JSC_DEFINE_HOST_FUNCTION(jsTTYSetMode, (JSC::JSGlobalObject * globalObject, CallFrame* callFrame))
{
#if OS(WINDOWS)
ASSERT(callFrame->argumentCount() == 1);
auto flag = callFrame->argument(0);
bool raw = flag.asBoolean();
ASSERT(callFrame->argumentCount() == 2);
int fd = callFrame->argument(0).asInt32();

Check failure on line 199 in src/jsc/bindings/ProcessBindingTTYWrap.cpp

View check run for this annotation

Claude / Claude Code Review

asInt32() on unvalidated fd argument in Windows jsTTYSetMode

`callFrame->argument(0)` is `this.fd`, a public user-mutable property that fs.ReadStream sets to `null` on close/destroy — `.asInt32()` on it debug-ASSERTs `isInt32()` and returns raw tag bits in release. Match the POSIX branch just below: check `fd.isNumber()` and use `fd.toInt32(globalObject)` under a throw scope (REVIEW.md: "coercing conversions (`toInt32(global)`, never `asInt32` on user values)").
Comment thread
robobun marked this conversation as resolved.
Resolved
bool raw = callFrame->argument(1).asBoolean();

Zig::GlobalObject* global = uncheckedDowncast<Zig::GlobalObject>(globalObject);

return JSValue::encode(jsNumber(Source__setRawModeStdin(global->uvLoop(), raw)));
return JSValue::encode(jsNumber(Source__setRawModeTty(global->uvLoop(), fd, raw)));
#else
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
Expand Down
120 changes: 119 additions & 1 deletion test/js/node/tty.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it, test } from "bun:test";
import { bunEnv, bunExe, isWindows } from "harness";
import { bunEnv, bunExe, isArm64, isWindows } from "harness";
import { WriteStream } from "node:tty";

describe("ReadStream.prototype.setRawMode", () => {
Expand Down Expand Up @@ -190,6 +190,124 @@ describe("ReadStream.prototype.setRawMode", () => {
});
expect(await proc.exited).toBe(0);
});

// On Windows, setRawMode on process.stdin requests UV_TTY_MODE_RAW_VT so
// the terminal supplies VT input sequences, but a tty.ReadStream on any
// other console fd (e.g. CONIN$) either failed outright ("not a TTY") or,
// via Source::set_raw_mode, would have used plain UV_TTY_MODE_RAW, which
// leaves ENABLE_VIRTUAL_TERMINAL_INPUT off and routes input through libuv's
// own INPUT_RECORD translator. The console input mode must be the same
// whichever fd the program raw-moded. bun:ffi has no Windows/arm64 backend.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
test.skipIf(!isWindows || isArm64)(
"uses the same VT raw console mode for CONIN$ as for stdin on Windows",
async () => {
const ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;

let output = "";
const decoder = new TextDecoder();
const done = Promise.withResolvers<void>();
const eof = Promise.withResolvers<void>();

const proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const fs = require("node:fs");
const tty = require("node:tty");
const { dlopen, ptr } = require("bun:ffi");

const k32 = dlopen("kernel32.dll", {
GetConsoleMode: { args: ["ptr", "ptr"], returns: "i32" },
GetStdHandle: { args: ["u32"], returns: "ptr" },
GetLastError: { args: [], returns: "u32" },
});

// Console input mode is per input buffer (not per handle), so the
// stdin handle observes the same mode whichever console handle
// uv_tty_set_mode was called on.
const STD_INPUT_HANDLE = 0xfffffff6; // (DWORD)-10
const probe = k32.symbols.GetStdHandle(STD_INPUT_HANDLE);
if (!probe) throw new Error("GetStdHandle failed");
const out = new Uint32Array(1);
const mode = () => {
if (!k32.symbols.GetConsoleMode(probe, ptr(out)))
throw new Error("GetConsoleMode failed: " + k32.symbols.GetLastError());
return out[0];
};

let err;
process.stdin.on("error", e => (err = String(e)));
process.stdin.setRawMode(true);
const stdinRawMode = mode();
process.stdin.setRawMode(false);
const stdinNormalMode = mode();

const fd = fs.openSync("CONIN$", "r");
const stream = new tty.ReadStream(fd);
stream.on("error", e => (err = String(e)));
stream.setRawMode(true);
const coninRawMode = mode();
const coninIsRaw = stream.isRaw;
stream.setRawMode(false);
const coninNormalMode = mode();

process.stdout.write(
"RESULT " +
JSON.stringify({
fd,
isTTY: stream.isTTY,
stdinRawMode,
coninRawMode,
stdinNormalMode,
coninNormalMode,
coninIsRaw,
...(err ? { err } : {}),
}),
);
process.exit(0);
`,
],
env: bunEnv,
terminal: {
cols: 200,
rows: 24,
data(_t, chunk: Uint8Array) {
output += decoder.decode(chunk, { stream: true });
if (output.includes("RESULT ") && output.includes("}")) done.resolve();
},
exit() {
eof.resolve();
},
},
});

await Promise.race([done.promise, eof.promise]);
proc.kill();
await proc.exited;
proc.terminal?.close();
output += decoder.decode();

const stripped = Bun.stripANSI(output).replace(/[\r\n]/g, "");
const match = stripped.match(/RESULT (\{[^}]*\})/);
if (!match) {
throw new Error("child did not emit RESULT; terminal output was: " + JSON.stringify(output));
}
const result = JSON.parse(match[1]);
expect(result).toEqual({
fd: expect.any(Number),
isTTY: true,
stdinRawMode: result.stdinRawMode,
coninRawMode: result.stdinRawMode,
stdinNormalMode: result.stdinNormalMode,
coninNormalMode: result.stdinNormalMode,
coninIsRaw: true,
});
expect(result.fd).not.toBe(0);
expect(result.stdinRawMode & ENABLE_VIRTUAL_TERMINAL_INPUT).toBe(ENABLE_VIRTUAL_TERMINAL_INPUT);
expect(result.coninRawMode & ENABLE_VIRTUAL_TERMINAL_INPUT).toBe(ENABLE_VIRTUAL_TERMINAL_INPUT);
},
);
});

describe("WriteStream.prototype.getColorDepth", () => {
Expand Down
Loading