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 <borneo.antonio@gmail.com>
Reviewed-on: http://openocd.zylin.com/4838
Tested-by: jenkins
Reviewed-by: Tomas Vanek <vanekt@fbl.cz>
This commit is contained in:
Antonio Borneo 2019-01-08 09:54:30 +01:00 committed by Tomas Vanek
parent c0ec54d8ae
commit c4a7a62262

View File

@ -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. */