Panic in the go Replace method, part of the strings package

Viewed 172

We got the following panic on one of our servers:

error: panic: runtime error: slice bounds out of range [102:101] -

goroutine 113 [running]:
strings.Replace(0xc0001302a0, 0x6a, 0x3046f88, 0x1, 0x0, 0x0, 0x7, 0x0, 0xbb)
    /usr/local/go/src/strings/strings.go:950 +0x566
strings.ReplaceAll(...)
    /usr/local/go/src/strings/strings.go:964

The call in code is by calling ReplaceAll to remove whitespace:

strings.ReplaceAll(someString, " ", "")

And the input string can be a process command line read from the /proc/<pid>/cmdline file or the process path.

From the Replace function:

func Replace(s, old, new string, n int) string {
    if old == new || n == 0 {
        return s // avoid allocation
    }

    // Compute number of replacements.
    if m := Count(s, old); m == 0 {
        return s // avoid allocation
    } else if n < 0 || m < n {
        n = m
    }

    // Apply replacements to buffer.
    var b Builder
    b.Grow(len(s) + n*(len(new)-len(old)))
    start := 0
    for i := 0; i < n; i++ {
        j := start
        if len(old) == 0 {
            if i > 0 {
                _, wid := utf8.DecodeRuneInString(s[start:])
                j += wid
            }
        } else {
            j += Index(s[start:], old)
        }
        b.WriteString(s[start:j]) // -->> This panics!

So it seems like the only reason can be is that the implementation in Count which is using bytealg.CountString is different than the one in Index which is using bytealg.IndexByteString. Then Index returns -1 in the last iteration and the result is the indexes above.

The system is amd64 architecture.

The only possible scenario I can think of is if the input string is encoded in some non UTF-8 way, but couldn't reproduce.

Anyone got an idea?

0 Answers
Related