Skip to content

Instantly share code, notes, and snippets.

@573
Last active April 5, 2024 01:50
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 573/885a062ca49d2db355c22004cc395066 to your computer and use it in GitHub Desktop.
Save 573/885a062ca49d2db355c22004cc395066 to your computer and use it in GitHub Desktop.
How to build webassembly via rust using just nix
nix-shell -p wasm-pack cargo rustc -I nixpkgs=channel:nixos-unstable
cargo generate-lockfile
crate2nix generate -n '<nixos-unstable>'
nix-build -I nixpkgs=channel:nixos-unstable
wasm-pack build --target web

[INFO]: Checking for the Wasm target...
Error: wasm32-unknown-unknown target not found in sysroot: "/nix/store/lm64cjp5c5kc772rpmf88q22s8lr2zhi-rustc-1.40.0"

Used rustc from the following path: "/nix/store/lm64cjp5c5kc772rpmf88q22s8lr2zhi-rustc-1.40.0/bin/rustc"
It looks like Rustup is not being used. For non-Rustup setups, the wasm32-unknown-unknown target needs to be installed manually. See https://rustwasm.github.io/wasm-pack/book/prerequisites/non-rustup-setups.html on how to do this.

Did exactly that:

$(which rustc) --print sysroot

/nix/store/lm64cjp5c5kc772rpmf88q22s8lr2zhi-rustc-1.40.0

ls -lr /nix/store/lm64cjp5c5kc772rpmf88q22s8lr2zhi-rustc-1.40.0/lib/rustlib/wasm32-unknown-unknown/

drwxr-xr-x 1 me me 4096 Dec 16 17:43 lib

wasm-pack build --target web

[INFO]: Checking for the Wasm target...
[INFO]: Compiling to Wasm...
Compiling proc-macro2 v1.0.8
Compiling unicode-xid v0.2.0
Compiling syn v1.0.14
Compiling wasm-bindgen-shared v0.2.58
Compiling log v0.4.8
Compiling cfg-if v0.1.10
Compiling bumpalo v3.2.0
Compiling lazy_static v1.4.0
Compiling wasm-bindgen v0.2.58
error[E0514]: found crate core compiled by an incompatible version of rustc
|
= help: please recompile that crate using this compiler (rustc 1.40.0)
= note: the following crate versions were found:
crate core compiled by rustc 1.40.0 (73528e339 2019-12-16): /nix/store/lm64cjp5c5kc772rpmf88q22s8lr2zhi-rustc-1.40.0/lib/rustlib/wasm32-unknown-unknown/lib/libcore-ef54709e300503ed.rlib

error: aborting due to previous error

error: could not compile cfg-if.
warning: build failed, waiting for other jobs to finish...
error: build failed
Error: Compiling your crate to WebAssembly failed
Caused by: failed to execute cargo build: exited with exit code: 101

cargo-features = ["edition"]
[package]
edition = "2018"
name = "wasm-pack-examples"
version = "0.1.0"
authors = ["573 <me@gmail.com>"]
[lib]
crate-type = ["cdylib"]
[profile.release]
lto = true
[dependencies]
wasm-bindgen = "0.2"
# or just nix build -f Cargo.nix rootCrate.build
# ./result/bin/${your_crate_name}
{ pkgs ? import <nixpkgs> { config = {}; } }:
let cargo_nix = pkgs.callPackage ./Cargo.nix {};
in cargo_nix.rootCrate.build
#![allow(non_upper_case_globals)]
# src/lib.rs
use wasm_bindgen::prelude::*;
build:
date
RUSTFLAGS="-C linker=lld" cargo build --release --target wasm32-unknown-unknown
# TODO make work with watch, maybe builtfarm
clean:
cargo clean
# this allows caching of instability.
# making switches less annoying but also less up to date
import (
builtins.fetchGit (
{
url = "https://github.com/NixOS/nixpkgs";
ref = "master";
rev = "b61999e4ad60c351b4da63ae3ff43aae3c0bbdfb";
}
))
{ pkgs, stdenv, rustc }:
stdenv.mkDerivation {
name = "rust-src";
src = rustc.src;
phases = [ "unpackPhase" "installPhase" ];
installPhase = ''
mv src $out
rm -rf $out/{ci,doc,driver,etc,grammar,llvm,rt,rtstartup,rustllvm,test,tools,vendor}
'';
}
with import ./pin-unstable.nix { };
stdenv.mkDerivation {
name = "rust-env";
RUST_SRC_PATH = import ./rust-src.nix {
inherit stdenv;
inherit rustc;
inherit pkgs;
};
RUSTFLAGS="-C linker=lld";
nativeBuildInputs = [
(rustc.override {
stdenv = stdenv.override{
targetPlatform= {
parsed = {
cpu = { name = "wasm32"; };
vendor = {name = "unknown";};
kernel = {name = "unknown";};
abi = {name = "unknown";};
};
};
};
}) cargo wasm-pack llvmPackages_9.lld
##inotify-tools
];
# Set Environment Variables
RUST_BACKTRACE = 1;
}
@jappeace
Copy link

@573
Copy link
Author

573 commented Apr 16, 2020

@jappeace thanks, great, will try!

@573
Copy link
Author

573 commented Sep 23, 2020

@jappeace I got build errors copying your setup.

@jappeace
Copy link

It can't run that binary:

/nix/store/nbijngv5ywj7kh07ypgcfgxjrc5zpdwv-cargo-bootstrap-1.41.0/bin/cargo: line 3: /nix/store/nbijngv5ywj7kh07ypgcfgxjrc5zpdwv-cargo-bootstrap-1.41.0/bin/.cargo-wrapped: cannot execute binary file: Exec format error

I'm not sure why it's the wrong executable format. Almost looks like it's executed on a different architecture or operating system.
It's what google said: https://askubuntu.com/questions/648555/bash-program-cannot-execute-binary-file-exec-format-error

@573
Copy link
Author

573 commented Sep 23, 2020

I guess it's due that I setup my project afresh, have to do the steps where the unknown target is added once more and then we'll see.

[x] Tried:

$ nix-shell -p wasm-pack rustc cargo --command 'wasm-pack build --target web --out-name wasm'
warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels/nixpkgs' does not exist, ignoring
warning: Nix search path entry '/nix/var/nix/profiles/per-user/root/channels' does not exist, ignoring
[INFO]: Checking for the Wasm target...
Error: wasm32-unknown-unknown target not found in sysroot: "/nix/store/2i7l7nlnlhzvifk21i8a94p7y1544c9b-rustc-1.45.2"

Used rustc from the following path: "/nix/store/2i7l7nlnlhzvifk21i8a94p7y1544c9b-rustc-1.45.2/bin/rustc"
It looks like Rustup is not being used. For non-Rustup setups, the wasm32-unknown-unknown target needs to be installed manually. See https://rustwasm.github.io/wasm-pack/book/prerequisites/non-rustup-setups.html on how to do this.

Thanks for your input.

@winston0410
Copy link

Is there any solution on this right now, I have the same error with this flake. How can I set target for wasm32-unknown-unknown?:

{
  description = "wasm-pack setup";

  inputs = {
    nixpkgs = { url = "github:nixos/nixpkgs/nixos-unstable"; };
    rust-overlay = { url = "github:oxalica/rust-overlay"; };
  };

  outputs = { nixpkgs, rust-overlay, ... }:
    let system = "x86_64-linux";
    in {
      devShell.${system} = let
        overlay = [ (import rust-overlay) ];
        pkgs = import nixpkgs { inherit system overlay; };
      in (({ pkgs, ... }:
        pkgs.mkShell {
          buildInputs = with pkgs; [
            rustc
            cargo
            nodejs
            wasm-pack
          ];

          shellHook = "";
        }) { pkgs = pkgs; });
    };
}

@573
Copy link
Author

573 commented Oct 10, 2021

solution not here also no flakes experience but I'd like to add that I once had plans to bring the following approach (see original issue) further to also support wasm, link at bottom:

The example above is from the excellent blogpost (sources) @Xe wrote.

I changed one line in the nix/rust.nix file to contain just:

  targets = [ "x86_64-unknown-linux-musl" ];

and also added the line

  CARGO_BUILD_TARGET = "x86_64-unknown-linux-musl";

to the naersk.buildPackage closure in the file helloworld.nix.

This indeed built a static executable for me:

ldd result/bin/helloworld
statically linked

Originally posted by @573 in nix-community/naersk#155 (comment)

@winston0410
Copy link

winston0410 commented Oct 11, 2021

Hi I have a flake solution now, feel free to copy and paste

{
  description = "wasm-pack setup";

  inputs = {
    nixpkgs = { url = "github:nixos/nixpkgs/nixos-unstable"; };
    rust-overlay = { url = "github:oxalica/rust-overlay"; };
  };

  outputs = { nixpkgs, rust-overlay, ... }:
    let system = "x86_64-linux";
    in {
      devShell.${system} = let
        pkgs = import nixpkgs {
          inherit system;
          overlays = [ rust-overlay.overlay ];
        };
      in (({ pkgs, ... }:
        pkgs.mkShell {
          buildInputs = with pkgs; [
            cargo
            cargo-watch
            nodejs
            wasm-pack
            (rust-bin.stable.latest.default.override {
              extensions = [ "rust-src" ];
              targets = [ "wasm32-unknown-unknown" ];
            })
          ];

          shellHook = "";
        }) { pkgs = pkgs; });
    };
}

@573
Copy link
Author

573 commented Oct 11, 2021

awesome, thanks !

@jappeace
Copy link

@winston0410 better share the lock file as well, this won't last for very long without a pin.

@winston0410
Copy link

True, this is the flake.lock

{
  "nodes": {
    "flake-utils": {
      "locked": {
        "lastModified": 1623875721,
        "narHash": "sha256-A8BU7bjS5GirpAUv4QA+QnJ4CceLHkcXdRp4xITDB0s=",
        "owner": "numtide",
        "repo": "flake-utils",
        "rev": "f7e004a55b120c02ecb6219596820fcd32ca8772",
        "type": "github"
      },
      "original": {
        "owner": "numtide",
        "repo": "flake-utils",
        "type": "github"
      }
    },
    "nixpkgs": {
      "locked": {
        "lastModified": 1633528625,
        "narHash": "sha256-AGj5q58eHACAe0RQGxObrGwMUsjMozTsiznhsLCYisQ=",
        "owner": "nixos",
        "repo": "nixpkgs",
        "rev": "5e2018f7b383aeca6824a30c0cd1978c9532a46a",
        "type": "github"
      },
      "original": {
        "owner": "nixos",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "nixpkgs_2": {
      "locked": {
        "lastModified": 1628186154,
        "narHash": "sha256-r2d0wvywFnL9z4iptztdFMhaUIAaGzrSs7kSok0PgmE=",
        "owner": "NixOS",
        "repo": "nixpkgs",
        "rev": "06552b72346632b6943c8032e57e702ea12413bf",
        "type": "github"
      },
      "original": {
        "owner": "NixOS",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "root": {
      "inputs": {
        "nixpkgs": "nixpkgs",
        "rust-overlay": "rust-overlay"
      }
    },
    "rust-overlay": {
      "inputs": {
        "flake-utils": "flake-utils",
        "nixpkgs": "nixpkgs_2"
      },
      "locked": {
        "lastModified": 1633659483,
        "narHash": "sha256-tzEpYI8IMtzm/eqZp3tKe4A/g1iWF4xub0E58wA7uu0=",
        "owner": "oxalica",
        "repo": "rust-overlay",
        "rev": "7da3fe8b192f96dfe8b2223f4fe55e2e40850a2a",
        "type": "github"
      },
      "original": {
        "owner": "oxalica",
        "repo": "rust-overlay",
        "type": "github"
      }
    }
  },
  "root": "root",
  "version": 7
}

@GuillaumeDesforges
Copy link

Still working even without lockfile, many thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment