Debian Codegraph @

stack/source.go

raw
1 // Copyright 2015 Marc-Antoine Ruel. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 // This file contains the code to process sources, to be able to deduct the
6 // original types.
7
8 package stack
9
10 import (
11 "bytes"
12 "fmt"
13 "go/ast"
14 "go/parser"
15 "go/token"
16 "math"
17 "os"
18 "strconv"
19 "strings"
20 )
21
22 // Private stuff.
23
24 // cacheAST is a cache of parsed Go sources.
25 type cacheAST struct {
26 files map[string][]byte
27 parsed map[string]*parsedFile
28 }
29
30 // augmentGoroutine processes source files to improve call to be more
31 // descriptive.
32 //
33 // It modifies the routine.
34 func (c *cacheAST) augmentGoroutine(g *Goroutine) error {
35 var err error
36 for i, call := range g.Stack.Calls {
37 // Only load the AST if there's an argument to process.
38 if len(call.Args.Values) == 0 {
39 continue
40 }
41 if err1 := c.loadFile(g.Stack.Calls[i].LocalSrcPath); err1 != nil {
42 //log.Printf("%s", err)
43 err = err1
44 }
45 if p := c.parsed[call.LocalSrcPath]; p != nil {
46 f, err1 := p.getFuncAST(call.Func.Name, call.Line)
47 if err1 != nil {
48 err = err1
49 continue
50 }
51 if f != nil {
52 augmentCall(&g.Stack.Calls[i], f)
53 }
54 }
55 }
56 return err
57 }
58
59 // loadFile loads a Go source file and parses the AST tree.
60 func (c *cacheAST) loadFile(fileName string) error {
61 if fileName == "" {
62 return nil
63 }
64 if _, ok := c.parsed[fileName]; ok {
65 return nil
66 }
67 // Do not attempt to parse the same file twice.
68 c.parsed[fileName] = nil
69
70 if !strings.HasSuffix(fileName, ".go") {
71 // Ignore C and assembly.
72 return fmt.Errorf("cannot load non-go file %q", fileName)
73 }
74 /* #nosec G304 */
75 src, err := os.ReadFile(fileName)
76 if err != nil {
77 return err
78 }
79 c.files[fileName] = src
80 fset := token.NewFileSet()
81 parsed, err := parser.ParseFile(fset, fileName, src, 0)
82 if err != nil {
83 return fmt.Errorf("failed to parse %w", err)
84 }
85 c.parsed[fileName] = &parsedFile{
86 lineToByteOffset: lineToByteOffsets(src),
87 parsed: parsed,
88 }
89 return nil
90 }
91
92 // lineToByteOffsets extract the line number into raw file offset.
93 //
94 // Inserts a dummy 0 at offset 0 so line offsets can be 1 based.
95 func lineToByteOffsets(src []byte) []int {
96 offsets := []int{0, 0}
97 for offset := 0; offset < len(src); {
98 n := bytes.IndexByte(src[offset:], '\n')
99 if n == -1 {
100 break
101 }
102 offset += n + 1
103 offsets = append(offsets, offset)
104 }
105 return offsets
106 }
107
108 // parsedFile is a processed Go source file.
109 type parsedFile struct {
110 lineToByteOffset []int
111 parsed *ast.File
112 }
113
114 // getFuncAST gets the callee site function AST representation for the code
115 // inside the function f at line l.
116 func (p *parsedFile) getFuncAST(f string, l int) (d *ast.FuncDecl, err error) {
117 if len(p.lineToByteOffset) <= l {
118 // The line number in the stack trace line does not exist in the file. That
119 // can only mean that the sources on disk do not match the sources used to
120 // build the binary.
121 return nil, fmt.Errorf("line %d is over line count of %d", l, len(p.lineToByteOffset)-1)
122 }
123
124 // Walk the AST to find the lineToByteOffset that fits the line number.
125 var lastFunc *ast.FuncDecl
126 // Inspect() goes depth first. This means for example that a function like:
127 // func a() {
128 // b := func() {}
129 // c()
130 // }
131 //
132 // Were we are looking at the c() call can return confused values. It is
133 // important to look at the actual ast.Node hierarchy.
134 ast.Inspect(p.parsed, func(n ast.Node) bool {
135 if d != nil {
136 return false
137 }
138 if n == nil {
139 return true
140 }
141 if int(n.Pos()) >= p.lineToByteOffset[l] {
142 // We are expecting a ast.CallExpr node. It can be harder to figure out
143 // when there are multiple calls on a single line, as the stack trace
144 // doesn't have file byte offset information, only line based.
145 // gofmt will always format to one function call per line but there can
146 // be edge cases, like:
147 // a = A{Foo(), Bar()}
148 d = lastFunc
149 //p.processNode(call, n)
150 return false
151 } else if f, ok := n.(*ast.FuncDecl); ok {
152 lastFunc = f
153 }
154 return true
155 })
156 return
157 }
158
159 func name(n ast.Node) string {
160 switch t := n.(type) {
161 case *ast.InterfaceType:
162 return "interface{}"
163 case *ast.Ident:
164 return t.Name
165 case *ast.SelectorExpr:
166 return t.Sel.Name
167 case *ast.StarExpr:
168 return "*" + name(t.X)
169 case *ast.BasicLit:
170 return t.Value
171 case *ast.Ellipsis:
172 return "..."
173 default:
174 return "<unknown>"
175 }
176 }
177
178 // fieldToType returns the type name and whether if it's an ellipsis.
179 func fieldToType(f *ast.Field) (string, bool) {
180 switch arg := f.Type.(type) {
181 case *ast.ArrayType:
182 if arg.Len != nil {
183 // Array.
184 return "[" + name(arg.Len) + "]" + name(arg.Elt), false
185 }
186 // Slice.
187 return "[]" + name(arg.Elt), false
188 case *ast.Ellipsis:
189 return name(arg.Elt), true
190 case *ast.FuncType:
191 // Do not print the function signature to not overload the trace.
192 return "func", false
193 case *ast.Ident:
194 return arg.Name, false
195 case *ast.InterfaceType:
196 return "interface{}", false
197 case *ast.SelectorExpr:
198 return arg.Sel.Name, false
199 case *ast.StarExpr:
200 return "*" + name(arg.X), false
201 case *ast.MapType:
202 return fmt.Sprintf("map[%s]%s", name(arg.Key), name(arg.Value)), false
203 case *ast.ChanType:
204 return fmt.Sprintf("chan %s", name(arg.Value)), false
205 default:
206 // TODO(maruel): Implement anything missing.
207 return "<unknown>", false
208 }
209 }
210
211 // extractArgumentsType returns the name of the type of each input argument.
212 func extractArgumentsType(f *ast.FuncDecl) ([]string, bool) {
213 var fields []*ast.Field
214 if f.Recv != nil {
215 if len(f.Recv.List) != 1 {
216 panic("Expect only one receiver; please fix panicparse's code")
217 }
218 // If it is an object receiver (vs a pointer receiver), its address is not
219 // printed in the stack trace so it needs to be ignored.
220 if _, ok := f.Recv.List[0].Type.(*ast.StarExpr); ok {
221 fields = append(fields, f.Recv.List[0])
222 }
223 }
224 var types []string
225 ellipsis := false
226 for _, arg := range append(fields, f.Type.Params.List...) {
227 // Assert that ellipsis is only set on the last item of fields?
228 var t string
229 t, ellipsis = fieldToType(arg)
230 mult := len(arg.Names)
231 if mult == 0 {
232 mult = 1
233 }
234 for i := 0; i < mult; i++ {
235 types = append(types, t)
236 }
237 }
238 return types, ellipsis
239 }
240
241 // augmentCall walks the function and populate call accordingly.
242 func augmentCall(call *Call, f *ast.FuncDecl) {
243 flatArgs := make([]*Arg, 0, len(call.Args.Values))
244 call.Args.walk(func(arg *Arg) {
245 flatArgs = append(flatArgs, arg)
246 })
247
248 pop := func() *Arg {
249 if len(flatArgs) == 0 {
250 return nil
251 }
252 a := flatArgs[0]
253 flatArgs = flatArgs[1:]
254 return a
255 }
256 popFmt := func(fmtFn func(v uint64) string) string {
257 a := pop()
258 if a == nil {
259 return "<nil>"
260 }
261 if a.IsOffsetTooLarge {
262 return "_"
263 }
264 return fmtFn(a.Value)
265 }
266 popName := func() string {
267 a := pop()
268 if a == nil {
269 return "<nil>"
270 }
271 if len(a.Name) != 0 {
272 return a.Name
273 }
274 if a.IsOffsetTooLarge {
275 return "_"
276 }
277 return fmt.Sprintf("0x%x", a.Value)
278 }
279
280 types, extra := extractArgumentsType(f)
281 for i := 0; len(flatArgs) != 0; i++ {
282 var t string
283 if i >= len(types) {
284 if !extra {
285 // These are unexpected value! Print them as hex.
286 call.Args.Processed = append(call.Args.Processed, popName())
287 continue
288 }
289 t = types[len(types)-1]
290 } else {
291 t = types[i]
292 }
293 var str string
294 switch t {
295 case "float32":
296 str = popFmt(func(v uint64) string {
297 f := float64(math.Float32frombits(uint32(v)))
298 return strconv.FormatFloat(f, 'g', -1, 32)
299 })
300 case "float64":
301 str = popFmt(func(v uint64) string {
302 f := math.Float64frombits(v)
303 return strconv.FormatFloat(f, 'g', -1, 64)
304 })
305 case "int":
306 str = popFmt(func(v uint64) string {
307 return strconv.FormatInt(int64(int(v)), 10)
308 })
309 case "int8":
310 str = popFmt(func(v uint64) string {
311 return strconv.FormatInt(int64(int8(v)), 10)
312 })
313 case "int16":
314 str = popFmt(func(v uint64) string {
315 return strconv.FormatInt(int64(int16(v)), 10)
316 })
317 case "int32":
318 str = popFmt(func(v uint64) string {
319 return strconv.FormatInt(int64(int32(v)), 10)
320 })
321 case "int64":
322 str = popFmt(func(v uint64) string {
323 return strconv.FormatInt(int64(v), 10)
324 })
325 case "uint", "uint8", "uint16", "uint32", "uint64":
326 str = popFmt(func(v uint64) string {
327 return strconv.FormatUint(v, 10)
328 })
329 case "bool":
330 str = popFmt(func(v uint64) string {
331 if v == 0 {
332 return "false"
333 }
334 return "true"
335 })
336 case "string":
337 name := popName()
338 lenStr := popFmt(func(v uint64) string {
339 return strconv.FormatUint(v, 10)
340 })
341 str = fmt.Sprintf("%s(%s, len=%s)", t, name, lenStr)
342 default:
343 if strings.HasPrefix(t, "*") {
344 str = fmt.Sprintf("%s(%s)", t, popName())
345 } else if strings.HasPrefix(t, "[]") {
346 name := popName()
347 lenStr := popFmt(func(v uint64) string {
348 return strconv.FormatUint(v, 10)
349 })
350 capStr := popFmt(func(v uint64) string {
351 return strconv.FormatUint(v, 10)
352 })
353 str = fmt.Sprintf("%s(%s len=%s cap=%s)", t, name, lenStr, capStr)
354 } else {
355 if i < len(call.Args.Values) && call.Args.Values[i].IsAggregate {
356 // If top-level argument is an aggregate-type, include each
357 // of its sub-arguments.
358 v := &call.Args.Values[i].Fields
359 var fields []string
360 v.walk(func(arg *Arg) {
361 fields = append(fields, popName())
362 })
363 if v.Elided {
364 fields = append(fields, "...")
365 }
366 str = fmt.Sprintf("%s{%s}", t, strings.Join(fields, ", "))
367 } else {
368 // Assumes it's an interface. For now, discard the object
369 // value, which is probably not a good idea.
370 str = fmt.Sprintf("%s(%s)", t, popName())
371 pop()
372 }
373 }
374 }
375 call.Args.Processed = append(call.Args.Processed, str)
376 }
377 }