Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/UglyToad.PdfPig.Tests/Integration/CrossReferenceParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,17 @@ public void CanReadDocumentWithMissingWhitespaceAfterXRef()
using var document = PdfDocument.Open(path);
Assert.Equal(3, document.NumberOfPages);
}

[Fact]
public void CanReadDocumentWithCircularXRef()
{
string path = IntegrationHelpers.GetSpecificTestDocumentPath("B17-2000-transportation-fuels.pdf");

// If parser can't deal with xrefs that have circular references then
// opening the document will loop forever
using var document = PdfDocument.Open(path);

Assert.Equal(1, document.NumberOfPages);
}
}
}
Binary file not shown.
22 changes: 20 additions & 2 deletions src/UglyToad.PdfPig/Parser/FileStructure/XrefBruteForcer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public static Result FindAllXrefsInFileOrder(
{
var results = new List<IXrefSection>();

// Guard against circular references; only read xref at each offset once
var xrefOffsetSeen = new HashSet<long>();

var bruteForceObjPositions = new Dictionary<IndirectReference, long>();

DictionaryToken? trailer = null;
Expand Down Expand Up @@ -131,6 +134,14 @@ void AddQueues(long num)
ClearQueues();

var potentialTableOffset = bytes.CurrentOffset - 4;

if (xrefOffsetSeen.Contains(potentialTableOffset))
{
log.Debug($"Skipping circular xref reference at {potentialTableOffset}");
continue;
}
xrefOffsetSeen.Add(potentialTableOffset);

var table = XrefTableParser.TryReadTableAtOffset(
new FileHeaderOffset(0),
potentialTableOffset,
Expand All @@ -152,15 +163,22 @@ void AddQueues(long num)
{
ClearQueues();

if (!lastObjPosition.HasValue)
if (lastObjPosition is not long offset)
{
log.Error("Found an /XRef without having encountered an object first");
continue;
}

if (xrefOffsetSeen.Contains(offset))
{
log.Debug($"Skipping circular /XRef reference at {offset}");
continue;
}
xrefOffsetSeen.Add(offset);

var stream = XrefStreamParser.TryReadStreamAtOffset(
new FileHeaderOffset(0),
lastObjPosition.Value,
offset,
bytes,
scanner,
log);
Expand Down
Loading