Debian Codegraph @

fuzz/fuzz.c

raw
1 /*
2 * fuzz.c: Common functions for fuzzing.
3 *
4 * See Copyright for the status of this software.
5 */
6
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/stat.h>
11
12 #include <libxml/hash.h>
13 #include <libxml/parser.h>
14 #include <libxml/parserInternals.h>
15 #include <libxml/tree.h>
16 #include <libxml/xmlIO.h>
17 #include "fuzz.h"
18
19 typedef struct {
20 const char *data;
21 size_t size;
22 } xmlFuzzEntityInfo;
23
24 /* Single static instance for now */
25 static struct {
26 /* Original data */
27 const char *data;
28 size_t size;
29
30 /* Remaining data */
31 const char *ptr;
32 size_t remaining;
33
34 /* Buffer for unescaped strings */
35 char *outBuf;
36 char *outPtr; /* Free space at end of buffer */
37
38 xmlHashTablePtr entities; /* Maps URLs to xmlFuzzEntityInfos */
39
40 /* The first entity is the main entity. */
41 const char *mainUrl;
42 xmlFuzzEntityInfo *mainEntity;
43 const char *secondaryUrl;
44 xmlFuzzEntityInfo *secondaryEntity;
45 } fuzzData;
46
47 size_t fuzzNumAttempts;
48 size_t fuzzFailurePos;
49 int fuzzAllocFailed;
50 int fuzzIoFailed;
51
52 /**
53 * xmlFuzzErrorFunc:
54 *
55 * An error function that simply discards all errors.
56 */
57 void
58 xmlFuzzErrorFunc(void *ctx ATTRIBUTE_UNUSED, const char *msg ATTRIBUTE_UNUSED,
59 ...) {
60 }
61
62 /**
63 * xmlFuzzSErrorFunc:
64 *
65 * A structured error function that simply discards all errors.
66 */
67 void
68 xmlFuzzSErrorFunc(void *ctx ATTRIBUTE_UNUSED,
69 const xmlError *error ATTRIBUTE_UNUSED) {
70 }
71
72 /*
73 * Failure injection.
74 *
75 * To debug issues involving injected failures, it's often helpful to set
76 * FAILURE_ABORT to 1. This should provide a backtrace of the failed
77 * operation.
78 */
79
80 #define XML_FUZZ_FAILURE_ABORT 0
81
82 void
83 xmlFuzzInjectFailure(size_t failurePos) {
84 fuzzNumAttempts = 0;
85 fuzzFailurePos = failurePos;
86 fuzzAllocFailed = 0;
87 fuzzIoFailed = 0;
88 }
89
90 static int
91 xmlFuzzTryMalloc(void) {
92 if (fuzzFailurePos > 0) {
93 fuzzNumAttempts += 1;
94 if (fuzzNumAttempts == fuzzFailurePos) {
95 #if XML_FUZZ_FAILURE_ABORT
96 abort();
97 #endif
98 fuzzAllocFailed = 1;
99 return -1;
100 }
101 }
102
103 return 0;
104 }
105
106 static int
107 xmlFuzzTryIo(void) {
108 if (fuzzFailurePos > 0) {
109 fuzzNumAttempts += 1;
110 if (fuzzNumAttempts == fuzzFailurePos) {
111 #if XML_FUZZ_FAILURE_ABORT
112 abort();
113 #endif
114 fuzzIoFailed = 1;
115 return -1;
116 }
117 }
118
119 return 0;
120 }
121
122 static void *
123 xmlFuzzMalloc(size_t size) {
124 void *ret;
125
126 if (xmlFuzzTryMalloc() < 0)
127 return NULL;
128
129 ret = malloc(size);
130 if (ret == NULL)
131 fuzzAllocFailed = 1;
132
133 return ret;
134 }
135
136 static void *
137 xmlFuzzRealloc(void *ptr, size_t size) {
138 void *ret;
139
140 if (xmlFuzzTryMalloc() < 0)
141 return NULL;
142
143 ret = realloc(ptr, size);
144 if (ret == NULL)
145 fuzzAllocFailed = 1;
146
147 return ret;
148 }
149
150 void
151 xmlFuzzMemSetup(void) {
152 xmlMemSetup(free, xmlFuzzMalloc, xmlFuzzRealloc, xmlMemStrdup);
153 }
154
155 int
156 xmlFuzzMallocFailed(void) {
157 return fuzzAllocFailed;
158 }
159
160 void
161 xmlFuzzResetFailure(void) {
162 fuzzAllocFailed = 0;
163 fuzzIoFailed = 0;
164 }
165
166 void
167 xmlFuzzCheckFailureReport(const char *func, int oomReport, int ioReport) {
168 if (oomReport >= 0 && fuzzAllocFailed != oomReport) {
169 fprintf(stderr, "%s: malloc failure %s reported\n",
170 func, fuzzAllocFailed ? "not" : "erroneously");
171 abort();
172 }
173 if (ioReport >= 0 && fuzzIoFailed != ioReport) {
174 fprintf(stderr, "%s: IO failure %s reported\n",
175 func, fuzzIoFailed ? "not" : "erroneously");
176 abort();
177 }
178 fuzzAllocFailed = 0;
179 fuzzIoFailed = 0;
180 }
181
182 /**
183 * xmlFuzzDataInit:
184 *
185 * Initialize fuzz data provider.
186 */
187 void
188 xmlFuzzDataInit(const char *data, size_t size) {
189 fuzzData.data = data;
190 fuzzData.size = size;
191 fuzzData.ptr = data;
192 fuzzData.remaining = size;
193
194 fuzzData.outBuf = xmlMalloc(size + 1);
195 fuzzData.outPtr = fuzzData.outBuf;
196
197 fuzzData.entities = xmlHashCreate(8);
198 fuzzData.mainUrl = NULL;
199 fuzzData.mainEntity = NULL;
200 fuzzData.secondaryUrl = NULL;
201 fuzzData.secondaryEntity = NULL;
202 }
203
204 /**
205 * xmlFuzzDataFree:
206 *
207 * Cleanup fuzz data provider.
208 */
209 void
210 xmlFuzzDataCleanup(void) {
211 xmlFree(fuzzData.outBuf);
212 xmlHashFree(fuzzData.entities, xmlHashDefaultDeallocator);
213 }
214
215 /**
216 * xmlFuzzWriteInt:
217 * @out: output file
218 * @v: integer to write
219 * @size: size of integer in bytes
220 *
221 * Write an integer to the fuzz data.
222 */
223 void
224 xmlFuzzWriteInt(FILE *out, size_t v, int size) {
225 int shift;
226
227 while (size > (int) sizeof(size_t)) {
228 putc(0, out);
229 size--;
230 }
231
232 shift = size * 8;
233 while (shift > 0) {
234 shift -= 8;
235 putc((v >> shift) & 255, out);
236 }
237 }
238
239 /**
240 * xmlFuzzReadInt:
241 * @size: size of integer in bytes
242 *
243 * Read an integer from the fuzz data.
244 */
245 size_t
246 xmlFuzzReadInt(int size) {
247 size_t ret = 0;
248
249 while ((size > 0) && (fuzzData.remaining > 0)) {
250 unsigned char c = (unsigned char) *fuzzData.ptr++;
251 fuzzData.remaining--;
252 ret = (ret << 8) | c;
253 size--;
254 }
255
256 return ret;
257 }
258
259 /**
260 * xmlFuzzBytesRemaining:
261 *
262 * Return number of remaining bytes in fuzz data.
263 */
264 size_t
265 xmlFuzzBytesRemaining(void) {
266 return(fuzzData.remaining);
267 }
268
269 /**
270 * xmlFuzzReadRemaining:
271 * @size: size of string in bytes
272 *
273 * Read remaining bytes from fuzz data.
274 */
275 const char *
276 xmlFuzzReadRemaining(size_t *size) {
277 const char *ret = fuzzData.ptr;
278
279 *size = fuzzData.remaining;
280 fuzzData.ptr += fuzzData.remaining;
281 fuzzData.remaining = 0;
282
283 return(ret);
284 }
285
286 /*
287 * xmlFuzzWriteString:
288 * @out: output file
289 * @str: string to write
290 *
291 * Write a random-length string to file in a format similar to
292 * FuzzedDataProvider. Backslash followed by newline marks the end of the
293 * string. Two backslashes are used to escape a backslash.
294 */
295 void
296 xmlFuzzWriteString(FILE *out, const char *str) {
297 for (; *str; str++) {
298 int c = (unsigned char) *str;
299 putc(c, out);
300 if (c == '\\')
301 putc(c, out);
302 }
303 putc('\\', out);
304 putc('\n', out);
305 }
306
307 /**
308 * xmlFuzzReadString:
309 * @size: size of string in bytes
310 *
311 * Read a random-length string from the fuzz data.
312 *
313 * The format is similar to libFuzzer's FuzzedDataProvider but treats
314 * backslash followed by newline as end of string. This makes the fuzz data
315 * more readable. A backslash character is escaped with another backslash.
316 *
317 * Returns a zero-terminated string or NULL if the fuzz data is exhausted.
318 */
319 const char *
320 xmlFuzzReadString(size_t *size) {
321 const char *out = fuzzData.outPtr;
322
323 while (fuzzData.remaining > 0) {
324 int c = *fuzzData.ptr++;
325 fuzzData.remaining--;
326
327 if ((c == '\\') && (fuzzData.remaining > 0)) {
328 int c2 = *fuzzData.ptr;
329
330 if (c2 == '\n') {
331 fuzzData.ptr++;
332 fuzzData.remaining--;
333 if (size != NULL)
334 *size = fuzzData.outPtr - out;
335 *fuzzData.outPtr++ = '\0';
336 return(out);
337 }
338 if (c2 == '\\') {
339 fuzzData.ptr++;
340 fuzzData.remaining--;
341 }
342 }
343
344 *fuzzData.outPtr++ = c;
345 }
346
347 if (fuzzData.outPtr > out) {
348 if (size != NULL)
349 *size = fuzzData.outPtr - out;
350 *fuzzData.outPtr++ = '\0';
351 return(out);
352 }
353
354 if (size != NULL)
355 *size = 0;
356 return(NULL);
357 }
358
359 /**
360 * xmlFuzzReadEntities:
361 *
362 * Read entities like the main XML file, external DTDs, external parsed
363 * entities from fuzz data.
364 */
365 void
366 xmlFuzzReadEntities(void) {
367 size_t num = 0;
368
369 while (1) {
370 const char *url, *entity;
371 size_t urlSize, entitySize;
372 xmlFuzzEntityInfo *entityInfo;
373
374 url = xmlFuzzReadString(&urlSize);
375 if (url == NULL) break;
376
377 entity = xmlFuzzReadString(&entitySize);
378 if (entity == NULL) break;
379
380 /*
381 * Cap URL size to avoid quadratic behavior when generating
382 * error messages or looking up entities.
383 */
384 if (urlSize < 50 &&
385 xmlHashLookup(fuzzData.entities, (xmlChar *)url) == NULL) {
386 entityInfo = xmlMalloc(sizeof(xmlFuzzEntityInfo));
387 if (entityInfo == NULL)
388 break;
389 entityInfo->data = entity;
390 entityInfo->size = entitySize;
391
392 xmlHashAddEntry(fuzzData.entities, (xmlChar *)url, entityInfo);
393
394 if (num == 0) {
395 fuzzData.mainUrl = url;
396 fuzzData.mainEntity = entityInfo;
397 } else if (num == 1) {
398 fuzzData.secondaryUrl = url;
399 fuzzData.secondaryEntity = entityInfo;
400 }
401
402 num++;
403 }
404 }
405 }
406
407 /**
408 * xmlFuzzMainUrl:
409 *
410 * Returns the main URL.
411 */
412 const char *
413 xmlFuzzMainUrl(void) {
414 return(fuzzData.mainUrl);
415 }
416
417 /**
418 * xmlFuzzMainEntity:
419 * @size: size of the main entity in bytes
420 *
421 * Returns the main entity.
422 */
423 const char *
424 xmlFuzzMainEntity(size_t *size) {
425 if (fuzzData.mainEntity == NULL)
426 return(NULL);
427 *size = fuzzData.mainEntity->size;
428 return(fuzzData.mainEntity->data);
429 }
430
431 /**
432 * xmlFuzzSecondaryUrl:
433 *
434 * Returns the secondary URL.
435 */
436 const char *
437 xmlFuzzSecondaryUrl(void) {
438 return(fuzzData.secondaryUrl);
439 }
440
441 /**
442 * xmlFuzzSecondaryEntity:
443 * @size: size of the secondary entity in bytes
444 *
445 * Returns the secondary entity.
446 */
447 const char *
448 xmlFuzzSecondaryEntity(size_t *size) {
449 if (fuzzData.secondaryEntity == NULL)
450 return(NULL);
451 *size = fuzzData.secondaryEntity->size;
452 return(fuzzData.secondaryEntity->data);
453 }
454
455 /**
456 * xmlFuzzResourceLoader:
457 *
458 * The resource loader for fuzz data.
459 */
460 xmlParserErrors
461 xmlFuzzResourceLoader(void *data ATTRIBUTE_UNUSED, const char *URL,
462 const char *ID ATTRIBUTE_UNUSED,
463 xmlResourceType type ATTRIBUTE_UNUSED,
464 xmlParserInputFlags flags ATTRIBUTE_UNUSED,
465 xmlParserInputPtr *out) {
466 xmlParserInputPtr input;
467 xmlFuzzEntityInfo *entity;
468
469 entity = xmlHashLookup(fuzzData.entities, (xmlChar *) URL);
470 if (entity == NULL)
471 return(XML_IO_ENOENT);
472
473 /* IO failure injection */
474 if (xmlFuzzTryIo() < 0)
475 return(XML_IO_EIO);
476
477 input = xmlNewInputFromMemory(URL, entity->data, entity->size,
478 XML_INPUT_BUF_STATIC |
479 XML_INPUT_BUF_ZERO_TERMINATED);
480 if (input == NULL)
481 return(XML_ERR_NO_MEMORY);
482
483 *out = input;
484 return(XML_ERR_OK);
485 }
486
487 char *
488 xmlSlurpFile(const char *path, size_t *sizeRet) {
489 FILE *file;
490 struct stat statbuf;
491 char *data;
492 size_t size;
493
494 if ((stat(path, &statbuf) != 0) || (!S_ISREG(statbuf.st_mode)))
495 return(NULL);
496 size = statbuf.st_size;
497 file = fopen(path, "rb");
498 if (file == NULL)
499 return(NULL);
500 data = xmlMalloc(size + 1);
501 if (data != NULL) {
502 if (fread(data, 1, size, file) != size) {
503 xmlFree(data);
504 data = NULL;
505 } else {
506 data[size] = 0;
507 if (sizeRet != NULL)
508 *sizeRet = size;
509 }
510 }
511 fclose(file);
512
513 return(data);
514 }
515
516 int
517 xmlFuzzOutputWrite(void *ctxt ATTRIBUTE_UNUSED,
518 const char *buffer ATTRIBUTE_UNUSED, int len) {
519 if (xmlFuzzTryIo() < 0)
520 return -XML_IO_EIO;
521
522 return len;
523 }
524
525 int
526 xmlFuzzOutputClose(void *ctxt ATTRIBUTE_UNUSED) {
527 if (xmlFuzzTryIo() < 0)
528 return XML_IO_EIO;
529
530 return 0;
531 }
532
533 /**
534 * xmlFuzzMutateChunks:
535 * @chunks: array of chunk descriptions
536 * @data: fuzz data (from LLVMFuzzerCustomMutator)
537 * @size: data size (from LLVMFuzzerCustomMutator)
538 * @maxSize: max data size (from LLVMFuzzerCustomMutator)
539 * @seed: seed (from LLVMFuzzerCustomMutator)
540 * @mutator: mutator function, use LLVMFuzzerMutate
541 *
542 * Mutates one of several chunks with a given probability.
543 *
544 * Probability is a value between 0 and XML_FUZZ_PROB_ONE.
545 *
546 * The last chunk has flexible size and must have size and
547 * mutateProb set to 0.
548 *
549 * Returns the size of the mutated data like LLVMFuzzerCustomMutator.
550 */
551 size_t
552 xmlFuzzMutateChunks(const xmlFuzzChunkDesc *chunks,
553 char *data, size_t size, size_t maxSize, unsigned seed,
554 xmlFuzzMutator mutator) {
555 size_t off = 0;
556 size_t ret, chunkSize, maxChunkSize, mutSize;
557 unsigned prob = seed % XML_FUZZ_PROB_ONE;
558 unsigned descSize = 0;
559 int i = 0;
560
561 while (1) {
562 unsigned descProb;
563
564 descSize = chunks[i].size;
565 descProb = chunks[i].mutateProb;
566
567 if (descSize == 0 ||
568 off + descSize > size ||
569 off + descSize >= maxSize ||
570 prob < descProb)
571 break;
572
573 off += descSize;
574 prob -= descProb;
575 i += 1;
576 }
577
578 chunkSize = size - off;
579 maxChunkSize = maxSize - off;
580
581 if (descSize != 0) {
582 if (chunkSize > descSize)
583 chunkSize = descSize;
584 if (maxChunkSize > descSize)
585 maxChunkSize = descSize;
586 }
587
588 mutSize = mutator(data + off, chunkSize, maxChunkSize);
589
590 if (size > off + chunkSize) {
591 size_t j;
592
593 for (j = mutSize; j < chunkSize; j++)
594 data[off + j] = 0;
595
596 ret = size;
597 } else {
598 ret = off + mutSize;
599 }
600
601 return ret;
602 }
603