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