From 806d037671e133bd28a7864248763f643967973a Mon Sep 17 00:00:00 2001
From: Bram Moolenaar <Bram@vim.org>
Date: Tue, 25 Jan 2022 20:45:16 +0000
Subject: [PATCH] patch 8.2.4218: illegal memory access with bracketed paste in
 Ex mode

Problem:    Illegal memory access with bracketed paste in Ex mode.
Solution:   Reserve space for the trailing NUL.

---
 src/edit.c                 |  3 ++-
 src/testdir/test_paste.vim | 11 +++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/src/edit.c b/src/edit.c
index c67f67c..3767769 100644
--- a/src/edit.c
+++ b/src/edit.c
@@ -4984,7 +4984,8 @@ bracketed_paste(paste_mode_T mode, int drop, garray_T *gap)
 		    break;
 
 		case PASTE_EX:
-		    if (gap != NULL && ga_grow(gap, idx) == OK)
+	            // add one for the NUL that is going to be appended
+		    if (gap != NULL && ga_grow(gap, idx + 1) == OK)
 		    {
 			mch_memmove((char *)gap->ga_data + gap->ga_len,
 							     buf, (size_t)idx);
diff --git a/src/testdir/test_paste.vim b/src/testdir/test_paste.vim
index c30140f..263f084 100644
--- a/src/testdir/test_paste.vim
+++ b/src/testdir/test_paste.vim
@@ -134,3 +134,14 @@ func Test_xrestore()
 
   bwipe!
 endfunc
+
+" bracketed paste in Ex-mode
+func Test_paste_ex_mode()
+  unlet! foo
+  call feedkeys("Qlet foo=\"\<Esc>[200~foo\<CR>bar\<Esc>[201~\"\<CR>vi\<CR>", 'xt')
+  call assert_equal("foo\rbar", foo)
+
+
+  " pasting more than 40 bytes
+  exe "norm Q\<PasteStart>0000000000000000000000000000000000000000000000000000000000000000000000\<C-C>"
+endfunc
-- 
2.27.0

