git: 904c148f1c93 - main - libutil: eliminate one syscall from kinfo_getproc

From: Ed Maste <emaste_at_FreeBSD.org>
Date: Sat, 07 May 2022 00:06:17 UTC
The branch main has been updated by emaste:

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

commit 904c148f1c939f080b9fad345b76caa8ccb6d03c
Author:     Ed Maste <emaste@FreeBSD.org>
AuthorDate: 2022-05-06 16:41:04 +0000
Commit:     Ed Maste <emaste@FreeBSD.org>
CommitDate: 2022-05-07 00:06:09 +0000

    libutil: eliminate one syscall from kinfo_getproc
    
    Previously we invoked the sysctl with a NULL buffer to query the size,
    allocated a buffer, then invoked it again to fetch the data.
    
    As we only handle the case where the sysctl provides data of the
    expected size we can just allocate a correctly-sized buffer to begin
    with.
    
    Reported by:    Thomas Hurst via Twitter
    Reviewed by:    kevans
    MFC after:      1 week
    Sponsored by:   The FreeBSD Foundation
    Differential Revision:  https://reviews.freebsd.org/D35140
---
 lib/libutil/kinfo_getproc.c | 12 +++++-------
 1 file changed, 5 insertions(+), 7 deletions(-)

diff --git a/lib/libutil/kinfo_getproc.c b/lib/libutil/kinfo_getproc.c
index 4d16b1c16a13..e34fdbdf18e8 100644
--- a/lib/libutil/kinfo_getproc.c
+++ b/lib/libutil/kinfo_getproc.c
@@ -46,17 +46,15 @@ kinfo_getproc(pid_t pid)
 	int mib[4];
 	size_t len;
 
-	len = 0;
+	len = sizeof(*kipp);
+	kipp = malloc(len);
+	if (kipp == NULL)
+		return (NULL);
+
 	mib[0] = CTL_KERN;
 	mib[1] = KERN_PROC;
 	mib[2] = KERN_PROC_PID;
 	mib[3] = pid;
-	if (sysctl(mib, nitems(mib), NULL, &len, NULL, 0) < 0)
-		return (NULL);
-
-	kipp = malloc(len);
-	if (kipp == NULL)
-		return (NULL);
 
 	if (sysctl(mib, nitems(mib), kipp, &len, NULL, 0) < 0)
 		goto bad;