From 41e1d9075e428c2fc32d966b3752a3029b620e2c Mon Sep 17 00:00:00 2001 From: =?utf8?q?R=C3=A9my=20Oudompheng?= Date: Fri, 29 Apr 2022 11:54:13 +0200 Subject: [PATCH] strconv: avoid panic on invalid call to FormatFloat Calling FormatFloat with an invalid value of fmt is expected to return a string containing '%' and the input fmt character. Since even before Go 1.0, the code has been panicking in the case where prec=0. Fixes #52187 Change-Id: I74fec601eedb7fe28efc5132c4253674661452aa Reviewed-on: https://go-review.googlesource.com/c/go/+/402817 TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: Emmanuel Odeke Reviewed-by: Ian Lance Taylor Run-TryBot: Ian Lance Taylor Reviewed-by: Carlos Amedee Auto-Submit: Emmanuel Odeke Auto-Submit: Ian Lance Taylor --- src/strconv/ftoa.go | 3 +++ src/strconv/ftoa_test.go | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/src/strconv/ftoa.go b/src/strconv/ftoa.go index eca04b851c..f602d0ffe6 100644 --- a/src/strconv/ftoa.go +++ b/src/strconv/ftoa.go @@ -138,6 +138,9 @@ func genericFtoa(dst []byte, val float64, fmt byte, prec, bitSize int) []byte { prec = 1 } digits = prec + default: + // Invalid mode. + digits = 1 } var buf [24]byte if bitSize == 32 && digits <= 9 { diff --git a/src/strconv/ftoa_test.go b/src/strconv/ftoa_test.go index 73008b1c62..3512ccf580 100644 --- a/src/strconv/ftoa_test.go +++ b/src/strconv/ftoa_test.go @@ -151,6 +151,11 @@ var ftoatests = []ftoaTest{ {498484681984085570, 'f', -1, "498484681984085570"}, {-5.8339553793802237e+23, 'g', -1, "-5.8339553793802237e+23"}, + // Issue 52187 + {123.45, '?', 0, "%?"}, + {123.45, '?', 1, "%?"}, + {123.45, '?', -1, "%?"}, + // rounding {2.275555555555555, 'x', -1, "0x1.23456789abcdep+01"}, {2.275555555555555, 'x', 0, "0x1p+01"}, -- 2.48.1