(module ;; import functions from env (func $close (import "env" "close") (param i32) (result i32)) (func $open (import "env" "open") (param i32 i32) (result i32)) (func $write (import "env" "write") (param i32 i32 i32) (result i32)) (func $read (import "env" "read") (param i32 i32 i32) (result i32)) (func $istty (import "env" "isatty") (param i32) (result i32)) (func $unlink (import "env" "unlink") (param i32) (result i32)) ;; memory (memory $mem 1) ;; constants (data (i32.const 200) "data") (data (i32.const 230) "Hello, world!\n") ;; functions (func $openFile (result i32) ;; open stdout (call $open (i32.const 200) (i32.const 42))) (func $writeHelloWorld (param $fd i32) ;; write hello world (call $write (get_local $fd) (i32.const 230) (i32.const 14)) (drop)) (func $readHello (param $fd i32) ;; read hello world (call $read (get_local $fd) (i32.const 255) (i32.const 14)) (drop)) (func $removeFile (call $unlink (i32.const 200)) (drop)) (func $main (result i32) (local $fd i32) ;; set $fd to the file descriptor (set_local $fd (call $openFile)) (call $writeHelloWorld (get_local $fd)) ;; close file (call $close (get_local $fd)) ;; set $fd to the new file descriptor (set_local $fd (call $openFile)) ;; read Hello, World (call $readHello (get_local $fd)) ;; istty (call $istty (get_local $fd)) (drop) ;; close file again (call $close (get_local $fd)) ;; unlink filename (call $removeFile) ;; return 0 (set_local $fd (i32.const 0)) (drop)) (export "main" (func $main)))