1 module fib32; 2 3 import std.file : exists; 4 import std.stdio : writeln, printf, File; 5 import std.algorithm : endsWith; 6 import wasm3; 7 8 struct Fib 9 { 10 @disable this(); 11 this(uint stackByteSize) 12 { 13 env = Environment(null); 14 if (env is null) 15 { 16 writeln("Failed to create environment\n"); 17 return; 18 } 19 rt = env.newRuntime(stackByteSize); 20 if (rt.runtime is null) 21 { 22 writeln("Failed to init runtime\n"); 23 return; 24 } 25 } 26 27 void loadFile(string filename) 28 { 29 assert(exists(filename), "File does not exist: " ~ filename); 30 auto f = File(filename, "rb"); 31 if (!f.isOpen) 32 { 33 writeln("Failed to open file!\n"); 34 return; 35 } 36 buffer.length = 1024 * 512; 37 while (!f.eof) 38 { 39 wasmBytes = cast(ubyte[]) f.rawRead(buffer); 40 if (wasmBytes.length == 0) 41 { 42 writeln("Failed to read .wasm file\n"); 43 return; 44 } 45 } 46 writeln("Wasm file size: ", wasmBytes.length); 47 f.close(); 48 mod = env.parseModule(wasmBytes, wasmBytes.length); 49 result = env.result; 50 if (result !is null) 51 { 52 writeln("env.parseModule: "); 53 printf("%s\n", result); 54 return; 55 } 56 } 57 58 void loadContent(ubyte[] content, uint len) 59 { 60 mod = env.parseModule(content, len); 61 result = env.result; 62 if (result !is null) 63 { 64 writeln("env.parseModule: "); 65 printf("%s\n", result); 66 return; 67 } 68 } 69 70 void run() 71 { 72 result = m3_LoadModule(rt.runtime, mod.m_module); 73 if (result !is null) 74 { 75 writeln("m3_LoadModule: "); 76 printf("%s\n", result); 77 return; 78 } 79 80 result = m3_FindFunction(&func, rt.runtime, "fib"); 81 if (result !is null) 82 { 83 writeln("m3_FindFunction: "); 84 printf("%s\n", result); 85 return; 86 } 87 88 result = m3_CallV(func, 24); 89 if (result !is null) 90 { 91 writeln("m3_Call: "); 92 printf("%s\n", result); 93 return; 94 } 95 96 int* value = cast(int*)(rt.runtime.stack); 97 printf("Result: %d\n", *value); 98 } 99 100 IM3Function func; 101 Environment env; 102 Runtime rt; 103 Module mod; 104 const(char)* result = void; 105 ubyte[] buffer; 106 ubyte[] wasmBytes = void; 107 } 108 109 void main(string[] args) 110 { 111 112 Fib f = Fib(1024); 113 if (args.length > 1 && args[1].endsWith(".wasm")) 114 { 115 f.loadFile(args[1]); 116 } 117 else 118 { 119 f.loadContent(fib32_wasm, fib32_wasm.length); 120 } 121 f.run(); 122 } 123 124 ubyte[62] fib32_wasm = [ 125 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 126 0x01, 0x7f, 0x01, 0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01, 0x03, 127 0x66, 0x69, 0x62, 0x00, 0x00, 0x0a, 0x1f, 0x01, 0x1d, 0x00, 0x20, 0x00, 128 0x41, 0x02, 0x49, 0x04, 0x40, 0x20, 0x00, 0x0f, 0x0b, 0x20, 0x00, 0x41, 129 0x02, 0x6b, 0x10, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6b, 0x10, 0x00, 0x6a, 130 0x0f, 0x0b 131 ];