You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1463 lines
38 KiB

  1. #include "Python.h"
  2. #include "hashtable.h"
  3. #include "frameobject.h"
  4. #include "pythread.h"
  5. #include "osdefs.h"
  6. /* Trace memory blocks allocated by PyMem_RawMalloc() */
  7. #define TRACE_RAW_MALLOC
  8. /* Forward declaration */
  9. static void tracemalloc_stop(void);
  10. static void* raw_malloc(size_t size);
  11. static void raw_free(void *ptr);
  12. #ifdef Py_DEBUG
  13. # define TRACE_DEBUG
  14. #endif
  15. /* Protected by the GIL */
  16. static struct {
  17. PyMemAllocatorEx mem;
  18. PyMemAllocatorEx raw;
  19. PyMemAllocatorEx obj;
  20. } allocators;
  21. static struct {
  22. /* Module initialized?
  23. Variable protected by the GIL */
  24. enum {
  25. TRACEMALLOC_NOT_INITIALIZED,
  26. TRACEMALLOC_INITIALIZED,
  27. TRACEMALLOC_FINALIZED
  28. } initialized;
  29. /* Is tracemalloc tracing memory allocations?
  30. Variable protected by the GIL */
  31. int tracing;
  32. /* limit of the number of frames in a traceback, 1 by default.
  33. Variable protected by the GIL. */
  34. int max_nframe;
  35. } tracemalloc_config = {TRACEMALLOC_NOT_INITIALIZED, 0, 1};
  36. #if defined(TRACE_RAW_MALLOC) && defined(WITH_THREAD)
  37. /* This lock is needed because tracemalloc_free() is called without
  38. the GIL held from PyMem_RawFree(). It cannot acquire the lock because it
  39. would introduce a deadlock in PyThreadState_DeleteCurrent(). */
  40. static PyThread_type_lock tables_lock;
  41. # define TABLES_LOCK() PyThread_acquire_lock(tables_lock, 1)
  42. # define TABLES_UNLOCK() PyThread_release_lock(tables_lock)
  43. #else
  44. /* variables are protected by the GIL */
  45. # define TABLES_LOCK()
  46. # define TABLES_UNLOCK()
  47. #endif
  48. /* Pack the frame_t structure to reduce the memory footprint on 64-bit
  49. architectures: 12 bytes instead of 16. This optimization might produce
  50. SIGBUS on architectures not supporting unaligned memory accesses (64-bit
  51. MIPS CPU?): on such architecture, the structure must not be packed. */
  52. typedef struct
  53. #ifdef __GNUC__
  54. __attribute__((packed))
  55. #elif defined(_MSC_VER)
  56. _declspec(align(4))
  57. #endif
  58. {
  59. PyObject *filename;
  60. int lineno;
  61. } frame_t;
  62. typedef struct {
  63. Py_uhash_t hash;
  64. int nframe;
  65. frame_t frames[1];
  66. } traceback_t;
  67. #define TRACEBACK_SIZE(NFRAME) \
  68. (sizeof(traceback_t) + sizeof(frame_t) * (NFRAME - 1))
  69. #define MAX_NFRAME \
  70. ((INT_MAX - (int)sizeof(traceback_t)) / (int)sizeof(frame_t) + 1)
  71. static PyObject *unknown_filename = NULL;
  72. static traceback_t tracemalloc_empty_traceback;
  73. /* Trace of a memory block */
  74. typedef struct {
  75. /* Size of the memory block in bytes */
  76. size_t size;
  77. /* Traceback where the memory block was allocated */
  78. traceback_t *traceback;
  79. } trace_t;
  80. /* Size in bytes of currently traced memory.
  81. Protected by TABLES_LOCK(). */
  82. static size_t tracemalloc_traced_memory = 0;
  83. /* Peak size in bytes of traced memory.
  84. Protected by TABLES_LOCK(). */
  85. static size_t tracemalloc_peak_traced_memory = 0;
  86. /* Hash table used as a set to intern filenames:
  87. PyObject* => PyObject*.
  88. Protected by the GIL */
  89. static _Py_hashtable_t *tracemalloc_filenames = NULL;
  90. /* Buffer to store a new traceback in traceback_new().
  91. Protected by the GIL. */
  92. static traceback_t *tracemalloc_traceback = NULL;
  93. /* Hash table used as a set to intern tracebacks:
  94. traceback_t* => traceback_t*
  95. Protected by the GIL */
  96. static _Py_hashtable_t *tracemalloc_tracebacks = NULL;
  97. /* pointer (void*) => trace (trace_t).
  98. Protected by TABLES_LOCK(). */
  99. static _Py_hashtable_t *tracemalloc_traces = NULL;
  100. #ifdef TRACE_DEBUG
  101. static void
  102. tracemalloc_error(const char *format, ...)
  103. {
  104. va_list ap;
  105. fprintf(stderr, "tracemalloc: ");
  106. va_start(ap, format);
  107. vfprintf(stderr, format, ap);
  108. va_end(ap);
  109. fprintf(stderr, "\n");
  110. fflush(stderr);
  111. }
  112. #endif
  113. #if defined(WITH_THREAD) && defined(TRACE_RAW_MALLOC)
  114. #define REENTRANT_THREADLOCAL
  115. /* If your OS does not provide native thread local storage, you can implement
  116. it manually using a lock. Functions of thread.c cannot be used because
  117. they use PyMem_RawMalloc() which leads to a reentrant call. */
  118. #if !(defined(_POSIX_THREADS) || defined(NT_THREADS))
  119. # error "need native thread local storage (TLS)"
  120. #endif
  121. static int tracemalloc_reentrant_key;
  122. /* Any non-NULL pointer can be used */
  123. #define REENTRANT Py_True
  124. static int
  125. get_reentrant(void)
  126. {
  127. void *ptr = PyThread_get_key_value(tracemalloc_reentrant_key);
  128. if (ptr != NULL) {
  129. assert(ptr == REENTRANT);
  130. return 1;
  131. }
  132. else
  133. return 0;
  134. }
  135. static void
  136. set_reentrant(int reentrant)
  137. {
  138. assert(reentrant == 0 || reentrant == 1);
  139. if (reentrant) {
  140. assert(PyThread_get_key_value(tracemalloc_reentrant_key) == NULL);
  141. PyThread_set_key_value(tracemalloc_reentrant_key, REENTRANT);
  142. }
  143. else {
  144. assert(PyThread_get_key_value(tracemalloc_reentrant_key) == REENTRANT);
  145. PyThread_set_key_value(tracemalloc_reentrant_key, NULL);
  146. }
  147. }
  148. #else
  149. /* WITH_THREAD not defined: Python compiled without threads,
  150. or TRACE_RAW_MALLOC not defined: variable protected by the GIL */
  151. static int tracemalloc_reentrant = 0;
  152. static int
  153. get_reentrant(void)
  154. {
  155. return tracemalloc_reentrant;
  156. }
  157. static void
  158. set_reentrant(int reentrant)
  159. {
  160. assert(!reentrant || !get_reentrant());
  161. tracemalloc_reentrant = reentrant;
  162. }
  163. #endif
  164. static int
  165. hashtable_compare_unicode(const void *key, const _Py_hashtable_entry_t *entry)
  166. {
  167. if (key != NULL && entry->key != NULL)
  168. return (PyUnicode_Compare((PyObject *)key, (PyObject *)entry->key) == 0);
  169. else
  170. return key == entry->key;
  171. }
  172. static _Py_hashtable_allocator_t hashtable_alloc = {malloc, free};
  173. static _Py_hashtable_t *
  174. hashtable_new(size_t data_size,
  175. _Py_hashtable_hash_func hash_func,
  176. _Py_hashtable_compare_func compare_func)
  177. {
  178. return _Py_hashtable_new_full(data_size, 0,
  179. hash_func, compare_func,
  180. NULL, NULL, NULL, &hashtable_alloc);
  181. }
  182. static void*
  183. raw_malloc(size_t size)
  184. {
  185. return allocators.raw.malloc(allocators.raw.ctx, size);
  186. }
  187. static void
  188. raw_free(void *ptr)
  189. {
  190. allocators.raw.free(allocators.raw.ctx, ptr);
  191. }
  192. static Py_uhash_t
  193. hashtable_hash_traceback(const void *key)
  194. {
  195. const traceback_t *traceback = key;
  196. return traceback->hash;
  197. }
  198. static int
  199. hashtable_compare_traceback(const traceback_t *traceback1,
  200. const _Py_hashtable_entry_t *he)
  201. {
  202. const traceback_t *traceback2 = he->key;
  203. const frame_t *frame1, *frame2;
  204. int i;
  205. if (traceback1->nframe != traceback2->nframe)
  206. return 0;
  207. for (i=0; i < traceback1->nframe; i++) {
  208. frame1 = &traceback1->frames[i];
  209. frame2 = &traceback2->frames[i];
  210. if (frame1->lineno != frame2->lineno)
  211. return 0;
  212. if (frame1->filename != frame2->filename) {
  213. assert(PyUnicode_Compare(frame1->filename, frame2->filename) != 0);
  214. return 0;
  215. }
  216. }
  217. return 1;
  218. }
  219. static void
  220. tracemalloc_get_frame(PyFrameObject *pyframe, frame_t *frame)
  221. {
  222. PyCodeObject *code;
  223. PyObject *filename;
  224. _Py_hashtable_entry_t *entry;
  225. frame->filename = unknown_filename;
  226. frame->lineno = PyFrame_GetLineNumber(pyframe);
  227. assert(frame->lineno >= 0);
  228. if (frame->lineno < 0)
  229. frame->lineno = 0;
  230. code = pyframe->f_code;
  231. if (code == NULL) {
  232. #ifdef TRACE_DEBUG
  233. tracemalloc_error("failed to get the code object of the frame");
  234. #endif
  235. return;
  236. }
  237. if (code->co_filename == NULL) {
  238. #ifdef TRACE_DEBUG
  239. tracemalloc_error("failed to get the filename of the code object");
  240. #endif
  241. return;
  242. }
  243. filename = code->co_filename;
  244. assert(filename != NULL);
  245. if (filename == NULL)
  246. return;
  247. if (!PyUnicode_Check(filename)) {
  248. #ifdef TRACE_DEBUG
  249. tracemalloc_error("filename is not an unicode string");
  250. #endif
  251. return;
  252. }
  253. if (!PyUnicode_IS_READY(filename)) {
  254. /* Don't make a Unicode string ready to avoid reentrant calls
  255. to tracemalloc_malloc() or tracemalloc_realloc() */
  256. #ifdef TRACE_DEBUG
  257. tracemalloc_error("filename is not a ready unicode string");
  258. #endif
  259. return;
  260. }
  261. /* intern the filename */
  262. entry = _Py_hashtable_get_entry(tracemalloc_filenames, filename);
  263. if (entry != NULL) {
  264. filename = (PyObject *)entry->key;
  265. }
  266. else {
  267. /* tracemalloc_filenames is responsible to keep a reference
  268. to the filename */
  269. Py_INCREF(filename);
  270. if (_Py_hashtable_set(tracemalloc_filenames, filename, NULL, 0) < 0) {
  271. Py_DECREF(filename);
  272. #ifdef TRACE_DEBUG
  273. tracemalloc_error("failed to intern the filename");
  274. #endif
  275. return;
  276. }
  277. }
  278. /* the tracemalloc_filenames table keeps a reference to the filename */
  279. frame->filename = filename;
  280. }
  281. static Py_uhash_t
  282. traceback_hash(traceback_t *traceback)
  283. {
  284. /* code based on tuplehash() of Objects/tupleobject.c */
  285. Py_uhash_t x, y; /* Unsigned for defined overflow behavior. */
  286. int len = traceback->nframe;
  287. Py_uhash_t mult = _PyHASH_MULTIPLIER;
  288. frame_t *frame;
  289. x = 0x345678UL;
  290. frame = traceback->frames;
  291. while (--len >= 0) {
  292. y = (Py_uhash_t)PyObject_Hash(frame->filename);
  293. y ^= (Py_uhash_t)frame->lineno;
  294. frame++;
  295. x = (x ^ y) * mult;
  296. /* the cast might truncate len; that doesn't change hash stability */
  297. mult += (Py_uhash_t)(82520UL + len + len);
  298. }
  299. x += 97531UL;
  300. return x;
  301. }
  302. static void
  303. traceback_get_frames(traceback_t *traceback)
  304. {
  305. PyThreadState *tstate;
  306. PyFrameObject *pyframe;
  307. #ifdef WITH_THREAD
  308. tstate = PyGILState_GetThisThreadState();
  309. #else
  310. tstate = PyThreadState_Get();
  311. #endif
  312. if (tstate == NULL) {
  313. #ifdef TRACE_DEBUG
  314. tracemalloc_error("failed to get the current thread state");
  315. #endif
  316. return;
  317. }
  318. for (pyframe = tstate->frame; pyframe != NULL; pyframe = pyframe->f_back) {
  319. tracemalloc_get_frame(pyframe, &traceback->frames[traceback->nframe]);
  320. assert(traceback->frames[traceback->nframe].filename != NULL);
  321. assert(traceback->frames[traceback->nframe].lineno >= 0);
  322. traceback->nframe++;
  323. if (traceback->nframe == tracemalloc_config.max_nframe)
  324. break;
  325. }
  326. }
  327. static traceback_t *
  328. traceback_new(void)
  329. {
  330. traceback_t *traceback;
  331. _Py_hashtable_entry_t *entry;
  332. #ifdef WITH_THREAD
  333. assert(PyGILState_Check());
  334. #endif
  335. /* get frames */
  336. traceback = tracemalloc_traceback;
  337. traceback->nframe = 0;
  338. traceback_get_frames(traceback);
  339. if (traceback->nframe == 0)
  340. return &tracemalloc_empty_traceback;
  341. traceback->hash = traceback_hash(traceback);
  342. /* intern the traceback */
  343. entry = _Py_hashtable_get_entry(tracemalloc_tracebacks, traceback);
  344. if (entry != NULL) {
  345. traceback = (traceback_t *)entry->key;
  346. }
  347. else {
  348. traceback_t *copy;
  349. size_t traceback_size;
  350. traceback_size = TRACEBACK_SIZE(traceback->nframe);
  351. copy = raw_malloc(traceback_size);
  352. if (copy == NULL) {
  353. #ifdef TRACE_DEBUG
  354. tracemalloc_error("failed to intern the traceback: malloc failed");
  355. #endif
  356. return NULL;
  357. }
  358. memcpy(copy, traceback, traceback_size);
  359. if (_Py_hashtable_set(tracemalloc_tracebacks, copy, NULL, 0) < 0) {
  360. raw_free(copy);
  361. #ifdef TRACE_DEBUG
  362. tracemalloc_error("failed to intern the traceback: putdata failed");
  363. #endif
  364. return NULL;
  365. }
  366. traceback = copy;
  367. }
  368. return traceback;
  369. }
  370. static int
  371. tracemalloc_add_trace(void *ptr, size_t size)
  372. {
  373. traceback_t *traceback;
  374. trace_t trace;
  375. int res;
  376. #ifdef WITH_THREAD
  377. assert(PyGILState_Check());
  378. #endif
  379. traceback = traceback_new();
  380. if (traceback == NULL)
  381. return -1;
  382. trace.size = size;
  383. trace.traceback = traceback;
  384. res = _Py_HASHTABLE_SET(tracemalloc_traces, ptr, trace);
  385. if (res == 0) {
  386. assert(tracemalloc_traced_memory <= PY_SIZE_MAX - size);
  387. tracemalloc_traced_memory += size;
  388. if (tracemalloc_traced_memory > tracemalloc_peak_traced_memory)
  389. tracemalloc_peak_traced_memory = tracemalloc_traced_memory;
  390. }
  391. return res;
  392. }
  393. static void
  394. tracemalloc_remove_trace(void *ptr)
  395. {
  396. trace_t trace;
  397. if (_Py_hashtable_pop(tracemalloc_traces, ptr, &trace, sizeof(trace))) {
  398. assert(tracemalloc_traced_memory >= trace.size);
  399. tracemalloc_traced_memory -= trace.size;
  400. }
  401. }
  402. static void*
  403. tracemalloc_alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
  404. {
  405. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  406. void *ptr;
  407. assert(elsize == 0 || nelem <= PY_SIZE_MAX / elsize);
  408. if (use_calloc)
  409. ptr = alloc->calloc(alloc->ctx, nelem, elsize);
  410. else
  411. ptr = alloc->malloc(alloc->ctx, nelem * elsize);
  412. if (ptr == NULL)
  413. return NULL;
  414. TABLES_LOCK();
  415. if (tracemalloc_add_trace(ptr, nelem * elsize) < 0) {
  416. /* Failed to allocate a trace for the new memory block */
  417. TABLES_UNLOCK();
  418. alloc->free(alloc->ctx, ptr);
  419. return NULL;
  420. }
  421. TABLES_UNLOCK();
  422. return ptr;
  423. }
  424. static void*
  425. tracemalloc_realloc(void *ctx, void *ptr, size_t new_size)
  426. {
  427. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  428. void *ptr2;
  429. ptr2 = alloc->realloc(alloc->ctx, ptr, new_size);
  430. if (ptr2 == NULL)
  431. return NULL;
  432. if (ptr != NULL) {
  433. /* an existing memory block has been resized */
  434. TABLES_LOCK();
  435. tracemalloc_remove_trace(ptr);
  436. if (tracemalloc_add_trace(ptr2, new_size) < 0) {
  437. /* Memory allocation failed. The error cannot be reported to
  438. the caller, because realloc() may already have shrinked the
  439. memory block and so removed bytes.
  440. This case is very unlikely: an hash entry has just been
  441. released, so the hash table should have at least one free entry.
  442. The GIL and the table lock ensures that only one thread is
  443. allocating memory. */
  444. assert(0 && "should never happen");
  445. }
  446. TABLES_UNLOCK();
  447. }
  448. else {
  449. /* new allocation */
  450. TABLES_LOCK();
  451. if (tracemalloc_add_trace(ptr2, new_size) < 0) {
  452. /* Failed to allocate a trace for the new memory block */
  453. TABLES_UNLOCK();
  454. alloc->free(alloc->ctx, ptr2);
  455. return NULL;
  456. }
  457. TABLES_UNLOCK();
  458. }
  459. return ptr2;
  460. }
  461. static void
  462. tracemalloc_free(void *ctx, void *ptr)
  463. {
  464. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  465. if (ptr == NULL)
  466. return;
  467. /* GIL cannot be locked in PyMem_RawFree() because it would introduce
  468. a deadlock in PyThreadState_DeleteCurrent(). */
  469. alloc->free(alloc->ctx, ptr);
  470. TABLES_LOCK();
  471. tracemalloc_remove_trace(ptr);
  472. TABLES_UNLOCK();
  473. }
  474. static void*
  475. tracemalloc_alloc_gil(int use_calloc, void *ctx, size_t nelem, size_t elsize)
  476. {
  477. void *ptr;
  478. if (get_reentrant()) {
  479. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  480. if (use_calloc)
  481. return alloc->calloc(alloc->ctx, nelem, elsize);
  482. else
  483. return alloc->malloc(alloc->ctx, nelem * elsize);
  484. }
  485. /* Ignore reentrant call. PyObjet_Malloc() calls PyMem_Malloc() for
  486. allocations larger than 512 bytes, don't trace the same memory
  487. allocation twice. */
  488. set_reentrant(1);
  489. ptr = tracemalloc_alloc(use_calloc, ctx, nelem, elsize);
  490. set_reentrant(0);
  491. return ptr;
  492. }
  493. static void*
  494. tracemalloc_malloc_gil(void *ctx, size_t size)
  495. {
  496. return tracemalloc_alloc_gil(0, ctx, 1, size);
  497. }
  498. static void*
  499. tracemalloc_calloc_gil(void *ctx, size_t nelem, size_t elsize)
  500. {
  501. return tracemalloc_alloc_gil(1, ctx, nelem, elsize);
  502. }
  503. static void*
  504. tracemalloc_realloc_gil(void *ctx, void *ptr, size_t new_size)
  505. {
  506. void *ptr2;
  507. if (get_reentrant()) {
  508. /* Reentrant call to PyMem_Realloc() and PyMem_RawRealloc().
  509. Example: PyMem_RawRealloc() is called internally by pymalloc
  510. (_PyObject_Malloc() and _PyObject_Realloc()) to allocate a new
  511. arena (new_arena()). */
  512. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  513. ptr2 = alloc->realloc(alloc->ctx, ptr, new_size);
  514. if (ptr2 != NULL && ptr != NULL) {
  515. TABLES_LOCK();
  516. tracemalloc_remove_trace(ptr);
  517. TABLES_UNLOCK();
  518. }
  519. return ptr2;
  520. }
  521. /* Ignore reentrant call. PyObjet_Realloc() calls PyMem_Realloc() for
  522. allocations larger than 512 bytes. Don't trace the same memory
  523. allocation twice. */
  524. set_reentrant(1);
  525. ptr2 = tracemalloc_realloc(ctx, ptr, new_size);
  526. set_reentrant(0);
  527. return ptr2;
  528. }
  529. #ifdef TRACE_RAW_MALLOC
  530. static void*
  531. tracemalloc_raw_alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize)
  532. {
  533. #ifdef WITH_THREAD
  534. PyGILState_STATE gil_state;
  535. #endif
  536. void *ptr;
  537. if (get_reentrant()) {
  538. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  539. if (use_calloc)
  540. return alloc->calloc(alloc->ctx, nelem, elsize);
  541. else
  542. return alloc->malloc(alloc->ctx, nelem * elsize);
  543. }
  544. /* Ignore reentrant call. PyGILState_Ensure() may call PyMem_RawMalloc()
  545. indirectly which would call PyGILState_Ensure() if reentrant are not
  546. disabled. */
  547. set_reentrant(1);
  548. #ifdef WITH_THREAD
  549. gil_state = PyGILState_Ensure();
  550. ptr = tracemalloc_alloc(use_calloc, ctx, nelem, elsize);
  551. PyGILState_Release(gil_state);
  552. #else
  553. ptr = tracemalloc_alloc(use_calloc, ctx, nelem, elsize);
  554. #endif
  555. set_reentrant(0);
  556. return ptr;
  557. }
  558. static void*
  559. tracemalloc_raw_malloc(void *ctx, size_t size)
  560. {
  561. return tracemalloc_raw_alloc(0, ctx, 1, size);
  562. }
  563. static void*
  564. tracemalloc_raw_calloc(void *ctx, size_t nelem, size_t elsize)
  565. {
  566. return tracemalloc_raw_alloc(1, ctx, nelem, elsize);
  567. }
  568. static void*
  569. tracemalloc_raw_realloc(void *ctx, void *ptr, size_t new_size)
  570. {
  571. #ifdef WITH_THREAD
  572. PyGILState_STATE gil_state;
  573. #endif
  574. void *ptr2;
  575. if (get_reentrant()) {
  576. /* Reentrant call to PyMem_RawRealloc(). */
  577. PyMemAllocatorEx *alloc = (PyMemAllocatorEx *)ctx;
  578. ptr2 = alloc->realloc(alloc->ctx, ptr, new_size);
  579. if (ptr2 != NULL && ptr != NULL) {
  580. TABLES_LOCK();
  581. tracemalloc_remove_trace(ptr);
  582. TABLES_UNLOCK();
  583. }
  584. return ptr2;
  585. }
  586. /* Ignore reentrant call. PyGILState_Ensure() may call PyMem_RawMalloc()
  587. indirectly which would call PyGILState_Ensure() if reentrant calls are
  588. not disabled. */
  589. set_reentrant(1);
  590. #ifdef WITH_THREAD
  591. gil_state = PyGILState_Ensure();
  592. ptr2 = tracemalloc_realloc(ctx, ptr, new_size);
  593. PyGILState_Release(gil_state);
  594. #else
  595. ptr2 = tracemalloc_realloc(ctx, ptr, new_size);
  596. #endif
  597. set_reentrant(0);
  598. return ptr2;
  599. }
  600. #endif /* TRACE_RAW_MALLOC */
  601. static int
  602. tracemalloc_clear_filename(_Py_hashtable_entry_t *entry, void *user_data)
  603. {
  604. PyObject *filename = (PyObject *)entry->key;
  605. Py_DECREF(filename);
  606. return 0;
  607. }
  608. static int
  609. traceback_free_traceback(_Py_hashtable_entry_t *entry, void *user_data)
  610. {
  611. traceback_t *traceback = (traceback_t *)entry->key;
  612. raw_free(traceback);
  613. return 0;
  614. }
  615. /* reentrant flag must be set to call this function and GIL must be held */
  616. static void
  617. tracemalloc_clear_traces(void)
  618. {
  619. #ifdef WITH_THREAD
  620. /* The GIL protects variables againt concurrent access */
  621. assert(PyGILState_Check());
  622. #endif
  623. /* Disable also reentrant calls to tracemalloc_malloc() to not add a new
  624. trace while we are clearing traces */
  625. assert(get_reentrant());
  626. TABLES_LOCK();
  627. _Py_hashtable_clear(tracemalloc_traces);
  628. tracemalloc_traced_memory = 0;
  629. tracemalloc_peak_traced_memory = 0;
  630. TABLES_UNLOCK();
  631. _Py_hashtable_foreach(tracemalloc_tracebacks, traceback_free_traceback, NULL);
  632. _Py_hashtable_clear(tracemalloc_tracebacks);
  633. _Py_hashtable_foreach(tracemalloc_filenames, tracemalloc_clear_filename, NULL);
  634. _Py_hashtable_clear(tracemalloc_filenames);
  635. }
  636. static int
  637. tracemalloc_init(void)
  638. {
  639. if (tracemalloc_config.initialized == TRACEMALLOC_FINALIZED) {
  640. PyErr_SetString(PyExc_RuntimeError,
  641. "the tracemalloc module has been unloaded");
  642. return -1;
  643. }
  644. if (tracemalloc_config.initialized == TRACEMALLOC_INITIALIZED)
  645. return 0;
  646. PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &allocators.raw);
  647. #ifdef REENTRANT_THREADLOCAL
  648. tracemalloc_reentrant_key = PyThread_create_key();
  649. if (tracemalloc_reentrant_key == -1) {
  650. #ifdef MS_WINDOWS
  651. PyErr_SetFromWindowsErr(0);
  652. #else
  653. PyErr_SetFromErrno(PyExc_OSError);
  654. #endif
  655. return -1;
  656. }
  657. #endif
  658. #if defined(WITH_THREAD) && defined(TRACE_RAW_MALLOC)
  659. if (tables_lock == NULL) {
  660. tables_lock = PyThread_allocate_lock();
  661. if (tables_lock == NULL) {
  662. PyErr_SetString(PyExc_RuntimeError, "cannot allocate lock");
  663. return -1;
  664. }
  665. }
  666. #endif
  667. tracemalloc_filenames = hashtable_new(0,
  668. (_Py_hashtable_hash_func)PyObject_Hash,
  669. hashtable_compare_unicode);
  670. tracemalloc_tracebacks = hashtable_new(0,
  671. (_Py_hashtable_hash_func)hashtable_hash_traceback,
  672. (_Py_hashtable_compare_func)hashtable_compare_traceback);
  673. tracemalloc_traces = hashtable_new(sizeof(trace_t),
  674. _Py_hashtable_hash_ptr,
  675. _Py_hashtable_compare_direct);
  676. if (tracemalloc_filenames == NULL || tracemalloc_tracebacks == NULL
  677. || tracemalloc_traces == NULL)
  678. {
  679. PyErr_NoMemory();
  680. return -1;
  681. }
  682. unknown_filename = PyUnicode_FromString("<unknown>");
  683. if (unknown_filename == NULL)
  684. return -1;
  685. PyUnicode_InternInPlace(&unknown_filename);
  686. tracemalloc_empty_traceback.nframe = 1;
  687. /* borrowed reference */
  688. tracemalloc_empty_traceback.frames[0].filename = unknown_filename;
  689. tracemalloc_empty_traceback.frames[0].lineno = 0;
  690. tracemalloc_empty_traceback.hash = traceback_hash(&tracemalloc_empty_traceback);
  691. /* Disable tracing allocations until hooks are installed. Set
  692. also the reentrant flag to detect bugs: fail with an assertion error
  693. if set_reentrant(1) is called while tracing is disabled. */
  694. set_reentrant(1);
  695. tracemalloc_config.initialized = TRACEMALLOC_INITIALIZED;
  696. return 0;
  697. }
  698. static void
  699. tracemalloc_deinit(void)
  700. {
  701. if (tracemalloc_config.initialized != TRACEMALLOC_INITIALIZED)
  702. return;
  703. tracemalloc_config.initialized = TRACEMALLOC_FINALIZED;
  704. tracemalloc_stop();
  705. /* destroy hash tables */
  706. _Py_hashtable_destroy(tracemalloc_traces);
  707. _Py_hashtable_destroy(tracemalloc_tracebacks);
  708. _Py_hashtable_destroy(tracemalloc_filenames);
  709. #if defined(WITH_THREAD) && defined(TRACE_RAW_MALLOC)
  710. if (tables_lock != NULL) {
  711. PyThread_free_lock(tables_lock);
  712. tables_lock = NULL;
  713. }
  714. #endif
  715. #ifdef REENTRANT_THREADLOCAL
  716. PyThread_delete_key(tracemalloc_reentrant_key);
  717. #endif
  718. Py_XDECREF(unknown_filename);
  719. }
  720. static int
  721. tracemalloc_start(int max_nframe)
  722. {
  723. PyMemAllocatorEx alloc;
  724. size_t size;
  725. if (tracemalloc_init() < 0)
  726. return -1;
  727. if (tracemalloc_config.tracing) {
  728. /* hook already installed: do nothing */
  729. return 0;
  730. }
  731. assert(1 <= max_nframe && max_nframe <= MAX_NFRAME);
  732. tracemalloc_config.max_nframe = max_nframe;
  733. /* allocate a buffer to store a new traceback */
  734. size = TRACEBACK_SIZE(max_nframe);
  735. assert(tracemalloc_traceback == NULL);
  736. tracemalloc_traceback = raw_malloc(size);
  737. if (tracemalloc_traceback == NULL) {
  738. PyErr_NoMemory();
  739. return -1;
  740. }
  741. #ifdef TRACE_RAW_MALLOC
  742. alloc.malloc = tracemalloc_raw_malloc;
  743. alloc.calloc = tracemalloc_raw_calloc;
  744. alloc.realloc = tracemalloc_raw_realloc;
  745. alloc.free = tracemalloc_free;
  746. alloc.ctx = &allocators.raw;
  747. PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &allocators.raw);
  748. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc);
  749. #endif
  750. alloc.malloc = tracemalloc_malloc_gil;
  751. alloc.calloc = tracemalloc_calloc_gil;
  752. alloc.realloc = tracemalloc_realloc_gil;
  753. alloc.free = tracemalloc_free;
  754. alloc.ctx = &allocators.mem;
  755. PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &allocators.mem);
  756. PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc);
  757. alloc.ctx = &allocators.obj;
  758. PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &allocators.obj);
  759. PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc);
  760. /* everything is ready: start tracing Python memory allocations */
  761. tracemalloc_config.tracing = 1;
  762. set_reentrant(0);
  763. return 0;
  764. }
  765. static void
  766. tracemalloc_stop(void)
  767. {
  768. if (!tracemalloc_config.tracing)
  769. return;
  770. /* stop tracing Python memory allocations */
  771. tracemalloc_config.tracing = 0;
  772. /* set the reentrant flag to detect bugs: fail with an assertion error if
  773. set_reentrant(1) is called while tracing is disabled. */
  774. set_reentrant(1);
  775. /* unregister the hook on memory allocators */
  776. #ifdef TRACE_RAW_MALLOC
  777. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &allocators.raw);
  778. #endif
  779. PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &allocators.mem);
  780. PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &allocators.obj);
  781. /* release memory */
  782. tracemalloc_clear_traces();
  783. raw_free(tracemalloc_traceback);
  784. tracemalloc_traceback = NULL;
  785. }
  786. static PyObject*
  787. lineno_as_obj(int lineno)
  788. {
  789. if (lineno >= 0)
  790. return PyLong_FromLong(lineno);
  791. else
  792. Py_RETURN_NONE;
  793. }
  794. PyDoc_STRVAR(tracemalloc_is_tracing_doc,
  795. "is_tracing()->bool\n"
  796. "\n"
  797. "True if the tracemalloc module is tracing Python memory allocations,\n"
  798. "False otherwise.");
  799. static PyObject*
  800. py_tracemalloc_is_tracing(PyObject *self)
  801. {
  802. return PyBool_FromLong(tracemalloc_config.tracing);
  803. }
  804. PyDoc_STRVAR(tracemalloc_clear_traces_doc,
  805. "clear_traces()\n"
  806. "\n"
  807. "Clear traces of memory blocks allocated by Python.");
  808. static PyObject*
  809. py_tracemalloc_clear_traces(PyObject *self)
  810. {
  811. if (!tracemalloc_config.tracing)
  812. Py_RETURN_NONE;
  813. set_reentrant(1);
  814. tracemalloc_clear_traces();
  815. set_reentrant(0);
  816. Py_RETURN_NONE;
  817. }
  818. static PyObject*
  819. frame_to_pyobject(frame_t *frame)
  820. {
  821. PyObject *frame_obj, *lineno_obj;
  822. frame_obj = PyTuple_New(2);
  823. if (frame_obj == NULL)
  824. return NULL;
  825. if (frame->filename == NULL)
  826. frame->filename = Py_None;
  827. Py_INCREF(frame->filename);
  828. PyTuple_SET_ITEM(frame_obj, 0, frame->filename);
  829. assert(frame->lineno >= 0);
  830. lineno_obj = lineno_as_obj(frame->lineno);
  831. if (lineno_obj == NULL) {
  832. Py_DECREF(frame_obj);
  833. return NULL;
  834. }
  835. PyTuple_SET_ITEM(frame_obj, 1, lineno_obj);
  836. return frame_obj;
  837. }
  838. static PyObject*
  839. traceback_to_pyobject(traceback_t *traceback, _Py_hashtable_t *intern_table)
  840. {
  841. int i;
  842. PyObject *frames, *frame;
  843. if (intern_table != NULL) {
  844. if (_Py_HASHTABLE_GET(intern_table, traceback, frames)) {
  845. Py_INCREF(frames);
  846. return frames;
  847. }
  848. }
  849. frames = PyTuple_New(traceback->nframe);
  850. if (frames == NULL)
  851. return NULL;
  852. for (i=0; i < traceback->nframe; i++) {
  853. frame = frame_to_pyobject(&traceback->frames[i]);
  854. if (frame == NULL) {
  855. Py_DECREF(frames);
  856. return NULL;
  857. }
  858. PyTuple_SET_ITEM(frames, i, frame);
  859. }
  860. if (intern_table != NULL) {
  861. if (_Py_HASHTABLE_SET(intern_table, traceback, frames) < 0) {
  862. Py_DECREF(frames);
  863. PyErr_NoMemory();
  864. return NULL;
  865. }
  866. /* intern_table keeps a new reference to frames */
  867. Py_INCREF(frames);
  868. }
  869. return frames;
  870. }
  871. static PyObject*
  872. trace_to_pyobject(trace_t *trace, _Py_hashtable_t *intern_tracebacks)
  873. {
  874. PyObject *trace_obj = NULL;
  875. PyObject *size, *traceback;
  876. trace_obj = PyTuple_New(2);
  877. if (trace_obj == NULL)
  878. return NULL;
  879. size = PyLong_FromSize_t(trace->size);
  880. if (size == NULL) {
  881. Py_DECREF(trace_obj);
  882. return NULL;
  883. }
  884. PyTuple_SET_ITEM(trace_obj, 0, size);
  885. traceback = traceback_to_pyobject(trace->traceback, intern_tracebacks);
  886. if (traceback == NULL) {
  887. Py_DECREF(trace_obj);
  888. return NULL;
  889. }
  890. PyTuple_SET_ITEM(trace_obj, 1, traceback);
  891. return trace_obj;
  892. }
  893. typedef struct {
  894. _Py_hashtable_t *traces;
  895. _Py_hashtable_t *tracebacks;
  896. PyObject *list;
  897. } get_traces_t;
  898. static int
  899. tracemalloc_get_traces_fill(_Py_hashtable_entry_t *entry, void *user_data)
  900. {
  901. get_traces_t *get_traces = user_data;
  902. trace_t *trace;
  903. PyObject *tracemalloc_obj;
  904. int res;
  905. trace = (trace_t *)_Py_HASHTABLE_ENTRY_DATA(entry);
  906. tracemalloc_obj = trace_to_pyobject(trace, get_traces->tracebacks);
  907. if (tracemalloc_obj == NULL)
  908. return 1;
  909. res = PyList_Append(get_traces->list, tracemalloc_obj);
  910. Py_DECREF(tracemalloc_obj);
  911. if (res < 0)
  912. return 1;
  913. return 0;
  914. }
  915. static int
  916. tracemalloc_pyobject_decref_cb(_Py_hashtable_entry_t *entry, void *user_data)
  917. {
  918. PyObject *obj = (PyObject *)_Py_HASHTABLE_ENTRY_DATA_AS_VOID_P(entry);
  919. Py_DECREF(obj);
  920. return 0;
  921. }
  922. PyDoc_STRVAR(tracemalloc_get_traces_doc,
  923. "_get_traces() -> list\n"
  924. "\n"
  925. "Get traces of all memory blocks allocated by Python.\n"
  926. "Return a list of (size: int, traceback: tuple) tuples.\n"
  927. "traceback is a tuple of (filename: str, lineno: int) tuples.\n"
  928. "\n"
  929. "Return an empty list if the tracemalloc module is disabled.");
  930. static PyObject*
  931. py_tracemalloc_get_traces(PyObject *self, PyObject *obj)
  932. {
  933. get_traces_t get_traces;
  934. int err;
  935. get_traces.traces = NULL;
  936. get_traces.tracebacks = NULL;
  937. get_traces.list = PyList_New(0);
  938. if (get_traces.list == NULL)
  939. goto error;
  940. if (!tracemalloc_config.tracing)
  941. return get_traces.list;
  942. /* the traceback hash table is used temporarily to intern traceback tuple
  943. of (filename, lineno) tuples */
  944. get_traces.tracebacks = hashtable_new(sizeof(PyObject *),
  945. _Py_hashtable_hash_ptr,
  946. _Py_hashtable_compare_direct);
  947. if (get_traces.tracebacks == NULL) {
  948. PyErr_NoMemory();
  949. goto error;
  950. }
  951. TABLES_LOCK();
  952. get_traces.traces = _Py_hashtable_copy(tracemalloc_traces);
  953. TABLES_UNLOCK();
  954. if (get_traces.traces == NULL) {
  955. PyErr_NoMemory();
  956. goto error;
  957. }
  958. set_reentrant(1);
  959. err = _Py_hashtable_foreach(get_traces.traces,
  960. tracemalloc_get_traces_fill, &get_traces);
  961. set_reentrant(0);
  962. if (err)
  963. goto error;
  964. goto finally;
  965. error:
  966. Py_CLEAR(get_traces.list);
  967. finally:
  968. if (get_traces.tracebacks != NULL) {
  969. _Py_hashtable_foreach(get_traces.tracebacks,
  970. tracemalloc_pyobject_decref_cb, NULL);
  971. _Py_hashtable_destroy(get_traces.tracebacks);
  972. }
  973. if (get_traces.traces != NULL)
  974. _Py_hashtable_destroy(get_traces.traces);
  975. return get_traces.list;
  976. }
  977. PyDoc_STRVAR(tracemalloc_get_object_traceback_doc,
  978. "_get_object_traceback(obj)\n"
  979. "\n"
  980. "Get the traceback where the Python object obj was allocated.\n"
  981. "Return a tuple of (filename: str, lineno: int) tuples.\n"
  982. "\n"
  983. "Return None if the tracemalloc module is disabled or did not\n"
  984. "trace the allocation of the object.");
  985. static PyObject*
  986. py_tracemalloc_get_object_traceback(PyObject *self, PyObject *obj)
  987. {
  988. PyTypeObject *type;
  989. void *ptr;
  990. trace_t trace;
  991. int found;
  992. if (!tracemalloc_config.tracing)
  993. Py_RETURN_NONE;
  994. type = Py_TYPE(obj);
  995. if (PyType_IS_GC(type))
  996. ptr = (void *)((char *)obj - sizeof(PyGC_Head));
  997. else
  998. ptr = (void *)obj;
  999. TABLES_LOCK();
  1000. found = _Py_HASHTABLE_GET(tracemalloc_traces, ptr, trace);
  1001. TABLES_UNLOCK();
  1002. if (!found)
  1003. Py_RETURN_NONE;
  1004. return traceback_to_pyobject(trace.traceback, NULL);
  1005. }
  1006. PyDoc_STRVAR(tracemalloc_start_doc,
  1007. "start(nframe: int=1)\n"
  1008. "\n"
  1009. "Start tracing Python memory allocations. Set also the maximum number \n"
  1010. "of frames stored in the traceback of a trace to nframe.");
  1011. static PyObject*
  1012. py_tracemalloc_start(PyObject *self, PyObject *args)
  1013. {
  1014. Py_ssize_t nframe = 1;
  1015. int nframe_int;
  1016. if (!PyArg_ParseTuple(args, "|n:start", &nframe))
  1017. return NULL;
  1018. if (nframe < 1 || nframe > MAX_NFRAME) {
  1019. PyErr_Format(PyExc_ValueError,
  1020. "the number of frames must be in range [1; %i]",
  1021. MAX_NFRAME);
  1022. return NULL;
  1023. }
  1024. nframe_int = Py_SAFE_DOWNCAST(nframe, Py_ssize_t, int);
  1025. if (tracemalloc_start(nframe_int) < 0)
  1026. return NULL;
  1027. Py_RETURN_NONE;
  1028. }
  1029. PyDoc_STRVAR(tracemalloc_stop_doc,
  1030. "stop()\n"
  1031. "\n"
  1032. "Stop tracing Python memory allocations and clear traces\n"
  1033. "of memory blocks allocated by Python.");
  1034. static PyObject*
  1035. py_tracemalloc_stop(PyObject *self)
  1036. {
  1037. tracemalloc_stop();
  1038. Py_RETURN_NONE;
  1039. }
  1040. PyDoc_STRVAR(tracemalloc_get_traceback_limit_doc,
  1041. "get_traceback_limit() -> int\n"
  1042. "\n"
  1043. "Get the maximum number of frames stored in the traceback\n"
  1044. "of a trace.\n"
  1045. "\n"
  1046. "By default, a trace of an allocated memory block only stores\n"
  1047. "the most recent frame: the limit is 1.");
  1048. static PyObject*
  1049. py_tracemalloc_get_traceback_limit(PyObject *self)
  1050. {
  1051. return PyLong_FromLong(tracemalloc_config.max_nframe);
  1052. }
  1053. PyDoc_STRVAR(tracemalloc_get_tracemalloc_memory_doc,
  1054. "get_tracemalloc_memory() -> int\n"
  1055. "\n"
  1056. "Get the memory usage in bytes of the tracemalloc module\n"
  1057. "used internally to trace memory allocations.");
  1058. static PyObject*
  1059. tracemalloc_get_tracemalloc_memory(PyObject *self)
  1060. {
  1061. size_t size;
  1062. PyObject *size_obj;
  1063. size = _Py_hashtable_size(tracemalloc_tracebacks);
  1064. size += _Py_hashtable_size(tracemalloc_filenames);
  1065. TABLES_LOCK();
  1066. size += _Py_hashtable_size(tracemalloc_traces);
  1067. TABLES_UNLOCK();
  1068. size_obj = PyLong_FromSize_t(size);
  1069. return Py_BuildValue("N", size_obj);
  1070. }
  1071. PyDoc_STRVAR(tracemalloc_get_traced_memory_doc,
  1072. "get_traced_memory() -> (int, int)\n"
  1073. "\n"
  1074. "Get the current size and peak size of memory blocks traced\n"
  1075. "by the tracemalloc module as a tuple: (current: int, peak: int).");
  1076. static PyObject*
  1077. tracemalloc_get_traced_memory(PyObject *self)
  1078. {
  1079. Py_ssize_t size, peak_size;
  1080. PyObject *size_obj, *peak_size_obj;
  1081. if (!tracemalloc_config.tracing)
  1082. return Py_BuildValue("ii", 0, 0);
  1083. TABLES_LOCK();
  1084. size = tracemalloc_traced_memory;
  1085. peak_size = tracemalloc_peak_traced_memory;
  1086. TABLES_UNLOCK();
  1087. size_obj = PyLong_FromSize_t(size);
  1088. peak_size_obj = PyLong_FromSize_t(peak_size);
  1089. return Py_BuildValue("NN", size_obj, peak_size_obj);
  1090. }
  1091. static PyMethodDef module_methods[] = {
  1092. {"is_tracing", (PyCFunction)py_tracemalloc_is_tracing,
  1093. METH_NOARGS, tracemalloc_is_tracing_doc},
  1094. {"clear_traces", (PyCFunction)py_tracemalloc_clear_traces,
  1095. METH_NOARGS, tracemalloc_clear_traces_doc},
  1096. {"_get_traces", (PyCFunction)py_tracemalloc_get_traces,
  1097. METH_NOARGS, tracemalloc_get_traces_doc},
  1098. {"_get_object_traceback", (PyCFunction)py_tracemalloc_get_object_traceback,
  1099. METH_O, tracemalloc_get_object_traceback_doc},
  1100. {"start", (PyCFunction)py_tracemalloc_start,
  1101. METH_VARARGS, tracemalloc_start_doc},
  1102. {"stop", (PyCFunction)py_tracemalloc_stop,
  1103. METH_NOARGS, tracemalloc_stop_doc},
  1104. {"get_traceback_limit", (PyCFunction)py_tracemalloc_get_traceback_limit,
  1105. METH_NOARGS, tracemalloc_get_traceback_limit_doc},
  1106. {"get_tracemalloc_memory", (PyCFunction)tracemalloc_get_tracemalloc_memory,
  1107. METH_NOARGS, tracemalloc_get_tracemalloc_memory_doc},
  1108. {"get_traced_memory", (PyCFunction)tracemalloc_get_traced_memory,
  1109. METH_NOARGS, tracemalloc_get_traced_memory_doc},
  1110. /* sentinel */
  1111. {NULL, NULL}
  1112. };
  1113. PyDoc_STRVAR(module_doc,
  1114. "Debug module to trace memory blocks allocated by Python.");
  1115. static struct PyModuleDef module_def = {
  1116. PyModuleDef_HEAD_INIT,
  1117. "_tracemalloc",
  1118. module_doc,
  1119. 0, /* non-negative size to be able to unload the module */
  1120. module_methods,
  1121. NULL,
  1122. };
  1123. PyMODINIT_FUNC
  1124. PyInit__tracemalloc(void)
  1125. {
  1126. PyObject *m;
  1127. m = PyModule_Create(&module_def);
  1128. if (m == NULL)
  1129. return NULL;
  1130. if (tracemalloc_init() < 0)
  1131. return NULL;
  1132. return m;
  1133. }
  1134. static int
  1135. parse_sys_xoptions(PyObject *value)
  1136. {
  1137. PyObject *valuelong;
  1138. long nframe;
  1139. if (value == Py_True)
  1140. return 1;
  1141. assert(PyUnicode_Check(value));
  1142. if (PyUnicode_GetLength(value) == 0)
  1143. return -1;
  1144. valuelong = PyLong_FromUnicodeObject(value, 10);
  1145. if (valuelong == NULL)
  1146. return -1;
  1147. nframe = PyLong_AsLong(valuelong);
  1148. Py_DECREF(valuelong);
  1149. if (nframe == -1 && PyErr_Occurred())
  1150. return -1;
  1151. if (nframe < 1 || nframe > MAX_NFRAME)
  1152. return -1;
  1153. return Py_SAFE_DOWNCAST(nframe, long, int);
  1154. }
  1155. int
  1156. _PyTraceMalloc_Init(void)
  1157. {
  1158. char *p;
  1159. int nframe;
  1160. #ifdef WITH_THREAD
  1161. assert(PyGILState_Check());
  1162. #endif
  1163. if ((p = Py_GETENV("PYTHONTRACEMALLOC")) && *p != '\0') {
  1164. char *endptr = p;
  1165. long value;
  1166. errno = 0;
  1167. value = strtol(p, &endptr, 10);
  1168. if (*endptr != '\0'
  1169. || value < 1
  1170. || value > MAX_NFRAME
  1171. || errno == ERANGE)
  1172. {
  1173. Py_FatalError("PYTHONTRACEMALLOC: invalid number of frames");
  1174. return -1;
  1175. }
  1176. nframe = (int)value;
  1177. }
  1178. else {
  1179. PyObject *xoptions, *key, *value;
  1180. xoptions = PySys_GetXOptions();
  1181. if (xoptions == NULL)
  1182. return -1;
  1183. key = PyUnicode_FromString("tracemalloc");
  1184. if (key == NULL)
  1185. return -1;
  1186. value = PyDict_GetItemWithError(xoptions, key);
  1187. Py_DECREF(key);
  1188. if (value == NULL) {
  1189. if (PyErr_Occurred())
  1190. return -1;
  1191. /* -X tracemalloc is not used */
  1192. return 0;
  1193. }
  1194. nframe = parse_sys_xoptions(value);
  1195. Py_DECREF(value);
  1196. if (nframe < 0) {
  1197. Py_FatalError("-X tracemalloc=NFRAME: invalid number of frames");
  1198. }
  1199. }
  1200. return tracemalloc_start(nframe);
  1201. }
  1202. void
  1203. _PyTraceMalloc_Fini(void)
  1204. {
  1205. #ifdef WITH_THREAD
  1206. assert(PyGILState_Check());
  1207. #endif
  1208. tracemalloc_deinit();
  1209. }