1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <inttypes.h>
5
6 #include "wasm.h"
7
8 #define own
9
10
print_frame(wasm_frame_t * frame)11 void print_frame(wasm_frame_t* frame) {
12 printf("> %p @ 0x%zx = %"PRIu32".0x%zx\n",
13 wasm_frame_instance(frame),
14 wasm_frame_module_offset(frame),
15 wasm_frame_func_index(frame),
16 wasm_frame_func_offset(frame)
17 );
18 }
19
20
main(int argc,const char * argv[])21 int main(int argc, const char* argv[]) {
22 // Initialize.
23 printf("Initializing...\n");
24 wasm_engine_t* engine = wasm_engine_new();
25 wasm_store_t* store = wasm_store_new(engine);
26
27 // Load binary.
28 printf("Loading binary...\n");
29 FILE* file = fopen("start.wasm", "r");
30 if (!file) {
31 printf("> Error loading module!\n");
32 return 1;
33 }
34 fseek(file, 0L, SEEK_END);
35 size_t file_size = ftell(file);
36 fseek(file, 0L, SEEK_SET);
37 wasm_byte_vec_t binary;
38 wasm_byte_vec_new_uninitialized(&binary, file_size);
39 if (fread(binary.data, file_size, 1, file) != 1) {
40 printf("> Error loading module!\n");
41 return 1;
42 }
43 fclose(file);
44
45 // Compile.
46 printf("Compiling module...\n");
47 own wasm_module_t* module = wasm_module_new(store, &binary);
48 if (!module) {
49 printf("> Error compiling module!\n");
50 return 1;
51 }
52
53 wasm_byte_vec_delete(&binary);
54
55 // Instantiate.
56 printf("Instantiating module...\n");
57 own wasm_trap_t* trap = NULL;
58 own wasm_instance_t* instance =
59 wasm_instance_new(store, module, NULL, &trap);
60 if (instance || !trap) {
61 printf("> Error instantiating module, expected trap!\n");
62 return 1;
63 }
64
65 wasm_module_delete(module);
66
67 // Print result.
68 printf("Printing message...\n");
69 own wasm_name_t message;
70 wasm_trap_message(trap, &message);
71 printf("> %s\n", message.data);
72
73 printf("Printing origin...\n");
74 own wasm_frame_t* frame = wasm_trap_origin(trap);
75 if (frame) {
76 print_frame(frame);
77 wasm_frame_delete(frame);
78 } else {
79 printf("> Empty origin.\n");
80 }
81
82 printf("Printing trace...\n");
83 own wasm_frame_vec_t trace;
84 wasm_trap_trace(trap, &trace);
85 if (trace.size > 0) {
86 for (size_t i = 0; i < trace.size; ++i) {
87 print_frame(trace.data[i]);
88 }
89 } else {
90 printf("> Empty trace.\n");
91 }
92
93 wasm_frame_vec_delete(&trace);
94 wasm_trap_delete(trap);
95 wasm_name_delete(&message);
96
97 // Shut down.
98 printf("Shutting down...\n");
99 wasm_store_delete(store);
100 wasm_engine_delete(engine);
101
102 // All done.
103 printf("Done.\n");
104 return 0;
105 }
106