On 2019-01-04 10:38 a.m., Pádraig Brady wrote:

I wonder should we avoid VLAs in coreutils altogether?
I.E. add -Werror=vla. The kernel has done this for security reaons.

Attached is a suggested patch to allocate buffers on the heap
(even if they were not VLAs).

Comments welcomed,
 - assaf
>From d045ce5166c06829ee5a63a33e120fe5ee5b83d4 Mon Sep 17 00:00:00 2001
From: Assaf Gordon <[email protected]>
Date: Sat, 5 Jan 2019 16:22:41 -0700
Subject: [PATCH] basenc: allocate buffers on heap

Allocate the encoding/decoding buffers dynamically on the heap instead
of using variable-length-array (VLA) on the stack.
Discussed in https://lists.gnu.org/r/coreutils/2019-01/msg00004.html .

* src/basenc.c (do_encode,do_decode): Allocate inbuf/outbuf using
xmalloc, and free if using LINT.
---
 src/basenc.c | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/src/basenc.c b/src/basenc.c
index c25dc49f9..5ec7bf4a5 100644
--- a/src/basenc.c
+++ b/src/basenc.c
@@ -976,10 +976,12 @@ static void
 do_encode (FILE *in, FILE *out, uintmax_t wrap_column)
 {
   size_t current_column = 0;
-  char inbuf[ENC_BLOCKSIZE];
-  char outbuf[BASE_LENGTH (ENC_BLOCKSIZE)];
+  char *inbuf, *outbuf;
   size_t sum;
 
+  inbuf = xmalloc (ENC_BLOCKSIZE);
+  outbuf = xmalloc (BASE_LENGTH (ENC_BLOCKSIZE));
+
   do
     {
       size_t n;
@@ -1010,16 +1012,21 @@ do_encode (FILE *in, FILE *out, uintmax_t wrap_column)
 
   if (ferror (in))
     die (EXIT_FAILURE, errno, _("read error"));
+
+  IF_LINT (free (inbuf));
+  IF_LINT (free (outbuf));
 }
 
 static void
 do_decode (FILE *in, FILE *out, bool ignore_garbage)
 {
-  char inbuf[BASE_LENGTH (DEC_BLOCKSIZE)];
-  char outbuf[DEC_BLOCKSIZE];
+  char *inbuf, *outbuf;
   size_t sum;
   struct base_decode_context ctx;
 
+  inbuf = xmalloc (BASE_LENGTH (DEC_BLOCKSIZE));
+  outbuf = xmalloc (DEC_BLOCKSIZE);
+
 #if BASE_TYPE == 42
   ctx.inbuf = NULL;
 #endif
@@ -1077,6 +1084,8 @@ do_decode (FILE *in, FILE *out, bool ignore_garbage)
 #if BASE_TYPE == 42
   IF_LINT (free (ctx.inbuf));
 #endif
+  IF_LINT (free (inbuf));
+  IF_LINT (free (outbuf));
 }
 
 int
-- 
2.11.0

Reply via email to