[PATCH v3 1/2] lib/vsprintf: Fix to check field_width and precision

From: Masami Hiramatsu (Google)

Date: Sat Mar 21 2026 - 10:41:43 EST


From: Masami Hiramatsu (Google) <mhiramat@xxxxxxxxxx>

Check the field_width and presition correctly. Previously it depends
on the bitfield conversion from int to check out-of-range error.
However, commit 938df695e98d ("vsprintf: associate the format state
with the format pointer") changed those fields to int.
We need to check the out-of-range correctly without bitfield
conversion.

Fixes: 938df695e98d ("vsprintf: associate the format state with the format pointer")
Reported-by: David Laight <david.laight.linux@xxxxxxxxx>
Closes: https://lore.kernel.org/all/20260318151250.40fef0ab@pumpkin/
Signed-off-by: Masami Hiramatsu (Google) <mhiramat@xxxxxxxxxx>
---
Changes in v3:
- Check and update width and precision before assigning to spec.
Changes in v2:
- Fix to use logical split.
---
lib/vsprintf.c | 14 ++++++++------
1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/lib/vsprintf.c b/lib/vsprintf.c
index 800b8ac49f53..ce9cbe071ab2 100644
--- a/lib/vsprintf.c
+++ b/lib/vsprintf.c
@@ -2802,19 +2802,21 @@ struct fmt format_decode(struct fmt fmt, struct printf_spec *spec)
static void
set_field_width(struct printf_spec *spec, int width)
{
- spec->field_width = width;
- if (WARN_ONCE(spec->field_width != width, "field width %d too large", width)) {
- spec->field_width = clamp(width, -FIELD_WIDTH_MAX, FIELD_WIDTH_MAX);
+ if (WARN_ONCE(width > FIELD_WIDTH_MAX || width < -FIELD_WIDTH_MAX,
+ "field width %d too large", width)) {
+ width = clamp(width, -FIELD_WIDTH_MAX, FIELD_WIDTH_MAX);
}
+ spec->field_width = width;
}

static void
set_precision(struct printf_spec *spec, int prec)
{
- spec->precision = prec;
- if (WARN_ONCE(spec->precision != prec, "precision %d too large", prec)) {
- spec->precision = clamp(prec, 0, PRECISION_MAX);
+ if (WARN_ONCE(prec > PRECISION_MAX || prec < 0,
+ "precision %d too large", prec)) {
+ prec = clamp(prec, 0, PRECISION_MAX);
}
+ spec->precision = prec;
}

/*