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.

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