Debian Codegraph @

internal/trace/trace.go

raw
1 // Copyright (c) 2021, Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package trace
8
9 import (
10 "fmt"
11 "go/build"
12 "os"
13 "path/filepath"
14 "runtime"
15 "strings"
16 )
17
18 var (
19 ignorePkg = map[string]struct{}{}
20 goPaths []string
21 goModDir string
22 )
23
24 func getPackage(skip ...int) string {
25 sk := 2
26 if len(skip) > 0 {
27 sk += skip[0]
28 }
29 pc, _, _, ok := runtime.Caller(sk)
30 if ok {
31 fn := runtime.FuncForPC(pc)
32 if fn != nil {
33 pkg, _ := SplitPackageFunc(fn.Name())
34 return pkg
35 }
36 }
37 return ""
38 }
39
40 // IgnorePackage records the calling package as ignored one in trace.
41 func IgnorePackage(skip ...int) bool {
42 if pkg := getPackage(skip...); pkg != "" {
43 ignorePkg[pkg] = struct{}{}
44 return true
45 }
46 return false
47 }
48
49 // UnignorePackage cancels a previous use of [IgnorePackage], so the
50 // calling package is no longer ignored. Only intended to be used in
51 // go-testdeep internal tests.
52 func UnignorePackage(skip ...int) bool {
53 if pkg := getPackage(skip...); pkg != "" {
54 delete(ignorePkg, pkg)
55 return true
56 }
57 return false
58 }
59
60 // IsIgnoredPackage returns true if pkg is ignored, false
61 // otherwise. Only intended to be used in go-testdeep internal tests.
62 func IsIgnoredPackage(pkg string) (ok bool) {
63 _, ok = ignorePkg[pkg]
64 return
65 }
66
67 // FindGoModDir finds the closest directory containing go.mod file
68 // starting from directory in.
69 func FindGoModDir(in string) string {
70 for {
71 _, err := os.Stat(filepath.Join(in, "go.mod"))
72 if err == nil {
73 // Do not accept /tmp/go.mod
74 if in != os.TempDir() {
75 return in + string(filepath.Separator)
76 }
77 return ""
78 }
79
80 nd := filepath.Dir(in)
81 if nd == in {
82 return ""
83 }
84 in = nd
85 }
86 }
87
88 // FindGoModDirLinks finds the closest directory containing go.mod
89 // file starting from directory in after cleaning it. If not found,
90 // expands symlinks and re-searches.
91 func FindGoModDirLinks(in string) string {
92 in = filepath.Clean(in)
93
94 if gm := FindGoModDir(in); gm != "" {
95 return gm
96 }
97
98 lin, err := filepath.EvalSymlinks(in)
99 if err == nil && lin != in {
100 return FindGoModDir(lin)
101 }
102 return ""
103 }
104
105 // Reset resets the ignored packages map plus cached mod and GOPATH
106 // directories ([Init] should be called again). Only intended to be
107 // used in go-testdeep internal tests.
108 func Reset() {
109 ignorePkg = map[string]struct{}{}
110 goPaths = nil
111 goModDir = ""
112 }
113
114 // Init initializes trace global variables.
115 func Init() {
116 // GOPATH directories
117 goPaths = nil //nolint: prealloc
118 for _, dir := range filepath.SplitList(build.Default.GOPATH) {
119 dir = filepath.Clean(dir)
120 goPaths = append(goPaths,
121 filepath.Join(dir, "pkg", "mod")+string(filepath.Separator),
122 filepath.Join(dir, "src")+string(filepath.Separator),
123 )
124 }
125
126 if wd, err := os.Getwd(); err == nil {
127 // go.mod directory
128 goModDir = FindGoModDirLinks(wd)
129 }
130 }
131
132 // Frames is the interface corresponding to type returned by
133 // [runtime.CallersFrames]. See [CallersFrames] variable.
134 type Frames interface {
135 Next() (frame runtime.Frame, more bool)
136 }
137
138 // CallersFrames is only intended to be used in go-testdeep internal
139 // tests to cover all cases.
140 var CallersFrames = func(callers []uintptr) Frames {
141 return runtime.CallersFrames(callers)
142 }
143
144 // Retrieve retrieves a trace and returns it.
145 func Retrieve(skip int, endFunction string) Stack {
146 var trace Stack
147 var pc [40]uintptr
148 if num := runtime.Callers(skip+2, pc[:]); num > 0 {
149 checkIgnore := true
150 frames := CallersFrames(pc[:num])
151 for {
152 frame, more := frames.Next()
153
154 fn := frame.Function
155 if fn == endFunction {
156 break
157 }
158
159 var pkg string
160 if fn == "" {
161 if frame.File == "" {
162 if more {
163 continue
164 }
165 break
166 }
167 fn = "<unknown function>"
168 } else {
169 pkg, fn = SplitPackageFunc(fn)
170 if checkIgnore && IsIgnoredPackage(pkg) {
171 if more {
172 continue
173 }
174 break
175 }
176 checkIgnore = false
177 }
178
179 file := strings.TrimPrefix(frame.File, goModDir)
180 if file == frame.File {
181 for _, dir := range goPaths {
182 file = strings.TrimPrefix(frame.File, dir)
183 if file != frame.File {
184 break
185 }
186 }
187
188 if file == frame.File {
189 file = strings.TrimPrefix(frame.File, build.Default.GOROOT)
190 if file != frame.File {
191 file = filepath.Join("$GOROOT", file)
192 }
193 }
194 }
195
196 level := Level{
197 Package: pkg,
198 Func: fn,
199 }
200 if file != "" {
201 level.FileLine = fmt.Sprintf("%s:%d", file, frame.Line)
202 }
203
204 trace = append(trace, level)
205 if !more {
206 break
207 }
208 }
209 }
210 return trace
211 }
212
213 // SplitPackageFunc splits a fully qualified function name into its
214 // package and function parts:
215 //
216 // "foo/bar/test.fn" → "foo/bar/test", "fn"
217 // "foo/bar/test.X.fn" → "foo/bar/test", "X.fn"
218 // "foo/bar/test.(*X).fn" → "foo/bar/test", "(*X).fn"
219 // "foo/bar/test.(*X).fn.func1" → "foo/bar/test", "(*X).fn.func1"
220 // "weird" → "", "weird"
221 func SplitPackageFunc(fn string) (string, string) {
222 sp := strings.LastIndexByte(fn, '/')
223 if sp < 0 {
224 sp = 0 // std package
225 }
226
227 dp := strings.IndexByte(fn[sp:], '.')
228 if dp < 0 {
229 return "", fn
230 }
231
232 return fn[:sp+dp], fn[sp+dp+1:]
233 }