Utilities for loading and running WASM modules from Dart code

Overview

Provides utilities for loading and running WASM modules

Built on top of the Wasmer runtime.

Setup

Run dart run wasm:setup to build the Wasmer runtime.

Basic Usage

As a simple example, we'll try to call the following C function from Dart using package:wasm. For a more detailed example that uses WASI, check out the example directory.

extern "C" int square(int n) { return n * n; }

We can compile this C++ code to WASM using a recent version of the clang compiler:

clang --target=wasm32 -nostdlib -Wl,--export-all -Wl,--no-entry -o square.wasm square.cc

Then we can load and run it like this:

import 'dart:io';
import 'package:wasm/wasm.dart';

void main() {
  final data = File('square.wasm').readAsBytesSync();
  final mod = WasmModule(data);
  print(mod.describe());
  final inst = mod.builder().build();
  final square = inst.lookupFunction('square');
  print(square(12));
}

This should print:

export memory: memory
export function: int32 square(int32)

144
Issues
  • `dart run wasm:setup` fails (on windows? latest dev? not sure)

    `dart run wasm:setup` fails (on windows? latest dev? not sure)

    I couldn't resist trying to run this in between meetings. :p

    PS C:\Users\micro\Documents\GitHub\wasm> dart --version
    Dart SDK version: 2.14.0-182.0.dev (dev) (Thu Jun 3 16:01:27 2021 -0700) on "windows_x64"
    
    [√] Flutter (Channel master, 2.3.0-17.0.pre.220, on Microsoft Windows [Version 10.0.19041.985], locale en-US)
        • Flutter version 2.3.0-17.0.pre.220 at C:\Users\micro\flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 2f88966935 (75 minutes ago), 2021-06-04 13:58:21 -0700
        • Engine revision 03d645e782
        • Dart version 2.14.0 (build 2.14.0-182.0.dev)
    
    PS C:\Users\micro\Documents\GitHub\wasm> dart pub get
    Resolving dependencies...
      analyzer 1.7.0 (1.7.1 available)
    Got dependencies!
    PS C:\Users\micro\Documents\GitHub\wasm> dart run wasm:setup      
    Unhandled exception:
    Invalid argument(s): Could not find ".dart_tool/package_config.json" within "file:///C:/Users/micro/Documents/GitHub/wasm/".
    #0      _getOutDir (file:///C:/Users/micro/Documents/GitHub/wasm/bin/setup.dart:64:5)
    #1      _main (file:///C:/Users/micro/Documents/GitHub/wasm/bin/setup.dart:118:18)
    #2      main (file:///C:/Users/micro/Documents/GitHub/wasm/bin/setup.dart:25:11)
    <asynchronous suspension>
    

    Although there is a comment in the code (_getLibName) suggesting windows support may not be implemented yet, so maybe this is expected.

    Please feel free to disregard if this is not helpful. I just was curious to play with the fancy new code, that's all. Maybe I'll find some time on a weekend to hack on it a bit.

    bug 
    opened by eseidel 24
  • Include setup script in flutter_wasm

    Include setup script in flutter_wasm

    It's necessary to run package:wasm's setup.dart script when using package:flutter_wasm, but pub says "Cannot run executables in transitive dependencies.". So in the documentation users are told to depend on package:wasm as well as package:flutter_wasm. This is not ideal.

    It would be better to include setup.dart in flutter_wasm. It would be nice to figure out a way to avoid code duplication, but export 'package:wasm/bin/setup.dart'; doesn't work because that path is relative to wasm/lib/, so it can't get to the bin directory.

    enhancement 
    opened by liamappelbe 21
  • Switch to a singleton store

    Switch to a singleton store

    This is one of the feature requests from #38

    This change should be transparent to users at this stage, but will enable future features like sharing memory or functions between modules.

    opened by liamappelbe 9
  • Initial commit of package:flutter_wasm

    Initial commit of package:flutter_wasm

    Only Android is supported at the moment. #40

    opened by liamappelbe 7
  • CI: enable windows

    CI: enable windows

    opened by kevmoo 4
  • fn_import_exception_test flakey on mac

    fn_import_exception_test flakey on mac

    Tried it on linux without an issue.

    Mac @ Dart 2.12 https://github.com/dart-lang/wasm/pull/12/checks?check_run_id=2750754609#step:7:568

    Mac @ Dart SDK version: 2.14.0-176.0.dev (dev) (Wed Jun 2 15:17:55 2021 -0700) on "macos_x64" https://github.com/dart-lang/wasm/pull/12/checks?check_run_id=2750754624#step:7:190

    Here's a repro.

    // Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
    // for details. All rights reserved. Use of this source code is governed by a
    // BSD-style license that can be found in the LICENSE file.
    
    // Test throwing exceptions from an imported function.
    import 'dart:typed_data';
    
    import 'package:wasm/wasm.dart';
    
    void main() {
      var data = Uint8List.fromList([
        0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60, //
        0x00, 0x00, 0x02, 0x11, 0x02, 0x03, 0x65, 0x6e, 0x76, 0x01, 0x61, 0x00,
        0x00, 0x03, 0x65, 0x6e, 0x76, 0x01, 0x62, 0x00, 0x00, 0x03, 0x02, 0x01,
        0x00, 0x04, 0x05, 0x01, 0x70, 0x01, 0x01, 0x01, 0x05, 0x03, 0x01, 0x00,
        0x02, 0x06, 0x08, 0x01, 0x7f, 0x01, 0x41, 0x80, 0x88, 0x04, 0x0b, 0x07,
        0x0f, 0x02, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x02,
        0x66, 0x6e, 0x00, 0x02, 0x0a, 0x10, 0x01, 0x0e, 0x00, 0x10, 0x80, 0x80,
        0x80, 0x80, 0x00, 0x10, 0x81, 0x80, 0x80, 0x80, 0x00, 0x0b,
      ]);
    
      var thrownException = Exception('Hello exception!');
    
      var errorCount = 0;
      for (var i = 0; true; i++) {
        var builder = (WasmModule(data).builder()
          ..addFunction('env', 'a', () {
            throw thrownException;
          })
          ..addFunction('env', 'b', () {
            throw StateError('should not get here!');
          }));
    
        var inst = builder.build();
    
        var fn = inst.lookupFunction('fn');
    
        try {
          fn();
        } on Exception {
          // noop
        } catch (e, stack) {
          print(e);
          print(stack);
          errorCount++;
    
          if (errorCount > 10) {
            break;
          }
        }
        print([errorCount, i]);
      }
    }
    
    bug 
    opened by kevmoo 4
  • Async compilation and instantiation

    Async compilation and instantiation

    Add WasmModule.compileAsync and WasmInstanceBuilder.buildAsync, so that the web API can be supported in the future.

    #34

    opened by liamappelbe 3
  • Support Windows in setup.dart

    Support Windows in setup.dart

    Fixes https://github.com/dart-lang/wasm/issues/9

    opened by liamappelbe 3
  • Look to upgrade to wasmer v2.0.0

    Look to upgrade to wasmer v2.0.0

    https://wasmer.io/posts/wasmer-2.0

    V2 is out.

    I tried. Tests don't work. But worth investigating.

    enhancement 
    opened by kevmoo 3
  • dart run wasm:setup fails on linux when referenced as a dependency pointing to git

    dart run wasm:setup fails on linux when referenced as a dependency pointing to git

    I tried to reproduce the example on README on Ubuntu and it failed when i executed dart run wasm:setup.

    I got this error:

    ...
    manifest path `/home/abner/dart-wasm-project/.dart_tool/pub/bin/wasm/Cargo.toml` does not exist
    

    I referenced the wasm project in my pubspec.yaml using git reference:

    dependencies:
      wasm: 
        git:
          url: https://github.com/dart-lang/wasm.git
          ref: main
    

    I manually copied the files in the wasm repository bin folder (Cargo.toml, finalizers.cc, setup.dart, wasmer.rs) into my .dart_tool/pub/bin/wasm and after it, the command dart run wasm:setup just worked.

    Actually, i wanna also to know if dart-lang/wasm is intended to work inside Flutter apps (both mobile, desktop and web)?

    opened by abner 3
  • Fix test

    Fix test "deserializing module from file"

    See https://github.com/wasmerio/wasmer/issues/2707 for details

    opened by liamappelbe 0
  • Update to Wasmer 2.1.0

    Update to Wasmer 2.1.0

    null

    opened by liamappelbe 0
  • Enable non-standard features

    Enable non-standard features

    In the Rust Wasmer SDK, there is a way to enable non-standard features such as threads and simd through https://docs.rs/wasmer/latest/wasmer/struct.Features.html . Please could we enable these with the dart package or at least provide a way to enable selected ones?

    opened by rhobro 0
  • Support Flutter Desktop

    Support Flutter Desktop

    Add desktop support to flutter_wasm plugin.

    enhancement 
    opened by liamappelbe 0
  • Configure Wasmer engine to use: Singlepass, Cranelift, (LLVM)

    Configure Wasmer engine to use: Singlepass, Cranelift, (LLVM)

    The way that wasm_bindgen in Rust can access functions that are defined externally, how does one allow the WASM to call dart functions?

    enhancement 
    opened by rhobro 12
  • Support Android x64

    Support Android x64

    Block on https://github.com/wasmerio/wasmer/issues/2099

    enhancement 
    opened by liamappelbe 0
  • Support Android arm32

    Support Android arm32

    Blocked on https://github.com/wasmerio/wasmer/issues/2324

    enhancement 
    opened by liamappelbe 0
  • import_error_test crash on exit

    import_error_test crash on exit

    The crash is in the wasm imported function finalizers. With all the finalizers, the isolate shutdown flow is pretty complicated:

    Test finishes (Dart code) -> Dart_ShutdownIsolate, finalizes weak handles (Dart VM, C++ code) -> wasm_func_finalizer (package:wasm, C++ code) -> wasm_func_delete (wasmer, Rust code) -> ... -> wasm_func_new_with_env::drop (wasmer, Rust code) -> _wasmFnImportFinalizer (package:wasm, Dart code)

    That last step from Rust to Dart is where the crash is happening. I suppose it makes sense that this step would crash if the isolate is shutting down. I don't understand why this is only crashing in this one test though, since every pretty much every test has something like this flow. Need to investigate a bit more.

    I've disabled this finalizer for now, since this only leaks a _WasmFnImport, which is small.

    bug 
    opened by liamappelbe 1
  • WIP: Enable windows CI

    WIP: Enable windows CI

    null

    opened by liamappelbe 0
  • Support Android/iOS

    Support Android/iOS

    I am having an issue with the WasmModule loading. I have the following in my Flutter app:

      final data = await rootBundle.load('assets/add.wasm');
    
      final mod = WasmModule(data.buffer.asUint8List());
    
      print(mod.describe());
    
      final inst = mod.builder().build();
      final add = inst.lookupFunction('add_one');
    
      print(add(12));
    

    I have run dart run wasm:setup. The issue I find is Directory.current.uri returns \ which is obviously incorrect. In particular, I am talking about _getLibPath() where locating the library fails.

    Is this not designed to work with Flutter applications? Mobile in particular.

    enhancement 
    opened by jlalvarez18 2
Owner
Dart
Dart is an open-source, scalable programming language, with robust libraries and runtimes, for building web, server, and mobile apps.
Dart
A Flutter package for building custom skeleton widgets to mimic the page's layout while loading.

Skeletons A Flutter package for building custom skeleton widgets to mimic the page's layout while loading. Examples Items ListView (Default) ListView

Moh Badjah 24 Jan 13, 2022
A multiplatform Dart movie app with 40% of code sharing between Flutter and the Web.

A multiplatform Dart movie app with 40% of code sharing between Flutter and the Web.

Iiro Krankka 3.2k Jan 17, 2022
A Dart library for creating a Dart object to represent directory trees.

Directory Tree A Dart library for creating a Dart object to represent directory trees. Getting Started Import and initialize package import 'package:d

Chiziaruhoma Ogbonda 5 Dec 1, 2021
Berikut merupakan source code Chat Apps dengan Flutter + GetX + Firebase

chatapp A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

Sandikha Rahardi 17 Dec 28, 2021
Source code for @flutter.master

Flutter-Master Reels Onboarding screen Go Personal Finance Go Nike Store Go Travel App Go Solar system App Go Animations Implicit animations Go Tween

null 18 Dec 21, 2021
A simple and easy to use Redis client for Dart

redis_dart A simple and minimalist Redis client for Dart See it in pub: https://pub.dev/packages/redis_dart and GitHub: https://github.com/gabrielpach

Gabriel Pacheco 5 Jan 11, 2022
GChat is a chatting application developed using Flutter(Dart) and firebase for 2 users. Trying to Develop an application that does not sell your data with whatsapp rolling out its privacy policy updates.

Gchat - The Chatting Application A Flutter project for chatting. I used Android Studio and you can you any editor of your choice for ex: VS Code, Inte

Sanchaksh Kaul 5 Aug 17, 2021
A full, sound, modern and documented JS interop for Dart.

This is (or should be) a full JavaScript interop package using package:js bindings. The bindings are generated by machine-reading WebIDL files for typ

Jonathan Rezende 17 Dec 24, 2021
Unofficial Bavatar dart app for android, iOS and macOS

Unofficial Bavatar dart app for android, iOS and macOS Generated by the Very Good CLI ?? Getting Started ?? This project contains 3 flavors: developme

Pishure 3 Jul 12, 2021
server side dart micro-framework to handle incoming http requests

Queen Palace ???? Introduction server side dart micro-framework to handle incoming http requests

Ahmed Masoud 30 Dec 12, 2021
Nhost Dart & Flutter packages

Nhost Packages for Dart & Flutter Package nhost_sdk Dart authentication and file storage API clients nhost_flutter_auth Flutter widgets for exposing N

Nhost 32 Dec 10, 2021
Upper is a open source back-end framework based on the Dart language.

What is Upper? Upper is a open source back-end framework based on the Dart language. With it, it is possible to automatically generate a gRPC API for

Andriws Luna 39 Jan 8, 2022
a python-like bytes_io implementation for dart

bytes_io A python-like bytes_io implementation for dart A powerful helper for processing raw binary data Usage A simple usage example: import 'package

Kelly 6 Dec 21, 2021
A simple app to keep track the time you Learn, Playing, Reading, ... in every week. This is also my attempt to teach myself Flutter & Dart

Progressor 0.0.1 Sometime you want to set a target for you weekly, for example: "Reading Book for 8 hours every week". This app helps you to do that.

Son Nguyen Hoang 3 Aug 8, 2021
A type-safe command-line parsing library for Dart

plade Plade is a type-safe CLI parsing library for Dart. Highlights Fully type-safe and null-safe. Support for a variety of different parsing styles (

Ryan Gonzalez 6 Jan 1, 2022
Agent library for Internet Computer, in Dart

agent_dart An agent library built for Internet Computer, a plugin package for dart and flutter apps. Developers can build ones to interact with Dfinit

null 47 Jan 5, 2022
ThingsBoard PE API client library for Dart developers.

ThingsBoard PE API client library for Dart developers. It's compatible with TB PE 3.3.0. Usage A simple usage example: import 'package:thingsboard_pe_

ThingsBoard - Open-source IoT Platform 40 Dec 17, 2021
This is a fully fledged Sudoku game written in Dart using Flutter.

This is a fully fledged Sudoku game written in Dart using Flutter.

Varun Shanbhag 24 Jan 9, 2022
A bugless implementation of BigDecimal in Dart based on Java's BigDecimal

big_decimal A bugless implementation of BigDecimal in Dart based on Java's BigDecimal Installation Add the following to your pubspec.yaml: dependencie

null 11 Dec 23, 2021