Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

read builtin: buffer size overflows int at 1 GiB, then writes through a NULL-based pointer (follow-up to workers/50621)



Hi,

I wanted to report the following bug that I discovered doing testing on Mac OSX. Since this is an email exchange, I've pasted a snippet from the REPORT.MD below that covers the basics and includes an overview of what I've attached. 

As referenced in your readme, I am not subscribed to the list, so you'd have to copy me on replies. I would also like to be up front and say that I used tools to help me generate the report and attached files. Let me know if you have further questions.

Thanks,
Billy


----
Summary:
read dies with SIGSEGV as soon as one line of input fills its buffer to
1 GiB. The buffer size, `bsiz`, is an `int` that starts at 64 and doubles. At
2^30 the next doubling does not fit in an `int`, so `realloc()` is asked for
about 2^64 bytes and returns NULL. The result is not checked: `bptr` becomes
`NULL + 2^30`, and the next input byte is stored through it.

This is the crash reported in workers/50621 (September 2022). That thread
discussed it as running out of memory: 50633 noted that a shell that is out
of memory usually cannot recover, and 50636 said that the nastier cases,
such as reading input not under your control, might still be worth checking.
I think the cause is different. The request that fails is a wrapped number,
and a line one byte shorter is read without error, although by then the
buffer has grown to the same 1 GiB.

Attached:
- run.sh: runs the bug case and the control
- `results.txt`: the output of step 1 below on that zsh, on a machine with
  16 GiB, and on master with and without the patch
- `crash-excerpt.txt`: the crash report from the bug case, identifiers removed
- `read-bsiz.patch`: the suggested change, also inline below
----
zsh 5.9 (arm64-apple-darwin26.0), Darwin arm64
args=[nul_bytes=536870912] runs=1 crashes=1 other_failures=0
args=[nul_bytes=536870911] runs=1 crashes=0 other_failures=0

master at b13bbf2a, without the patch:
zsh 5.9.999.3-test [zsh-5.9.0.3-test-512-gb13bbf2] (aarch64-apple-darwin27.2.0), Darwin arm64
args=[nul_bytes=536870912] runs=1 crashes=1 other_failures=0
args=[nul_bytes=536870911] runs=1 crashes=0 other_failures=0

master at b13bbf2a, with read-bsiz.patch:
zsh 5.9.999.3-test [zsh-5.9.0.3-test-512-gb13bbf2] (aarch64-apple-darwin27.2.0), Darwin arm64
args=[nul_bytes=536870912] runs=1 crashes=0 other_failures=0
args=[nul_bytes=536870911] runs=1 crashes=0 other_failures=0
# read builtin: buffer size overflows int at 1 GiB, then writes through a NULL-based pointer (follow-up to workers/50621)

- zsh: 5.9 (arm64-apple-darwin26.0), the `/bin/zsh` of macOS 27.2.1, run as
  `zsh -f`
- Source read: 5.9, 5.9.2, and master at b13bbf2a (2026-11-10); the code is
  the same in all three
- Built and run: master at b13bbf2a, with and without the suggested patch

## Summary

`read` dies with SIGSEGV as soon as one line of input fills its buffer to
1 GiB. The buffer size, `bsiz`, is an `int` that starts at 64 and doubles. At
2^30 the next doubling does not fit in an `int`, so `realloc()` is asked for
about 2^64 bytes and returns NULL. The result is not checked: `bptr` becomes
`NULL + 2^30`, and the next input byte is stored through it.

This is the crash reported in workers/50621 (September 2022). That thread
discussed it as running out of memory: 50633 noted that a shell that is out
of memory usually cannot recover, and 50636 said that the nastier cases,
such as reading input not under your control, might still be worth checking.
I think the cause is different. The request that fails is a wrapped number,
and a line one byte shorter is read without error, although by then the
buffer has grown to the same 1 GiB.

## Attached

- `run.sh`: runs the bug case and the control
- `results.txt`: the output of step 1 below on that zsh, on a machine with
  16 GiB, and on master with and without the patch
- `crash-excerpt.txt`: the crash report from the bug case, identifiers removed
- `read-bsiz.patch`: the suggested change, also inline below

## Steps to reproduce

The short form, whose input has no end:

```text
zsh -f -c 'read x < /dev/zero'
```

`run.sh` uses a finite line instead, to show where the limit is. It needs
bash, `head`, `seq`, `uname`, and 1 GiB of memory. Each of its two cases took
4 to 15 minutes here (about 5 CPU-minutes), because `read` takes its input
one byte per `read(2)` call. Set `ZSH_BIN` to test a zsh other than the first
one on `PATH`. Run it from the folder that holds the attachments.

1. `ZSH_BIN=/bin/zsh bash run.sh`

   The bug case pipes 2^29 NUL bytes and a newline into
   `zsh -f -c 'read line'`. `read` stores a NUL byte as two bytes (Meta, then
   the byte XOR 32), so 2^29 of them fill the buffer to exactly 2^30. The
   control sends one NUL byte fewer. A run counts as a crash when zsh dies
   from a signal. Output on the machine above:

   ```text
   zsh 5.9 (arm64-apple-darwin26.0), Darwin arm64
   args=[nul_bytes=536870912] runs=1 crashes=1 other_failures=0
   args=[nul_bytes=536870911] runs=1 crashes=0 other_failures=0
   ```

## Expected

`read` assigns the line, or fails with a message. It does not write through an
invalid pointer.

## Actual

The bug case dies with SIGSEGV. From the crash report (`crash-excerpt.txt`):

- The faulting instruction is a one-byte store in `bin_read`.
- The fault address is `0x40000000`, exactly 2^30.
- The VM summary shows 1.0G of malloc memory. The machine has 16 GiB.

## Why this is an overflow and not memory exhaustion

1. The arithmetic. `bsiz` goes 64, 128, and so on up to 2^30. `bsiz *= 2` is
   then a signed overflow; in practice the result is `INT_MIN`, which
   `realloc()` receives as the `size_t` value `0xffffffff80000000`.
2. The ASan log in workers/50621 already shows the size: "requested
   allocation size 0xffffffff80000000". That value is `INT_MIN` converted to
   `size_t`.
3. The control. One input byte fewer never asks for the doubling, and `read`
   exits 0. By the same arithmetic its buffer is already 1 GiB.
4. The fault address. After the failed `realloc()`, `bptr = buf + blen` is
   `NULL + 2^30`, and the report shows a byte write to exactly that address.

## Where it is in the source

The same code appears in two places in `bin_read` (`Src/builtin.c`): first in
the loop that reads every variable except the last, then in the loop that
reads the last variable.

| Version | First site | Second site |
| --- | --- | --- |
| 5.9 | lines 6719 to 6726 | lines 6902 to 6909 |
| 5.9.2 | lines 6735 to 6742 | lines 6918 to 6925 |
| master, b13bbf2a | lines 6863 to 6870 | lines 7046 to 7053 |

```c
int bsiz, ...;
...
/* increase the buffer size, if necessary */
if (bptr >= buf + bsiz - 1) {
    int blen = bptr - buf;
    ...
    buf = realloc(buf, bsiz *= 2);
    bptr = buf + blen;
    ...
}
```

`read x` reaches the second site. I reached the first site with `read a b`
and an endless stream of the letter `a`
(`tr '\0' a < /dev/zero | zsh -f -c 'read a b'`). That run crashed at a
different instruction in `bin_read`. Its fault address was `0x3fffffff`, one
less than 2^30, because the letter `a` is stored as one byte and not two.
Be warned that this run took about 9 GiB of memory here, not 1 GiB (see "Not
checked"), and I attach no crash report for it.

## Suggested fix (built and run on master, macOS arm64 only)

Make the size a `size_t`, stop before a doubling would wrap, and call
`zrealloc()` so that the result is checked; 50624 suggested the `zrealloc()`
part. The wrap check is the one 54538 added to `gethere()` for the same
`bsiz` doubling. Here it ends in zsh's usual "fatal error: out of memory",
as a failed `zrealloc()` does: where `size_t` is 32 bits, a buffer that
cannot double already fills half the address space. 50633 objected that
`zrealloc()` only changes how the shell dies. That holds for real exhaustion,
but with a `size_t` the 1 GiB case no longer fails: on a 64-bit build `read`
keeps growing, and only real exhaustion ends in zsh's usual "fatal error: out
of memory". Nor does the patch change what `read` returns, so 50635's concern,
that a script would take a new failure status to mean an empty file and
remove it, does not arise; only the alternative at the end of this section
would raise it.
Against master:

```diff
--- a/Src/builtin.c
+++ b/Src/builtin.c
@@ -6393,7 +6393,8 @@
 bin_read(char *name, char **args, Options ops, UNUSED(int func))
 {
     char *reply, *readpmpt;
-    int bsiz, c = 0, gotnl = 0, al = 0, first, nchars = 1, bslash, keys = 0;
+    int c = 0, gotnl = 0, al = 0, first, nchars = 1, bslash, keys = 0;
+    size_t bsiz;
     int haso = 0;      /* true if /dev/tty has been opened specially */
     int isem = !strcmp(term, "emacs"), izle = zleactive;
     char *buf, *bptr, *firstarg, *zbuforig;
```

and at both sites:

```diff
-               int blen = bptr - buf;
+               size_t blen = bptr - buf;
 #ifdef MULTIBYTE_SUPPORT
-               int llen = laststart - buf;
+               size_t llen = laststart - buf;
 #endif
 
-               buf = realloc(buf, bsiz *= 2);
+               if (bsiz > SIZE_MAX / 2) {
+                   /* doubling would wrap: the address space is exhausted */
+                   zerr("fatal error: out of memory");
+                   exit(1);
+               }
+               buf = zrealloc(buf, bsiz *= 2);
```

`read-bsiz.patch` is the complete diff and keeps the source's tabs, which are
shown as spaces above. If lines over 1 GiB are not worth supporting, an
alternative is to make `read` fail with a message when `bsiz` can no longer
double.

The same unchecked `int` doubling is in `hdynread()` and `hdynread2()` in
`Src/hist.c` (lines 2574 and 2602 at b13bbf2a) and in `Src/lex.c` (line 604),
so 50624's point that other `realloc()` calls go unchecked still stands. This
patch changes only `read`, the one this report measured. The same change
fits those three if it is wanted.

## The patch, built and run

Master at b13bbf2a was built twice, with and without `read-bsiz.patch`, by
`./Util/preconfig && ./configure && make`, on the machine above. The patch
applies with no offset and adds no compiler warning in `builtin.c`.

| Test | Without the patch | With the patch |
| --- | --- | --- |
| `run.sh`, bug case (2^29 NUL bytes) | SIGSEGV | exit 0 |
| `run.sh`, control (one byte fewer) | exit 0 | exit 0 |
| 2^30 NUL bytes, stored as 2^31 bytes | not run | `read` returns 0 |
| `make check` | 70 pass, 5 fail, 3 skipped | the same |
| Wrap check, its limit lowered to 2^19 | not applicable | "fatal error: out of memory", exit 1 |

- The longer line goes past `INT_MAX`, to check the code after the loop. The
  command was `zsh -f -c 'read line; print -r -- "rc=$? len=${#line}"'`, and
  it printed `rc=0 len=1073741824`. The run took about 11 minutes and a peak
  resident size of about 1.6 GB.
- The five `make check` failures are in A02alias, B06fc, D04parameter,
  K01nameref, and W01history. Their output is the same with and without the
  patch, so they come from this build environment, not from the change.
  B04read passes on both builds.
- On a 64-bit build the wrap check cannot fire, so a third copy was built
  with `SIZE_MAX / 2` replaced by 2^19 and fed 1 MiB of the letter `a`. Both
  `read x` and `read a b` printed `zsh:1: fatal error: out of memory` and
  exited 1, so both sites take the check.

## Not checked

- 5.9.2 was read, not built. Master was built and run only on the machine
  above, with 16 GiB. Free memory was not varied.
- Real memory exhaustion, where `zrealloc()` exits with its fatal error, was
  not reached.
- No 32-bit build was made. The wrap check was run only with its limit
  lowered, in a copy built for that test.
- The `read a b` run above had a peak memory footprint of about 9 GiB in
  some 75,000 regions, whereas the NUL runs peaked at 1 GiB. I did not look
  into why.
- I did not check whether `NULL + 2^30` can be a mapped address on some
  platform, for example a 32-bit build. On the machine above it is unmapped,
  so the process dies at once.

## How it was found

Unattended scripts used `read` from `/dev/zero` as a way to wait. `read -t`
does not prevent the crash: `/dev/zero` is always ready, so the timeout never
takes effect. Each such shell took 1 GiB and several CPU-minutes, then crashed.

I am not subscribed to the list. Please copy me on replies.

Attachment: read-bsiz.patch
Description: Binary data

Crash of /bin/zsh in the reproducer's bug case, excerpt of the macOS crash report.
Machine, account, session, and device identifiers are removed, and the
parent process is not named. Values are copied from the report; frames it
gives no symbol for are shown by their offset in the image.

Process:          zsh
Path:             /bin/zsh
Code Signing ID:  com.apple.zsh
Code Type:        ARM-64 (Native)
Binary UUID:      4d1ee5ad-a2fb-3385-bd53-98ae005f7094 (arm64e)
OS Version:       macOS 27.2.1 (26B131)
Launch Time:      18:32:38.0540
Date/Time:        18:46:27.1536

Triggered by Thread:  0
Exception Type:       EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype:    KERN_INVALID_ADDRESS at 0x0000000040000000
Termination Reason:   Namespace SIGNAL, Code 11, Segmentation fault: 11
ESR:                  (Data Abort) byte write Translation fault

VM Region Info:
  0x40000000 is not in any region.  Bytes before following region: 3263774720
        REGION TYPE                    START - END         [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
        UNUSED SPACE AT START
  --->  
        __TEXT                      102894000-10291c000    [  544K] r-x/r-x SM=COW  /bin/zsh

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   zsh                          bin_read + 4264
1   zsh                          execbuiltin + 1684
2   zsh                          (image offset 113564)
3   zsh                          (image offset 101948)
4   zsh                          (image offset 81444)
5   zsh                          execlist + 1940
6   zsh                          execode + 196
7   zsh                          execstring + 132
8   zsh                          init_misc + 152
9   zsh                          zsh_main + 1316
10  dyld                         start + 6652

Thread 0 crashed with ARM Thread State (64-bit):
  x0: 0x000000000000000a  x1: 0x0000000000000000  x2: 0x0000000000000001
  x3: 0x00000000617b92b5  x4: 0x00000001f02dcd40  x5: 0x00000001830686c8
  x6: 0x0000000000000001  x7: 0x0000000000000000  x8: 0x00000000ffffffff
  x9: 0x0000000000000000  x10: 0x0000000000000000  x11: 0x0000000000000100
  x12: 0x0000000040000000  x13: 0x0000000040000000  x14: 0x0000000000000000
  x15: 0x0000000000000004  x16: 0x0000000000000003  x17: 0x000000010291d200
  x18: 0x0000000000000000  x19: 0x000000016d56a140  x20: 0x0000000040000000
  x21: 0x0000000102994460  x22: 0x000000016d569f80  x23: 0x0000000040000000
  x24: 0x0000000000000000  x25: 0x0000000000000000  x26: 0x000000000000000a
  x27: 0x0000000102994460  x28: 0x0000000040000000
  fp: 0x000000016d56a0c0
  lr: 0x00000001028a34d4
  sp: 0x000000016d569ea0
  pc: 0x00000001028a3318
  far: 0x0000000040000000

VM summary (excerpt):
  Writable regions: Total=1.1G written=801K(0%) resident=801K(0%) swapped_out=16K(0%) unallocated=1.1G(100%)
  Malloc                             1.0G       25 
  Malloc Guard Page                 3568K        4 
  Stack                             8176K        1 
  Stack Guard                       56.0M        1 
  TOTAL                            387.9G      342 

Attachment: run.sh
Description: Bourne shell script



Messages sorted by: Reverse Date, Date, Thread, Author