4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
13 ** This file implements an extension that uses the SQLITE_CONFIG_MALLOC
14 ** mechanism to add a tracing layer on top of SQLite. If this extension
15 ** is registered prior to sqlite3_initialize(), it will cause all memory
16 ** allocation activities to be logged on standard output, or to some other
17 ** FILE specified by the initializer.
19 ** This file needs to be compiled into the application that uses it.
21 ** This extension is used to implement the --memtrace option of the
22 ** command-line shell.
28 /* The original memory allocation routines */
29 static sqlite3_mem_methods memtraceBase
;
30 static FILE *memtraceOut
;
32 /* Methods that trace memory allocations */
33 static void *memtraceMalloc(int n
){
35 fprintf(memtraceOut
, "MEMTRACE: allocate %d bytes\n",
36 memtraceBase
.xRoundup(n
));
38 return memtraceBase
.xMalloc(n
);
40 static void memtraceFree(void *p
){
43 fprintf(memtraceOut
, "MEMTRACE: free %d bytes\n", memtraceBase
.xSize(p
));
45 memtraceBase
.xFree(p
);
47 static void *memtraceRealloc(void *p
, int n
){
48 if( p
==0 ) return memtraceMalloc(n
);
54 fprintf(memtraceOut
, "MEMTRACE: resize %d -> %d bytes\n",
55 memtraceBase
.xSize(p
), memtraceBase
.xRoundup(n
));
57 return memtraceBase
.xRealloc(p
, n
);
59 static int memtraceSize(void *p
){
60 return memtraceBase
.xSize(p
);
62 static int memtraceRoundup(int n
){
63 return memtraceBase
.xRoundup(n
);
65 static int memtraceInit(void *p
){
66 return memtraceBase
.xInit(p
);
68 static void memtraceShutdown(void *p
){
69 memtraceBase
.xShutdown(p
);
72 /* The substitute memory allocator */
73 static sqlite3_mem_methods ersaztMethods
= {
84 /* Begin tracing memory allocations to out. */
85 int sqlite3MemTraceActivate(FILE *out
){
87 if( memtraceBase
.xMalloc
==0 ){
88 rc
= sqlite3_config(SQLITE_CONFIG_GETMALLOC
, &memtraceBase
);
90 rc
= sqlite3_config(SQLITE_CONFIG_MALLOC
, &ersaztMethods
);
97 /* Deactivate memory tracing */
98 int sqlite3MemTraceDeactivate(void){
100 if( memtraceBase
.xMalloc
!=0 ){
101 rc
= sqlite3_config(SQLITE_CONFIG_MALLOC
, &memtraceBase
);
103 memset(&memtraceBase
, 0, sizeof(memtraceBase
));