support_format_hostent: Add more error information for NETDB_INTERNAL
[glibc.git] / dirent / scandir-tail.c
blob068c644c4efe350aea9489ea5406f40b67bdea37
1 /* Logic guts of scandir*.
2 Copyright (C) 1992-2017 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
19 #include <dirent.h>
20 #include <errno.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <libc-lock.h>
25 #ifndef SCANDIR_TAIL
26 # define SCANDIR_TAIL __scandir_tail
27 # define READDIR __readdir
28 # define DIRENT_TYPE struct dirent
29 #endif
31 int
32 SCANDIR_TAIL (DIR *dp,
33 DIRENT_TYPE ***namelist,
34 int (*select) (const DIRENT_TYPE *),
35 int (*cmp) (const DIRENT_TYPE **, const DIRENT_TYPE **))
37 if (dp == NULL)
38 return -1;
40 int save = errno;
41 __set_errno (0);
43 int result;
44 struct scandir_cancel_struct c = { .dp = dp };
45 __libc_cleanup_push (&__scandir_cancel_handler, &c);
47 DIRENT_TYPE **v = NULL;
48 size_t vsize = 0;
49 DIRENT_TYPE *d;
50 while ((d = READDIR (dp)) != NULL)
52 if (select != NULL)
54 int selected = (*select) (d);
56 /* The SELECT function might have changed errno. It was
57 zero before and it need to be again to make the later
58 tests work. */
59 __set_errno (0);
61 if (!selected)
62 continue;
64 else
65 __set_errno (0);
67 if (__glibc_unlikely (c.cnt == vsize))
69 if (vsize == 0)
70 vsize = 10;
71 else
72 vsize *= 2;
73 DIRENT_TYPE **new = realloc (v, vsize * sizeof *v);
74 if (new == NULL)
75 break;
76 c.v = v = new;
79 size_t dsize = &d->d_name[_D_ALLOC_NAMLEN (d)] - (char *) d;
80 DIRENT_TYPE *vnew = malloc (dsize);
81 if (vnew == NULL)
82 break;
83 v[c.cnt++] = (DIRENT_TYPE *) memcpy (vnew, d, dsize);
86 if (__glibc_likely (errno == 0))
88 __closedir (dp);
90 /* Sort the list if we have a comparison function to sort with. */
91 if (cmp != NULL)
92 qsort (v, c.cnt, sizeof *v, (__compar_fn_t) cmp);
94 *namelist = v;
95 result = c.cnt;
97 else
99 /* This frees everything and calls closedir. */
100 __scandir_cancel_handler (&c);
101 result = -1;
104 __libc_cleanup_pop (0);
106 if (result >= 0)
107 __set_errno (save);
108 return result;