curl-fuzzer C++ reference
Loading...
Searching...
No Matches
bounded_anonymous_input_file.cc
Go to the documentation of this file.
1/*
2 * Copyright (C) Max Dymond, <cmeister2@gmail.com>, et al.
3 *
4 * SPDX-License-Identifier: curl
5 */
6
9
11
12#include <sys/types.h>
13#include <unistd.h>
14
15#include <cerrno>
16#include <string>
17
18namespace proto_fuzzer {
19
24 : max_bytes_(max_bytes), file_(nullptr), ready_(false) {}
25
28 if (file_ != nullptr) {
29 std::fclose(file_);
30 }
31}
32
35bool BoundedAnonymousInputFile::EnsureOpen() {
36 if (file_ != nullptr) {
37 return true;
38 }
39
40 file_ = std::tmpfile();
41 if (file_ == nullptr) {
42 return false;
43 }
44 const int fd = fileno(file_);
45 if (fd < 0) {
46 std::fclose(file_);
47 file_ = nullptr;
48 return false;
49 }
50 path_ = "/proc/self/fd/" + std::to_string(fd);
51 return true;
52}
53
60bool BoundedAnonymousInputFile::Write(const std::uint8_t* data, std::size_t size) {
61 ready_ = false;
62 if (size > max_bytes_ || (data == nullptr && size != 0) || !EnsureOpen()) {
63 return false;
64 }
65
66 const int fd = fileno(file_);
67 if (fd < 0 || ftruncate(fd, 0) != 0) {
68 return false;
69 }
70
71 std::size_t offset = 0;
72 while (offset < size) {
73 const ssize_t written = pwrite(fd, data + offset, size - offset, static_cast<off_t>(offset));
74 if (written < 0 && errno == EINTR) {
75 continue;
76 }
77 if (written <= 0) {
78 return false;
79 }
80 offset += static_cast<std::size_t>(written);
81 }
82
83 ready_ = true;
84 return true;
85}
86
89const char* BoundedAnonymousInputFile::path() const { return ready_ ? path_.c_str() : nullptr; }
90
91} // namespace proto_fuzzer
Owns bounded bytes exposed to filename-only APIs through procfs.
bool Write(const std::uint8_t *data, std::size_t size)
Replace the complete file contents with one bounded byte string.
~BoundedAnonymousInputFile()
Close the anonymous file, invalidating the procfs pathname.
BoundedAnonymousInputFile(std::size_t max_bytes)
Construct a lazy owner.
const char * path() const
Return the stable procfs pathname after a successful Write.