_lsprof.c 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. #ifndef Py_BUILD_CORE_BUILTIN
  2. # define Py_BUILD_CORE_MODULE 1
  3. #endif
  4. #include "Python.h"
  5. #include "pycore_call.h" // _PyObject_CallNoArgs()
  6. #include "pycore_pystate.h" // _PyThreadState_GET()
  7. #include "rotatingtree.h"
  8. /************************************************************/
  9. /* Written by Brett Rosen and Ted Czotter */
  10. struct _ProfilerEntry;
  11. /* represents a function called from another function */
  12. typedef struct _ProfilerSubEntry {
  13. rotating_node_t header;
  14. _PyTime_t tt;
  15. _PyTime_t it;
  16. long callcount;
  17. long recursivecallcount;
  18. long recursionLevel;
  19. } ProfilerSubEntry;
  20. /* represents a function or user defined block */
  21. typedef struct _ProfilerEntry {
  22. rotating_node_t header;
  23. PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
  24. _PyTime_t tt; /* total time in this entry */
  25. _PyTime_t it; /* inline time in this entry (not in subcalls) */
  26. long callcount; /* how many times this was called */
  27. long recursivecallcount; /* how many times called recursively */
  28. long recursionLevel;
  29. rotating_node_t *calls;
  30. } ProfilerEntry;
  31. typedef struct _ProfilerContext {
  32. _PyTime_t t0;
  33. _PyTime_t subt;
  34. struct _ProfilerContext *previous;
  35. ProfilerEntry *ctxEntry;
  36. } ProfilerContext;
  37. typedef struct {
  38. PyObject_HEAD
  39. rotating_node_t *profilerEntries;
  40. ProfilerContext *currentProfilerContext;
  41. ProfilerContext *freelistProfilerContext;
  42. int flags;
  43. PyObject *externalTimer;
  44. double externalTimerUnit;
  45. int tool_id;
  46. PyObject* missing;
  47. } ProfilerObject;
  48. #define POF_ENABLED 0x001
  49. #define POF_SUBCALLS 0x002
  50. #define POF_BUILTINS 0x004
  51. #define POF_NOMEMORY 0x100
  52. /*[clinic input]
  53. module _lsprof
  54. class _lsprof.Profiler "ProfilerObject *" "&ProfilerType"
  55. [clinic start generated code]*/
  56. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=e349ac952152f336]*/
  57. #include "clinic/_lsprof.c.h"
  58. typedef struct {
  59. PyTypeObject *profiler_type;
  60. PyTypeObject *stats_entry_type;
  61. PyTypeObject *stats_subentry_type;
  62. } _lsprof_state;
  63. static inline _lsprof_state*
  64. _lsprof_get_state(PyObject *module)
  65. {
  66. void *state = PyModule_GetState(module);
  67. assert(state != NULL);
  68. return (_lsprof_state *)state;
  69. }
  70. /*** External Timers ***/
  71. static _PyTime_t CallExternalTimer(ProfilerObject *pObj)
  72. {
  73. PyObject *o = _PyObject_CallNoArgs(pObj->externalTimer);
  74. if (o == NULL) {
  75. PyErr_WriteUnraisable(pObj->externalTimer);
  76. return 0;
  77. }
  78. _PyTime_t result;
  79. int err;
  80. if (pObj->externalTimerUnit > 0.0) {
  81. /* interpret the result as an integer that will be scaled
  82. in profiler_getstats() */
  83. err = _PyTime_FromNanosecondsObject(&result, o);
  84. }
  85. else {
  86. /* interpret the result as a double measured in seconds.
  87. As the profiler works with _PyTime_t internally
  88. we convert it to a large integer */
  89. err = _PyTime_FromSecondsObject(&result, o, _PyTime_ROUND_FLOOR);
  90. }
  91. Py_DECREF(o);
  92. if (err < 0) {
  93. PyErr_WriteUnraisable(pObj->externalTimer);
  94. return 0;
  95. }
  96. return result;
  97. }
  98. static inline _PyTime_t
  99. call_timer(ProfilerObject *pObj)
  100. {
  101. if (pObj->externalTimer != NULL) {
  102. return CallExternalTimer(pObj);
  103. }
  104. else {
  105. return _PyTime_GetPerfCounter();
  106. }
  107. }
  108. /*** ProfilerObject ***/
  109. static PyObject *
  110. normalizeUserObj(PyObject *obj)
  111. {
  112. PyCFunctionObject *fn;
  113. if (!PyCFunction_Check(obj)) {
  114. return Py_NewRef(obj);
  115. }
  116. /* Replace built-in function objects with a descriptive string
  117. because of built-in methods -- keeping a reference to
  118. __self__ is probably not a good idea. */
  119. fn = (PyCFunctionObject *)obj;
  120. if (fn->m_self == NULL) {
  121. /* built-in function: look up the module name */
  122. PyObject *mod = fn->m_module;
  123. PyObject *modname = NULL;
  124. if (mod != NULL) {
  125. if (PyUnicode_Check(mod)) {
  126. modname = Py_NewRef(mod);
  127. }
  128. else if (PyModule_Check(mod)) {
  129. modname = PyModule_GetNameObject(mod);
  130. if (modname == NULL)
  131. PyErr_Clear();
  132. }
  133. }
  134. if (modname != NULL) {
  135. if (!_PyUnicode_EqualToASCIIString(modname, "builtins")) {
  136. PyObject *result;
  137. result = PyUnicode_FromFormat("<%U.%s>", modname,
  138. fn->m_ml->ml_name);
  139. Py_DECREF(modname);
  140. return result;
  141. }
  142. Py_DECREF(modname);
  143. }
  144. return PyUnicode_FromFormat("<%s>", fn->m_ml->ml_name);
  145. }
  146. else {
  147. /* built-in method: try to return
  148. repr(getattr(type(__self__), __name__))
  149. */
  150. PyObject *self = fn->m_self;
  151. PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name);
  152. PyObject *modname = fn->m_module;
  153. if (name != NULL) {
  154. PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
  155. Py_XINCREF(mo);
  156. Py_DECREF(name);
  157. if (mo != NULL) {
  158. PyObject *res = PyObject_Repr(mo);
  159. Py_DECREF(mo);
  160. if (res != NULL)
  161. return res;
  162. }
  163. }
  164. /* Otherwise, use __module__ */
  165. PyErr_Clear();
  166. if (modname != NULL && PyUnicode_Check(modname))
  167. return PyUnicode_FromFormat("<built-in method %S.%s>",
  168. modname, fn->m_ml->ml_name);
  169. else
  170. return PyUnicode_FromFormat("<built-in method %s>",
  171. fn->m_ml->ml_name);
  172. }
  173. }
  174. static ProfilerEntry*
  175. newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj)
  176. {
  177. ProfilerEntry *self;
  178. self = (ProfilerEntry*) PyMem_Malloc(sizeof(ProfilerEntry));
  179. if (self == NULL) {
  180. pObj->flags |= POF_NOMEMORY;
  181. return NULL;
  182. }
  183. userObj = normalizeUserObj(userObj);
  184. if (userObj == NULL) {
  185. PyErr_Clear();
  186. PyMem_Free(self);
  187. pObj->flags |= POF_NOMEMORY;
  188. return NULL;
  189. }
  190. self->header.key = key;
  191. self->userObj = userObj;
  192. self->tt = 0;
  193. self->it = 0;
  194. self->callcount = 0;
  195. self->recursivecallcount = 0;
  196. self->recursionLevel = 0;
  197. self->calls = EMPTY_ROTATING_TREE;
  198. RotatingTree_Add(&pObj->profilerEntries, &self->header);
  199. return self;
  200. }
  201. static ProfilerEntry*
  202. getEntry(ProfilerObject *pObj, void *key)
  203. {
  204. return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
  205. }
  206. static ProfilerSubEntry *
  207. getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
  208. {
  209. return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
  210. (void *)entry);
  211. }
  212. static ProfilerSubEntry *
  213. newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
  214. {
  215. ProfilerSubEntry *self;
  216. self = (ProfilerSubEntry*) PyMem_Malloc(sizeof(ProfilerSubEntry));
  217. if (self == NULL) {
  218. pObj->flags |= POF_NOMEMORY;
  219. return NULL;
  220. }
  221. self->header.key = (void *)entry;
  222. self->tt = 0;
  223. self->it = 0;
  224. self->callcount = 0;
  225. self->recursivecallcount = 0;
  226. self->recursionLevel = 0;
  227. RotatingTree_Add(&caller->calls, &self->header);
  228. return self;
  229. }
  230. static int freeSubEntry(rotating_node_t *header, void *arg)
  231. {
  232. ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
  233. PyMem_Free(subentry);
  234. return 0;
  235. }
  236. static int freeEntry(rotating_node_t *header, void *arg)
  237. {
  238. ProfilerEntry *entry = (ProfilerEntry*) header;
  239. RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
  240. Py_DECREF(entry->userObj);
  241. PyMem_Free(entry);
  242. return 0;
  243. }
  244. static void clearEntries(ProfilerObject *pObj)
  245. {
  246. RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
  247. pObj->profilerEntries = EMPTY_ROTATING_TREE;
  248. /* release the memory hold by the ProfilerContexts */
  249. if (pObj->currentProfilerContext) {
  250. PyMem_Free(pObj->currentProfilerContext);
  251. pObj->currentProfilerContext = NULL;
  252. }
  253. while (pObj->freelistProfilerContext) {
  254. ProfilerContext *c = pObj->freelistProfilerContext;
  255. pObj->freelistProfilerContext = c->previous;
  256. PyMem_Free(c);
  257. }
  258. pObj->freelistProfilerContext = NULL;
  259. }
  260. static void
  261. initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
  262. {
  263. self->ctxEntry = entry;
  264. self->subt = 0;
  265. self->previous = pObj->currentProfilerContext;
  266. pObj->currentProfilerContext = self;
  267. ++entry->recursionLevel;
  268. if ((pObj->flags & POF_SUBCALLS) && self->previous) {
  269. /* find or create an entry for me in my caller's entry */
  270. ProfilerEntry *caller = self->previous->ctxEntry;
  271. ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
  272. if (subentry == NULL)
  273. subentry = newSubEntry(pObj, caller, entry);
  274. if (subentry)
  275. ++subentry->recursionLevel;
  276. }
  277. self->t0 = call_timer(pObj);
  278. }
  279. static void
  280. Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
  281. {
  282. _PyTime_t tt = call_timer(pObj) - self->t0;
  283. _PyTime_t it = tt - self->subt;
  284. if (self->previous)
  285. self->previous->subt += tt;
  286. pObj->currentProfilerContext = self->previous;
  287. if (--entry->recursionLevel == 0)
  288. entry->tt += tt;
  289. else
  290. ++entry->recursivecallcount;
  291. entry->it += it;
  292. entry->callcount++;
  293. if ((pObj->flags & POF_SUBCALLS) && self->previous) {
  294. /* find or create an entry for me in my caller's entry */
  295. ProfilerEntry *caller = self->previous->ctxEntry;
  296. ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
  297. if (subentry) {
  298. if (--subentry->recursionLevel == 0)
  299. subentry->tt += tt;
  300. else
  301. ++subentry->recursivecallcount;
  302. subentry->it += it;
  303. ++subentry->callcount;
  304. }
  305. }
  306. }
  307. static void
  308. ptrace_enter_call(PyObject *self, void *key, PyObject *userObj)
  309. {
  310. /* entering a call to the function identified by 'key'
  311. (which can be a PyCodeObject or a PyMethodDef pointer) */
  312. ProfilerObject *pObj = (ProfilerObject*)self;
  313. ProfilerEntry *profEntry;
  314. ProfilerContext *pContext;
  315. /* In the case of entering a generator expression frame via a
  316. * throw (gen_send_ex(.., 1)), we may already have an
  317. * Exception set here. We must not mess around with this
  318. * exception, and some of the code under here assumes that
  319. * PyErr_* is its own to mess around with, so we have to
  320. * save and restore any current exception. */
  321. PyObject *exc = PyErr_GetRaisedException();
  322. profEntry = getEntry(pObj, key);
  323. if (profEntry == NULL) {
  324. profEntry = newProfilerEntry(pObj, key, userObj);
  325. if (profEntry == NULL)
  326. goto restorePyerr;
  327. }
  328. /* grab a ProfilerContext out of the free list */
  329. pContext = pObj->freelistProfilerContext;
  330. if (pContext) {
  331. pObj->freelistProfilerContext = pContext->previous;
  332. }
  333. else {
  334. /* free list exhausted, allocate a new one */
  335. pContext = (ProfilerContext*)
  336. PyMem_Malloc(sizeof(ProfilerContext));
  337. if (pContext == NULL) {
  338. pObj->flags |= POF_NOMEMORY;
  339. goto restorePyerr;
  340. }
  341. }
  342. initContext(pObj, pContext, profEntry);
  343. restorePyerr:
  344. PyErr_SetRaisedException(exc);
  345. }
  346. static void
  347. ptrace_leave_call(PyObject *self, void *key)
  348. {
  349. /* leaving a call to the function identified by 'key' */
  350. ProfilerObject *pObj = (ProfilerObject*)self;
  351. ProfilerEntry *profEntry;
  352. ProfilerContext *pContext;
  353. pContext = pObj->currentProfilerContext;
  354. if (pContext == NULL)
  355. return;
  356. profEntry = getEntry(pObj, key);
  357. if (profEntry) {
  358. Stop(pObj, pContext, profEntry);
  359. }
  360. else {
  361. pObj->currentProfilerContext = pContext->previous;
  362. }
  363. /* put pContext into the free list */
  364. pContext->previous = pObj->freelistProfilerContext;
  365. pObj->freelistProfilerContext = pContext;
  366. }
  367. static int
  368. pending_exception(ProfilerObject *pObj)
  369. {
  370. if (pObj->flags & POF_NOMEMORY) {
  371. pObj->flags -= POF_NOMEMORY;
  372. PyErr_SetString(PyExc_MemoryError,
  373. "memory was exhausted while profiling");
  374. return -1;
  375. }
  376. return 0;
  377. }
  378. /************************************************************/
  379. static PyStructSequence_Field profiler_entry_fields[] = {
  380. {"code", "code object or built-in function name"},
  381. {"callcount", "how many times this was called"},
  382. {"reccallcount", "how many times called recursively"},
  383. {"totaltime", "total time in this entry"},
  384. {"inlinetime", "inline time in this entry (not in subcalls)"},
  385. {"calls", "details of the calls"},
  386. {0}
  387. };
  388. static PyStructSequence_Field profiler_subentry_fields[] = {
  389. {"code", "called code object or built-in function name"},
  390. {"callcount", "how many times this is called"},
  391. {"reccallcount", "how many times this is called recursively"},
  392. {"totaltime", "total time spent in this call"},
  393. {"inlinetime", "inline time (not in further subcalls)"},
  394. {0}
  395. };
  396. static PyStructSequence_Desc profiler_entry_desc = {
  397. .name = "_lsprof.profiler_entry",
  398. .fields = profiler_entry_fields,
  399. .doc = NULL,
  400. .n_in_sequence = 6
  401. };
  402. static PyStructSequence_Desc profiler_subentry_desc = {
  403. .name = "_lsprof.profiler_subentry",
  404. .fields = profiler_subentry_fields,
  405. .doc = NULL,
  406. .n_in_sequence = 5
  407. };
  408. typedef struct {
  409. PyObject *list;
  410. PyObject *sublist;
  411. double factor;
  412. _lsprof_state *state;
  413. } statscollector_t;
  414. static int statsForSubEntry(rotating_node_t *node, void *arg)
  415. {
  416. ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
  417. statscollector_t *collect = (statscollector_t*) arg;
  418. ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
  419. int err;
  420. PyObject *sinfo;
  421. sinfo = PyObject_CallFunction((PyObject*) collect->state->stats_subentry_type,
  422. "((Olldd))",
  423. entry->userObj,
  424. sentry->callcount,
  425. sentry->recursivecallcount,
  426. collect->factor * sentry->tt,
  427. collect->factor * sentry->it);
  428. if (sinfo == NULL)
  429. return -1;
  430. err = PyList_Append(collect->sublist, sinfo);
  431. Py_DECREF(sinfo);
  432. return err;
  433. }
  434. static int statsForEntry(rotating_node_t *node, void *arg)
  435. {
  436. ProfilerEntry *entry = (ProfilerEntry*) node;
  437. statscollector_t *collect = (statscollector_t*) arg;
  438. PyObject *info;
  439. int err;
  440. if (entry->callcount == 0)
  441. return 0; /* skip */
  442. if (entry->calls != EMPTY_ROTATING_TREE) {
  443. collect->sublist = PyList_New(0);
  444. if (collect->sublist == NULL)
  445. return -1;
  446. if (RotatingTree_Enum(entry->calls,
  447. statsForSubEntry, collect) != 0) {
  448. Py_DECREF(collect->sublist);
  449. return -1;
  450. }
  451. }
  452. else {
  453. collect->sublist = Py_NewRef(Py_None);
  454. }
  455. info = PyObject_CallFunction((PyObject*) collect->state->stats_entry_type,
  456. "((OllddO))",
  457. entry->userObj,
  458. entry->callcount,
  459. entry->recursivecallcount,
  460. collect->factor * entry->tt,
  461. collect->factor * entry->it,
  462. collect->sublist);
  463. Py_DECREF(collect->sublist);
  464. if (info == NULL)
  465. return -1;
  466. err = PyList_Append(collect->list, info);
  467. Py_DECREF(info);
  468. return err;
  469. }
  470. /*[clinic input]
  471. _lsprof.Profiler.getstats
  472. cls: defining_class
  473. list of profiler_entry objects.
  474. getstats() -> list of profiler_entry objects
  475. Return all information collected by the profiler.
  476. Each profiler_entry is a tuple-like object with the
  477. following attributes:
  478. code code object
  479. callcount how many times this was called
  480. reccallcount how many times called recursively
  481. totaltime total time in this entry
  482. inlinetime inline time in this entry (not in subcalls)
  483. calls details of the calls
  484. The calls attribute is either None or a list of
  485. profiler_subentry objects:
  486. code called code object
  487. callcount how many times this is called
  488. reccallcount how many times this is called recursively
  489. totaltime total time spent in this call
  490. inlinetime inline time (not in further subcalls)
  491. [clinic start generated code]*/
  492. static PyObject *
  493. _lsprof_Profiler_getstats_impl(ProfilerObject *self, PyTypeObject *cls)
  494. /*[clinic end generated code: output=1806ef720019ee03 input=445e193ef4522902]*/
  495. {
  496. statscollector_t collect;
  497. collect.state = _PyType_GetModuleState(cls);
  498. if (pending_exception(self)) {
  499. return NULL;
  500. }
  501. if (!self->externalTimer || self->externalTimerUnit == 0.0) {
  502. _PyTime_t onesec = _PyTime_FromSeconds(1);
  503. collect.factor = (double)1 / onesec;
  504. }
  505. else {
  506. collect.factor = self->externalTimerUnit;
  507. }
  508. collect.list = PyList_New(0);
  509. if (collect.list == NULL)
  510. return NULL;
  511. if (RotatingTree_Enum(self->profilerEntries, statsForEntry, &collect)
  512. != 0) {
  513. Py_DECREF(collect.list);
  514. return NULL;
  515. }
  516. return collect.list;
  517. }
  518. static int
  519. setSubcalls(ProfilerObject *pObj, int nvalue)
  520. {
  521. if (nvalue == 0)
  522. pObj->flags &= ~POF_SUBCALLS;
  523. else if (nvalue > 0)
  524. pObj->flags |= POF_SUBCALLS;
  525. return 0;
  526. }
  527. static int
  528. setBuiltins(ProfilerObject *pObj, int nvalue)
  529. {
  530. if (nvalue == 0)
  531. pObj->flags &= ~POF_BUILTINS;
  532. else if (nvalue > 0) {
  533. pObj->flags |= POF_BUILTINS;
  534. }
  535. return 0;
  536. }
  537. PyObject* pystart_callback(ProfilerObject* self, PyObject *const *args, Py_ssize_t size)
  538. {
  539. PyObject* code = args[0];
  540. ptrace_enter_call((PyObject*)self, (void *)code, (PyObject *)code);
  541. Py_RETURN_NONE;
  542. }
  543. PyObject* pyreturn_callback(ProfilerObject* self, PyObject *const *args, Py_ssize_t size)
  544. {
  545. PyObject* code = args[0];
  546. ptrace_leave_call((PyObject*)self, (void *)code);
  547. Py_RETURN_NONE;
  548. }
  549. PyObject* get_cfunc_from_callable(PyObject* callable, PyObject* self_arg, PyObject* missing)
  550. {
  551. // return a new reference
  552. if (PyCFunction_Check(callable)) {
  553. Py_INCREF(callable);
  554. return (PyObject*)((PyCFunctionObject *)callable);
  555. }
  556. if (Py_TYPE(callable) == &PyMethodDescr_Type) {
  557. /* For backwards compatibility need to
  558. * convert to builtin method */
  559. /* If no arg, skip */
  560. if (self_arg == missing) {
  561. return NULL;
  562. }
  563. PyObject *meth = Py_TYPE(callable)->tp_descr_get(
  564. callable, self_arg, (PyObject*)Py_TYPE(self_arg));
  565. if (meth == NULL) {
  566. return NULL;
  567. }
  568. if (PyCFunction_Check(meth)) {
  569. return (PyObject*)((PyCFunctionObject *)meth);
  570. }
  571. }
  572. return NULL;
  573. }
  574. PyObject* ccall_callback(ProfilerObject* self, PyObject *const *args, Py_ssize_t size)
  575. {
  576. if (self->flags & POF_BUILTINS) {
  577. PyObject* callable = args[2];
  578. PyObject* self_arg = args[3];
  579. PyObject* cfunc = get_cfunc_from_callable(callable, self_arg, self->missing);
  580. if (cfunc) {
  581. ptrace_enter_call((PyObject*)self,
  582. ((PyCFunctionObject *)cfunc)->m_ml,
  583. cfunc);
  584. Py_DECREF(cfunc);
  585. }
  586. }
  587. Py_RETURN_NONE;
  588. }
  589. PyObject* creturn_callback(ProfilerObject* self, PyObject *const *args, Py_ssize_t size)
  590. {
  591. if (self->flags & POF_BUILTINS) {
  592. PyObject* callable = args[2];
  593. PyObject* self_arg = args[3];
  594. PyObject* cfunc = get_cfunc_from_callable(callable, self_arg, self->missing);
  595. if (cfunc) {
  596. ptrace_leave_call((PyObject*)self,
  597. ((PyCFunctionObject *)cfunc)->m_ml);
  598. Py_DECREF(cfunc);
  599. }
  600. }
  601. Py_RETURN_NONE;
  602. }
  603. static const struct {
  604. int event;
  605. const char* callback_method;
  606. } callback_table[] = {
  607. {PY_MONITORING_EVENT_PY_START, "_pystart_callback"},
  608. {PY_MONITORING_EVENT_PY_RESUME, "_pystart_callback"},
  609. {PY_MONITORING_EVENT_PY_THROW, "_pystart_callback"},
  610. {PY_MONITORING_EVENT_PY_RETURN, "_pyreturn_callback"},
  611. {PY_MONITORING_EVENT_PY_YIELD, "_pyreturn_callback"},
  612. {PY_MONITORING_EVENT_PY_UNWIND, "_pyreturn_callback"},
  613. {PY_MONITORING_EVENT_CALL, "_ccall_callback"},
  614. {PY_MONITORING_EVENT_C_RETURN, "_creturn_callback"},
  615. {PY_MONITORING_EVENT_C_RAISE, "_creturn_callback"},
  616. {0, NULL}
  617. };
  618. PyDoc_STRVAR(enable_doc, "\
  619. enable(subcalls=True, builtins=True)\n\
  620. \n\
  621. Start collecting profiling information.\n\
  622. If 'subcalls' is True, also records for each function\n\
  623. statistics separated according to its current caller.\n\
  624. If 'builtins' is True, records the time spent in\n\
  625. built-in functions separately from their caller.\n\
  626. ");
  627. static PyObject*
  628. profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds)
  629. {
  630. int subcalls = -1;
  631. int builtins = -1;
  632. static char *kwlist[] = {"subcalls", "builtins", 0};
  633. int all_events = 0;
  634. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|pp:enable",
  635. kwlist, &subcalls, &builtins))
  636. return NULL;
  637. if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0) {
  638. return NULL;
  639. }
  640. PyObject* monitoring = _PyImport_GetModuleAttrString("sys", "monitoring");
  641. if (!monitoring) {
  642. return NULL;
  643. }
  644. if (PyObject_CallMethod(monitoring, "use_tool_id", "is", self->tool_id, "cProfile") == NULL) {
  645. PyErr_Format(PyExc_ValueError, "Another profiling tool is already active");
  646. Py_DECREF(monitoring);
  647. return NULL;
  648. }
  649. for (int i = 0; callback_table[i].callback_method; i++) {
  650. PyObject* callback = PyObject_GetAttrString((PyObject*)self, callback_table[i].callback_method);
  651. if (!callback) {
  652. Py_DECREF(monitoring);
  653. return NULL;
  654. }
  655. Py_XDECREF(PyObject_CallMethod(monitoring, "register_callback", "iiO", self->tool_id,
  656. (1 << callback_table[i].event),
  657. callback));
  658. Py_DECREF(callback);
  659. all_events |= (1 << callback_table[i].event);
  660. }
  661. if (!PyObject_CallMethod(monitoring, "set_events", "ii", self->tool_id, all_events)) {
  662. Py_DECREF(monitoring);
  663. return NULL;
  664. }
  665. Py_DECREF(monitoring);
  666. self->flags |= POF_ENABLED;
  667. Py_RETURN_NONE;
  668. }
  669. static void
  670. flush_unmatched(ProfilerObject *pObj)
  671. {
  672. while (pObj->currentProfilerContext) {
  673. ProfilerContext *pContext = pObj->currentProfilerContext;
  674. ProfilerEntry *profEntry= pContext->ctxEntry;
  675. if (profEntry)
  676. Stop(pObj, pContext, profEntry);
  677. else
  678. pObj->currentProfilerContext = pContext->previous;
  679. if (pContext)
  680. PyMem_Free(pContext);
  681. }
  682. }
  683. PyDoc_STRVAR(disable_doc, "\
  684. disable()\n\
  685. \n\
  686. Stop collecting profiling information.\n\
  687. ");
  688. static PyObject*
  689. profiler_disable(ProfilerObject *self, PyObject* noarg)
  690. {
  691. if (self->flags & POF_ENABLED) {
  692. PyObject* result = NULL;
  693. PyObject* monitoring = _PyImport_GetModuleAttrString("sys", "monitoring");
  694. if (!monitoring) {
  695. return NULL;
  696. }
  697. for (int i = 0; callback_table[i].callback_method; i++) {
  698. result = PyObject_CallMethod(monitoring, "register_callback", "iiO", self->tool_id,
  699. (1 << callback_table[i].event), Py_None);
  700. if (!result) {
  701. Py_DECREF(monitoring);
  702. return NULL;
  703. }
  704. Py_DECREF(result);
  705. }
  706. result = PyObject_CallMethod(monitoring, "set_events", "ii", self->tool_id, 0);
  707. if (!result) {
  708. Py_DECREF(monitoring);
  709. return NULL;
  710. }
  711. Py_DECREF(result);
  712. result = PyObject_CallMethod(monitoring, "free_tool_id", "i", self->tool_id);
  713. if (!result) {
  714. Py_DECREF(monitoring);
  715. return NULL;
  716. }
  717. Py_DECREF(result);
  718. Py_DECREF(monitoring);
  719. self->flags &= ~POF_ENABLED;
  720. flush_unmatched(self);
  721. }
  722. if (pending_exception(self)) {
  723. return NULL;
  724. }
  725. Py_RETURN_NONE;
  726. }
  727. PyDoc_STRVAR(clear_doc, "\
  728. clear()\n\
  729. \n\
  730. Clear all profiling information collected so far.\n\
  731. ");
  732. static PyObject*
  733. profiler_clear(ProfilerObject *pObj, PyObject* noarg)
  734. {
  735. clearEntries(pObj);
  736. Py_RETURN_NONE;
  737. }
  738. static int
  739. profiler_traverse(ProfilerObject *op, visitproc visit, void *arg)
  740. {
  741. Py_VISIT(Py_TYPE(op));
  742. return 0;
  743. }
  744. static void
  745. profiler_dealloc(ProfilerObject *op)
  746. {
  747. PyObject_GC_UnTrack(op);
  748. if (op->flags & POF_ENABLED) {
  749. PyThreadState *tstate = _PyThreadState_GET();
  750. if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
  751. _PyErr_WriteUnraisableMsg("When destroying _lsprof profiler", NULL);
  752. }
  753. }
  754. flush_unmatched(op);
  755. clearEntries(op);
  756. Py_XDECREF(op->externalTimer);
  757. PyTypeObject *tp = Py_TYPE(op);
  758. tp->tp_free(op);
  759. Py_DECREF(tp);
  760. }
  761. static int
  762. profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw)
  763. {
  764. PyObject *timer = NULL;
  765. double timeunit = 0.0;
  766. int subcalls = 1;
  767. int builtins = 1;
  768. static char *kwlist[] = {"timer", "timeunit",
  769. "subcalls", "builtins", 0};
  770. if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odpp:Profiler", kwlist,
  771. &timer, &timeunit,
  772. &subcalls, &builtins))
  773. return -1;
  774. if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
  775. return -1;
  776. pObj->externalTimerUnit = timeunit;
  777. Py_XSETREF(pObj->externalTimer, Py_XNewRef(timer));
  778. pObj->tool_id = PY_MONITORING_PROFILER_ID;
  779. PyObject* monitoring = _PyImport_GetModuleAttrString("sys", "monitoring");
  780. if (!monitoring) {
  781. return -1;
  782. }
  783. pObj->missing = PyObject_GetAttrString(monitoring, "MISSING");
  784. if (!pObj->missing) {
  785. Py_DECREF(monitoring);
  786. return -1;
  787. }
  788. Py_DECREF(monitoring);
  789. return 0;
  790. }
  791. static PyMethodDef profiler_methods[] = {
  792. _LSPROF_PROFILER_GETSTATS_METHODDEF
  793. {"enable", _PyCFunction_CAST(profiler_enable),
  794. METH_VARARGS | METH_KEYWORDS, enable_doc},
  795. {"disable", (PyCFunction)profiler_disable,
  796. METH_NOARGS, disable_doc},
  797. {"clear", (PyCFunction)profiler_clear,
  798. METH_NOARGS, clear_doc},
  799. {"_pystart_callback", _PyCFunction_CAST(pystart_callback),
  800. METH_FASTCALL, NULL},
  801. {"_pyreturn_callback", _PyCFunction_CAST(pyreturn_callback),
  802. METH_FASTCALL, NULL},
  803. {"_ccall_callback", _PyCFunction_CAST(ccall_callback),
  804. METH_FASTCALL, NULL},
  805. {"_creturn_callback", _PyCFunction_CAST(creturn_callback),
  806. METH_FASTCALL, NULL},
  807. {NULL, NULL}
  808. };
  809. PyDoc_STRVAR(profiler_doc, "\
  810. Profiler(timer=None, timeunit=None, subcalls=True, builtins=True)\n\
  811. \n\
  812. Builds a profiler object using the specified timer function.\n\
  813. The default timer is a fast built-in one based on real time.\n\
  814. For custom timer functions returning integers, timeunit can\n\
  815. be a float specifying a scale (i.e. how long each integer unit\n\
  816. is, in seconds).\n\
  817. ");
  818. static PyType_Slot _lsprof_profiler_type_spec_slots[] = {
  819. {Py_tp_doc, (void *)profiler_doc},
  820. {Py_tp_methods, profiler_methods},
  821. {Py_tp_dealloc, profiler_dealloc},
  822. {Py_tp_init, profiler_init},
  823. {Py_tp_traverse, profiler_traverse},
  824. {0, 0}
  825. };
  826. static PyType_Spec _lsprof_profiler_type_spec = {
  827. .name = "_lsprof.Profiler",
  828. .basicsize = sizeof(ProfilerObject),
  829. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  830. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  831. .slots = _lsprof_profiler_type_spec_slots,
  832. };
  833. static PyMethodDef moduleMethods[] = {
  834. {NULL, NULL}
  835. };
  836. static int
  837. _lsprof_traverse(PyObject *module, visitproc visit, void *arg)
  838. {
  839. _lsprof_state *state = _lsprof_get_state(module);
  840. Py_VISIT(state->profiler_type);
  841. Py_VISIT(state->stats_entry_type);
  842. Py_VISIT(state->stats_subentry_type);
  843. return 0;
  844. }
  845. static int
  846. _lsprof_clear(PyObject *module)
  847. {
  848. _lsprof_state *state = _lsprof_get_state(module);
  849. Py_CLEAR(state->profiler_type);
  850. Py_CLEAR(state->stats_entry_type);
  851. Py_CLEAR(state->stats_subentry_type);
  852. return 0;
  853. }
  854. static void
  855. _lsprof_free(void *module)
  856. {
  857. _lsprof_clear((PyObject *)module);
  858. }
  859. static int
  860. _lsprof_exec(PyObject *module)
  861. {
  862. _lsprof_state *state = PyModule_GetState(module);
  863. state->profiler_type = (PyTypeObject *)PyType_FromModuleAndSpec(
  864. module, &_lsprof_profiler_type_spec, NULL);
  865. if (state->profiler_type == NULL) {
  866. return -1;
  867. }
  868. if (PyModule_AddType(module, state->profiler_type) < 0) {
  869. return -1;
  870. }
  871. state->stats_entry_type = PyStructSequence_NewType(&profiler_entry_desc);
  872. if (state->stats_entry_type == NULL) {
  873. return -1;
  874. }
  875. if (PyModule_AddType(module, state->stats_entry_type) < 0) {
  876. return -1;
  877. }
  878. state->stats_subentry_type = PyStructSequence_NewType(&profiler_subentry_desc);
  879. if (state->stats_subentry_type == NULL) {
  880. return -1;
  881. }
  882. if (PyModule_AddType(module, state->stats_subentry_type) < 0) {
  883. return -1;
  884. }
  885. return 0;
  886. }
  887. static PyModuleDef_Slot _lsprofslots[] = {
  888. {Py_mod_exec, _lsprof_exec},
  889. // XXX gh-103092: fix isolation.
  890. {Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},
  891. //{Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  892. {0, NULL}
  893. };
  894. static struct PyModuleDef _lsprofmodule = {
  895. PyModuleDef_HEAD_INIT,
  896. .m_name = "_lsprof",
  897. .m_doc = "Fast profiler",
  898. .m_size = sizeof(_lsprof_state),
  899. .m_methods = moduleMethods,
  900. .m_slots = _lsprofslots,
  901. .m_traverse = _lsprof_traverse,
  902. .m_clear = _lsprof_clear,
  903. .m_free = _lsprof_free
  904. };
  905. PyMODINIT_FUNC
  906. PyInit__lsprof(void)
  907. {
  908. return PyModuleDef_Init(&_lsprofmodule);
  909. }