Fix memcpy(size=0) ubsan warning in vsnprintf()

Fixes #785
This commit is contained in:
Justine Tunney 2023-03-29 01:23:59 -07:00
parent 7f925e6be9
commit 999481ace0
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
2 changed files with 15 additions and 7 deletions

View file

@ -30,14 +30,16 @@ struct SprintfStr {
};
static int vsnprintfputchar(const char *s, struct SprintfStr *t, size_t n) {
if (n == 1 && t->i < t->n) {
t->p[t->i] = s[0];
} else if (t->i + n <= t->n) {
memcpy(t->p + t->i, s, n);
} else if (t->i < t->n) {
memcpy(t->p + t->i, s, t->n - t->i);
if (n) {
if (n == 1 && t->i < t->n) {
t->p[t->i] = s[0];
} else if (t->i + n <= t->n) {
memcpy(t->p + t->i, s, n);
} else if (t->i < t->n) {
memcpy(t->p + t->i, s, t->n - t->i);
}
t->i += n;
}
t->i += n;
return 0;
}

View file

@ -628,6 +628,12 @@ TEST(sprintf, commas) {
ASSERT_STREQ("123,456,789", buf);
}
TEST(vsnprintf, issue785) {
ASSERT_EQ(0, snprintf(0, 0, "%s", ""));
ASSERT_EQ(1, snprintf(0, 0, "%s", " "));
ASSERT_EQ(2, snprintf(0, 0, "%s", " "));
}
BENCH(palandprintf, bench) {
EZBENCH2("ascii", donothing, Format(VEIL("r", "hiuhcreohucreo")));
EZBENCH2("ascii %s", donothing, Format("%s", VEIL("r", "hiuhcreohucreo")));