1 // Copyright 2020 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ///////////////////////////////////////////////////////////////////////////////
16 
17 #include "postgres.h"
18 
19 #include "common/jsonapi.h"
20 #include "mb/pg_wchar.h"
21 #include "utils/memutils.h"
22 #include "utils/memdebug.h"
23 
LLVMFuzzerInitialize(int * argc,char *** argv)24 int LLVMFuzzerInitialize(int *argc, char ***argv) {
25 	FuzzerInitialize("json_db", argv);
26 	return 0;
27 }
28 
29 /*
30 ** Main entry point.  The fuzzer invokes this function with each
31 ** fuzzed input.
32 */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)33 int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
34 	sigjmp_buf local_sigjmp_buf;
35 	char *buffer;
36 	JsonSemAction sem;
37 	JsonLexContext *lex;
38 
39 	buffer = (char *) calloc(size+1, sizeof(char));
40 	memcpy(buffer, data, size);
41 
42 	MemoryContextInit();
43 	set_stack_base();
44 	sem = nullSemAction;
45 	lex = makeJsonLexContextCstringLen(buffer, size+1, PG_UTF8, true);
46 
47 	if(!sigsetjmp(local_sigjmp_buf,0)){
48 		error_context_stack = NULL;
49 		PG_exception_stack = &local_sigjmp_buf;
50 		pg_parse_json(lex, &sem);
51 	}
52 	free(buffer);
53 	FlushErrorState();
54 	MemoryContextReset(TopMemoryContext);
55 	TopMemoryContext->ident = NULL;
56 	TopMemoryContext->methods->delete_context(TopMemoryContext);
57 	VALGRIND_DESTROY_MEMPOOL(TopMemoryContext);
58 	return 0;
59 }
60