From b22e51797c34cefd85fb8d90190a4a20f570ea0d Mon Sep 17 00:00:00 2001 From: Bharath Rupireddy Date: Thu, 20 Oct 2022 17:30:41 +0000 Subject: [PATCH v8] Avoid memory leaks during backups using SQL-callable functions --- src/backend/access/transam/xlogfuncs.c | 43 ++++++++++++++------------ 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/src/backend/access/transam/xlogfuncs.c b/src/backend/access/transam/xlogfuncs.c index a801a94fe8..69c761d7dd 100644 --- a/src/backend/access/transam/xlogfuncs.c +++ b/src/backend/access/transam/xlogfuncs.c @@ -45,6 +45,9 @@ static BackupState *backup_state = NULL; static StringInfo tablespace_map = NULL; +/* A long-lived workspace for SQL-callable backup functions. */ +static MemoryContext backupcontext = NULL; + /* * pg_backup_start: set up for taking an on-line backup dump * @@ -72,27 +75,28 @@ pg_backup_start(PG_FUNCTION_ARGS) /* * backup_state and tablespace_map need to be long-lived as they are used - * in pg_backup_stop(). + * in pg_backup_stop(). Create a special session-level memory context as a + * direct child of TopMemoryContext so that the memory allocated is carried + * across. We keep the memory allocated in this memory context less, + * because any error before reaching pg_backup_stop() can leak the memory + * until pg_backup_start() is called again. While this is not smart, it + * helps to keep things simple. */ - oldcontext = MemoryContextSwitchTo(TopMemoryContext); - - /* Allocate backup state or reset it, if it comes from a previous run */ - if (backup_state == NULL) - backup_state = (BackupState *) palloc0(sizeof(BackupState)); + if (backupcontext == NULL) + backupcontext = AllocSetContextCreate(TopMemoryContext, + "on-line backup context", + ALLOCSET_START_SMALL_SIZES); else - MemSet(backup_state, 0, sizeof(BackupState)); - - /* - * tablespace_map may have been created in a previous backup, so take this - * occasion to clean it. - */ - if (tablespace_map != NULL) { - pfree(tablespace_map->data); - pfree(tablespace_map); + MemoryContextReset(backupcontext); + backup_state = NULL; tablespace_map = NULL; } + oldcontext = MemoryContextSwitchTo(backupcontext); + Assert(backup_state == NULL); + Assert(tablespace_map == NULL); + backup_state = (BackupState *) palloc0(sizeof(BackupState)); tablespace_map = makeStringInfo(); MemoryContextSwitchTo(oldcontext); @@ -157,12 +161,13 @@ pg_backup_stop(PG_FUNCTION_ARGS) values[2] = CStringGetTextDatum(tablespace_map->data); /* Deallocate backup-related variables */ - pfree(backup_state); + pfree(backup_label); + + /* Clean up the session-level backup memory context */ + MemoryContextDelete(backupcontext); backup_state = NULL; - pfree(tablespace_map->data); - pfree(tablespace_map); tablespace_map = NULL; - pfree(backup_label); + backupcontext = NULL; /* Returns the record as Datum */ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls))); -- 2.34.1