Blame SOURCES/0001-patch-8.2.4253-using-freed-memory-when-substitute-wi.patch

da4393
diff -up vim82/src/ex_cmds.c.cve0413 vim82/src/ex_cmds.c
da4393
--- vim82/src/ex_cmds.c.cve0413	2022-02-10 08:09:27.644493218 +0100
da4393
+++ vim82/src/ex_cmds.c	2022-02-10 08:09:27.653493168 +0100
da4393
@@ -3627,6 +3627,7 @@ ex_substitute(exarg_T *eap)
da4393
     int		save_do_all;		// remember user specified 'g' flag
da4393
     int		save_do_ask;		// remember user specified 'c' flag
da4393
     char_u	*pat = NULL, *sub = NULL;	// init for GCC
da4393
+    char_u	*sub_copy = NULL;
da4393
     int		delimiter;
da4393
     int		sublen;
da4393
     int		got_quit = FALSE;
da4393
@@ -3928,11 +3929,20 @@ ex_substitute(exarg_T *eap)
da4393
     sub_firstline = NULL;
da4393
 
da4393
     /*
da4393
-     * ~ in the substitute pattern is replaced with the old pattern.
da4393
-     * We do it here once to avoid it to be replaced over and over again.
da4393
-     * But don't do it when it starts with "\=", then it's an expression.
da4393
+     * If the substitute pattern starts with "\=" then it's an expression.
da4393
+     * Make a copy, a recursive function may free it.
da4393
+     * Otherwise, '~' in the substitute pattern is replaced with the old
da4393
+     * pattern.  We do it here once to avoid it to be replaced over and over
da4393
+     * again.
da4393
      */
da4393
-    if (!(sub[0] == '\\' && sub[1] == '='))
da4393
+    if (sub[0] == '\\' && sub[1] == '=')
da4393
+    {
da4393
+	sub = vim_strsave(sub);
da4393
+	if (sub == NULL)
da4393
+	    return;
da4393
+	sub_copy = sub;
da4393
+    }
da4393
+    else
da4393
 	sub = regtilde(sub, magic_isset());
da4393
 
da4393
     /*
da4393
@@ -4737,6 +4747,7 @@ outofmem:
da4393
 #endif
da4393
 
da4393
     vim_regfree(regmatch.regprog);
da4393
+    vim_free(sub_copy);
da4393
 
da4393
     // Restore the flag values, they can be used for ":&&".
da4393
     subflags.do_all = save_do_all;
da4393
diff -up vim82/src/testdir/test_substitute.vim.cve0413 vim82/src/testdir/test_substitute.vim
da4393
--- vim82/src/testdir/test_substitute.vim.cve0413	2022-02-10 08:09:27.654493162 +0100
da4393
+++ vim82/src/testdir/test_substitute.vim	2022-02-10 08:10:14.392230843 +0100
da4393
@@ -926,4 +926,21 @@ func Test_substitute_multiline_submatch(
da4393
   close!
da4393
 endfunc
da4393
 
da4393
+" This was using "old_sub" after it was freed.
da4393
+func Test_using_old_sub()
da4393
+  set compatible maxfuncdepth=10
da4393
+  new
da4393
+  call setline(1, 'some text.')
da4393
+  func Repl()
da4393
+    ~
da4393
+    s/
da4393
+  endfunc
da4393
+  silent!  s/\%')/\=Repl()
da4393
+
da4393
+  delfunc Repl
da4393
+  bwipe!
da4393
+  set nocompatible
da4393
+endfunc
da4393
+
da4393
+
da4393
 " vim: shiftwidth=2 sts=2 expandtab