Coverage Report

Created: 2025-06-22 08:03

/src/fuzzer_temp_file.h
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2018 Google Inc.
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
// Adapter utility from fuzzer input to a temporary file, for fuzzing APIs that
16
// require a file instead of an input buffer.
17
18
#ifndef FUZZER_TEMP_FILE_H_
19
#define FUZZER_TEMP_FILE_H_
20
21
#include <stdint.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
#include <unistd.h>
26
27
// Pure-C interface for creating and cleaning up temporary files.
28
29
0
static char* fuzzer_get_tmpfile(const uint8_t* data, size_t size) {
30
0
  char* filename_buffer = strdup("/tmp/generate_temporary_file.XXXXXX");
31
0
  if (!filename_buffer) {
32
0
    perror("Failed to allocate file name buffer.");
33
0
    abort();
34
0
  }
35
0
  const int file_descriptor = mkstemp(filename_buffer);
36
0
  if (file_descriptor < 0) {
37
0
    perror("Failed to make temporary file.");
38
0
    abort();
39
0
  }
40
0
  FILE* file = fdopen(file_descriptor, "wb");
41
0
  if (!file) {
42
0
    perror("Failed to open file descriptor.");
43
0
    close(file_descriptor);
44
0
    abort();
45
0
  }
46
0
  const size_t bytes_written = fwrite(data, sizeof(uint8_t), size, file);
47
0
  if (bytes_written < size) {
48
0
    close(file_descriptor);
49
0
    fprintf(stderr, "Failed to write all bytes to file (%zu out of %zu)",
50
0
            bytes_written, size);
51
0
    abort();
52
0
  }
53
0
  fclose(file);
54
0
  return filename_buffer;
55
0
}
56
57
0
static void fuzzer_release_tmpfile(char* filename) {
58
0
  if (unlink(filename) != 0) {
59
0
    perror("WARNING: Failed to delete temporary file.");
60
0
  }
61
0
  free(filename);
62
0
}
63
64
// C++ RAII object for creating temporary files.
65
66
#ifdef __cplusplus
67
class FuzzerTemporaryFile {
68
 public:
69
  FuzzerTemporaryFile(const uint8_t* data, size_t size)
70
      : filename_(fuzzer_get_tmpfile(data, size)) {}
71
72
  ~FuzzerTemporaryFile() { fuzzer_release_tmpfile(filename_); }
73
74
  const char* filename() const { return filename_; }
75
76
 private:
77
  char* filename_;
78
};
79
#endif
80
81
#endif  // FUZZER_TEMP_FILE_H_