Fix CVE-2016-7504:
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-7504
http://bugs.ghostscript.com/show_bug.cgi?id=697142

Patch copied from upstream source repository:
http://git.ghostscript.com/?p=mujs.git;a=commitdiff;h=5c337af4b3df80cf967e4f9f6a21522de84b392a

From 5c337af4b3df80cf967e4f9f6a21522de84b392a Mon Sep 17 00:00:00 2001
From: Tor Andersson <tor.andersson@artifex.com>
Date: Wed, 21 Sep 2016 16:01:08 +0200
Subject: [PATCH] Fix bug 697142: Stale string pointer stored in regexp object.

Make sure to make a copy of the source pattern string.
A case we missed when adding short and memory strings to the runtime.
The code assumed all strings passed to it were either literal or interned.
---
 jsgc.c     | 4 +++-
 jsi.h      | 1 +
 jsregexp.c | 2 +-
 jsrun.c    | 8 ++++++++
 jsvalue.h  | 2 +-
 5 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/jsgc.c b/jsgc.c
index 9bd6482..4f7e7dc 100644
--- a/thirdparty/mujs/jsgc.c
+++ b/thirdparty/mujs/jsgc.c
@@ -44,8 +44,10 @@ static void jsG_freeobject(js_State *J, js_Object *obj)
 {
 	if (obj->head)
 		jsG_freeproperty(J, obj->head);
-	if (obj->type == JS_CREGEXP)
+	if (obj->type == JS_CREGEXP) {
+		js_free(J, obj->u.r.source);
 		js_regfree(obj->u.r.prog);
+	}
 	if (obj->type == JS_CITERATOR)
 		jsG_freeiterator(J, obj->u.iter.head);
 	if (obj->type == JS_CUSERDATA && obj->u.user.finalize)
diff --git a/jsi.h b/jsi.h
index 7d9f7c7..e855045 100644
--- a/thirdparty/mujs/jsi.h
+++ b/thirdparty/mujs/jsi.h
@@ -79,6 +79,7 @@ typedef unsigned short js_Instruction;
 
 /* String interning */
 
+char *js_strdup(js_State *J, const char *s);
 const char *js_intern(js_State *J, const char *s);
 void jsS_dumpstrings(js_State *J);
 void jsS_freestrings(js_State *J);
diff --git a/jsregexp.c b/jsregexp.c
index 2a056b7..a2d5156 100644
--- a/thirdparty/mujs/jsregexp.c
+++ b/thirdparty/mujs/jsregexp.c
@@ -21,7 +21,7 @@ void js_newregexp(js_State *J, const char *pattern, int flags)
 		js_syntaxerror(J, "regular expression: %s", error);
 
 	obj->u.r.prog = prog;
-	obj->u.r.source = pattern;
+	obj->u.r.source = js_strdup(J, pattern);
 	obj->u.r.flags = flags;
 	obj->u.r.last = 0;
 	js_pushobject(J, obj);
diff --git a/jsrun.c b/jsrun.c
index 2648c4c..ee80845 100644
--- a/thirdparty/mujs/jsrun.c
+++ b/thirdparty/mujs/jsrun.c
@@ -45,6 +45,14 @@ void *js_realloc(js_State *J, void *ptr, int size)
 	return ptr;
 }
 
+char *js_strdup(js_State *J, const char *s)
+{
+	int n = strlen(s) + 1;
+	char *p = js_malloc(J, n);
+	memcpy(p, s, n);
+	return p;
+}
+
 void js_free(js_State *J, void *ptr)
 {
 	J->alloc(J->actx, ptr, 0);
diff --git a/jsvalue.h b/jsvalue.h
index 6cfbd89..8fb5016 100644
--- a/thirdparty/mujs/jsvalue.h
+++ b/thirdparty/mujs/jsvalue.h
@@ -71,7 +71,7 @@ struct js_String
 struct js_Regexp
 {
 	void *prog;
-	const char *source;
+	char *source;
 	unsigned short flags;
 	unsigned short last;
 };
-- 
2.10.2

