go/analysis/passes/printf: fix panic parsing argument index

Fixes golang/go#54828

Change-Id: I516dc83230f6bc96b0ff21f3bbae702f1511e5b0
GitHub-Last-Rev: b26f46a2df820d4862b7c81200c86551b84719fa
GitHub-Pull-Request: golang/tools#395
Reviewed-on: https://go-review.googlesource.com/c/tools/+/426875
Auto-Submit: Tim King <taking@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
Run-TryBot: Tim King <taking@google.com>
Reviewed-by: Tim King <taking@google.com>
This commit is contained in:
Timon Wong 2022-09-07 07:00:12 +00:00 committed by Gopher Robot
parent bac5507b3e
commit dd1bab2d98
2 changed files with 4 additions and 2 deletions

View File

@ -672,12 +672,13 @@ func (s *formatState) parseIndex() bool {
s.scanNum()
ok := true
if s.nbytes == len(s.format) || s.nbytes == start || s.format[s.nbytes] != ']' {
ok = false
s.nbytes = strings.Index(s.format, "]")
ok = false // syntax error is either missing "]" or invalid index.
s.nbytes = strings.Index(s.format[start:], "]")
if s.nbytes < 0 {
s.pass.ReportRangef(s.call, "%s format %s is missing closing ]", s.name, s.format)
return false
}
s.nbytes = s.nbytes + start
}
arg32, err := strconv.ParseInt(s.format[start:s.nbytes], 10, 32)
if err != nil || !ok || arg32 <= 0 || arg32 > int64(len(s.call.Args)-s.firstArg) {

View File

@ -217,6 +217,7 @@ func PrintfTests() {
Printf("%[2]*.[1]*[3]d x", 2, "hi", 4) // want `a.Printf format %\[2]\*\.\[1\]\*\[3\]d uses non-int \x22hi\x22 as argument of \*`
Printf("%[0]s x", "arg1") // want `a.Printf format has invalid argument index \[0\]`
Printf("%[0]d x", 1) // want `a.Printf format has invalid argument index \[0\]`
Printf("%[3]*.[2*[1]f", 1, 2, 3) // want `a.Printf format has invalid argument index \[2\*\[1\]`
// Something that satisfies the error interface.
var e error
fmt.Println(e.Error()) // ok