git: d3a7b75bbcb5 - stable/12 - Fix coredump_phnum test with ASLR enabled

From: Ed Maste <emaste_at_FreeBSD.org>
Date: Sun, 28 Nov 2021 02:56:12 UTC
The branch stable/12 has been updated by emaste:

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

commit d3a7b75bbcb5171d7eda9d712437efd46bb7605b
Author:     Ed Maste <emaste@FreeBSD.org>
AuthorDate: 2021-11-21 17:17:20 +0000
Commit:     Ed Maste <emaste@FreeBSD.org>
CommitDate: 2021-11-28 02:55:46 +0000

    Fix coredump_phnum test with ASLR enabled
    
    coredump_phnum intends to generate a core file with many PT_LOAD
    segments.  Previously it called mmap() in a loop with alternating
    protections, relying on each mapping following the previous, to produce
    a core file with many page-sized PT_LOAD segments.  With ASLR on we no
    longer have this property of each mmap() following the previous.
    
    Instead, perform a single allocation, and then use mprotect() to set
    alternating pages to PROT_READ.
    
    PR:             259970
    Reported by:    lwhsu, mw
    Reviewed by:    kib
    MFC after:      1 week
    Sponsored by:   The FreeBSD Foundation
    Differential Revision:  https://reviews.freebsd.org/D33070
    
    (cherry picked from commit 8ec4c5dae32765701ac70811455084efd1570c32)
    (cherry picked from commit ee2e925603e42897fbabe1b24208d27bdcaae786)
---
 tests/sys/kern/coredump_phnum_helper.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/tests/sys/kern/coredump_phnum_helper.c b/tests/sys/kern/coredump_phnum_helper.c
index da023e691a24..0dff59b918d9 100644
--- a/tests/sys/kern/coredump_phnum_helper.c
+++ b/tests/sys/kern/coredump_phnum_helper.c
@@ -42,18 +42,21 @@ int
 main(int argc __unused, char **argv __unused)
 {
 	void *v;
-	unsigned i;
+	size_t i, pages;
 
-	for (i = 0; i < UINT16_MAX + 1000; i++) {
+	pages = UINT16_MAX + 1000;
+	v = mmap(NULL, pages * PAGE_SIZE, PROT_READ | PROT_WRITE,
+	    MAP_ANON | MAP_PRIVATE, -1, 0);
+	if (v == NULL)
+		err(1, "mmap");
+	for (i = 0; i < pages; i += 2) {
 		/*
-		 * Alternate protections; otherwise the kernel will just extend
-		 * the adjacent same-protection previous mapping.
+		 * Alternate protections to interleave RW and R PT_LOAD
+		 * segments.
 		 */
-		v = mmap(NULL, PAGE_SIZE,
-		    (((i % 2) == 0) ? PROT_READ : 0) | PROT_WRITE,
-		    MAP_ANON | MAP_PRIVATE, -1, 0);
-		if (v == MAP_FAILED)
-			err(1, "mmap");
+		if (mprotect((char *)v + i * PAGE_SIZE, PAGE_SIZE,
+		    PROT_READ) != 0)
+			err(1, "mprotect");
 	}
 
 	/* Dump core. */