fixup: uninitialized argument vector element

This patch addresses the potential issue of uninitialized elements in
the argument vector returned by `lwp_get_command_line_args()`. The
previous implementation could leave `argv` in an inconsistent state
if certain errors occurred, leading to possible undefined behavior.

Changes:
- Replaced `rt_malloc()` with `rt_calloc()` to ensure `argv` is properly initialized.
- Added a consistent error handling path using `goto error_exit` to handle memory allocation failures and string copy errors.
- Ensured `lwp_free_command_line_args()` is called before returning on error, preventing potential memory leaks.

Signed-off-by: Shell <smokewood@qq.com>
This commit is contained in:
Shell 2024-08-21 18:10:25 +08:00 committed by Meco Man
parent d6d6752627
commit 564ca848f4
1 changed files with 12 additions and 11 deletions

View File

@ -633,10 +633,10 @@ quit:
return error; return error;
} }
char** lwp_get_command_line_args(struct rt_lwp *lwp) char **lwp_get_command_line_args(struct rt_lwp *lwp)
{ {
size_t argc = 0; size_t argc = 0;
char** argv = NULL; char **argv = NULL;
int ret; int ret;
size_t i; size_t i;
size_t len; size_t len;
@ -648,7 +648,7 @@ char** lwp_get_command_line_args(struct rt_lwp *lwp)
{ {
return RT_NULL; return RT_NULL;
} }
argv = (char**)rt_malloc((argc + 1) * sizeof(char*)); argv = (char**)rt_calloc((argc + 1), sizeof(char*));
if (argv) if (argv)
{ {
@ -658,25 +658,23 @@ char** lwp_get_command_line_args(struct rt_lwp *lwp)
ret = lwp_data_get(lwp, &argvp, &((char **)lwp->args)[1 + i], sizeof(argvp)); ret = lwp_data_get(lwp, &argvp, &((char **)lwp->args)[1 + i], sizeof(argvp));
if (ret == 0) if (ret == 0)
{ {
lwp_free_command_line_args(argv); goto error_exit;
return RT_NULL;
} }
len = lwp_user_strlen_ext(lwp, argvp);
if (len > 0) len = lwp_user_strlen_ext(lwp, argvp);
if (len >= 0)
{ {
argv[i] = (char*)rt_malloc(len + 1); argv[i] = (char*)rt_malloc(len + 1);
ret = lwp_data_get(lwp, argv[i], argvp, len); ret = lwp_data_get(lwp, argv[i], argvp, len);
if (ret == 0) if (ret != len)
{ {
lwp_free_command_line_args(argv); goto error_exit;
return RT_NULL;
} }
argv[i][len] = '\0'; argv[i][len] = '\0';
} }
else else
{ {
argv[i] = NULL; goto error_exit;
} }
} }
argv[argc] = NULL; argv[argc] = NULL;
@ -684,6 +682,9 @@ char** lwp_get_command_line_args(struct rt_lwp *lwp)
} }
return argv; return argv;
error_exit:
lwp_free_command_line_args(argv);
return RT_NULL;
} }
void lwp_print_envp(struct rt_lwp *lwp) void lwp_print_envp(struct rt_lwp *lwp)