Repository: uber-go/zap
File: stacktrace.go (Go)

Code before:
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"runtime"
	"strings"
	"sync"

	"go.uber.org/zap/internal/bufferpool"
)

var (
	_stacktraceIgnorePrefixes = []string{
		"go.uber.org/zap",
		"runtime.",
	}
	_stacktraceUintptrPool = sync.Pool{
		New: func() interface{} {
			return make([]uintptr, 64)
		},
	}
)

// takeStacktrace attempts to use the provided byte slice to take a stacktrace.
// If the provided slice isn't large enough, takeStacktrace will allocate
// successively larger slices until it can capture the whole stack.
func takeStacktrace() string {
	buffer := bufferpool.Get()
	programCounters := _stacktraceUintptrPool.Get().([]uintptr)
	defer bufferpool.Put(buffer)
	defer _stacktraceUintptrPool.Put(programCounters)

	for {
		n := runtime.Callers(2, programCounters)
		if n < len(programCounters) {
			programCounters = programCounters[:n]
			break
		}
		// Do not put programCounters back in pool, will put larger buffer in
		// This is in case our size is always wrong, we optimize to pul
		// correctly-sized buffers back in the pool
		programCounters = make([]uintptr, len(programCounters)*2)
	}

	i := 0
	for _, programCounter := range programCounters {
		f := runtime.FuncForPC(programCounter)
		name := f.Name()
		if shouldIgnoreStacktraceName(name) {
			continue
		}
		if i != 0 {
			buffer.AppendByte('\n')
		}
		i++
		file, line := f.FileLine(programCounter - 1)
		buffer.AppendString(name)
		buffer.AppendByte('\n')
		buffer.AppendByte('\t')
		buffer.AppendString(file)
		buffer.AppendByte(':')
		buffer.AppendInt(int64(line))
	}

	return buffer.String()
}

func shouldIgnoreStacktraceName(name string) bool {
	for _, prefix := range _stacktraceIgnorePrefixes {
		if strings.HasPrefix(name, prefix) {
			return true
		}
	}
	return false
}


Review comment (bug):
Usually only stack suffix and prefix are trimmed, but here frames in middle of stack could be ignored. That can make stack inconsistent and hard to understand. 
For example, if we pass `Stringer` field to logger, which `String() string` call cause panic, and then take `Stack` in `defer`, we will miss valuable `runtime.panic` frames, and `zap` frames that points to problem inside our stringer. 
Test that illustrates example:
```go
type corruptedStringer struct{}
func (*corruptedStringer) String() string {
	var someNilPtr *string
	return *someNilPtr
}
func TestMiddleStackFramesNotSkipped(t *testing.T) {
	l, err := zap.NewProduction()
	require.NoError(t, err)
	defer func() {
		require.NotNil(t, recover(), "should panic")
		f := zap.Stack("stacktrace")
		enc := zapcore.NewMapObjectEncoder()
		f.AddTo(enc)
		stack := enc.Fields["stacktrace"]
		t.Logf("real stack: %s\n", debug.Stack())
		assert.Contains(t, stack, "panic")
		assert.Contains(t, stack, "zap")
	}()
	l.Warn("", zap.Stringer("should panic inside zap package", &corruptedStringer{}))
}
```
Test run outside of zap repo (allows not to skip test frames) fails with message:
```
test_test.go:32: real stack: goroutine 5 [running]:
    runtime/debug.Stack(0x26b8e0, 0xc420019410, 0x2b9581)
        /usr/local/Cellar/go/1.7.4_2/libexec/src/runtime/debug/stack.go:24 +0x79
    github.com/skipor/playground.TestMiddleStackFramesNotSkipped.func1(0xc420088180)
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:32 +0x251
    panic(0x26cee0, 0xc4200120d0)
        /usr/local/Cellar/go/1.7.4_2/libexec/src/runtime/panic.go:458 +0x243
    github.com/skipor/playground.(*corruptedStringer).String(0x413898, 0x266240, 0x413898)
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:20 +0x2
    go.uber.org/zap/zapcore.Field.AddTo(0x2c0171, 0x1f, 0x17, 0x0, 0x0, 0x0, 0x266240, 0x413898, 0x3df600, 0xc4200ccb20)
        /Users/skipor/Dev/Go/src/go.uber.org/zap/zapcore/field.go:152 +0xca1
    go.uber.org/zap/zapcore.addFields(0x3df600, 0xc4200ccb20, 0xc42000cc40, 0x1, 0x1)
        /Users/skipor/Dev/Go/src/go.uber.org/zap/zapcore/field.go:178 +0x74
    go.uber.org/zap/zapcore.(*jsonEncoder).EncodeEntry(0xc4200cc9e0, 0x1, 0xed04740fa, 0x6396a92, 0x3f7160, 0x0, 0x0, 0x0, 0x0, 0x1, ...)
        /Users/skipor/Dev/Go/src/go.uber.org/zap/zapcore/json_encoder.go:312 +0x346
    go.uber.org/zap/zapcore.(*ioCore).Write(0xc4200193b0, 0x1, 0xed04740fa, 0x6396a92, 0x3f7160, 0x0, 0x0, 0x0, 0x0, 0x1, ...)
        /Users/skipor/Dev/Go/src/go.uber.org/zap/zapcore/core.go:85 +0xa9
    go.uber.org/zap/zapcore.(*CheckedEntry).Write(0xc4200a6370, 0xc42000cc40, 0x1, 0x1)
        /Users/skipor/Dev/Go/src/go.uber.org/zap/zapcore/entry.go:170 +0x147
    go.uber.org/zap.(*Logger).Warn(0xc4200107e0, 0x0, 0x0, 0xc42000cc40, 0x1, 0x1)
        /Users/skipor/Dev/Go/src/go.uber.org/zap/logger.go:169 +0x7f
    github.com/skipor/playground.TestMiddleStackFramesNotSkipped(0xc420088180)
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:36 +0x22c
    testing.tRunner(0xc420088180, 0x2dc2b8)
        /usr/local/Cellar/go/1.7.4_2/libexec/src/testing/testing.go:610 +0x81
    created by testing.(*T).Run
        /usr/local/Cellar/go/1.7.4_2/libexec/src/testing/testing.go:646 +0x2ec
		
Error Trace:	
    test_test.go:33
    asm_amd64.s:479
    panic.go:458
    panic.go:62
    sigpanic_unix.go:24
    test_test.go:20
    field.go:152
    field.go:178
    json_encoder.go:312
    core.go:85
    entry.go:170
    logger.go:169
    test_test.go:36
Error:		
    "github.com/skipor/playground.TestMiddleStackFramesNotSkipped.func1
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:28
    github.com/skipor/playground.(*corruptedStringer).String
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:19
    github.com/skipor/playground.TestMiddleStackFramesNotSkipped
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:36
    testing.tRunner
        /usr/local/Cellar/go/1.7.4_2/libexec/src/testing/testing.go:610" does not contain "panic"
    
Error Trace:	
    test_test.go:34
    asm_amd64.s:479
    panic.go:458
    panic.go:62
    sigpanic_unix.go:24
    test_test.go:20
    field.go:152
    field.go:178
    json_encoder.go:312
    core.go:85
    entry.go:170
    logger.go:169
    test_test.go:36
Error:	
    "github.com/skipor/playground.TestMiddleStackFramesNotSkipped.func1
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:28
    github.com/skipor/playground.(*corruptedStringer).String
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:19
    github.com/skipor/playground.TestMiddleStackFramesNotSkipped
        /Users/skipor/Dev/Go/src/github.com/skipor/playground/test_test.go:36
    testing.tRunner
        /usr/local/Cellar/go/1.7.4_2/libexec/src/testing/testing.go:610" does not contain "zap"
```
So, consider only to trim `runtime` stack bottom, and `zap` stack top.


Code after:
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package zap

import (
	"runtime"
	"strings"
	"sync"

	"go.uber.org/zap/internal/bufferpool"
)

var (
	_stacktraceIgnorePrefixes = []string{
		"runtime.goexit",
		"runtime.main",
	}
	_stacktracePool = sync.Pool{
		New: func() interface{} {
			return newProgramCounters(64)
		},
	}
)

func takeStacktrace() string {
	buffer := bufferpool.Get()
	defer bufferpool.Put(buffer)
	programCounters := _stacktracePool.Get().(*programCounters)
	defer _stacktracePool.Put(programCounters)

	for {
		// Skip the call to runtime.Counters and takeStacktrace so that the
		// program counters start at the caller of takeStacktrace.
		n := runtime.Callers(2, programCounters.pcs)
		if n < cap(programCounters.pcs) {
			programCounters.pcs = programCounters.pcs[:n]
			break
		}
		// Don't put the too-short counter slice back into the pool; this lets
		// the pool adjust if we consistently take deep stacktraces.
		programCounters = newProgramCounters(len(programCounters.pcs) * 2)
	}

	i := 0
	for _, programCounter := range programCounters.pcs {
		f := runtime.FuncForPC(programCounter)
		name := f.Name()
		if shouldIgnoreStacktraceName(name) {
			continue
		}
		if i != 0 {
			buffer.AppendByte('\n')
		}
		i++
		file, line := f.FileLine(programCounter - 1)
		buffer.AppendString(name)
		buffer.AppendByte('\n')
		buffer.AppendByte('\t')
		buffer.AppendString(file)
		buffer.AppendByte(':')
		buffer.AppendInt(int64(line))
	}

	return buffer.String()
}

func shouldIgnoreStacktraceName(name string) bool {
	for _, prefix := range _stacktraceIgnorePrefixes {
		if strings.HasPrefix(name, prefix) {
			return true
		}
	}
	return false
}

type programCounters struct {
	pcs []uintptr
}

func newProgramCounters(size int) *programCounters {
	return &programCounters{make([]uintptr, size)}
}