StandaloneFuzzTargetMain.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*===- StandaloneFuzzTargetMain.c - standalone main() for fuzz targets. ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // This main() function can be linked to a fuzz target (i.e. a library
  9. // that exports LLVMFuzzerTestOneInput() and possibly LLVMFuzzerInitialize())
  10. // instead of libFuzzer. This main() function will not perform any fuzzing
  11. // but will simply feed all input files one by one to the fuzz target.
  12. //
  13. // Use this file to provide reproducers for bugs when linking against libFuzzer
  14. // or other fuzzing engine is undesirable.
  15. //===----------------------------------------------------------------------===*/
  16. #include <assert.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. extern int LLVMFuzzerTestOneInput(const unsigned char *data, size_t size);
  20. #ifndef _MSC_VER
  21. __attribute__((weak))
  22. extern int LLVMFuzzerInitialize(int *argc, char ***argv);
  23. #endif
  24. int main(int argc, char **argv) {
  25. fprintf(stderr, "StandaloneFuzzTargetMain: running %d inputs\n", argc - 1);
  26. #ifndef _MSC_VER
  27. if (LLVMFuzzerInitialize)
  28. LLVMFuzzerInitialize(&argc, &argv);
  29. #endif
  30. for (int i = 1; i < argc; i++) {
  31. fprintf(stderr, "Running: %s\n", argv[i]);
  32. FILE *f = fopen(argv[i], "r");
  33. assert(f);
  34. fseek(f, 0, SEEK_END);
  35. size_t len = ftell(f);
  36. fseek(f, 0, SEEK_SET);
  37. unsigned char *buf = (unsigned char*)malloc(len);
  38. size_t n_read = fread(buf, 1, len, f);
  39. fclose(f);
  40. assert(n_read == len);
  41. LLVMFuzzerTestOneInput(buf, len);
  42. free(buf);
  43. fprintf(stderr, "Done: %s: (%zd bytes)\n", argv[i], n_read);
  44. }
  45. }