From 7ae09a9695bcc5fad606441db3ab6e413b9d48ce Mon Sep 17 00:00:00 2001 From: Stefan Metzmacher Date: Tue, 28 May 2013 13:04:29 +0200 Subject: [PATCH] tdb: add proper OOM/ENOSPC handling to tdb_expand() Failing to do so will result in corrupt tdbs: We will overwrite the hash chain pointers with 0x42424242. Pair-Programmed-With: Volker Lendecke Signed-off-by: Stefan Metzmacher Signed-off-by: Volker Lendecke Reviewed-by: Rusty Russell --- lib/tdb/common/io.c | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/lib/tdb/common/io.c b/lib/tdb/common/io.c index c9c9fa8dc93..87d47b970b0 100644 --- a/lib/tdb/common/io.c +++ b/lib/tdb/common/io.c @@ -421,6 +421,7 @@ int tdb_expand(struct tdb_context *tdb, tdb_off_t size) { struct tdb_record rec; tdb_off_t offset; + tdb_off_t new_size; if (tdb_lock(tdb, -1, F_WRLCK) == -1) { TDB_LOG((tdb, TDB_DEBUG_ERROR, "lock failed in tdb_expand\n")); @@ -432,10 +433,12 @@ int tdb_expand(struct tdb_context *tdb, tdb_off_t size) size = tdb_expand_adjust(tdb->map_size, size, tdb->page_size); - /* expand the file itself */ - if (!(tdb->flags & TDB_INTERNAL)) { - if (tdb->methods->tdb_expand_file(tdb, tdb->map_size, size) != 0) - goto fail; + if (!tdb_add_off_t(tdb->map_size, size, &new_size)) { + tdb->ecode = TDB_ERR_OOM; + TDB_LOG((tdb, TDB_DEBUG_FATAL, "tdb_expand " + "overflow detected current map_size[%u] size[%u]!\n", + (unsigned)tdb->map_size, (unsigned)size)); + goto fail; } /* form a new freelist record */ @@ -444,18 +447,30 @@ int tdb_expand(struct tdb_context *tdb, tdb_off_t size) rec.rec_len = size - sizeof(rec); if (tdb->flags & TDB_INTERNAL) { - char *new_map_ptr = (char *)realloc(tdb->map_ptr, - tdb->map_size + size); + char *new_map_ptr; + + new_map_ptr = (char *)realloc(tdb->map_ptr, new_size); if (!new_map_ptr) { + tdb->ecode = TDB_ERR_OOM; goto fail; } tdb->map_ptr = new_map_ptr; - tdb->map_size += size; + tdb->map_size = new_size; } else { + int ret; + + /* + * expand the file itself + */ + ret = tdb->methods->tdb_expand_file(tdb, tdb->map_size, size); + if (ret != 0) { + goto fail; + } + /* Explicitly remap: if we're in a transaction, this won't * happen automatically! */ tdb_munmap(tdb); - tdb->map_size += size; + tdb->map_size = new_size; if (tdb_mmap(tdb) != 0) { goto fail; } -- 2.11.4.GIT