diff --git a/std/os.zig b/std/os.zig index 139bc5b09d64..c55597f13552 100644 --- a/std/os.zig +++ b/std/os.zig @@ -756,6 +756,37 @@ pub fn getEnvMap(allocator: *Allocator) !BufMap { try result.setMove(key, value); } + } else if (builtin.os == Os.wasi) { + var environ_count: usize = undefined; + var environ_buf_size: usize = undefined; + + const environ_sizes_get_ret = std.os.wasi.environ_sizes_get(&environ_count, &environ_buf_size); + if (environ_sizes_get_ret != os.wasi.ESUCCESS) { + return unexpectedErrorPosix(environ_sizes_get_ret); + } + + // TODO: Verify that the documentation is incorrect + // https://github.com/WebAssembly/WASI/issues/27 + var environ = try allocator.alloc(?[*]u8, environ_count + 1); + defer allocator.free(environ); + var environ_buf = try std.heap.wasm_allocator.alloc(u8, environ_buf_size); + defer allocator.free(environ_buf); + + const environ_get_ret = std.os.wasi.environ_get(environ.ptr, environ_buf.ptr); + if (environ_get_ret != os.wasi.ESUCCESS) { + return unexpectedErrorPosix(environ_get_ret); + } + + for (environ) |env| { + if (env) |ptr| { + const pair = mem.toSlice(u8, ptr); + var parts = mem.separate(pair, "="); + const key = parts.next().?; + const value = parts.next().?; + try result.set(key, value); + } + } + return result; } else { for (posix_environ_raw) |ptr| { var line_i: usize = 0; @@ -2190,7 +2221,7 @@ pub fn argsAlloc(allocator: *mem.Allocator) ![]const []u8 { } var result_slice = try allocator.alloc([]u8, count); - + var i: usize = 0; while (i < count) : (i += 1) { result_slice[i] = mem.toSlice(u8, argv[i]); diff --git a/std/os/wasi/core.zig b/std/os/wasi/core.zig index dc24218dfc5e..534fcc17efc7 100644 --- a/std/os/wasi/core.zig +++ b/std/os/wasi/core.zig @@ -13,8 +13,10 @@ pub const SIGABRT: signal_t = 6; pub extern "wasi_unstable" fn args_get(argv: [*][*]u8, argv_buf: [*]u8) errno_t; pub extern "wasi_unstable" fn args_sizes_get(argc: *usize, argv_buf_size: *usize) errno_t; -pub extern "wasi_unstable" fn proc_raise(sig: signal_t) errno_t; +pub extern "wasi_unstable" fn environ_get(environ: [*]?[*]u8, environ_buf: [*]u8) errno_t; +pub extern "wasi_unstable" fn environ_sizes_get(environ_count: *usize, environ_buf_size: *usize) errno_t; +pub extern "wasi_unstable" fn proc_raise(sig: signal_t) errno_t; pub extern "wasi_unstable" fn proc_exit(rval: exitcode_t) noreturn; pub extern "wasi_unstable" fn fd_write(fd: fd_t, iovs: *const ciovec_t, iovs_len: usize, nwritten: *usize) errno_t;