Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

Clamp CSI parameters before looping on them

RoversX411dfc089cd6
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index 45fbf303..e4966b7d 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -2166,7 +2166,10 @@ impl TerminalState {
if x >= self.left_and_right_margins.start && x < self.left_and_right_margins.end {
let right_margin = self.left_and_right_margins.end;
- let limit = (x + n as usize).min(right_margin);
+ // n comes from the escape sequence and reaches u32::MAX,
+ // which overflows usize on 32-bit targets before min() can
+ // clamp it.
+ let limit = x.saturating_add(n as usize).min(right_margin);
let blank_attr = self.pen.clone_sgr_only();
let screen = self.screen_mut();
@@ -2196,7 +2199,11 @@ impl TerminalState {
Edit::EraseCharacter(n) => {
let y = self.cursor.y;
let x = self.cursor.x;
- let limit = (x + n as usize).min(self.screen().physical_cols);
+ // Saturating because n reaches u32::MAX, which overflows usize
+ // on 32-bit targets before min() can clamp it.
+ let limit = x
+ .saturating_add(n as usize)
+ .min(self.screen().physical_cols);
{
let blank = Cell::blank_with_attrs(self.pen.clone_sgr_only());
let screen = self.screen_mut();
@@ -2240,8 +2247,14 @@ impl TerminalState {
&& self.left_and_right_margins.contains(&x)
{
let margin = self.left_and_right_margins.end;
+ // As the comment above says, characters past the margin are
+ // lost: once the row is blank from the cursor to the margin
+ // each further insert only shifts blanks and drops one off
+ // the end, so those iterations cannot be observed. n reaches
+ // u32::MAX, which is a minute and a half of them.
+ let n = (n as usize).min(margin.saturating_sub(x));
let screen = self.screen_mut();
- for _ in 0..n as usize {
+ for _ in 0..n {
screen.insert_cell(x, y, margin, seqno);
}
}
@@ -2299,6 +2312,23 @@ impl TerminalState {
}
};
+ // Repeats wrap and scroll, so unlike ICH the screen keeps
+ // changing -- but only until the viewport and the scrollback
+ // hold nothing but the repeated cell. Past that only the cursor
+ // column still depends on n, and it cycles with the margin
+ // width, so keeping the remainder leaves the cursor exactly
+ // where it would have landed and drops the rest. Otherwise n
+ // reaches u32::MAX and this loop runs for a minute.
+ let width = (left_and_right_margins.end - left_and_right_margins.start).max(1);
+ let saturated = width
+ .saturating_mul(self.screen().physical_rows + self.config.scrollback_size());
+ let n = n as usize;
+ let n = if n > saturated {
+ saturated + (n % width)
+ } else {
+ n
+ };
+
for _ in 0..n {
{
let screen = self.screen_mut();
@@ -2381,11 +2411,17 @@ impl TerminalState {
}
Cursor::ForwardTabulation(n) => {
+ // Each tab moves at least one column and then sticks at the
+ // right margin, so more tabs than there are columns cannot move
+ // the cursor any further; n reaches u32::MAX.
+ let n = (n as usize).min(self.screen().physical_cols);
for _ in 0..n {
self.c0_horizontal_tab();
}
}
Cursor::BackwardTabulation(n) => {
+ // Likewise, but sticking at column zero.
+ let n = (n as usize).min(self.screen().physical_cols);
for _ in 0..n {
let x = match self.tabs.find_prev_tab_stop(self.cursor.x) {
Some(x) => x,
@@ -2414,12 +2450,15 @@ impl TerminalState {
Cursor::Right(n) => {
// https://vt100.net/docs/vt510-rm/CUF.html
let cols = self.screen().physical_cols;
+ // Saturating because n reaches u32::MAX, which overflows usize
+ // on 32-bit targets before min() can clamp it.
+ let target = self.cursor.x.saturating_add(n as usize);
let new_x = if self.cursor.x >= self.left_and_right_margins.end {
// outside the margin, so allow movement to screen edge
- (self.cursor.x + n as usize).min(cols - 1)
+ target.min(cols - 1)
} else {
// Else constrain to margin
- (self.cursor.x + n as usize).min(self.left_and_right_margins.end - 1)
+ target.min(self.left_and_right_margins.end - 1)
};
self.cursor.x = new_x;
diff --git a/term/src/test/csi.rs b/term/src/test/csi.rs
index 2e5e9665..0a636e70 100644
--- a/term/src/test/csi.rs
+++ b/term/src/test/csi.rs
@@ -401,3 +401,159 @@ fn test_ed_erase_scrollback() {
term.print("b");
assert_all_contents(&term, file!(), line!(), &["111", "222", "ab"]);
}
+
+/// The largest value a CSI parameter can carry: anything above it is rejected
+/// by the parser, so this is what a hostile program actually gets to send.
+const HUGE_PARAM: u32 = u32::MAX;
+
+/// Asserts that two terminals fed different parameters ended up in the same
+/// state. The left-hand terminal is always given a parameter small enough to
+/// run the handler's loop for real, so it stands in for the unclamped
+/// behaviour; the right-hand one is given HUGE_PARAM and goes through the
+/// clamp.
+fn assert_same_state(saturating: &TestTerm, huge: &TestTerm, file: &str, line: u32) {
+ assert_lines_equal(
+ file,
+ line,
+ &huge.screen().all_lines(),
+ &saturating.screen().all_lines(),
+ Compare::TEXT | Compare::ATTRS,
+ );
+ let (huge_pos, saturating_pos) = (huge.cursor_pos(), saturating.cursor_pos());
+ assert!(
+ huge_pos.x == saturating_pos.x && huge_pos.y == saturating_pos.y,
+ "{}:{}: cursor differs: huge={:?} saturating={:?}",
+ file,
+ line,
+ (huge_pos.x, huge_pos.y),
+ (saturating_pos.x, saturating_pos.y)
+ );
+}
+
+/// ICH past the right margin has nothing left to push, so a huge count must
+/// land in the same place as one that just reaches the margin.
+#[test]
+fn test_ich_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 4, 0);
+ term.print("abcd");
+ term.cup(1, 0);
+ term.print(format!("\x1b[{n}@"));
+ term
+ };
+ // 4 columns, cursor at column 1: three inserts blank the rest of the row.
+ assert_same_state(&run(3), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// DCH stops at the right margin. On a 32-bit target the unclamped `x + n`
+/// overflowed before min() saw it, turning this into a no-op.
+#[test]
+fn test_dch_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 4, 0);
+ term.print("abcd");
+ term.cup(1, 0);
+ term.print(format!("\x1b[{n}P"));
+ term
+ };
+ assert_same_state(&run(3), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// ECH stops at the last column; same 32-bit overflow as DCH.
+#[test]
+fn test_ech_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 4, 0);
+ term.print("abcd");
+ term.cup(1, 0);
+ term.print(format!("\x1b[{n}X"));
+ term
+ };
+ assert_same_state(&run(3), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// CUF stops at the last column; same 32-bit overflow as DCH.
+#[test]
+fn test_cuf_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 4, 0);
+ term.cup(1, 0);
+ term.print(format!("\x1b[{n}C"));
+ term
+ };
+ assert_same_state(&run(2), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// Tabs stick at the right margin, so more of them than there are columns
+/// cannot move the cursor any further.
+#[test]
+fn test_cht_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 32, 0);
+ term.print(format!("\x1b[{n}I"));
+ term
+ };
+ assert_same_state(&run(32), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// Backwards tabs stick at column zero.
+#[test]
+fn test_cbt_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 32, 0);
+ term.cup(31, 0);
+ term.print(format!("\x1b[{n}Z"));
+ term
+ };
+ assert_same_state(&run(32), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// REP keeps changing the screen as it wraps and scrolls, so its clamp is the
+/// one that has to preserve more than "nothing further happens": past a full
+/// screen and scrollback the picture is fixed and only the cursor column moves,
+/// cycling with the margin width.
+///
+/// The reference here is 15 on a 4x3 screen with no scrollback. That is above
+/// the saturation point (4 * 3 = 12) yet congruent to u32::MAX modulo 4, so the
+/// clamp leaves it alone and the loop really does run fifteen times -- which is
+/// what the unclamped code would settle on for any larger count.
+#[test]
+fn test_rep_huge_param() {
+ let run = |n: u32| {
+ let mut term = TestTerm::new(3, 4, 0);
+ term.print("x");
+ term.cup(0, 0);
+ term.print(format!("\x1b[{n}b"));
+ term
+ };
+ assert!(
+ HUGE_PARAM % 4 == 15 % 4,
+ "reference count must stay congruent to HUGE_PARAM"
+ );
+ assert_same_state(&run(15), &run(HUGE_PARAM), file!(), line!());
+}
+
+/// The reason the clamps exist. Unclamped, these four sequences are roughly
+/// three minutes of work between them in a release build and far more here.
+/// The bound is loose enough not to be flaky on a busy machine and still two
+/// orders of magnitude below the unclamped cost.
+#[test]
+fn test_huge_params_are_bounded_work() {
+ let start = std::time::Instant::now();
+ for seq in [
+ format!("\x1b[{HUGE_PARAM}@"),
+ format!("\x1b[{HUGE_PARAM}b"),
+ format!("\x1b[{HUGE_PARAM}I"),
+ format!("\x1b[{HUGE_PARAM}Z"),
+ ] {
+ let mut term = TestTerm::new(24, 80, 3500);
+ term.print("filler text");
+ term.print(seq);
+ }
+ let elapsed = start.elapsed();
+ assert!(
+ elapsed < std::time::Duration::from_secs(10),
+ "huge CSI parameters took {:?}; a clamp is missing",
+ elapsed
+ );
+}