1+ #ifdef __wasilibc_use_wasip2
2+ #include <wasi/wasip2.h>
3+ #else
14#include <wasi/api.h>
5+ #endif
26#include <stdlib.h>
37#include <sysexits.h>
48
@@ -21,6 +25,46 @@ int __main_argc_argv(int argc, char *argv[]);
2125// (e.g. crt0.o or crtend.o) and teach Clang to use it when needed.
2226__attribute__((__weak__ , nodebug ))
2327int __main_void (void ) {
28+ #ifdef __wasilibc_use_wasip2
29+ wasip2_list_string_t argument_list ;
30+
31+ environment_get_arguments (& argument_list );
32+
33+ // Add 1 for the NULL pointer to mark the end, and check for overflow.
34+ size_t argc = argument_list .len ;
35+ size_t num_ptrs = argc + 1 ;
36+ if (num_ptrs == 0 ) {
37+ wasip2_list_string_free (& argument_list );
38+ _Exit (EX_SOFTWARE );
39+ }
40+
41+ // Allocate memory for the array of pointers. This uses `calloc` both to
42+ // handle overflow and to initialize the NULL pointer at the end.
43+ char * * argv = calloc (num_ptrs , sizeof (char * ));
44+ if (argv == NULL ) {
45+ wasip2_list_string_free (& argument_list );
46+ _Exit (EX_SOFTWARE );
47+ }
48+
49+ // Copy the arguments
50+ for (size_t i = 0 ; i < argc ; i ++ ) {
51+ wasip2_string_t wasi_string = argument_list .ptr [i ];
52+ size_t len = wasi_string .len ;
53+ argv [i ] = malloc (len + 1 );
54+ if (!argv [i ]) {
55+ wasip2_list_string_free (& argument_list );
56+ _Exit (EX_SOFTWARE );
57+ }
58+ memcpy (argv [i ], wasi_string .ptr , len );
59+ argv [i ][len ] = '\0' ;
60+ }
61+
62+ // Free the WASI argument list
63+ wasip2_list_string_free (& argument_list );
64+
65+ // Call `__main_argc_argv` with the arguments!
66+ return __main_argc_argv (argc , argv );
67+ #else
2468 __wasi_errno_t err ;
2569
2670 // Get the sizes of the arrays we'll have to create to copy in the args.
@@ -62,4 +106,5 @@ int __main_void(void) {
62106
63107 // Call `__main_argc_argv` with the arguments!
64108 return __main_argc_argv (argc , argv );
109+ #endif
65110}
0 commit comments