1// Copyright 2021 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package pkgbits
6
7import (
8	"fmt"
9	"runtime"
10	"strings"
11)
12
13// fmtFrames formats a backtrace for reporting reader/writer desyncs.
14func fmtFrames(pcs ...uintptr) []string {
15	res := make([]string, 0, len(pcs))
16	walkFrames(pcs, func(file string, line int, name string, offset uintptr) {
17		// Trim package from function name. It's just redundant noise.
18		name = strings.TrimPrefix(name, "cmd/compile/internal/noder.")
19
20		res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset))
21	})
22	return res
23}
24
25type frameVisitor func(file string, line int, name string, offset uintptr)
26
27// walkFrames calls visit for each call frame represented by pcs.
28//
29// pcs should be a slice of PCs, as returned by runtime.Callers.
30func walkFrames(pcs []uintptr, visit frameVisitor) {
31	if len(pcs) == 0 {
32		return
33	}
34
35	frames := runtime.CallersFrames(pcs)
36	for {
37		frame, more := frames.Next()
38		visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry)
39		if !more {
40			return
41		}
42	}
43}
44
45// SyncMarker is an enum type that represents markers that may be
46// written to export data to ensure the reader and writer stay
47// synchronized.
48type SyncMarker int
49
50//go:generate stringer -type=SyncMarker -trimprefix=Sync
51
52const (
53	_ SyncMarker = iota
54
55	// Public markers (known to go/types importers).
56
57	// Low-level coding markers.
58	SyncEOF
59	SyncBool
60	SyncInt64
61	SyncUint64
62	SyncString
63	SyncValue
64	SyncVal
65	SyncRelocs
66	SyncReloc
67	SyncUseReloc
68
69	// Higher-level object and type markers.
70	SyncPublic
71	SyncPos
72	SyncPosBase
73	SyncObject
74	SyncObject1
75	SyncPkg
76	SyncPkgDef
77	SyncMethod
78	SyncType
79	SyncTypeIdx
80	SyncTypeParamNames
81	SyncSignature
82	SyncParams
83	SyncParam
84	SyncCodeObj
85	SyncSym
86	SyncLocalIdent
87	SyncSelector
88
89	// Private markers (only known to cmd/compile).
90	SyncPrivate
91
92	SyncFuncExt
93	SyncVarExt
94	SyncTypeExt
95	SyncPragma
96
97	SyncExprList
98	SyncExprs
99	SyncExpr
100	SyncExprType
101	SyncAssign
102	SyncOp
103	SyncFuncLit
104	SyncCompLit
105
106	SyncDecl
107	SyncFuncBody
108	SyncOpenScope
109	SyncCloseScope
110	SyncCloseAnotherScope
111	SyncDeclNames
112	SyncDeclName
113
114	SyncStmts
115	SyncBlockStmt
116	SyncIfStmt
117	SyncForStmt
118	SyncSwitchStmt
119	SyncRangeStmt
120	SyncCaseClause
121	SyncCommClause
122	SyncSelectStmt
123	SyncDecls
124	SyncLabeledStmt
125	SyncUseObjLocal
126	SyncAddLocal
127	SyncLinkname
128	SyncStmt1
129	SyncStmtsEnd
130	SyncLabel
131	SyncOptLabel
132
133	SyncMultiExpr
134	SyncRType
135	SyncConvRTTI
136)
137