ares-fuzz.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * General driver to allow command-line fuzzer (i.e. afl) to
  3. * exercise the libFuzzer entrypoint.
  4. */
  5. #include <sys/types.h>
  6. #include <fcntl.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #ifdef WIN32
  11. #include <io.h>
  12. #else
  13. #include <unistd.h>
  14. #endif
  15. #define kMaxAflInputSize (1 << 20)
  16. static unsigned char afl_buffer[kMaxAflInputSize];
  17. #ifdef __AFL_LOOP
  18. /* If we are built with afl-clang-fast, use persistent mode */
  19. #define KEEP_FUZZING(count) __AFL_LOOP(1000)
  20. #else
  21. /* If we are built with afl-clang, execute each input once */
  22. #define KEEP_FUZZING(count) ((count) < 1)
  23. #endif
  24. /* In ares-test-fuzz.c and ares-test-fuzz-name.c: */
  25. int LLVMFuzzerTestOneInput(const unsigned char *data, unsigned long size);
  26. static void ProcessFile(int fd) {
  27. int count = read(fd, afl_buffer, kMaxAflInputSize);
  28. /*
  29. * Make a copy of the data so that it's not part of a larger
  30. * buffer (where buffer overflows would go unnoticed).
  31. */
  32. unsigned char *copied_data = (unsigned char *)malloc(count);
  33. memcpy(copied_data, afl_buffer, count);
  34. LLVMFuzzerTestOneInput(copied_data, count);
  35. free(copied_data);
  36. }
  37. int main(int argc, char *argv[]) {
  38. if (argc == 1) {
  39. int count = 0;
  40. while (KEEP_FUZZING(count)) {
  41. ProcessFile(fileno(stdin));
  42. count++;
  43. }
  44. } else {
  45. int ii;
  46. for (ii = 1; ii < argc; ++ii) {
  47. int fd = open(argv[ii], O_RDONLY);
  48. if (fd < 0) {
  49. fprintf(stderr, "Failed to open '%s'\n", argv[ii]);
  50. continue;
  51. }
  52. ProcessFile(fd);
  53. close(fd);
  54. }
  55. }
  56. return 0;
  57. }