]> git.proxmox.com Git - wasi-libc.git/blobdiff - libc-bottom-half/libpreopen/libpreopen.c
Use constructor functions for optional init routines. (#142)
[wasi-libc.git] / libc-bottom-half / libpreopen / libpreopen.c
index 8800b89e5d4db58ebd4bbf7ea8a9143a80955914..25c104066f3f1df23c1f3d2fa7205889c6facf21 100644 (file)
@@ -54,6 +54,7 @@
 #include <errno.h>
 #include <dirent.h>
 #include <assert.h>
+#include <sysexits.h>
 #include <wasi/libc.h>
 #include <wasi/libc-find-relpath.h>
 
@@ -522,7 +523,10 @@ __wasilibc_find_relpath(
 
 /// This is referenced by weak reference from crt1.c and lives in the same source
 /// file as `__wasilibc_find_relpath` so that it's linked in when it's needed.
-__wasi_errno_t
+// Concerning the 51 -- see the comment by the constructor priority in
+// libc-bottom-half/sources/__environ.c.
+__attribute__((constructor(51)))
+static void
 __wasilibc_populate_libpreopen(void)
 {
     // Skip stdin, stdout, and stderr, and count up until we reach an invalid
@@ -533,24 +537,24 @@ __wasilibc_populate_libpreopen(void)
         if (ret == __WASI_ERRNO_BADF)
             break;
         if (ret != __WASI_ERRNO_SUCCESS)
-            return ret;
+            goto oserr;
         switch (prestat.pr_type) {
         case __WASI_PREOPENTYPE_DIR: {
             char *path = malloc(prestat.u.dir.pr_name_len + 1);
             if (path == NULL)
-                return __WASI_ERRNO_NOMEM;
+                goto software;
 
             // TODO: Remove the cast on `path` once the witx is updated with char8 support.
             ret = __wasi_fd_prestat_dir_name(fd, (uint8_t *)path, prestat.u.dir.pr_name_len);
             if (ret != __WASI_ERRNO_SUCCESS) {
                 free(path);
-                return ret;
+                goto oserr;
             }
             path[prestat.u.dir.pr_name_len] = '\0';
 
             if (internal_register_preopened_fd(fd, path) != 0) {
                 free(path);
-                return __WASI_ERRNO_NOMEM;
+                goto software;
             }
 
             break;
@@ -560,5 +564,9 @@ __wasilibc_populate_libpreopen(void)
         }
     }
 
-    return __WASI_ERRNO_SUCCESS;
+    return;
+oserr:
+    _Exit(EX_OSERR);
+software:
+    _Exit(EX_SOFTWARE);
 }