Skip to content

Environment variables don't work if main isn't used #180

Closed
@alexcrichton

Description

@alexcrichton

We discovered an issue in the Rust wasm32-wasi target today where a wasm binary uses std::env but doesn't end up importing the requisite wasi items to actually get env vars working.

The broken example looks like this:

#[no_mangle]
pub extern fn foo() {
    println!("{:?}", std::env::var("FOO"));
}

And when compiled:

$ rustc +nightly foo.rs --target wasm32-wasi -O --crate-type cdylib
$ wasm2wat foo.wasm | grep import
  (import "wasi_snapshot_preview1" "fd_write" (func $_ZN4wasi13lib_generated22wasi_snapshot_preview18fd_write17h8cb541fbb70a6a5bE (type 7)))

This is showing that environ_get isn't imported at all!

When compiled as a binary though it does indeed work:

fn main() {
    println!("{:?}", std::env::var("FOO"));
}
$ rustc +nightly foo.rs --target wasm32-wasi -O
$ wasm2wat foo.wasm | grep import
  (import "wasi_snapshot_preview1" "proc_exit" (func $__wasi_proc_exit (type 1)))
  (import "wasi_snapshot_preview1" "fd_write" (func $_ZN4wasi13lib_generated22wasi_snapshot_preview18fd_write17h8cb541fbb70a6a5bE (type 9)))
  (import "wasi_snapshot_preview1" "fd_prestat_get" (func $__wasi_fd_prestat_get (type 3)))
  (import "wasi_snapshot_preview1" "fd_prestat_dir_name" (func $__wasi_fd_prestat_dir_name (type 8)))
  (import "wasi_snapshot_preview1" "environ_sizes_get" (func $__wasi_environ_sizes_get (type 3)))
  (import "wasi_snapshot_preview1" "environ_get" (func $__wasi_environ_get (type 3)))

I'm told that @sunfishcode is working on a fix!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions