bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[readline 8.3] cursor mis-positioned after SIGWINCH on wrapped prompt wi


From: Félix Bouynot
Subject: [readline 8.3] cursor mis-positioned after SIGWINCH on wrapped prompt with non-printing region
Date: Fri, 15 May 2026 18:56:16 +0200

Configuration Information [Automatically generated, do not change]:
Machine: x86_64
OS: linux-gnu
Compiler: gcc
Compilation CFLAGS: -DPROGRAM='bash' -DCONF_HOSTTYPE='x86_64' -
DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='x86_64-redhat-linux-gnu' -
DCONF_VENDOR='redhat' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash'
-DSHELL -DHAVE_CONFIG_H   -I.  -I../. -I.././include -I.././lib  -O2 -
flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe
-Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-
D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -
fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -
m64 -march=x86-64-v3 -mtune=generic -fasynchronous-unwind-tables -
fstack-clash-protection -fcf-protection -fno-omit-frame-pointer -mno-
omit-leaf-frame-pointer -D_GNU_SOURCE -DRECYCLES_PIDS -
DDEFAULT_PATH_VALUE='/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin'
-DSTANDARD_UTILS_PATH='/usr/bin:/usr/sbin' -DSYS_BASHRC='/etc/bashrc' -
DSYS_BASH_LOGOUT='/etc/bash.bash_logout' -DNON_INTERACTIVE_LOGIN_SHELLS
-DSSH_SOURCE_BASHRC
uname output: Linux XPS9530-SRE1 6.19.14-200.fc43.x86_64 #1 SMP
PREEMPT_DYNAMIC Thu Apr 23 17:34:07 UTC 2026 x86_64 GNU/Linux
Machine Type: x86_64-redhat-linux-gnu

Bash Version: 5.3
Patch Level: 0
Release Status: release






# Bug report: readline 8.3 mis-positions cursor after SIGWINCH on a
wrapped prompt that contains a non-printing region

## AI-assistance disclosure

I (the reporter) noticed the symptom on my own setup and drove the
investigation. Once bash was identified as the likely root cause, I
asked an
AI coding assistant (Anthropic Claude) to produce, in this order:

1. a use case that reproduces the bug 100% of the time,
2. proof that the bug is in bash by demonstrating that another shell
does not
   exhibit it under an equivalent prompt,
3. the first bash version in which the bug appears (without modifying
my
   system bash; using containers / from-source builds),
4. a reproducer that does not rely on my own PS1, ideally with a
default-ish
   prompt or a minimal one, so the report cannot be dismissed as user
PS1
   error,
5. a pointer to the exact spot in the code that is responsible,
6. a candidate fix if one was identifiable.

What the assistant produced under that direction:

- located `_rl_redisplay_after_sigwinch` in `lib/readline/display.c`,
- ran `git blame` / `git log` against
git.savannah.gnu.org/git/readline.git
  and identified commit `447b829` as the introducing change,
- wrote the Python/pty automated reproducer included below and the
version
  sweep across containerised bash 5.0 to 5.2.37 plus zsh 5.9,
- built bash 5.3 from the GNU tarball with the proposed one-line patch
and
  re-ran the reproducer matrix (resize up / down / no-op / non-
wrapping).

I reproduced the bug interactively in foot on my own terminal before
and
after the patch, reviewed each command and result, and accept
responsibility
for the content of this report. The proposed patch is two lines of
mechanical
change (removing one conditional); I am not asserting any copyright on
it.

## Summary

When bash 5.3 (linked with bundled readline 8.3) renders a prompt that
wraps in
the current terminal width, and the terminal is then enlarged
(SIGWINCH), the
cursor lands several columns short of the actual end of the redrawn
prompt.
The visible cursor sits inside the visible prompt text while bash's
logical
input cursor is correctly past the end. Typing reveals the discrepancy:
typed
characters appear on top of the rendered prompt.

The number of columns by which the cursor is short equals
(approximately) the
total byte length of the SGR escape sequences that lie after the wrap
point of
the prompt in the original (narrow) terminal.

The bug is a regression introduced by the readline 8.3 redisplay
rewrite (`447b829`,
2025-07-03). bash 5.2 (readline 8.2) and earlier are not affected. The
bug
reproduces with bash --norc --noprofile and a minimal PS1; it is not
specific
to any particular user prompt.

## System

```
Linux 6.19.14-200.fc43.x86_64 (Fedora 43)
bash-5.3.0-2.fc43.x86_64
readline-8.3-2.fc43.x86_64
```

Same reproduction observed against an unmodified bash 5.3 built from
ftp.gnu.org/gnu/bash/bash-5.3.tar.gz.

## Reproduction (interactive)

1. Open a terminal emulator (foot, gnome-terminal, xterm — confirmed in
all).
2. Resize it small enough that the prompt wraps onto a second screen
line.
   With `PS1='\[\e[1m\]aaaa...80*a...\[\e[m\]> '` an 80-column terminal
is
   enough.
3. Enlarge the terminal so the prompt fits on a single line again.
4. Without typing anything yet, observe: the text cursor visually sits
inside
   the prompt text, not after the trailing `> `.
5. Type any character. It appears at the *real* end of the prompt,
overwriting
   the rendered prompt at the visual position where the cursor was.

## Reproduction (automated, 100% reliable)

The script below spawns bash on a pty with PS1 set via the environment
(which
bash honours under `--norc --noprofile`), renders the prompt at width
80, sends
TIOCSWINSZ to width 200 (which delivers SIGWINCH to bash), then counts
how
many backspaces (`\x08`) bash emits as part of its redisplay. A correct
implementation emits zero. The buggy implementation emits one backspace
per
column the cursor is off.

```python
#!/usr/bin/env python3
"""Minimal bash SIGWINCH redisplay regression reproducer.
No system rc files, no .bashrc, just bash + a PS1 with one SGR pair."""
import os, pty, time, select, fcntl, termios, struct, re

PS1 = "\\[\\e[1m\\]" + "a" * 80 + "\\[\\e[m\\]> "

def repro(bash_path, initial=80, final=200):
    pid, fd = pty.fork()
    if pid == 0:
        os.environ["TERM"] = "xterm-256color"
        os.environ["PS1"] = PS1
        os.execvp(bash_path, [bash_path, "--norc", "--noprofile", "-
i"])
    fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24,
initial, 0, 0))
    # Wait for the prompt to render at the initial width.
    raw = b""; deadline = time.time() + 2.0
    while time.time() < deadline:
        r, _, _ = select.select([fd], [], [], 0.1)
        if r:
            try:
                d = os.read(fd, 4096); raw += d; deadline = time.time()
+ 0.3
            except OSError: break
    # SIGWINCH to the larger width (TIOCSWINSZ on the pty sends
SIGWINCH to
    # the foreground process group automatically).
    fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, final,
0, 0))
    rb = b""; deadline = time.time() + 1.0
    while time.time() < deadline:
        r, _, _ = select.select([fd], [], [], 0.1)
        if r:
            try:
                rb += os.read(fd, 4096); deadline = time.time() + 0.3
            except OSError: break
    os.kill(pid, 9)
    bs = rb.count(b"\x08")
    cub = sum(int(n) if n else 1
              for n in re.findall(rb"\x1b\[(\d*)D", rb))
    return bs + cub

print("backspaces emitted on SIGWINCH:", repro("/usr/bin/bash"))
```

Observed output on bash 5.3.0:

```
backspaces emitted on SIGWINCH: 4
```

A correct bash emits 0.

Equivalent shell-only one-liner (visual rather than automated):

```sh
# In a terminal of width 80, run:
env -i TERM=xterm-256color HOME=/tmp
PS1='\[\e[1m\]aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaa\[\e[m\]> ' bash --norc --noprofile -i
# then enlarge the terminal to >82 columns and observe that the cursor
sits
# 4 columns short of the trailing space after the rendered "> ".
```

## Reproduction with the bash default prompt

The default Fedora bash prompt `[\u@\h \W]\$ ` contains no `\[ \]`
markers, so
it does not trigger the bug. The minimal PS1 above is the smallest
example
that does. Any PS1 that wraps and contains an `\[...\]`-bracketed SGR
sequence
positioned after the wrap point exhibits the bug.

## Magnitude of the offset

The offset in columns equals the number of bytes of `\e[...]` escape
data that
the original wrap pushes onto the second line of the prompt.
Concretely:

| PS1 (after wrap, ESC bytes count)            | observed offset |
|----------------------------------------------|-----------------|
| `\e[m`              (3 bytes)                 |               4 |
| `\e[01;31m\e[m`     (8+3 = 11 bytes after wrap) |              12 |
| `\e[01;33m\e[01;35m\e[m`  (8+8+5 = 21 bytes) |              22 |

The minimal repro PS1 above has 3 bytes of escape (`\e[m`) after the
wrap
point and shows an offset of 4 columns.

## Other shells, same prompt

zsh 5.9 with the equivalent prompt
(`PROMPT=$'%{\\x1b[1m%}aaa...a%{\\x1b[m%}> '`)
renders correctly across the same resize: zero backspaces emitted.

bash 5.0.17 (Ubuntu 20.04), bash 5.1.4 (Debian 11), bash 5.1.16 (Ubuntu
22.04),
bash 5.2.15 (Debian 12), bash 5.2.21 (Ubuntu 24.04) and bash 5.2.37
(Debian 13)
all render correctly across the same resize: zero backspaces emitted.

bash 5.3.0 emits a non-zero backspace count under the same conditions.

## Bisect

| bash    | readline | result |
|---------|----------|--------|
| 5.0.17  | 8.0      | ok     |
| 5.1.4   | 8.1      | ok     |
| 5.1.16  | 8.1      | ok     |
| 5.2.15  | 8.2      | ok     |
| 5.2.21  | 8.2      | ok     |
| 5.2.37  | 8.2      | ok     |
| 5.3.0   | 8.3      | bug    |

The first affected version is readline 8.3, distributed in commit
`447b8290b3e2e2d117dc8e9cdb83b0dc6448a638` (`Readline-8.3 distribution
sources
and documentation`, 2025-07-03) in the readline git tree at
git.savannah.gnu.org/git/readline.git, and bundled with bash 5.3.

## Root cause

The relevant function in `lib/readline/display.c`:

```c
void
_rl_redisplay_after_sigwinch (void)
{
  char *t;

  if (_rl_term_cr)
    {
      rl_clear_visible_line ();
      if (_rl_last_v_pos > 0)
        _rl_move_vert (0);
    }
  else
    rl_crlf ();

  if (_rl_screenwidth < prompt_visible_length)
    _rl_reset_prompt ();    /* update local_prompt_newlines array */

  t = strrchr (rl_display_prompt, '\n');
  if (t)
    redraw_prompt (++t);
  else
    rl_forced_update_display ();
}
```

The conditional re-expansion was already present in readline 8.2. What
is new
in 8.3 is the `local_prompt_invis_chars` array introduced by the same
commit
`447b8290`. The array stores, per *screen line* of the prompt, the
number of
invisible (between `\[ \]`) bytes on that line. It is populated by
`expand_prompt()` at the screenwidth in effect at expansion time, and
consumed
through the redefined `WRAP_OFFSET` macro:

```c
/* readline 8.3, display.c */
#define WRAP_OFFSET(line, offset)  \
    ((line <= prompt_last_screen_line) ? local_prompt_invis_chars[line]
: 0)
```

When the terminal is **enlarged** past `prompt_visible_length`, the
existing
condition `_rl_screenwidth < prompt_visible_length` is false, so
`_rl_reset_prompt()` is *not* called, `expand_prompt()` is not re-run,
and
`local_prompt_invis_chars[]` keeps the per-line counts that were valid
for
the *previous*, narrower terminal. `rl_forced_update_display()` then
uses
those stale counts and miscomputes the cursor position. The miscount is
exactly the byte count of the escape sequences that, in the narrow
layout,
sat on screen line 1 (i.e. after the wrap point) and that the resized
layout
must now treat as belonging to screen line 0.

The 8.2 macro did not depend on a precomputed per-line array:

```c
/* readline 8.2 */
#define WRAP_OFFSET(line, offset)                                     
\
    ((line == 0)                                                      
\
       ? (offset ? INVIS_FIRST() : 0)                                 
\
       : ((line == prompt_last_screen_line)                           
\
          ? wrap_offset - prompt_invis_chars_first_line : 0))
```

`wrap_offset` and `prompt_invis_chars_first_line` are also computed
from the
screenwidth, but they are not indexed per line and recompute correctly
enough
that the stale-screenwidth case does not produce a visible bug in the
same
scenario. That is why bash 5.2 does not exhibit this regression.

## Proposed fix

Drop the condition, or replace it with `!=`:

```diff
--- a/lib/readline/display.c
+++ b/lib/readline/display.c
@@ -3525,8 +3525,7 @@ _rl_redisplay_after_sigwinch (void)
   else
     rl_crlf ();
 
-  if (_rl_screenwidth < prompt_visible_length)
-    _rl_reset_prompt ();        /* update local_prompt_newlines array
*/
+  _rl_reset_prompt ();          /* refresh
local_prompt_{newlines,invis_chars}[] */
 
   /* Redraw only the last line of a multi-line prompt. */
   t = strrchr (rl_display_prompt, '\n');
```

A narrower variant only re-resets when the new width could change the
wrap
layout (`_rl_screenwidth != cached_screenwidth`) would also work; the
above
is the smallest change.

## Verification of the fix

Built `bash-5.3.tar.gz` with the patch above, ran the automated
reproducer:

```
stock     bash 5.3.0   sigwinch_bytes=195  backspaces=4   bug
patched   bash 5.3.0   sigwinch_bytes=290  backspaces=0   ok
```

The fix also resolves the bug on the original user prompt (which has
multiple
SGR pairs and a long kubectl context substitution, offset 18 cols):

```
stock     bash 5.3.0   sigwinch_bytes=333  backspaces=18  bug
patched   bash 5.3.0   sigwinch_bytes=352  backspaces=0   ok
```

Re-checked the other resize cases the previous condition was meant to
handle:

| resize                                          | stock | patched |
|-------------------------------------------------|-------|---------|
| 200→80 (terminal shrinks, prompt now wraps)     | ok    | ok      |
| 100→100 (no-op)                                 | ok    | ok      |
| 100→150 (prompt fits at both sizes, no wrap)    | ok    | ok      |
| 80→200 (terminal grows, prompt now fits — bug)  | bug   | ok      |

The patch does not regress any of the other resize directions.

## Workaround for affected users

Until a fix lands: keep `\[ \]`-bracketed SGR sequences only in the
part of
the prompt that is guaranteed not to wrap, or use a prompt short enough
that
it never wraps in the smallest terminal width you use. The bug requires
both
(a) the prompt wraps in the current terminal width before the resize,
and
(b) at least one `\[...]\]` block is positioned after the wrap point of
the
original layout.

Attachment: screen2_terminal_open.png
Description: PNG image

Attachment: screen4_after_typing.png
Description: PNG image

Attachment: screen3_after_resize.png
Description: PNG image


reply via email to

[Prev in Thread] Current Thread [Next in Thread]