blob: 13ccdd64d591a1c5e5cc1e756e4cf84d9e933b9d [file] [log] [blame]
Vadim Yanitskiyfbd736e2018-07-31 22:40:30 +07001/*
2 * libtalloc based memory allocator for SQLite3.
3 *
4 * (C) 2019 by Vadim Yanitskiy <axilirator@gmail.com>
5 *
6 * All Rights Reserved
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
17 *
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 */
22
23#include <sqlite3.h>
24#include <talloc.h>
25#include <errno.h>
26
27/* Dedicated talloc context for SQLite */
28static void *db_sqlite_ctx = NULL;
29
30static void *tall_xMalloc(int size)
31{
32 return talloc_size(db_sqlite_ctx, size);
33}
34
35static void tall_xFree(void *ptr)
36{
37 talloc_free(ptr);
38}
39
40static void *tall_xRealloc(void *ptr, int size)
41{
42 return talloc_realloc_fn(db_sqlite_ctx, ptr, size);
43}
44
45static int tall_xSize(void *ptr)
46{
47 return talloc_total_size(ptr);
48}
49
50/* DUMMY: talloc doesn't round up the allocation size */
51static int tall_xRoundup(int size) { return size; }
52
53/* DUMMY: nothing to initialize */
54static int tall_xInit(void *data) { return 0; }
55
56/* DUMMY: nothing to deinitialize */
57static void tall_xShutdown(void *data) { }
58
59/* Interface between SQLite and talloc memory allocator */
60static const struct sqlite3_mem_methods tall_sqlite_if = {
61 /* Memory allocation function */
62 .xMalloc = &tall_xMalloc,
63 /* Free a prior allocation */
64 .xFree = &tall_xFree,
65 /* Resize an allocation */
66 .xRealloc = &tall_xRealloc,
67 /* Return the size of an allocation */
68 .xSize = &tall_xSize,
69 /* Round up request size to allocation size */
70 .xRoundup = &tall_xRoundup,
71 /* Initialize the memory allocator */
72 .xInit = &tall_xInit,
73 /* Deinitialize the memory allocator */
74 .xShutdown = &tall_xShutdown,
75 /* Argument to xInit() and xShutdown() */
76 .pAppData = NULL,
77};
78
79int db_sqlite3_use_talloc(void *ctx)
80{
81 if (db_sqlite_ctx != NULL)
82 return -EEXIST;
83
84 db_sqlite_ctx = talloc_named_const(ctx, 0, "SQLite3");
85 return sqlite3_config(SQLITE_CONFIG_MALLOC, &tall_sqlite_if);
86}