5

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 (; ... ;))
)
4
  • I'm not sure if it is of any help, but i know that rust has a console-log crate specifically for WASM ( crates.io/crates/console_log ) ; you may benefit either from the rust sourcecode of that project, or by rust--build-->wasm-->wasm_textmode. Commented Dec 18, 2021 at 1: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. Commented Dec 18, 2021 at 4:33
  • Ahyea, shame. I hadn't played with it myself yet tbh, but just figured it may be relevant to your project. Commented Dec 18, 2021 at 4: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: github.com/bytecodealliance/wasmtime/blob/main/docs/… Commented Dec 23, 2022 at 5:50

1 Answer 1

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)
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.