1
+ #ifdef __wasilibc_use_wasip2
2
+ #include <wasi/wasip2.h>
3
+ #else
1
4
#include <wasi/api.h>
5
+ #endif
2
6
#include <stdlib.h>
3
7
#include <sysexits.h>
4
8
@@ -21,6 +25,46 @@ int __main_argc_argv(int argc, char *argv[]);
21
25
// (e.g. crt0.o or crtend.o) and teach Clang to use it when needed.
22
26
__attribute__((__weak__ , nodebug ))
23
27
int __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
24
68
__wasi_errno_t err ;
25
69
26
70
// Get the sizes of the arrays we'll have to create to copy in the args.
@@ -62,4 +106,5 @@ int __main_void(void) {
62
106
63
107
// Call `__main_argc_argv` with the arguments!
64
108
return __main_argc_argv (argc , argv );
109
+ #endif
65
110
}
0 commit comments