Updated documentation for findCaller() to indicate that a 3-tuple is now returned...
[python.git] / Modules / _ctypes / malloc_closure.c
blob4cd5dd6f5a23a2301811791aebefa6588ef782e4
1 /*****************************************************************
2 This file should be kept compatible with Python 2.3, see PEP 291.
3 *****************************************************************/
5 #include <Python.h>
6 #include <ffi.h>
7 #ifdef MS_WIN32
8 #include <windows.h>
9 #else
10 #include <sys/mman.h>
11 #include <unistd.h>
12 # if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
13 # define MAP_ANONYMOUS MAP_ANON
14 # endif
15 #endif
16 #include "ctypes.h"
18 /* BLOCKSIZE can be adjusted. Larger blocksize will take a larger memory
19 overhead, but allocate less blocks from the system. It may be that some
20 systems have a limit of how many mmap'd blocks can be open.
23 #define BLOCKSIZE _pagesize
25 /* #define MALLOC_CLOSURE_DEBUG */ /* enable for some debugging output */
27 /******************************************************************/
29 typedef union _tagITEM {
30 ffi_closure closure;
31 union _tagITEM *next;
32 } ITEM;
34 static ITEM *free_list;
35 int _pagesize;
37 static void more_core(void)
39 ITEM *item;
40 int count, i;
42 /* determine the pagesize */
43 #ifdef MS_WIN32
44 if (!_pagesize) {
45 SYSTEM_INFO systeminfo;
46 GetSystemInfo(&systeminfo);
47 _pagesize = systeminfo.dwPageSize;
49 #else
50 if (!_pagesize) {
51 _pagesize = getpagesize();
53 #endif
55 /* calculate the number of nodes to allocate */
56 count = BLOCKSIZE / sizeof(ITEM);
58 /* allocate a memory block */
59 #ifdef MS_WIN32
60 item = (ITEM *)VirtualAlloc(NULL,
61 count * sizeof(ITEM),
62 MEM_COMMIT,
63 PAGE_EXECUTE_READWRITE);
64 if (item == NULL)
65 return;
66 #else
67 item = (ITEM *)mmap(NULL,
68 count * sizeof(ITEM),
69 PROT_READ | PROT_WRITE | PROT_EXEC,
70 MAP_PRIVATE | MAP_ANONYMOUS,
71 -1,
72 0);
73 if (item == (void *)MAP_FAILED)
74 return;
75 #endif
77 #ifdef MALLOC_CLOSURE_DEBUG
78 printf("block at %p allocated (%d bytes), %d ITEMs\n",
79 item, count * sizeof(ITEM), count);
80 #endif
81 /* put them into the free list */
82 for (i = 0; i < count; ++i) {
83 item->next = free_list;
84 free_list = item;
85 ++item;
89 /******************************************************************/
91 /* put the item back into the free list */
92 void FreeClosure(void *p)
94 ITEM *item = (ITEM *)p;
95 item->next = free_list;
96 free_list = item;
99 /* return one item from the free list, allocating more if needed */
100 void *MallocClosure(void)
102 ITEM *item;
103 if (!free_list)
104 more_core();
105 if (!free_list)
106 return NULL;
107 item = free_list;
108 free_list = item->next;
109 return item;