git: 0c835785ebe4 - stable/13 - cred: group_is_supplementary(): Use bsearch()

From: Olivier Certner <olce_at_FreeBSD.org>
Date: Fri, 15 Nov 2024 13:00:44 UTC
The branch stable/13 has been updated by olce:

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

commit 0c835785ebe48f6033d8f0007b00b659d4dd3a22
Author:     Olivier Certner <olce@FreeBSD.org>
AuthorDate: 2024-07-19 11:23:19 +0000
Commit:     Olivier Certner <olce@FreeBSD.org>
CommitDate: 2024-11-15 12:59:07 +0000

    cred: group_is_supplementary(): Use bsearch()
    
    This makes that function use a more efficient version of binary search
    instead, and removes one more hand-rolled binary search code from the
    tree (and the kernel binary).
    
    Reviewed by:    mhorne, emaste
    Approved by:    markj (mentor)
    MFC after:      3 days
    Differential Revision:  https://reviews.freebsd.org/D46907
    
    (cherry picked from commit 372605478c6fe2c628f25428af201f866d7eb015)
    
    Approved by:    markj (mentor)
---
 sys/kern/kern_prot.c | 25 ++++++++++++-------------
 1 file changed, 12 insertions(+), 13 deletions(-)

diff --git a/sys/kern/kern_prot.c b/sys/kern/kern_prot.c
index 0ec3df305048..eb4910e1591a 100644
--- a/sys/kern/kern_prot.c
+++ b/sys/kern/kern_prot.c
@@ -52,6 +52,7 @@
 #include <sys/acct.h>
 #include <sys/kdb.h>
 #include <sys/kernel.h>
+#include <sys/libkern.h>
 #include <sys/lock.h>
 #include <sys/loginclass.h>
 #include <sys/malloc.h>
@@ -828,6 +829,15 @@ sys_setgroups(struct thread *td, struct setgroups_args *uap)
 	return (error);
 }
 
+static int
+gidp_cmp(const void *p1, const void *p2)
+{
+	const gid_t g1 = *(const gid_t *)p1;
+	const gid_t g2 = *(const gid_t *)p2;
+
+	return ((g1 > g2) - (g1 < g2));
+}
+
 int
 kern_setgroups(struct thread *td, u_int ngrp, gid_t *groups)
 {
@@ -1278,24 +1288,13 @@ sys___setugid(struct thread *td, struct __setugid_args *uap)
 static int
 group_is_supplementary(const gid_t gid, const struct ucred *const cred)
 {
-	int l, h, m;
 
 	/*
 	 * Perform a binary search of the supplementary groups.  This is
 	 * possible because we sort the groups in crsetgroups().
 	 */
-	l = 1;
-	h = cred->cr_ngroups;
-
-	while (l < h) {
-		m = l + (h - l) / 2;
-		if (cred->cr_groups[m] < gid)
-			l = m + 1;
-		else
-			h = m;
-	}
-
-	return (l < cred->cr_ngroups && cred->cr_groups[l] == gid);
+	return (bsearch(&gid, cred->cr_groups + 1, cred->cr_ngroups - 1,
+	    sizeof(gid), gidp_cmp) != NULL);
 }
 
 /*