From 795d92ab3455044348ae63ef0874ae0cb599241a Mon Sep 17 00:00:00 2001 From: Prashant V Date: Sun, 27 Oct 2024 23:48:24 -0700 Subject: [PATCH 1/4] Add GetCaller for use in error helpers `errtrace.Wrap` captures the immediate caller, which doesn't compose with existing error-wrapping helpers. To support this use-case, add `errtrace.GetCaller()` that helpers can use to capture their caller and add that to the error trace. This approach was chosen over the typical `skip` callers as: * Skip requires a more complex assembly implementation to skip an arbitrary number of frames, which is more error-prone, e.g., handling the skip argument being too large. * Faster as each call only skips a fixed (and predictable) number of frames. This is especially important since it's expected that `errtrace` is used to annotate all frames in the return path. * Avoids skip calculations, and generally more flexible to pass around compared to skipping frames, which is tied to the stack. Regardless of which approach is chosen, there is a limitation: incompatibility with inlined callers. Go tracks inlined code and PCs of inlined code is correctly mapped back, but the stack does not contain inlined frames, so the skip calculation done cannot correctly skip inlined frames. This approach only requires the error helper to have a stack frame, which is typically the case when calling `errtrace.GetCaller` followed by `Wrap`, but callers should use `go:noinline` for correct stack frames. --- example_errhelper_test.go | 44 ++++++++++++++++ internal/pc/pc_amd64.s | 8 +++ internal/pc/pc_arm64.s | 9 ++++ internal/pc/pc_asm.go | 3 ++ internal/pc/pc_safe.go | 20 ++++++-- wrap_caller.go | 25 +++++++++ wrap_caller_safe_test.go | 10 ++++ wrap_caller_test.go | 105 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 219 insertions(+), 5 deletions(-) create mode 100644 example_errhelper_test.go create mode 100644 wrap_caller.go create mode 100644 wrap_caller_safe_test.go create mode 100644 wrap_caller_test.go diff --git a/example_errhelper_test.go b/example_errhelper_test.go new file mode 100644 index 0000000..86b7180 --- /dev/null +++ b/example_errhelper_test.go @@ -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 +} diff --git a/internal/pc/pc_amd64.s b/internal/pc/pc_amd64.s index 82be23c..cd56407 100644 --- a/internal/pc/pc_amd64.s +++ b/internal/pc/pc_amd64.s @@ -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 diff --git a/internal/pc/pc_arm64.s b/internal/pc/pc_arm64.s index c26a85f..2212f1b 100644 --- a/internal/pc/pc_arm64.s +++ b/internal/pc/pc_arm64.s @@ -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 diff --git a/internal/pc/pc_asm.go b/internal/pc/pc_asm.go index 3d6d597..1ff83ed 100644 --- a/internal/pc/pc_asm.go +++ b/internal/pc/pc_asm.go @@ -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 diff --git a/internal/pc/pc_safe.go b/internal/pc/pc_safe.go index 6e7f002..5fdc22f 100644 --- a/internal/pc/pc_safe.go +++ b/internal/pc/pc_safe.go @@ -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 } diff --git a/wrap_caller.go b/wrap_caller.go new file mode 100644 index 0000000..696c066 --- /dev/null +++ b/wrap_caller.go @@ -0,0 +1,25 @@ +package errtrace + +import "braces.dev/errtrace/internal/pc" + +// Caller represents a single caller frame, intended for ... +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. +// +// Note: Callers of this function should be marked using `//go:noinline` +// to avoid inlining, as GetCaller expects to skip the caller's stack frame. +// +//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) +} diff --git a/wrap_caller_safe_test.go b/wrap_caller_safe_test.go new file mode 100644 index 0000000..377795e --- /dev/null +++ b/wrap_caller_safe_test.go @@ -0,0 +1,10 @@ +//go:build safe || !(amd64 || arm64) + +// +// Build tag must match pc_safe.go + +package errtrace_test + +func init() { + safe = true +} diff --git a/wrap_caller_test.go b/wrap_caller_test.go new file mode 100644 index 0000000..df53580 --- /dev/null +++ b/wrap_caller_test.go @@ -0,0 +1,105 @@ +package errtrace_test + +import ( + "errors" + "runtime" + "strings" + "testing" + + "braces.dev/errtrace" +) + +var safe = false + +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 we end up using its' caller. + // Callers of GetCaller using `go:noinline` avoid this (hence the docs). + 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 +} From 959ee853ba265a657b47beef412970616e2b5a9f Mon Sep 17 00:00:00 2001 From: Prashant V Date: Sat, 9 Nov 2024 19:57:45 -0800 Subject: [PATCH 2/4] TestGetCallerWrap_RetCaller: allow both correct/incorrect when !safe --- wrap_caller_test.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/wrap_caller_test.go b/wrap_caller_test.go index df53580..c21cbec 100644 --- a/wrap_caller_test.go +++ b/wrap_caller_test.go @@ -63,9 +63,13 @@ func TestGetCallerWrap_RetCaller(t *testing.T) { wantFn := "callRetCaller" if !safe { // If the function calling pc.GetCaller is inlined, there's no stack frame - // so we end up using its' caller. - // Callers of GetCaller using `go:noinline` avoid this (hence the docs). - wantFn = "TestGetCallerWrap_RetCaller" + // 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) } From da968e0e9c1e259ab08b899315773bc3894881bd Mon Sep 17 00:00:00 2001 From: Prashant V Date: Sat, 9 Nov 2024 21:46:56 -0800 Subject: [PATCH 3/4] Update doc comments --- wrap_caller.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/wrap_caller.go b/wrap_caller.go index 696c066..3bc0ff7 100644 --- a/wrap_caller.go +++ b/wrap_caller.go @@ -2,7 +2,8 @@ package errtrace import "braces.dev/errtrace/internal/pc" -// Caller represents a single caller frame, intended for ... +// 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 } @@ -10,8 +11,15 @@ type Caller struct { // GetCaller captures the program counter of a caller, primarily intended for // error helpers so caller information captures the helper's caller. // -// Note: Callers of this function should be marked using `//go:noinline` -// to avoid inlining, as GetCaller expects to skip the caller's stack frame. +// 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 { From b1783c85d4a72444b81dd79d7f21a0ea958161eb Mon Sep 17 00:00:00 2001 From: Prashant V Date: Sat, 9 Nov 2024 21:48:52 -0800 Subject: [PATCH 4/4] Add note for why tests don't use a test table --- wrap_caller_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/wrap_caller_test.go b/wrap_caller_test.go index c21cbec..eb9d41b 100644 --- a/wrap_caller_test.go +++ b/wrap_caller_test.go @@ -11,6 +11,10 @@ import ( 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")