From 51f0bfb88a3554ca2dde777d78a59880d1ee37a8 Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Tue, 17 May 2022 20:11:02 +0100
Subject: [PATCH] patch 8.2.4975: recursive command line loop may cause a crash
 
Problem:    Recursive command line loop may cause a crash.
Solution:   Limit recursion of getcmdline().
 
Reference:https://github.com/vim/vim/commit/51f0bfb88a3554ca2dde777d78a59880d1ee37a8
Conflict:(1)The src/version.c file is not modified
(2)add e_command_too_recursive in src/globals.h
---
 src/ex_getln.c               | 12 ++++++++++++
 src/globals.h                |  3 +++
 src/testdir/test_cmdline.vim | 11 +++++++++++
 3 files changed, 26 insertions(+)

diff --git a/src/ex_getln.c b/src/ex_getln.c
index 7571ae2..aa01f80 100644
--- a/src/ex_getln.c
+++ b/src/ex_getln.c
@@ -791,6 +791,7 @@ getcmdline_int(
     int		indent,		// indent for inside conditionals
     int		init_ccline)	// clear ccline first
 {
+    static int	depth = 0;	    // call depth
     int		c;
     int		i;
     int		j;
@@ -820,6 +821,9 @@ getcmdline_int(
     int		did_save_ccline = FALSE;
     int		cmdline_type;
 
+    // one recursion level deeper
+    ++depth;
+
     if (ccline.cmdbuff != NULL)
     {
 	// Being called recursively.  Since ccline is global, we need to save
@@ -873,6 +877,13 @@ getcmdline_int(
 	ccline.cmdlen = indent;
     }
 
+    if (depth == 50)
+    {
+	// Somehow got into a loop recursively calling getcmdline(), bail out.
+	emsg(_(e_command_too_recursive));
+	goto theend;
+    }
+
     ExpandInit(&xpc);
     ccline.xpc = &xpc;
 
@@ -2425,6 +2436,7 @@ theend:
     {
 	char_u *p = ccline.cmdbuff;
 
+	--depth;
 	if (did_save_ccline)
 	    restore_cmdline(&save_ccline);
 	else
diff --git a/src/globals.h b/src/globals.h
index 54f68b3..01ebbb8 100644
--- a/src/globals.h
+++ b/src/globals.h
@@ -1755,3 +1755,6 @@ EXTERN int did_repeated_msg INIT(= 0);
 EXTERN char e_illegal_character_in_word[]
        INIT(= N_("E1280: Illegal character in word"));
 #endif
+
+EXTERN char e_command_too_recursive[]
+	INIT(= N_("E169: Command too recursive"));
diff --git a/src/testdir/test_cmdline.vim b/src/testdir/test_cmdline.vim
index c55ee0b..4665c75 100644
--- a/src/testdir/test_cmdline.vim
+++ b/src/testdir/test_cmdline.vim
@@ -913,5 +913,16 @@ func Test_zero_line_search()
   q!
 endfunc
 
+func Test_recursive_register()
+  let @= = ''
+  silent! ?e/
+  let caught = 'no'
+  try
+    normal // 
+  catch /E169:/
+    let caught = 'yes'
+  endtry
+  call assert_equal('yes', caught)
+endfunc
 
 " vim: shiftwidth=2 sts=2 expandtab
-- 
2.27.0

