Path: blob/main/contrib/libcbor/oss-fuzz/cbor_load_fuzzer.cc
39478 views
#include <cstdint>1#include <cstdio>2#include <cstdlib>3#include <unordered_map>45#include "cbor.h"67static size_t allocated_mem = 0;8static std::unordered_map<void*, size_t> allocated_len_map;9static constexpr size_t kMemoryLimit = 1 << 30;1011void *limited_malloc(size_t size) {12if (size + allocated_mem > kMemoryLimit) {13return nullptr;14}15if (size == 0) {16return nullptr;17}18void* m = malloc(size);19if (m != nullptr) {20allocated_mem += size;21allocated_len_map[m] = size;22}23return m;24}2526void limited_free(void *ptr) {27if (ptr != NULL && allocated_len_map.find(ptr) == allocated_len_map.end()) {28abort();29}30free(ptr);31if (ptr != NULL) {32allocated_mem -= allocated_len_map[ptr];33allocated_len_map.erase(ptr);34}35}3637void *limited_realloc(void *ptr, size_t size) {38if (ptr != NULL && allocated_len_map.find(ptr) == allocated_len_map.end()) {39abort();40}41if (ptr == NULL) {42return limited_malloc(size);43}44long delta = (long) size - allocated_len_map[ptr];45if (delta + allocated_mem > kMemoryLimit) {46return nullptr;47}48void* new_ptr = realloc(ptr, size);49if (size > 0 && new_ptr == nullptr) {50return nullptr;51}52allocated_mem += delta;53allocated_len_map.erase(ptr);54if (size > 0) {55allocated_len_map[new_ptr] = size;56}57return new_ptr;58}5960struct State {61FILE* fout;6263State() : fout(fopen("/dev/null", "r")) {64cbor_set_allocs(limited_malloc, limited_realloc, limited_free);65}66};6768static State kState;6970extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {71cbor_load_result result;72cbor_item_t *item = cbor_load(Data, Size, &result);73if (result.error.code == CBOR_ERR_NONE) {74cbor_describe(item, kState.fout);75unsigned char *buffer;76size_t buffer_size;77cbor_serialize_alloc(item, &buffer, &buffer_size);78free(buffer);79cbor_item_t *copied = cbor_copy(item);80cbor_decref(&copied);81cbor_decref(&item);82}83return 0;84}858687