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
This commit is contained in:
John Baldwin 2022-10-05 16:47:40 -07:00
parent bb31e1bbf2
commit e5f2d5b35e

View File

@ -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);
}