git: cb6e97f4dae6 - main - libc: split scandir() into scandir_dirp() and proper scandir()

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Wed, 24 Aug 2022 19:44:06 UTC
The branch main has been updated by kib:

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

commit cb6e97f4dae6d0b631b65f23baf2d4c67120f672
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2022-08-23 04:30:40 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2022-08-24 19:26:00 +0000

    libc: split scandir() into scandir_dirp() and proper scandir()
    
    The new helper scandir_dirp() takes DIR *, i.e. a pre-opened directory,
    instead of the directory name.
    
    Reviewed by:    emaste, imp, kevans, markj, Aymeric Wibo <obiwac@gmail.com>
    Sponsored by:   The FreeBSD Foundation
    MFC after:      1 week
    Differential revision:  https://reviews.freebsd.org/D36301
---
 lib/libc/gen/scandir.c | 36 ++++++++++++++++++++++++++++--------
 1 file changed, 28 insertions(+), 8 deletions(-)

diff --git a/lib/libc/gen/scandir.c b/lib/libc/gen/scandir.c
index 10cd7633dac1..4cfc823e4f94 100644
--- a/lib/libc/gen/scandir.c
+++ b/lib/libc/gen/scandir.c
@@ -64,22 +64,18 @@ typedef DECLARE_BLOCK(int, dcomp_block, const struct dirent **,
 static int alphasort_thunk(void *thunk, const void *p1, const void *p2);
 #endif
 
-int
+static int
 #ifdef I_AM_SCANDIR_B
-scandir_b(const char *dirname, struct dirent ***namelist, select_block select,
+scandir_b_dirp(DIR *dirp, struct dirent ***namelist, select_block select,
     dcomp_block dcomp)
 #else
-scandir(const char *dirname, struct dirent ***namelist,
+scandir_dirp(DIR *dirp, struct dirent ***namelist,
     int (*select)(const struct dirent *), int (*dcomp)(const struct dirent **,
-	const struct dirent **))
+    const struct dirent **))
 #endif
 {
 	struct dirent *d, *p, **names = NULL;
 	size_t arraysz, numitems;
-	DIR *dirp;
-
-	if ((dirp = opendir(dirname)) == NULL)
-		return(-1);
 
 	numitems = 0;
 	arraysz = 32;	/* initial estimate of the array size */
@@ -138,6 +134,30 @@ fail:
 	return (-1);
 }
 
+int
+#ifdef I_AM_SCANDIR_B
+scandir_b(const char *dirname, struct dirent ***namelist, select_block select,
+    dcomp_block dcomp)
+#else
+scandir(const char *dirname, struct dirent ***namelist,
+    int (*select)(const struct dirent *), int (*dcomp)(const struct dirent **,
+    const struct dirent **))
+#endif
+{
+	DIR *dirp;
+
+	dirp = opendir(dirname);
+	if (dirp == NULL)
+		return (-1);
+	return (
+#ifdef I_AM_SCANDIR_B
+	    scandir_b_dirp
+#else
+	    scandir_dirp
+#endif
+	    (dirp, namelist, select, dcomp));
+}
+
 #ifndef I_AM_SCANDIR_B
 /*
  * Alphabetic order comparison routine for those who want it.