xref: /wasmtime-44.0.1/crates/c-api/tests/store.cc (revision 1f2feaf7)
1 #include <wasmtime/store.hh>
2 
3 #include <gtest/gtest.h>
4 #include <wasmtime/config.hh>
5 #include <wasmtime/error.hh>
6 #include <wasmtime/func.hh>
7 #include <wasmtime/instance.hh>
8 #include <wasmtime/module.hh>
9 
10 using namespace wasmtime;
11 
unwrap(Result<T,E> result)12 template <typename T, typename E> T unwrap(Result<T, E> result) {
13   if (result) {
14     return result.ok();
15   }
16   std::cerr << "error: " << result.err().message() << "\n";
17   std::abort();
18 }
19 
TEST(Store,Smoke)20 TEST(Store, Smoke) {
21   Engine engine;
22   Store store(engine);
23   Store store2 = std::move(store);
24   Store store3(std::move(store2));
25 
26   store = Store(engine);
27   store.limiter(-1, -1, -1, -1, -1);
28   store.context().gc();
29   store.context().get_fuel().err();
30   store.context().set_fuel(1).err();
31   store.context().set_epoch_deadline(1);
32 }
33 
TEST(Store,EpochDeadlineCallback)34 TEST(Store, EpochDeadlineCallback) {
35   Config config;
36   config.epoch_interruption(true);
37   Engine engine(std::move(config));
38 
39   size_t num_calls = 0;
40   Store store(engine);
41   store.epoch_deadline_callback(
42       [&num_calls](wasmtime::Store::Context /* context */,
43                    uint64_t &epoch_deadline_delta)
44           -> wasmtime::Result<wasmtime::DeadlineKind> {
45         epoch_deadline_delta += 1;
46         num_calls += 1;
47         return wasmtime::DeadlineKind::Continue;
48       });
49 
50   store.context().set_epoch_deadline(1);
51 
52   Module m = unwrap(Module::compile(engine, "(module (func (export \"f\")))"));
53   Instance i = unwrap(Instance::create(store, m, {}));
54 
55   auto f = std::get<Func>(*i.get(store, "f"));
56 
57   unwrap(f.call(store, {}));
58   ASSERT_EQ(num_calls, 0);
59 
60   engine.increment_epoch();
61   unwrap(f.call(store, {}));
62   ASSERT_EQ(num_calls, 1);
63 
64   /// epoch_deadline_delta increased by 1 in the callback
65   unwrap(f.call(store, {}));
66   ASSERT_EQ(num_calls, 1);
67 
68   engine.increment_epoch();
69   unwrap(f.call(store, {}));
70   ASSERT_EQ(num_calls, 2);
71 
72   store.epoch_deadline_callback(
73       [](wasmtime::Store::Context /* context */, uint64_t &epoch_deadline_delta)
74           -> wasmtime::Result<wasmtime::DeadlineKind> {
75         return Error("error from callback");
76       });
77 
78   engine.increment_epoch();
79   auto result = f.call(store, {});
80   EXPECT_FALSE(result);
81   EXPECT_TRUE(result.err().message().find("error from callback") !=
82               std::string::npos);
83 }
84