git: 461cad31f3fd - stable/13 - rtld-elf: Fix leaks and wild frees in origin_subst

From: Jessica Clarke <jrtc27_at_FreeBSD.org>
Date: Wed, 10 Aug 2022 23:12:04 UTC
The branch stable/13 has been updated by jrtc27:

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

commit 461cad31f3fdac9e5ee10464e3557866a8ed0e5a
Author:     Jessica Clarke <jrtc27@FreeBSD.org>
AuthorDate: 2022-07-12 16:47:47 +0000
Commit:     Jessica Clarke <jrtc27@FreeBSD.org>
CommitDate: 2022-08-10 23:11:48 +0000

    rtld-elf: Fix leaks and wild frees in origin_subst
    
    55abf23dd36b inverted the value passed to origin_subst_one when rolling
    up the existing code into a loop. If the first token is found ($ORIGIN),
    this results in a wild free of part of strtab. Processing the second
    token works fine and will act how the first should have regardless of
    whether found, allocating memory for the string without freeing.
    Processing subsequent tokens however will then leak, regardless of
    whether found, as they will also believe they need to allocate memory
    and can't free the string.
    
    Found by:       CHERI
    Reviewed by:    kib, markj
    Fixes:          55abf23dd36b ("rtld: make token substitution table-driven")
    MFC after:      3 days
    Differential Revision:  https://reviews.freebsd.org/D35792
    
    (cherry picked from commit becd9908beb8f1b47ddc6628cb005185a26ec85c)
---
 libexec/rtld-elf/rtld.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libexec/rtld-elf/rtld.c b/libexec/rtld-elf/rtld.c
index ef600b3e52ca..ab3a0740bede 100644
--- a/libexec/rtld-elf/rtld.c
+++ b/libexec/rtld-elf/rtld.c
@@ -1226,7 +1226,7 @@ origin_subst(Obj_Entry *obj, const char *real)
 	res = __DECONST(char *, real);
 	for (i = 0; i < (int)nitems(tokens); i++) {
 		res = origin_subst_one(tokens[i].pass_obj ? obj : NULL,
-		    res, tokens[i].kw, tokens[i].subst, i == 0);
+		    res, tokens[i].kw, tokens[i].subst, i != 0);
 	}
 	return (res);
 }