git: 97c0b4e0eacd - stable/14 - cred: group_is_supplementary(): Use bsearch()

From: Olivier Certner <olce_at_FreeBSD.org>
Date: Fri, 15 Nov 2024 10:48:53 UTC
The branch stable/14 has been updated by olce:

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

commit 97c0b4e0eacd8d163795c11ce790259db56af935
Author:     Olivier Certner <olce@FreeBSD.org>
AuthorDate: 2024-07-19 11:23:19 +0000
Commit:     Olivier Certner <olce@FreeBSD.org>
CommitDate: 2024-11-15 10:47:41 +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 be7a71ae6879..ab2adbffa23b 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>
@@ -832,6 +833,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)
 {
@@ -1282,24 +1292,13 @@ sys___setugid(struct thread *td, struct __setugid_args *uap)
 static bool
 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);
 }
 
 /*