Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions example_errhelper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package errtrace_test

import (
"errors"
"fmt"

"braces.dev/errtrace"
"braces.dev/errtrace/internal/tracetest"
)

func f1Wrap() error {
return wrap(f2Wrap(), "u=1")
}

func f2Wrap() error {
return wrap(f3Wrap(), "method=order")
}

func f3Wrap() error {
return wrap(errors.New("failed"), "foo")
}

func wrap(err error, fields ...string) error {
return errtrace.GetCaller().
Wrap(fmt.Errorf("%w %v", err, fields))
}

func Example_getCaller() {
got := errtrace.FormatString(f1Wrap())

// make trace agnostic to environment-specific location
// and less sensitive to line number changes.
fmt.Println(tracetest.MustClean(got))

// Output:
//failed [foo] [method=order] [u=1]
//
//braces.dev/errtrace_test.f3Wrap
// /path/to/errtrace/example_errhelper_test.go:3
//braces.dev/errtrace_test.f2Wrap
// /path/to/errtrace/example_errhelper_test.go:2
//braces.dev/errtrace_test.f1Wrap
// /path/to/errtrace/example_errhelper_test.go:1
}
8 changes: 8 additions & 0 deletions internal/pc/pc_amd64.s
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,11 @@ TEXT ·GetCaller(SB),NOSPLIT|NOFRAME,$0-8
MOVQ 8(BP), AX
MOVQ AX, ret+0(FP)
RET

// func GetCallerSkip1() uintptr
TEXT ·GetCallerSkip1(SB),NOSPLIT|NOFRAME,$0-8
// BP contains the frame pointer, dereference it to skip a frame.
MOVQ (BP), AX
MOVQ 8(AX), AX
MOVQ AX, ret+0(FP)
RET
9 changes: 9 additions & 0 deletions internal/pc/pc_arm64.s
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@ TEXT ·GetCaller(SB),NOSPLIT|NOFRAME,$0-8
MOVD 8(R29), R20
MOVD R20, ret+0(FP)
RET


// func GetCallerSkip1() uintptr
TEXT ·GetCallerSkip1(SB),NOSPLIT|NOFRAME,$0-8
// R29 contains the frame pointer, dereference it to skip a frame.
MOVD (R29), R20
MOVD 8(R20), R20
MOVD R20, ret+0(FP)
RET
3 changes: 3 additions & 0 deletions internal/pc/pc_asm.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ package pc

// GetCaller returns the program counter of the caller's caller.
func GetCaller() uintptr

// GetCallerSkip1 is similar to GetCaller, but skips an additional caller.
func GetCallerSkip1() uintptr
20 changes: 15 additions & 5 deletions internal/pc/pc_safe.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,24 @@ package pc

import "runtime"

// GetCaller gets the caller's caller's PC.
// GetCaller returns the program counter of the caller's caller.
func GetCaller() uintptr {
const skip = 1 + // frame for Callers
1 + // frame for GetCaller
1 // frame for our caller, which should be errtrace.Wrap
return getCaller(0)
}

// GetCallerSkip1 is similar to GetCaller, but skips an additional caller.
func GetCallerSkip1() uintptr {
return getCaller(1)
}

func getCaller(skip int) uintptr {
const baseSkip = 1 + // runtime.Callers
1 + // getCaller
1 + // GetCaller or GetCallerSkip1
1 // errtrace.Wrap, or errtrace.GetCaller

var callers [1]uintptr
n := runtime.Callers(skip, callers[:]) // skip getcallerpc + caller
n := runtime.Callers(baseSkip+skip, callers[:]) // skip getcallerpc + caller
if n == 0 {
return 0
}
Expand Down
33 changes: 33 additions & 0 deletions wrap_caller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package errtrace

import "braces.dev/errtrace/internal/pc"

// Caller represents a single caller frame, and is intended for error helpers
// to capture caller information for wrapping. See [GetCaller] for details.
type Caller struct {
callerPC uintptr
}

// GetCaller captures the program counter of a caller, primarily intended for
// error helpers so caller information captures the helper's caller.
//
Comment thread
prashantv marked this conversation as resolved.
Resolved
// Callers of this function should be marked '//go:noinline' to avoid inlining,
// as GetCaller expects to skip the caller's stack frame.
//
// //go:noinline
// func Wrapf(err error, msg string, args ...any) {
// caller := errtrace.GetCaller()
// err := ...
// return caller.Wrap(err)
// }
//
//go:noinline
func GetCaller() Caller {
return Caller{pc.GetCallerSkip1()}
}

// Wrap adds the program counter captured in Caller to the error,
// similar to [Wrap], but relying on previously captured caller inforamtion.
func (c Caller) Wrap(err error) error {
return wrap(err, c.callerPC)
}
10 changes: 10 additions & 0 deletions wrap_caller_safe_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
//go:build safe || !(amd64 || arm64)

//
// Build tag must match pc_safe.go

package errtrace_test

func init() {
safe = true
}
113 changes: 113 additions & 0 deletions wrap_caller_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package errtrace_test

import (
"errors"
"runtime"
"strings"
"testing"

"braces.dev/errtrace"
)

var safe = false

// Note: Though test tables could DRY up the below tests, they're intentionally
// kept as functions calling other simple functions to test how inlining impacts
// use of `GetCaller`.

func TestGetCallerWrap_ErrorsNew(t *testing.T) {
err := callErrorsNew()
wantErr(t, err, "callErrorsNew")
}

func callErrorsNew() error {
return errorsNew("wrap errors.New")
}

func errorsNew(msg string) error {
caller := errtrace.GetCaller()
return caller.Wrap(errors.New(msg))
}

func TestGetCallerWrap_WrapExisting(t *testing.T) {
err := callWrapExisting()
wantErr(t, err, "callWrapExisting")
}

func callWrapExisting() error {
return wrapExisting()
}

var errFoo = errors.New("foo")

func wrapExisting() error {
return errtrace.GetCaller().Wrap(errFoo)
}

func TestGetCallerWrap_PassCaller(t *testing.T) {
err := callPassCaller()
wantErr(t, err, "callPassCaller")
}

func callPassCaller() error {
return passCaller()
}

func passCaller() error {
return passCallerInner(errtrace.GetCaller())
}

func passCallerInner(caller errtrace.Caller) error {
return caller.Wrap(errFoo)
}

func TestGetCallerWrap_RetCaller(t *testing.T) {
err := callRetCaller()

wantFn := "callRetCaller"
if !safe {
// If the function calling pc.GetCaller is inlined, there's no stack frame
// so the assembly implementation can skip the correct caller.
// Callers of GetCaller using `go:noinline` avoid this (as recommended in the docs).
// Inlining is not consistent, hence we check the frame in !safe mode.
f, _, _ := errtrace.UnwrapFrame(err)
if !strings.HasSuffix(f.Function, wantFn) {
wantFn = "TestGetCallerWrap_RetCaller"
}
}
wantErr(t, err, wantFn)
}

func callRetCaller() error {
return retCaller().Wrap(errFoo)
}

func retCaller() errtrace.Caller {
return errtrace.GetCaller()
}

func TestGetCallerWrap_RetCallerNoInline(t *testing.T) {
err := callRetCallerNoInline()
wantErr(t, err, "callRetCallerNoInline")
}

func callRetCallerNoInline() error {
return retCallerNoInline().Wrap(errFoo)
}

//go:noinline
func retCallerNoInline() errtrace.Caller {
return errtrace.GetCaller()
}

func wantErr(t testing.TB, err error, fn string) runtime.Frame {
if err == nil {
t.Fatalf("expected err")
}

f, _, _ := errtrace.UnwrapFrame(err)
if !strings.HasSuffix(f.Function, "."+fn) {
t.Errorf("expected caller to be %v, got %v", fn, f.Function)
}
return f
}