From 64a43b38d2e7843a3d2a301d928eac6b5609fe01 Mon Sep 17 00:00:00 2001 From: Adrian-George Bostan Date: Wed, 1 Apr 2020 23:08:41 +0300 Subject: [PATCH] Prevent crashing when processing content stream (#291) * Skip invalid pop operation on empty graphics state stacks * Fix clipping input values to size for Type 0 Functions * Do not pass invalid Q content stream operator to external handlers --- contentstream/processor.go | 4 ++++ model/functions.go | 5 ++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/contentstream/processor.go b/contentstream/processor.go index ccfb13e4..7cd2a2db 100644 --- a/contentstream/processor.go +++ b/contentstream/processor.go @@ -230,6 +230,10 @@ func (proc *ContentStreamProcessor) Process(resources *model.PdfPageResources) e case "q": proc.graphicsStack.Push(proc.graphicsState) case "Q": + if len(proc.graphicsStack) == 0 { + common.Log.Debug("WARN: invalid `Q` operator. Graphics state stack is empty. Skipping.") + continue + } proc.graphicsState = proc.graphicsStack.Pop() // Color operations (Table 74 p. 179) diff --git a/model/functions.go b/model/functions.go index 6f0b1553..1e7e0f56 100644 --- a/model/functions.go +++ b/model/functions.go @@ -306,10 +306,10 @@ func (f *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { for i := 0; i < len(x); i++ { xi := x[i] + // See section 7.10.2 Type 0 (Sampled) Functions (pp. 93-94 PDF32000_2008). xip := math.Min(math.Max(xi, f.Domain[2*i]), f.Domain[2*i+1]) - ei := interpolate(xip, f.Domain[2*i], f.Domain[2*i+1], encode[2*i], encode[2*i+1]) - eip := math.Min(math.Max(ei, 0), float64(f.Size[i])) + eip := math.Min(math.Max(ei, 0), float64(f.Size[i]-1)) // eip represents coordinate into the data table. // At this point it is real values. @@ -325,7 +325,6 @@ func (f *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) { index = f.Size[i] - 1 } indices = append(indices, index) - } // Calculate the index