From 3c487e9d9b50e220f9eb32a020cbd9fd742d4405 Mon Sep 17 00:00:00 2001 From: Martin Kletzander Date: Tue, 27 Oct 2020 13:48:38 +0100 Subject: [PATCH 072/108] util: Avoid double free in virProcessSetAffinity The cpu mask was free()'d immediately on any error and at the end of the function, where it was expected that it would either error out and return or goto another allocation if the code was to fail. However since commit 9514e24984ee the error path did not return in one new case which caused double-free in such situation. In order to make the code more straightforward just free the mask after it's been used even before checking the return code of the call. Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1819801 Signed-off-by: Martin Kletzander Reviewed-by: Peter Krempa (cherry picked from commit 1f807631f402210d036ec4803e7adfefa222f786) --- src/util/virprocess.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/util/virprocess.c b/src/util/virprocess.c index 141ebb54e0..c3f88d206b 100644 --- a/src/util/virprocess.c +++ b/src/util/virprocess.c @@ -450,6 +450,7 @@ int virProcessSetAffinity(pid_t pid, virBitmapPtr map) int numcpus = 1024; size_t masklen; cpu_set_t *mask; + int rv = -1; /* Not only may the statically allocated cpu_set_t be too small, * but there is no way to ask the kernel what size is large enough. @@ -473,8 +474,10 @@ int virProcessSetAffinity(pid_t pid, virBitmapPtr map) CPU_SET_S(i, masklen, mask); } - if (sched_setaffinity(pid, masklen, mask) < 0) { - CPU_FREE(mask); + rv = sched_setaffinity(pid, masklen, mask); + CPU_FREE(mask); + + if (rv < 0) { if (errno == EINVAL && numcpus < (1024 << 8)) { /* 262144 cpus ought to be enough for anyone */ numcpus = numcpus << 2; @@ -484,7 +487,6 @@ int virProcessSetAffinity(pid_t pid, virBitmapPtr map) _("cannot set CPU affinity on process %d"), pid); return -1; } - CPU_FREE(mask); return 0; } -- 2.33.0