cjson_read_fuzzer.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <string.h>
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif
  7. #include "../cJSON.h"
  8. int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); /* required by C89 */
  9. int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
  10. {
  11. cJSON *json;
  12. size_t offset = 4;
  13. unsigned char *copied;
  14. char *printed_json = NULL;
  15. int minify, require_termination, formatted, buffered;
  16. if(size <= offset) return 0;
  17. if(data[size-1] != '\0') return 0;
  18. if(data[0] != '1' && data[0] != '0') return 0;
  19. if(data[1] != '1' && data[1] != '0') return 0;
  20. if(data[2] != '1' && data[2] != '0') return 0;
  21. if(data[3] != '1' && data[3] != '0') return 0;
  22. minify = data[0] == '1' ? 1 : 0;
  23. require_termination = data[1] == '1' ? 1 : 0;
  24. formatted = data[2] == '1' ? 1 : 0;
  25. buffered = data[3] == '1' ? 1 : 0;
  26. json = cJSON_ParseWithOpts((const char*)data + offset, NULL, require_termination);
  27. if(json == NULL) return 0;
  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. copied = (unsigned char*)malloc(size);
  48. if(copied == NULL) return 0;
  49. memcpy(copied, data, size);
  50. cJSON_Minify((char*)copied + offset);
  51. free(copied);
  52. }
  53. cJSON_Delete(json);
  54. return 0;
  55. }
  56. #ifdef __cplusplus
  57. }
  58. #endif