| 26 | |
| 27 | |
| 28 | void run() { |
| 29 | // Initialize. |
| 30 | std::cout << "Initializing..." << std::endl; |
| 31 | auto engine = wasm::Engine::make(); |
| 32 | auto store_ = wasm::Store::make(engine.get()); |
| 33 | auto store = store_.get(); |
| 34 | |
| 35 | // Load binary. |
| 36 | std::cout << "Loading binary..." << std::endl; |
| 37 | std::ifstream file("trap.wasm"); |
| 38 | file.seekg(0, std::ios_base::end); |
| 39 | auto file_size = file.tellg(); |
| 40 | file.seekg(0); |
| 41 | auto binary = wasm::vec<byte_t>::make_uninitialized(file_size); |
| 42 | file.read(binary.get(), file_size); |
| 43 | file.close(); |
| 44 | if (file.fail()) { |
| 45 | std::cout << "> Error loading module!" << std::endl; |
| 46 | exit(1); |
| 47 | } |
| 48 | |
| 49 | // Compile. |
| 50 | std::cout << "Compiling module..." << std::endl; |
| 51 | auto module = wasm::Module::make(store, binary); |
| 52 | if (!module) { |
| 53 | std::cout << "> Error compiling module!" << std::endl; |
| 54 | exit(1); |
| 55 | } |
| 56 | |
| 57 | // Create external print functions. |
| 58 | std::cout << "Creating callback..." << std::endl; |
| 59 | auto fail_type = wasm::FuncType::make( |
| 60 | wasm::ownvec<wasm::ValType>::make(), |
| 61 | wasm::ownvec<wasm::ValType>::make(wasm::ValType::make(wasm::ValKind::I32)) |
| 62 | ); |
| 63 | auto fail_func = |
| 64 | wasm::Func::make(store, fail_type.get(), fail_callback, store); |
| 65 | |
| 66 | // Instantiate. |
| 67 | std::cout << "Instantiating module..." << std::endl; |
| 68 | auto imports = wasm::vec<wasm::Extern*>::make(fail_func.get()); |
| 69 | auto instance = wasm::Instance::make(store, module.get(), imports); |
| 70 | if (!instance) { |
| 71 | std::cout << "> Error instantiating module!" << std::endl; |
| 72 | exit(1); |
| 73 | } |
| 74 | |
| 75 | // Extract export. |
| 76 | std::cout << "Extracting exports..." << std::endl; |
| 77 | auto exports = instance->exports(); |
| 78 | if (exports.size() < 2 || |
| 79 | exports[0]->kind() != wasm::ExternKind::FUNC || !exports[0]->func() || |
| 80 | exports[1]->kind() != wasm::ExternKind::FUNC || !exports[1]->func()) { |
| 81 | std::cout << "> Error accessing exports!" << std::endl; |
| 82 | exit(1); |
| 83 | } |
| 84 | |
| 85 | // Call. |