getopt: Get rid of alloca usage in process_long_option

Message ID 20230925184846.4096885-1-josimmon@redhat.com
State New
Headers
Series getopt: Get rid of alloca usage in process_long_option |

Checks

Context Check Description
redhat-pt-bot/TryBot-apply_patch success Patch applied to master at the time it was sent
redhat-pt-bot/TryBot-32bit success Build for i686
linaro-tcwg-bot/tcwg_glibc_build--master-aarch64 success Testing passed
linaro-tcwg-bot/tcwg_glibc_check--master-arm success Testing passed
linaro-tcwg-bot/tcwg_glibc_check--master-aarch64 success Testing passed
linaro-tcwg-bot/tcwg_glibc_build--master-arm success Testing passed

Commit Message

Joe Simmons-Talbott Sept. 25, 2023, 6:48 p.m. UTC
  Replace alloca usage with a scratch_buffer.
---
 posix/getopt.c | 24 +++++++++++-------------
 1 file changed, 11 insertions(+), 13 deletions(-)
  

Patch

diff --git a/posix/getopt.c b/posix/getopt.c
index 1e2441c4af..a65e85b3f9 100644
--- a/posix/getopt.c
+++ b/posix/getopt.c
@@ -23,6 +23,7 @@ 
 
 #include "getopt.h"
 
+#include <scratch_buffer.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -50,10 +51,6 @@ 
 #  define flockfile(fp) /* nop */
 #  define funlockfile(fp) /* nop */
 # endif
-/* When used standalone, do not attempt to use alloca.  */
-# define __libc_use_alloca(size) 0
-# undef alloca
-# define alloca(size) (abort (), (void *)0)
 #endif
 
 /* This implementation of 'getopt' has three modes for handling
@@ -223,9 +220,10 @@  process_long_option (int argc, char **argv, const char *optstring,
     {
       /* Didn't find an exact match, so look for abbreviations.  */
       unsigned char *ambig_set = NULL;
-      int ambig_malloced = 0;
       int ambig_fallback = 0;
       int indfound = -1;
+      struct scratch_buffer sbuf;
+      scratch_buffer_init (&sbuf);
 
       for (p = longopts, option_index = 0; p->name; p++, option_index++)
 	if (!strncmp (p->name, d->__nextchar, namelen))
@@ -250,13 +248,14 @@  process_long_option (int argc, char **argv, const char *optstring,
 		      ambig_fallback = 1;
 		    else if (!ambig_set)
 		      {
-			if (__libc_use_alloca (n_options))
-			  ambig_set = alloca (n_options);
-			else if ((ambig_set = malloc (n_options)) == NULL)
-			  /* Fall back to simpler error message.  */
-			  ambig_fallback = 1;
+			if (!scratch_buffer_set_array_size (
+			    &sbuf, 1, n_options))
+			  {
+			    ambig_fallback = 1;
+			    ambig_set = NULL;
+			  }
 			else
-			  ambig_malloced = 1;
+			  ambig_set = sbuf.data;
 
 			if (ambig_set)
 			  {
@@ -296,8 +295,7 @@  process_long_option (int argc, char **argv, const char *optstring,
 		  funlockfile (stderr);
 		}
 	    }
-	  if (ambig_malloced)
-	    free (ambig_set);
+	  scratch_buffer_free (&sbuf);
 	  d->__nextchar += strlen (d->__nextchar);
 	  d->optind++;
 	  d->optopt = 0;