Fix printf funcs on memory pressure with floats (#1275)

Cosmopolitan's printf-family functions will currently crash if one tries
formatting a floating point number with a larger precision (large enough
that gdtoa attempts to allocate memory to format the number) while under
memory pressure (i.e. when malloc fails) because gdtoa fails to check if
malloc fails.

The added tests (which would previously crash under cosmopolitan without
this patch) show how to reproduce the issue.

This patch fixes this, and adds the aforementioned tests.
This commit is contained in:
Gabriel Ravier 2024-09-01 23:42:14 +02:00 committed by GitHub
parent ae57fa2c4e
commit a089c07ddc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 86 additions and 5 deletions

View file

@ -1145,6 +1145,8 @@ int __fmt(void *fn, void *arg, const char *format, va_list va, int *wrote) {
s = s0 =
gdtoa(fpb.fpi, fpb.ex, fpb.bits, &fpb.kind, 3, prec, &decpt, &se);
}
if (s0 == NULL)
return -1;
if (decpt == 9999 || decpt == -32768) {
FormatDecpt9999Or32768:
if (s0)
@ -1258,6 +1260,8 @@ int __fmt(void *fn, void *arg, const char *format, va_list va, int *wrote) {
s = s0 = gdtoa(fpb.fpi, fpb.ex, fpb.bits, &fpb.kind, prec ? 2 : 0,
prec, &decpt, &se);
}
if (s0 == NULL)
return -1;
if (decpt == 9999 || decpt == -32768)
goto FormatDecpt9999Or32768;
c = se - s;
@ -1304,6 +1308,8 @@ int __fmt(void *fn, void *arg, const char *format, va_list va, int *wrote) {
s = s0 = gdtoa(fpb.fpi, fpb.ex, fpb.bits, &fpb.kind, prec ? 2 : 0,
prec, &decpt, &se);
}
if (s0 == NULL)
return -1;
if (decpt == 9999 || decpt == -32768)
goto FormatDecpt9999Or32768;
FormatExpo: