]> Cypherpunks repositories - gostls13.git/commitdiff
bufio: fix overflow calculation in Scan
authorRob Pike <r@golang.org>
Sat, 19 Sep 2015 18:39:22 +0000 (11:39 -0700)
committerRob Pike <r@golang.org>
Sun, 20 Sep 2015 04:46:08 +0000 (04:46 +0000)
I was being too clever, as usual. Write the obvious code to make sure
that when we grow the buffer we don't overflow.

Change-Id: I1641831177b0bb8a89ab6e9bcabccf6c2fcfe1d2
Reviewed-on: https://go-review.googlesource.com/14781
Reviewed-by: Minux Ma <minux@golang.org>
src/bufio/scan.go

index 4f06f9764f0f717b124b3847749efaa3b1caf401..0ec584b0276fe13d1ebace1c0061dc4ec6aefb8e 100644 (file)
@@ -162,11 +162,13 @@ func (s *Scanner) Scan() bool {
                }
                // Is the buffer full? If so, resize.
                if s.end == len(s.buf) {
-                       if len(s.buf) >= s.maxTokenSize {
+                       // Guarantee no overflow in the multiplication below.
+                       const maxInt = int(^uint(0) >> 1)
+                       if len(s.buf) >= s.maxTokenSize || len(s.buf) > maxInt/2 {
                                s.setErr(ErrTooLong)
                                return false
                        }
-                       newSize := len(s.buf) * 2 // See protection against overflow in Buffer.
+                       newSize := len(s.buf) * 2
                        if newSize == 0 {
                                newSize = startBufSize
                        }
@@ -238,12 +240,6 @@ func (s *Scanner) Buffer(buf []byte, max int) {
                panic("Buffer called after Scan")
        }
        s.buf = buf[0:cap(buf)]
-       // Guarantee no overflow: we multiply len(s.buf) by two in Scan,
-       // but only if it exceeds maxTokenSize.
-       const maxInt = int(^uint(0) >> 1)
-       if max > maxInt {
-               max = maxInt
-       }
        s.maxTokenSize = max
 }