From 671fd59eb657743aa86fbc1895cb15872a317caa Mon Sep 17 00:00:00 2001
From: Chris Liddell <chris.liddell@artifex.com>
Date: Thu, 6 Jul 2017 14:54:02 +0100
Subject: [PATCH] Bug 698158: prevent trying to reloc a freed object

In the token reader, we pass the scanner state structure around as a
t_struct ref on the Postscript operand stack.

But we explicitly free the scanner state when we're done, which leaves a
dangling reference on the operand stack and, unless that reference gets
overwritten before the next garbager run, we can end up with the garbager
trying to deal with an already freed object - that can cause a crash, or
memory corruption.
---
 psi/ztoken.c |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

--- end of original header

CVE: CVE-2017-11714

Upstream-Status: Backport [git://git.ghostscript.com/ghostpdl.git]

Signed-off-by: Joe Slater <joe.slater@windriver.com>

diff --git a/psi/ztoken.c b/psi/ztoken.c
index 4dba7c5..af1ceeb 100644
--- a/psi/ztoken.c
+++ b/psi/ztoken.c
@@ -107,6 +107,12 @@ token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save)
     int code;
     ref token;
 
+    /* Since we might free pstate below, and we're dealing with
+     * gc memory referenced by the stack, we need to explicitly
+     * remove the reference to pstate from the stack, otherwise
+     * the garbager will fall over
+     */
+    make_null(osp);
     /* Note that gs_scan_token may change osp! */
     pop(1);                     /* remove the file or scanner state */
 again:
@@ -183,8 +189,14 @@ ztokenexec_continue(i_ctx_t *i_ctx_p)
 static int
 tokenexec_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save)
 {
-    os_ptr op;
+    os_ptr op = osp;
     int code;
+    /* Since we might free pstate below, and we're dealing with
+     * gc memory referenced by the stack, we need to explicitly
+     * remove the reference to pstate from the stack, otherwise
+     * the garbager will fall over
+     */
+    make_null(osp);
     /* Note that gs_scan_token may change osp! */
     pop(1);
 again:
-- 
1.7.9.5

