cjson_read_fuzzer.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4. #include "../cJSON.h"
  5. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
  6. {
  7. size_t offset = 4;
  8. if(size <= offset) return 0;
  9. if(data[0] != '1' && data[0] != '0') return 0;
  10. if(data[1] != '1' && data[1] != '0') return 0;
  11. if(data[2] != '1' && data[2] != '0') return 0;
  12. if(data[3] != '1' && data[3] != '0') return 0;
  13. int minify = data[0] == '1' ? 1 : 0;
  14. int require_termination = data[1] == '1' ? 1 : 0;
  15. int formatted = data[2] == '1' ? 1 : 0;
  16. int buffered = data[3] == '1' ? 1 : 0;
  17. unsigned char *copied = (unsigned char*)malloc(size);
  18. if(copied == NULL) return 0;
  19. memcpy(copied, data, size);
  20. copied[size-1] = '\0';
  21. cJSON *json = cJSON_ParseWithOpts((const char*)copied + offset, NULL, require_termination);
  22. if(json == NULL)
  23. {
  24. free(copied);
  25. return 0;
  26. }
  27. char *printed_json = NULL;
  28. if(buffered)
  29. {
  30. printed_json = cJSON_PrintBuffered(json, 1, formatted);
  31. }
  32. else
  33. {
  34. /* unbuffered printing */
  35. if(formatted)
  36. {
  37. printed_json = cJSON_Print(json);
  38. }
  39. else
  40. {
  41. printed_json = cJSON_PrintUnformatted(json);
  42. }
  43. }
  44. if(printed_json != NULL) free(printed_json);
  45. if(minify)
  46. {
  47. cJSON_Minify((char*)copied + offset);
  48. }
  49. cJSON_Delete(json);
  50. free(copied);
  51. return 0;
  52. }