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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! Defines WasmEdge Executor.

use super::ffi;
#[cfg(all(feature = "async", target_os = "linux"))]
use crate::r#async::fiber::{AsyncState, FiberFuture};

#[cfg(all(feature = "async", target_os = "linux", not(target_env = "musl")))]
use crate::r#async::fiber::TimeoutFiberFuture;

use crate::{
    instance::module::InnerInstance, types::WasmEdgeString, utils::check, Config, Engine, FuncRef,
    Function, ImportModule, Instance, Module, Statistics, Store, WasiInstance, WasmEdgeResult,
    WasmValue,
};
use parking_lot::Mutex;
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
use std::os::raw::c_void;
use std::sync::Arc;
use wasmedge_types::error::WasmEdgeError;

#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub(crate) struct JmpState {
    pub(crate) sigjmp_buf: *mut setjmp::sigjmp_buf,
}

#[cfg(all(target_os = "linux", not(target_env = "musl")))]
scoped_tls::scoped_thread_local!(pub(crate) static JMP_BUF: JmpState);

#[cfg(all(target_os = "linux", not(target_env = "musl")))]
unsafe extern "C" fn sync_timeout(sig: i32, info: *mut libc::siginfo_t) {
    if let Some(info) = info.as_mut() {
        let si_value = info.si_value();
        let value: *mut libc::pthread_t = si_value.sival_ptr.cast();
        let dist_pthread = *value;
        let self_pthread = libc::pthread_self();
        if self_pthread == dist_pthread {
            if JMP_BUF.is_set() {
                let env = JMP_BUF.with(|s| s.sigjmp_buf);
                setjmp::siglongjmp(env, 1);
            }
        } else {
            libc::pthread_sigqueue(dist_pthread, sig, si_value);
        }
    }
}
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
unsafe extern "C" fn pre_host_func(_: *mut c_void) {
    use libc::SIG_BLOCK;

    let mut set = std::mem::zeroed();
    libc::sigemptyset(&mut set);
    libc::sigaddset(&mut set, timeout_signo());
    libc::pthread_sigmask(SIG_BLOCK, &set, std::ptr::null_mut());
}
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
unsafe extern "C" fn post_host_func(_: *mut c_void) {
    use libc::SIG_UNBLOCK;

    let mut set = std::mem::zeroed();
    libc::sigemptyset(&mut set);
    libc::sigaddset(&mut set, timeout_signo());
    libc::pthread_sigmask(SIG_UNBLOCK, &set, std::ptr::null_mut());
}

#[inline]
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub(crate) fn timeout_signo() -> i32 {
    option_env!("SIG_OFFSET")
        .and_then(|s| s.parse().ok())
        .unwrap_or(0)
        + libc::SIGRTMIN()
}

#[cfg(all(target_os = "linux", not(target_env = "musl")))]
static INIT_SIGNAL_LISTEN: std::sync::Once = std::sync::Once::new();

#[inline(always)]
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub(crate) unsafe fn init_signal_listen() {
    INIT_SIGNAL_LISTEN.call_once(|| {
        let mut new_act: libc::sigaction = std::mem::zeroed();
        new_act.sa_sigaction = sync_timeout as usize;
        new_act.sa_flags = libc::SA_RESTART | libc::SA_SIGINFO;
        libc::sigaction(timeout_signo(), &new_act, std::ptr::null_mut());
    });
}

/// Defines an execution environment for both pure WASM and compiled WASM.
#[derive(Debug, Clone)]
pub struct Executor {
    pub(crate) inner: Arc<InnerExecutor>,
    pub(crate) registered: bool,
}
impl Executor {
    /// Creates a new [executor](crate::Executor) to be associated with the given [config](crate::Config) and [statistics](crate::Statistics).
    ///
    /// # Arguments
    ///
    /// * `config` - The configuration of the new [executor](crate::Executor).
    ///
    /// * `stat` - The [statistics](crate::Statistics) needed by the new [executor](crate::Executor).
    ///
    /// # Error
    ///
    /// If fail to create a [executor](crate::Executor), then an error is returned.
    pub fn create(config: Option<&Config>, stat: Option<&mut Statistics>) -> WasmEdgeResult<Self> {
        let ctx = match config {
            Some(config) => match stat {
                Some(stat) => unsafe { ffi::WasmEdge_ExecutorCreate(config.inner.0, stat.inner.0) },
                None => unsafe {
                    ffi::WasmEdge_ExecutorCreate(config.inner.0, std::ptr::null_mut())
                },
            },
            None => match stat {
                Some(stat) => unsafe {
                    ffi::WasmEdge_ExecutorCreate(std::ptr::null_mut(), stat.inner.0)
                },
                None => unsafe {
                    ffi::WasmEdge_ExecutorCreate(std::ptr::null_mut(), std::ptr::null_mut())
                },
            },
        };

        match ctx.is_null() {
            true => Err(Box::new(WasmEdgeError::ExecutorCreate)),
            false => {
                #[cfg(all(target_os = "linux", not(target_env = "musl")))]
                unsafe {
                    ffi::WasmEdge_ExecutorExperimentalRegisterPreHostFunction(
                        ctx,
                        std::ptr::null_mut(),
                        Some(pre_host_func),
                    );
                    ffi::WasmEdge_ExecutorExperimentalRegisterPostHostFunction(
                        ctx,
                        std::ptr::null_mut(),
                        Some(post_host_func),
                    );
                }

                Ok(Executor {
                    inner: Arc::new(InnerExecutor(ctx)),
                    registered: false,
                })
            }
        }
    }

    /// Registers and instantiates the given [WASI instance](crate::WasiInstance) into a [store](crate::Store).
    ///
    /// # Arguments
    ///
    /// * `store` - The target [store](crate::Store), into which the given [wasi instance] is registered.
    ///
    /// * `instance` - The [WASI instance](crate::WasiInstance) to be registered.
    ///
    /// # Error
    ///
    /// If fail to register the given [WASI instance](crate::WasiInstance), then an error is returned.
    pub fn register_wasi_instance(
        &mut self,
        store: &Store,
        instance: &WasiInstance,
    ) -> WasmEdgeResult<()> {
        match instance {
            #[cfg(not(feature = "async"))]
            WasiInstance::Wasi(import) => unsafe {
                check(ffi::WasmEdge_ExecutorRegisterImport(
                    self.inner.0,
                    store.inner.0,
                    import.inner.0 as *const _,
                ))?;
            },
            #[cfg(all(feature = "async", target_os = "linux"))]
            WasiInstance::AsyncWasi(import) => unsafe {
                check(ffi::WasmEdge_ExecutorRegisterImport(
                    self.inner.0,
                    store.inner.0,
                    import.inner.0 as *const _,
                ))?;
            },
        }

        Ok(())
    }

    /// Registers and instantiates a [import module](crate::ImportModule) into a [store](crate::Store).
    ///
    /// # Arguments
    ///
    /// * `store` - The target [store](crate::Store), into which the given [import module](crate::ImportModule) is registered.
    ///
    /// * `import` - The WasmEdge [import module](crate::ImportModule) to be registered.
    ///
    /// # Error
    ///
    /// If fail to register the given [import module](crate::ImportModule), then an error is returned.
    pub fn register_import_module<T>(
        &mut self,
        store: &Store,
        import: &ImportModule<T>,
    ) -> WasmEdgeResult<()>
    where
        T: ?Sized + Send + Sync + Clone,
    {
        unsafe {
            check(ffi::WasmEdge_ExecutorRegisterImport(
                self.inner.0,
                store.inner.0,
                import.inner.0 as *const _,
            ))?;
        }

        Ok(())
    }

    /// Registers and instantiates a WasmEdge [module](crate::Module) into a store.
    ///
    /// Instantiates the given WasmEdge [module](crate::Module), including the [functions](crate::Function), [memories](crate::Memory), [tables](crate::Table), and [globals](crate::Global) it hosts; and then, registers the module [instance](crate::Instance) into the [store](crate::Store) with the given name.
    ///
    /// # Arguments
    ///
    /// * `store` - The target [store](crate::Store), into which the given [module](crate::Module) is registered.
    ///
    /// * `module` - A validated [module](crate::Module) to be registered.
    ///
    /// * `name` - The exported name of the registered [module](crate::Module).
    ///
    /// # Error
    ///
    /// If fail to register the given [module](crate::Module), then an error is returned.
    pub fn register_named_module(
        &mut self,
        store: &Store,
        module: &Module,
        name: impl AsRef<str>,
    ) -> WasmEdgeResult<Instance> {
        let mut instance_ctx = std::ptr::null_mut();
        let mod_name: WasmEdgeString = name.as_ref().into();
        unsafe {
            check(ffi::WasmEdge_ExecutorRegister(
                self.inner.0,
                &mut instance_ctx,
                store.inner.0,
                module.inner.0 as *const _,
                mod_name.as_raw(),
            ))?;
        }

        Ok(Instance {
            inner: Arc::new(Mutex::new(InnerInstance(instance_ctx))),
            registered: false,
        })
    }

    /// Registers and instantiates a WasmEdge [module](crate::Module) into a [store](crate::Store) as an anonymous module.
    ///
    /// Notice that when a new module is instantiated into the [store](crate::Store), the old instantiated module is removed; in addition, ensure that the [imports](crate::ImportModule) the module depends on are already registered into the [store](crate::Store).
    ///
    ///
    /// # Arguments
    ///
    /// * `store` - The [store](crate::Store), in which the [module](crate::Module) to be instantiated
    /// is stored.
    ///
    /// * `ast_mod` - The target [module](crate::Module) to be instantiated.
    ///
    /// # Error
    ///
    /// If fail to instantiate the given [module](crate::Module), then an error is returned.
    pub fn register_active_module(
        &mut self,
        store: &Store,
        module: &Module,
    ) -> WasmEdgeResult<Instance> {
        let mut instance_ctx = std::ptr::null_mut();
        unsafe {
            check(ffi::WasmEdge_ExecutorInstantiate(
                self.inner.0,
                &mut instance_ctx,
                store.inner.0,
                module.inner.0 as *const _,
            ))?;
        }
        Ok(Instance {
            inner: Arc::new(Mutex::new(InnerInstance(instance_ctx))),
            registered: false,
        })
    }

    /// Registers plugin module instance into a [store](crate::Store).
    ///
    /// # Arguments
    ///
    /// * `store` - The [store](crate::Store), in which the [module](crate::Module) to be instantiated
    /// is stored.
    ///
    /// * `instance` - The plugin module instance to be registered.
    ///
    /// # Error
    ///
    /// If fail to register the given plugin module instance, then an error is returned.
    pub fn register_plugin_instance(
        &mut self,
        store: &Store,
        instance: &Instance,
    ) -> WasmEdgeResult<()> {
        unsafe {
            check(ffi::WasmEdge_ExecutorRegisterImport(
                self.inner.0,
                store.inner.0,
                instance.inner.lock().0 as *const _,
            ))?;
        }

        Ok(())
    }

    /// Runs a host function instance and returns the results.
    ///
    /// # Arguments
    ///
    /// * `func` - The function instance to run.
    ///
    /// * `params` - The arguments to pass to the function.
    ///
    /// # Errors
    ///
    /// If fail to run the host function, then an error is returned.
    pub fn call_func(
        &self,
        func: &Function,
        params: impl IntoIterator<Item = WasmValue>,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        let raw_params = params.into_iter().map(|x| x.as_raw()).collect::<Vec<_>>();

        // get the length of the function's returns
        let func_ty = func.ty()?;
        let returns_len = func_ty.returns_len();
        let mut returns = Vec::with_capacity(returns_len as usize);

        unsafe {
            check(ffi::WasmEdge_ExecutorInvoke(
                self.inner.0,
                func.inner.lock().0 as *const _,
                raw_params.as_ptr(),
                raw_params.len() as u32,
                returns.as_mut_ptr(),
                returns_len,
            ))?;

            returns.set_len(returns_len as usize);
        }

        Ok(returns.into_iter().map(Into::into).collect::<Vec<_>>())
    }

    /// Run a host function instance and return the results or timeout.
    ///
    /// # Arguments
    ///
    /// * `func` - The function instance to run.
    ///
    /// * `params` - The arguments to pass to the function.
    ///
    /// * `timeout` - The maximum execution time of the function to be run.
    ///
    /// # Errors
    ///
    /// If fail to run the host function, then an error is returned.
    #[cfg(all(target_os = "linux", not(target_env = "musl")))]
    #[cfg_attr(docsrs, doc(cfg(all(target_os = "linux", not(target_env = "musl")))))]
    pub fn call_func_with_timeout(
        &self,
        func: &Function,
        params: impl IntoIterator<Item = WasmValue>,
        timeout: std::time::Duration,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        use wasmedge_types::error;

        let raw_params = params.into_iter().map(|x| x.as_raw()).collect::<Vec<_>>();
        // get the length of the function's returns
        let func_ty = func.ty()?;
        let returns_len = func_ty.returns_len();
        let mut returns = Vec::with_capacity(returns_len as usize);

        unsafe {
            init_signal_listen();
            let mut self_thread = libc::pthread_self();
            let mut sigjmp_buf: setjmp::sigjmp_buf = std::mem::zeroed();
            let env = &mut sigjmp_buf as *mut _;

            let mut timerid: libc::timer_t = std::mem::zeroed();
            let mut sev: libc::sigevent = std::mem::zeroed();
            sev.sigev_notify = libc::SIGEV_SIGNAL;
            sev.sigev_signo = timeout_signo();
            sev.sigev_value.sival_ptr = &mut self_thread as *mut _ as *mut libc::c_void;

            if libc::timer_create(libc::CLOCK_REALTIME, &mut sev, &mut timerid) < 0 {
                return Err(Box::new(error::WasmEdgeError::Operation(
                    "timer_create error".into(),
                )));
            }
            let mut value: libc::itimerspec = std::mem::zeroed();
            value.it_value.tv_sec = timeout.as_secs() as _;
            value.it_value.tv_nsec = timeout.subsec_nanos() as _;
            if libc::timer_settime(timerid, 0, &value, std::ptr::null_mut()) < 0 {
                libc::timer_delete(timerid);
                return Err(Box::new(error::WasmEdgeError::Operation(
                    "timer_settime error".into(),
                )));
            }
            let jmp_state = JmpState { sigjmp_buf: env };

            JMP_BUF.set(&jmp_state, || {
                if setjmp::sigsetjmp(env, 1) == 0 {
                    let r = check(ffi::WasmEdge_ExecutorInvoke(
                        self.inner.0,
                        func.inner.lock().0 as *const _,
                        raw_params.as_ptr(),
                        raw_params.len() as u32,
                        returns.as_mut_ptr(),
                        returns_len,
                    ));
                    libc::timer_delete(timerid);
                    r
                } else {
                    libc::timer_delete(timerid);
                    Err(Box::new(error::WasmEdgeError::ExecuteTimeout))
                }
            })?;

            returns.set_len(returns_len as usize);
            Ok(returns.into_iter().map(Into::into).collect::<Vec<_>>())
        }
    }

    /// Asynchronously runs a host function instance and returns the results.
    ///
    /// # Arguments
    ///
    /// * `async_state` - Used to store asynchronous state at run time.
    ///
    /// * `func` - The function instance to run.
    ///
    /// * `params` - The arguments to pass to the function.
    ///
    /// # Errors
    ///
    /// If fail to run the host function, then an error is returned.
    #[cfg(all(feature = "async", target_os = "linux"))]
    #[cfg_attr(docsrs, doc(cfg(all(feature = "async", target_os = "linux"))))]
    pub async fn call_func_async(
        &self,
        async_state: &AsyncState,
        func: &Function,
        params: impl IntoIterator<Item = WasmValue> + Send,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        FiberFuture::on_fiber(async_state, || self.call_func(func, params))
            .await
            .unwrap()
    }

    /// Asynchronously runs a host function instance with a timeout setting
    ///
    /// # Arguments
    ///
    /// * `async_state` - Used to store asynchronous state at run time.
    ///
    /// * `func` - The function instance to run.
    ///
    /// * `params` - The arguments to pass to the function.
    ///
    /// * `timeout` - The maximum execution time of the function to be run.
    ///
    /// # Errors
    ///
    /// If fail to run the host function, then an error is returned.
    #[cfg(all(feature = "async", target_os = "linux", not(target_env = "musl")))]
    #[cfg_attr(
        docsrs,
        doc(cfg(all(feature = "async", target_os = "linux", not(target_env = "musl"))))
    )]
    #[cfg(feature = "async")]
    pub async fn call_func_async_with_timeout(
        &self,
        async_state: &AsyncState,
        func: &Function,
        params: impl IntoIterator<Item = WasmValue> + Send,
        timeout: std::time::Duration,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        use wasmedge_types::error;
        let ldd = std::time::SystemTime::now() + timeout;
        TimeoutFiberFuture::on_fiber(async_state, || self.call_func(func, params), ldd)
            .await
            .map_err(|_| Box::new(error::WasmEdgeError::ExecuteTimeout))?
    }

    /// Runs a host function reference instance and returns the results.
    ///
    /// # Arguments
    ///
    /// * `func_ref` - The function reference instance to run.
    ///
    /// * `params` - The arguments to pass to the function.
    ///
    /// # Errors
    ///
    /// If fail to run the host function reference instance, then an error is returned.
    pub fn call_func_ref(
        &self,
        func_ref: &FuncRef,
        params: impl IntoIterator<Item = WasmValue>,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        let raw_params = params.into_iter().map(|x| x.as_raw()).collect::<Vec<_>>();

        // get the length of the function's returns
        let func_ty = func_ref.ty()?;
        let returns_len = func_ty.returns_len();
        let mut returns = Vec::with_capacity(returns_len as usize);

        unsafe {
            check(ffi::WasmEdge_ExecutorInvoke(
                self.inner.0,
                func_ref.inner.0 as *const _,
                raw_params.as_ptr(),
                raw_params.len() as u32,
                returns.as_mut_ptr(),
                returns_len,
            ))?;
            returns.set_len(returns_len as usize);
        }

        Ok(returns.into_iter().map(Into::into).collect::<Vec<_>>())
    }

    /// Asynchronously runs a host function reference instance and returns the results.
    ///
    /// # Arguments
    ///
    /// * `async_state` - Used to store asynchronous state at run time.
    ///
    /// * `func_ref` - The function reference instance to run.
    ///
    /// * `params` - The arguments to pass to the function.
    ///
    /// # Errors
    ///
    /// If fail to run the host function reference instance, then an error is returned.
    #[cfg(all(feature = "async", target_os = "linux"))]
    #[cfg_attr(docsrs, doc(cfg(all(feature = "async", target_os = "linux"))))]
    pub async fn call_func_ref_async(
        &self,
        async_state: &AsyncState,
        func_ref: &FuncRef,
        params: impl IntoIterator<Item = WasmValue> + Send,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        FiberFuture::on_fiber(async_state, || self.call_func_ref(func_ref, params))
            .await
            .unwrap()
    }

    /// Provides a raw pointer to the inner Executor context.
    #[cfg(feature = "ffi")]
    #[cfg_attr(docsrs, doc(cfg(feature = "ffi")))]
    pub fn as_ptr(&self) -> *const ffi::WasmEdge_ExecutorContext {
        self.inner.0 as *const _
    }
}
impl Drop for Executor {
    fn drop(&mut self) {
        if !self.registered && Arc::strong_count(&self.inner) == 1 && !self.inner.0.is_null() {
            unsafe { ffi::WasmEdge_ExecutorDelete(self.inner.0) }
        }
    }
}
impl Engine for Executor {
    fn run_func(
        &self,
        func: &Function,
        params: impl IntoIterator<Item = WasmValue>,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        self.call_func(func, params)
    }

    fn run_func_ref(
        &self,
        func_ref: &FuncRef,
        params: impl IntoIterator<Item = WasmValue>,
    ) -> WasmEdgeResult<Vec<WasmValue>> {
        self.call_func_ref(func_ref, params)
    }
}

#[derive(Debug)]
pub(crate) struct InnerExecutor(pub(crate) *mut ffi::WasmEdge_ExecutorContext);
unsafe impl Send for InnerExecutor {}
unsafe impl Sync for InnerExecutor {}

#[cfg(test)]
mod tests {
    use super::*;
    cfg_if::cfg_if! {
        if #[cfg(all(feature = "async", target_os = "linux"))] {
            use crate::r#async::AsyncWasiModule;
            use crate::{Loader, Validator};
            use wasmedge_macro::sys_async_host_function;
        }
    }
    use crate::{
        AsImport, CallingFrame, Config, FuncType, Function, Global, GlobalType, ImportModule,
        MemType, Memory, Statistics, Table, TableType, HOST_FUNCS, HOST_FUNC_FOOTPRINTS,
    };
    use std::{
        sync::{Arc, Mutex},
        thread,
    };
    use wasmedge_macro::sys_host_function;
    use wasmedge_types::{error::HostFuncError, Mutability, NeverType, RefType, ValType};

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_executor_create() {
        {
            // create an Executor context without configuration and statistics
            let result = Executor::create(None, None);
            assert!(result.is_ok());
            let executor = result.unwrap();
            assert!(!executor.inner.0.is_null());
        }

        {
            // create an Executor context with a given configuration
            let result = Config::create();
            assert!(result.is_ok());
            let config = result.unwrap();
            let result = Executor::create(Some(&config), None);
            assert!(result.is_ok());
            let executor = result.unwrap();
            assert!(!executor.inner.0.is_null());
        }

        {
            // create an Executor context with a given statistics
            let result = Statistics::create();
            assert!(result.is_ok());
            let mut stat = result.unwrap();
            let result = Executor::create(None, Some(&mut stat));
            assert!(result.is_ok());
            let executor = result.unwrap();
            assert!(!executor.inner.0.is_null());
        }

        {
            // create an Executor context with the given configuration and statistics.
            let result = Config::create();
            assert!(result.is_ok());
            let config = result.unwrap();

            let result = Statistics::create();
            assert!(result.is_ok());
            let mut stat = result.unwrap();

            let result = Executor::create(Some(&config), Some(&mut stat));
            assert!(result.is_ok());
            let executor = result.unwrap();
            assert!(!executor.inner.0.is_null());
        }
    }

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_executor_register_import() {
        // create an Executor
        let result = Executor::create(None, None);
        assert!(result.is_ok());
        let mut executor = result.unwrap();
        assert!(!executor.inner.0.is_null());

        // create a Store
        let result = Store::create();
        assert!(result.is_ok());
        let mut store = result.unwrap();

        // create an ImportObj module
        let host_name = "extern";
        let result = ImportModule::<NeverType>::create(host_name, None);
        assert!(result.is_ok());
        let mut import = result.unwrap();

        assert_eq!(HOST_FUNCS.read().len(), 0);
        assert_eq!(HOST_FUNC_FOOTPRINTS.lock().len(), 0);

        // add host function "func-add": (externref, i32) -> (i32)
        let result = FuncType::create([ValType::ExternRef, ValType::I32], [ValType::I32]);
        assert!(result.is_ok());
        let func_ty = result.unwrap();
        let result = Function::create_sync_func::<NeverType>(&func_ty, Box::new(real_add), None, 0);
        assert!(result.is_ok());
        let host_func = result.unwrap();
        // add the function into the import_obj module
        import.add_func("func-add", host_func);

        // create a Table instance
        let result = TableType::create(RefType::FuncRef, 10, Some(20));
        assert!(result.is_ok());
        let table_ty = result.unwrap();
        let result = Table::create(&table_ty);
        assert!(result.is_ok());
        let host_table = result.unwrap();
        // add the table into the import_obj module
        import.add_table("table", host_table);

        // create a Memory instance
        let result = MemType::create(1, Some(2), false);
        assert!(result.is_ok());
        let mem_ty = result.unwrap();
        let result = Memory::create(&mem_ty);
        assert!(result.is_ok());
        let host_memory = result.unwrap();
        // add the memory into the import_obj module
        import.add_memory("memory", host_memory);

        // create a Global instance
        let result = GlobalType::create(ValType::I32, Mutability::Const);
        assert!(result.is_ok());
        let global_ty = result.unwrap();
        let result = Global::create(&global_ty, WasmValue::from_i32(666));
        assert!(result.is_ok());
        let host_global = result.unwrap();
        // add the global into import_obj module
        import.add_global("global_i32", host_global);

        let result = executor.register_import_module(&mut store, &import);
        assert!(result.is_ok());

        {
            let result = store.module("extern");
            assert!(result.is_ok());
            let instance = result.unwrap();

            let result = instance.get_global("global_i32");
            assert!(result.is_ok());
            let global = result.unwrap();
            assert_eq!(global.get_value().to_i32(), 666);
        }

        let handle = thread::spawn(move || {
            let result = store.module("extern");
            assert!(result.is_ok());
            let instance = result.unwrap();

            let result = instance.get_global("global_i32");
            assert!(result.is_ok());
            let global = result.unwrap();
            assert_eq!(global.get_value().to_i32(), 666);
        });

        handle.join().unwrap();
    }

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_executor_send() {
        // create an Executor context with the given configuration and statistics.
        let result = Config::create();
        assert!(result.is_ok());
        let config = result.unwrap();

        let result = Statistics::create();
        assert!(result.is_ok());
        let mut stat = result.unwrap();

        let result = Executor::create(Some(&config), Some(&mut stat));
        assert!(result.is_ok());
        let executor = result.unwrap();
        assert!(!executor.inner.0.is_null());

        let handle = thread::spawn(move || {
            assert!(!executor.inner.0.is_null());
            println!("{:?}", executor.inner);
        });

        handle.join().unwrap();
    }

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_executor_sync() {
        // create an Executor context with the given configuration and statistics.
        let result = Config::create();
        assert!(result.is_ok());
        let config = result.unwrap();

        let result = Statistics::create();
        assert!(result.is_ok());
        let mut stat = result.unwrap();

        let result = Executor::create(Some(&config), Some(&mut stat));
        assert!(result.is_ok());
        let executor = Arc::new(Mutex::new(result.unwrap()));

        let executor_cloned = Arc::clone(&executor);
        let handle = thread::spawn(move || {
            let result = executor_cloned.lock();
            assert!(result.is_ok());
            let executor = result.unwrap();

            assert!(!executor.inner.0.is_null());
        });

        handle.join().unwrap();
    }

    #[cfg(all(feature = "async", target_os = "linux"))]
    #[tokio::test]
    async fn test_executor_register_async_wasi() -> Result<(), Box<dyn std::error::Error>> {
        // create a Config
        let mut config = Config::create()?;
        config.wasi(true);
        assert!(config.wasi_enabled());

        // create an Executor
        let result = Executor::create(None, None);
        assert!(result.is_ok());
        let mut executor = result.unwrap();
        assert!(!executor.inner.0.is_null());

        // create a Store
        let result = Store::create();
        assert!(result.is_ok());
        let mut store = result.unwrap();

        // create an AsyncWasiModule
        let result = AsyncWasiModule::create(Some(vec!["abc"]), Some(vec![("ENV", "1")]), None);
        assert!(result.is_ok());
        let async_wasi_module = result.unwrap();

        let wasi_import = WasiInstance::AsyncWasi(async_wasi_module);
        let result = executor.register_wasi_instance(&mut store, &wasi_import);
        assert!(result.is_ok());

        // register async_wasi module into the store
        let wasm_file = std::env::current_dir()
            .unwrap()
            .ancestors()
            .nth(2)
            .unwrap()
            .join("examples/wasmedge-sys/async_hello.wasm");
        let module = Loader::create(None)?.from_file(&wasm_file)?;
        Validator::create(None)?.validate(&module)?;
        let instance = executor.register_active_module(&mut store, &module)?;
        let fn_start = instance.get_func("_start")?;

        async fn tick() {
            let mut i = 0;
            loop {
                println!("[tick] i={i}");
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                i += 1;
            }
        }
        tokio::spawn(tick());

        dbg!("call async host func");

        let async_state = AsyncState::new();
        let _ = executor
            .call_func_async(&async_state, &fn_start, [])
            .await?;

        dbg!("call async host func done");

        Ok(())
    }

    #[cfg(all(feature = "async", target_os = "linux"))]
    #[tokio::test]
    async fn test_executor_run_async_host_func() -> Result<(), Box<dyn std::error::Error>> {
        fn async_hello(
            _frame: CallingFrame,
            _inputs: Vec<WasmValue>,
            _: *mut std::os::raw::c_void,
        ) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)>
        {
            Box::new(async move {
                for _ in 0..10 {
                    println!("[async hello] say hello");
                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                }

                println!("[async hello] Done!");

                Ok(vec![])
            })
        }

        // create a Config
        let mut config = Config::create()?;
        config.wasi(true);
        assert!(config.wasi_enabled());

        // create an Executor
        let result = Executor::create(None, None);
        assert!(result.is_ok());
        let mut executor = result.unwrap();
        assert!(!executor.inner.0.is_null());

        // create a Store
        let result = Store::create();
        assert!(result.is_ok());
        let mut store = result.unwrap();

        // create an AsyncWasiModule
        let result = AsyncWasiModule::create(None, None, None);
        assert!(result.is_ok());
        let async_wasi_module = result.unwrap();

        // register async_wasi module into the store
        let wasi_import = WasiInstance::AsyncWasi(async_wasi_module);
        let result = executor.register_wasi_instance(&mut store, &wasi_import);
        assert!(result.is_ok());

        let ty = FuncType::create([], [])?;
        let async_hello_func =
            Function::create_async_func::<NeverType>(&ty, Box::new(async_hello), None, 0)?;
        let mut import = ImportModule::<NeverType>::create("extern", None)?;
        import.add_func("async_hello", async_hello_func);

        executor.register_import_module(&mut store, &import)?;

        let extern_instance = store.module("extern")?;
        let async_hello = extern_instance.get_func("async_hello")?;

        async fn tick() {
            let mut i = 0;
            loop {
                println!("[tick] i={i}");
                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                i += 1;
            }
        }
        tokio::spawn(tick());

        let async_state = AsyncState::new();
        let _ = executor
            .call_func_async(&async_state, &async_hello, [])
            .await?;

        Ok(())
    }

    #[sys_host_function]
    fn real_add(
        _frame: CallingFrame,
        inputs: Vec<WasmValue>,
    ) -> Result<Vec<WasmValue>, HostFuncError> {
        if inputs.len() != 2 {
            return Err(HostFuncError::User(1));
        }

        let a = if inputs[0].ty() == ValType::I32 {
            inputs[0].to_i32()
        } else {
            return Err(HostFuncError::User(2));
        };

        let b = if inputs[1].ty() == ValType::I32 {
            inputs[1].to_i32()
        } else {
            return Err(HostFuncError::User(3));
        };

        let c = a + b;

        Ok(vec![WasmValue::from_i32(c)])
    }

    #[cfg(all(feature = "async", target_os = "linux"))]
    #[sys_async_host_function]
    async fn async_hello<T>(
        _frame: CallingFrame,
        _inputs: Vec<WasmValue>,
        _data: *mut std::os::raw::c_void,
    ) -> Result<Vec<WasmValue>, HostFuncError> {
        for _ in 0..10 {
            println!("[async hello] say hello");
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        }

        println!("[async hello] Done!");

        Ok(vec![])
    }
}