From da6b1c1b22ce0386214bbc5395d4cc42529be4fb Mon Sep 17 00:00:00 2001 From: Cathy Avery Date: Thu, 25 Jul 2019 12:32:25 +0200 Subject: [PATCH 02/16] Fix memory leak in GetFormattedCommandLine() function (linuxDeployment.c) RH-Author: Cathy Avery Message-id: <20190725123239.18274-3-cavery@redhat.com> Patchwork-id: 89712 O-Subject: [RHEL8.1 open-vm-tools PATCH 02/16] Fix memory leak in GetFormattedCommandLine() function (linuxDeployment.c) Bugzilla: 1602648 RH-Acked-by: Vitaly Kuznetsov RH-Acked-by: Miroslav Rezanina commit d93219282ff7e89e3f581bf757dfd807c7568452 Author: Oliver Kurth Date: Thu Mar 28 12:42:59 2019 -0700 Fix memory leak in GetFormattedCommandLine() function (linuxDeployment.c) 1. There are malloc() calls happening in a loop; this function returns NULL when one of malloc fails. If a malloc call fails in the loop, all memory allocated in previous iterations should be freed before the return NULL. 2. Clear allocated resources before return NULL in this file. 3. Add NULL check following malloc calls in this file. 4. Encapsulate %s in () only if %s is strerror(errno), otherwise encapsulate %s in single quotes. 5. End with \n in sLog. Signed-off-by: Cathy Avery Partial port: Only the parts of the patch that addesses the coverity defects were backported. Signed-off-by: Miroslav Rezanina --- open-vm-tools/libDeployPkg/linuxDeployment.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/libDeployPkg/linuxDeployment.c b/libDeployPkg/linuxDeployment.c index 6e22aac..74b2f90 100644 --- a/libDeployPkg/linuxDeployment.c +++ b/libDeployPkg/linuxDeployment.c @@ -454,6 +454,8 @@ AddToList(struct List* head, const char* token) l = malloc(sizeof(struct List)); if (!l) { SetDeployError("Error allocating memory. (%s)", strerror(errno)); + // clear allocated resource + free(data); return NULL; } @@ -1495,13 +1497,23 @@ GetFormattedCommandLine(const char* command) args = malloc((ListSize(commandTokens) + 1) * sizeof(char*)); if (!args) { SetDeployError("Error allocating memory."); + // clear resources + DeleteList(commandTokens); return NULL; } for(l = commandTokens, i = 0; l; l = l->next, i++) { char* arg = malloc(strlen(l->data) + 1); if (!arg) { - SetDeployError("Error allocating memory.(%s)", strerror(errno)); + unsigned int j; + SetDeployError("Error allocating memory. (%s)", strerror(errno)); + // free allocated memories in previous iterations if any + for (j = 0; j < i; j++) { + free(args[j]); + } + free(args); + // clear resources + DeleteList(commandTokens); return NULL; } -- 1.8.3.1