diff --git a/Modules/_sqlite/module.c b/Modules/_sqlite/module.c index 8dbfa7b38a..d40989bd55 100644 --- a/Modules/_sqlite/module.c +++ b/Modules/_sqlite/module.c @@ -360,6 +360,50 @@ do { \ } \ } while (0) +static void * +pysqlite_mem_malloc(int size) +{ + if (size == 0) { + return NULL; + } + + int *ptr = PyMem_RawMalloc(size + sizeof(int)); + if (ptr == NULL) { + return NULL; + } + + *ptr = size; + return ptr+1; +} + +#include +static int +pysqlite_mem_size(void *ptr) +{ + if (ptr == NULL) { + return 0; + } + + int *iptr = ptr; + return iptr[0]; +} + +static void +pysqlite_mem_free(void *ptr) +{ + if (ptr) { + int *iptr = ptr; + PyMem_RawFree(iptr-1); + } +} + +static void * +pysqlite_mem_realloc(void *ptr, int size) +{ + pysqlite_mem_free(ptr); + return pysqlite_mem_malloc(size); +} + PyMODINIT_FUNC PyInit__sqlite3(void) { PyObject *module; @@ -369,12 +413,28 @@ PyMODINIT_FUNC PyInit__sqlite3(void) return NULL; } - int rc = sqlite3_initialize(); + /* Set SQLite up to use Python's memory allocators to give access to the + * built-in memory debugger. */ + struct sqlite3_mem_methods mem_methods; + int rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem_methods); if (rc != SQLITE_OK) { PyErr_SetString(PyExc_ImportError, sqlite3_errstr(rc)); return NULL; } + mem_methods.xMalloc = pysqlite_mem_malloc; + mem_methods.xFree = pysqlite_mem_free; + mem_methods.xSize = pysqlite_mem_size; + mem_methods.xRealloc = pysqlite_mem_realloc; + + rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &mem_methods); + if (rc != SQLITE_OK) { + PyErr_SetString(PyExc_ImportError, sqlite3_errstr(rc)); + return NULL; + } + + int rc = sqlite3_initialize(); + module = PyModule_Create(&_sqlite3module); if (!module ||