summaryrefslogtreecommitdiffstats
path: root/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/language-bindings/go/wamr/instance.go
blob: 08757f4dc6e27603b416907b45ef36eadad20162 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Copyright (C) 2019 Intel Corporation.  All rights reserved.
 * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 */

package wamr

/*
#include <stdlib.h>
#include <wasm_export.h>

static inline void
PUT_I64_TO_ADDR(uint32_t *addr, int64_t value)
{
    union {
        int64_t val;
        uint32_t parts[2];
    } u;
    u.val = value;
    addr[0] = u.parts[0];
    addr[1] = u.parts[1];
}

static inline void
PUT_F64_TO_ADDR(uint32_t *addr, double value)
{
    union {
        double val;
        uint32_t parts[2];
    } u;
    u.val = value;
    addr[0] = u.parts[0];
    addr[1] = u.parts[1];
}

static inline int64_t
GET_I64_FROM_ADDR(uint32_t *addr)
{
    union {
        int64_t val;
        uint32_t parts[2];
    } u;
    u.parts[0] = addr[0];
    u.parts[1] = addr[1];
    return u.val;
}

static inline double
GET_F64_FROM_ADDR(uint32_t *addr)
{
    union {
        double val;
        uint32_t parts[2];
    } u;
    u.parts[0] = addr[0];
    u.parts[1] = addr[1];
    return u.val;
}
*/
import "C"

import (
    "runtime"
    "unsafe"
    "fmt"
)

type Instance struct {
    _instance C.wasm_module_inst_t
    _exec_env C.wasm_exec_env_t
    _module *Module
    _exportsCache map[string]C.wasm_function_inst_t
}

/* Create instance from the module */
func NewInstance(module *Module,
                 stackSize uint, heapSize uint) (*Instance, error) {
    if (module == nil) {
        return nil, fmt.Errorf("NewInstance error: invalid input")
    }

    errorBytes := make([]byte, 128)
    errorPtr := (*C.char)(unsafe.Pointer(&errorBytes[0]))
    errorLen := C.uint(len(errorBytes))

    instance := C.wasm_runtime_instantiate(module.module, C.uint(stackSize),
                                           C.uint(heapSize), errorPtr, errorLen)
    if (instance == nil) {
        return nil, fmt.Errorf("NewInstance Error: %s", string(errorBytes))
    }

    exec_env := C.wasm_runtime_create_exec_env(instance, C.uint(stackSize))
    if (exec_env == nil) {
        C.wasm_runtime_deinstantiate(instance)
        return nil, fmt.Errorf("NewInstance Error: create exec_env failed")
    }

    self := &Instance{
        _instance: instance,
        _exec_env: exec_env,
        _module: module,
        _exportsCache: make(map[string]C.wasm_function_inst_t),
    }

    runtime.SetFinalizer(self, func(self *Instance) {
        self.Destroy()
    })

    return self, nil
}

/* Destroy the instance */
func (self *Instance) Destroy() {
    runtime.SetFinalizer(self, nil)
    if (self._instance != nil) {
        C.wasm_runtime_deinstantiate(self._instance)
    }
    if (self._exec_env != nil) {
        C.wasm_runtime_destroy_exec_env(self._exec_env)
    }
}

/* Call the wasm function with argument in the uint32 array, and store
   the return values back into the array */
func (self *Instance) CallFunc(funcName string,
                               argc uint32, args []uint32) error {
    _func := self._exportsCache[funcName]
    if _func == nil {
        cName := C.CString(funcName)
        defer C.free(unsafe.Pointer(cName))

        _func = C.wasm_runtime_lookup_function(self._instance,
                                               cName, (*C.char)(C.NULL))
        if _func == nil {
            return fmt.Errorf("CallFunc error: lookup function failed")
        }
        self._exportsCache[funcName] = _func
    }

    thread_env_inited := Runtime().ThreadEnvInited()
    if (!thread_env_inited) {
        Runtime().InitThreadEnv()
    }

    var args_C *C.uint32_t
    if (argc > 0) {
        args_C = (*C.uint32_t)(unsafe.Pointer(&args[0]))
    }
    if (!C.wasm_runtime_call_wasm(self._exec_env, _func,
                                  C.uint(argc), args_C)) {
        if (!thread_env_inited) {
            Runtime().DestroyThreadEnv()
        }
        return fmt.Errorf("CallFunc error: %s", string(self.GetException()))
    }

    if (!thread_env_inited) {
        Runtime().DestroyThreadEnv()
    }
    return nil
}

/* Call the wasm function with variant arguments, and store the return
   values back into the results array */
func (self *Instance) CallFuncV(funcName string,
                                num_results uint32, results []interface{},
                                args ... interface{}) error {
    _func := self._exportsCache[funcName]
    if _func == nil {
        cName := C.CString(funcName)
        defer C.free(unsafe.Pointer(cName))

        _func = C.wasm_runtime_lookup_function(self._instance,
                                               cName, (*C.char)(C.NULL))
        if _func == nil {
            return fmt.Errorf("CallFunc error: lookup function failed")
        }
        self._exportsCache[funcName] = _func
    }

    param_count := uint32(C.wasm_func_get_param_count(_func, self._instance))
    result_count := uint32(C.wasm_func_get_result_count(_func, self._instance))

    if (num_results < result_count) {
        str := "CallFunc error: invalid result count %d, " +
               "must be no smaller than %d"
        return fmt.Errorf(str, num_results, result_count)
    }

    param_types := make([]C.uchar, param_count, param_count)
    result_types := make([]C.uchar, result_count, result_count)
    if (param_count > 0) {
        C.wasm_func_get_param_types(_func, self._instance,
                                    (*C.uchar)(unsafe.Pointer(&param_types[0])))
    }
    if (result_count > 0) {
        C.wasm_func_get_result_types(_func, self._instance,
                                     (*C.uchar)(unsafe.Pointer(&result_types[0])))
    }

    argv_size := param_count * 2
    if (result_count > param_count) {
        argv_size = result_count * 2
    }
    argv := make([]uint32, argv_size, argv_size)

    var i, argc uint32
    for _, arg := range args {
        if (i >= param_count) {
            break;
        }
        switch arg.(type) {
            case int32:
                if (param_types[i] != C.WASM_I32 &&
                    param_types[i] != C.WASM_FUNCREF &&
                    param_types[i] != C.WASM_ANYREF) {
                    str := "CallFunc error: invalid param type %d, " +
                           "expect i32 but got other"
                    return fmt.Errorf(str, param_types[i])
                }
                argv[argc] = (uint32)(arg.(int32))
                argc++
                break
            case int64:
                if (param_types[i] != C.WASM_I64) {
                    str := "CallFunc error: invalid param type %d, " +
                           "expect i64 but got other"
                    return fmt.Errorf(str, param_types[i])
                }
                addr := (*C.uint32_t)(unsafe.Pointer(&argv[argc]))
                C.PUT_I64_TO_ADDR(addr, (C.int64_t)(arg.(int64)))
                argc += 2
                break
            case float32:
                if (param_types[i] != C.WASM_F32) {
                    str := "CallFunc error: invalid param type %d, " +
                           "expect f32 but got other"
                    return fmt.Errorf(str, param_types[i])
                }
                *(*C.float)(unsafe.Pointer(&argv[argc])) = (C.float)(arg.(float32))
                argc++
                break
            case float64:
                if (param_types[i] != C.WASM_F64) {
                    str := "CallFunc error: invalid param type %d, " +
                           "expect f64 but got other"
                    return fmt.Errorf(str, param_types[i])
                }
                addr := (*C.uint32_t)(unsafe.Pointer(&argv[argc]))
                C.PUT_F64_TO_ADDR(addr, (C.double)(arg.(float64)))
                argc += 2
                break
            default:
                return fmt.Errorf("CallFunc error: unknown param type %d",
                                  param_types[i])
        }
        i++
    }

    if (i < param_count) {
        str := "CallFunc error: invalid param count, " +
               "must be no smaller than %d"
        return fmt.Errorf(str, param_count)
    }

    err := self.CallFunc(funcName, argc, argv)
    if (err != nil) {
        return err
    }

    argc = 0
    for i = 0; i < result_count; i++ {
        switch result_types[i] {
            case C.WASM_I32:
            case C.WASM_FUNCREF:
            case C.WASM_ANYREF:
                i32 := (int32)(argv[argc])
                results[i] = i32
                argc++
                break
            case C.WASM_I64:
                addr := (*C.uint32_t)(unsafe.Pointer(&argv[argc]))
                results[i] = (int64)(C.GET_I64_FROM_ADDR(addr))
                argc += 2
                break
            case C.WASM_F32:
                addr := (*C.float)(unsafe.Pointer(&argv[argc]))
                results[i] = (float32)(*addr)
                argc++
                break
            case C.WASM_F64:
                addr := (*C.uint32_t)(unsafe.Pointer(&argv[argc]))
                results[i] = (float64)(C.GET_F64_FROM_ADDR(addr))
                argc += 2
                break
        }
    }

    return nil
}

/* Get exception info of the instance */
func (self *Instance) GetException() string {
    cStr := C.wasm_runtime_get_exception(self._instance)
    goStr := C.GoString(cStr)
    return goStr
}

/* Allocate memory from the heap of the instance */
func (self Instance) ModuleMalloc(size uint32) (uint32, *uint8) {
    var offset C.uint32_t
    native_addrs := make([]*uint8, 1, 1)
    ptr := unsafe.Pointer(&native_addrs[0])
    offset = C.wasm_runtime_module_malloc(self._instance, (C.uint32_t)(size),
                                          (*unsafe.Pointer)(ptr))
    return (uint32)(offset), native_addrs[0]
}

/* Free memory to the heap of the instance */
func (self Instance) ModuleFree(offset uint32) {
    C.wasm_runtime_module_free(self._instance, (C.uint32_t)(offset))
}

func (self Instance) ValidateAppAddr(app_offset uint32, size uint32) bool {
    ret := C.wasm_runtime_validate_app_addr(self._instance,
                                            (C.uint32_t)(app_offset),
                                            (C.uint32_t)(size))
    return (bool)(ret)
}

func (self Instance) ValidateStrAddr(app_str_offset uint32) bool {
    ret := C.wasm_runtime_validate_app_str_addr(self._instance,
                                                (C.uint32_t)(app_str_offset))
    return (bool)(ret)
}

func (self Instance) ValidateNativeAddr(native_ptr *uint8, size uint32) bool {
    native_ptr_C := (unsafe.Pointer)(native_ptr)
    ret := C.wasm_runtime_validate_native_addr(self._instance,
                                               native_ptr_C,
                                               (C.uint32_t)(size))
    return (bool)(ret)
}

func (self Instance) AddrAppToNative(app_offset uint32) *uint8 {
    native_ptr := C.wasm_runtime_addr_app_to_native(self._instance,
                                                    (C.uint32_t)(app_offset))
    return (*uint8)(native_ptr)
}

func (self Instance) AddrNativeToApp(native_ptr *uint8) uint32 {
    native_ptr_C := (unsafe.Pointer)(native_ptr)
    offset := C.wasm_runtime_addr_native_to_app(self._instance,
                                                native_ptr_C)
    return (uint32)(offset)
}

func (self Instance) GetAppAddrRange(app_offset uint32) (bool,
                                                         uint32,
                                                         uint32) {
    var start_offset, end_offset C.uint32_t
    ret := C.wasm_runtime_get_app_addr_range(self._instance,
                                             (C.uint32_t)(app_offset),
                                             &start_offset, &end_offset)
    return (bool)(ret), (uint32)(start_offset), (uint32)(end_offset)
}

func (self Instance) GetNativeAddrRange(native_ptr *uint8) (bool,
                                                            *uint8,
                                                            *uint8) {
    var start_addr, end_addr *C.uint8_t
    native_ptr_C := (*C.uint8_t)((unsafe.Pointer)(native_ptr))
    ret := C.wasm_runtime_get_native_addr_range(self._instance,
                                                native_ptr_C,
                                                &start_addr, &end_addr)
    return (bool)(ret), (*uint8)(start_addr), (*uint8)(end_addr)
}

func (self Instance) DumpMemoryConsumption() {
    C.wasm_runtime_dump_mem_consumption(self._exec_env)
}

func (self Instance) DumpCallStack() {
    C.wasm_runtime_dump_call_stack(self._exec_env)
}