247368f28eb01f5938a332104693e2493f4a2ee4
[platform/framework/web/lwnode.git] /
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 const int iterations = 100000;
11
12 int live_count = 0;
13
14 void finalize(void* data) {
15   int i = (int)data;
16   if (i % (iterations / 10) == 0) printf("Finalizing #%d...\n", i);
17   --live_count;
18 }
19
20 void run_in_store(wasm_store_t* store) {
21   // Load binary.
22   printf("Loading binary...\n");
23   FILE* file = fopen("finalize.wasm", "r");
24   if (!file) {
25     printf("> Error loading module!\n");
26     exit(1);
27   }
28   fseek(file, 0L, SEEK_END);
29   size_t file_size = ftell(file);
30   fseek(file, 0L, SEEK_SET);
31   wasm_byte_vec_t binary;
32   wasm_byte_vec_new_uninitialized(&binary, file_size);
33   if (fread(binary.data, file_size, 1, file) != 1) {
34     printf("> Error loading module!\n");
35     exit(1);
36   }
37   fclose(file);
38
39   // Compile.
40   printf("Compiling module...\n");
41   own wasm_module_t* module = wasm_module_new(store, &binary);
42   if (!module) {
43     printf("> Error compiling module!\n");
44     exit(1);
45   }
46
47   wasm_byte_vec_delete(&binary);
48
49   // Instantiate.
50   printf("Instantiating modules...\n");
51   for (int i = 0; i <= iterations; ++i) {
52     if (i % (iterations / 10) == 0) printf("%d\n", i);
53     own wasm_instance_t* instance =
54       wasm_instance_new(store, module, NULL, NULL);
55     if (!instance) {
56       printf("> Error instantiating module %d!\n", i);
57       exit(1);
58     }
59     void* data = (void*)(intptr_t)i;
60     wasm_instance_set_host_info_with_finalizer(instance, data, &finalize);
61     wasm_instance_delete(instance);
62     ++live_count;
63   }
64
65   wasm_module_delete(module);
66 }
67
68 int main(int argc, const char* argv[]) {
69   // Initialize.
70   printf("Initializing...\n");
71   wasm_engine_t* engine = wasm_engine_new();
72
73   printf("Live count %d\n", live_count);
74   printf("Creating store 1...\n");
75   wasm_store_t* store1 = wasm_store_new(engine);
76
77   printf("Running in store 1...\n");
78   run_in_store(store1);
79   printf("Live count %d\n", live_count);
80
81   printf("Creating store 2...\n");
82   wasm_store_t* store2 = wasm_store_new(engine);
83
84   printf("Running in store 2...\n");
85   run_in_store(store2);
86   printf("Live count %d\n", live_count);
87
88   printf("Deleting store 2...\n");
89   wasm_store_delete(store2);
90   printf("Live count %d\n", live_count);
91
92   printf("Running in store 1...\n");
93   run_in_store(store1);
94   printf("Live count %d\n", live_count);
95
96   printf("Deleting store 1...\n");
97   wasm_store_delete(store1);
98   printf("Live count %d\n", live_count);
99
100   assert(live_count == 0);
101
102   // Shut down.
103   printf("Shutting down...\n");
104   wasm_engine_delete(engine);
105
106   // All done.
107   printf("Done.\n");
108   return 0;
109 }