From 2e553194ecc4f9ebde7e417c68ddbf89ce2ea3a8 Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Thu, 24 Oct 2019 20:56:18 -0700 Subject: [PATCH] Allocate the argv buffers with alloca instead of malloc. This way, if an application doesn't otherwise use malloc, they don't need to link in malloc. Idea from https://github.com/CraneStation/wasi-libc/pull/118#discussion_r337596386! --- libc-bottom-half/sources/__original_main.c | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/libc-bottom-half/sources/__original_main.c b/libc-bottom-half/sources/__original_main.c index b1388535b..defebdf92 100644 --- a/libc-bottom-half/sources/__original_main.c +++ b/libc-bottom-half/sources/__original_main.c @@ -1,5 +1,6 @@ #include #include +#include #include #include @@ -27,27 +28,24 @@ int __original_main(void) { } // Allocate memory for storing the argument chars. - char *argv_buf = malloc(argv_buf_size); - if (argv_buf == NULL) { - _Exit(EX_SOFTWARE); - } + char *argv_buf = alloca(argv_buf_size); - // Allocate memory for the array of pointers. This uses `calloc` both to - // handle overflow and to initialize the NULL pointer at the end. - char **argv = calloc(num_ptrs, sizeof(char *)); - if (argv == NULL) { - free(argv_buf); + // Allocate memory for the array of pointers. + size_t num_ptrs_size; + if (__builtin_mul_overflow(num_ptrs, sizeof(char *), &num_ptrs_size)) { _Exit(EX_SOFTWARE); } + char **argv = alloca(num_ptrs_size); // Fill the argument chars, and the argv array with pointers into those chars. err = __wasi_args_get(argv, argv_buf); if (err != __WASI_ESUCCESS) { - free(argv_buf); - free(argv); _Exit(EX_OSERR); } + // Make sure the last pointer in the array is NULL. + argv[argc] = NULL; + // Call main with the arguments! return main(argc, argv); }