| 1 |
/* Copyright 2021 Google LLC |
| 2 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
you may not use this file except in compliance with the License. |
| 4 |
You may obtain a copy of the License at |
| 5 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 6 |
Unless required by applicable law or agreed to in writing, software |
| 7 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 8 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 |
See the License for the specific language governing permissions and |
| 10 |
limitations under the License. |
| 11 |
*/ |
| 12 |
#include <fcntl.h> /* open() O_RDONLY O_BINARY */ |
| 13 |
#include <stdint.h> |
| 14 |
#include <stdio.h> |
| 15 |
#include <stdlib.h> |
| 16 |
#include <string.h> |
| 17 |
#include <sys/stat.h> |
| 18 |
#include <sys/types.h> |
| 19 |
#include <unistd.h> |
| 20 |
/* |
| 21 |
* Libdwarf library callers can only use these headers. |
| 22 |
*/ |
| 23 |
#include "dwarf.h" |
| 24 |
#include "libdwarf.h" |
| 25 |
|
| 26 |
#ifndef O_BINARY |
| 27 |
#define O_BINARY 0 |
| 28 |
#endif |
| 29 |
|
| 30 |
/* |
| 31 |
* Fuzzer function |
| 32 |
*/ |
| 33 |
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { |
| 34 |
char filename[256]; |
| 35 |
sprintf(filename, "/tmp/libfuzzer.%d", getpid()); |
| 36 |
|
| 37 |
FILE *fp = fopen(filename, "wb"); |
| 38 |
if (!fp) { |
| 39 |
return 0; |
| 40 |
} |
| 41 |
fwrite(data, size, 1, fp); |
| 42 |
fclose(fp); |
| 43 |
|
| 44 |
int fuzz_fd = 0; |
| 45 |
Dwarf_Ptr errarg = 0; |
| 46 |
Dwarf_Handler errhand = 0; |
| 47 |
Dwarf_Error *errp = NULL; |
| 48 |
Dwarf_Debug dbg = 0; |
| 49 |
off_t size_left = 0; |
| 50 |
off_t fsize = 0; |
| 51 |
ssize_t readlen = 1000; |
| 52 |
ssize_t readval = 0; |
| 53 |
unsigned char *readbuf = 0; |
| 54 |
unsigned int tcrc = 0; |
| 55 |
unsigned int init = 0; |
| 56 |
|
| 57 |
fuzz_fd = open(filename, O_RDONLY | O_BINARY); |
| 58 |
fsize = size_left = lseek(fuzz_fd, 0L, SEEK_END); |
| 59 |
readbuf = (unsigned char *)malloc(readlen); |
| 60 |
/* The read below will fail, so to avoid |
| 61 |
reading uninitialized data we ensure |
| 62 |
the data is initialized. */ |
| 63 |
memset((void *)readbuf,10,(size_t)readlen); |
| 64 |
if (fuzz_fd != -1) { |
| 65 |
while (size_left > 0) { |
| 66 |
if (size_left < readlen) { |
| 67 |
readlen = size_left; |
| 68 |
} |
| 69 |
readval = read(fuzz_fd, readbuf, readlen); |
| 70 |
if (readval != readlen) { |
| 71 |
/* The read failed as it is expected to. */ |
| 72 |
} |
| 73 |
size_left -= readlen; |
| 74 |
tcrc = dwarf_basic_crc32(readbuf, readlen, init); |
| 75 |
init = tcrc; |
| 76 |
} |
| 77 |
} |
| 78 |
free(readbuf); |
| 79 |
close(fuzz_fd); |
| 80 |
unlink(filename); |
| 81 |
return 0; |
| 82 |
} |