aot_compiler_fuzz.cc 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. option.aux_stack_frame_type = AOT_STACK_FRAME_TYPE_STANDARD;
  52. comp_data =
  53. aot_create_comp_data(module, option.target_arch, option.enable_gc);
  54. if (!comp_data) {
  55. handle_aot_recent_error("[CREATING comp_data]");
  56. goto UNLOAD_MODULE;
  57. }
  58. comp_ctx = aot_create_comp_context(comp_data, &option);
  59. if (!comp_ctx) {
  60. handle_aot_recent_error("[CREATING comp_context]");
  61. goto DESTROY_COMP_DATA;
  62. }
  63. if (!aot_compile_wasm(comp_ctx)) {
  64. handle_aot_recent_error("[COMPILING]");
  65. goto DESTROY_COMP_CTX;
  66. }
  67. DESTROY_COMP_CTX:
  68. aot_destroy_comp_context(comp_ctx);
  69. DESTROY_COMP_DATA:
  70. aot_destroy_comp_data(comp_data);
  71. UNLOAD_MODULE:
  72. wasm_runtime_unload(module);
  73. DESTROY_RUNTIME:
  74. wasm_runtime_destroy();
  75. /* Values other than 0 and -1 are reserved for future use. */
  76. return 0;
  77. }