cJSON/fuzzing/cjson_read_fuzzer.c

78 lines
1.7 KiB
C
Raw Normal View History

2019-07-11 11:56:07 +00:00
#include <stdlib.h>
#include <stdint.h>
2019-07-11 12:42:27 +00:00
#include <string.h>
2019-07-11 11:56:07 +00:00
#ifdef __cplusplus
extern "C" {
#endif
2019-07-11 11:56:07 +00:00
#include "../cJSON.h"
2019-10-21 13:27:47 +00:00
int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); /* required by C89 */
int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
2019-07-11 11:56:07 +00:00
{
cJSON *json;
2019-07-11 12:42:27 +00:00
size_t offset = 4;
unsigned char *copied;
char *printed_json = NULL;
int minify, require_termination, formatted, buffered;
2019-07-11 11:56:07 +00:00
2019-07-11 13:09:10 +00:00
if(size <= offset) return 0;
2019-10-21 13:27:47 +00:00
if(data[size-1] != '\0') return 0;
2019-07-11 12:42:27 +00:00
if(data[0] != '1' && data[0] != '0') return 0;
if(data[1] != '1' && data[1] != '0') return 0;
if(data[2] != '1' && data[2] != '0') return 0;
if(data[3] != '1' && data[3] != '0') return 0;
minify = data[0] == '1' ? 1 : 0;
require_termination = data[1] == '1' ? 1 : 0;
formatted = data[2] == '1' ? 1 : 0;
buffered = data[3] == '1' ? 1 : 0;
2019-07-11 12:42:27 +00:00
2019-10-21 13:27:47 +00:00
json = cJSON_ParseWithOpts((const char*)data + offset, NULL, require_termination);
2019-07-11 13:03:04 +00:00
2019-10-21 13:27:47 +00:00
if(json == NULL) return 0;
2019-07-11 11:56:07 +00:00
2019-07-11 12:42:27 +00:00
if(buffered)
2019-07-11 11:56:07 +00:00
{
2019-07-11 12:42:27 +00:00
printed_json = cJSON_PrintBuffered(json, 1, formatted);
2019-07-11 11:56:07 +00:00
}
else
{
/* unbuffered printing */
2019-07-11 12:42:27 +00:00
if(formatted)
2019-07-11 11:56:07 +00:00
{
printed_json = cJSON_Print(json);
}
else
{
printed_json = cJSON_PrintUnformatted(json);
}
}
if(printed_json != NULL) free(printed_json);
2019-07-11 12:42:27 +00:00
if(minify)
{
2019-10-21 13:27:47 +00:00
copied = (unsigned char*)malloc(size);
if(copied == NULL) return 0;
memcpy(copied, data, size);
2019-07-11 13:03:04 +00:00
cJSON_Minify((char*)copied + offset);
2019-10-21 13:27:47 +00:00
free(copied);
2019-07-11 12:42:27 +00:00
}
2019-07-11 11:56:07 +00:00
cJSON_Delete(json);
return 0;
}
#ifdef __cplusplus
}
2019-10-29 04:47:36 +00:00
#endif