From c4a7a62262952237bb1d7db3f174ece935235ea4 Mon Sep 17 00:00:00 2001 From: Antonio Borneo Date: Tue, 8 Jan 2019 09:54:30 +0100 Subject: [PATCH] helper/command: check for malloc failure in __command_name If malloc fails in __command_name, the following strcpy will segfault, thus preventing __command_name to return. The actual calls to command_name() implement the correct check for the NULL pointer, but propagate error -ENOMEM, that is not an error value coherent within OpenOCD. Plus, in one case it overwrites an already detected error. Check the pointer returned by malloc and, in case of failure, issue an error message and return the NULL pointer. Let the caller of command_name() to keep the already detected error or to return ERROR_FAIL in case of end of memory. Change-Id: I151a24569409777dd5bc09a3daf5dba2b8e2829b Signed-off-by: Antonio Borneo Reviewed-on: http://openocd.zylin.com/4838 Tested-by: jenkins Reviewed-by: Tomas Vanek --- src/helper/command.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/helper/command.c b/src/helper/command.c index 35c4486af8..48d998f663 100644 --- a/src/helper/command.c +++ b/src/helper/command.c @@ -557,6 +557,10 @@ static char *__command_name(struct command *c, char delim, unsigned extra) if (NULL == c->parent) { /* allocate enough for the name, child names, and '\0' */ name = malloc(len + extra + 1); + if (!name) { + LOG_ERROR("Out of memory"); + return NULL; + } strcpy(name, c->name); } else { /* parent's extra must include both the space and name */ @@ -631,8 +635,7 @@ static int run_command(struct command_context *context, if (NULL != full_name) { command_run_linef(context, "usage %s", full_name); free(full_name); - } else - retval = -ENOMEM; + } } else if (retval == ERROR_COMMAND_CLOSE_CONNECTION) { /* just fall through for a shutdown request */ } else if (retval != ERROR_OK) { @@ -870,7 +873,7 @@ static COMMAND_HELPER(command_help_show, struct command *c, unsigned n, { char *cmd_name = command_name(c, ' '); if (NULL == cmd_name) - return -ENOMEM; + return ERROR_FAIL; /* If the match string occurs anywhere, we print out * stuff for this command. */ -- 2.30.2