git: d5fccc19aa1b - stable/13 - vm_map_protect(): add VM_MAP_PROTECT_GROWSDOWN flag

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Fri, 25 Aug 2023 01:08:37 UTC
The branch stable/13 has been updated by kib:

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

commit d5fccc19aa1b1e9440b5ad3bc386b6bb42fdff78
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2023-07-28 00:40:53 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2023-08-25 01:06:44 +0000

    vm_map_protect(): add VM_MAP_PROTECT_GROWSDOWN flag
    
    (cherry picked from commit 90049eabcfadf229e3983f04310a8ea28fe3d2b1)
---
 sys/vm/vm_map.c | 19 +++++++++++++++++++
 sys/vm/vm_map.h |  1 +
 2 files changed, 20 insertions(+)

diff --git a/sys/vm/vm_map.c b/sys/vm/vm_map.c
index 1f223bbbd396..029605eb272a 100644
--- a/sys/vm/vm_map.c
+++ b/sys/vm/vm_map.c
@@ -2752,6 +2752,7 @@ vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
 	vm_map_entry_t entry, first_entry, in_tran, prev_entry;
 	vm_object_t obj;
 	struct ucred *cred;
+	vm_offset_t orig_start;
 	vm_prot_t check_prot, max_prot, old_prot;
 	int rv;
 
@@ -2763,8 +2764,10 @@ vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
 	    !CONTAINS_BITS(new_maxprot, new_prot))
 		return (KERN_OUT_OF_BOUNDS);
 
+	orig_start = start;
 again:
 	in_tran = NULL;
+	start = orig_start;
 	vm_map_lock(map);
 
 	if ((map->flags & MAP_WXORX) != 0 &&
@@ -2787,6 +2790,22 @@ again:
 	if (!vm_map_lookup_entry(map, start, &first_entry))
 		first_entry = vm_map_entry_succ(first_entry);
 
+	if ((flags & VM_MAP_PROTECT_GROWSDOWN) != 0 &&
+	    (first_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0) {
+		/*
+		 * Handle Linux's PROT_GROWSDOWN flag.
+		 * It means that protection is applied down to the
+		 * whole stack, including the specified range of the
+		 * mapped region, and the grow down region (AKA
+		 * guard).
+		 */
+		while (!CONTAINS_BITS(first_entry->eflags,
+		    MAP_ENTRY_GUARD | MAP_ENTRY_STACK_GAP_DN) &&
+		    first_entry != vm_map_entry_first(map))
+			first_entry = vm_map_entry_pred(first_entry);
+		start = first_entry->start;
+	}
+
 	/*
 	 * Make a first pass to check for protection violations.
 	 */
diff --git a/sys/vm/vm_map.h b/sys/vm/vm_map.h
index 8adfcaf57cb3..9e4e1db0fd98 100644
--- a/sys/vm/vm_map.h
+++ b/sys/vm/vm_map.h
@@ -518,6 +518,7 @@ vm_map_entry_succ(vm_map_entry_t entry)
 
 #define	VM_MAP_PROTECT_SET_PROT		0x0001
 #define	VM_MAP_PROTECT_SET_MAXPROT	0x0002
+#define	VM_MAP_PROTECT_GROWSDOWN	0x0004
 
 int vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
     vm_prot_t new_prot, vm_prot_t new_maxprot, int flags);