From e25a91f9279b444f5230a0864d84589e2fbd21e9 Mon Sep 17 00:00:00 2001
From: Koichi Murase <myoga.murase@gmail.com>
Date: Sat, 12 Mar 2022 15:52:57 +0900
Subject: [PATCH 1/3] fix backslash quoting of invisible character ^\

---
 lib/sh/shquote.c | 30 +++++++++++++++++++++---------
 1 file changed, 21 insertions(+), 9 deletions(-)

diff --git a/lib/sh/shquote.c b/lib/sh/shquote.c
index 622fcbb0..f9511c7f 100644
--- a/lib/sh/shquote.c
+++ b/lib/sh/shquote.c
@@ -331,10 +331,25 @@ sh_backslash_quote_for_double_quotes (string, flags)
   DECLARE_MBSTATE;
  
   slen = strlen (string);
+
+  /* Make unsafe characters visible by sh_charvis() and replace `string' and
+     `slen'. */
+  if (flags & 1)
+    {
+      /* Max is 3*string length (three-character visible representation) */
+      result = (char *)xmalloc (3 * slen + 1);
+      rind = sind = 0;
+      while (string[sind])
+	sh_charvis (string, &sind, slen, result, &rind);
+      result[rind] = '\0';
+      string = result;
+      slen = rind;
+    }
+
   send = string + slen;
   mb_cur_max = MB_CUR_MAX;
-  /* Max is 4*string length (backslash + three-character visible representation) */
-  result = (char *)xmalloc (4 * slen + 1);
+  /* Max is 2*string length (backslash) */
+  result = (char *)xmalloc (2 * slen + 1);
 
   for (rind = sind = 0; c = string[sind]; sind++)
     {
@@ -343,13 +358,6 @@ sh_backslash_quote_for_double_quotes (string, flags)
       if ((sh_syntaxtab[c] & CBSDQUOTE) && c != '\n')
 	result[rind++] = '\\';
 
-      if (flags & 1)
-	{
-	  sh_charvis (string, &sind, slen, result, &rind);
-	  sind--;		/* sh_charvis consumes an extra character */
-	  continue;
-	}
-
       /* I should probably use the CSPECL flag for these in sh_syntaxtab[] */
       else if (c == CTLESC || c == CTLNUL)
 	result[rind++] = CTLESC;		/* could be '\\'? */
@@ -368,6 +376,10 @@ sh_backslash_quote_for_double_quotes (string, flags)
     }
 
   result[rind] = '\0';
+
+  if (flags & 1)
+    free(string);
+
   return (result);
 }
 #endif /* PROMPT_STRING_DECODE */
-- 
2.35.1

