unittest_main.cc 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // A simple unit-test style driver for libfuzzer tests.
  5. // Usage: <fuzzer_test> <file>...
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <iterator>
  11. #include <vector>
  12. // Libfuzzer API.
  13. extern "C" {
  14. // User function.
  15. int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
  16. // Initialization function.
  17. __attribute__((weak)) int LLVMFuzzerInitialize(int *argc, char ***argv);
  18. // Mutation function provided by libFuzzer.
  19. size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
  20. }
  21. std::vector<uint8_t> readFile(std::string path) {
  22. std::ifstream in(path);
  23. return std::vector<uint8_t>((std::istreambuf_iterator<char>(in)),
  24. std::istreambuf_iterator<char>());
  25. }
  26. size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
  27. return 0;
  28. }
  29. int main(int argc, char **argv) {
  30. if (argc == 1) {
  31. std::cerr
  32. << "Usage: " << argv[0]
  33. << " <file>...\n"
  34. "\n"
  35. "Alternatively, try building this target with "
  36. "use_libfuzzer=true for a better test driver. For details see:\n"
  37. "\n"
  38. "https://chromium.googlesource.com/chromium/src/+/main/"
  39. "testing/libfuzzer/getting_started.md"
  40. << std::endl;
  41. exit(1);
  42. }
  43. if (LLVMFuzzerInitialize)
  44. LLVMFuzzerInitialize(&argc, &argv);
  45. for (int i = 1; i < argc; ++i) {
  46. std::cout << argv[i] << std::endl;
  47. auto v = readFile(argv[i]);
  48. LLVMFuzzerTestOneInput(v.data(), v.size());
  49. }
  50. }