PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/obmalloc.c

http://unladen-swallow.googlecode.com/
C | 1765 lines | 854 code | 178 blank | 733 comment | 200 complexity | 25e3cb94ae75a45a8cdcc27df47330d6 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. #include "Python.h"
  2. #ifdef WITH_PYMALLOC
  3. /* An object allocator for Python.
  4. Here is an introduction to the layers of the Python memory architecture,
  5. showing where the object allocator is actually used (layer +2), It is
  6. called for every object allocation and deallocation (PyObject_New/Del),
  7. unless the object-specific allocators implement a proprietary allocation
  8. scheme (ex.: ints use a simple free list). This is also the place where
  9. the cyclic garbage collector operates selectively on container objects.
  10. Object-specific allocators
  11. _____ ______ ______ ________
  12. [ int ] [ dict ] [ list ] ... [ string ] Python core |
  13. +3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
  14. _______________________________ | |
  15. [ Python's object allocator ] | |
  16. +2 | ####### Object memory ####### | <------ Internal buffers ------> |
  17. ______________________________________________________________ |
  18. [ Python's raw memory allocator (PyMem_ API) ] |
  19. +1 | <----- Python memory (under PyMem manager's control) ------> | |
  20. __________________________________________________________________
  21. [ Underlying general-purpose allocator (ex: C library malloc) ]
  22. 0 | <------ Virtual memory allocated for the python process -------> |
  23. =========================================================================
  24. _______________________________________________________________________
  25. [ OS-specific Virtual Memory Manager (VMM) ]
  26. -1 | <--- Kernel dynamic storage allocation & management (page-based) ---> |
  27. __________________________________ __________________________________
  28. [ ] [ ]
  29. -2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> |
  30. */
  31. /*==========================================================================*/
  32. /* A fast, special-purpose memory allocator for small blocks, to be used
  33. on top of a general-purpose malloc -- heavily based on previous art. */
  34. /* Vladimir Marangozov -- August 2000 */
  35. /*
  36. * "Memory management is where the rubber meets the road -- if we do the wrong
  37. * thing at any level, the results will not be good. And if we don't make the
  38. * levels work well together, we are in serious trouble." (1)
  39. *
  40. * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles,
  41. * "Dynamic Storage Allocation: A Survey and Critical Review",
  42. * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
  43. */
  44. /* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
  45. /*==========================================================================*/
  46. /*
  47. * Allocation strategy abstract:
  48. *
  49. * For small requests, the allocator sub-allocates <Big> blocks of memory.
  50. * Requests greater than 256 bytes are routed to the system's allocator.
  51. *
  52. * Small requests are grouped in size classes spaced 8 bytes apart, due
  53. * to the required valid alignment of the returned address. Requests of
  54. * a particular size are serviced from memory pools of 4K (one VMM page).
  55. * Pools are fragmented on demand and contain free lists of blocks of one
  56. * particular size class. In other words, there is a fixed-size allocator
  57. * for each size class. Free pools are shared by the different allocators
  58. * thus minimizing the space reserved for a particular size class.
  59. *
  60. * This allocation strategy is a variant of what is known as "simple
  61. * segregated storage based on array of free lists". The main drawback of
  62. * simple segregated storage is that we might end up with lot of reserved
  63. * memory for the different free lists, which degenerate in time. To avoid
  64. * this, we partition each free list in pools and we share dynamically the
  65. * reserved space between all free lists. This technique is quite efficient
  66. * for memory intensive programs which allocate mainly small-sized blocks.
  67. *
  68. * For small requests we have the following table:
  69. *
  70. * Request in bytes Size of allocated block Size class idx
  71. * ----------------------------------------------------------------
  72. * 1-8 8 0
  73. * 9-16 16 1
  74. * 17-24 24 2
  75. * 25-32 32 3
  76. * 33-40 40 4
  77. * 41-48 48 5
  78. * 49-56 56 6
  79. * 57-64 64 7
  80. * 65-72 72 8
  81. * ... ... ...
  82. * 241-248 248 30
  83. * 249-256 256 31
  84. *
  85. * 0, 257 and up: routed to the underlying allocator.
  86. */
  87. /*==========================================================================*/
  88. /*
  89. * -- Main tunable settings section --
  90. */
  91. /*
  92. * Alignment of addresses returned to the user. 8-bytes alignment works
  93. * on most current architectures (with 32-bit or 64-bit address busses).
  94. * The alignment value is also used for grouping small requests in size
  95. * classes spaced ALIGNMENT bytes apart.
  96. *
  97. * You shouldn't change this unless you know what you are doing.
  98. */
  99. #define ALIGNMENT 8 /* must be 2^N */
  100. #define ALIGNMENT_SHIFT 3
  101. #define ALIGNMENT_MASK (ALIGNMENT - 1)
  102. /* Return the number of bytes in size class I, as a uint. */
  103. #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
  104. /*
  105. * Max size threshold below which malloc requests are considered to be
  106. * small enough in order to use preallocated memory pools. You can tune
  107. * this value according to your application behaviour and memory needs.
  108. *
  109. * The following invariants must hold:
  110. * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256
  111. * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
  112. *
  113. * Although not required, for better performance and space efficiency,
  114. * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
  115. */
  116. #define SMALL_REQUEST_THRESHOLD 256
  117. #define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
  118. /*
  119. * The system's VMM page size can be obtained on most unices with a
  120. * getpagesize() call or deduced from various header files. To make
  121. * things simpler, we assume that it is 4K, which is OK for most systems.
  122. * It is probably better if this is the native page size, but it doesn't
  123. * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page
  124. * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation
  125. * violation fault. 4K is apparently OK for all the platforms that python
  126. * currently targets.
  127. */
  128. #define SYSTEM_PAGE_SIZE (4 * 1024)
  129. #define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
  130. /*
  131. * Maximum amount of memory managed by the allocator for small requests.
  132. */
  133. #ifdef WITH_MEMORY_LIMITS
  134. #ifndef SMALL_MEMORY_LIMIT
  135. #define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
  136. #endif
  137. #endif
  138. /*
  139. * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned
  140. * on a page boundary. This is a reserved virtual address space for the
  141. * current process (obtained through a malloc call). In no way this means
  142. * that the memory arenas will be used entirely. A malloc(<Big>) is usually
  143. * an address range reservation for <Big> bytes, unless all pages within this
  144. * space are referenced subsequently. So malloc'ing big blocks and not using
  145. * them does not mean "wasting memory". It's an addressable range wastage...
  146. *
  147. * Therefore, allocating arenas with malloc is not optimal, because there is
  148. * some address space wastage, but this is the most portable way to request
  149. * memory from the system across various platforms.
  150. */
  151. #define ARENA_SIZE (256 << 10) /* 256KB */
  152. #ifdef WITH_MEMORY_LIMITS
  153. #define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
  154. #endif
  155. /*
  156. * Size of the pools used for small blocks. Should be a power of 2,
  157. * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
  158. */
  159. #define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
  160. #define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
  161. /*
  162. * -- End of tunable settings section --
  163. */
  164. /*==========================================================================*/
  165. /*
  166. * Locking
  167. *
  168. * To reduce lock contention, it would probably be better to refine the
  169. * crude function locking with per size class locking. I'm not positive
  170. * however, whether it's worth switching to such locking policy because
  171. * of the performance penalty it might introduce.
  172. *
  173. * The following macros describe the simplest (should also be the fastest)
  174. * lock object on a particular platform and the init/fini/lock/unlock
  175. * operations on it. The locks defined here are not expected to be recursive
  176. * because it is assumed that they will always be called in the order:
  177. * INIT, [LOCK, UNLOCK]*, FINI.
  178. */
  179. /*
  180. * Python's threads are serialized, so object malloc locking is disabled.
  181. */
  182. #define SIMPLELOCK_DECL(lock) /* simple lock declaration */
  183. #define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
  184. #define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
  185. #define SIMPLELOCK_LOCK(lock) /* acquire released lock */
  186. #define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
  187. /*
  188. * Basic types
  189. * I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
  190. */
  191. #undef uchar
  192. #define uchar unsigned char /* assuming == 8 bits */
  193. #undef uint
  194. #define uint unsigned int /* assuming >= 16 bits */
  195. #undef ulong
  196. #define ulong unsigned long /* assuming >= 32 bits */
  197. #undef uptr
  198. #define uptr Py_uintptr_t
  199. /* When you say memory, my mind reasons in terms of (pointers to) blocks */
  200. typedef uchar block;
  201. /* Pool for small blocks. */
  202. struct pool_header {
  203. union { block *_padding;
  204. uint count; } ref; /* number of allocated blocks */
  205. block *freeblock; /* pool's free list head */
  206. struct pool_header *nextpool; /* next pool of this size class */
  207. struct pool_header *prevpool; /* previous pool "" */
  208. uint arenaindex; /* index into arenas of base adr */
  209. uint szidx; /* block size class index */
  210. uint nextoffset; /* bytes to virgin block */
  211. uint maxnextoffset; /* largest valid nextoffset */
  212. };
  213. typedef struct pool_header *poolp;
  214. /* Record keeping for arenas. */
  215. struct arena_object {
  216. /* The address of the arena, as returned by malloc. Note that 0
  217. * will never be returned by a successful malloc, and is used
  218. * here to mark an arena_object that doesn't correspond to an
  219. * allocated arena.
  220. */
  221. uptr address;
  222. /* Pool-aligned pointer to the next pool to be carved off. */
  223. block* pool_address;
  224. /* The number of available pools in the arena: free pools + never-
  225. * allocated pools.
  226. */
  227. uint nfreepools;
  228. /* The total number of pools in the arena, whether or not available. */
  229. uint ntotalpools;
  230. /* Singly-linked list of available pools. */
  231. struct pool_header* freepools;
  232. /* Whenever this arena_object is not associated with an allocated
  233. * arena, the nextarena member is used to link all unassociated
  234. * arena_objects in the singly-linked `unused_arena_objects` list.
  235. * The prevarena member is unused in this case.
  236. *
  237. * When this arena_object is associated with an allocated arena
  238. * with at least one available pool, both members are used in the
  239. * doubly-linked `usable_arenas` list, which is maintained in
  240. * increasing order of `nfreepools` values.
  241. *
  242. * Else this arena_object is associated with an allocated arena
  243. * all of whose pools are in use. `nextarena` and `prevarena`
  244. * are both meaningless in this case.
  245. */
  246. struct arena_object* nextarena;
  247. struct arena_object* prevarena;
  248. };
  249. #undef ROUNDUP
  250. #define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
  251. #define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
  252. #define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
  253. /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
  254. #define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
  255. /* Return total number of blocks in pool of size index I, as a uint. */
  256. #define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
  257. /*==========================================================================*/
  258. /*
  259. * This malloc lock
  260. */
  261. SIMPLELOCK_DECL(_malloc_lock)
  262. #define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
  263. #define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
  264. #define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
  265. #define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
  266. /*
  267. * Pool table -- headed, circular, doubly-linked lists of partially used pools.
  268. This is involved. For an index i, usedpools[i+i] is the header for a list of
  269. all partially used pools holding small blocks with "size class idx" i. So
  270. usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size
  271. 16, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT.
  272. Pools are carved off an arena's highwater mark (an arena_object's pool_address
  273. member) as needed. Once carved off, a pool is in one of three states forever
  274. after:
  275. used == partially used, neither empty nor full
  276. At least one block in the pool is currently allocated, and at least one
  277. block in the pool is not currently allocated (note this implies a pool
  278. has room for at least two blocks).
  279. This is a pool's initial state, as a pool is created only when malloc
  280. needs space.
  281. The pool holds blocks of a fixed size, and is in the circular list headed
  282. at usedpools[i] (see above). It's linked to the other used pools of the
  283. same size class via the pool_header's nextpool and prevpool members.
  284. If all but one block is currently allocated, a malloc can cause a
  285. transition to the full state. If all but one block is not currently
  286. allocated, a free can cause a transition to the empty state.
  287. full == all the pool's blocks are currently allocated
  288. On transition to full, a pool is unlinked from its usedpools[] list.
  289. It's not linked to from anything then anymore, and its nextpool and
  290. prevpool members are meaningless until it transitions back to used.
  291. A free of a block in a full pool puts the pool back in the used state.
  292. Then it's linked in at the front of the appropriate usedpools[] list, so
  293. that the next allocation for its size class will reuse the freed block.
  294. empty == all the pool's blocks are currently available for allocation
  295. On transition to empty, a pool is unlinked from its usedpools[] list,
  296. and linked to the front of its arena_object's singly-linked freepools list,
  297. via its nextpool member. The prevpool member has no meaning in this case.
  298. Empty pools have no inherent size class: the next time a malloc finds
  299. an empty list in usedpools[], it takes the first pool off of freepools.
  300. If the size class needed happens to be the same as the size class the pool
  301. last had, some pool initialization can be skipped.
  302. Block Management
  303. Blocks within pools are again carved out as needed. pool->freeblock points to
  304. the start of a singly-linked list of free blocks within the pool. When a
  305. block is freed, it's inserted at the front of its pool's freeblock list. Note
  306. that the available blocks in a pool are *not* linked all together when a pool
  307. is initialized. Instead only "the first two" (lowest addresses) blocks are
  308. set up, returning the first such block, and setting pool->freeblock to a
  309. one-block list holding the second such block. This is consistent with that
  310. pymalloc strives at all levels (arena, pool, and block) never to touch a piece
  311. of memory until it's actually needed.
  312. So long as a pool is in the used state, we're certain there *is* a block
  313. available for allocating, and pool->freeblock is not NULL. If pool->freeblock
  314. points to the end of the free list before we've carved the entire pool into
  315. blocks, that means we simply haven't yet gotten to one of the higher-address
  316. blocks. The offset from the pool_header to the start of "the next" virgin
  317. block is stored in the pool_header nextoffset member, and the largest value
  318. of nextoffset that makes sense is stored in the maxnextoffset member when a
  319. pool is initialized. All the blocks in a pool have been passed out at least
  320. once when and only when nextoffset > maxnextoffset.
  321. Major obscurity: While the usedpools vector is declared to have poolp
  322. entries, it doesn't really. It really contains two pointers per (conceptual)
  323. poolp entry, the nextpool and prevpool members of a pool_header. The
  324. excruciating initialization code below fools C so that
  325. usedpool[i+i]
  326. "acts like" a genuine poolp, but only so long as you only reference its
  327. nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
  328. compensating for that a pool_header's nextpool and prevpool members
  329. immediately follow a pool_header's first two members:
  330. union { block *_padding;
  331. uint count; } ref;
  332. block *freeblock;
  333. each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
  334. contains is a fudged-up pointer p such that *if* C believes it's a poolp
  335. pointer, then p->nextpool and p->prevpool are both p (meaning that the headed
  336. circular list is empty).
  337. It's unclear why the usedpools setup is so convoluted. It could be to
  338. minimize the amount of cache required to hold this heavily-referenced table
  339. (which only *needs* the two interpool pointer members of a pool_header). OTOH,
  340. referencing code has to remember to "double the index" and doing so isn't
  341. free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying
  342. on that C doesn't insert any padding anywhere in a pool_header at or before
  343. the prevpool member.
  344. **************************************************************************** */
  345. #define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
  346. #define PT(x) PTA(x), PTA(x)
  347. static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
  348. PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
  349. #if NB_SMALL_SIZE_CLASSES > 8
  350. , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
  351. #if NB_SMALL_SIZE_CLASSES > 16
  352. , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
  353. #if NB_SMALL_SIZE_CLASSES > 24
  354. , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
  355. #if NB_SMALL_SIZE_CLASSES > 32
  356. , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
  357. #if NB_SMALL_SIZE_CLASSES > 40
  358. , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
  359. #if NB_SMALL_SIZE_CLASSES > 48
  360. , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
  361. #if NB_SMALL_SIZE_CLASSES > 56
  362. , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
  363. #endif /* NB_SMALL_SIZE_CLASSES > 56 */
  364. #endif /* NB_SMALL_SIZE_CLASSES > 48 */
  365. #endif /* NB_SMALL_SIZE_CLASSES > 40 */
  366. #endif /* NB_SMALL_SIZE_CLASSES > 32 */
  367. #endif /* NB_SMALL_SIZE_CLASSES > 24 */
  368. #endif /* NB_SMALL_SIZE_CLASSES > 16 */
  369. #endif /* NB_SMALL_SIZE_CLASSES > 8 */
  370. };
  371. /*==========================================================================
  372. Arena management.
  373. `arenas` is a vector of arena_objects. It contains maxarenas entries, some of
  374. which may not be currently used (== they're arena_objects that aren't
  375. currently associated with an allocated arena). Note that arenas proper are
  376. separately malloc'ed.
  377. Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5,
  378. we do try to free() arenas, and use some mild heuristic strategies to increase
  379. the likelihood that arenas eventually can be freed.
  380. unused_arena_objects
  381. This is a singly-linked list of the arena_objects that are currently not
  382. being used (no arena is associated with them). Objects are taken off the
  383. head of the list in new_arena(), and are pushed on the head of the list in
  384. PyObject_Free() when the arena is empty. Key invariant: an arena_object
  385. is on this list if and only if its .address member is 0.
  386. usable_arenas
  387. This is a doubly-linked list of the arena_objects associated with arenas
  388. that have pools available. These pools are either waiting to be reused,
  389. or have not been used before. The list is sorted to have the most-
  390. allocated arenas first (ascending order based on the nfreepools member).
  391. This means that the next allocation will come from a heavily used arena,
  392. which gives the nearly empty arenas a chance to be returned to the system.
  393. In my unscientific tests this dramatically improved the number of arenas
  394. that could be freed.
  395. Note that an arena_object associated with an arena all of whose pools are
  396. currently in use isn't on either list.
  397. */
  398. /* Array of objects used to track chunks of memory (arenas). */
  399. static struct arena_object* arenas = NULL;
  400. /* Number of slots currently allocated in the `arenas` vector. */
  401. static uint maxarenas = 0;
  402. /* The head of the singly-linked, NULL-terminated list of available
  403. * arena_objects.
  404. */
  405. static struct arena_object* unused_arena_objects = NULL;
  406. /* The head of the doubly-linked, NULL-terminated at each end, list of
  407. * arena_objects associated with arenas that have pools available.
  408. */
  409. static struct arena_object* usable_arenas = NULL;
  410. /* How many arena_objects do we initially allocate?
  411. * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the
  412. * `arenas` vector.
  413. */
  414. #define INITIAL_ARENA_OBJECTS 16
  415. /* Number of arenas allocated that haven't been free()'d. */
  416. static size_t narenas_currently_allocated = 0;
  417. #ifdef PYMALLOC_DEBUG
  418. /* Total number of times malloc() called to allocate an arena. */
  419. static size_t ntimes_arena_allocated = 0;
  420. /* High water mark (max value ever seen) for narenas_currently_allocated. */
  421. static size_t narenas_highwater = 0;
  422. #endif
  423. /* Allocate a new arena. If we run out of memory, return NULL. Else
  424. * allocate a new arena, and return the address of an arena_object
  425. * describing the new arena. It's expected that the caller will set
  426. * `usable_arenas` to the return value.
  427. */
  428. static struct arena_object*
  429. new_arena(void)
  430. {
  431. struct arena_object* arenaobj;
  432. uint excess; /* number of bytes above pool alignment */
  433. #ifdef PYMALLOC_DEBUG
  434. if (Py_GETENV("PYTHONMALLOCSTATS"))
  435. _PyObject_DebugMallocStats();
  436. #endif
  437. if (unused_arena_objects == NULL) {
  438. uint i;
  439. uint numarenas;
  440. size_t nbytes;
  441. /* Double the number of arena objects on each allocation.
  442. * Note that it's possible for `numarenas` to overflow.
  443. */
  444. numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
  445. if (numarenas <= maxarenas)
  446. return NULL; /* overflow */
  447. #if SIZEOF_SIZE_T <= SIZEOF_INT
  448. if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
  449. return NULL; /* overflow */
  450. #endif
  451. nbytes = numarenas * sizeof(*arenas);
  452. arenaobj = (struct arena_object *)realloc(arenas, nbytes);
  453. if (arenaobj == NULL)
  454. return NULL;
  455. arenas = arenaobj;
  456. /* We might need to fix pointers that were copied. However,
  457. * new_arena only gets called when all the pages in the
  458. * previous arenas are full. Thus, there are *no* pointers
  459. * into the old array. Thus, we don't have to worry about
  460. * invalid pointers. Just to be sure, some asserts:
  461. */
  462. assert(usable_arenas == NULL);
  463. assert(unused_arena_objects == NULL);
  464. /* Put the new arenas on the unused_arena_objects list. */
  465. for (i = maxarenas; i < numarenas; ++i) {
  466. arenas[i].address = 0; /* mark as unassociated */
  467. arenas[i].nextarena = i < numarenas - 1 ?
  468. &arenas[i+1] : NULL;
  469. }
  470. /* Update globals. */
  471. unused_arena_objects = &arenas[maxarenas];
  472. maxarenas = numarenas;
  473. }
  474. /* Take the next available arena object off the head of the list. */
  475. assert(unused_arena_objects != NULL);
  476. arenaobj = unused_arena_objects;
  477. unused_arena_objects = arenaobj->nextarena;
  478. assert(arenaobj->address == 0);
  479. arenaobj->address = (uptr)malloc(ARENA_SIZE);
  480. if (arenaobj->address == 0) {
  481. /* The allocation failed: return NULL after putting the
  482. * arenaobj back.
  483. */
  484. arenaobj->nextarena = unused_arena_objects;
  485. unused_arena_objects = arenaobj;
  486. return NULL;
  487. }
  488. ++narenas_currently_allocated;
  489. #ifdef PYMALLOC_DEBUG
  490. ++ntimes_arena_allocated;
  491. if (narenas_currently_allocated > narenas_highwater)
  492. narenas_highwater = narenas_currently_allocated;
  493. #endif
  494. arenaobj->freepools = NULL;
  495. /* pool_address <- first pool-aligned address in the arena
  496. nfreepools <- number of whole pools that fit after alignment */
  497. arenaobj->pool_address = (block*)arenaobj->address;
  498. arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
  499. assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
  500. excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
  501. if (excess != 0) {
  502. --arenaobj->nfreepools;
  503. arenaobj->pool_address += POOL_SIZE - excess;
  504. }
  505. arenaobj->ntotalpools = arenaobj->nfreepools;
  506. return arenaobj;
  507. }
  508. /*
  509. Py_ADDRESS_IN_RANGE(P, POOL)
  510. Return true if and only if P is an address that was allocated by pymalloc.
  511. POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P)
  512. (the caller is asked to compute this because the macro expands POOL more than
  513. once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a
  514. variable and pass the latter to the macro; because Py_ADDRESS_IN_RANGE is
  515. called on every alloc/realloc/free, micro-efficiency is important here).
  516. Tricky: Let B be the arena base address associated with the pool, B =
  517. arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
  518. B <= P < B + ARENA_SIZE
  519. Subtracting B throughout, this is true iff
  520. 0 <= P-B < ARENA_SIZE
  521. By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
  522. Obscure: A PyMem "free memory" function can call the pymalloc free or realloc
  523. before the first arena has been allocated. `arenas` is still NULL in that
  524. case. We're relying on that maxarenas is also 0 in that case, so that
  525. (POOL)->arenaindex < maxarenas must be false, saving us from trying to index
  526. into a NULL arenas.
  527. Details: given P and POOL, the arena_object corresponding to P is AO =
  528. arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild
  529. stores, etc), POOL is the correct address of P's pool, AO.address is the
  530. correct base address of the pool's arena, and P must be within ARENA_SIZE of
  531. AO.address. In addition, AO.address is not 0 (no arena can start at address 0
  532. (NULL)). Therefore Py_ADDRESS_IN_RANGE correctly reports that obmalloc
  533. controls P.
  534. Now suppose obmalloc does not control P (e.g., P was obtained via a direct
  535. call to the system malloc() or realloc()). (POOL)->arenaindex may be anything
  536. in this case -- it may even be uninitialized trash. If the trash arenaindex
  537. is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't
  538. control P.
  539. Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an
  540. allocated arena, obmalloc controls all the memory in slice AO.address :
  541. AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc,
  542. so P doesn't lie in that slice, so the macro correctly reports that P is not
  543. controlled by obmalloc.
  544. Finally, if P is not controlled by obmalloc and AO corresponds to an unused
  545. arena_object (one not currently associated with an allocated arena),
  546. AO.address is 0, and the second test in the macro reduces to:
  547. P < ARENA_SIZE
  548. If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
  549. that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
  550. of the test still passes, and the third clause (AO.address != 0) is necessary
  551. to get the correct result: AO.address is 0 in this case, so the macro
  552. correctly reports that P is not controlled by obmalloc (despite that P lies in
  553. slice AO.address : AO.address + ARENA_SIZE).
  554. Note: The third (AO.address != 0) clause was added in Python 2.5. Before
  555. 2.5, arenas were never free()'ed, and an arenaindex < maxarena always
  556. corresponded to a currently-allocated arena, so the "P is not controlled by
  557. obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case
  558. was impossible.
  559. Note that the logic is excruciating, and reading up possibly uninitialized
  560. memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex)
  561. creates problems for some memory debuggers. The overwhelming advantage is
  562. that this test determines whether an arbitrary address is controlled by
  563. obmalloc in a small constant time, independent of the number of arenas
  564. obmalloc controls. Since this test is needed at every entry point, it's
  565. extremely desirable that it be this fast.
  566. */
  567. #define Py_ADDRESS_IN_RANGE(P, POOL) \
  568. ((POOL)->arenaindex < maxarenas && \
  569. (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \
  570. arenas[(POOL)->arenaindex].address != 0)
  571. /* This is only useful when running memory debuggers such as
  572. * Purify or Valgrind. Uncomment to use.
  573. *
  574. #define Py_USING_MEMORY_DEBUGGER
  575. */
  576. #ifdef Py_USING_MEMORY_DEBUGGER
  577. /* Py_ADDRESS_IN_RANGE may access uninitialized memory by design
  578. * This leads to thousands of spurious warnings when using
  579. * Purify or Valgrind. By making a function, we can easily
  580. * suppress the uninitialized memory reads in this one function.
  581. * So we won't ignore real errors elsewhere.
  582. *
  583. * Disable the macro and use a function.
  584. */
  585. #undef Py_ADDRESS_IN_RANGE
  586. #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
  587. (__GNUC__ >= 4))
  588. #define Py_NO_INLINE __attribute__((__noinline__))
  589. #else
  590. #define Py_NO_INLINE
  591. #endif
  592. /* Don't make static, to try to ensure this isn't inlined. */
  593. int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
  594. #undef Py_NO_INLINE
  595. #endif
  596. /*==========================================================================*/
  597. /* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct
  598. * from all other currently live pointers. This may not be possible.
  599. */
  600. /*
  601. * The basic blocks are ordered by decreasing execution frequency,
  602. * which minimizes the number of jumps in the most common cases,
  603. * improves branching prediction and instruction scheduling (small
  604. * block allocations typically result in a couple of instructions).
  605. * Unless the optimizer reorders everything, being too smart...
  606. */
  607. #undef PyObject_Malloc
  608. void *
  609. PyObject_Malloc(size_t nbytes)
  610. {
  611. block *bp;
  612. poolp pool;
  613. poolp next;
  614. uint size;
  615. /*
  616. * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
  617. * Most python internals blindly use a signed Py_ssize_t to track
  618. * things without checking for overflows or negatives.
  619. * As size_t is unsigned, checking for nbytes < 0 is not required.
  620. */
  621. if (nbytes > PY_SSIZE_T_MAX)
  622. return NULL;
  623. /*
  624. * This implicitly redirects malloc(0).
  625. */
  626. if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
  627. LOCK();
  628. /*
  629. * Most frequent paths first
  630. */
  631. size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
  632. pool = usedpools[size + size];
  633. if (pool != pool->nextpool) {
  634. /*
  635. * There is a used pool for this size class.
  636. * Pick up the head block of its free list.
  637. */
  638. ++pool->ref.count;
  639. bp = pool->freeblock;
  640. assert(bp != NULL);
  641. if ((pool->freeblock = *(block **)bp) != NULL) {
  642. UNLOCK();
  643. return (void *)bp;
  644. }
  645. /*
  646. * Reached the end of the free list, try to extend it.
  647. */
  648. if (pool->nextoffset <= pool->maxnextoffset) {
  649. /* There is room for another block. */
  650. pool->freeblock = (block*)pool +
  651. pool->nextoffset;
  652. pool->nextoffset += INDEX2SIZE(size);
  653. *(block **)(pool->freeblock) = NULL;
  654. UNLOCK();
  655. return (void *)bp;
  656. }
  657. /* Pool is full, unlink from used pools. */
  658. next = pool->nextpool;
  659. pool = pool->prevpool;
  660. next->prevpool = pool;
  661. pool->nextpool = next;
  662. UNLOCK();
  663. return (void *)bp;
  664. }
  665. /* There isn't a pool of the right size class immediately
  666. * available: use a free pool.
  667. */
  668. if (usable_arenas == NULL) {
  669. /* No arena has a free pool: allocate a new arena. */
  670. #ifdef WITH_MEMORY_LIMITS
  671. if (narenas_currently_allocated >= MAX_ARENAS) {
  672. UNLOCK();
  673. goto redirect;
  674. }
  675. #endif
  676. usable_arenas = new_arena();
  677. if (usable_arenas == NULL) {
  678. UNLOCK();
  679. goto redirect;
  680. }
  681. usable_arenas->nextarena =
  682. usable_arenas->prevarena = NULL;
  683. }
  684. assert(usable_arenas->address != 0);
  685. /* Try to get a cached free pool. */
  686. pool = usable_arenas->freepools;
  687. if (pool != NULL) {
  688. /* Unlink from cached pools. */
  689. usable_arenas->freepools = pool->nextpool;
  690. /* This arena already had the smallest nfreepools
  691. * value, so decreasing nfreepools doesn't change
  692. * that, and we don't need to rearrange the
  693. * usable_arenas list. However, if the arena has
  694. * become wholly allocated, we need to remove its
  695. * arena_object from usable_arenas.
  696. */
  697. --usable_arenas->nfreepools;
  698. if (usable_arenas->nfreepools == 0) {
  699. /* Wholly allocated: remove. */
  700. assert(usable_arenas->freepools == NULL);
  701. assert(usable_arenas->nextarena == NULL ||
  702. usable_arenas->nextarena->prevarena ==
  703. usable_arenas);
  704. usable_arenas = usable_arenas->nextarena;
  705. if (usable_arenas != NULL) {
  706. usable_arenas->prevarena = NULL;
  707. assert(usable_arenas->address != 0);
  708. }
  709. }
  710. else {
  711. /* nfreepools > 0: it must be that freepools
  712. * isn't NULL, or that we haven't yet carved
  713. * off all the arena's pools for the first
  714. * time.
  715. */
  716. assert(usable_arenas->freepools != NULL ||
  717. usable_arenas->pool_address <=
  718. (block*)usable_arenas->address +
  719. ARENA_SIZE - POOL_SIZE);
  720. }
  721. init_pool:
  722. /* Frontlink to used pools. */
  723. next = usedpools[size + size]; /* == prev */
  724. pool->nextpool = next;
  725. pool->prevpool = next;
  726. next->nextpool = pool;
  727. next->prevpool = pool;
  728. pool->ref.count = 1;
  729. if (pool->szidx == size) {
  730. /* Luckily, this pool last contained blocks
  731. * of the same size class, so its header
  732. * and free list are already initialized.
  733. */
  734. bp = pool->freeblock;
  735. pool->freeblock = *(block **)bp;
  736. UNLOCK();
  737. return (void *)bp;
  738. }
  739. /*
  740. * Initialize the pool header, set up the free list to
  741. * contain just the second block, and return the first
  742. * block.
  743. */
  744. pool->szidx = size;
  745. size = INDEX2SIZE(size);
  746. bp = (block *)pool + POOL_OVERHEAD;
  747. pool->nextoffset = POOL_OVERHEAD + (size << 1);
  748. pool->maxnextoffset = POOL_SIZE - size;
  749. pool->freeblock = bp + size;
  750. *(block **)(pool->freeblock) = NULL;
  751. UNLOCK();
  752. return (void *)bp;
  753. }
  754. /* Carve off a new pool. */
  755. assert(usable_arenas->nfreepools > 0);
  756. assert(usable_arenas->freepools == NULL);
  757. pool = (poolp)usable_arenas->pool_address;
  758. assert((block*)pool <= (block*)usable_arenas->address +
  759. ARENA_SIZE - POOL_SIZE);
  760. pool->arenaindex = usable_arenas - arenas;
  761. assert(&arenas[pool->arenaindex] == usable_arenas);
  762. pool->szidx = DUMMY_SIZE_IDX;
  763. usable_arenas->pool_address += POOL_SIZE;
  764. --usable_arenas->nfreepools;
  765. if (usable_arenas->nfreepools == 0) {
  766. assert(usable_arenas->nextarena == NULL ||
  767. usable_arenas->nextarena->prevarena ==
  768. usable_arenas);
  769. /* Unlink the arena: it is completely allocated. */
  770. usable_arenas = usable_arenas->nextarena;
  771. if (usable_arenas != NULL) {
  772. usable_arenas->prevarena = NULL;
  773. assert(usable_arenas->address != 0);
  774. }
  775. }
  776. goto init_pool;
  777. }
  778. /* The small block allocator ends here. */
  779. redirect:
  780. /* Redirect the original request to the underlying (libc) allocator.
  781. * We jump here on bigger requests, on error in the code above (as a
  782. * last chance to serve the request) or when the max memory limit
  783. * has been reached.
  784. */
  785. if (nbytes == 0)
  786. nbytes = 1;
  787. return (void *)malloc(nbytes);
  788. }
  789. /* free */
  790. #undef PyObject_Free
  791. void
  792. PyObject_Free(void *p)
  793. {
  794. poolp pool;
  795. block *lastfree;
  796. poolp next, prev;
  797. uint size;
  798. if (p == NULL) /* free(NULL) has no effect */
  799. return;
  800. pool = POOL_ADDR(p);
  801. if (Py_ADDRESS_IN_RANGE(p, pool)) {
  802. /* We allocated this address. */
  803. LOCK();
  804. /* Link p to the start of the pool's freeblock list. Since
  805. * the pool had at least the p block outstanding, the pool
  806. * wasn't empty (so it's already in a usedpools[] list, or
  807. * was full and is in no list -- it's not in the freeblocks
  808. * list in any case).
  809. */
  810. assert(pool->ref.count > 0); /* else it was empty */
  811. *(block **)p = lastfree = pool->freeblock;
  812. pool->freeblock = (block *)p;
  813. if (lastfree) {
  814. struct arena_object* ao;
  815. uint nf; /* ao->nfreepools */
  816. /* freeblock wasn't NULL, so the pool wasn't full,
  817. * and the pool is in a usedpools[] list.
  818. */
  819. if (--pool->ref.count != 0) {
  820. /* pool isn't empty: leave it in usedpools */
  821. UNLOCK();
  822. return;
  823. }
  824. /* Pool is now empty: unlink from usedpools, and
  825. * link to the front of freepools. This ensures that
  826. * previously freed pools will be allocated later
  827. * (being not referenced, they are perhaps paged out).
  828. */
  829. next = pool->nextpool;
  830. prev = pool->prevpool;
  831. next->prevpool = prev;
  832. prev->nextpool = next;
  833. /* Link the pool to freepools. This is a singly-linked
  834. * list, and pool->prevpool isn't used there.
  835. */
  836. ao = &arenas[pool->arenaindex];
  837. pool->nextpool = ao->freepools;
  838. ao->freepools = pool;
  839. nf = ++ao->nfreepools;
  840. /* All the rest is arena management. We just freed
  841. * a pool, and there are 4 cases for arena mgmt:
  842. * 1. If all the pools are free, return the arena to
  843. * the system free().
  844. * 2. If this is the only free pool in the arena,
  845. * add the arena back to the `usable_arenas` list.
  846. * 3. If the "next" arena has a smaller count of free
  847. * pools, we have to "slide this arena right" to
  848. * restore that usable_arenas is sorted in order of
  849. * nfreepools.
  850. * 4. Else there's nothing more to do.
  851. */
  852. if (nf == ao->ntotalpools) {
  853. /* Case 1. First unlink ao from usable_arenas.
  854. */
  855. assert(ao->prevarena == NULL ||
  856. ao->prevarena->address != 0);
  857. assert(ao ->nextarena == NULL ||
  858. ao->nextarena->address != 0);
  859. /* Fix the pointer in the prevarena, or the
  860. * usable_arenas pointer.
  861. */
  862. if (ao->prevarena == NULL) {
  863. usable_arenas = ao->nextarena;
  864. assert(usable_arenas == NULL ||
  865. usable_arenas->address != 0);
  866. }
  867. else {
  868. assert(ao->prevarena->nextarena == ao);
  869. ao->prevarena->nextarena =
  870. ao->nextarena;
  871. }
  872. /* Fix the pointer in the nextarena. */
  873. if (ao->nextarena != NULL) {
  874. assert(ao->nextarena->prevarena == ao);
  875. ao->nextarena->prevarena =
  876. ao->prevarena;
  877. }
  878. /* Record that this arena_object slot is
  879. * available to be reused.
  880. */
  881. ao->nextarena = unused_arena_objects;
  882. unused_arena_objects = ao;
  883. /* Free the entire arena. */
  884. free((void *)ao->address);
  885. ao->address = 0; /* mark unassociated */
  886. --narenas_currently_allocated;
  887. UNLOCK();
  888. return;
  889. }
  890. if (nf == 1) {
  891. /* Case 2. Put ao at the head of
  892. * usable_arenas. Note that because
  893. * ao->nfreepools was 0 before, ao isn't
  894. * currently on the usable_arenas list.
  895. */
  896. ao->nextarena = usable_arenas;
  897. ao->prevarena = NULL;
  898. if (usable_arenas)
  899. usable_arenas->prevarena = ao;
  900. usable_arenas = ao;
  901. assert(usable_arenas->address != 0);
  902. UNLOCK();
  903. return;
  904. }
  905. /* If this arena is now out of order, we need to keep
  906. * the list sorted. The list is kept sorted so that
  907. * the "most full" arenas are used first, which allows
  908. * the nearly empty arenas to be completely freed. In
  909. * a few un-scientific tests, it seems like this
  910. * approach allowed a lot more memory to be freed.
  911. */
  912. if (ao->nextarena == NULL ||
  913. nf <= ao->nextarena->nfreepools) {
  914. /* Case 4. Nothing to do. */
  915. UNLOCK();
  916. return;
  917. }
  918. /* Case 3: We have to move the arena towards the end
  919. * of the list, because it has more free pools than
  920. * the arena to its right.
  921. * First unlink ao from usable_arenas.
  922. */
  923. if (ao->prevarena != NULL) {
  924. /* ao isn't at the head of the list */
  925. assert(ao->prevarena->nextarena == ao);
  926. ao->prevarena->nextarena = ao->nextarena;
  927. }
  928. else {
  929. /* ao is at the head of the list */
  930. assert(usable_arenas == ao);
  931. usable_arenas = ao->nextarena;
  932. }
  933. ao->nextarena->prevarena = ao->prevarena;
  934. /* Locate the new insertion point by iterating over
  935. * the list, using our nextarena pointer.
  936. */
  937. while (ao->nextarena != NULL &&
  938. nf > ao->nextarena->nfreepools) {
  939. ao->prevarena = ao->nextarena;
  940. ao->nextarena = ao->nextarena->nextarena;
  941. }
  942. /* Insert ao at this point. */
  943. assert(ao->nextarena == NULL ||
  944. ao->prevarena == ao->nextarena->prevarena);
  945. assert(ao->prevarena->nextarena == ao->nextarena);
  946. ao->prevarena->nextarena = ao;
  947. if (ao->nextarena != NULL)
  948. ao->nextarena->prevarena = ao;
  949. /* Verify that the swaps worked. */
  950. assert(ao->nextarena == NULL ||
  951. nf <= ao->nextarena->nfreepools);
  952. assert(ao->prevarena == NULL ||
  953. nf > ao->prevarena->nfreepools);
  954. assert(ao->nextarena == NULL ||
  955. ao->nextarena->prevarena == ao);
  956. assert((usable_arenas == ao &&
  957. ao->prevarena == NULL) ||
  958. ao->prevarena->nextarena == ao);
  959. UNLOCK();
  960. return;
  961. }
  962. /* Pool was full, so doesn't currently live in any list:
  963. * link it to the front of the appropriate usedpools[] list.
  964. * This mimics LRU pool usage for new allocations and
  965. * targets optimal filling when several pools contain
  966. * blocks of the same size class.
  967. */
  968. --pool->ref.count;
  969. assert(pool->ref.count > 0); /* else the pool is empty */
  970. size = pool->szidx;
  971. next = usedpools[size + size];
  972. prev = next->prevpool;
  973. /* insert pool before next: prev <-> pool <-> next */
  974. pool->nextpool = next;
  975. pool->prevpool = prev;
  976. next->prevpool = pool;
  977. prev->nextpool = pool;
  978. UNLOCK();
  979. return;
  980. }
  981. /* We didn't allocate this address. */
  982. free(p);
  983. }
  984. /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
  985. * then as the Python docs promise, we do not treat this like free(p), and
  986. * return a non-NULL result.
  987. */
  988. #undef PyObject_Realloc
  989. void *
  990. PyObject_Realloc(void *p, size_t nbytes)
  991. {
  992. void *bp;
  993. poolp pool;
  994. size_t size;
  995. if (p == NULL)
  996. return PyObject_Malloc(nbytes);
  997. /*
  998. * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
  999. * Most python internals blindly use a signed Py_ssize_t to track
  1000. * things without checking for overflows or negatives.
  1001. * As size_t is unsigned, checking for nbytes < 0 is not required.
  1002. */
  1003. if (nbytes > PY_SSIZE_T_MAX)
  1004. return NULL;
  1005. pool = POOL_ADDR(p);
  1006. if (Py_ADDRESS_IN_RANGE(p, pool)) {
  1007. /* We're in charge of this block */
  1008. size = INDEX2SIZE(pool->szidx);
  1009. if (nbytes <= size) {
  1010. /* The block is staying the same or shrinking. If
  1011. * it's shrinking, there's a tradeoff: it costs
  1012. * cycles to copy the block to a smaller size class,
  1013. * but it wastes memory not to copy it. The
  1014. * compromise here is to copy on shrink only if at
  1015. * least 25% of size can be shaved off.
  1016. */
  1017. if (4 * nbytes > 3 * size) {
  1018. /* It's the same,
  1019. * or shrinking and new/old > 3/4.
  1020. */
  1021. return p;
  1022. }
  1023. size = nbytes;
  1024. }
  1025. bp = PyObject_Malloc(nbytes);
  1026. if (bp != NULL) {
  1027. memcpy(bp, p, size);
  1028. PyObject_Free(p);
  1029. }
  1030. return bp;
  1031. }
  1032. /* We're not managing this block. If nbytes <=
  1033. * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
  1034. * block. However, if we do, we need to copy the valid data from
  1035. * the C-managed block to one of our blocks, and there's no portable
  1036. * way to know how much of the memory space starting at p is valid.
  1037. * As bug 1185883 pointed out the hard way, it's possible that the
  1038. * C-managed block is "at the end" of allocated VM space, so that
  1039. * a memory fault can occur if we try to copy nbytes bytes starting
  1040. * at p. Instead we punt: let C continue to manage this block.
  1041. */
  1042. if (nbytes)
  1043. return realloc(p, nbytes);
  1044. /* C doesn't define the result of realloc(p, 0) (it may or may not
  1045. * return NULL then), but Python's docs promise that nbytes==0 never
  1046. * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
  1047. * to begin with. Even then, we can't be sure that realloc() won't
  1048. * return NULL.
  1049. */
  1050. bp = realloc(p, 1);
  1051. return bp ? bp : p;
  1052. }
  1053. #else /* ! WITH_PYMALLOC */
  1054. /*==========================================================================*/
  1055. /* pymalloc not enabled: Redirect the entry points to malloc. These will
  1056. * only be used by extensions that are compiled with pymalloc enabled. */
  1057. void *
  1058. PyObject_Malloc(size_t n)
  1059. {
  1060. return PyMem_MALLOC(n);
  1061. }
  1062. void *
  1063. PyObject_Realloc(void *p, size_t n)
  1064. {
  1065. return PyMem_REALLOC(p, n);
  1066. }
  1067. void
  1068. PyObject_Free(void *p)
  1069. {
  1070. PyMem_FREE(p);
  1071. }
  1072. #endif /* WITH_PYMALLOC */
  1073. #ifdef PYMALLOC_DEBUG
  1074. /*==========================================================================*/
  1075. /* A x-platform debugging allocator. This doesn't manage memory directly,
  1076. * it wraps a real allocator, adding extra debugging info to the memory blocks.
  1077. */
  1078. /* Special bytes broadcast into debug memory blocks at appropriate times.
  1079. * Strings of these are unlikely to be valid addresses, floats, ints or
  1080. * 7-bit ASCII.
  1081. */
  1082. #undef CLEANBYTE
  1083. #undef DEADBYTE
  1084. #undef FORBIDDENBYTE
  1085. #define CLEANBYTE 0xCB /* clean (newly allocated) memory */
  1086. #define DEADBYTE 0xDB /* dead (newly freed) memory */
  1087. #define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */
  1088. static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
  1089. /* serialno is always incremented via calling this routine. The point is
  1090. * to supply a single place to set a breakpoint.
  1091. */
  1092. static void
  1093. bumpserialno(void)
  1094. {
  1095. ++serialno;
  1096. }
  1097. #define SST SIZEOF_SIZE_T
  1098. /* Read sizeof(size_t) bytes at p as a big-endian size_t. */
  1099. static size_t
  1100. read_size_t(const void *p)
  1101. {
  1102. const uchar *q = (const uchar *)p;
  1103. size_t result = *q++;
  1104. int i;
  1105. for (i = SST; --i > 0; ++q)
  1106. result = (result << 8) | *q;
  1107. return result;
  1108. }
  1109. /* Write n as a big-endian size_t, MSB at address p, LSB at
  1110. * p + sizeof(size_t) - 1.
  1111. */
  1112. static void
  1113. write_size_t(void *p, size_t n)
  1114. {
  1115. uchar *q = (uchar *)p + SST - 1;
  1116. int i;
  1117. for (i = SST; --i >= 0; --q) {
  1118. *q = (uchar)(n & 0xff);
  1119. n >>= 8;
  1120. }
  1121. }
  1122. #ifdef Py_DEBUG
  1123. /* Is target in the list? The list is traversed via the nextpool pointers.
  1124. * The list may be NULL-terminated, or circular. Return 1 if target is in
  1125. * list, else 0.
  1126. */
  1127. static int
  1128. pool_is_in_list(const poolp target, poolp list)
  1129. {
  1130. poolp origlist = list;
  1131. assert(target != NULL);
  1132. if (list == NULL)
  1133. return 0;
  1134. do {
  1135. if (target == list)
  1136. return 1;
  1137. list = list->nextpool;
  1138. } while (list != NULL && list != origlist);
  1139. return 0;
  1140. }
  1141. #else
  1142. #define pool_is_in_list(X, Y) 1
  1143. #endif /* Py_DEBUG */
  1144. /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
  1145. fills them with useful stuff, here calling the underlying malloc's result p:
  1146. p[0: S]
  1147. Number of bytes originally asked for. This is a size_t, big-endian (easier
  1148. to read in a memory dump).
  1149. p[S: 2*S]
  1150. Copies of FORBIDDENBYTE. Used to catch under- writes and reads.
  1151. p[2*S: 2*S+n]
  1152. The requested memory, filled with copies of CLEANBYTE.
  1153. Used to catch reference to uninitialized memory.
  1154. &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc
  1155. handled the request itself.
  1156. p[2*S+n: 2*S+n+S]
  1157. Copies of FORBIDDENBYTE. Used to catch over- writes and reads.
  1158. p[2*S+n+S: 2*S+n+2*S]
  1159. A serial number, incremented by 1 on each call to _PyObject_DebugMalloc
  1160. and _PyObject_DebugRealloc.
  1161. This is a big-endian size_t.
  1162. If "bad memory" is detected later, the serial number gives an
  1163. excellent way to set a breakpoint on the next run, to capture the
  1164. instant at which this block was passed out.
  1165. */
  1166. void *
  1167. _PyObject_DebugMalloc(size_t nbytes)
  1168. {
  1169. uchar *p; /* base address of malloc'ed block */
  1170. uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
  1171. size_t total; /* nbytes + 4*SST */
  1172. bumpserialno();
  1173. total = nbytes + 4*SST;
  1174. if (total < nbytes)
  1175. /* overflow: can't represent total as a size_t */
  1176. return NULL;
  1177. p = (uchar *)PyObject_Malloc(total);
  1178. if (p == NULL)
  1179. return NULL;
  1180. write_size_t(p, nbytes);
  1181. memset(p + SST, FORBIDDENBYTE, SST);
  1182. if (nbytes > 0)
  1183. memset(p + 2*SST, CLEANBYTE, nbytes);
  1184. tail = p + 2*SST + nbytes;
  1185. memset(tail, FORBIDDENBYTE, SST);
  1186. write_size_t(tail + SST, serialno);
  1187. return p + 2*SST;
  1188. }
  1189. /* The debug free first checks the 2*SST bytes on each end for sanity (in
  1190. particular, that the FORBIDDENBYTEs are still intact).
  1191. Then fills the original bytes with DEADBYTE.
  1192. Then calls the underlying free.
  1193. */
  1194. void
  1195. _PyObject_DebugFree(void *p)
  1196. {
  1197. uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
  1198. size_t nbytes;
  1199. if (p == NULL)
  1200. return;
  1201. _PyObject_DebugCheckAddress(p);
  1202. nbytes = read_size_t(q);
  1203. if (nbytes > 0)
  1204. memset(q, DEADBYTE, nbytes);
  1205. PyObject_Free(q);
  1206. }
  1207. void *
  1208. _PyObject_DebugRealloc(void *p, size_t nbytes)
  1209. {
  1210. uchar *q = (uchar *)p;
  1211. uchar *tail;
  1212. size_t total; /* nbytes + 4*SST */
  1213. size_t original_nbytes;
  1214. int i;
  1215. if (p == NULL)
  1216. return _PyObject_DebugMalloc(nbytes);
  1217. _PyObject_DebugCheckAddress(p);
  1218. bumpserialno();
  1219. original_nbytes = read_size_t(q - 2*SST);
  1220. total = nbytes + 4*SST;
  1221. if (total < nbytes)
  1222. /* overflow: can't represent total as a size_t */
  1223. return NULL;
  1224. if (nbytes < original_nbytes) {
  1225. /* shrinking: mark old extra memory dead */
  1226. memset(q + nbytes, DEADBYTE, original_nbytes - nbytes);
  1227. }
  1228. /* Resize and add decorations. */
  1229. q = (uchar *)PyObject_Realloc(q - 2*SST, total);
  1230. if (q == NULL)
  1231. return NULL;
  1232. write_size_t(q, nbytes);
  1233. for (i = 0; i < SST; ++i)
  1234. assert(q[SST + i] == FORBIDDENBYTE);
  1235. q += 2*SST;
  1236. tail = q + nbytes;
  1237. memset(tail, FORBIDDENBYTE, SST);
  1238. write_size_t(tail + SST, serialno);
  1239. if (nbytes > original_nbytes) {
  1240. /* growing: mark new extra memory clean */
  1241. memset(q + original_nbytes, CLEANBYTE,
  1242. nbytes - original_nbytes);
  1243. }
  1244. return q;
  1245. }
  1246. /* Check the forbidden bytes on both ends of the memory allocated for p.
  1247. * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress,
  1248. * and call Py_FatalError to kill the program.
  1249. */
  1250. void
  1251. _PyObject_DebugCheckAddress(const void *p)
  1252. {
  1253. const uchar *q = (const uchar *)p;
  1254. char *msg;
  1255. size_t nbytes;
  1256. const uchar *tail;
  1257. int i;
  1258. if (p == NULL) {
  1259. msg = "didn't expect a NULL pointer";
  1260. goto error;
  1261. }
  1262. /* Check the stuff at the start of p first: if there's underwrite
  1263. * corruption, the number-of-bytes field may be nuts, and checking
  1264. * the tail could lead to a segfault then.
  1265. */
  1266. for (i = SST; i >= 1; --i) {
  1267. if (*(q-i) != FORBIDDENBYTE) {
  1268. msg = "bad leading pad byte";
  1269. goto error;
  1270. }
  1271. }
  1272. nbytes = read_size_t(q - 2*SST);
  1273. tail = q + nbytes;
  1274. for (i = 0; i < SST; ++i) {
  1275. if (tail[i] != FORBIDDENBYTE) {
  1276. msg = "bad trailing pad byte";
  1277. goto error;
  1278. }
  1279. }
  1280. return;
  1281. error:
  1282. _PyObject_DebugDumpAddress(p);
  1283. Py_FatalError(msg);
  1284. }
  1285. /* Display info to stderr about the memory block at p. */
  1286. void
  1287. _PyObject_DebugDumpAddress(const void *p)
  1288. {
  1289. const uchar *q = (const uchar *)p;
  1290. const uchar *tail;
  1291. size_t nbytes, serial;
  1292. int i;
  1293. int ok;
  1294. fprintf(stderr, "Debug memory block at address p=%p:\n", p);
  1295. if (p == NULL)
  1296. return;
  1297. nbytes = read_size_t(q - 2*SST);
  1298. fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
  1299. "requested\n", nbytes);
  1300. /* In case this is nuts, check the leading pad bytes first. */
  1301. fprintf(stderr, " The %d pad bytes at p-%d are ", SST, SST);
  1302. ok = 1;
  1303. for (i = 1; i <= SST; ++i) {
  1304. if (*(q-i) != FORBIDDENBYTE) {
  1305. ok = 0;
  1306. break;
  1307. }
  1308. }
  1309. if (ok)
  1310. fputs("FORBIDDENBYTE, as expected.\n", stderr);
  1311. else {
  1312. fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
  1313. FORBIDDENBYTE);
  1314. for (i = SST; i >= 1; --i) {
  1315. const uchar byte = *(q-i);
  1316. fprintf(stderr, " at p-%d: 0x%02x", i, byte);
  1317. if (byte != FORBIDDENBYTE)
  1318. fputs(" *** OUCH", stderr);
  1319. fputc('\n', stderr);
  1320. }
  1321. fputs(" Because memory is corrupted at the start, the "
  1322. "count of bytes requested\n"
  1323. " may be bogus, and checking the trailing pad "
  1324. "bytes may segfault.\n", stderr);
  1325. }
  1326. tail = q + nbytes;
  1327. fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
  1328. ok = 1;
  1329. for (i = 0; i < SST; ++i) {
  1330. if (tail[i] != FORBIDDENBYTE) {
  1331. ok = 0;
  1332. break;
  1333. }
  1334. }
  1335. if (ok)
  1336. fputs("FORBIDDENBYTE, as expected.\n", stderr);
  1337. else {
  1338. fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
  1339. FORBIDDENBYTE);
  1340. for (i = 0; i < SST; ++i) {
  1341. const uchar byte = tail[i];
  1342. fprintf(stderr, " at tail+%d: 0x%02x",
  1343. i, byte);
  1344. if (byte != FORBIDDENBYTE)
  1345. fputs(" *** OUCH", stderr);
  1346. fputc('\n', stderr);
  1347. }
  1348. }
  1349. serial = read_size_t(tail + SST);
  1350. fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
  1351. "u to debug malloc/realloc.\n", serial);
  1352. if (nbytes > 0) {
  1353. i = 0;
  1354. fputs(" Data at p:", stderr);
  1355. /* print up to 8 bytes at the start */
  1356. while (q < tail && i < 8) {
  1357. fprintf(stderr, " %02x", *q);
  1358. ++i;
  1359. ++q;
  1360. }
  1361. /* and up to 8 at the end */
  1362. if (q < tail) {
  1363. if (tail - q > 8) {
  1364. fputs(" ...", stderr);
  1365. q = tail - 8;
  1366. }
  1367. while (q < tail) {
  1368. fprintf(stderr, " %02x", *q);
  1369. ++q;
  1370. }
  1371. }
  1372. fputc('\n', stderr);
  1373. }
  1374. }
  1375. static size_t
  1376. printone(const char* msg, size_t value)
  1377. {
  1378. int i, k;
  1379. char buf[100];
  1380. size_t origvalue = value;
  1381. fputs(msg, stderr);
  1382. for (i = (int)strlen(msg); i < 35; ++i)
  1383. fputc(' ', stderr);
  1384. fputc('=', stderr);
  1385. /* Write the value with commas. */
  1386. i = 22;
  1387. buf[i--] = '\0';
  1388. buf[i--] = '\n';
  1389. k = 3;
  1390. do {
  1391. size_t nextvalue = value / 10;
  1392. uint digit = (uint)(value - nextvalue * 10);
  1393. value = nextvalue;
  1394. buf[i--] = (char)(digit + '0');
  1395. --k;
  1396. if (k == 0 && value && i >= 0) {
  1397. k = 3;
  1398. buf[i--] = ',';
  1399. }
  1400. } while (value && i >= 0);
  1401. while (i >= 0)
  1402. buf[i--] = ' ';
  1403. fputs(buf, stderr);
  1404. return origvalue;
  1405. }
  1406. /* Print summary info to stderr about the state of pymalloc's structures.
  1407. * In Py_DEBUG mode, also perform some expensive internal consistency
  1408. * checks.
  1409. */
  1410. void
  1411. _PyObject_DebugMallocStats(void)
  1412. {
  1413. uint i;
  1414. const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
  1415. /* # of pools, allocated blocks, and free blocks per class index */
  1416. size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
  1417. size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
  1418. size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
  1419. /* total # of allocated bytes in used and full pools */
  1420. size_t allocated_bytes = 0;
  1421. /* total # of available bytes in used pools */
  1422. size_t available_bytes = 0;
  1423. /* # of free pools + pools not yet carved out of current arena */
  1424. uint numfreepools = 0;
  1425. /* # of bytes for arena alignment padding */
  1426. size_t arena_alignment = 0;
  1427. /* # of bytes in used and full pools used for pool_headers */
  1428. size_t pool_header_bytes = 0;
  1429. /* # of bytes in used and full pools wasted due to quantization,
  1430. * i.e. the necessarily leftover space at the ends of used and
  1431. * full pools.
  1432. */
  1433. size_t quantization = 0;
  1434. /* # of arenas actually allocated. */
  1435. size_t narenas = 0;
  1436. /* running total -- should equal narenas * ARENA_SIZE */
  1437. size_t total;
  1438. char buf[128];
  1439. fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
  1440. SMALL_REQUEST_THRESHOLD, numclasses);
  1441. for (i = 0; i < numclasses; ++i)
  1442. numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
  1443. /* Because full pools aren't linked to from anything, it's easiest
  1444. * to march over all the arenas. If we're lucky, most of the memory
  1445. * will be living in full pools -- would be a shame to miss them.
  1446. */
  1447. for (i = 0; i < maxarenas; ++i) {
  1448. uint poolsinarena;
  1449. uint j;
  1450. uptr base = arenas[i].address;
  1451. /* Skip arenas which are not allocated. */
  1452. if (arenas[i].address == (uptr)NULL)
  1453. continue;
  1454. narenas += 1;
  1455. poolsinarena = arenas[i].ntotalpools;
  1456. numfreepools += arenas[i].nfreepools;
  1457. /* round up to pool alignment */
  1458. if (base & (uptr)POOL_SIZE_MASK) {
  1459. arena_alignment += POOL_SIZE;
  1460. base &= ~(uptr)POOL_SIZE_MASK;
  1461. base += POOL_SIZE;
  1462. }
  1463. /* visit every pool in the arena */
  1464. assert(base <= (uptr) arenas[i].pool_address);
  1465. for (j = 0;
  1466. base < (uptr) arenas[i].pool_address;
  1467. ++j, base += POOL_SIZE) {
  1468. poolp p = (poolp)base;
  1469. const uint sz = p->szidx;
  1470. uint freeblocks;
  1471. if (p->ref.count == 0) {
  1472. /* currently unused */
  1473. assert(pool_is_in_list(p, arenas[i].freepools));
  1474. continue;
  1475. }
  1476. ++numpools[sz];
  1477. numblocks[sz] += p->ref.count;
  1478. freeblocks = NUMBLOCKS(sz) - p->ref.count;
  1479. numfreeblocks[sz] += freeblocks;
  1480. #ifdef Py_DEBUG
  1481. if (freeblocks > 0)
  1482. assert(pool_is_in_list(p, usedpools[sz + sz]));
  1483. #endif
  1484. }
  1485. }
  1486. assert(narenas == narenas_currently_allocated);
  1487. fputc('\n', stderr);
  1488. fputs("class size num pools blocks in use avail blocks\n"
  1489. "----- ---- --------- ------------- ------------\n",
  1490. stderr);
  1491. for (i = 0; i < numclasses; ++i) {
  1492. size_t p = numpools[i];
  1493. size_t b = numblocks[i];
  1494. size_t f = numfreeblocks[i];
  1495. uint size = INDEX2SIZE(i);
  1496. if (p == 0) {
  1497. assert(b == 0 && f == 0);
  1498. continue;
  1499. }
  1500. fprintf(stderr, "%5u %6u "
  1501. "%11" PY_FORMAT_SIZE_T "u "
  1502. "%15" PY_FORMAT_SIZE_T "u "
  1503. "%13" PY_FORMAT_SIZE_T "u\n",
  1504. i, size, p, b, f);
  1505. allocated_bytes += b * size;
  1506. available_bytes += f * size;
  1507. pool_header_bytes += p * POOL_OVERHEAD;
  1508. quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
  1509. }
  1510. fputc('\n', stderr);
  1511. (void)printone("# times object malloc called", serialno);
  1512. (void)printone("# arenas allocated total", ntimes_arena_allocated);
  1513. (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
  1514. (void)printone("# arenas highwater mark", narenas_highwater);
  1515. (void)printone("# arenas allocated current", narenas);
  1516. PyOS_snprintf(buf, sizeof(buf),
  1517. "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
  1518. narenas, ARENA_SIZE);
  1519. (void)printone(buf, narenas * ARENA_SIZE);
  1520. fputc('\n', stderr);
  1521. total = printone("# bytes in allocated blocks", allocated_bytes);
  1522. total += printone("# bytes in available blocks", available_bytes);
  1523. PyOS_snprintf(buf, sizeof(buf),
  1524. "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
  1525. total += printone(buf, (size_t)numfreepools * POOL_SIZE);
  1526. total += printone("# bytes lost to pool headers", pool_header_bytes);
  1527. total += printone("# bytes lost to quantization", quantization);
  1528. total += printone("# bytes lost to arena alignment", arena_alignment);
  1529. (void)printone("Total", total);
  1530. }
  1531. #endif /* PYMALLOC_DEBUG */
  1532. #ifdef Py_USING_MEMORY_DEBUGGER
  1533. /* Make this function last so gcc won't inline it since the definition is
  1534. * after the reference.
  1535. */
  1536. int
  1537. Py_ADDRESS_IN_RANGE(void *P, poolp pool)
  1538. {
  1539. return pool->arenaindex < maxarenas &&
  1540. (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE &&
  1541. arenas[pool->arenaindex].address != 0;
  1542. }
  1543. #endif