4

I want to understand the WebAssembly text format for educational purposes and for writing a POC compiler that compiles straight to WASM.

I want to understand how to properly import the necessary WASI functions to create a console log function.

I'd love to see an example written in somewhat readable WAT of a module that imports WASI and implements a simple console log/printf/echo function that can run outside the browser.

e.g.,

(module
  (func $wasi_snapshot_preview1.fd_close (;0;) (import "wasi_snapshot_preview1" "fd_close") (param i32) (result i32))
  (func $wasi_snapshot_preview1.fd_seek (;1;) (import "wasi_snapshot_preview1" "fd_seek") (param i32 i64 i32 i32) (result i32))
  (func $wasi_snapshot_preview1.fd_write (;2;) (import "wasi_snapshot_preview1" "fd_write") (param i32 i32 i32 i32) (result i32))
  (func $wasi_snapshot_preview1.proc_exit (;3;) (import "wasi_snapshot_preview1" "proc_exit") (param i32))
  (data (; ... ;) )
  (memory (; ... ;) )
  (func $log (; ... ;))
)
José Mancharo
  • 175
  • 1
  • 14
  • I'm not sure if it is of any help, but i know that rust has a console-log crate specifically for WASM ( https://crates.io/crates/console_log ) ; you may benefit either from the rust sourcecode of that project, or by rust--build-->wasm-->wasm_textmode. – Raxi Dec 18 '21 at 01:55
  • I've tried compiling a rust hello world using the wasm32-wasi target, but the `println!` macro generates a huge amount of overhead along with the standard library. I'm not looking to use the browser `console.log`, but instead write to the stdout file descriptor in a desktop/embedded wasi environment. – José Mancharo Dec 18 '21 at 04:33
  • Ahyea, shame. I hadn't played with it myself yet tbh, but just figured it may be relevant to your project. – Raxi Dec 18 '21 at 04:45
  • The Wasmtime docs include an example of using the WebAssembly text format (`.wat`) to write a file. It's not console.log, but it might prove a useful starting point: https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-tutorial.md#web-assembly-text-example – Jordan Eldredge Dec 23 '22 at 05:50

1 Answers1

0

This code imports the log function from JS and uses it to print a number:

(module
  (func $log (import "imports" "log") (param i32))
  (func (export "logNumber")
    i32.const 13
    call $log)
)
shluvme
  • 713
  • 7
  • 24