#
# Backport from upstream:
#
# From 1cef1b19089528db11f221e938f60b9b048945d7 Mon Sep 17 00:00:00 2001
# From: Andreas Schwab <schwab@suse.de>
# Date: Thu, 21 Mar 2013 15:50:27 +0100
# Subject: [PATCH] Fix stack overflow in getaddrinfo with many results
#
# ---
# ChangeLog                   |    6 ++++++
# NEWS                        |    5 ++++-
# sysdeps/posix/getaddrinfo.c |   23 +++++++++++++++++++++--
# 3 files changed, 31 insertions(+), 3 deletions(-)
#
# 2013-04-03  Andreas Schwab  <schwab@suse.de>
#
#	[BZ #15330]
#	* sysdeps/posix/getaddrinfo.c (getaddrinfo): Allocate results and
#	order arrays from heap if bigger than alloca cutoff.

diff -urN glibc-2.5-20061008T1257.orig/sysdeps/posix/getaddrinfo.c glibc-2.5-20061008T1257/sysdeps/posix/getaddrinfo.c
--- glibc-2.5-20061008T1257.orig/sysdeps/posix/getaddrinfo.c	2013-04-11 14:41:39.224166628 -0400
+++ glibc-2.5-20061008T1257/sysdeps/posix/getaddrinfo.c	2013-04-11 15:30:32.186995962 -0400
@@ -2577,11 +2577,27 @@
 	}
 
       /* Sort results according to RFC 3484.  */
-      struct sort_result results[nresults];
-      struct sort_order order[nresults];
+      struct sort_result *results;
+      struct sort_order *order;
       struct addrinfo *q;
       struct addrinfo *last = NULL;
       char *canonname = NULL;
+      bool malloc_results;
+
+      malloc_results
+	= !__libc_use_alloca (nresults * (sizeof (*results) + sizeof (*order)));
+      if (malloc_results)
+	{
+	  results = malloc (nresults * (sizeof (*results) + sizeof (*order)));
+	  if (results == NULL)
+	    {
+	      free (in6ai);
+	      return EAI_MEMORY;
+	    }
+	}
+      else
+	results = alloca (nresults * (sizeof (*results) + sizeof (*order)));
+      order = (struct sort_order *) (results + nresults);
 
       struct sort_result_combo src
 	= { .results = results, .nresults = nresults, .f9_mode = f9m };
@@ -2774,6 +2790,9 @@
 
       /* Fill in the canonical name into the new first entry.  */
       p->ai_canonname = canonname;
+
+      if (malloc_results)
+	free (results);
     }
 
   free (in6ai);
