| 1 | // Copyright (c) The EfficientGo Authors. |
| 2 | // Licensed under the Apache License 2.0. |
| 3 | |
| 4 | // Initially copied from Thanos and contributed by https://github.com/bisakhmondal. |
| 5 | // |
| 6 | // Copyright (c) The Thanos Authors. |
| 7 | // Licensed under the Apache License 2.0. |
| 8 | |
| 9 | package errors |
| 10 | |
| 11 | import ( |
| 12 | "fmt" |
| 13 | "runtime" |
| 14 | "strings" |
| 15 | ) |
| 16 | |
| 17 | // stacktrace holds a snapshot of program counters. |
| 18 | type stacktrace []uintptr |
| 19 | |
| 20 | // newStackTrace captures a stack trace. It skips first 3 frames to record the |
| 21 | // snapshot of the stack trace at the origin of a particular error. It tries to |
| 22 | // record maximum 16 frames (if available). |
| 23 | func newStackTrace() stacktrace { |
| 24 | const stackDepth = 16 // record maximum 16 frames (if available). |
| 25 | |
| 26 | pc := make([]uintptr, stackDepth) |
| 27 | // using skip=3 for not to count the program counter address of |
| 28 | // 1. the respective function from errors package (eg. errors.New) |
| 29 | // 2. newStacktrace itself |
| 30 | // 3. the function used in runtime.Callers |
| 31 | n := runtime.Callers(3, pc) |
| 32 | |
| 33 | // this approach is taken to reduce long term memory footprint (obtained through escape analysis). |
| 34 | // We are returning a new slice by re-slicing the pc with the required length and capacity (when the |
| 35 | // no of returned callFrames is less that stackDepth). This uses less memory compared to pc[:n] as |
| 36 | // the capacity of new slice is inherited from the parent slice if not specified. |
| 37 | return pc[:n:n] |
| 38 | } |
| 39 | |
| 40 | // String implements the fmt.Stringer interface to provide formatted text output. |
| 41 | func (s stacktrace) String() string { |
| 42 | var buf strings.Builder |
| 43 | |
| 44 | // CallersFrames takes the slice of Program Counter addresses returned by Callers to |
| 45 | // retrieve function/file/line information. |
| 46 | cf := runtime.CallersFrames(s) |
| 47 | for { |
| 48 | // more indicates if the next call will be successful or not. |
| 49 | frame, more := cf.Next() |
| 50 | // used formatting scheme <`>`space><function name><tab><filepath><:><line><newline> for example: |
| 51 | // > testing.tRunner /home/go/go1.17.8/src/testing/testing.go:1259 |
| 52 | buf.WriteString(fmt.Sprintf("> %s\t%s:%d\n", frame.Func.Name(), frame.File, frame.Line)) |
| 53 | if !more { |
| 54 | break |
| 55 | } |
| 56 | } |
| 57 | return buf.String() |
| 58 | } |