| 1 |
// SPDX-FileCopyrightText: 2026 PoDoFo contributors |
| 2 |
// SPDX-License-Identifier: MIT-0 |
| 3 |
|
| 4 |
#include <PdfTest.h> |
| 5 |
|
| 6 |
using namespace std; |
| 7 |
using namespace PoDoFo; |
| 8 |
|
| 9 |
TEST_CASE("TestContentStreamReaderTerminates") |
| 10 |
{ |
| 11 |
// Regression test for infinite loop in PdfContentStreamReader. |
| 12 |
// |
| 13 |
// Input "+\n\tH" (and similar short inputs like "-\0TT", ".\n\t\xf6", |
| 14 |
// ".///") causes an infinite loop when fed into the content stream reader. |
| 15 |
// |
| 16 |
// Root cause: PdfTokenizer::DetermineDataType classifies a bare "+" |
| 17 |
// (or "-", ".") as a candidate Number/Real, but std::from_chars fails |
| 18 |
// to parse it. The recovery path re-enqueues the same token via |
| 19 |
// EnqueueToken, then returns Unknown. On the next call to TryReadNextToken |
| 20 |
// the enqueued token is dequeued, DetermineDataType fails again and |
| 21 |
// re-enqueues it — creating an infinite loop. |
| 22 |
// |
| 23 |
// Inputs are taken from libFuzzer timeout artifacts (4 bytes each). |
| 24 |
const string_view inputs[] = { |
| 25 |
"+\n\tH"sv, |
| 26 |
{ "-\x00TT", 4 }, |
| 27 |
".\n\t\xf6"sv, |
| 28 |
".///"sv, |
| 29 |
{ "\x00-(\xff", 4 }, |
| 30 |
}; |
| 31 |
|
| 32 |
for (auto& input : inputs) |
| 33 |
{ |
| 34 |
INFO("Input bytes: " << input.size()); |
| 35 |
|
| 36 |
auto device = std::make_shared<SpanStreamDevice>(input); |
| 37 |
PdfContentReaderArgs args; |
| 38 |
args.Flags = PdfContentReaderFlags::SkipFollowFormXObjects |
| 39 |
| PdfContentReaderFlags::SkipHandleNonFormXObjects; |
| 40 |
|
| 41 |
PdfContentStreamReader reader(device, args); |
| 42 |
PdfContent content; |
| 43 |
|
| 44 |
// Must terminate — before the fix this loops forever. |
| 45 |
// A generous iteration cap ensures the test fails fast if |
| 46 |
// the bug regresses, without relying on wall-clock timeouts. |
| 47 |
unsigned iterations = 0; |
| 48 |
constexpr unsigned maxIterations = 100; |
| 49 |
try |
| 50 |
{ |
| 51 |
while (reader.TryReadNext(content) && iterations < maxIterations) |
| 52 |
iterations++; |
| 53 |
} |
| 54 |
catch (PdfError&) |
| 55 |
{ |
| 56 |
} |
| 57 |
catch (std::exception&) |
| 58 |
{ |
| 59 |
} |
| 60 |
|
| 61 |
REQUIRE(iterations < maxIterations); |
| 62 |
} |
| 63 |
} |