Skip to content

Commit 3088f83

Browse files
committed
fuzz: extend FuzzedSock::Recv() to support MSG_PEEK
A conforming `recv(2)` call is supposed to return the same data on a call following `recv(..., MSG_PEEK)`. Extend `FuzzedSock::Recv()` to do that. For simplicity we only return 1 byte when `MSG_PEEK` is used. If we would return a buffer of N bytes, then we would have to keep track how many of them were consumed on subsequent non-`MSG_PEEK` calls.
1 parent 9b05c49 commit 3088f83

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/test/fuzz/util.h

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,13 @@ class FuzzedSock : public Sock
555555
{
556556
FuzzedDataProvider& m_fuzzed_data_provider;
557557

558+
/**
559+
* Data to return when `MSG_PEEK` is used as a `Recv()` flag.
560+
* If `MSG_PEEK` is used, then our `Recv()` returns some random data as usual, but on the next
561+
* `Recv()` call we must return the same data, thus we remember it here.
562+
*/
563+
mutable std::optional<uint8_t> m_peek_data;
564+
558565
public:
559566
explicit FuzzedSock(FuzzedDataProvider& fuzzed_data_provider) : m_fuzzed_data_provider{fuzzed_data_provider}
560567
{
@@ -635,8 +642,26 @@ class FuzzedSock : public Sock
635642
}
636643
return r;
637644
}
638-
const std::vector<uint8_t> random_bytes = m_fuzzed_data_provider.ConsumeBytes<uint8_t>(
639-
m_fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, len));
645+
std::vector<uint8_t> random_bytes;
646+
bool pad_to_len_bytes{m_fuzzed_data_provider.ConsumeBool()};
647+
if (m_peek_data.has_value()) {
648+
// `MSG_PEEK` was used in the preceding `Recv()` call, return `m_peek_data`.
649+
random_bytes.assign({m_peek_data.value()});
650+
if ((flags & MSG_PEEK) == 0) {
651+
m_peek_data.reset();
652+
}
653+
pad_to_len_bytes = false;
654+
} else if ((flags & MSG_PEEK) != 0) {
655+
// New call with `MSG_PEEK`.
656+
random_bytes = m_fuzzed_data_provider.ConsumeBytes<uint8_t>(1);
657+
if (!random_bytes.empty()) {
658+
m_peek_data = random_bytes[0];
659+
pad_to_len_bytes = false;
660+
}
661+
} else {
662+
random_bytes = m_fuzzed_data_provider.ConsumeBytes<uint8_t>(
663+
m_fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, len));
664+
}
640665
if (random_bytes.empty()) {
641666
const ssize_t r = m_fuzzed_data_provider.ConsumeBool() ? 0 : -1;
642667
if (r == -1) {
@@ -645,7 +670,7 @@ class FuzzedSock : public Sock
645670
return r;
646671
}
647672
std::memcpy(buf, random_bytes.data(), random_bytes.size());
648-
if (m_fuzzed_data_provider.ConsumeBool()) {
673+
if (pad_to_len_bytes) {
649674
if (len > random_bytes.size()) {
650675
std::memset((char*)buf + random_bytes.size(), 0, len - random_bytes.size());
651676
}

0 commit comments

Comments
 (0)