From: Ken Sharp <ken.sharp@artifex.com>
Date: Mon, 21 Aug 2023 16:50:00 +0100
Subject: PostScript interpreter - Null dangling references on stack
Origin: https://git.ghostscript.com/?p=ghostpdl.git;a=commit;h=05425198e588427327c55b76dfad57f20f62f944

In the wake of bug #707007 it is clear that due ot the way GC works on
stack clumps of memory, we cannot leave references to structures which
have been explicitly freed on the stacks.

So far this only seems to be a problem with the exec stack, because
objects on the operand stack are left to GC to free.

This commit is the result of reviewing all the places I could find where
we allocate a structure on the stack, and then free it explicitly in C
rather than leaving it to the garbage collector.
---
 psi/zfile.c    | 2 ++
 psi/zfsample.c | 2 ++
 psi/zht1.c     | 3 +++
 psi/zht2.c     | 3 +++
 4 files changed, 10 insertions(+)

diff --git a/psi/zfile.c b/psi/zfile.c
index 45f4d5909d2e..a4f5439cd290 100644
--- a/psi/zfile.c
+++ b/psi/zfile.c
@@ -464,6 +464,8 @@ file_cleanup(i_ctx_t *i_ctx_p)
     gx_io_device *iodev = r_ptr(esp + 2, gx_io_device);
 
     iodev->procs.enumerate_close(imemory, r_ptr(esp + 5, file_enum));
+    /* See bug #707007, gp_enumerate_file_close() explicitly frees the file enumerator */
+    make_null(esp + 5);
     return 0;
 }
 
diff --git a/psi/zfsample.c b/psi/zfsample.c
index 7ad503e3f87c..1fc30989ca32 100644
--- a/psi/zfsample.c
+++ b/psi/zfsample.c
@@ -621,6 +621,8 @@ sampled_data_finish(i_ctx_t *i_ctx_p)
     make_oper_new(cref.value.refs + 1, 0, zexecfunction);
     ref_assign(op, &cref);
 
+    /* See bug #707007, explicitly freed structures on the stacks need to be made NULL */
+    make_null(esp);
     esp -= estack_storage;
     ifree_object(penum->pfn, "sampled_data_finish(pfn)");
     ifree_object(penum, "sampled_data_finish(enum)");
diff --git a/psi/zht1.c b/psi/zht1.c
index 77a0bcb96dcc..fb33193a65c6 100644
--- a/psi/zht1.c
+++ b/psi/zht1.c
@@ -141,6 +141,9 @@ setcolorscreen_cleanup(i_ctx_t *i_ctx_p)
                    "setcolorscreen_cleanup(device halftone)");
     gs_free_object(pht->rc.memory, pht,
                    "setcolorscreen_cleanup(halftone)");
+    /* See bug #707007, explicitly freed structures on the stacks need to be made NULL */
+    make_null(esp + 6);
+    make_null(esp + 7);
     return 0;
 }
 
diff --git a/psi/zht2.c b/psi/zht2.c
index c0f151aa63ab..6a1e7666f2bf 100644
--- a/psi/zht2.c
+++ b/psi/zht2.c
@@ -649,6 +649,9 @@ sethalftone_cleanup(i_ctx_t *i_ctx_p)
                    "sethalftone_cleanup(device halftone)");
     gs_free_object(pht->rc.memory, pht,
                    "sethalftone_cleanup(halftone)");
+    /* See bug #707007, explicitly freed structures on the stacks need to be made NULL */
+    make_null(&esp[4]);
+    make_null(&esp[3]);
     return 0;
 }
 
-- 
2.45.2

