aot_compiler_fuzz.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright (C) 2025 Intel Corporation. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <errno.h>
  6. #include <string.h>
  7. #include <iostream>
  8. #include <vector>
  9. #include "aot_export.h"
  10. #include "wasm_export.h"
  11. #include "bh_read_file.h"
  12. static void
  13. handle_aot_recent_error(const char *tag)
  14. {
  15. const char *error = aot_get_last_error();
  16. if (strlen(error) == 0) {
  17. error = "UNKNOWN ERROR";
  18. }
  19. std::cout << tag << " " << error << std::endl;
  20. }
  21. extern "C" int
  22. LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
  23. {
  24. wasm_module_t module = NULL;
  25. char error_buf[128] = { 0 };
  26. AOTCompOption option = { 0 };
  27. aot_comp_data_t comp_data = NULL;
  28. aot_comp_context_t comp_ctx = NULL;
  29. /* libfuzzer don't allow to modify the given Data, so make a copy here */
  30. std::vector<uint8_t> myData(Data, Data + Size);
  31. if (Size >= 4
  32. && get_package_type(myData.data(), Size) != Wasm_Module_Bytecode) {
  33. printf("Invalid wasm file: magic header not detected\n");
  34. return 0;
  35. }
  36. wasm_runtime_init();
  37. module = wasm_runtime_load((uint8_t *)myData.data(), Size, error_buf, 120);
  38. if (!module) {
  39. std::cout << "[LOADING] " << error_buf << std::endl;
  40. goto DESTROY_RUNTIME;
  41. }
  42. // TODO: target_arch and other fields
  43. option.target_arch = "x86_64";
  44. option.target_abi = "gnu";
  45. option.enable_bulk_memory = true;
  46. option.enable_thread_mgr = true;
  47. option.enable_tail_call = true;
  48. option.enable_simd = true;
  49. option.enable_ref_types = true;
  50. option.enable_gc = true;
  51. comp_data =
  52. aot_create_comp_data(module, option.target_arch, option.enable_gc);
  53. if (!comp_data) {
  54. handle_aot_recent_error("[CREATING comp_data]");
  55. goto UNLOAD_MODULE;
  56. }
  57. comp_ctx = aot_create_comp_context(comp_data, &option);
  58. if (!comp_ctx) {
  59. handle_aot_recent_error("[CREATING comp_context]");
  60. goto DESTROY_COMP_DATA;
  61. }
  62. if (!aot_compile_wasm(comp_ctx)) {
  63. handle_aot_recent_error("[COMPILING]");
  64. goto DESTROY_COMP_CTX;
  65. }
  66. DESTROY_COMP_CTX:
  67. aot_destroy_comp_context(comp_ctx);
  68. DESTROY_COMP_DATA:
  69. aot_destroy_comp_data(comp_data);
  70. UNLOAD_MODULE:
  71. wasm_runtime_unload(module);
  72. DESTROY_RUNTIME:
  73. wasm_runtime_destroy();
  74. /* Values other than 0 and -1 are reserved for future use. */
  75. return 0;
  76. }