_lsprof.c 31 KB

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