Debian Codegraph @

c/tests/fuzz/StandaloneFuzzTargetInit.c

raw
1 /*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21
22 #include <assert.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "libFuzzingEngine.h"
28
29 /*
30 * Use this to implement response file:
31 * - Check if there is one file mentioned and its name starts with '@'
32 * - If so then read the file line by line making up the new argv
33 * - Modify argc/argv then return.
34 *
35 * Problem: Somehow need to free buf and nargv to avoid sanitizer warnings
36 */
37
38 /* Free allocated memory at program exit to avoid the leak sanitizer complaining */
39 static char *buf = 0;
40 static char **nargv = 0;
41
42 static void freeall(void)
43 {
44 free(buf);
45 free(nargv);
46 }
47
48 int LLVMFuzzerInitialize(int *argc, char ***argv)
49 {
50 if (*argc==2 && (*argv)[1][0]=='@') {
51 const char* rfilename = (*argv)[1]+1;
52
53 /* Read entire file into memory */
54 fprintf(stderr, "Reading response file: %s\n", rfilename);
55 FILE *f = fopen(rfilename, "rb");
56 assert(f);
57 fseek(f, 0, SEEK_END);
58 size_t len = ftell(f);
59 fseek(f, 0, SEEK_SET);
60 buf = (char*)malloc(len+1);
61 size_t n_read = fread(buf, 1, len, f);
62 fclose(f);
63 assert(n_read == len);
64 buf[len] = '\0';
65
66 /* scan file counting lines and replacing line ends with \0 */
67 int line = 0;
68 char *p = buf;
69 while (p<&buf[len]) {
70 p += strcspn(p, "\n\r ");
71 *p++ = '\0';
72 line +=1;
73 };
74
75 fprintf(stderr, " response file: (%zd bytes, %d lines)\n", n_read, line);
76
77 /* scan again putting each line into the argv array */
78 nargv = (char**) calloc(line+1, sizeof(p));
79
80 p = buf;
81 line = 1;
82 do {
83 char* s = p;
84 int l = strlen(p);
85 p += l+1;
86 if (l>0) nargv[line++] = s;
87 } while (p<&buf[len]);
88
89 int nargc = line;
90 *argc = nargc;
91 *argv = nargv;
92 atexit(&freeall);
93 }
94 return 0;
95 }
96