legacy_tracing.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /* Support for legacy tracing on top of PEP 669 instrumentation
  2. * Provides callables to forward PEP 669 events to legacy events.
  3. */
  4. #include <stddef.h>
  5. #include "Python.h"
  6. #include "opcode.h"
  7. #include "pycore_ceval.h"
  8. #include "pycore_object.h"
  9. #include "pycore_sysmodule.h"
  10. typedef struct _PyLegacyEventHandler {
  11. PyObject_HEAD
  12. vectorcallfunc vectorcall;
  13. int event;
  14. } _PyLegacyEventHandler;
  15. /* The Py_tracefunc function expects the following arguments:
  16. * obj: the trace object (PyObject *)
  17. * frame: the current frame (PyFrameObject *)
  18. * kind: the kind of event, see PyTrace_XXX #defines (int)
  19. * arg: The arg (a PyObject *)
  20. */
  21. static PyObject *
  22. call_profile_func(_PyLegacyEventHandler *self, PyObject *arg)
  23. {
  24. PyThreadState *tstate = _PyThreadState_GET();
  25. if (tstate->c_profilefunc == NULL) {
  26. Py_RETURN_NONE;
  27. }
  28. PyFrameObject *frame = PyEval_GetFrame();
  29. if (frame == NULL) {
  30. PyErr_SetString(PyExc_SystemError,
  31. "Missing frame when calling profile function.");
  32. return NULL;
  33. }
  34. Py_INCREF(frame);
  35. int err = tstate->c_profilefunc(tstate->c_profileobj, frame, self->event, arg);
  36. Py_DECREF(frame);
  37. if (err) {
  38. return NULL;
  39. }
  40. Py_RETURN_NONE;
  41. }
  42. static PyObject *
  43. sys_profile_func2(
  44. _PyLegacyEventHandler *self, PyObject *const *args,
  45. size_t nargsf, PyObject *kwnames
  46. ) {
  47. assert(kwnames == NULL);
  48. assert(PyVectorcall_NARGS(nargsf) == 2);
  49. return call_profile_func(self, Py_None);
  50. }
  51. static PyObject *
  52. sys_profile_func3(
  53. _PyLegacyEventHandler *self, PyObject *const *args,
  54. size_t nargsf, PyObject *kwnames
  55. ) {
  56. assert(kwnames == NULL);
  57. assert(PyVectorcall_NARGS(nargsf) == 3);
  58. return call_profile_func(self, args[2]);
  59. }
  60. static PyObject *
  61. sys_profile_unwind(
  62. _PyLegacyEventHandler *self, PyObject *const *args,
  63. size_t nargsf, PyObject *kwnames
  64. ) {
  65. assert(kwnames == NULL);
  66. assert(PyVectorcall_NARGS(nargsf) == 3);
  67. return call_profile_func(self, Py_None);
  68. }
  69. static PyObject *
  70. sys_profile_call_or_return(
  71. _PyLegacyEventHandler *self, PyObject *const *args,
  72. size_t nargsf, PyObject *kwnames
  73. ) {
  74. assert(kwnames == NULL);
  75. assert(PyVectorcall_NARGS(nargsf) == 4);
  76. PyObject *callable = args[2];
  77. if (PyCFunction_Check(callable)) {
  78. return call_profile_func(self, callable);
  79. }
  80. if (Py_TYPE(callable) == &PyMethodDescr_Type) {
  81. PyObject *self_arg = args[3];
  82. /* For backwards compatibility need to
  83. * convert to builtin method */
  84. /* If no arg, skip */
  85. if (self_arg == &_PyInstrumentation_MISSING) {
  86. Py_RETURN_NONE;
  87. }
  88. PyObject *meth = Py_TYPE(callable)->tp_descr_get(
  89. callable, self_arg, (PyObject*)Py_TYPE(self_arg));
  90. if (meth == NULL) {
  91. return NULL;
  92. }
  93. PyObject *res = call_profile_func(self, meth);
  94. Py_DECREF(meth);
  95. return res;
  96. }
  97. Py_RETURN_NONE;
  98. }
  99. static PyObject *
  100. call_trace_func(_PyLegacyEventHandler *self, PyObject *arg)
  101. {
  102. PyThreadState *tstate = _PyThreadState_GET();
  103. if (tstate->c_tracefunc == NULL) {
  104. Py_RETURN_NONE;
  105. }
  106. PyFrameObject *frame = PyEval_GetFrame();
  107. if (frame == NULL) {
  108. PyErr_SetString(PyExc_SystemError,
  109. "Missing frame when calling trace function.");
  110. return NULL;
  111. }
  112. Py_INCREF(frame);
  113. int err = tstate->c_tracefunc(tstate->c_traceobj, frame, self->event, arg);
  114. Py_DECREF(frame);
  115. if (err) {
  116. return NULL;
  117. }
  118. Py_RETURN_NONE;
  119. }
  120. static PyObject *
  121. sys_trace_exception_func(
  122. _PyLegacyEventHandler *self, PyObject *const *args,
  123. size_t nargsf, PyObject *kwnames
  124. ) {
  125. assert(kwnames == NULL);
  126. assert(PyVectorcall_NARGS(nargsf) == 3);
  127. PyObject *exc = args[2];
  128. assert(PyExceptionInstance_Check(exc));
  129. PyObject *type = (PyObject *)Py_TYPE(exc);
  130. PyObject *tb = PyException_GetTraceback(exc);
  131. if (tb == NULL) {
  132. tb = Py_NewRef(Py_None);
  133. }
  134. PyObject *tuple = PyTuple_Pack(3, type, exc, tb);
  135. Py_DECREF(tb);
  136. if (tuple == NULL) {
  137. return NULL;
  138. }
  139. PyObject *res = call_trace_func(self, tuple);
  140. Py_DECREF(tuple);
  141. return res;
  142. }
  143. static PyObject *
  144. sys_trace_func2(
  145. _PyLegacyEventHandler *self, PyObject *const *args,
  146. size_t nargsf, PyObject *kwnames
  147. ) {
  148. assert(kwnames == NULL);
  149. assert(PyVectorcall_NARGS(nargsf) == 2);
  150. return call_trace_func(self, Py_None);
  151. }
  152. static PyObject *
  153. sys_trace_func3(
  154. _PyLegacyEventHandler *self, PyObject *const *args,
  155. size_t nargsf, PyObject *kwnames
  156. ) {
  157. assert(kwnames == NULL);
  158. assert(PyVectorcall_NARGS(nargsf) == 3);
  159. return call_trace_func(self, Py_None);
  160. }
  161. static PyObject *
  162. sys_trace_return(
  163. _PyLegacyEventHandler *self, PyObject *const *args,
  164. size_t nargsf, PyObject *kwnames
  165. ) {
  166. assert(!PyErr_Occurred());
  167. assert(kwnames == NULL);
  168. assert(PyVectorcall_NARGS(nargsf) == 3);
  169. assert(PyCode_Check(args[0]));
  170. PyObject *val = args[2];
  171. PyObject *res = call_trace_func(self, val);
  172. return res;
  173. }
  174. static PyObject *
  175. sys_trace_yield(
  176. _PyLegacyEventHandler *self, PyObject *const *args,
  177. size_t nargsf, PyObject *kwnames
  178. ) {
  179. assert(kwnames == NULL);
  180. assert(PyVectorcall_NARGS(nargsf) == 3);
  181. return call_trace_func(self, args[2]);
  182. }
  183. static PyObject *
  184. sys_trace_instruction_func(
  185. _PyLegacyEventHandler *self, PyObject *const *args,
  186. size_t nargsf, PyObject *kwnames
  187. ) {
  188. assert(kwnames == NULL);
  189. assert(PyVectorcall_NARGS(nargsf) == 2);
  190. PyFrameObject *frame = PyEval_GetFrame();
  191. if (frame == NULL) {
  192. PyErr_SetString(PyExc_SystemError,
  193. "Missing frame when calling trace function.");
  194. return NULL;
  195. }
  196. if (!frame->f_trace_opcodes) {
  197. Py_RETURN_NONE;
  198. }
  199. Py_INCREF(frame);
  200. PyThreadState *tstate = _PyThreadState_GET();
  201. int err = tstate->c_tracefunc(tstate->c_traceobj, frame, self->event, Py_None);
  202. frame->f_lineno = 0;
  203. Py_DECREF(frame);
  204. if (err) {
  205. return NULL;
  206. }
  207. Py_RETURN_NONE;
  208. }
  209. static PyObject *
  210. trace_line(
  211. PyThreadState *tstate, _PyLegacyEventHandler *self,
  212. PyFrameObject *frame, int line
  213. ) {
  214. if (!frame->f_trace_lines) {
  215. Py_RETURN_NONE;
  216. }
  217. if (line < 0) {
  218. Py_RETURN_NONE;
  219. }
  220. Py_INCREF(frame);
  221. frame->f_lineno = line;
  222. int err = tstate->c_tracefunc(tstate->c_traceobj, frame, self->event, Py_None);
  223. frame->f_lineno = 0;
  224. Py_DECREF(frame);
  225. if (err) {
  226. return NULL;
  227. }
  228. Py_RETURN_NONE;
  229. }
  230. static PyObject *
  231. sys_trace_line_func(
  232. _PyLegacyEventHandler *self, PyObject *const *args,
  233. size_t nargsf, PyObject *kwnames
  234. ) {
  235. assert(kwnames == NULL);
  236. PyThreadState *tstate = _PyThreadState_GET();
  237. if (tstate->c_tracefunc == NULL) {
  238. Py_RETURN_NONE;
  239. }
  240. assert(PyVectorcall_NARGS(nargsf) == 2);
  241. int line = _PyLong_AsInt(args[1]);
  242. assert(line >= 0);
  243. PyFrameObject *frame = PyEval_GetFrame();
  244. if (frame == NULL) {
  245. PyErr_SetString(PyExc_SystemError,
  246. "Missing frame when calling trace function.");
  247. return NULL;
  248. }
  249. assert(args[0] == (PyObject *)frame->f_frame->f_code);
  250. return trace_line(tstate, self, frame, line);
  251. }
  252. /* sys.settrace generates line events for all backward
  253. * edges, even if on the same line.
  254. * Handle that case here */
  255. static PyObject *
  256. sys_trace_jump_func(
  257. _PyLegacyEventHandler *self, PyObject *const *args,
  258. size_t nargsf, PyObject *kwnames
  259. ) {
  260. assert(kwnames == NULL);
  261. PyThreadState *tstate = _PyThreadState_GET();
  262. if (tstate->c_tracefunc == NULL) {
  263. Py_RETURN_NONE;
  264. }
  265. assert(PyVectorcall_NARGS(nargsf) == 3);
  266. int from = _PyLong_AsInt(args[1])/sizeof(_Py_CODEUNIT);
  267. assert(from >= 0);
  268. int to = _PyLong_AsInt(args[2])/sizeof(_Py_CODEUNIT);
  269. assert(to >= 0);
  270. if (to > from) {
  271. /* Forward jump */
  272. return &_PyInstrumentation_DISABLE;
  273. }
  274. PyCodeObject *code = (PyCodeObject *)args[0];
  275. assert(PyCode_Check(code));
  276. /* We can call _Py_Instrumentation_GetLine because we always set
  277. * line events for tracing */
  278. int to_line = _Py_Instrumentation_GetLine(code, to);
  279. int from_line = _Py_Instrumentation_GetLine(code, from);
  280. if (to_line != from_line) {
  281. /* Will be handled by target INSTRUMENTED_LINE */
  282. return &_PyInstrumentation_DISABLE;
  283. }
  284. PyFrameObject *frame = PyEval_GetFrame();
  285. if (frame == NULL) {
  286. PyErr_SetString(PyExc_SystemError,
  287. "Missing frame when calling trace function.");
  288. return NULL;
  289. }
  290. assert(code == frame->f_frame->f_code);
  291. if (!frame->f_trace_lines) {
  292. Py_RETURN_NONE;
  293. }
  294. return trace_line(tstate, self, frame, to_line);
  295. }
  296. PyTypeObject _PyLegacyEventHandler_Type = {
  297. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  298. "sys.legacy_event_handler",
  299. sizeof(_PyLegacyEventHandler),
  300. .tp_dealloc = (destructor)PyObject_Free,
  301. .tp_vectorcall_offset = offsetof(_PyLegacyEventHandler, vectorcall),
  302. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  303. Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_DISALLOW_INSTANTIATION,
  304. .tp_call = PyVectorcall_Call,
  305. };
  306. static int
  307. set_callbacks(int tool, vectorcallfunc vectorcall, int legacy_event, int event1, int event2)
  308. {
  309. _PyLegacyEventHandler *callback =
  310. PyObject_NEW(_PyLegacyEventHandler, &_PyLegacyEventHandler_Type);
  311. if (callback == NULL) {
  312. return -1;
  313. }
  314. callback->vectorcall = vectorcall;
  315. callback->event = legacy_event;
  316. Py_XDECREF(_PyMonitoring_RegisterCallback(tool, event1, (PyObject *)callback));
  317. if (event2 >= 0) {
  318. Py_XDECREF(_PyMonitoring_RegisterCallback(tool, event2, (PyObject *)callback));
  319. }
  320. Py_DECREF(callback);
  321. return 0;
  322. }
  323. #ifndef NDEBUG
  324. /* Ensure that tstate is valid: sanity check for PyEval_AcquireThread() and
  325. PyEval_RestoreThread(). Detect if tstate memory was freed. It can happen
  326. when a thread continues to run after Python finalization, especially
  327. daemon threads. */
  328. static int
  329. is_tstate_valid(PyThreadState *tstate)
  330. {
  331. assert(!_PyMem_IsPtrFreed(tstate));
  332. assert(!_PyMem_IsPtrFreed(tstate->interp));
  333. return 1;
  334. }
  335. #endif
  336. int
  337. _PyEval_SetProfile(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
  338. {
  339. assert(is_tstate_valid(tstate));
  340. /* The caller must hold the GIL */
  341. assert(PyGILState_Check());
  342. /* Call _PySys_Audit() in the context of the current thread state,
  343. even if tstate is not the current thread state. */
  344. PyThreadState *current_tstate = _PyThreadState_GET();
  345. if (_PySys_Audit(current_tstate, "sys.setprofile", NULL) < 0) {
  346. return -1;
  347. }
  348. /* Setup PEP 669 monitoring callbacks and events. */
  349. if (!tstate->interp->sys_profile_initialized) {
  350. tstate->interp->sys_profile_initialized = true;
  351. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  352. (vectorcallfunc)sys_profile_func2, PyTrace_CALL,
  353. PY_MONITORING_EVENT_PY_START, PY_MONITORING_EVENT_PY_RESUME)) {
  354. return -1;
  355. }
  356. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  357. (vectorcallfunc)sys_profile_func3, PyTrace_CALL,
  358. PY_MONITORING_EVENT_PY_THROW, -1)) {
  359. return -1;
  360. }
  361. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  362. (vectorcallfunc)sys_profile_func3, PyTrace_RETURN,
  363. PY_MONITORING_EVENT_PY_RETURN, PY_MONITORING_EVENT_PY_YIELD)) {
  364. return -1;
  365. }
  366. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  367. (vectorcallfunc)sys_profile_unwind, PyTrace_RETURN,
  368. PY_MONITORING_EVENT_PY_UNWIND, -1)) {
  369. return -1;
  370. }
  371. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  372. (vectorcallfunc)sys_profile_call_or_return, PyTrace_C_CALL,
  373. PY_MONITORING_EVENT_CALL, -1)) {
  374. return -1;
  375. }
  376. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  377. (vectorcallfunc)sys_profile_call_or_return, PyTrace_C_RETURN,
  378. PY_MONITORING_EVENT_C_RETURN, -1)) {
  379. return -1;
  380. }
  381. if (set_callbacks(PY_MONITORING_SYS_PROFILE_ID,
  382. (vectorcallfunc)sys_profile_call_or_return, PyTrace_C_EXCEPTION,
  383. PY_MONITORING_EVENT_C_RAISE, -1)) {
  384. return -1;
  385. }
  386. }
  387. int delta = (func != NULL) - (tstate->c_profilefunc != NULL);
  388. tstate->c_profilefunc = func;
  389. PyObject *old_profileobj = tstate->c_profileobj;
  390. tstate->c_profileobj = Py_XNewRef(arg);
  391. Py_XDECREF(old_profileobj);
  392. tstate->interp->sys_profiling_threads += delta;
  393. assert(tstate->interp->sys_profiling_threads >= 0);
  394. uint32_t events = 0;
  395. if (tstate->interp->sys_profiling_threads) {
  396. events =
  397. (1 << PY_MONITORING_EVENT_PY_START) | (1 << PY_MONITORING_EVENT_PY_RESUME) |
  398. (1 << PY_MONITORING_EVENT_PY_RETURN) | (1 << PY_MONITORING_EVENT_PY_YIELD) |
  399. (1 << PY_MONITORING_EVENT_CALL) | (1 << PY_MONITORING_EVENT_PY_UNWIND) |
  400. (1 << PY_MONITORING_EVENT_PY_THROW);
  401. }
  402. return _PyMonitoring_SetEvents(PY_MONITORING_SYS_PROFILE_ID, events);
  403. }
  404. int
  405. _PyEval_SetTrace(PyThreadState *tstate, Py_tracefunc func, PyObject *arg)
  406. {
  407. assert(is_tstate_valid(tstate));
  408. /* The caller must hold the GIL */
  409. assert(PyGILState_Check());
  410. /* Call _PySys_Audit() in the context of the current thread state,
  411. even if tstate is not the current thread state. */
  412. PyThreadState *current_tstate = _PyThreadState_GET();
  413. if (_PySys_Audit(current_tstate, "sys.settrace", NULL) < 0) {
  414. return -1;
  415. }
  416. assert(tstate->interp->sys_tracing_threads >= 0);
  417. /* Setup PEP 669 monitoring callbacks and events. */
  418. if (!tstate->interp->sys_trace_initialized) {
  419. tstate->interp->sys_trace_initialized = true;
  420. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  421. (vectorcallfunc)sys_trace_func2, PyTrace_CALL,
  422. PY_MONITORING_EVENT_PY_START, PY_MONITORING_EVENT_PY_RESUME)) {
  423. return -1;
  424. }
  425. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  426. (vectorcallfunc)sys_trace_func3, PyTrace_CALL,
  427. PY_MONITORING_EVENT_PY_THROW, -1)) {
  428. return -1;
  429. }
  430. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  431. (vectorcallfunc)sys_trace_return, PyTrace_RETURN,
  432. PY_MONITORING_EVENT_PY_RETURN, -1)) {
  433. return -1;
  434. }
  435. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  436. (vectorcallfunc)sys_trace_yield, PyTrace_RETURN,
  437. PY_MONITORING_EVENT_PY_YIELD, -1)) {
  438. return -1;
  439. }
  440. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  441. (vectorcallfunc)sys_trace_exception_func, PyTrace_EXCEPTION,
  442. PY_MONITORING_EVENT_RAISE, PY_MONITORING_EVENT_STOP_ITERATION)) {
  443. return -1;
  444. }
  445. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  446. (vectorcallfunc)sys_trace_line_func, PyTrace_LINE,
  447. PY_MONITORING_EVENT_LINE, -1)) {
  448. return -1;
  449. }
  450. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  451. (vectorcallfunc)sys_trace_func3, PyTrace_RETURN,
  452. PY_MONITORING_EVENT_PY_UNWIND, -1)) {
  453. return -1;
  454. }
  455. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  456. (vectorcallfunc)sys_trace_jump_func, PyTrace_LINE,
  457. PY_MONITORING_EVENT_JUMP, -1)) {
  458. return -1;
  459. }
  460. if (set_callbacks(PY_MONITORING_SYS_TRACE_ID,
  461. (vectorcallfunc)sys_trace_instruction_func, PyTrace_OPCODE,
  462. PY_MONITORING_EVENT_INSTRUCTION, -1)) {
  463. return -1;
  464. }
  465. }
  466. int delta = (func != NULL) - (tstate->c_tracefunc != NULL);
  467. tstate->c_tracefunc = func;
  468. PyObject *old_traceobj = tstate->c_traceobj;
  469. tstate->c_traceobj = Py_XNewRef(arg);
  470. Py_XDECREF(old_traceobj);
  471. tstate->interp->sys_tracing_threads += delta;
  472. assert(tstate->interp->sys_tracing_threads >= 0);
  473. uint32_t events = 0;
  474. if (tstate->interp->sys_tracing_threads) {
  475. events =
  476. (1 << PY_MONITORING_EVENT_PY_START) | (1 << PY_MONITORING_EVENT_PY_RESUME) |
  477. (1 << PY_MONITORING_EVENT_PY_RETURN) | (1 << PY_MONITORING_EVENT_PY_YIELD) |
  478. (1 << PY_MONITORING_EVENT_RAISE) | (1 << PY_MONITORING_EVENT_LINE) |
  479. (1 << PY_MONITORING_EVENT_JUMP) | (1 << PY_MONITORING_EVENT_BRANCH) |
  480. (1 << PY_MONITORING_EVENT_PY_UNWIND) | (1 << PY_MONITORING_EVENT_PY_THROW) |
  481. (1 << PY_MONITORING_EVENT_STOP_ITERATION) |
  482. (1 << PY_MONITORING_EVENT_EXCEPTION_HANDLED);
  483. if (tstate->interp->f_opcode_trace_set) {
  484. events |= (1 << PY_MONITORING_EVENT_INSTRUCTION);
  485. }
  486. }
  487. return _PyMonitoring_SetEvents(PY_MONITORING_SYS_TRACE_ID, events);
  488. }