code:
Make sure that statements such as:

  strcpy (dst, "/gnu/store/…");

or

  static const char str[] = "/gnu/store/…";
  …
  strcpy (dst, str);

do not result in chunked /gnu/store strings that are undetectable by
Guix's GC and its grafting code.  See <https://bugs.gnu.org/24703>
and <https://bugs.gnu.org/30395>.

--- gcc-5.3.0/gcc/builtins.c	2016-10-18 10:50:46.080616285 +0200
+++ gcc-5.3.0/gcc/builtins.c	2016-11-09 15:26:43.693042737 +0100
@@ -3192,6 +3192,54 @@ determine_block_size (tree len, rtx len_
 			  GET_MODE_MASK (GET_MODE (len_rtx)));
 }

+extern void debug_tree (tree);
+
+/* Return true if STR contains the string "/gnu/store".  */
+
+bool
+store_reference_p (tree str)
+{
+  if (getenv ("GUIX_GCC_DEBUG") != NULL)
+    debug_tree (str);
+
+  if (TREE_CODE (str) == ADDR_EXPR)
+    str = TREE_OPERAND (str, 0);
+
+  if (TREE_CODE (str) == VAR_DECL
+      && TREE_STATIC (str)
+      && TREE_READONLY (str))
+    /* STR may be a 'static const' variable whose initial value
+       is a string constant.  See <https://bugs.gnu.org/30395>.  */
+    str = DECL_INITIAL (str);
+
+  if (TREE_CODE (str) != STRING_CST)
+    return false;
+
+  int len;
+  const char *store;
+
+  store = getenv ("NIX_STORE") ? getenv ("NIX_STORE") : "/gnu/store";
+  len = strlen (store);
+
+  /* Size of the hash part of store file names, including leading slash and
+     trailing hyphen.  */
+  const int hash_len = 34;
+
+  if (TREE_STRING_LENGTH (str) < len + hash_len)
+    return false;
+
+  /* We cannot use 'strstr' because 'TREE_STRING_POINTER' returns a string
+     that is not necessarily NUL-terminated.  */
+
+  for (int i = 0; i < TREE_STRING_LENGTH (str) - (len + hash_len); i++)
+    {
+      if (strncmp (TREE_STRING_POINTER (str) + i, store, len) == 0)
+	return true;
+    }
+
+  return false;
+}
+
 /* Helper function to do the actual work for expand_builtin_memcpy.  */

 static rtx
@@ -3207,6 +3243,13 @@ expand_builtin_memcpy_args (tree dest, t
   unsigned HOST_WIDE_INT max_size;
   unsigned HOST_WIDE_INT probable_max_size;

+  /* Do not emit block moves, which translate to the 'movabs' instruction on
+     x86_64, when SRC refers to store items.  That way, store references
+     remain visible to the Guix GC and grafting code.  See
+     <https://bugs.gnu.org/24703>.  */
+  if (store_reference_p (src))
+    return NULL_RTX;
+
   /* If DEST is not a pointer type, call the normal function.  */
   if (dest_align == 0)
     return NULL_RTX;

--- gcc-5.5.0/gcc/gimple-fold.c	2018-03-20 11:36:16.709442004 +0100
+++ gcc-5.5.0/gcc/gimple-fold.c	2018-03-20 11:46:43.838487065 +0100
@@ -769,6 +769,8 @@ var_decl_component_p (tree var)
   return SSA_VAR_P (inner);
 }

+extern bool store_reference_p (tree);
+
 /* Fold function call to builtin mem{{,p}cpy,move}.  Return
    false if no simplification can be made.
    If ENDP is 0, return DEST (like memcpy).
@@ -1099,6 +1101,9 @@ gimple_fold_builtin_memory_op (gimple_st
       if (!srctype)
 	return false;

+      if (store_reference_p (src))
+        return false;
+
       src_align = get_pointer_alignment (src);
       dest_align = get_pointer_alignment (dest);
       if (dest_align < TYPE_ALIGN (desttype)


code:
This patch removes a group of tests that fail because /var/lib/dbus/machine-id
is not present in the build environment.

--- gcr-3.20.0.old/Makefile.in	2017-07-03 18:05:10.742595317 -0400
+++ gcr-3.20.0/Makefile.in	2017-07-03 18:08:26.379565428 -0400
@@ -482,8 +482,7 @@
 	test-openssh$(EXEEXT) test-secure-memory$(EXEEXT) \
 	test-trust$(EXEEXT) test-parser$(EXEEXT) test-record$(EXEEXT) \
 	test-memory-icon$(EXEEXT) test-gnupg-key$(EXEEXT) \
-	test-gnupg-collection$(EXEEXT) test-gnupg-process$(EXEEXT) \
-	test-system-prompt$(EXEEXT)
+	test-gnupg-collection$(EXEEXT) test-gnupg-process$(EXEEXT)
 @WITH_GTK_TRUE@am__EXEEXT_4 = frob-certificate$(EXEEXT) \
 @WITH_GTK_TRUE@	frob-combo-selector$(EXEEXT) \
 @WITH_GTK_TRUE@	frob-gnupg-selector$(EXEEXT) \
@@ -882,14 +881,6 @@
 am_test_symkey_OBJECTS = egg/test-symkey.$(OBJEXT)
 test_symkey_OBJECTS = $(am_test_symkey_OBJECTS)
 test_symkey_DEPENDENCIES = $(am__DEPENDENCIES_4)
-am_test_system_prompt_OBJECTS =  \
-	gcr/test_system_prompt-test-system-prompt.$(OBJEXT)
-test_system_prompt_OBJECTS = $(am_test_system_prompt_OBJECTS)
-test_system_prompt_DEPENDENCIES = $(am__DEPENDENCIES_3)
-test_system_prompt_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC \
-	$(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CCLD) \
-	$(test_system_prompt_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \
-	$(LDFLAGS) -o $@
 am_test_trust_OBJECTS = gcr/test_trust-test-trust.$(OBJEXT)
 test_trust_OBJECTS = $(am_test_trust_OBJECTS)
 test_trust_DEPENDENCIES = $(am__DEPENDENCIES_3)
@@ -974,8 +965,7 @@
 	$(test_secret_exchange_SOURCES) $(test_secure_memory_SOURCES) \
 	$(test_simple_certificate_SOURCES) \
 	$(test_subject_public_key_SOURCES) $(test_symkey_SOURCES) \
-	$(test_system_prompt_SOURCES) $(test_trust_SOURCES) \
-	$(test_util_SOURCES)
+	$(test_trust_SOURCES) $(test_util_SOURCES)
 DIST_SOURCES = $(libegg_asn1x_la_SOURCES) $(libegg_hex_la_SOURCES) \
 	$(libegg_secmem_la_SOURCES) $(libegg_test_la_SOURCES) \
 	$(libegg_la_SOURCES) $(libgck_@GCK_MAJOR@_la_SOURCES) \
@@ -1016,8 +1006,7 @@
 	$(test_secret_exchange_SOURCES) $(test_secure_memory_SOURCES) \
 	$(test_simple_certificate_SOURCES) \
 	$(test_subject_public_key_SOURCES) $(test_symkey_SOURCES) \
-	$(test_system_prompt_SOURCES) $(test_trust_SOURCES) \
-	$(test_util_SOURCES)
+	$(test_trust_SOURCES) $(test_util_SOURCES)
 RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
 	ctags-recursive dvi-recursive html-recursive info-recursive \
 	install-data-recursive install-dvi-recursive \
@@ -2117,8 +2106,7 @@
 	test-memory-icon \
 	test-gnupg-key \
 	test-gnupg-collection \
-	test-gnupg-process \
-	test-system-prompt
+	test-gnupg-process

 test_certificate_SOURCES = gcr/test-certificate.c
 test_certificate_CFLAGS = $(gcr_CFLAGS)
@@ -2171,9 +2159,6 @@
 test_subject_public_key_SOURCES = gcr/test-subject-public-key.c
 test_subject_public_key_CFLAGS = $(gcr_CFLAGS)
 test_subject_public_key_LDADD = $(gcr_LIBS)
-test_system_prompt_SOURCES = gcr/test-system-prompt.c
-test_system_prompt_CFLAGS = $(gcr_CFLAGS)
-test_system_prompt_LDADD = $(gcr_LIBS)
 test_trust_SOURCES = gcr/test-trust.c
 test_trust_CFLAGS = $(gcr_CFLAGS)
 test_trust_LDADD = $(gcr_LIBS)
@@ -3283,12 +3268,6 @@
 test-symkey$(EXEEXT): $(test_symkey_OBJECTS) $(test_symkey_DEPENDENCIES) $(EXTRA_test_symkey_DEPENDENCIES)
 	@rm -f test-symkey$(EXEEXT)
 	$(AM_V_CCLD)$(LINK) $(test_symkey_OBJECTS) $(test_symkey_LDADD) $(LIBS)
-gcr/test_system_prompt-test-system-prompt.$(OBJEXT):  \
-	gcr/$(am__dirstamp) gcr/$(DEPDIR)/$(am__dirstamp)
-
-test-system-prompt$(EXEEXT): $(test_system_prompt_OBJECTS) $(test_system_prompt_DEPENDENCIES) $(EXTRA_test_system_prompt_DEPENDENCIES)
-	@rm -f test-system-prompt$(EXEEXT)
-	$(AM_V_CCLD)$(test_system_prompt_LINK) $(test_system_prompt_OBJECTS) $(test_system_prompt_LDADD) $(LIBS)
 gcr/test_trust-test-trust.$(OBJEXT): gcr/$(am__dirstamp) \
 	gcr/$(DEPDIR)/$(am__dirstamp)

@@ -3446,7 +3425,6 @@
 @AMDEP_TRUE@@am__include@ @am__quote@gcr/$(DEPDIR)/test_secure_memory-test-secure-memory.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@gcr/$(DEPDIR)/test_simple_certificate-test-simple-certificate.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@gcr/$(DEPDIR)/test_subject_public_key-test-subject-public-key.Po@am__quote@
-@AMDEP_TRUE@@am__include@ @am__quote@gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@gcr/$(DEPDIR)/test_trust-test-trust.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@gcr/$(DEPDIR)/test_util-test-util.Po@am__quote@
 @AMDEP_TRUE@@am__include@ @am__quote@ui/$(DEPDIR)/frob_certificate-frob-certificate.Po@am__quote@
@@ -4968,20 +4946,6 @@
 @AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_subject_public_key_CFLAGS) $(CFLAGS) -c -o gcr/test_subject_public_key-test-subject-public-key.obj `if test -f 'gcr/test-subject-public-key.c'; then $(CYGPATH_W) 'gcr/test-subject-public-key.c'; else $(CYGPATH_W) '$(srcdir)/gcr/test-subject-public-key.c'; fi`

-gcr/test_system_prompt-test-system-prompt.o: gcr/test-system-prompt.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_system_prompt_CFLAGS) $(CFLAGS) -MT gcr/test_system_prompt-test-system-prompt.o -MD -MP -MF gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Tpo -c -o gcr/test_system_prompt-test-system-prompt.o `test -f 'gcr/test-system-prompt.c' || echo '$(srcdir)/'`gcr/test-system-prompt.c
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Tpo gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='gcr/test-system-prompt.c' object='gcr/test_system_prompt-test-system-prompt.o' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_system_prompt_CFLAGS) $(CFLAGS) -c -o gcr/test_system_prompt-test-system-prompt.o `test -f 'gcr/test-system-prompt.c' || echo '$(srcdir)/'`gcr/test-system-prompt.c
-
-gcr/test_system_prompt-test-system-prompt.obj: gcr/test-system-prompt.c
-@am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_system_prompt_CFLAGS) $(CFLAGS) -MT gcr/test_system_prompt-test-system-prompt.obj -MD -MP -MF gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Tpo -c -o gcr/test_system_prompt-test-system-prompt.obj `if test -f 'gcr/test-system-prompt.c'; then $(CYGPATH_W) 'gcr/test-system-prompt.c'; else $(CYGPATH_W) '$(srcdir)/gcr/test-system-prompt.c'; fi`
-@am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Tpo gcr/$(DEPDIR)/test_system_prompt-test-system-prompt.Po
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	$(AM_V_CC)source='gcr/test-system-prompt.c' object='gcr/test_system_prompt-test-system-prompt.obj' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCC_FALSE@	DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
-@am__fastdepCC_FALSE@	$(AM_V_CC@am__nodep@)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_system_prompt_CFLAGS) $(CFLAGS) -c -o gcr/test_system_prompt-test-system-prompt.obj `if test -f 'gcr/test-system-prompt.c'; then $(CYGPATH_W) 'gcr/test-system-prompt.c'; else $(CYGPATH_W) '$(srcdir)/gcr/test-system-prompt.c'; fi`
-
 gcr/test_trust-test-trust.o: gcr/test-trust.c
 @am__fastdepCC_TRUE@	$(AM_V_CC)$(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(test_trust_CFLAGS) $(CFLAGS) -MT gcr/test_trust-test-trust.o -MD -MP -MF gcr/$(DEPDIR)/test_trust-test-trust.Tpo -c -o gcr/test_trust-test-trust.o `test -f 'gcr/test-trust.c' || echo '$(srcdir)/'`gcr/test-trust.c
 @am__fastdepCC_TRUE@	$(AM_V_at)$(am__mv) gcr/$(DEPDIR)/test_trust-test-trust.Tpo gcr/$(DEPDIR)/test_trust-test-trust.Po
@@ -5808,13 +5772,6 @@
 	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
 	--log-file $$b.log --trs-file $$b.trs \
 	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
-	"$$tst" $(AM_TESTS_FD_REDIRECT)
-test-system-prompt.log: test-system-prompt$(EXEEXT)
-	@p='test-system-prompt$(EXEEXT)'; \
-	b='test-system-prompt'; \
-	$(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \
-	--log-file $$b.log --trs-file $$b.trs \
-	$(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \
 	"$$tst" $(AM_TESTS_FD_REDIRECT)
 .test.log:
 	@p='$<'; \

license: mit


code:
This patch comes from Debian.

https://bugzilla.gnome.org/show_bug.cgi?id=771052
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=835737

--- gcr-3.20.0.old/gcr/test-gnupg-collection.c	2017-06-29 14:26:33.810838197 -0400
+++ gcr-3.20.0/gcr/test-gnupg-collection.c	2017-06-30 17:25:09.149383067 -0400
@@ -115,6 +115,14 @@

	g_object_unref (test->collection);

+	/* remove potential gpg 2.1 extras, ignore any errors. */
+	cmd = g_strdup_printf ("rm -rf %s/*.d", test->directory);
+	system(cmd);
+	g_free(cmd);
+	cmd = g_strdup_printf ("rm -f %s/.gpg-v21-migrated", test->directory);
+	system(cmd);
+	g_free(cmd);
+
	cmd = g_strdup_printf ("rm -f %s/*", test->directory);
	g_spawn_check_exit_status (system (cmd), &error);
	g_assert_no_error (error);
@@ -202,7 +210,7 @@
	GcrGnupgKey *key;

	_gcr_gnupg_collection_load_async (test->collection, NULL, on_async_ready, test);
-	egg_test_wait_until (500);
+	egg_test_wait_until (2500);
	g_assert (test->result);
	_gcr_gnupg_collection_load_finish (test->collection, test->result, &error);
	g_assert_no_error (error);


code:
Fix CVE-2018-1000222:

https://github.com/libgd/libgd/issues/447
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-1000222

Patch copied from upstream source repository:

https://github.com/libgd/libgd/commit/4b1e18a00ce7c4b7e6919c3b3109a034393b805a

From 4b1e18a00ce7c4b7e6919c3b3109a034393b805a Mon Sep 17 00:00:00 2001
From: Mike Frysinger <vapier@gentoo.org>
Date: Sat, 14 Jul 2018 13:54:08 -0400
Subject: [PATCH] bmp: check return value in gdImageBmpPtr

Closes #447.

(cherry picked from commit ac16bdf2d41724b5a65255d4c28fb0ec46bc42f5)
---
 src/gd_bmp.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/src/gd_bmp.c b/src/gd_bmp.c
index ccafdcd..d625da1 100644
--- a/src/gd_bmp.c
+++ b/src/gd_bmp.c
@@ -48,6 +48,8 @@ static int bmp_read_4bit(gdImagePtr im, gdIOCtxPtr infile, bmp_info_t *info, bmp
 static int bmp_read_8bit(gdImagePtr im, gdIOCtxPtr infile, bmp_info_t *info, bmp_hdr_t *header);
 static int bmp_read_rle(gdImagePtr im, gdIOCtxPtr infile, bmp_info_t *info);

+static int _gdImageBmpCtx(gdImagePtr im, gdIOCtxPtr out, int compression);
+
 #define BMP_DEBUG(s)

 static int gdBMPPutWord(gdIOCtx *out, int w)
@@ -88,8 +90,10 @@ BGD_DECLARE(void *) gdImageBmpPtr(gdImagePtr im, int *size, int compression)
 	void *rv;
 	gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
 	if (out == NULL) return NULL;
-	gdImageBmpCtx(im, out, compression);
-	rv = gdDPExtractData(out, size);
+	if (!_gdImageBmpCtx(im, out, compression))
+		rv = gdDPExtractData(out, size);
+	else
+		rv = NULL;
 	out->gd_free(out);
 	return rv;
 }
@@ -142,6 +146,11 @@ BGD_DECLARE(void) gdImageBmp(gdImagePtr im, FILE *outFile, int compression)
 		compression - whether to apply RLE or not.
 */
 BGD_DECLARE(void) gdImageBmpCtx(gdImagePtr im, gdIOCtxPtr out, int compression)
+{
+	_gdImageBmpCtx(im, out, compression);
+}
+
+static int _gdImageBmpCtx(gdImagePtr im, gdIOCtxPtr out, int compression)
 {
 	int bitmap_size = 0, info_size, total_size, padding;
 	int i, row, xpos, pixel;
@@ -149,6 +158,7 @@ BGD_DECLARE(void) gdImageBmpCtx(gdImagePtr im, gdIOCtxPtr out, int compression)
 	unsigned char *uncompressed_row = NULL, *uncompressed_row_start = NULL;
 	FILE *tmpfile_for_compression = NULL;
 	gdIOCtxPtr out_original = NULL;
+	int ret = 1;

 	/* No compression if its true colour or we don't support seek */
 	if (im->trueColor) {
@@ -326,6 +336,7 @@ BGD_DECLARE(void) gdImageBmpCtx(gdImagePtr im, gdIOCtxPtr out, int compression)
 		out_original = NULL;
 	}

+	ret = 0;
 cleanup:
 	if (tmpfile_for_compression) {
 #ifdef _WIN32
@@ -339,7 +350,7 @@ cleanup:
 	if (out_original) {
 		out_original->gd_free(out_original);
 	}
-	return;
+	return ret;
 }

 static int compress_row(unsigned char *row, int length)
--
2.18.0


code:
This patch is adapted from commit a11f47475e6443b7f32d21f2271f28f417e2ac04 and
fixes CVE-2018-5711.

From a11f47475e6443b7f32d21f2271f28f417e2ac04 Mon Sep 17 00:00:00 2001
From: "Christoph M. Becker" <cmbecker69@gmx.de>
Date: Wed, 29 Nov 2017 19:37:38 +0100
Subject: [PATCH] Fix #420: Potential infinite loop in gdImageCreateFromGifCtx

Due to a signedness confusion in `GetCode_` a corrupt GIF file can
trigger an infinite loop.  Furthermore we make sure that a GIF without
any palette entries is treated as invalid *after* open palette entries
have been removed.

CVE-2018-5711

See also https://bugs.php.net/bug.php?id=75571.
---
 src/gd_gif_in.c             |  12 ++++++------
 1 file changed, 38 insertions(+), 6 deletions(-)

diff --git a/src/gd_gif_in.c b/src/gd_gif_in.c
index daf26e7..0a8bd71 100644
--- a/src/gd_gif_in.c
+++ b/src/gd_gif_in.c
@@ -335,11 +335,6 @@ terminated:
 		return 0;
 	}

-	if(!im->colorsTotal) {
-		gdImageDestroy(im);
-		return 0;
-	}
-
 	/* Check for open colors at the end, so
 	 * we can reduce colorsTotal and ultimately
 	 * BitsPerPixel */
@@ -351,6 +346,11 @@ terminated:
 		}
 	}

+	if(!im->colorsTotal) {
+		gdImageDestroy(im);
+		return 0;
+	}
+
 	return im;
 }

@@ -447,7 +447,7 @@ static int
 GetCode_(gdIOCtx *fd, CODE_STATIC_DATA *scd, int code_size, int flag, int *ZeroDataBlockP)
 {
 	int i, j, ret;
-	unsigned char count;
+	int count;

 	if(flag) {
 		scd->curbit = 0;

--
2.13.6


code:
Disable some image comparison tests on architectures such as i686
where intermediate floating-point operations are done with 80-bit long
doubles, and typically later rounded to 64-bit doubles.  This double
rounding causes small differences in the resulting pixel values
compared with other architectures, causing the image comparisons to
fail.

Patch by Mark H Weaver <mhw@netris.org>.

diff -ru libgd-2.2.3.orig/tests/gdimagecopyresampled/basic_alpha.c libgd-2.2.3/tests/gdimagecopyresampled/basic_alpha.c
--- libgd-2.2.3.orig/tests/gdimagecopyresampled/basic_alpha.c	2016-07-21 04:06:42.000000000 -0400
+++ libgd-2.2.3/tests/gdimagecopyresampled/basic_alpha.c	2016-07-29 13:50:56.214877446 -0400
@@ -1,5 +1,6 @@
 /* Testing basic gdImageCopyResampled() functionality with alpha channel */

+#include <float.h>
 #include "gd.h"
 #include "gdtest.h"

@@ -33,7 +34,8 @@
 	gdImageCopyResampled(copy, im, 0,0, 0,0, 200,200, 400,300);
 	gdImageDestroy(im);

-	gdAssertImageEqualsToFile("gdimagecopyresampled/basic_alpha_exp.png", copy);
+	if (FLT_EVAL_METHOD != 2)
+		gdAssertImageEqualsToFile("gdimagecopyresampled/basic_alpha_exp.png", copy);

 	gdImageDestroy(copy);
 	return gdNumFailures();
diff -ru libgd-2.2.3.orig/tests/gdimagecopyresampled/bug00201.c libgd-2.2.3/tests/gdimagecopyresampled/bug00201.c
--- libgd-2.2.3.orig/tests/gdimagecopyresampled/bug00201.c	2016-07-21 04:06:42.000000000 -0400
+++ libgd-2.2.3/tests/gdimagecopyresampled/bug00201.c	2016-07-29 13:50:30.638559003 -0400
@@ -1,3 +1,4 @@
+#include <float.h>
 #include "gd.h"
 #include "gdtest.h"

@@ -65,7 +66,8 @@
     gdImageDestroy(background);
     gdImageDestroy(scaled_logo);

-    gdAssertImageEqualsToFile("gdimagecopyresampled/bug00201_exp.png", img);
+    if (FLT_EVAL_METHOD != 2)
+        gdAssertImageEqualsToFile("gdimagecopyresampled/bug00201_exp.png", img);
     gdImageDestroy(img);
     return gdNumFailures();
 }
diff -ru libgd-2.2.3.orig/tests/gdimagerotate/bug00067.c libgd-2.2.3/tests/gdimagerotate/bug00067.c
--- libgd-2.2.3.orig/tests/gdimagerotate/bug00067.c	2016-06-18 05:42:16.000000000 -0400
+++ libgd-2.2.3/tests/gdimagerotate/bug00067.c	2016-07-29 13:50:07.566271765 -0400
@@ -1,5 +1,6 @@
 #include <stdio.h>
 #include <stdlib.h>
+#include <float.h>
 #include "gd.h"

 #include "gdtest.h"
@@ -43,7 +44,7 @@

 		sprintf(filename, "bug00067_%03d_exp.png", angle);
 		path = gdTestFilePath2("gdimagerotate", filename);
-		if (!gdAssertImageEqualsToFile(path, exp)) {
+		if (FLT_EVAL_METHOD != 2 && !gdAssertImageEqualsToFile(path, exp)) {
 			gdTestErrorMsg("comparing rotated image to %s failed.\n", path);
 			error += 1;
 		}


code:
Fix a test failure with freetype 2.7:

https://github.com/libgd/libgd/commit/a5570d3ed30ff76c2a8bdd54f4ab1825acca0143

Patch copied from upstream source repository:

https://github.com/libgd/libgd/commit/a5570d3ed30ff76c2a8bdd54f4ab1825acca0143

From a5570d3ed30ff76c2a8bdd54f4ab1825acca0143 Mon Sep 17 00:00:00 2001
From: "Christoph M. Becker" <cmbecker69@gmx.de>
Date: Sun, 29 Jan 2017 17:07:50 +0100
Subject: [PATCH] Fix #302: Test suite fails with freetype 2.7

Actually, the test failures are not necessarily related to freetype
2.7, but rather are caused by subpixel hinting which is enabled by
default in freetype 2.7. Subpixel hinting is, however, already
available in freetype 2.5 and in versions having the "Infinality"
patch.

To get the expected results in all environments, we have to disable
subpixel hinting, what is easily done by setting a respective
environment variable.

See also:
* https://www.freetype.org/freetype2/docs/subpixel-hinting.html
* https://www.freetype.org/freetype2/docs/reference/ft2-tt_driver.html
---
 tests/freetype/bug00132.c                    | 3 +++
 tests/gdimagestringft/gdimagestringft_bbox.c | 3 +++
 2 files changed, 6 insertions(+)

diff --git a/tests/freetype/bug00132.c b/tests/freetype/bug00132.c
index 713dd2d..42ed5b1 100644
--- a/tests/freetype/bug00132.c
+++ b/tests/freetype/bug00132.c
@@ -11,6 +11,9 @@ int main()
 	char *path;
 	char *ret = NULL;

+	/* disable subpixel hinting */
+	putenv("FREETYPE_PROPERTIES=truetype:interpreter-version=35");
+
 	im = gdImageCreateTrueColor(50, 30);

 	if (!im) {
diff --git a/tests/gdimagestringft/gdimagestringft_bbox.c b/tests/gdimagestringft/gdimagestringft_bbox.c
index 0161ec8..1596a9e 100644
--- a/tests/gdimagestringft/gdimagestringft_bbox.c
+++ b/tests/gdimagestringft/gdimagestringft_bbox.c
@@ -38,6 +38,9 @@ int main()
 	int error = 0;
 	FILE *fp;

+	/* disable subpixel hinting */
+	putenv("FREETYPE_PROPERTIES=truetype:interpreter-version=35");
+
 	path = gdTestFilePath("freetype/DejaVuSans.ttf");
 	im = gdImageCreate(800, 800);
 	gdImageColorAllocate(im, 0xFF, 0xFF, 0xFF); /* allocate white for background color */


code:
Fix CVE-2018-14424:

https://gitlab.gnome.org/GNOME/gdm/issues/401
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-14424

Patch copied from upstream source repository:

https://gitlab.gnome.org/GNOME/gdm/commit/1ac1697b3b019f50729a6e992065959586e170da

From 1ac1697b3b019f50729a6e992065959586e170da Mon Sep 17 00:00:00 2001
From: Chris Coulson <chris.coulson@canonical.com>
Date: Thu, 19 Jul 2018 18:26:05 +0100
Subject: [PATCH] display-store: Pass the display object rather than the id in
 the removed signal

By the time GdmDisplayStore emits the "display-removed" signal, the display
is no longer in the store and gdm_display_store_lookup will not work in
signal handlers.

Change the "display-removed" parameter from the display id to the GdmDisplay
object, so that signal handers can perform any cleanup they need to do

CVE-2018-14424

Closes: https://gitlab.gnome.org/GNOME/gdm/issues/401
---
 daemon/gdm-display-store.c         | 11 +++--------
 daemon/gdm-display-store.h         |  2 +-
 daemon/gdm-local-display-factory.c | 13 +++----------
 daemon/gdm-manager.c               | 19 +++++++++----------
 daemon/gdm-manager.h               |  3 ++-
 5 files changed, 18 insertions(+), 30 deletions(-)

diff --git a/daemon/gdm-display-store.c b/daemon/gdm-display-store.c
index af76f519..fd24334e 100644
--- a/daemon/gdm-display-store.c
+++ b/daemon/gdm-display-store.c
@@ -76,15 +76,10 @@ stored_display_new (GdmDisplayStore *store,
 static void
 stored_display_free (StoredDisplay *stored_display)
 {
-        char *id;
-
-        gdm_display_get_id (stored_display->display, &id, NULL);
-
         g_signal_emit (G_OBJECT (stored_display->store),
                        signals[DISPLAY_REMOVED],
                        0,
-                       id);
-        g_free (id);
+                       stored_display->display);

         g_debug ("GdmDisplayStore: Unreffing display: %p",
                  stored_display->display);
@@ -281,9 +276,9 @@ gdm_display_store_class_init (GdmDisplayStoreClass *klass)
                               G_STRUCT_OFFSET (GdmDisplayStoreClass, display_removed),
                               NULL,
                               NULL,
-                              g_cclosure_marshal_VOID__STRING,
+                              g_cclosure_marshal_VOID__OBJECT,
                               G_TYPE_NONE,
-                              1, G_TYPE_STRING);
+                              1, G_TYPE_OBJECT);

         g_type_class_add_private (klass, sizeof (GdmDisplayStorePrivate));
 }
diff --git a/daemon/gdm-display-store.h b/daemon/gdm-display-store.h
index 28359933..0aff8ee2 100644
--- a/daemon/gdm-display-store.h
+++ b/daemon/gdm-display-store.h
@@ -49,7 +49,7 @@ typedef struct
         void          (* display_added)    (GdmDisplayStore *display_store,
                                             const char      *id);
         void          (* display_removed)  (GdmDisplayStore *display_store,
-                                            const char      *id);
+                                            GdmDisplay      *display);
 } GdmDisplayStoreClass;

 typedef enum
diff --git a/daemon/gdm-local-display-factory.c b/daemon/gdm-local-display-factory.c
index 5f1ae89e..39f3e30a 100644
--- a/daemon/gdm-local-display-factory.c
+++ b/daemon/gdm-local-display-factory.c
@@ -805,18 +805,11 @@ on_display_added (GdmDisplayStore        *display_store,

 static void
 on_display_removed (GdmDisplayStore        *display_store,
-                    const char             *id,
+                    GdmDisplay             *display,
                     GdmLocalDisplayFactory *factory)
 {
-        GdmDisplay *display;
-
-        display = gdm_display_store_lookup (display_store, id);
-
-        if (display != NULL) {
-                g_signal_handlers_disconnect_by_func (display, G_CALLBACK (on_display_status_changed), factory);
-                g_object_weak_unref (G_OBJECT (display), (GWeakNotify)on_display_disposed, factory);
-
-        }
+        g_signal_handlers_disconnect_by_func (display, G_CALLBACK (on_display_status_changed), factory);
+        g_object_weak_unref (G_OBJECT (display), (GWeakNotify)on_display_disposed, factory);
 }

 static gboolean
diff --git a/daemon/gdm-manager.c b/daemon/gdm-manager.c
index f17bd1a5..f6684a8b 100644
--- a/daemon/gdm-manager.c
+++ b/daemon/gdm-manager.c
@@ -1541,19 +1541,18 @@ on_display_status_changed (GdmDisplay *display,

 static void
 on_display_removed (GdmDisplayStore *display_store,
-                    const char      *id,
+                    GdmDisplay      *display,
                     GdmManager      *manager)
 {
-        GdmDisplay *display;
+        char    *id;

-        display = gdm_display_store_lookup (display_store, id);
-        if (display != NULL) {
-                g_dbus_object_manager_server_unexport (manager->priv->object_manager, id);
+        gdm_display_get_id (display, &id, NULL);
+        g_dbus_object_manager_server_unexport (manager->priv->object_manager, id);
+        g_free (id);

-                g_signal_handlers_disconnect_by_func (display, G_CALLBACK (on_display_status_changed), manager);
+        g_signal_handlers_disconnect_by_func (display, G_CALLBACK (on_display_status_changed), manager);

-                g_signal_emit (manager, signals[DISPLAY_REMOVED], 0, id);
-        }
+        g_signal_emit (manager, signals[DISPLAY_REMOVED], 0, display);
 }

 static void
@@ -2535,9 +2534,9 @@ gdm_manager_class_init (GdmManagerClass *klass)
                               G_STRUCT_OFFSET (GdmManagerClass, display_removed),
                               NULL,
                               NULL,
-                              g_cclosure_marshal_VOID__STRING,
+                              g_cclosure_marshal_VOID__OBJECT,
                               G_TYPE_NONE,
-                              1, G_TYPE_STRING);
+                              1, G_TYPE_OBJECT);

         g_object_class_install_property (object_class,
                                          PROP_XDMCP_ENABLED,
diff --git a/daemon/gdm-manager.h b/daemon/gdm-manager.h
index 41c68a7a..c8fb3f22 100644
--- a/daemon/gdm-manager.h
+++ b/daemon/gdm-manager.h
@@ -24,6 +24,7 @@

 #include <glib-object.h>

+#include "gdm-display.h"
 #include "gdm-manager-glue.h"

 G_BEGIN_DECLS
@@ -50,7 +51,7 @@ typedef struct
         void          (* display_added)    (GdmManager      *manager,
                                             const char      *id);
         void          (* display_removed)  (GdmManager      *manager,
-                                            const char      *id);
+                                            GdmDisplay      *display);
 } GdmManagerClass;

 typedef enum
--
2.17.1


code:
From da1ed24209121f7b0f03f360b1029d7125a38e70 Mon Sep 17 00:00:00 2001
From: Efraim Flashner <efraim@flashner.co.il>
Date: Tue, 4 Jul 2017 12:44:53 +0300
Subject: [PATCH] Add NO_INTEL_COMPAT flag to Makefile.

see also: https://github.com/xiangzhou/GEMMA/pull/47

---
 Makefile | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/Makefile b/Makefile
index 5bb8748..712b1ad 100644
--- a/Makefile
+++ b/Makefile
@@ -11,6 +11,7 @@
 SYS = LNX
 # Leave blank after "=" to disable; put "= 1" to enable
 WITH_LAPACK = 1
+NO_INTEL_COMPAT =
 FORCE_32BIT =
 FORCE_DYNAMIC =
 DIST_NAME = gemma-0.96
@@ -64,10 +65,13 @@ endif
   HDR += $(SRC_DIR)/lapack.h
 endif

-ifdef FORCE_32BIT
-  CPPFLAGS += -m32
-else
-  CPPFLAGS += -m64
+ifdef NO_INTEL_COMPAT
+  else
+  ifdef FORCE_32BIT
+    CPPFLAGS += -m32
+  else
+    CPPFLAGS += -m64
+  endif
 endif

 ifdef FORCE_DYNAMIC
--
2.13.2


code:
Allow the configuration file to be specified via an environment variable.

--- geoclue-2.1.10/src/gclue-config.c	2015-04-07 09:50:07.721074380 +0200
+++ geoclue-2.1.10/src/gclue-config.c	2015-04-07 10:27:26.613171960 +0200
@@ -235,6 +235,11 @@
 gclue_config_init (GClueConfig *config)
 {
         GError *error = NULL;
+	const char *config_file_path;
+
+	config_file_path = g_getenv ("GEOCLUE_CONFIG_FILE");
+	if (config_file_path == NULL)
+	  config_file_path = CONFIG_FILE_PATH;

         config->priv =
                 G_TYPE_INSTANCE_GET_PRIVATE (config,
@@ -242,7 +247,7 @@
                                             GClueConfigPrivate);
         config->priv->key_file = g_key_file_new ();
         g_key_file_load_from_file (config->priv->key_file,
-                                   CONFIG_FILE_PATH,
+                                   config_file_path,
                                    0,
                                    &error);
         if (error != NULL) {


code:
ghc runtime by default (otherwise depending on a "configure" option)
does memory allocation on their own by first mmapping a 1 TB range of
memory into the process and then parceling out chunks from it.

If one of the chunks is not needed, the kernel needs to be informed -
otherwise the system would quickly run out of available RAM.

ghc does that via madvise(2).

There are two options when doing this informing:

MADV_FREE - Means "I don't need this range or the data in it any more".
Kernel promises to fail later accesses to it.

MADV_DONTNEED - Means "I don't need this range right now - and I don't
need the data in it anymore". Kernel promises to make later accesses to
it succeed (if necessary by providing a new page initialized with zeroes).

MADV_FREE was introduced in Linux 4.5.
glibc 2.25 and later always define MADV_FREE.

Unpatched ghc 8.0.2 will use either MADV_FREE or MADV_DONTNEED, determined
at ghc compile time.  Which of them will actually succeed is determined
by the Linux kernel at run time.

This patch makes ghc try MADV_FREE.  If it doesn't work, it falls back to
MADV_DONTNEED.

The end result is that ghc programs free their memory with Linux < 4.5 again.

See https://git.haskell.org/ghc.git/commitdiff/6576bf83cdf4eac05eb88a24aa934a736c91e3da for more information.
--- a/rts/posix/OSMem.c
+++ b/rts/posix/OSMem.c
@@ -541,11 +541,24 @@ void osDecommitMemory(void *at, W_ size)

 #ifdef MADV_FREE
     // Try MADV_FREE first, FreeBSD has both and MADV_DONTNEED
-    // just swaps memory out
+    // just swaps memory out. Linux >= 4.5 has both DONTNEED and FREE; either
+    // will work as they both allow the system to free anonymous pages.
+    // It is important that we try both methods as the kernel which we were
+    // built on may differ from the kernel we are now running on.
     r = madvise(at, size, MADV_FREE);
-#else
-    r = madvise(at, size, MADV_DONTNEED);
+    if(r < 0) {
+        if (errno == EINVAL) {
+            // Perhaps the system doesn't support MADV_FREE; fall-through and
+            // try MADV_DONTNEED.
+        } else {
+            sysErrorBelch("unable to decommit memory");
+        }
+    } else {
+        return;
+    }
 #endif
+
+    r = madvise(at, size, MADV_DONTNEED);
     if(r < 0)
         sysErrorBelch("unable to decommit memory");
 }


code:
Don’t add linker flags via ‘response files’ since ld-wrapper
doesn’t handle them.
See https://github.com/NixOS/nixpkgs/commit/a421e7bd4a28c69bded8b17888325e31554f61a1
https://gcc.gnu.org/ml/gcc/2016-10/msg00151.html

diff --git a/compiler/main/SysTools.hs.orig b/compiler/main/SysTools.hs
index 1ab5b13..99270fc 100644
--- a/compiler/main/SysTools.hs.orig
+++ b/compiler/main/SysTools.hs
@@ -424,7 +424,7 @@ runCc dflags args =   do
       args1 = map Option (getOpts dflags opt_c)
       args2 = args0 ++ args1 ++ args
   mb_env <- getGccEnv args2
-  runSomethingResponseFile dflags cc_filter "C Compiler" p args2 mb_env
+  runSomethingFiltered dflags cc_filter "C Compiler" p args2 mb_env
  where
   -- discard some harmless warnings from gcc that we can't turn off
   cc_filter = unlines . doFilter . lines
@@ -945,7 +945,7 @@ runLink dflags args = do
       args1     = map Option (getOpts dflags opt_l)
       args2     = args0 ++ linkargs ++ args1 ++ args
   mb_env <- getGccEnv args2
-  runSomethingResponseFile dflags ld_filter "Linker" p args2 mb_env
+  runSomethingFiltered dflags ld_filter "Linker" p args2 mb_env
   where
     ld_filter = case (platformOS (targetPlatform dflags)) of
                   OSSolaris2 -> sunos_ld_filter


code:
This patch (inspired by Debian) allows ghc-haddock-library to use our
ghc-attoparsec package instead of using a bundled version.

--- a/haddock-library.cabal	2018-09-01 01:22:18.676855884 -0400
+++ b/haddock-library.cabal	2018-09-01 01:25:10.501150260 -0400
@@ -10,7 +10,6 @@
                       itself, see the ‘haddock’ package.
 license:              BSD3
 license-files:        LICENSE
-                      vendor/attoparsec-0.13.1.0/LICENSE
 maintainer:           Alex Biehl <alexbiehl@gmail.com>, Simon Hengel <sol@typeful.net>, Mateusz Kowalczyk <fuuzetsu@fuuzetsu.co.uk>
 homepage:             http://www.haskell.org/haddock/
 bug-reports:          https://github.com/haskell/haddock/issues
@@ -28,7 +27,6 @@
     , containers   >= 0.4.2.1 && < 0.6
     , transformers >= 0.3.0   && < 0.6

-  -- internal sub-lib
   build-depends:        attoparsec

   hs-source-dirs:       src
@@ -49,42 +47,6 @@
   if impl(ghc >= 8.0)
     ghc-options: -Wcompat -Wnoncanonical-monad-instances -Wnoncanonical-monadfail-instances

-library attoparsec
-  default-language:     Haskell2010
-
-  build-depends:
-      base         >= 4.5     && < 4.12
-    , bytestring   >= 0.9.2.1 && < 0.11
-    , deepseq      >= 1.3     && < 1.5
-
-  hs-source-dirs:       vendor/attoparsec-0.13.1.0
-
-  -- NB: haddock-library needs only small part of lib:attoparsec
-  --     internally, so we only bundle that subset here
-  exposed-modules:
-    Data.Attoparsec.ByteString
-    Data.Attoparsec.ByteString.Char8
-    Data.Attoparsec.Combinator
-
-  other-modules:
-    Data.Attoparsec
-    Data.Attoparsec.ByteString.Buffer
-    Data.Attoparsec.ByteString.FastSet
-    Data.Attoparsec.ByteString.Internal
-    Data.Attoparsec.Internal
-    Data.Attoparsec.Internal.Fhthagn
-    Data.Attoparsec.Internal.Types
-    Data.Attoparsec.Number
-
-  ghc-options:          -funbox-strict-fields -Wall -fwarn-tabs -O2
-
-  ghc-options: -Wall
-  if impl(ghc >= 8.0)
-    ghc-options: -Wcompat -Wnoncanonical-monad-instances -Wnoncanonical-monadfail-instances
-  else
-    build-depends: semigroups ^>= 0.18.3, fail ^>= 4.9.0.0
-
-
 test-suite spec
   type:             exitcode-stdio-1.0
   default-language: Haskell2010
@@ -115,11 +77,10 @@
     , hspec         ^>= 2.4.4
     , QuickCheck    ^>= 2.11

-  -- internal sub-lib
   build-depends: attoparsec

   -- Versions for the dependencies below are transitively pinned by
-  -- dependency on haddock-library:lib:attoparsec
+  -- dependency on attoparsec
   build-depends:
       base
     , bytestring
@@ -146,7 +107,7 @@
     haddock-library

   -- Versions for the dependencies below are transitively pinned by
-  -- dependency on haddock-library:lib:attoparsec
+  -- dependency on attoparsec
   build-depends:
       base


code:
Ghostscript 9.24 was released with an incomplete fix for CVE-2018-16509:
https://nvd.nist.gov/vuln/detail/CVE-2018-16509
https://bugs.chromium.org/p/project-zero/issues/detail?id=1640#c19
https://bugs.ghostscript.com/show_bug.cgi?id=699718

The reproducers no longer work after applying these commits:

https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=5812b1b78fc4d36fdc293b7859de69241140d590
https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=e914f1da46e33decc534486598dc3eadf69e6efb
https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=3e5d316b72e3965b7968bb1d96baa137cd063ac6
https://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=643b24dbd002fb9c131313253c307cf3951b3d47

This patch is a "squashed" version of those.

diff --git a/Resource/Init/gs_setpd.ps b/Resource/Init/gs_setpd.ps
index bba3c8c0e..8fa7c51df 100644
--- a/Resource/Init/gs_setpd.ps
+++ b/Resource/Init/gs_setpd.ps
@@ -95,27 +95,41 @@ level2dict begin
  {	% Since setpagedevice doesn't create new device objects,
         % we must (carefully) reinstall the old parameters in
         % the same device.
-   .currentpagedevice pop //null currentdevice //null .trysetparams
+   .currentpagedevice pop //null currentdevice //null
+   { .trysetparams } .internalstopped
+   {
+     //null
+   } if
    dup type /booleantype eq
     { pop pop }
-    {		% This should never happen!
+    {
       SETPDDEBUG { (Error in .trysetparams!) = pstack flush } if
-      cleartomark pop pop pop
+      {cleartomark pop pop pop} .internalstopped pop
+      % if resetting the entire device state failed, at least put back the
+      % security related key
+      currentdevice //null //false mark /.LockSafetyParams
+      currentpagedevice /.LockSafetyParams .knownget not
+      {systemdict /SAFER .knownget not {//false} } if
+      .putdeviceparamsonly
       /.installpagedevice cvx /rangecheck signalerror
     }
    ifelse pop pop
         % A careful reading of the Red Book reveals that an erasepage
         % should occur, but *not* an initgraphics.
    erasepage .beginpage
- } bind def
+ } bind executeonly def

 /.uninstallpagedevice
- { 2 .endpage { .currentnumcopies //false .outputpage } if
+ {
+   {2 .endpage { .currentnumcopies //false .outputpage } if} .internalstopped pop
    nulldevice
  } bind def

 (%grestorepagedevice) cvn
- { .uninstallpagedevice grestore .installpagedevice
+ {
+ .uninstallpagedevice
+ grestore
+ .installpagedevice
  } bind def

 (%grestoreallpagedevice) cvn
diff --git a/psi/zdevice2.c b/psi/zdevice2.c
index 0c7080d57..159a0c0d9 100644
--- a/psi/zdevice2.c
+++ b/psi/zdevice2.c
@@ -251,8 +251,8 @@ z2currentgstate(i_ctx_t *i_ctx_p)
 /* ------ Wrappers for operators that reset the graphics state. ------ */

 /* Check whether we need to call out to restore the page device. */
-static bool
-restore_page_device(const gs_gstate * pgs_old, const gs_gstate * pgs_new)
+static int
+restore_page_device(i_ctx_t *i_ctx_p, const gs_gstate * pgs_old, const gs_gstate * pgs_new)
 {
     gx_device *dev_old = gs_currentdevice(pgs_old);
     gx_device *dev_new;
@@ -260,9 +260,10 @@ restore_page_device(const gs_gstate * pgs_old, const gs_gstate * pgs_new)
     gx_device *dev_t2;
     bool samepagedevice = obj_eq(dev_old->memory, &gs_int_gstate(pgs_old)->pagedevice,
         &gs_int_gstate(pgs_new)->pagedevice);
+    bool LockSafetyParams = dev_old->LockSafetyParams;

     if ((dev_t1 = (*dev_proc(dev_old, get_page_device)) (dev_old)) == 0)
-        return false;
+        return 0;
     /* If we are going to putdeviceparams in a callout, we need to */
     /* unlock temporarily.  The device will be re-locked as needed */
     /* by putdeviceparams from the pgs_old->pagedevice dict state. */
@@ -271,23 +272,51 @@ restore_page_device(const gs_gstate * pgs_old, const gs_gstate * pgs_new)
     dev_new = gs_currentdevice(pgs_new);
     if (dev_old != dev_new) {
         if ((dev_t2 = (*dev_proc(dev_new, get_page_device)) (dev_new)) == 0)
-            return false;
-        if (dev_t1 != dev_t2)
-            return true;
+            samepagedevice = true;
+        else if (dev_t1 != dev_t2)
+            samepagedevice = false;
+    }
+
+    if (LockSafetyParams && !samepagedevice) {
+        const int required_ops = 512;
+        const int required_es = 32;
+
+        /* The %grestorepagedevice must complete: the biggest danger
+           is operand stack overflow. As we use get/putdeviceparams
+           that means pushing all the device params onto the stack,
+           pdfwrite having by far the largest number of parameters
+           at (currently) 212 key/value pairs - thus needing (currently)
+           424 entries on the op stack. Allowing for working stack
+           space, and safety margin.....
+         */
+        if (required_ops + ref_stack_count(&o_stack) >= ref_stack_max_count(&o_stack)) {
+           gs_currentdevice(pgs_old)->LockSafetyParams = LockSafetyParams;
+           return_error(gs_error_stackoverflow);
+        }
+        /* We also want enough exec stack space - 32 is an overestimate of
+           what we need to complete the Postscript call out.
+         */
+        if (required_es + ref_stack_count(&e_stack) >= ref_stack_max_count(&e_stack)) {
+           gs_currentdevice(pgs_old)->LockSafetyParams = LockSafetyParams;
+           return_error(gs_error_execstackoverflow);
+        }
     }
     /*
      * The current implementation of setpagedevice just sets new
      * parameters in the same device object, so we have to check
      * whether the page device dictionaries are the same.
      */
-    return !samepagedevice;
+    return samepagedevice ? 0 : 1;
 }

 /* - grestore - */
 static int
 z2grestore(i_ctx_t *i_ctx_p)
 {
-    if (!restore_page_device(igs, gs_gstate_saved(igs)))
+    int code = restore_page_device(i_ctx_p, igs, gs_gstate_saved(igs));
+    if (code < 0) return code;
+
+    if (code == 0)
         return gs_grestore(igs);
     return push_callout(i_ctx_p, "%grestorepagedevice");
 }
@@ -297,7 +326,9 @@ static int
 z2grestoreall(i_ctx_t *i_ctx_p)
 {
     for (;;) {
-        if (!restore_page_device(igs, gs_gstate_saved(igs))) {
+        int code = restore_page_device(i_ctx_p, igs, gs_gstate_saved(igs));
+        if (code < 0) return code;
+        if (code == 0) {
             bool done = !gs_gstate_saved(gs_gstate_saved(igs));

             gs_grestore(igs);
@@ -328,11 +359,15 @@ z2restore(i_ctx_t *i_ctx_p)
     if (code < 0) return code;

     while (gs_gstate_saved(gs_gstate_saved(igs))) {
-        if (restore_page_device(igs, gs_gstate_saved(igs)))
+        code = restore_page_device(i_ctx_p, igs, gs_gstate_saved(igs));
+        if (code < 0) return code;
+        if (code > 0)
             return push_callout(i_ctx_p, "%restore1pagedevice");
         gs_grestore(igs);
     }
-    if (restore_page_device(igs, gs_gstate_saved(igs)))
+    code = restore_page_device(i_ctx_p, igs, gs_gstate_saved(igs));
+    if (code < 0) return code;
+    if (code > 0)
         return push_callout(i_ctx_p, "%restorepagedevice");

     code = dorestore(i_ctx_p, asave);
@@ -355,9 +390,12 @@ static int
 z2setgstate(i_ctx_t *i_ctx_p)
 {
     os_ptr op = osp;
+    int code;

     check_stype(*op, st_igstate_obj);
-    if (!restore_page_device(igs, igstate_ptr(op)))
+    code = restore_page_device(i_ctx_p, igs, igstate_ptr(op));
+    if (code < 0) return code;
+    if (code == 0)
         return zsetgstate(i_ctx_p);
     return push_callout(i_ctx_p, "%setgstatepagedevice");
 }


code:
Additional security fix that missed 9.24.

Taken from upstream:
http://git.ghostscript.com/?p=ghostpdl.git;a=commitdiff;h=fb713b3818b52d8a6cf62c951eba2e1795ff9624

From fb713b3818b52d8a6cf62c951eba2e1795ff9624 Mon Sep 17 00:00:00 2001
From: Chris Liddell <chris.liddell@artifex.com>
Date: Thu, 6 Sep 2018 09:16:22 +0100
Subject: [PATCH] Bug 699708 (part 1): 'Hide' non-replaceable error handlers
 for SAFER

We already had a 'private' dictionary for non-standard errors: gserrordict.

This now includes all the default error handlers, the dictionary is made
noaccess and all the prodedures are bound and executeonly.

When running with -dSAFER, in the event of a Postscript error, instead of
pulling the handler from errordict, we'll pull it from gserrordict - thus
malicious input cannot trigger problems by the use of custom error handlers.

errordict remains open and writeable, so files such as the Quality Logic tests
that install their own handlers will still 'work', with the exception that the
custom error handlers will not be called.

This is a 'first pass', 'sledgehammer' approach: a nice addition would to allow
an integrator to specify a list of errors that are not to be replaced (for
example, embedded applications would probably want to ensure that VMerror is
always handled as they intend).
---
 Resource/Init/gs_init.ps | 29 ++++++++++++++++++-----------
 psi/interp.c             | 30 +++++++++++++++++++++---------
 2 files changed, 39 insertions(+), 20 deletions(-)

diff --git a/Resource/Init/gs_init.ps b/Resource/Init/gs_init.ps
index 071c39205..bc8b7951c 100644
--- a/Resource/Init/gs_init.ps
+++ b/Resource/Init/gs_init.ps
@@ -881,7 +881,7 @@ userdict /.currentresourcefile //null put
        { not exch pop exit } { pop } ifelse
     }
    for exch pop .quit
- } bind def
+ } bind executeonly def
 /.errorhandler		% <command> <errorname> .errorhandler -
   {		% Detect an internal 'stopped'.
     1 .instopped { //null eq { pop pop stop } if } if
@@ -926,7 +926,7 @@ userdict /.currentresourcefile //null put
     $error /globalmode get $error /.nosetlocal get and .setglobal
     $error /.inerror //false put
     stop
-  } bind def
+  } bind executeonly def
 % Define the standard handleerror.  We break out the printing procedure
 % (.printerror) so that it can be extended for binary output
 % if the Level 2 facilities are present.
@@ -976,7 +976,7 @@ userdict /.currentresourcefile //null put
      ifelse	% newerror
      end
      flush
-    } bind def
+    } bind executeonly def
   /.printerror_long			% long error printout,
                                         % $error is on the dict stack
    {	% Push the (anonymous) stack printing procedure.
@@ -1053,14 +1053,14 @@ userdict /.currentresourcefile //null put
         { (Current file position is ) print position = }
        if

-   } bind def
+   } bind executeonly def
 % Define a procedure for clearing the error indication.
 /.clearerror
  { $error /newerror //false put
    $error /errorname //null put
    $error /errorinfo //null put
    0 .setoserrno
- } bind def
+ } bind executeonly def

 % Define $error.  This must be in local VM.
 .currentglobal //false .setglobal
@@ -1086,11 +1086,15 @@ end
 /errordict ErrorNames length 3 add dict
 .forcedef		% errordict is local, systemdict is global
 .setglobal		% back to global VM
-% For greater Adobe compatibility, we put all non-standard errors in a
-%   separate dictionary, gserrordict.  It does not need to be in local VM,
-%   because PostScript programs do not access it.
+%  gserrordict contains all the default error handling methods, but unlike
+%  errordict it is noaccess after creation (also it is in global VM).
+%  When running 'SAFER', we'll ignore the contents of errordict, which
+%  may have been tampered with by the running job, and always use gserrordict
+%  gserrordict also contains any non-standard errors, for better compatibility
+%  with Adobe.
+%
 %   NOTE: the name gserrordict is known to the interpreter.
-/gserrordict 5 dict def
+/gserrordict ErrorNames length 3 add dict def
 % Register an error in errordict.  We make this a procedure because we only
 % register the Level 1 errors here: the rest are registered by "feature"
 % files.  However, ErrorNames contains all of the error names regardless of
@@ -1119,8 +1123,11 @@ errordict begin
  } bind def
 end		% errordict

-% Put non-standard errors in gserrordict.
-gserrordict /unknownerror errordict /unknownerror get put
+% Put all the default handlers in gserrordict
+gserrordict
+errordict {2 index 3 1 roll put} forall
+noaccess pop
+% remove the non-standard errors from errordict
 errordict /unknownerror .undef
 % Define a stable private copy of handleerror that we will always use under
 % JOBSERVER mode.
diff --git a/psi/interp.c b/psi/interp.c
index c27b70dca..d41a9d3f5 100644
--- a/psi/interp.c
+++ b/psi/interp.c
@@ -661,16 +661,28 @@ again:
         return code;
     if (gs_errorname(i_ctx_p, code, &error_name) < 0)
         return code;            /* out-of-range error code! */
-    /*
-     * For greater Adobe compatibility, only the standard PostScript errors
-     * are defined in errordict; the rest are in gserrordict.
+
+    /*  If LockFilePermissions is true, we only refer to gserrordict, which
+     *  is not accessible to Postcript jobs
      */
-    if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
-        (dict_find(perrordict, &error_name, &epref) <= 0 &&
-         (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
-          dict_find(perrordict, &error_name, &epref) <= 0))
-        )
-        return code;            /* error name not in errordict??? */
+    if (i_ctx_p->LockFilePermissions) {
+        if (((dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
+              dict_find(perrordict, &error_name, &epref) <= 0))
+            )
+            return code;            /* error name not in errordict??? */
+    }
+    else {
+        /*
+         * For greater Adobe compatibility, only the standard PostScript errors
+         * are defined in errordict; the rest are in gserrordict.
+         */
+        if (dict_find_string(systemdict, "errordict", &perrordict) <= 0 ||
+            (dict_find(perrordict, &error_name, &epref) <= 0 &&
+             (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 ||
+              dict_find(perrordict, &error_name, &epref) <= 0))
+            )
+            return code;            /* error name not in errordict??? */
+    }
     doref = *epref;
     epref = &doref;
     /* Push the error object on the operand stack if appropriate. */
--
2.18.0


code:
This patch makes emission of /CreationDate and /ModDate headers optional.

If the environment variable GS_GENERATE_UUIDS is set to "0" or "no", it will
not write out the "/ID" field (if that's permissible).

Upstream does not want to do this.

See: https://bugs.ghostscript.com/show_bug.cgi?id=698208
diff --git a/orig/gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c b/bb/gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c
index 0fb067e..b342e2c 100644
--- orig/gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c
+++ gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c
@@ -305,6 +305,9 @@ pdf_initialize_ids(gx_device_pdf * pdev)
      * date and time, rather than (for example) %%CreationDate from the
      * PostScript file.  We think this is wrong, but we do the same.
      */
+    if (!getenv("GS_GENERATE_UUIDS") ||
+        (strcasecmp(getenv("GS_GENERATE_UUIDS"), "0") != 0 &&
+         strcasecmp(getenv("GS_GENERATE_UUIDS"), "no") != 0))
     {
         struct tm tms;
         time_t t;


code:
This patch makes the "/ID" field optional.

If the environment variable GS_GENERATE_UUIDS is set to "0" or "no", it will
not write out the "/ID" field (if that's permissible).

Upstream does not want to do this.

See: https://bugs.ghostscript.com/show_bug.cgi?id=698208
diff -ur orig/gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c
--- orig/gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c	2017-07-09 23:30:28.960479189 +0200
+++ gnu-ghostscript-9.14.0/devices/vector/gdevpdf.c	2017-07-09 23:34:34.306524488 +0200
@@ -1785,8 +1785,11 @@
      * +1 for the linearisation dict and +1 for the primary hint stream.
      */
     linear_params->FirsttrailerOffset = gp_ftell_64(linear_params->Lin_File.file);
-    gs_sprintf(LDict, "\ntrailer\n<</Size %ld/Info %d 0 R/Root %d 0 R/ID[%s%s]/Prev %d>>\nstartxref\r\n0\n%%%%EOF\n        \n",
-        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber, fileID, fileID, 0);
+    gs_sprintf(LDict, "\ntrailer\n<</Size %ld/Info %d 0 R/Root %d 0 R",
+        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber);
+    if (pdev->OwnerPassword.size > 0 || !(!getenv("GS_GENERATE_UUIDS") || (strcasecmp(getenv("GS_GENERATE_UUIDS"), "0") != 0 && strcasecmp(getenv("GS_GENERATE_UUIDS"), "no") != 0))) /* ID is mandatory when encrypting */
+        gs_sprintf(LDict, "/ID[%s%s]", fileID, fileID);
+    gs_sprintf(LDict, "/Prev %d>>\nstartxref\r\n0\n%%%%EOF\n        \n", 0);
     fwrite(LDict, strlen(LDict), 1, linear_params->Lin_File.file);

     /* Write document catalog (Part 4) */
@@ -2321,8 +2324,11 @@
     if (code != 0)
         return_error(gs_error_ioerror);

-    gs_sprintf(LDict, "\ntrailer\n<</Size %ld/Info %d 0 R/Root %d 0 R/ID[%s%s]/Prev %"PRId64">>\nstartxref\r\n0\n%%%%EOF\n",
-        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber, fileID, fileID, mainxref);
+    gs_sprintf(LDict, "\ntrailer\n<</Size %ld/Info %d 0 R/Root %d 0 R",
+        linear_params->LastResource + 3, pdev->ResourceUsage[linear_params->Info_id].NewObjectNumber, pdev->ResourceUsage[linear_params->Catalog_id].NewObjectNumber);
+    if (pdev->OwnerPassword.size > 0 || !(!getenv("GS_GENERATE_UUIDS") || (strcasecmp(getenv("GS_GENERATE_UUIDS"), "0") != 0 || strcasecmp(getenv("GS_GENERATE_UUIDS"), "no") != 0))) /* ID is mandatory when encrypting */
+        gs_sprintf(LDict, "/ID[%s%s]", fileID, fileID);
+    gs_sprintf(LDict, "/Prev %"PRId64">>\nstartxref\r\n0\n%%%%EOF\n", mainxref);
     fwrite(LDict, strlen(LDict), 1, linear_params->sfile);

     code = gp_fseek_64(linear_params->sfile, pdev->ResourceUsage[HintStreamObj].LinearisedOffset, SEEK_SET);
@@ -3016,10 +3022,12 @@
             stream_puts(s, "trailer\n");
             pprintld3(s, "<< /Size %ld /Root %ld 0 R /Info %ld 0 R\n",
                   pdev->next_id, Catalog_id, Info_id);
-            stream_puts(s, "/ID [");
-            psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
-            psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
-            stream_puts(s, "]\n");
+            if (pdev->OwnerPassword.size > 0 || !(!getenv("GS_GENERATE_UUIDS") || (strcasecmp(getenv("GS_GENERATE_UUIDS"), "0") != 0 || strcasecmp(getenv("GS_GENERATE_UUIDS"), "no") != 0))) { /* ID is mandatory when encrypting */
+                stream_puts(s, "/ID [");
+                psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
+                psdf_write_string(pdev->strm, pdev->fileID, sizeof(pdev->fileID), 0);
+                stream_puts(s, "]\n");
+            }
             if (pdev->OwnerPassword.size > 0) {
                 pprintld1(s, "/Encrypt %ld 0 R ", Encrypt_id);
             }


code:
This patch makes the UUIDs in the XMP header optional, depending on the
setting of the environment variable GS_GENERATE_UUIDS.

If the environment variable GS_GENERATE_UUIDS is set to "0" or "no", it will
not write out the Document UUID field and also will write the Instance ID
field value as "".

Upstream does not want to do this.

See: https://bugs.ghostscript.com/show_bug.cgi?id=698208
diff -ur orig/gnu-ghostscript-9.14.0/devices/vector/gdevpdfe.c aa/gnu-ghostscript-9.14.0/devices/vector/gdevpdfe.c
--- orig/gnu-ghostscript-9.14.0/devices/vector/gdevpdfe.c	2017-07-09 23:30:28.960479189 +0200
+++ gnu-ghostscript-9.14.0/devices/vector/gdevpdfe.c	2017-07-10 01:04:12.252478276 +0200
@@ -617,7 +617,7 @@
         return code;

     /* PDF/A XMP reference recommends setting UUID to empty. If not empty must be a URI */
-    if (pdev->PDFA != 0)
+    if (pdev->PDFA != 0 || (getenv("GS_GENERATE_UUIDS") && (strcasecmp(getenv("GS_GENERATE_UUIDS"), "0") == 0 || strcasecmp(getenv("GS_GENERATE_UUIDS"), "no") == 0)))
         instance_uuid[0] = 0x00;

     cre_date_time_len = pdf_get_docinfo_item(pdev, "/CreationDate", cre_date_time, sizeof(cre_date_time));
@@ -719,15 +719,18 @@
             pdf_xml_tag_close(s, "rdf:Description");
             pdf_xml_newline(s);

-            pdf_xml_tag_open_beg(s, "rdf:Description");
-            pdf_xml_attribute_name(s, "rdf:about");
-            pdf_xml_attribute_value(s, instance_uuid);
-            pdf_xml_attribute_name(s, "xmlns:xapMM");
-            pdf_xml_attribute_value(s, "http://ns.adobe.com/xap/1.0/mm/");
-            pdf_xml_attribute_name(s, "xapMM:DocumentID");
-            pdf_xml_attribute_value(s, document_uuid);
-            pdf_xml_tag_end_empty(s);
-            pdf_xml_newline(s);
+            if (!getenv("GS_GENERATE_UUIDS") || (strcasecmp(getenv("GS_GENERATE_UUIDS"), "0") != 0 && strcasecmp(getenv("GS_GENERATE_UUIDS"), "no") != 0))
+            {
+                pdf_xml_tag_open_beg(s, "rdf:Description");
+                pdf_xml_attribute_name(s, "rdf:about");
+                pdf_xml_attribute_value(s, instance_uuid);
+                pdf_xml_attribute_name(s, "xmlns:xapMM");
+                pdf_xml_attribute_value(s, "http://ns.adobe.com/xap/1.0/mm/");
+                pdf_xml_attribute_name(s, "xapMM:DocumentID");
+                pdf_xml_attribute_value(s, document_uuid);
+                pdf_xml_tag_end_empty(s);
+                pdf_xml_newline(s);
+            }

             pdf_xml_tag_open_beg(s, "rdf:Description");
             pdf_xml_attribute_name(s, "rdf:about");


code:
diff --git a/base/unix-dll.mak b/base/unix-dll.mak
index 9d57a99..36ef1ff 100644
--- a/base/unix-dll.mak
+++ b/base/unix-dll.mak
@@ -171,11 +171,11 @@ gpdl-so-links-subtarget: $(GPDL_SO) $(UNIX_DLL_MAK) $(MAKEDIRS)
 # Build the small Ghostscript loaders, with Gtk+ and without
 $(GSSOC_XE): gs-so-links-subtarget $(PSSRC)$(SOC_LOADER) $(UNIX_DLL_MAK) $(MAKEDIRS)
 	$(GLCC) -g -o $(GSSOC_XE) $(PSSRC)dxmainc.c \
-	-L$(BINDIR) -l$(GS_SO_BASE)
+	-L$(BINDIR) -l$(GS_SO_BASE) -Wl,-rpath=$(libdir)

 $(GSSOX_XE): gs-so-links-subtarget $(PSSRC)$(SOC_LOADER) $(UNIX_DLL_MAK) $(MAKEDIRS)
 	$(GLCC) -g $(SOC_CFLAGS) -o $(GSSOX_XE) $(PSSRC)$(SOC_LOADER) \
-	-L$(BINDIR) -l$(GS_SO_BASE) $(SOC_LIBS)
+	-L$(BINDIR) -l$(GS_SO_BASE) $(SOC_LIBS) -Wl,-rpath=$(libdir)

 $(PCLSOC_XE): gpcl6-so-links-subtarget $(PLSRC)$(REALMAIN_SRC).c $(UNIX_DLL_MAK) $(MAKEDIRS)
 	$(GLCC) -g -o $(PCLSOC_XE) $(PLSRC)$(REALMAIN_SRC).c -L$(BINDIR) -l$(PCL_SO_BASE)


code:
Move the declaration from gif_lib.h to gif_lib_private.h to solve
conflicts when some .c-file #includes both stdlib.h and gif_lib.h.
See also https://sourceforge.net/p/giflib/bugs/110/

diff -ur giflib-5.1.4.orig/lib/dgif_lib.c giflib-5.1.4/lib/dgif_lib.c
--- giflib-5.1.4.orig/lib/dgif_lib.c	2018-02-28 20:31:02.294682673 +0100
+++ giflib-5.1.4/lib/dgif_lib.c	2018-02-28 22:38:11.659126414 +0100
@@ -396,7 +396,7 @@

     if (GifFile->SavedImages) {
         SavedImage* new_saved_images =
-            (SavedImage *)reallocarray(GifFile->SavedImages,
+            (SavedImage *)giflib_private_reallocarray(GifFile->SavedImages,
                             (GifFile->ImageCount + 1), sizeof(SavedImage));
         if (new_saved_images == NULL) {
             GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
@@ -1108,7 +1108,7 @@
               if (ImageSize > (SIZE_MAX / sizeof(GifPixelType))) {
                   return GIF_ERROR;
               }
-              sp->RasterBits = (unsigned char *)reallocarray(NULL, ImageSize,
+              sp->RasterBits = (unsigned char *)giflib_private_reallocarray(NULL, ImageSize,
                       sizeof(GifPixelType));

               if (sp->RasterBits == NULL) {
diff -ur giflib-5.1.4.orig/lib/gifalloc.c giflib-5.1.4/lib/gifalloc.c
--- giflib-5.1.4.orig/lib/gifalloc.c	2018-02-28 20:31:02.294682673 +0100
+++ giflib-5.1.4/lib/gifalloc.c	2018-02-28 22:38:11.657126423 +0100
@@ -8,7 +8,7 @@
 #include <stdio.h>
 #include <string.h>

-#include "gif_lib.h"
+#include "gif_lib_private.h"

 #define MAX(x, y)    (((x) > (y)) ? (x) : (y))

@@ -188,7 +188,7 @@

         /* perhaps we can shrink the map? */
         if (RoundUpTo < ColorUnion->ColorCount) {
-            GifColorType *new_map = (GifColorType *)reallocarray(Map,
+            GifColorType *new_map = (GifColorType *)giflib_private_reallocarray(Map,
                                  RoundUpTo, sizeof(GifColorType));
             if( new_map == NULL ) {
                 GifFreeMapObject(ColorUnion);
@@ -232,7 +232,7 @@
     if (*ExtensionBlocks == NULL)
         *ExtensionBlocks=(ExtensionBlock *)malloc(sizeof(ExtensionBlock));
     else {
-        ExtensionBlock* ep_new = (ExtensionBlock *)reallocarray
+        ExtensionBlock* ep_new = (ExtensionBlock *)giflib_private_reallocarray
 				 (*ExtensionBlocks, (*ExtensionBlockCount + 1),
                                       sizeof(ExtensionBlock));
         if( ep_new == NULL )
@@ -325,7 +325,7 @@
     if (GifFile->SavedImages == NULL)
         GifFile->SavedImages = (SavedImage *)malloc(sizeof(SavedImage));
     else
-        GifFile->SavedImages = (SavedImage *)reallocarray(GifFile->SavedImages,
+        GifFile->SavedImages = (SavedImage *)giflib_private_reallocarray(GifFile->SavedImages,
                                (GifFile->ImageCount + 1), sizeof(SavedImage));

     if (GifFile->SavedImages == NULL)
@@ -355,7 +355,7 @@
             }

             /* next, the raster */
-            sp->RasterBits = (unsigned char *)reallocarray(NULL,
+            sp->RasterBits = (unsigned char *)giflib_private_reallocarray(NULL,
                                                   (CopyFrom->ImageDesc.Height *
                                                   CopyFrom->ImageDesc.Width),
 						  sizeof(GifPixelType));
@@ -369,7 +369,7 @@

             /* finally, the extension blocks */
             if (sp->ExtensionBlocks != NULL) {
-                sp->ExtensionBlocks = (ExtensionBlock *)reallocarray(NULL,
+                sp->ExtensionBlocks = (ExtensionBlock *)giflib_private_reallocarray(NULL,
                                       CopyFrom->ExtensionBlockCount,
 				      sizeof(ExtensionBlock));
                 if (sp->ExtensionBlocks == NULL) {
diff -ur giflib-5.1.4.orig/lib/gif_lib.h giflib-5.1.4/lib/gif_lib.h
--- giflib-5.1.4.orig/lib/gif_lib.h	2018-02-28 20:31:02.294682673 +0100
+++ giflib-5.1.4/lib/gif_lib.h	2018-02-28 20:31:43.135716712 +0100
@@ -244,9 +244,6 @@
                                      GifPixelType ColorTransIn2[]);
 extern int GifBitSize(int n);

-extern void *
-reallocarray(void *optr, size_t nmemb, size_t size);
-
 /******************************************************************************
  Support for the in-core structures allocation (slurp mode).
 ******************************************************************************/
diff -ur giflib-5.1.4.orig/lib/gif_lib_private.h giflib-5.1.4/lib/gif_lib_private.h
--- giflib-5.1.4.orig/lib/gif_lib_private.h	2018-02-28 20:31:02.294682673 +0100
+++ giflib-5.1.4/lib/gif_lib_private.h	2018-02-28 22:38:11.657126423 +0100
@@ -54,6 +54,9 @@
     bool gif89;
 } GifFilePrivateType;

+extern void *
+giflib_private_reallocarray(void *optr, size_t nmemb, size_t size);
+
 #endif /* _GIF_LIB_PRIVATE_H */

 /* end */
diff -ur giflib-5.1.4.orig/lib/openbsd-reallocarray.c giflib-5.1.4/lib/openbsd-reallocarray.c
--- giflib-5.1.4.orig/lib/openbsd-reallocarray.c	2018-02-28 20:31:02.295682659 +0100
+++ giflib-5.1.4/lib/openbsd-reallocarray.c	2018-02-28 22:38:11.656126428 +0100
@@ -27,7 +27,7 @@
 #define MUL_NO_OVERFLOW	((size_t)1 << (sizeof(size_t) * 4))

 void *
-reallocarray(void *optr, size_t nmemb, size_t size)
+giflib_private_reallocarray(void *optr, size_t nmemb, size_t size)
 {
 	if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
 	    nmemb > 0 && SIZE_MAX / nmemb < size) {


code:
From b010e41346d418220582c20ab8d7f3971e4fb78a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=AE=8B=E6=96=87=E6=AD=A6?= <iyzsong@gmail.com>
Date: Fri, 14 Aug 2015 17:28:36 +0800
Subject: [PATCH] gnutls: Allow overriding the anchor file location by
 'SSL_CERT_FILE'

---
 tls/gnutls/gtlsbackend-gnutls.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/tls/gnutls/gtlsbackend-gnutls.c b/tls/gnutls/gtlsbackend-gnutls.c
index 55ec1a5..217d3c8 100644
--- a/tls/gnutls/gtlsbackend-gnutls.c
+++ b/tls/gnutls/gtlsbackend-gnutls.c
@@ -101,8 +101,10 @@ g_tls_backend_gnutls_real_create_database (GTlsBackendGnutls  *self,
                                            GError            **error)
 {
   const gchar *anchor_file = NULL;
+  anchor_file = g_getenv ("SSL_CERT_FILE");
 #ifdef GTLS_SYSTEM_CA_FILE
-  anchor_file = GTLS_SYSTEM_CA_FILE;
+  if (!anchor_file)
+    anchor_file = GTLS_SYSTEM_CA_FILE;
 #endif
   return g_tls_file_database_new (anchor_file, error);
 }
--
2.4.3


code:
* On i686 floating-point roundoff errors could sometimes cause this check to
  fail depending on the elapsed microseconds.  Improve rounding by adding a
  fractional bit.

--- glib-2.40.0/glib/tests/timer.c	2014-03-05 08:05:42.000000000 -0600
+++ glib-2.40.0/glib/tests/timer.c	2014-07-10 16:33:12.746862822 -0500
@@ -35,7 +35,7 @@
   elapsed = g_timer_elapsed (timer, &micros);

   g_assert_cmpfloat (elapsed, <, 1.0);
-  g_assert_cmpuint (micros, ==, ((guint64)(elapsed * 1e6)) % 1000000);
+  g_assert_cmpuint (micros, ==, ((guint64)(elapsed * 1e6 + 0.5)) % 1000000);

   g_timer_destroy (timer);
 }


code:
These commits are cherry-picked from the "release/2.27/master" branch.

https://sourceware.org/git/?p=glibc.git;a=shortlog;h=refs/heads/release/2.27/master

Currently, we have the following (with NEWS and ChangeLog entries omitted).

56170e064e2b21ce204f0817733e92f1730541ea
516fa6080481a1433c173320b1c1432868e1e38a
f36553bf6a4f69070f99badbdab5802b43e6e211
7c6304182b9f422b782ace1cdd3efbde056aec36
78a90c2f74a2012dd3eff302189e47ff6779a757
1e52d8e65a58c49a48549053a1b89c06240e0c6c
55ad82e45c313454de657931898e974a7a036cad

From 56170e064e2b21ce204f0817733e92f1730541ea Mon Sep 17 00:00:00 2001
From: Igor Gnatenko <ignatenko@redhat.com>
Date: Wed, 7 Feb 2018 13:53:10 +0100
Subject: [PATCH] Linux: use reserved name __key in pkey_get [BZ #22797]

_key is not reserved name and we should avoid using that. It seems that
it was simple typo when pkey_* was implemented.

(cherry picked from commit 388ff7bd0d57d7061fdd39a2f26f65687e8058da)

diff --git a/sysdeps/unix/sysv/linux/bits/mman-shared.h b/sysdeps/unix/sysv/linux/bits/mman-shared.h
index 7715e680ca..d15ba95c9d 100644
--- a/sysdeps/unix/sysv/linux/bits/mman-shared.h
+++ b/sysdeps/unix/sysv/linux/bits/mman-shared.h
@@ -61,7 +61,7 @@ int pkey_set (int __key, unsigned int __access_rights) __THROW;

 /* Return the access rights for the current thread for KEY, which must
    have been allocated using pkey_alloc.  */
-int pkey_get (int _key) __THROW;
+int pkey_get (int __key) __THROW;

 /* Free an allocated protection key, which must have been allocated
    using pkey_alloc.  */

From 516fa6080481a1433c173320b1c1432868e1e38a Mon Sep 17 00:00:00 2001
From: "Dmitry V. Levin" <ldv@altlinux.org>
Date: Fri, 29 Dec 2017 23:19:32 +0000
Subject: [PATCH] linux/aarch64: sync sys/ptrace.h with Linux 4.15 [BZ #22433]

Remove compat-specific constants that were never exported by kernel
headers under these names.  Before linux commit v3.7-rc1~16^2~1 they
were exported with COMPAT_ prefix, and since that commit they are not
exported at all.

* sysdeps/unix/sysv/linux/aarch64/sys/ptrace.h (__ptrace_request):
Remove arm-specific PTRACE_GET_THREAD_AREA, PTRACE_GETHBPREGS,
and PTRACE_SETHBPREGS.

(cherry picked from commit 2fd4bbaa1446f1be700e10c526cf585a796c4991)

diff --git a/sysdeps/unix/sysv/linux/aarch64/sys/ptrace.h b/sysdeps/unix/sysv/linux/aarch64/sys/ptrace.h
index 4be45b95ff..444edbb702 100644
--- a/sysdeps/unix/sysv/linux/aarch64/sys/ptrace.h
+++ b/sysdeps/unix/sysv/linux/aarch64/sys/ptrace.h
@@ -78,18 +78,10 @@ enum __ptrace_request
   PTRACE_DETACH = 17,
 #define PT_DETACH PTRACE_DETACH

-  PTRACE_GET_THREAD_AREA = 22,
-
   /* Continue and stop at the next entry to or return from syscall.  */
   PTRACE_SYSCALL = 24,
 #define PT_SYSCALL PTRACE_SYSCALL

-  /* Get all hardware breakpoint registers.  */
-  PTRACE_GETHBPREGS = 29,
-
-  /* Set all hardware breakpoint registers.  */
-  PTRACE_SETHBPREGS = 30,
-
   /* Set ptrace filter options.  */
   PTRACE_SETOPTIONS = 0x4200,
 #define PT_SETOPTIONS PTRACE_SETOPTIONS

From f36553bf6a4f69070f99badbdab5802b43e6e211 Mon Sep 17 00:00:00 2001
From: Mike FABIAN <mfabian@redhat.com>
Date: Mon, 19 Feb 2018 21:59:30 +0100
Subject: [PATCH] =?UTF-8?q?Add=20missing=20=E2=80=9Creorder-end=E2=80=9D?=
 =?UTF-8?q?=20in=20LC=5FCOLLATE=20of=20et=5FEE=20[BZ=20#22517]?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

	[BZ #22517]
	* localedata/locales/et_EE (LC_COLLATE): add missing “reorder-end”

(cherry picked from commit 7ec5f9465e732e668d0dc94ac078ba68056d6d0a)

diff --git a/localedata/locales/et_EE b/localedata/locales/et_EE
index 9cb55b568f..bab7493c98 100644
--- a/localedata/locales/et_EE
+++ b/localedata/locales/et_EE
@@ -103,6 +103,8 @@ reorder-after <w>
 <U00FC> <u-diaresis>;<BAS>;<MIN>;IGNORE % ü
 <U00DC> <u-diaresis>;<BAS>;<CAP>;IGNORE % Ü

+reorder-end
+
 END LC_COLLATE

 LC_CTYPE

From 7c6304182b9f422b782ace1cdd3efbde056aec36 Mon Sep 17 00:00:00 2001
From: DJ Delorie <dj@redhat.com>
Date: Thu, 1 Mar 2018 23:20:45 -0500
Subject: [PATCH] [BZ #22342] Fix netgroup cache keys.

Unlike other nscd caches, the netgroup cache contains two types of
records - those for "iterate through a netgroup" (i.e. setnetgrent())
and those for "is this user in this netgroup" (i.e. innetgr()),
i.e. full and partial records.  The timeout code assumes these records
have the same key for the group name, so that the collection of records
that is "this netgroup" can be expired as a unit.

However, the keys are not the same, as the in-netgroup key is generated
by nscd rather than being passed to it from elsewhere, and is generated
without the trailing NUL.  All other keys have the trailing NUL, and as
noted in the linked BZ, debug statements confirm that two keys for the
same netgroup are added to the cache with two different lengths.

The result of this is that as records in the cache expire, the purge
code only cleans out one of the two types of entries, resulting in
stale, possibly incorrect, and possibly inconsistent cache data.

The patch simply includes the existing NUL in the computation for the
key length ('key' points to the char after the NUL, and 'group' to the
first char of the group, so 'key-group' includes the first char to the
NUL, inclusive).

	[BZ #22342]
	* nscd/netgroupcache.c (addinnetgrX): Include trailing NUL in
	key value.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 1c81d55fc4b07b51adf68558ba74ce975153e580)

diff --git a/nscd/netgroupcache.c b/nscd/netgroupcache.c
index b832c9315f..2f187b208c 100644
--- a/nscd/netgroupcache.c
+++ b/nscd/netgroupcache.c
@@ -480,7 +480,7 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
 {
   const char *group = key;
   key = (char *) rawmemchr (key, '\0') + 1;
-  size_t group_len = key - group - 1;
+  size_t group_len = key - group;
   const char *host = *key++ ? key : NULL;
   if (host != NULL)
     key = (char *) rawmemchr (key, '\0') + 1;

From 78a90c2f74a2012dd3eff302189e47ff6779a757 Mon Sep 17 00:00:00 2001
From: Andreas Schwab <schwab@linux-m68k.org>
Date: Fri, 2 Mar 2018 23:07:14 +0100
Subject: [PATCH] Fix multiple definitions of __nss_*_database (bug 22918)

(cherry picked from commit eaf6753f8aac33a36deb98c1031d1bad7b593d2d)

diff --git a/nscd/gai.c b/nscd/gai.c
index d081747797..576fd0045b 100644
--- a/nscd/gai.c
+++ b/nscd/gai.c
@@ -45,3 +45,6 @@
 #ifdef HAVE_LIBIDN
 # include <libidn/idn-stub.c>
 #endif
+
+/* Some variables normally defined in libc.  */
+service_user *__nss_hosts_database attribute_hidden;
diff --git a/nss/nsswitch.c b/nss/nsswitch.c
index d5e655974f..b0f0c11a3e 100644
--- a/nss/nsswitch.c
+++ b/nss/nsswitch.c
@@ -62,7 +62,7 @@ static service_library *nss_new_service (name_database *database,

 /* Declare external database variables.  */
 #define DEFINE_DATABASE(name)						      \
-  extern service_user *__nss_##name##_database attribute_hidden;	      \
+  service_user *__nss_##name##_database attribute_hidden;		      \
   weak_extern (__nss_##name##_database)
 #include "databases.def"
 #undef DEFINE_DATABASE
diff --git a/nss/nsswitch.h b/nss/nsswitch.h
index eccb535ef5..63573b9ebc 100644
--- a/nss/nsswitch.h
+++ b/nss/nsswitch.h
@@ -226,10 +226,10 @@ libc_hidden_proto (__nss_hostname_digits_dots)
 #define MAX_NR_ADDRS    48

 /* Prototypes for __nss_*_lookup2 functions.  */
-#define DEFINE_DATABASE(arg)				    \
-  service_user *__nss_##arg##_database attribute_hidden;    \
-  int __nss_##arg##_lookup2 (service_user **, const char *, \
-			     const char *, void **);	    \
+#define DEFINE_DATABASE(arg)						      \
+  extern service_user *__nss_##arg##_database attribute_hidden;		      \
+  int __nss_##arg##_lookup2 (service_user **, const char *,		      \
+			     const char *, void **);			      \
   libc_hidden_proto (__nss_##arg##_lookup2)
 #include "databases.def"
 #undef DEFINE_DATABASE
diff --git a/posix/tst-rfc3484-2.c b/posix/tst-rfc3484-2.c
index f509534ca9..8c64ac59ff 100644
--- a/posix/tst-rfc3484-2.c
+++ b/posix/tst-rfc3484-2.c
@@ -58,6 +58,7 @@ _res_hconf_init (void)
 #undef	USE_NSCD
 #include "../sysdeps/posix/getaddrinfo.c"

+service_user *__nss_hosts_database attribute_hidden;

 /* This is the beginning of the real test code.  The above defines
    (among other things) the function rfc3484_sort.  */
diff --git a/posix/tst-rfc3484-3.c b/posix/tst-rfc3484-3.c
index ae44087a10..1c61aaf844 100644
--- a/posix/tst-rfc3484-3.c
+++ b/posix/tst-rfc3484-3.c
@@ -58,6 +58,7 @@ _res_hconf_init (void)
 #undef	USE_NSCD
 #include "../sysdeps/posix/getaddrinfo.c"

+service_user *__nss_hosts_database attribute_hidden;

 /* This is the beginning of the real test code.  The above defines
    (among other things) the function rfc3484_sort.  */
diff --git a/posix/tst-rfc3484.c b/posix/tst-rfc3484.c
index 7f191abbbc..8f45848e44 100644
--- a/posix/tst-rfc3484.c
+++ b/posix/tst-rfc3484.c
@@ -58,6 +58,7 @@ _res_hconf_init (void)
 #undef	USE_NSCD
 #include "../sysdeps/posix/getaddrinfo.c"

+service_user *__nss_hosts_database attribute_hidden;

 /* This is the beginning of the real test code.  The above defines
    (among other things) the function rfc3484_sort.  */

From 1e52d8e65a58c49a48549053a1b89c06240e0c6c Mon Sep 17 00:00:00 2001
From: Adhemerval Zanella <adhemerval.zanella@linaro.org>
Date: Fri, 17 Nov 2017 16:04:29 -0200
Subject: [PATCH] i386: Fix i386 sigaction sa_restorer initialization
 (BZ#21269)

This patch fixes the i386 sa_restorer field initialization for sigaction
syscall for kernel with vDSO.  As described in bug report, i386 Linux
(and compat on x86_64) interprets SA_RESTORER clear with nonzero
sa_restorer as a request for stack switching if the SS segment is 'funny'.
This means that anything that tries to mix glibc's signal handling with
segmentation (for instance through modify_ldt syscall) is randomly broken
depending on what values lands in sa_restorer.

The testcase added  is based on Linux test tools/testing/selftests/x86/ldt_gdt.c,
more specifically in do_multicpu_tests function.  The main changes are:

  - C11 atomics instead of plain access.

  - Remove x86_64 support which simplifies the syscall handling and fallbacks.

  - Replicate only the test required to trigger the issue.

Checked on i686-linux-gnu.

	[BZ #21269]
	* sysdeps/unix/sysv/linux/i386/Makefile (tests): Add tst-bz21269.
	* sysdeps/unix/sysv/linux/i386/sigaction.c (SET_SA_RESTORER): Clear
	sa_restorer for vDSO case.
	* sysdeps/unix/sysv/linux/i386/tst-bz21269.c: New file.

(cherry picked from commit 68448be208ee06e76665918b37b0a57e3e00c8b4)

diff --git a/sysdeps/unix/sysv/linux/i386/Makefile b/sysdeps/unix/sysv/linux/i386/Makefile
index 4080b8c966..da716e2c1b 100644
--- a/sysdeps/unix/sysv/linux/i386/Makefile
+++ b/sysdeps/unix/sysv/linux/i386/Makefile
@@ -3,6 +3,9 @@ default-abi := 32

 ifeq ($(subdir),misc)
 sysdep_routines += ioperm iopl vm86
+
+tests += tst-bz21269
+$(objpfx)tst-bz21269: $(shared-thread-library)
 endif

 ifeq ($(subdir),elf)
diff --git a/sysdeps/unix/sysv/linux/i386/sigaction.c b/sysdeps/unix/sysv/linux/i386/sigaction.c
index a5eb9e0d3e..177ff60ee6 100644
--- a/sysdeps/unix/sysv/linux/i386/sigaction.c
+++ b/sysdeps/unix/sysv/linux/i386/sigaction.c
@@ -42,7 +42,6 @@ extern void restore_rt (void) asm ("__restore_rt") attribute_hidden;
 #endif
 extern void restore (void) asm ("__restore") attribute_hidden;

-
 /* If ACT is not NULL, change the action for SIG to *ACT.
    If OACT is not NULL, put the old action for SIG in *OACT.  */
 int
@@ -65,6 +64,8 @@ __libc_sigaction (int sig, const struct sigaction *act, struct sigaction *oact)
 	  kact.sa_restorer = ((act->sa_flags & SA_SIGINFO)
 			      ? &restore_rt : &restore);
 	}
+      else
+	kact.sa_restorer = NULL;
     }

   /* XXX The size argument hopefully will have to be changed to the
diff --git a/sysdeps/unix/sysv/linux/i386/tst-bz21269.c b/sysdeps/unix/sysv/linux/i386/tst-bz21269.c
new file mode 100644
index 0000000000..353e36507d
--- /dev/null
+++ b/sysdeps/unix/sysv/linux/i386/tst-bz21269.c
@@ -0,0 +1,233 @@
+/* Test for i386 sigaction sa_restorer handling (BZ#21269)
+   Copyright (C) 2017 Free Software Foundation, Inc.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, see
+   <http://www.gnu.org/licenses/>.  */
+
+/* This is based on Linux test tools/testing/selftests/x86/ldt_gdt.c,
+   more specifically in do_multicpu_tests function.  The main changes
+   are:
+
+   - C11 atomics instead of plain access.
+   - Remove x86_64 support which simplifies the syscall handling
+     and fallbacks.
+   - Replicate only the test required to trigger the issue for the
+     BZ#21269.  */
+
+#include <stdatomic.h>
+
+#include <asm/ldt.h>
+#include <linux/futex.h>
+
+#include <setjmp.h>
+#include <signal.h>
+#include <errno.h>
+#include <sys/syscall.h>
+#include <sys/mman.h>
+
+#include <support/xunistd.h>
+#include <support/check.h>
+#include <support/xthread.h>
+
+static int
+xset_thread_area (struct user_desc *u_info)
+{
+  long ret = syscall (SYS_set_thread_area, u_info);
+  TEST_VERIFY_EXIT (ret == 0);
+  return ret;
+}
+
+static void
+xmodify_ldt (int func, const void *ptr, unsigned long bytecount)
+{
+  TEST_VERIFY_EXIT (syscall (SYS_modify_ldt, 1, ptr, bytecount) == 0);
+}
+
+static int
+futex (int *uaddr, int futex_op, int val, void *timeout, int *uaddr2,
+	int val3)
+{
+  return syscall (SYS_futex, uaddr, futex_op, val, timeout, uaddr2, val3);
+}
+
+static void
+xsethandler (int sig, void (*handler)(int, siginfo_t *, void *), int flags)
+{
+  struct sigaction sa = { 0 };
+  sa.sa_sigaction = handler;
+  sa.sa_flags = SA_SIGINFO | flags;
+  TEST_VERIFY_EXIT (sigemptyset (&sa.sa_mask) == 0);
+  TEST_VERIFY_EXIT (sigaction (sig, &sa, 0) == 0);
+}
+
+static jmp_buf jmpbuf;
+
+static void
+sigsegv_handler (int sig, siginfo_t *info, void *ctx_void)
+{
+  siglongjmp (jmpbuf, 1);
+}
+
+/* Points to an array of 1024 ints, each holding its own index.  */
+static const unsigned int *counter_page;
+static struct user_desc *low_user_desc;
+static struct user_desc *low_user_desc_clear; /* Used to delete GDT entry.  */
+static int gdt_entry_num;
+
+static void
+setup_counter_page (void)
+{
+  long page_size = sysconf (_SC_PAGE_SIZE);
+  TEST_VERIFY_EXIT (page_size > 0);
+  unsigned int *page = xmmap (NULL, page_size, PROT_READ | PROT_WRITE,
+			      MAP_ANONYMOUS | MAP_PRIVATE | MAP_32BIT, -1);
+  for (int i = 0; i < (page_size / sizeof (unsigned int)); i++)
+    page[i] = i;
+  counter_page = page;
+}
+
+static void
+setup_low_user_desc (void)
+{
+  low_user_desc = xmmap (NULL, 2 * sizeof (struct user_desc),
+			 PROT_READ | PROT_WRITE,
+			 MAP_ANONYMOUS | MAP_PRIVATE | MAP_32BIT, -1);
+
+  low_user_desc->entry_number    = -1;
+  low_user_desc->base_addr       = (unsigned long) &counter_page[1];
+  low_user_desc->limit           = 0xffff;
+  low_user_desc->seg_32bit       = 1;
+  low_user_desc->contents        = 0;
+  low_user_desc->read_exec_only  = 0;
+  low_user_desc->limit_in_pages  = 1;
+  low_user_desc->seg_not_present = 0;
+  low_user_desc->useable         = 0;
+
+  xset_thread_area (low_user_desc);
+
+  low_user_desc_clear = low_user_desc + 1;
+  low_user_desc_clear->entry_number = gdt_entry_num;
+  low_user_desc_clear->read_exec_only = 1;
+  low_user_desc_clear->seg_not_present = 1;
+}
+
+/* Possible values of futex:
+   0: thread is idle.
+   1: thread armed.
+   2: thread should clear LDT entry 0.
+   3: thread should exit.  */
+static atomic_uint ftx;
+
+static void *
+threadproc (void *ctx)
+{
+  while (1)
+    {
+      futex ((int *) &ftx, FUTEX_WAIT, 1, NULL, NULL, 0);
+      while (atomic_load (&ftx) != 2)
+	{
+	  if (atomic_load (&ftx) >= 3)
+	    return NULL;
+	}
+
+      /* clear LDT entry 0.  */
+      const struct user_desc desc = { 0 };
+      xmodify_ldt (1, &desc, sizeof (desc));
+
+      /* If ftx == 2, set it to zero,  If ftx == 100, quit.  */
+      if (atomic_fetch_add (&ftx, -2) != 2)
+	return NULL;
+    }
+}
+
+
+/* As described in testcase, for historical reasons x86_32 Linux (and compat
+   on x86_64) interprets SA_RESTORER clear with nonzero sa_restorer as a
+   request for stack switching if the SS segment is 'funny' (this is default
+   scenario for vDSO system).  This means that anything that tries to mix
+   signal handling with segmentation should explicit clear the sa_restorer.
+
+   This testcase check if sigaction in fact does it by changing the local
+   descriptor table (LDT) through the modify_ldt syscall and triggering
+   a synchronous segfault on iret fault by trying to install an invalid
+   segment.  With a correct zeroed sa_restorer it should not trigger an
+   'real' SEGSEGV and allows the siglongjmp in signal handler.  */
+
+static int
+do_test (void)
+{
+  setup_counter_page ();
+  setup_low_user_desc ();
+
+  pthread_t thread;
+  unsigned short orig_ss;
+
+  xsethandler (SIGSEGV, sigsegv_handler, 0);
+  /* 32-bit kernels send SIGILL instead of SIGSEGV on IRET faults.  */
+  xsethandler (SIGILL, sigsegv_handler, 0);
+
+  thread = xpthread_create (0, threadproc, 0);
+
+  asm volatile ("mov %%ss, %0" : "=rm" (orig_ss));
+
+  for (int i = 0; i < 5; i++)
+    {
+      if (sigsetjmp (jmpbuf, 1) != 0)
+	continue;
+
+      /* Make sure the thread is ready after the last test. */
+      while (atomic_load (&ftx) != 0)
+	;
+
+      struct user_desc desc = {
+	.entry_number       = 0,
+	.base_addr          = 0,
+	.limit              = 0xffff,
+	.seg_32bit          = 1,
+	.contents           = 0,
+	.read_exec_only     = 0,
+	.limit_in_pages     = 1,
+	.seg_not_present    = 0,
+	.useable            = 0
+      };
+
+      xmodify_ldt (0x11, &desc, sizeof (desc));
+
+      /* Arm the thread.  */
+      ftx = 1;
+      futex ((int*) &ftx, FUTEX_WAKE, 0, NULL, NULL, 0);
+
+      asm volatile ("mov %0, %%ss" : : "r" (0x7));
+
+      /* Fire up thread modify_ldt call.  */
+      atomic_store (&ftx, 2);
+
+      while (atomic_load (&ftx) != 0)
+	;
+
+      /* On success, modify_ldt will segfault us synchronously and we will
+	 escape via siglongjmp.  */
+      support_record_failure ();
+    }
+
+  atomic_store (&ftx, 100);
+  futex ((int*) &ftx, FUTEX_WAKE, 0, NULL, NULL, 0);
+
+  xpthread_join (thread);
+
+  return 0;
+}
+
+#include <support/test-driver.c>

From 55ad82e45c313454de657931898e974a7a036cad Mon Sep 17 00:00:00 2001
From: Andrew Senkevich <andrew.n.senkevich@gmail.com>
Date: Fri, 23 Mar 2018 16:19:45 +0100
Subject: [PATCH] Fix i386 memmove issue (bug 22644).

	[BZ #22644]
	* sysdeps/i386/i686/multiarch/memcpy-sse2-unaligned.S: Fixed
	branch conditions.
	* string/test-memmove.c (do_test2): New testcase.

(cherry picked from commit cd66c0e584c6d692bc8347b5e72723d02b8a8ada)

diff --git a/string/test-memmove.c b/string/test-memmove.c
index edc7a4c3bf..64e3651ba4 100644
--- a/string/test-memmove.c
+++ b/string/test-memmove.c
@@ -24,6 +24,7 @@
 # define TEST_NAME "memmove"
 #endif
 #include "test-string.h"
+#include <support/test-driver.h>

 char *simple_memmove (char *, const char *, size_t);

@@ -245,6 +246,60 @@ do_random_tests (void)
     }
 }

+static void
+do_test2 (void)
+{
+  size_t size = 0x20000000;
+  uint32_t * large_buf;
+
+  large_buf = mmap ((void*) 0x70000000, size, PROT_READ | PROT_WRITE,
+		    MAP_PRIVATE | MAP_ANON, -1, 0);
+
+  if (large_buf == MAP_FAILED)
+    error (EXIT_UNSUPPORTED, errno, "Large mmap failed");
+
+  if ((uintptr_t) large_buf > 0x80000000 - 128
+      || 0x80000000 - (uintptr_t) large_buf > 0x20000000)
+    {
+      error (0, 0, "Large mmap allocated improperly");
+      ret = EXIT_UNSUPPORTED;
+      munmap ((void *) large_buf, size);
+      return;
+    }
+
+  size_t bytes_move = 0x80000000 - (uintptr_t) large_buf;
+  size_t arr_size = bytes_move / sizeof (uint32_t);
+  size_t i;
+
+  FOR_EACH_IMPL (impl, 0)
+    {
+      for (i = 0; i < arr_size; i++)
+        large_buf[i] = (uint32_t) i;
+
+      uint32_t * dst = &large_buf[33];
+
+#ifdef TEST_BCOPY
+      CALL (impl, (char *) large_buf, (char *) dst, bytes_move);
+#else
+      CALL (impl, (char *) dst, (char *) large_buf, bytes_move);
+#endif
+
+      for (i = 0; i < arr_size; i++)
+	{
+	  if (dst[i] != (uint32_t) i)
+	    {
+	      error (0, 0,
+		     "Wrong result in function %s dst \"%p\" src \"%p\" offset \"%zd\"",
+		     impl->name, dst, large_buf, i);
+	      ret = 1;
+	      break;
+	    }
+	}
+    }
+
+  munmap ((void *) large_buf, size);
+}
+
 int
 test_main (void)
 {
@@ -284,6 +339,9 @@ test_main (void)
     }

   do_random_tests ();
+
+  do_test2 ();
+
   return ret;
 }

diff --git a/sysdeps/i386/i686/multiarch/memcpy-sse2-unaligned.S b/sysdeps/i386/i686/multiarch/memcpy-sse2-unaligned.S
index 9c3bbe7e17..9aa17de99c 100644
--- a/sysdeps/i386/i686/multiarch/memcpy-sse2-unaligned.S
+++ b/sysdeps/i386/i686/multiarch/memcpy-sse2-unaligned.S
@@ -72,7 +72,7 @@ ENTRY (MEMCPY)
 	cmp	%edx, %eax

 # ifdef USE_AS_MEMMOVE
-	jg	L(check_forward)
+	ja	L(check_forward)

 L(mm_len_0_or_more_backward):
 /* Now do checks for lengths. We do [0..16], [16..32], [32..64], [64..128]
@@ -81,7 +81,7 @@ L(mm_len_0_or_more_backward):
 	jbe	L(mm_len_0_16_bytes_backward)

 	cmpl	$32, %ecx
-	jg	L(mm_len_32_or_more_backward)
+	ja	L(mm_len_32_or_more_backward)

 /* Copy [0..32] and return.  */
 	movdqu	(%eax), %xmm0
@@ -92,7 +92,7 @@ L(mm_len_0_or_more_backward):

 L(mm_len_32_or_more_backward):
 	cmpl	$64, %ecx
-	jg	L(mm_len_64_or_more_backward)
+	ja	L(mm_len_64_or_more_backward)

 /* Copy [0..64] and return.  */
 	movdqu	(%eax), %xmm0
@@ -107,7 +107,7 @@ L(mm_len_32_or_more_backward):

 L(mm_len_64_or_more_backward):
 	cmpl	$128, %ecx
-	jg	L(mm_len_128_or_more_backward)
+	ja	L(mm_len_128_or_more_backward)

 /* Copy [0..128] and return.  */
 	movdqu	(%eax), %xmm0
@@ -132,7 +132,7 @@ L(mm_len_128_or_more_backward):
 	add	%ecx, %eax
 	cmp	%edx, %eax
 	movl	SRC(%esp), %eax
-	jle	L(forward)
+	jbe	L(forward)
 	PUSH (%esi)
 	PUSH (%edi)
 	PUSH (%ebx)
@@ -269,7 +269,7 @@ L(check_forward):
 	add	%edx, %ecx
 	cmp	%eax, %ecx
 	movl	LEN(%esp), %ecx
-	jle	L(forward)
+	jbe	L(forward)

 /* Now do checks for lengths. We do [0..16], [0..32], [0..64], [0..128]
 	separately.  */