Debian Codegraph @

experimental/listener.go

raw symbols SCIP
1 package experimental
2
3 import (
4 "context"
5
6 "github.com/tetratelabs/wazero/api"
7 "github.com/tetratelabs/wazero/internal/expctxkeys"
8 )
9
10 // StackIterator allows iterating on each function of the call stack, starting
11 // from the top. At least one call to Next() is required to start the iteration.
12 //
13 // Note: The iterator provides a view of the call stack at the time of
14 // iteration. As a result, parameter values may be different than the ones their
15 // function was called with.
16 type StackIterator interface {
17 // Next moves the iterator to the next function in the stack. Returns
18 // false if it reached the bottom of the stack.
19 Next() bool
20 // Function describes the function called by the current frame.
21 Function() InternalFunction
22 // ProgramCounter returns the program counter associated with the
23 // function call.
24 ProgramCounter() ProgramCounter
25 }
26
27 // WithFunctionListenerFactory registers a FunctionListenerFactory
28 // with the context.
29 func WithFunctionListenerFactory(ctx context.Context, factory FunctionListenerFactory) context.Context {
30 return context.WithValue(ctx, expctxkeys.FunctionListenerFactoryKey{}, factory)
31 }
32
33 // FunctionListenerFactory returns FunctionListeners to be notified when a
34 // function is called.
35 type FunctionListenerFactory interface {
36 // NewFunctionListener returns a FunctionListener for a defined function.
37 // If nil is returned, no listener will be notified.
38 NewFunctionListener(api.FunctionDefinition) FunctionListener
39 // ^^ A single instance can be returned to avoid instantiating a listener
40 // per function, especially as they may be thousands of functions. Shared
41 // listeners use their FunctionDefinition parameter to clarify.
42 }
43
44 // FunctionListener can be registered for any function via
45 // FunctionListenerFactory to be notified when the function is called.
46 type FunctionListener interface {
47 // Before is invoked before a function is called.
48 //
49 // There is always one corresponding call to After or Abort for each call to
50 // Before. This guarantee allows the listener to maintain an internal stack
51 // to perform correlations between the entry and exit of functions.
52 //
53 // # Params
54 //
55 // - ctx: the context of the caller function which must be the same
56 // instance or parent of the result.
57 // - mod: the calling module.
58 // - def: the function definition.
59 // - params: api.ValueType encoded parameters.
60 // - stackIterator: iterator on the call stack. At least one entry is
61 // guaranteed (the called function), whose Args() will be equal to
62 // params. The iterator will be reused between calls to Before.
63 //
64 // Note: api.Memory is meant for inspection, not modification.
65 // mod can be cast to InternalModule to read non-exported globals.
66 Before(ctx context.Context, mod api.Module, def api.FunctionDefinition, params []uint64, stackIterator StackIterator)
67
68 // After is invoked after a function is called.
69 //
70 // # Params
71 //
72 // - ctx: the context of the caller function.
73 // - mod: the calling module.
74 // - def: the function definition.
75 // - results: api.ValueType encoded results.
76 //
77 // # Notes
78 //
79 // - api.Memory is meant for inspection, not modification.
80 // - This is not called when a host function panics, or a guest function traps.
81 // See Abort for more details.
82 After(ctx context.Context, mod api.Module, def api.FunctionDefinition, results []uint64)
83
84 // Abort is invoked when a function does not return due to a trap or panic.
85 //
86 // # Params
87 //
88 // - ctx: the context of the caller function.
89 // - mod: the calling module.
90 // - def: the function definition.
91 // - err: the error value representing the reason why the function aborted.
92 //
93 // # Notes
94 //
95 // - api.Memory is meant for inspection, not modification.
96 Abort(ctx context.Context, mod api.Module, def api.FunctionDefinition, err error)
97 }
98
99 // FunctionListenerFunc is a function type implementing the FunctionListener
100 // interface, making it possible to use regular functions and methods as
101 // listeners of function invocation.
102 //
103 // The FunctionListener interface declares two methods (Before and After),
104 // but this type invokes its value only when Before is called. It is best
105 // suites for cases where the host does not need to perform correlation
106 // between the start and end of the function call.
107 type FunctionListenerFunc func(context.Context, api.Module, api.FunctionDefinition, []uint64, StackIterator)
108
109 // Before satisfies the FunctionListener interface, calls f.
110 func (f FunctionListenerFunc) Before(ctx context.Context, mod api.Module, def api.FunctionDefinition, params []uint64, stackIterator StackIterator) {
111 f(ctx, mod, def, params, stackIterator)
112 }
113
114 // After is declared to satisfy the FunctionListener interface, but it does
115 // nothing.
116 func (f FunctionListenerFunc) After(context.Context, api.Module, api.FunctionDefinition, []uint64) {
117 }
118
119 // Abort is declared to satisfy the FunctionListener interface, but it does
120 // nothing.
121 func (f FunctionListenerFunc) Abort(context.Context, api.Module, api.FunctionDefinition, error) {
122 }
123
124 // FunctionListenerFactoryFunc is a function type implementing the
125 // FunctionListenerFactory interface, making it possible to use regular
126 // functions and methods as factory of function listeners.
127 type FunctionListenerFactoryFunc func(api.FunctionDefinition) FunctionListener
128
129 // NewFunctionListener satisfies the FunctionListenerFactory interface, calls f.
130 func (f FunctionListenerFactoryFunc) NewFunctionListener(def api.FunctionDefinition) FunctionListener {
131 return f(def)
132 }
133
134 // MultiFunctionListenerFactory constructs a FunctionListenerFactory which
135 // combines the listeners created by each of the factories passed as arguments.
136 //
137 // This function is useful when multiple listeners need to be hooked to a module
138 // because the propagation mechanism based on installing a listener factory in
139 // the context.Context used when instantiating modules allows for a single
140 // listener to be installed.
141 //
142 // The stack iterator passed to the Before method is reset so that each listener
143 // can iterate the call stack independently without impacting the ability of
144 // other listeners to do so.
145 func MultiFunctionListenerFactory(factories ...FunctionListenerFactory) FunctionListenerFactory {
146 multi := make(multiFunctionListenerFactory, len(factories))
147 copy(multi, factories)
148 return multi
149 }
150
151 type multiFunctionListenerFactory []FunctionListenerFactory
152
153 func (multi multiFunctionListenerFactory) NewFunctionListener(def api.FunctionDefinition) FunctionListener {
154 var lstns []FunctionListener
155 for _, factory := range multi {
156 if lstn := factory.NewFunctionListener(def); lstn != nil {
157 lstns = append(lstns, lstn)
158 }
159 }
160 switch len(lstns) {
161 case 0:
162 return nil
163 case 1:
164 return lstns[0]
165 default:
166 return &multiFunctionListener{lstns: lstns}
167 }
168 }
169
170 type multiFunctionListener struct {
171 lstns []FunctionListener
172 stack stackIterator
173 }
174
175 func (multi *multiFunctionListener) Before(ctx context.Context, mod api.Module, def api.FunctionDefinition, params []uint64, si StackIterator) {
176 multi.stack.base = si
177 for _, lstn := range multi.lstns {
178 multi.stack.index = -1
179 lstn.Before(ctx, mod, def, params, &multi.stack)
180 }
181 }
182
183 func (multi *multiFunctionListener) After(ctx context.Context, mod api.Module, def api.FunctionDefinition, results []uint64) {
184 for _, lstn := range multi.lstns {
185 lstn.After(ctx, mod, def, results)
186 }
187 }
188
189 func (multi *multiFunctionListener) Abort(ctx context.Context, mod api.Module, def api.FunctionDefinition, err error) {
190 for _, lstn := range multi.lstns {
191 lstn.Abort(ctx, mod, def, err)
192 }
193 }
194
195 type stackIterator struct {
196 base StackIterator
197 index int
198 pcs []uint64
199 fns []InternalFunction
200 }
201
202 func (si *stackIterator) Next() bool {
203 if si.base != nil {
204 si.pcs = si.pcs[:0]
205 si.fns = si.fns[:0]
206
207 for si.base.Next() {
208 si.pcs = append(si.pcs, uint64(si.base.ProgramCounter()))
209 si.fns = append(si.fns, si.base.Function())
210 }
211
212 si.base = nil
213 }
214 si.index++
215 return si.index < len(si.pcs)
216 }
217
218 func (si *stackIterator) ProgramCounter() ProgramCounter {
219 return ProgramCounter(si.pcs[si.index])
220 }
221
222 func (si *stackIterator) Function() InternalFunction {
223 return si.fns[si.index]
224 }
225
226 // StackFrame represents a frame on the call stack.
227 type StackFrame struct {
228 Function api.Function
229 Params []uint64
230 Results []uint64
231 PC uint64
232 SourceOffset uint64
233 }
234
235 type internalFunction struct {
236 definition api.FunctionDefinition
237 sourceOffset uint64
238 }
239
240 func (f internalFunction) Definition() api.FunctionDefinition {
241 return f.definition
242 }
243
244 func (f internalFunction) SourceOffsetForPC(pc ProgramCounter) uint64 {
245 return f.sourceOffset
246 }
247
248 // stackFrameIterator is an implementation of the experimental.stackFrameIterator
249 // interface.
250 type stackFrameIterator struct {
251 index int
252 stack []StackFrame
253 fndef []api.FunctionDefinition
254 }
255
256 func (si *stackFrameIterator) Next() bool {
257 si.index++
258 return si.index < len(si.stack)
259 }
260
261 func (si *stackFrameIterator) Function() InternalFunction {
262 return internalFunction{
263 definition: si.fndef[si.index],
264 sourceOffset: si.stack[si.index].SourceOffset,
265 }
266 }
267
268 func (si *stackFrameIterator) ProgramCounter() ProgramCounter {
269 return ProgramCounter(si.stack[si.index].PC)
270 }
271
272 // NewStackIterator constructs a stack iterator from a list of stack frames.
273 // The top most frame is the last one.
274 func NewStackIterator(stack ...StackFrame) StackIterator {
275 si := &stackFrameIterator{
276 index: -1,
277 stack: make([]StackFrame, len(stack)),
278 fndef: make([]api.FunctionDefinition, len(stack)),
279 }
280 for i := range stack {
281 si.stack[i] = stack[len(stack)-(i+1)]
282 }
283 // The size of function definition is only one pointer which should allow
284 // the compiler to optimize the conversion to api.FunctionDefinition; but
285 // the presence of internal.WazeroOnlyType, despite being defined as an
286 // empty struct, forces a heap allocation that we amortize by caching the
287 // result.
288 for i, frame := range stack {
289 si.fndef[i] = frame.Function.Definition()
290 }
291 return si
292 }
293
294 // BenchmarkFunctionListener implements a benchmark for function listeners.
295 //
296 // The benchmark calls Before and After methods repeatedly using the provided
297 // module an stack frames to invoke the methods.
298 //
299 // The stack frame is a representation of the call stack that the Before method
300 // will be invoked with. The top of the stack is stored at index zero. The stack
301 // must contain at least one frame or the benchmark will fail.
302 func BenchmarkFunctionListener(n int, module api.Module, stack []StackFrame, listener FunctionListener) {
303 if len(stack) == 0 {
304 panic("cannot benchmark function listener with an empty stack")
305 }
306
307 ctx := context.Background()
308 def := stack[0].Function.Definition()
309 params := stack[0].Params
310 results := stack[0].Results
311 stackIterator := &stackIterator{base: NewStackIterator(stack...)}
312
313 for i := 0; i < n; i++ {
314 stackIterator.index = -1
315 listener.Before(ctx, module, def, params, stackIterator)
316 listener.After(ctx, module, def, results)
317 }
318 }
319
320 // TODO: the calls to Abort are not yet tested in internal/testing/enginetest,
321 // but they are validated indirectly in tests which exercise host logging,
322 // like Test_procExit in imports/wasi_snapshot_preview1. Eventually we should
323 // add dedicated tests to validate the behavior of the interpreter and compiler
324 // engines independently.