mpool: Avoid leak in the case that lseek fails.

I noticed while running the micropython testsuite under
-fsanitize=address and valgrind that a memory leaks was reported
with a stack trace like
```
2,128 bytes in 1 blocks are definitely lost in loss record 1 of 1
   at 0x48465EF: calloc (vg_replace_malloc.c:1328)
   by 0x62D6D2: mpool_open (mpool.c:67)
   by 0x614233: __bt_open (bt_open.c:300)
   by 0x450A1C: mod_btree_open (modbtree.c:416)
```
specifically in the case where lseek failed.

By moving the lseek call to before the allocation of the MPOOL
object, no new "free mp during error exit" code needed to be
added.
Signed-off-by: Jeff Epler <jepler@gmail.com>
This commit is contained in:
Jeff Epler 2025-06-01 20:34:32 +02:00
parent 85373b548f
commit 0f3bb6947c

View file

@ -63,6 +63,10 @@ mpool_open(key, fd, fvtable, pagesize, maxcache)
MPOOL *mp;
int entry;
off_t file_size = fvtable->lseek(fd, 0, SEEK_END);
if (file_size == (off_t)-1)
return (NULL);
/* Allocate and initialize the MPOOL cookie. */
if ((mp = (MPOOL *)calloc(1, sizeof(MPOOL))) == NULL)
return (NULL);
@ -71,9 +75,6 @@ mpool_open(key, fd, fvtable, pagesize, maxcache)
CIRCLEQ_INIT(&mp->hqh[entry]);
mp->maxcache = maxcache;
mp->fvtable = fvtable;
off_t file_size = mp->fvtable->lseek(fd, 0, SEEK_END);
if (file_size == (off_t)-1)
return (NULL);
mp->npages = file_size / pagesize;
mp->pagesize = pagesize;
mp->fd = fd;