Coverage Report

Created: 2025-07-04 06:49

/src/cpython/Python/legacy_tracing.c
Line
Count
Source (jump to first uncovered line)
1
/* Support for legacy tracing on top of PEP 669 instrumentation
2
 * Provides callables to forward PEP 669 events to legacy events.
3
 */
4
5
#include "Python.h"
6
#include "pycore_audit.h"         // _PySys_Audit()
7
#include "pycore_ceval.h"         // export _PyEval_SetProfile()
8
#include "pycore_frame.h"         // PyFrameObject members
9
#include "pycore_interpframe.h"   // _PyFrame_GetCode()
10
11
#include "opcode.h"
12
#include <stddef.h>
13
14
15
typedef struct _PyLegacyEventHandler {
16
    PyObject_HEAD
17
    vectorcallfunc vectorcall;
18
    int event;
19
} _PyLegacyEventHandler;
20
21
0
#define _PyLegacyEventHandler_CAST(op)  ((_PyLegacyEventHandler *)(op))
22
23
#ifdef Py_GIL_DISABLED
24
#define LOCK_SETUP()    PyMutex_Lock(&_PyRuntime.ceval.sys_trace_profile_mutex);
25
#define UNLOCK_SETUP()  PyMutex_Unlock(&_PyRuntime.ceval.sys_trace_profile_mutex);
26
#else
27
#define LOCK_SETUP()
28
#define UNLOCK_SETUP()
29
#endif
30
/* The Py_tracefunc function expects the following arguments:
31
 *   obj: the trace object (PyObject *)
32
 *   frame: the current frame (PyFrameObject *)
33
 *   kind: the kind of event, see PyTrace_XXX #defines (int)
34
 *   arg: The arg (a PyObject *)
35
 */
36
37
static PyObject *
38
call_profile_func(_PyLegacyEventHandler *self, PyObject *arg)
39
0
{
40
0
    PyThreadState *tstate = _PyThreadState_GET();
41
0
    if (tstate->c_profilefunc == NULL) {
42
0
        Py_RETURN_NONE;
43
0
    }
44
0
    PyFrameObject *frame = PyEval_GetFrame();
45
0
    if (frame == NULL) {
46
0
        PyErr_SetString(PyExc_SystemError,
47
0
                        "Missing frame when calling profile function.");
48
0
        return NULL;
49
0
    }
50
0
    Py_INCREF(frame);
51
0
    int err = tstate->c_profilefunc(tstate->c_profileobj, frame, self->event, arg);
52
0
    Py_DECREF(frame);
53
0
    if (err) {
54
0
        return NULL;
55
0
    }
56
0
    Py_RETURN_NONE;
57
0
}
58
59
static PyObject *
60
sys_profile_start(
61
    PyObject *callable, PyObject *const *args,
62
    size_t nargsf, PyObject *kwnames
63
0
) {
64
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
65
0
    assert(kwnames == NULL);
66
0
    assert(PyVectorcall_NARGS(nargsf) == 2);
67
0
    return call_profile_func(self, Py_None);
68
0
}
69
70
static PyObject *
71
sys_profile_throw(
72
    PyObject *callable, PyObject *const *args,
73
    size_t nargsf, PyObject *kwnames
74
0
) {
75
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
76
0
    assert(kwnames == NULL);
77
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
78
0
    return call_profile_func(self, Py_None);
79
0
}
80
81
static PyObject *
82
sys_profile_return(
83
    PyObject *callable, PyObject *const *args,
84
    size_t nargsf, PyObject *kwnames
85
0
) {
86
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
87
0
    assert(kwnames == NULL);
88
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
89
0
    return call_profile_func(self, args[2]);
90
0
}
91
92
static PyObject *
93
sys_profile_unwind(
94
    PyObject *callable, PyObject *const *args,
95
    size_t nargsf, PyObject *kwnames
96
0
) {
97
0
     _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
98
0
    assert(kwnames == NULL);
99
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
100
0
   return call_profile_func(self, NULL);
101
0
}
102
103
static PyObject *
104
sys_profile_call_or_return(
105
    PyObject *op, PyObject *const *args,
106
    size_t nargsf, PyObject *kwnames
107
0
) {
108
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(op);
109
0
    assert(kwnames == NULL);
110
0
    assert(PyVectorcall_NARGS(nargsf) == 4);
111
0
    PyObject *callable = args[2];
112
0
    if (PyCFunction_Check(callable)) {
113
0
        return call_profile_func(self, callable);
114
0
    }
115
0
    if (Py_TYPE(callable) == &PyMethodDescr_Type) {
116
0
        PyObject *self_arg = args[3];
117
        /* For backwards compatibility need to
118
         * convert to builtin method */
119
120
        /* If no arg, skip */
121
0
        if (self_arg == &_PyInstrumentation_MISSING) {
122
0
            Py_RETURN_NONE;
123
0
        }
124
0
        PyObject *meth = Py_TYPE(callable)->tp_descr_get(
125
0
            callable, self_arg, (PyObject*)Py_TYPE(self_arg));
126
0
        if (meth == NULL) {
127
0
            return NULL;
128
0
        }
129
0
        PyObject *res =  call_profile_func(self, meth);
130
0
        Py_DECREF(meth);
131
0
        return res;
132
0
    }
133
0
    Py_RETURN_NONE;
134
0
}
135
136
int
137
_PyEval_SetOpcodeTrace(
138
    PyFrameObject *frame,
139
    bool enable
140
0
) {
141
0
    assert(frame != NULL);
142
143
0
    PyCodeObject *code = _PyFrame_GetCode(frame->f_frame);
144
0
    _PyMonitoringEventSet events = 0;
145
146
0
    if (_PyMonitoring_GetLocalEvents(code, PY_MONITORING_SYS_TRACE_ID, &events) < 0) {
147
0
        return -1;
148
0
    }
149
150
0
    if (enable) {
151
0
        if (events & (1 << PY_MONITORING_EVENT_INSTRUCTION)) {
152
0
            return 0;
153
0
        }
154
0
        events |= (1 << PY_MONITORING_EVENT_INSTRUCTION);
155
0
    } else {
156
0
        if (!(events & (1 << PY_MONITORING_EVENT_INSTRUCTION))) {
157
0
            return 0;
158
0
        }
159
0
        events &= (~(1 << PY_MONITORING_EVENT_INSTRUCTION));
160
0
    }
161
0
    return _PyMonitoring_SetLocalEvents(code, PY_MONITORING_SYS_TRACE_ID, events);
162
0
}
163
164
static PyObject *
165
call_trace_func(_PyLegacyEventHandler *self, PyObject *arg)
166
0
{
167
0
    PyThreadState *tstate = _PyThreadState_GET();
168
0
    if (tstate->c_tracefunc == NULL) {
169
0
        Py_RETURN_NONE;
170
0
    }
171
0
    PyFrameObject *frame = PyEval_GetFrame();
172
0
    if (frame == NULL) {
173
0
        PyErr_SetString(PyExc_SystemError,
174
0
                        "Missing frame when calling trace function.");
175
0
        return NULL;
176
0
    }
177
0
    if (frame->f_trace_opcodes) {
178
0
        if (_PyEval_SetOpcodeTrace(frame, true) != 0) {
179
0
            return NULL;
180
0
        }
181
0
    }
182
183
0
    Py_INCREF(frame);
184
0
    int err = tstate->c_tracefunc(tstate->c_traceobj, frame, self->event, arg);
185
0
    frame->f_lineno = 0;
186
0
    Py_DECREF(frame);
187
0
    if (err) {
188
0
        return NULL;
189
0
    }
190
0
    Py_RETURN_NONE;
191
0
}
192
193
static PyObject *
194
sys_trace_exception_func(
195
    PyObject *callable, PyObject *const *args,
196
    size_t nargsf, PyObject *kwnames
197
0
) {
198
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
199
0
    assert(kwnames == NULL);
200
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
201
0
    PyObject *exc = args[2];
202
0
    assert(PyExceptionInstance_Check(exc));
203
0
    PyObject *type = (PyObject *)Py_TYPE(exc);
204
0
    PyObject *tb = PyException_GetTraceback(exc);
205
0
    if (tb == NULL) {
206
0
        tb = Py_NewRef(Py_None);
207
0
    }
208
0
    PyObject *tuple = PyTuple_Pack(3, type, exc, tb);
209
0
    Py_DECREF(tb);
210
0
    if (tuple == NULL) {
211
0
        return NULL;
212
0
    }
213
0
    PyObject *res = call_trace_func(self, tuple);
214
0
    Py_DECREF(tuple);
215
0
    return res;
216
0
}
217
218
static PyObject *
219
sys_trace_start(
220
    PyObject *callable, PyObject *const *args,
221
    size_t nargsf, PyObject *kwnames
222
0
) {
223
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
224
0
    assert(kwnames == NULL);
225
0
    assert(PyVectorcall_NARGS(nargsf) == 2);
226
0
    return call_trace_func(self, Py_None);
227
0
}
228
229
static PyObject *
230
sys_trace_throw(
231
    PyObject *callable, PyObject *const *args,
232
    size_t nargsf, PyObject *kwnames
233
0
) {
234
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
235
0
    assert(kwnames == NULL);
236
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
237
0
    return call_trace_func(self, Py_None);
238
0
}
239
240
static PyObject *
241
sys_trace_unwind(
242
    PyObject *callable, PyObject *const *args,
243
    size_t nargsf, PyObject *kwnames
244
0
) {
245
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
246
0
    assert(kwnames == NULL);
247
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
248
0
    return call_trace_func(self, NULL);
249
0
}
250
251
static PyObject *
252
sys_trace_return(
253
    PyObject *callable, PyObject *const *args,
254
    size_t nargsf, PyObject *kwnames
255
0
) {
256
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
257
0
    assert(!PyErr_Occurred());
258
0
    assert(kwnames == NULL);
259
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
260
0
    assert(PyCode_Check(args[0]));
261
0
    PyObject *val = args[2];
262
0
    PyObject *res = call_trace_func(self, val);
263
0
    return res;
264
0
}
265
266
static PyObject *
267
sys_trace_yield(
268
    PyObject *callable, PyObject *const *args,
269
    size_t nargsf, PyObject *kwnames
270
0
) {
271
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
272
0
    assert(kwnames == NULL);
273
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
274
0
    return call_trace_func(self, args[2]);
275
0
}
276
277
static PyObject *
278
sys_trace_instruction_func(
279
    PyObject *callable, PyObject *const *args,
280
    size_t nargsf, PyObject *kwnames
281
0
) {
282
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
283
0
    assert(kwnames == NULL);
284
0
    assert(PyVectorcall_NARGS(nargsf) == 2);
285
0
    PyFrameObject *frame = PyEval_GetFrame();
286
0
    if (frame == NULL) {
287
0
        PyErr_SetString(PyExc_SystemError,
288
0
                        "Missing frame when calling trace function.");
289
0
        return NULL;
290
0
    }
291
0
    PyThreadState *tstate = _PyThreadState_GET();
292
0
    if (!tstate->c_tracefunc || !frame->f_trace_opcodes) {
293
0
        if (_PyEval_SetOpcodeTrace(frame, false) != 0) {
294
0
            return NULL;
295
0
        }
296
0
        Py_RETURN_NONE;
297
0
    }
298
0
    Py_INCREF(frame);
299
0
    int err = tstate->c_tracefunc(tstate->c_traceobj, frame, self->event, Py_None);
300
0
    frame->f_lineno = 0;
301
0
    Py_DECREF(frame);
302
0
    if (err) {
303
0
        return NULL;
304
0
    }
305
0
    Py_RETURN_NONE;
306
0
}
307
308
static PyObject *
309
trace_line(
310
    PyThreadState *tstate, _PyLegacyEventHandler *self,
311
    PyFrameObject *frame, int line
312
0
) {
313
0
    if (!frame->f_trace_lines) {
314
0
        Py_RETURN_NONE;
315
0
    }
316
0
    if (line < 0) {
317
0
        Py_RETURN_NONE;
318
0
    }
319
0
    Py_INCREF(frame);
320
0
    frame->f_lineno = line;
321
0
    int err = tstate->c_tracefunc(tstate->c_traceobj, frame, self->event, Py_None);
322
0
    frame->f_lineno = 0;
323
0
    Py_DECREF(frame);
324
0
    if (err) {
325
0
        return NULL;
326
0
    }
327
0
    Py_RETURN_NONE;
328
0
}
329
330
static PyObject *
331
sys_trace_line_func(
332
    PyObject *callable, PyObject *const *args,
333
    size_t nargsf, PyObject *kwnames
334
0
) {
335
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
336
0
    assert(kwnames == NULL);
337
0
    PyThreadState *tstate = _PyThreadState_GET();
338
0
    if (tstate->c_tracefunc == NULL) {
339
0
        Py_RETURN_NONE;
340
0
    }
341
0
    assert(PyVectorcall_NARGS(nargsf) == 2);
342
0
    int line = PyLong_AsInt(args[1]);
343
0
    assert(line >= 0);
344
0
    PyFrameObject *frame = PyEval_GetFrame();
345
0
    if (frame == NULL) {
346
0
        PyErr_SetString(PyExc_SystemError,
347
0
                        "Missing frame when calling trace function.");
348
0
        return NULL;
349
0
    }
350
0
    assert(args[0] == (PyObject *)_PyFrame_GetCode(frame->f_frame));
351
0
    return trace_line(tstate, self, frame, line);
352
0
}
353
354
/* sys.settrace generates line events for all backward
355
 * edges, even if on the same line.
356
 * Handle that case here */
357
static PyObject *
358
sys_trace_jump_func(
359
    PyObject *callable, PyObject *const *args,
360
    size_t nargsf, PyObject *kwnames
361
0
) {
362
0
    _PyLegacyEventHandler *self = _PyLegacyEventHandler_CAST(callable);
363
0
    assert(kwnames == NULL);
364
0
    PyThreadState *tstate = _PyThreadState_GET();
365
0
    if (tstate->c_tracefunc == NULL) {
366
0
        Py_RETURN_NONE;
367
0
    }
368
0
    assert(PyVectorcall_NARGS(nargsf) == 3);
369
0
    int from = PyLong_AsInt(args[1])/sizeof(_Py_CODEUNIT);
370
0
    assert(from >= 0);
371
0
    int to = PyLong_AsInt(args[2])/sizeof(_Py_CODEUNIT);
372
0
    assert(to >= 0);
373
0
    if (to > from) {
374
        /* Forward jump */
375
0
        return &_PyInstrumentation_DISABLE;
376
0
    }
377
0
    PyCodeObject *code = (PyCodeObject *)args[0];
378
0
    assert(PyCode_Check(code));
379
    /* We can call _Py_Instrumentation_GetLine because we always set
380
    * line events for tracing */
381
0
    int to_line = _Py_Instrumentation_GetLine(code, to);
382
0
    int from_line = _Py_Instrumentation_GetLine(code, from);
383
0
    if (to_line != from_line) {
384
        /* Will be handled by target INSTRUMENTED_LINE */
385
0
        return &_PyInstrumentation_DISABLE;
386
0
    }
387
0
    PyFrameObject *frame = PyEval_GetFrame();
388
0
    if (frame == NULL) {
389
0
        PyErr_SetString(PyExc_SystemError,
390
0
                        "Missing frame when calling trace function.");
391
0
        return NULL;
392
0
    }
393
0
    if (!frame->f_trace_lines) {
394
0
        Py_RETURN_NONE;
395
0
    }
396
0
    return trace_line(tstate, self, frame, to_line);
397
0
}
398
399
PyTypeObject _PyLegacyEventHandler_Type = {
400
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
401
    "sys.legacy_event_handler",
402
    sizeof(_PyLegacyEventHandler),
403
    .tp_vectorcall_offset = offsetof(_PyLegacyEventHandler, vectorcall),
404
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
405
        Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_DISALLOW_INSTANTIATION,
406
    .tp_call = PyVectorcall_Call,
407
};
408
409
static int
410
set_callbacks(int tool, vectorcallfunc vectorcall, int legacy_event, int event1, int event2)
411
0
{
412
0
    _PyLegacyEventHandler *callback =
413
0
        PyObject_NEW(_PyLegacyEventHandler, &_PyLegacyEventHandler_Type);
414
0
    if (callback == NULL) {
415
0
        return -1;
416
0
    }
417
0
    callback->vectorcall = vectorcall;
418
0
    callback->event = legacy_event;
419
0
    Py_XDECREF(_PyMonitoring_RegisterCallback(tool, event1, (PyObject *)callback));
420
0
    if (event2 >= 0) {
421
0
        Py_XDECREF(_PyMonitoring_RegisterCallback(tool, event2, (PyObject *)callback));
422
0
    }
423
0
    Py_DECREF(callback);
424
0
    return 0;
425
0
}
426
427
#ifndef NDEBUG
428
/* Ensure that tstate is valid: sanity check for PyEval_AcquireThread() and
429
   PyEval_RestoreThread(). Detect if tstate memory was freed. It can happen
430
   when a thread continues to run after Python finalization, especially
431
   daemon threads. */
432
static int
433
is_tstate_valid(PyThreadState *tstate)
434
{
435
    assert(!_PyMem_IsPtrFreed(tstate));
436
    assert(!_PyMem_IsPtrFreed(tstate->interp));
437
    return 1;
438
}
439
#endif
440
441
static Py_ssize_t
442
setup_profile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg, PyObject **old_profileobj)
443
0
{
444
0
    *old_profileobj = NULL;
445
    /* Setup PEP 669 monitoring callbacks and events. */
446
0
    if (!tstate->interp->sys_profile_initialized) {
447
0
        tstate->interp->sys_profile_initialized = true;
448
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
449
0
                          sys_profile_start, PyTrace_CALL,
450
0
                          PY_MONITORING_EVENT_PY_START,
451
0
                          PY_MONITORING_EVENT_PY_RESUME)) {
452
0
            return -1;
453
0
        }
454
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
455
0
                          sys_profile_throw, PyTrace_CALL,
456
0
                          PY_MONITORING_EVENT_PY_THROW, -1)) {
457
0
            return -1;
458
0
        }
459
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
460
0
                          sys_profile_return, PyTrace_RETURN,
461
0
                          PY_MONITORING_EVENT_PY_RETURN,
462
0
                          PY_MONITORING_EVENT_PY_YIELD)) {
463
0
            return -1;
464
0
        }
465
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
466
0
                          sys_profile_unwind, PyTrace_RETURN,
467
0
                          PY_MONITORING_EVENT_PY_UNWIND, -1)) {
468
0
            return -1;
469
0
        }
470
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
471
0
                          sys_profile_call_or_return, PyTrace_C_CALL,
472
0
                          PY_MONITORING_EVENT_CALL, -1)) {
473
0
            return -1;
474
0
        }
475
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
476
0
                          sys_profile_call_or_return, PyTrace_C_RETURN,
477
0
                          PY_MONITORING_EVENT_C_RETURN, -1)) {
478
0
            return -1;
479
0
        }
480
0
        if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
481
0
                          sys_profile_call_or_return, PyTrace_C_EXCEPTION,
482
0
                          PY_MONITORING_EVENT_C_RAISE, -1)) {
483
0
            return -1;
484
0
        }
485
0
    }
486
487
0
    int delta = (func != NULL) - (tstate->c_profilefunc != NULL);
488
0
    tstate->c_profilefunc = func;
489
0
    *old_profileobj = tstate->c_profileobj;
490
0
    tstate->c_profileobj = Py_XNewRef(arg);
491
0
    tstate->interp->sys_profiling_threads += delta;
492
0
    assert(tstate->interp->sys_profiling_threads >= 0);
493
0
    return tstate->interp->sys_profiling_threads;
494
0
}
495
496
int
497
_PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
498
0
{
499
0
    assert(is_tstate_valid(tstate));
500
    /* The caller must hold a thread state */
501
0
    _Py_AssertHoldsTstate();
502
503
    /* Call _PySys_Audit() in the context of the current thread state,
504
       even if tstate is not the current thread state. */
505
0
    PyThreadState *current_tstate = _PyThreadState_GET();
506
0
    if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
507
0
        return -1;
508
0
    }
509
510
    // needs to be decref'd outside of the lock
511
0
    PyObject *old_profileobj;
512
0
    LOCK_SETUP();
513
0
    Py_ssize_t profiling_threads = setup_profile(tstate, func, arg, &old_profileobj);
514
0
    UNLOCK_SETUP();
515
0
    Py_XDECREF(old_profileobj);
516
517
0
    uint32_t events = 0;
518
0
    if (profiling_threads) {
519
0
        events =
520
0
            (1 << PY_MONITORING_EVENT_PY_START) | (1 << PY_MONITORING_EVENT_PY_RESUME) |
521
0
            (1 << PY_MONITORING_EVENT_PY_RETURN) | (1 << PY_MONITORING_EVENT_PY_YIELD) |
522
0
            (1 << PY_MONITORING_EVENT_CALL) | (1 << PY_MONITORING_EVENT_PY_UNWIND) |
523
0
            (1 << PY_MONITORING_EVENT_PY_THROW);
524
0
    }
525
0
    return _PyMonitoring_SetEvents(PY_MONITORING_SYS_PROFILE_ID, events);
526
0
}
527
528
static Py_ssize_t
529
setup_tracing(PyThreadState *tstate, Py_tracefunc func, PyObject *arg, PyObject **old_traceobj)
530
0
{
531
0
    *old_traceobj = NULL;
532
    /* Setup PEP 669 monitoring callbacks and events. */
533
0
    if (!tstate->interp->sys_trace_initialized) {
534
0
        tstate->interp->sys_trace_initialized = true;
535
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
536
0
                          sys_trace_start, PyTrace_CALL,
537
0
                          PY_MONITORING_EVENT_PY_START,
538
0
                          PY_MONITORING_EVENT_PY_RESUME)) {
539
0
            return -1;
540
0
        }
541
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
542
0
                          sys_trace_throw, PyTrace_CALL,
543
0
                          PY_MONITORING_EVENT_PY_THROW, -1)) {
544
0
            return -1;
545
0
        }
546
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
547
0
                          sys_trace_return, PyTrace_RETURN,
548
0
                          PY_MONITORING_EVENT_PY_RETURN, -1)) {
549
0
            return -1;
550
0
        }
551
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
552
0
                          sys_trace_yield, PyTrace_RETURN,
553
0
                          PY_MONITORING_EVENT_PY_YIELD, -1)) {
554
0
            return -1;
555
0
        }
556
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
557
0
                          sys_trace_exception_func, PyTrace_EXCEPTION,
558
0
                          PY_MONITORING_EVENT_RAISE,
559
0
                          PY_MONITORING_EVENT_STOP_ITERATION)) {
560
0
            return -1;
561
0
        }
562
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
563
0
                          sys_trace_line_func, PyTrace_LINE,
564
0
                          PY_MONITORING_EVENT_LINE, -1)) {
565
0
            return -1;
566
0
        }
567
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
568
0
                          sys_trace_unwind, PyTrace_RETURN,
569
0
                          PY_MONITORING_EVENT_PY_UNWIND, -1)) {
570
0
            return -1;
571
0
        }
572
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
573
0
                          sys_trace_jump_func, PyTrace_LINE,
574
0
                          PY_MONITORING_EVENT_JUMP, -1)) {
575
0
            return -1;
576
0
        }
577
0
        if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
578
0
                          sys_trace_instruction_func, PyTrace_OPCODE,
579
0
                          PY_MONITORING_EVENT_INSTRUCTION, -1)) {
580
0
            return -1;
581
0
        }
582
0
    }
583
584
0
    int delta = (func != NULL) - (tstate->c_tracefunc != NULL);
585
0
    tstate->c_tracefunc = func;
586
0
    *old_traceobj = tstate->c_traceobj;
587
0
    tstate->c_traceobj = Py_XNewRef(arg);
588
0
    tstate->interp->sys_tracing_threads += delta;
589
0
    assert(tstate->interp->sys_tracing_threads >= 0);
590
0
    return tstate->interp->sys_tracing_threads;
591
0
}
592
593
int
594
_PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
595
0
{
596
0
    assert(is_tstate_valid(tstate));
597
    /* The caller must hold a thread state */
598
0
    _Py_AssertHoldsTstate();
599
600
    /* Call _PySys_Audit() in the context of the current thread state,
601
       even if tstate is not the current thread state. */
602
0
    PyThreadState *current_tstate = _PyThreadState_GET();
603
0
    if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
604
0
        return -1;
605
0
    }
606
    // needs to be decref'd outside of the lock
607
0
    PyObject *old_traceobj;
608
0
    LOCK_SETUP();
609
0
    assert(tstate->interp->sys_tracing_threads >= 0);
610
0
    Py_ssize_t tracing_threads = setup_tracing(tstate, func, arg, &old_traceobj);
611
0
    UNLOCK_SETUP();
612
0
    Py_XDECREF(old_traceobj);
613
0
    if (tracing_threads < 0) {
614
0
        return -1;
615
0
    }
616
617
0
    uint32_t events = 0;
618
0
    if (tracing_threads) {
619
0
        events =
620
0
            (1 << PY_MONITORING_EVENT_PY_START) | (1 << PY_MONITORING_EVENT_PY_RESUME) |
621
0
            (1 << PY_MONITORING_EVENT_PY_RETURN) | (1 << PY_MONITORING_EVENT_PY_YIELD) |
622
0
            (1 << PY_MONITORING_EVENT_RAISE) | (1 << PY_MONITORING_EVENT_LINE) |
623
0
            (1 << PY_MONITORING_EVENT_JUMP) |
624
0
            (1 << PY_MONITORING_EVENT_PY_UNWIND) | (1 << PY_MONITORING_EVENT_PY_THROW) |
625
0
            (1 << PY_MONITORING_EVENT_STOP_ITERATION);
626
627
0
        PyFrameObject* frame = PyEval_GetFrame();
628
0
        if (frame && frame->f_trace_opcodes) {
629
0
            int ret = _PyEval_SetOpcodeTrace(frame, true);
630
0
            if (ret != 0) {
631
0
                return ret;
632
0
            }
633
0
        }
634
0
    }
635
636
0
    return _PyMonitoring_SetEvents(PY_MONITORING_SYS_TRACE_ID, events);
637
0
}