]> git.proxmox.com Git - wasi-libc.git/blob - libc-bottom-half/sources/__original_main.c
31ce665e9da8f350e2ff2d7a2218141db2a151ef
[wasi-libc.git] / libc-bottom-half / sources / __original_main.c
1 #include <wasi/core.h>
2 #include <wasi/libc.h>
3 #include <stdlib.h>
4 #include <sysexits.h>
5
6 // The user's `main` function, expecting arguments.
7 int main(int argc, char *argv[]);
8
9 // If the user's `main` function expects arguments, the compiler won't emit
10 // an `__original_main` function so this version will get linked in, which
11 // initializes the argument data and calls `main`.
12 __attribute__((weak))
13 int __original_main(void) {
14 __wasi_errno_t err;
15
16 // Get the sizes of the arrays we'll have to create to copy in the args.
17 size_t argv_buf_size;
18 size_t argc;
19 err = __wasi_args_sizes_get(&argc, &argv_buf_size);
20 if (err != __WASI_ESUCCESS) {
21 _Exit(EX_OSERR);
22 }
23
24 // Add 1 for the NULL pointer to mark the end, and check for overflow.
25 size_t num_ptrs = argc + 1;
26 if (num_ptrs == 0) {
27 _Exit(EX_SOFTWARE);
28 }
29
30 // Allocate memory for storing the argument chars.
31 char *argv_buf = malloc(argv_buf_size);
32 if (argv_buf == NULL) {
33 _Exit(EX_SOFTWARE);
34 }
35
36 // Allocate memory for the array of pointers. This uses `calloc` both to
37 // handle overflow and to initialize the NULL pointer at the end.
38 char **argv = calloc(num_ptrs, sizeof(char *));
39 if (argv == NULL) {
40 free(argv_buf);
41 _Exit(EX_SOFTWARE);
42 }
43
44 // Fill the argument chars, and the argv array with pointers into those chars.
45 err = __wasi_args_get(argv, argv_buf);
46 if (err != __WASI_ESUCCESS) {
47 free(argv_buf);
48 free(argv);
49 _Exit(EX_OSERR);
50 }
51
52 // Call main with the arguments!
53 return main(argc, argv);
54 }