tools/lib/api: Fix potential double-free from fdarray__grow()
PATCH v2 1/1 tools/lib/api: Fix potential double-free from fdarray__grow()
If the realloc for fda->entries succeeds but the realloc for fda->priv fails, the error path frees the newly allocated entries.
However, fda->entries is neither updated to point to the new entries block nor cleared to NULL. If realloc moved the allocation to a new block, the old fda->entries pointer is now freed memory.
When fdarray__exit() is later called to clean up, it executes free(fda->entries), which would trigger a double-free on that old pointer.
---
v2 changes)
* update the patch subject
tools/lib/api/fd/array.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
tools/lib/api/fd/array.c +3 -2
@@ -31,7 +31,8 @@ int fdarray__grow(struct fdarray *fda, int nr) priv =realloc (fda->priv, psize);if (priv ==NULL ) { -free (entries); +/* this will be freed by fdarray__exit() */ + fda->entries = entries;return -ENOMEM ; }
@@ -50,7 +51,7 @@ struct fdarray *fdarray__new(int nr_alloc, int nr_autogrow)if (fda !=NULL ) {if (fdarray__grow (fda, nr_alloc)) { -free (fda); +fdarray__delete (fda); fda =NULL ; }else { fda->nr_autogrow = nr_autogrow;
Signature · 1 line
2.55.0.795.g602f6c329a-goog
Quoted 8 lines · Namhyung Kim
If the realloc for
fda->entriessucceeds but the realloc forfda->privfails, the error path frees the newly allocated entries.However,
fda->entriesis neither updated to point to the new entries block nor cleared to NULL. If realloc moved the allocation to a new block, the oldfda->entriespointer is now freed memory.
Quoted 6 lines
When
fdarray__exit()is later called to clean up, it executesfree(fda->entries), which would trigger a double-free on that old pointer.Reported-by Sashiko Review <[email protected]>Signed-off-by Namhyung Kim <[email protected]>
Thanks,
Ian
Quoted 33 lines
---
v2 changes)
* update the patch subjecttools/lib/api/fd/array.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)tools/lib/api/fd/array.c +3
-3@@ -31,7 +31,8 @@ int fdarray__grow(struct fdarray *fda, int nr) priv =realloc (fda->priv, psize);if (priv ==NULL ) { -free (entries); +/* this will be freed by fdarray__exit() */ + fda->entries = entries;return -ENOMEM ; }@@ -50,7 +51,7 @@ struct fdarray *fdarray__new(int nr_alloc, int nr_autogrow)if (fda !=NULL ) {if (fdarray__grow (fda, nr_alloc)) { -free (fda); +fdarray__delete (fda); fda =NULL ; }else { fda->nr_autogrow = nr_autogrow; --2.55.0.795.g602f6c329a-goog
Namhyung Kim
AppliedQuoted 8 lines · Namhyung Kim
If the realloc for
fda->entriessucceeds but the realloc forfda->privfails, the error path frees the newly allocated entries.However,
fda->entriesis neither updated to point to the new entries block nor cleared to NULL. If realloc moved the allocation to a new block, the oldfda->entriespointer is now freed memory.[...]
Applied to perf-tools-next, thanks!
Best regards,
Namhyung