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