11#include <unistd.h>
22#include <stdlib.h>
33#include <sysexits.h>
4+ #ifdef __wasilibc_use_wasip2
5+ #include <wasi/wasip2.h>
6+ #else
47#include <wasi/api.h>
8+ #endif
59#include <wasi/libc.h>
610#include <wasi/libc-environ.h>
711
@@ -26,6 +30,55 @@ static char *empty_environ[1] = { NULL };
2630
2731// See the comments in libc-environ.h.
2832void __wasilibc_initialize_environ (void ) {
33+ #ifdef __wasilibc_use_wasip2
34+ // Get the environment
35+ wasip2_list_tuple2_string_string_t wasi_environment ;
36+ environment_get_environment (& wasi_environment );
37+
38+ size_t environ_count = wasi_environment .len ;
39+ if (environ_count == 0 ) {
40+ __wasilibc_environ = empty_environ ;
41+ return ;
42+ }
43+
44+ // Add 1 for the NULL pointer to mark the end, and check for overflow.
45+ size_t num_ptrs = environ_count + 1 ;
46+ if (num_ptrs == 0 ) {
47+ goto software ;
48+ }
49+
50+ // Allocate memory for the array of pointers. This uses `calloc` both to
51+ // handle overflow and to initialize the NULL pointer at the end.
52+ char * * environ_ptrs = calloc (num_ptrs , sizeof (char * ));
53+
54+ // Copy the environment variables
55+ for (size_t i = 0 ; i < environ_count ; i ++ ) {
56+ wasip2_tuple2_string_string_t pair = wasi_environment .ptr [i ];
57+ // 1 extra character for the null terminator, 1 for the '=' character
58+ environ_ptrs [i ] = malloc (pair .f0 .len + pair .f1 .len + 2 );
59+ if (!environ_ptrs [i ]) {
60+ for (size_t j = 0 ; j < i ; j ++ )
61+ free (environ_ptrs [j ]);
62+ free (environ_ptrs );
63+ goto software ;
64+ }
65+ memcpy (environ_ptrs [i ], pair .f0 .ptr , pair .f0 .len );
66+ environ_ptrs [i ][pair .f0 .len ] = '=' ;
67+ memcpy (environ_ptrs [i ] + pair .f0 .len + 1 , pair .f1 .ptr , pair .f1 .len );
68+ environ_ptrs [i ][pair .f0 .len + pair .f1 .len + 1 ] = '\0' ;
69+ }
70+
71+ // Free the WASI environment list
72+ wasip2_list_tuple2_string_string_free (& wasi_environment );
73+
74+ // Initialize the environment from the created array
75+ __wasilibc_environ = environ_ptrs ;
76+ return ;
77+ software :
78+ wasip2_list_tuple2_string_string_free (& wasi_environment );
79+ _Exit (EX_SOFTWARE );
80+
81+ #else
2982 // Get the sizes of the arrays we'll have to create to copy in the environment.
3083 size_t environ_count ;
3184 size_t environ_buf_size ;
@@ -74,6 +127,7 @@ void __wasilibc_initialize_environ(void) {
74127 _Exit (EX_OSERR );
75128software :
76129 _Exit (EX_SOFTWARE );
130+ #endif
77131}
78132
79133// See the comments in libc-environ.h.
0 commit comments