git: e5f2d5b35e79 - main - rs: Fix a use after free.

From: John Baldwin <jhb_at_FreeBSD.org>
Date: Wed, 05 Oct 2022 23:48:32 UTC
The branch main has been updated by jhb:

URL: https://cgit.FreeBSD.org/src/commit/?id=e5f2d5b35e79ddf995a8a5c782a7940ca2e05fdf

commit e5f2d5b35e79ddf995a8a5c782a7940ca2e05fdf
Author:     John Baldwin <jhb@FreeBSD.org>
AuthorDate: 2022-10-05 23:47:40 +0000
Commit:     John Baldwin <jhb@FreeBSD.org>
CommitDate: 2022-10-05 23:47:40 +0000

    rs: Fix a use after free.
    
    Using a pointer passed to realloc() after realloc() even for pointer
    arithmetic is UB.  It also breaks in practice on CHERI systems as
    the updated value of 'sp' in this case would have had the bounds from
    the old allocation.
    
    This would be much cleaner if elem were a std::vector<char *>.
    
    Reviewed by:    brooks, emaste
    Reported by:    GCC -Wuse-after-free
    Differential Revision:  https://reviews.freebsd.org/D36831
---
 usr.bin/rs/rs.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/usr.bin/rs/rs.c b/usr.bin/rs/rs.c
index 99e48194b3c7..557c5b9f56c0 100644
--- a/usr.bin/rs/rs.c
+++ b/usr.bin/rs/rs.c
@@ -38,6 +38,7 @@
 #include <err.h>
 #include <ctype.h>
 #include <limits.h>
+#include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -365,13 +366,15 @@ static char **
 getptrs(char **sp)
 {
 	char **p;
+	ptrdiff_t offset;
 
+	offset = sp - elem;
 	allocsize += allocsize;
 	p = (char **)realloc(elem, allocsize * sizeof(char *));
 	if (p == NULL)
 		err(1, "no memory");
 
-	sp += (p - elem);
+	sp = p + offset;
 	endelem = (elem = p) + allocsize;
 	return(sp);
 }