Coverage Report

Created: 2025-08-29 06:51

/src/libdwarf/fuzz/fuzz_crc.c
Line
Count
Source (jump to first uncovered line)
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
87
#define O_BINARY 0
28
#endif
29
30
/*
31
 * Fuzzer function
32
 */
33
87
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
34
87
  char filename[256];
35
#ifdef DWREGRESSIONTEMP
36
  /* Under msys2, the /tmp/ results in an open fail */
37
  sprintf(filename, "junklibfuzzer.%d", getpid());
38
#else
39
87
  sprintf(filename, "/tmp/libfuzzer.%d", getpid());
40
87
#endif
41
42
87
  FILE *fp = fopen(filename, "wb");
43
87
  if (!fp) {
44
0
    printf("FAIL libfuzzer cannot open temp as writeable %s\n",
45
0
        filename);
46
0
    return 0;
47
0
  }
48
49
87
  fwrite(data, size, 1, fp);
50
87
  fclose(fp);
51
52
87
  int fuzz_fd = 0;
53
87
  Dwarf_Ptr errarg = 0;
54
87
  Dwarf_Handler errhand = 0;
55
87
  Dwarf_Error *errp = NULL;
56
87
  Dwarf_Debug dbg = 0;
57
87
  off_t size_left = 0;
58
87
  off_t fsize = 0;
59
87
  ssize_t readlen = 1000;
60
87
  ssize_t readval = 0;
61
87
  unsigned char *readbuf = 0;
62
87
  unsigned int tcrc = 0;
63
87
  unsigned int init = 0;
64
65
87
  fuzz_fd = open(filename, O_RDONLY | O_BINARY);
66
87
  fsize = size_left = lseek(fuzz_fd, 0L, SEEK_END);
67
87
  readbuf = (unsigned char *)malloc(readlen);
68
  /*  The read below will fail, so to avoid
69
      reading uninitialized data we ensure
70
      the data is initialized. */
71
87
  memset((void *)readbuf,10,(size_t)readlen);
72
87
  if (fuzz_fd != -1) {
73
11.2k
    while (size_left > 0) {
74
11.1k
      if (size_left < readlen) {
75
79
        readlen = size_left;
76
79
      }
77
11.1k
      readval = read(fuzz_fd, readbuf, readlen);
78
11.1k
      if (readval != readlen) {
79
          /*  The read failed as it is expected to. */
80
11.1k
      }
81
11.1k
      size_left -= readlen;
82
11.1k
      tcrc = dwarf_basic_crc32(readbuf, readlen, init);
83
11.1k
      init = tcrc;
84
11.1k
    }
85
87
  }
86
87
  free(readbuf);
87
87
  close(fuzz_fd);
88
87
  unlink(filename);
89
87
  return 0;
90
87
}