Bug 14036

Summary: Segmentation fault on ash when invoking quoted string substitution with long replacement
Product: Busybox Reporter: Manu <mrg.foss>
Component: OtherAssignee: unassigned
Status: NEW ---    
Severity: minor CC: busybox-cvs
Priority: P5    
Version: 1.33.x   
Target Milestone: ---   
Hardware: All   
OS: Linux   
Host: Target:
Build:

Description Manu 2021-07-18 19:27:44 UTC
Having a long replacement string in a shell expansion with string substitution
leads to a segmentation fault. It doesn't matter whether the expansion
expression is quoted or not. It seems to occur only when using musl.

Also, this bug is present in 1.32.1, 1.33.1 and the current master (dabbeeb7).
Note that it does not crash in 1.31.1. Probably this bug was introduced at the
same time as https://bugs.busybox.net/show_bug.cgi?id=14031 was, but I didn't verify
that.

Here an example that causes the segmentation fault:

```shell
repl=$(yes | head -n 774 | tr -d '\n'); docker run --rm -it busybox:1.33.1-musl sh -c 'A=a; echo ${A/a/'$repl'}' 
```

It does not crash for all sizes of the replacement string, though. Here a small
loop to print some of them:

```shell
for i in $(seq 1 1500); do
  echo $i;
  repl=$(yes | head -n $i | tr -d '\n');
  [[ $(./busybox sh -c 'A=a; echo "${A/a/'$repl'}"' | wc -c) -eq $(( i + 1)) ]] || echo "Failed";
done
```

I've discovered this bug while debugging and trying to fix
https://bugs.busybox.net/show_bug.cgi?id=14031. I thought I might had to apply a
similar fix (checking for the restart condition after every use of STPUTC).
Based on the code, I therefore therefore predicted that big sizes of the
replacement string could also lead to segmentation faults. Although my
prediction was correct, adding checks after each STPUTC didn't fix the issue,
contrary to my initial expectation. I didn't look further on how to fix this bug
and just decided to report it.