git: 28391f188ca1 - main - kern_malloc: Restore working KASAN runtime after free() and zfree() folding

From: Olivier Certner <olce_at_FreeBSD.org>
Date: Thu, 01 Aug 2024 20:35:33 UTC
The branch main has been updated by olce:

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

commit 28391f188ca18b6251ba46040adf81946b0ccb03
Author:     Olivier Certner <olce@FreeBSD.org>
AuthorDate: 2024-08-01 19:22:56 +0000
Commit:     Olivier Certner <olce@FreeBSD.org>
CommitDate: 2024-08-01 20:35:14 +0000

    kern_malloc: Restore working KASAN runtime after free() and zfree() folding
    
    In the zfree() case, the explicit_bzero() calls zero all the allocation,
    including the redzone which malloc() has marked as invalid.  So calling
    kasan_mark() before those is in fact necessary.
    
    This fixes a crash at boot when 'ldconfig' is run and tries to get
    random bytes through getrandom() (relevant part of the stack is
    read_random_uio() -> zfree() -> explicit_bzero()) for kernels with KASAN
    compiled in.
    
    Approved by:    markj (mentor)
    Fixes:          4fab5f005482 ("kern_malloc: fold free and zfree together into one __always_inline func")
    MFC after:      10 days
    MFC with:       4fab5f005482
    Sponsored by:   The FreeBSD Foundation
---
 sys/kern/kern_malloc.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/sys/kern/kern_malloc.c b/sys/kern/kern_malloc.c
index ebdd00808f22..3c4cb63003c4 100644
--- a/sys/kern/kern_malloc.c
+++ b/sys/kern/kern_malloc.c
@@ -940,14 +940,18 @@ _free(void *addr, struct malloc_type *mtp, bool dozero)
 #if defined(INVARIANTS) && !defined(KASAN)
 		free_save_type(addr, mtp, size);
 #endif
-		if (dozero)
+		if (dozero) {
+			kasan_mark(addr, size, size, 0);
 			explicit_bzero(addr, size);
+		}
 		uma_zfree_arg(zone, addr, slab);
 		break;
 	case SLAB_COOKIE_MALLOC_LARGE:
 		size = malloc_large_size(slab);
-		if (dozero)
+		if (dozero) {
+			kasan_mark(addr, size, size, 0);
 			explicit_bzero(addr, size);
+		}
 		free_large(addr, size);
 		break;
 	case SLAB_COOKIE_CONTIG_MALLOC: