xref: /freebsd/contrib/pkgconf/libpkgconf/win-dirent.h (revision a3cefe7f2b4df0f70ff92d4570ce18e517af43ec)
1 /*
2  * Dirent interface for Microsoft Visual Studio
3  *
4  * Copyright (C) 1998-2019 Toni Ronkko
5  * This file is part of dirent.  Dirent may be freely distributed
6  * under the MIT license.  For all details and documentation, see
7  * https://github.com/tronkko/dirent
8  */
9 #ifndef DIRENT_H
10 #define DIRENT_H
11 
12 /* Hide warnings about unreferenced local functions */
13 #if defined(__clang__)
14 #	pragma clang diagnostic ignored "-Wunused-function"
15 #elif defined(_MSC_VER)
16 #	pragma warning(disable:4505)
17 #elif defined(__GNUC__)
18 #	pragma GCC diagnostic ignored "-Wunused-function"
19 #endif
20 
21 /*
22  * Include windows.h without Windows Sockets 1.1 to prevent conflicts with
23  * Windows Sockets 2.0.
24  */
25 #ifndef WIN32_LEAN_AND_MEAN
26 #	define WIN32_LEAN_AND_MEAN
27 #endif
28 #include <windows.h>
29 
30 #include <stdio.h>
31 #include <stdarg.h>
32 #include <wchar.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include <malloc.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <errno.h>
39 #include <ctype.h>
40 
41 /* Indicates that d_type field is available in dirent structure */
42 #define _DIRENT_HAVE_D_TYPE
43 
44 /* Indicates that d_namlen field is available in dirent structure */
45 #define _DIRENT_HAVE_D_NAMLEN
46 
47 /* Entries missing from MSVC 6.0 */
48 #if !defined(FILE_ATTRIBUTE_DEVICE)
49 #	define FILE_ATTRIBUTE_DEVICE 0x40
50 #endif
51 
52 /* File type and permission flags for stat(), general mask */
53 #if !defined(S_IFMT)
54 #	define S_IFMT _S_IFMT
55 #endif
56 
57 /* Directory bit */
58 #if !defined(S_IFDIR)
59 #	define S_IFDIR _S_IFDIR
60 #endif
61 
62 /* Character device bit */
63 #if !defined(S_IFCHR)
64 #	define S_IFCHR _S_IFCHR
65 #endif
66 
67 /* Pipe bit */
68 #if !defined(S_IFFIFO)
69 #	define S_IFFIFO _S_IFFIFO
70 #endif
71 
72 /* Regular file bit */
73 #if !defined(S_IFREG)
74 #	define S_IFREG _S_IFREG
75 #endif
76 
77 /* Read permission */
78 #if !defined(S_IREAD)
79 #	define S_IREAD _S_IREAD
80 #endif
81 
82 /* Write permission */
83 #if !defined(S_IWRITE)
84 #	define S_IWRITE _S_IWRITE
85 #endif
86 
87 /* Execute permission */
88 #if !defined(S_IEXEC)
89 #	define S_IEXEC _S_IEXEC
90 #endif
91 
92 /* Pipe */
93 #if !defined(S_IFIFO)
94 #	define S_IFIFO _S_IFIFO
95 #endif
96 
97 /* Block device */
98 #if !defined(S_IFBLK)
99 #	define S_IFBLK 0
100 #endif
101 
102 /* Link */
103 #if !defined(S_IFLNK)
104 #	define S_IFLNK 0
105 #endif
106 
107 /* Socket */
108 #if !defined(S_IFSOCK)
109 #	define S_IFSOCK 0
110 #endif
111 
112 /* Read user permission */
113 #if !defined(S_IRUSR)
114 #	define S_IRUSR S_IREAD
115 #endif
116 
117 /* Write user permission */
118 #if !defined(S_IWUSR)
119 #	define S_IWUSR S_IWRITE
120 #endif
121 
122 /* Execute user permission */
123 #if !defined(S_IXUSR)
124 #	define S_IXUSR 0
125 #endif
126 
127 /* Read group permission */
128 #if !defined(S_IRGRP)
129 #	define S_IRGRP 0
130 #endif
131 
132 /* Write group permission */
133 #if !defined(S_IWGRP)
134 #	define S_IWGRP 0
135 #endif
136 
137 /* Execute group permission */
138 #if !defined(S_IXGRP)
139 #	define S_IXGRP 0
140 #endif
141 
142 /* Read others permission */
143 #if !defined(S_IROTH)
144 #	define S_IROTH 0
145 #endif
146 
147 /* Write others permission */
148 #if !defined(S_IWOTH)
149 #	define S_IWOTH 0
150 #endif
151 
152 /* Execute others permission */
153 #if !defined(S_IXOTH)
154 #	define S_IXOTH 0
155 #endif
156 
157 /* Maximum length of file name */
158 #if !defined(PATH_MAX)
159 #	define PATH_MAX MAX_PATH
160 #endif
161 #if !defined(FILENAME_MAX)
162 #	define FILENAME_MAX MAX_PATH
163 #endif
164 #if !defined(NAME_MAX)
165 #	define NAME_MAX FILENAME_MAX
166 #endif
167 
168 /* File type flags for d_type */
169 #define DT_UNKNOWN 0
170 #define DT_REG S_IFREG
171 #define DT_DIR S_IFDIR
172 #define DT_FIFO S_IFIFO
173 #define DT_SOCK S_IFSOCK
174 #define DT_CHR S_IFCHR
175 #define DT_BLK S_IFBLK
176 #define DT_LNK S_IFLNK
177 
178 /* Macros for converting between st_mode and d_type */
179 #define IFTODT(mode) ((mode) & S_IFMT)
180 #define DTTOIF(type) (type)
181 
182 /*
183  * File type macros.  Note that block devices, sockets and links cannot be
184  * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
185  * only defined for compatibility.  These macros should always return false
186  * on Windows.
187  */
188 #if !defined(S_ISFIFO)
189 #	define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
190 #endif
191 #if !defined(S_ISDIR)
192 #	define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
193 #endif
194 #if !defined(S_ISREG)
195 #	define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
196 #endif
197 #if !defined(S_ISLNK)
198 #	define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
199 #endif
200 #if !defined(S_ISSOCK)
201 #	define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
202 #endif
203 #if !defined(S_ISCHR)
204 #	define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
205 #endif
206 #if !defined(S_ISBLK)
207 #	define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
208 #endif
209 
210 /* Return the exact length of the file name without zero terminator */
211 #define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
212 
213 /* Return the maximum size of a file name */
214 #define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1)
215 
216 
217 #ifdef __cplusplus
218 extern "C" {
219 #endif
220 
221 
222 /* Wide-character version */
223 struct _wdirent {
224 	/* Always zero */
225 	long d_ino;
226 
227 	/* File position within stream */
228 	long d_off;
229 
230 	/* Structure size */
231 	unsigned short d_reclen;
232 
233 	/* Length of name without \0 */
234 	size_t d_namlen;
235 
236 	/* File type */
237 	int d_type;
238 
239 	/* File name */
240 	wchar_t d_name[PATH_MAX+1];
241 };
242 typedef struct _wdirent _wdirent;
243 
244 struct _WDIR {
245 	/* Current directory entry */
246 	struct _wdirent ent;
247 
248 	/* Private file data */
249 	WIN32_FIND_DATAW data;
250 
251 	/* True if data is valid */
252 	int cached;
253 
254 	/* Win32 search handle */
255 	HANDLE handle;
256 
257 	/* Initial directory name */
258 	wchar_t *patt;
259 };
260 typedef struct _WDIR _WDIR;
261 
262 /* Multi-byte character version */
263 struct dirent {
264 	/* Always zero */
265 	long d_ino;
266 
267 	/* File position within stream */
268 	long d_off;
269 
270 	/* Structure size */
271 	unsigned short d_reclen;
272 
273 	/* Length of name without \0 */
274 	size_t d_namlen;
275 
276 	/* File type */
277 	int d_type;
278 
279 	/* File name */
280 	char d_name[PATH_MAX+1];
281 };
282 typedef struct dirent dirent;
283 
284 struct DIR {
285 	struct dirent ent;
286 	struct _WDIR *wdirp;
287 };
288 typedef struct DIR DIR;
289 
290 
291 /* Dirent functions */
292 static DIR *opendir(const char *dirname);
293 static _WDIR *_wopendir(const wchar_t *dirname);
294 
295 static struct dirent *readdir(DIR *dirp);
296 static struct _wdirent *_wreaddir(_WDIR *dirp);
297 
298 static int readdir_r(
299 	DIR *dirp, struct dirent *entry, struct dirent **result);
300 static int _wreaddir_r(
301 	_WDIR *dirp, struct _wdirent *entry, struct _wdirent **result);
302 
303 static int closedir(DIR *dirp);
304 static int _wclosedir(_WDIR *dirp);
305 
306 static void rewinddir(DIR* dirp);
307 static void _wrewinddir(_WDIR* dirp);
308 
309 static int scandir(const char *dirname, struct dirent ***namelist,
310 	int (*filter)(const struct dirent*),
311 	int (*compare)(const struct dirent**, const struct dirent**));
312 
313 static int alphasort(const struct dirent **a, const struct dirent **b);
314 
315 static int versionsort(const struct dirent **a, const struct dirent **b);
316 
317 static int strverscmp(const char *a, const char *b);
318 
319 /* For compatibility with Symbian */
320 #define wdirent _wdirent
321 #define WDIR _WDIR
322 #define wopendir _wopendir
323 #define wreaddir _wreaddir
324 #define wclosedir _wclosedir
325 #define wrewinddir _wrewinddir
326 
327 /* Compatibility with older Microsoft compilers and non-Microsoft compilers */
328 #if !defined(_MSC_VER) || _MSC_VER < 1400
329 #	define wcstombs_s dirent_wcstombs_s
330 #	define mbstowcs_s dirent_mbstowcs_s
331 #endif
332 
333 /* Optimize dirent_set_errno() away on modern Microsoft compilers */
334 #if defined(_MSC_VER) && _MSC_VER >= 1400
335 #	define dirent_set_errno _set_errno
336 #endif
337 
338 
339 /* Internal utility functions */
340 static WIN32_FIND_DATAW *dirent_first(_WDIR *dirp);
341 static WIN32_FIND_DATAW *dirent_next(_WDIR *dirp);
342 
343 #if !defined(_MSC_VER) || _MSC_VER < 1400
344 static int dirent_mbstowcs_s(
345 	size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords,
346 	const char *mbstr, size_t count);
347 #endif
348 
349 #if !defined(_MSC_VER) || _MSC_VER < 1400
350 static int dirent_wcstombs_s(
351 	size_t *pReturnValue, char *mbstr, size_t sizeInBytes,
352 	const wchar_t *wcstr, size_t count);
353 #endif
354 
355 #if !defined(_MSC_VER) || _MSC_VER < 1400
356 static void dirent_set_errno(int error);
357 #endif
358 
359 
360 /*
361  * Open directory stream DIRNAME for read and return a pointer to the
362  * internal working area that is used to retrieve individual directory
363  * entries.
364  */
_wopendir(const wchar_t * dirname)365 static _WDIR *_wopendir(const wchar_t *dirname)
366 {
367 	wchar_t *p;
368 
369 	/* Must have directory name */
370 	if (dirname == NULL || dirname[0] == '\0') {
371 		dirent_set_errno(ENOENT);
372 		return NULL;
373 	}
374 
375 	/* Allocate new _WDIR structure */
376 	_WDIR *dirp = (_WDIR*) malloc(sizeof(struct _WDIR));
377 	if (!dirp)
378 		return NULL;
379 
380 	/* Reset _WDIR structure */
381 	dirp->handle = INVALID_HANDLE_VALUE;
382 	dirp->patt = NULL;
383 	dirp->cached = 0;
384 
385 	/*
386 	 * Compute the length of full path plus zero terminator
387 	 *
388 	 * Note that on WinRT there's no way to convert relative paths
389 	 * into absolute paths, so just assume it is an absolute path.
390 	 */
391 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
392 	/* Desktop */
393 	DWORD n = GetFullPathNameW(dirname, 0, NULL, NULL);
394 #else
395 	/* WinRT */
396 	size_t n = wcslen(dirname);
397 #endif
398 
399 	/* Allocate room for absolute directory name and search pattern */
400 	dirp->patt = (wchar_t*) malloc(sizeof(wchar_t) * n + 16);
401 	if (dirp->patt == NULL)
402 		goto exit_closedir;
403 
404 	/*
405 	 * Convert relative directory name to an absolute one.  This
406 	 * allows rewinddir() to function correctly even when current
407 	 * working directory is changed between opendir() and rewinddir().
408 	 *
409 	 * Note that on WinRT there's no way to convert relative paths
410 	 * into absolute paths, so just assume it is an absolute path.
411 	 */
412 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
413 	/* Desktop */
414 	n = GetFullPathNameW(dirname, n, dirp->patt, NULL);
415 	if (n <= 0)
416 		goto exit_closedir;
417 #else
418 	/* WinRT */
419 	wcsncpy_s(dirp->patt, n+1, dirname, n);
420 #endif
421 
422 	/* Append search pattern \* to the directory name */
423 	p = dirp->patt + n;
424 	switch (p[-1]) {
425 	case '\\':
426 	case '/':
427 	case ':':
428 		/* Directory ends in path separator, e.g. c:\temp\ */
429 		/*NOP*/;
430 		break;
431 
432 	default:
433 		/* Directory name doesn't end in path separator */
434 		*p++ = '\\';
435 	}
436 	*p++ = '*';
437 	*p = '\0';
438 
439 	/* Open directory stream and retrieve the first entry */
440 	if (!dirent_first(dirp))
441 		goto exit_closedir;
442 
443 	/* Success */
444 	return dirp;
445 
446 	/* Failure */
447 exit_closedir:
448 	_wclosedir(dirp);
449 	return NULL;
450 }
451 
452 /*
453  * Read next directory entry.
454  *
455  * Returns pointer to static directory entry which may be overwritten by
456  * subsequent calls to _wreaddir().
457  */
_wreaddir(_WDIR * dirp)458 static struct _wdirent *_wreaddir(_WDIR *dirp)
459 {
460 	/*
461 	 * Read directory entry to buffer.  We can safely ignore the return
462 	 * value as entry will be set to NULL in case of error.
463 	 */
464 	struct _wdirent *entry;
465 	(void) _wreaddir_r(dirp, &dirp->ent, &entry);
466 
467 	/* Return pointer to statically allocated directory entry */
468 	return entry;
469 }
470 
471 /*
472  * Read next directory entry.
473  *
474  * Returns zero on success.  If end of directory stream is reached, then sets
475  * result to NULL and returns zero.
476  */
_wreaddir_r(_WDIR * dirp,struct _wdirent * entry,struct _wdirent ** result)477 static int _wreaddir_r(
478 	_WDIR *dirp, struct _wdirent *entry, struct _wdirent **result)
479 {
480 	/* Read next directory entry */
481 	WIN32_FIND_DATAW *datap = dirent_next(dirp);
482 	if (!datap) {
483 		/* Return NULL to indicate end of directory */
484 		*result = NULL;
485 		return /*OK*/0;
486 	}
487 
488 	/*
489 	 * Copy file name as wide-character string.  If the file name is too
490 	 * long to fit in to the destination buffer, then truncate file name
491 	 * to PATH_MAX characters and zero-terminate the buffer.
492 	 */
493 	size_t n = 0;
494 	while (n < PATH_MAX && datap->cFileName[n] != 0) {
495 		entry->d_name[n] = datap->cFileName[n];
496 		n++;
497 	}
498 	entry->d_name[n] = 0;
499 
500 	/* Length of file name excluding zero terminator */
501 	entry->d_namlen = n;
502 
503 	/* File type */
504 	DWORD attr = datap->dwFileAttributes;
505 	if ((attr & FILE_ATTRIBUTE_DEVICE) != 0)
506 		entry->d_type = DT_CHR;
507 	else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
508 		entry->d_type = DT_DIR;
509 	else
510 		entry->d_type = DT_REG;
511 
512 	/* Reset dummy fields */
513 	entry->d_ino = 0;
514 	entry->d_off = 0;
515 	entry->d_reclen = sizeof(struct _wdirent);
516 
517 	/* Set result address */
518 	*result = entry;
519 	return /*OK*/0;
520 }
521 
522 /*
523  * Close directory stream opened by opendir() function.  This invalidates the
524  * DIR structure as well as any directory entry read previously by
525  * _wreaddir().
526  */
_wclosedir(_WDIR * dirp)527 static int _wclosedir(_WDIR *dirp)
528 {
529 	if (!dirp) {
530 		dirent_set_errno(EBADF);
531 		return /*failure*/-1;
532 	}
533 
534 	/* Release search handle */
535 	if (dirp->handle != INVALID_HANDLE_VALUE)
536 		FindClose(dirp->handle);
537 
538 	/* Release search pattern */
539 	free(dirp->patt);
540 
541 	/* Release directory structure */
542 	free(dirp);
543 	return /*success*/0;
544 }
545 
546 /*
547  * Rewind directory stream such that _wreaddir() returns the very first
548  * file name again.
549  */
_wrewinddir(_WDIR * dirp)550 static void _wrewinddir(_WDIR* dirp)
551 {
552 	if (!dirp)
553 		return;
554 
555 	/* Release existing search handle */
556 	if (dirp->handle != INVALID_HANDLE_VALUE)
557 		FindClose(dirp->handle);
558 
559 	/* Open new search handle */
560 	dirent_first(dirp);
561 }
562 
563 /* Get first directory entry */
dirent_first(_WDIR * dirp)564 static WIN32_FIND_DATAW *dirent_first(_WDIR *dirp)
565 {
566 	if (!dirp)
567 		return NULL;
568 
569 	/* Open directory and retrieve the first entry */
570 	dirp->handle = FindFirstFileExW(
571 		dirp->patt, FindExInfoStandard, &dirp->data,
572 		FindExSearchNameMatch, NULL, 0);
573 	if (dirp->handle == INVALID_HANDLE_VALUE)
574 		goto error;
575 
576 	/* A directory entry is now waiting in memory */
577 	dirp->cached = 1;
578 	return &dirp->data;
579 
580 error:
581 	/* Failed to open directory: no directory entry in memory */
582 	dirp->cached = 0;
583 
584 	/* Set error code */
585 	DWORD errorcode = GetLastError();
586 	switch (errorcode) {
587 	case ERROR_ACCESS_DENIED:
588 		/* No read access to directory */
589 		dirent_set_errno(EACCES);
590 		break;
591 
592 	case ERROR_DIRECTORY:
593 		/* Directory name is invalid */
594 		dirent_set_errno(ENOTDIR);
595 		break;
596 
597 	case ERROR_PATH_NOT_FOUND:
598 	default:
599 		/* Cannot find the file */
600 		dirent_set_errno(ENOENT);
601 	}
602 	return NULL;
603 }
604 
605 /* Get next directory entry */
dirent_next(_WDIR * dirp)606 static WIN32_FIND_DATAW *dirent_next(_WDIR *dirp)
607 {
608 	/* Is the next directory entry already in cache? */
609 	if (dirp->cached) {
610 		/* Yes, a valid directory entry found in memory */
611 		dirp->cached = 0;
612 		return &dirp->data;
613 	}
614 
615 	/* No directory entry in cache */
616 	if (dirp->handle == INVALID_HANDLE_VALUE)
617 		return NULL;
618 
619 	/* Read the next directory entry from stream */
620 	if (FindNextFileW(dirp->handle, &dirp->data) == FALSE)
621 		goto exit_close;
622 
623 	/* Success */
624 	return &dirp->data;
625 
626 	/* Failure */
627 exit_close:
628 	FindClose(dirp->handle);
629 	dirp->handle = INVALID_HANDLE_VALUE;
630 	return NULL;
631 }
632 
633 /* Open directory stream using plain old C-string */
opendir(const char * dirname)634 static DIR *opendir(const char *dirname)
635 {
636 	/* Must have directory name */
637 	if (dirname == NULL || dirname[0] == '\0') {
638 		dirent_set_errno(ENOENT);
639 		return NULL;
640 	}
641 
642 	/* Allocate memory for DIR structure */
643 	struct DIR *dirp = (DIR*) malloc(sizeof(struct DIR));
644 	if (!dirp)
645 		return NULL;
646 
647 	/* Convert directory name to wide-character string */
648 	wchar_t wname[PATH_MAX + 1];
649 	size_t n;
650 	int error = mbstowcs_s(&n, wname, PATH_MAX + 1, dirname, PATH_MAX+1);
651 	if (error)
652 		goto exit_failure;
653 
654 	/* Open directory stream using wide-character name */
655 	dirp->wdirp = _wopendir(wname);
656 	if (!dirp->wdirp)
657 		goto exit_failure;
658 
659 	/* Success */
660 	return dirp;
661 
662 	/* Failure */
663 exit_failure:
664 	free(dirp);
665 	return NULL;
666 }
667 
668 /* Read next directory entry */
readdir(DIR * dirp)669 static struct dirent *readdir(DIR *dirp)
670 {
671 	/*
672 	 * Read directory entry to buffer.  We can safely ignore the return
673 	 * value as entry will be set to NULL in case of error.
674 	 */
675 	struct dirent *entry;
676 	(void) readdir_r(dirp, &dirp->ent, &entry);
677 
678 	/* Return pointer to statically allocated directory entry */
679 	return entry;
680 }
681 
682 /*
683  * Read next directory entry into called-allocated buffer.
684  *
685  * Returns zero on success.  If the end of directory stream is reached, then
686  * sets result to NULL and returns zero.
687  */
readdir_r(DIR * dirp,struct dirent * entry,struct dirent ** result)688 static int readdir_r(
689 	DIR *dirp, struct dirent *entry, struct dirent **result)
690 {
691 	/* Read next directory entry */
692 	WIN32_FIND_DATAW *datap = dirent_next(dirp->wdirp);
693 	if (!datap) {
694 		/* No more directory entries */
695 		*result = NULL;
696 		return /*OK*/0;
697 	}
698 
699 	/* Attempt to convert file name to multi-byte string */
700 	size_t n;
701 	int error = wcstombs_s(
702 		&n, entry->d_name, PATH_MAX + 1,
703 		datap->cFileName, PATH_MAX + 1);
704 
705 	/*
706 	 * If the file name cannot be represented by a multi-byte string, then
707 	 * attempt to use old 8+3 file name.  This allows the program to
708 	 * access files although file names may seem unfamiliar to the user.
709 	 *
710 	 * Be ware that the code below cannot come up with a short file name
711 	 * unless the file system provides one.  At least VirtualBox shared
712 	 * folders fail to do this.
713 	 */
714 	if (error && datap->cAlternateFileName[0] != '\0') {
715 		error = wcstombs_s(
716 			&n, entry->d_name, PATH_MAX + 1,
717 			datap->cAlternateFileName, PATH_MAX + 1);
718 	}
719 
720 	if (!error) {
721 		/* Length of file name excluding zero terminator */
722 		entry->d_namlen = n - 1;
723 
724 		/* File attributes */
725 		DWORD attr = datap->dwFileAttributes;
726 		if ((attr & FILE_ATTRIBUTE_DEVICE) != 0)
727 			entry->d_type = DT_CHR;
728 		else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
729 			entry->d_type = DT_DIR;
730 		else
731 			entry->d_type = DT_REG;
732 
733 		/* Reset dummy fields */
734 		entry->d_ino = 0;
735 		entry->d_off = 0;
736 		entry->d_reclen = sizeof(struct dirent);
737 	} else {
738 		/*
739 		 * Cannot convert file name to multi-byte string so construct
740 		 * an erroneous directory entry and return that.  Note that
741 		 * we cannot return NULL as that would stop the processing
742 		 * of directory entries completely.
743 		 */
744 		entry->d_name[0] = '?';
745 		entry->d_name[1] = '\0';
746 		entry->d_namlen = 1;
747 		entry->d_type = DT_UNKNOWN;
748 		entry->d_ino = 0;
749 		entry->d_off = -1;
750 		entry->d_reclen = 0;
751 	}
752 
753 	/* Return pointer to directory entry */
754 	*result = entry;
755 	return /*OK*/0;
756 }
757 
758 /* Close directory stream */
closedir(DIR * dirp)759 static int closedir(DIR *dirp)
760 {
761 	int ok;
762 
763 	if (!dirp)
764 		goto exit_failure;
765 
766 	/* Close wide-character directory stream */
767 	ok = _wclosedir(dirp->wdirp);
768 	dirp->wdirp = NULL;
769 
770 	/* Release multi-byte character version */
771 	free(dirp);
772 	return ok;
773 
774 exit_failure:
775 	/* Invalid directory stream */
776 	dirent_set_errno(EBADF);
777 	return /*failure*/-1;
778 }
779 
780 /* Rewind directory stream to beginning */
rewinddir(DIR * dirp)781 static void rewinddir(DIR* dirp)
782 {
783 	if (!dirp)
784 		return;
785 
786 	/* Rewind wide-character string directory stream */
787 	_wrewinddir(dirp->wdirp);
788 }
789 
790 /* Scan directory for entries */
scandir(const char * dirname,struct dirent *** namelist,int (* filter)(const struct dirent *),int (* compare)(const struct dirent **,const struct dirent **))791 static int scandir(
792 	const char *dirname, struct dirent ***namelist,
793 	int (*filter)(const struct dirent*),
794 	int (*compare)(const struct dirent**, const struct dirent**))
795 {
796 	int result;
797 
798 	/* Open directory stream */
799 	DIR *dir = opendir(dirname);
800 	if (!dir) {
801 		/* Cannot open directory */
802 		return /*Error*/ -1;
803 	}
804 
805 	/* Read directory entries to memory */
806 	struct dirent *tmp = NULL;
807 	struct dirent **files = NULL;
808 	size_t size = 0;
809 	size_t allocated = 0;
810 	while (1) {
811 		/* Allocate room for a temporary directory entry */
812 		if (!tmp) {
813 			tmp = (struct dirent*) malloc(sizeof(struct dirent));
814 			if (!tmp)
815 				goto exit_failure;
816 		}
817 
818 		/* Read directory entry to temporary area */
819 		struct dirent *entry;
820 		if (readdir_r(dir, tmp, &entry) != /*OK*/0)
821 			goto exit_failure;
822 
823 		/* Stop if we already read the last directory entry */
824 		if (entry == NULL)
825 			goto exit_success;
826 
827 		/* Determine whether to include the entry in results */
828 		if (filter && !filter(tmp))
829 			continue;
830 
831 		/* Enlarge pointer table to make room for another pointer */
832 		if (size >= allocated) {
833 			/* Compute number of entries in the new table */
834 			size_t num_entries = size * 2 + 16;
835 
836 			/* Allocate new pointer table or enlarge existing */
837 			void *p = realloc(files, sizeof(void*) * num_entries);
838 			if (!p)
839 				goto exit_failure;
840 
841 			/* Got the memory */
842 			files = (dirent**) p;
843 			allocated = num_entries;
844 		}
845 
846 		/* Store the temporary entry to ptr table */
847 		files[size++] = tmp;
848 		tmp = NULL;
849 	}
850 
851 exit_failure:
852 	/* Release allocated file entries */
853 	for (size_t i = 0; i < size; i++) {
854 		free(files[i]);
855 	}
856 
857 	/* Release the pointer table */
858 	free(files);
859 	files = NULL;
860 
861 	/* Exit with error code */
862 	result = /*error*/ -1;
863 	goto exit_status;
864 
865 exit_success:
866 	/* Sort directory entries */
867 	qsort(files, size, sizeof(void*),
868 		(int (*) (const void*, const void*)) compare);
869 
870 	/* Pass pointer table to caller */
871 	if (namelist)
872 		*namelist = files;
873 
874 	/* Return the number of directory entries read */
875 	result = (int) size;
876 
877 exit_status:
878 	/* Release temporary directory entry, if we had one */
879 	free(tmp);
880 
881 	/* Close directory stream */
882 	closedir(dir);
883 	return result;
884 }
885 
886 /* Alphabetical sorting */
alphasort(const struct dirent ** a,const struct dirent ** b)887 static int alphasort(const struct dirent **a, const struct dirent **b)
888 {
889 	return strcoll((*a)->d_name, (*b)->d_name);
890 }
891 
892 /* Sort versions */
versionsort(const struct dirent ** a,const struct dirent ** b)893 static int versionsort(const struct dirent **a, const struct dirent **b)
894 {
895 	return strverscmp((*a)->d_name, (*b)->d_name);
896 }
897 
898 /* Compare strings */
strverscmp(const char * a,const char * b)899 static int strverscmp(const char *a, const char *b)
900 {
901 	size_t i = 0;
902 	size_t j;
903 
904 	/* Find first difference */
905 	while (a[i] == b[i]) {
906 		if (a[i] == '\0') {
907 			/* No difference */
908 			return 0;
909 		}
910 		++i;
911 	}
912 
913 	/* Count backwards and find the leftmost digit */
914 	j = i;
915 	while (j > 0 && isdigit((unsigned char)a[j-1])) {
916 		--j;
917 	}
918 
919 	/* Determine mode of comparison */
920 	if (a[j] == '0' || b[j] == '0') {
921 		/* Find the next non-zero digit */
922 		while (a[j] == '0' && a[j] == b[j]) {
923 			j++;
924 		}
925 
926 		/* String with more digits is smaller, e.g 002 < 01 */
927 		if (isdigit((unsigned char)a[j])) {
928 			if (!isdigit((unsigned char)b[j])) {
929 				return -1;
930 			}
931 		} else if ((unsigned char)isdigit(b[j])) {
932 			return 1;
933 		}
934 	} else if ((unsigned char)isdigit(a[j]) &&
935 	    isdigit((unsigned char)b[j])) {
936 		/* Numeric comparison */
937 		size_t k1 = j;
938 		size_t k2 = j;
939 
940 		/* Compute number of digits in each string */
941 		while (isdigit((unsigned char)a[k1])) {
942 			k1++;
943 		}
944 		while (isdigit((unsigned char)b[k2])) {
945 			k2++;
946 		}
947 
948 		/* Number with more digits is bigger, e.g 999 < 1000 */
949 		if (k1 < k2)
950 			return -1;
951 		else if (k1 > k2)
952 			return 1;
953 	}
954 
955 	/* Alphabetical comparison */
956 	return (int) ((unsigned char) a[i]) - ((unsigned char) b[i]);
957 }
958 
959 /* Convert multi-byte string to wide character string */
960 #if !defined(_MSC_VER) || _MSC_VER < 1400
dirent_mbstowcs_s(size_t * pReturnValue,wchar_t * wcstr,size_t sizeInWords,const char * mbstr,size_t count)961 static int dirent_mbstowcs_s(
962 	size_t *pReturnValue, wchar_t *wcstr,
963 	size_t sizeInWords, const char *mbstr, size_t count)
964 {
965 	/* Older Visual Studio or non-Microsoft compiler */
966 	size_t n = mbstowcs(wcstr, mbstr, sizeInWords);
967 	if (wcstr && n >= count)
968 		return /*error*/ 1;
969 
970 	/* Zero-terminate output buffer */
971 	if (wcstr && sizeInWords) {
972 		if (n >= sizeInWords)
973 			n = sizeInWords - 1;
974 		wcstr[n] = 0;
975 	}
976 
977 	/* Length of multi-byte string with zero terminator */
978 	if (pReturnValue) {
979 		*pReturnValue = n + 1;
980 	}
981 
982 	/* Success */
983 	return 0;
984 }
985 #endif
986 
987 /* Convert wide-character string to multi-byte string */
988 #if !defined(_MSC_VER) || _MSC_VER < 1400
dirent_wcstombs_s(size_t * pReturnValue,char * mbstr,size_t sizeInBytes,const wchar_t * wcstr,size_t count)989 static int dirent_wcstombs_s(
990 	size_t *pReturnValue, char *mbstr,
991 	size_t sizeInBytes, const wchar_t *wcstr, size_t count)
992 {
993 	/* Older Visual Studio or non-Microsoft compiler */
994 	size_t n = wcstombs(mbstr, wcstr, sizeInBytes);
995 	if (mbstr && n >= count)
996 		return /*error*/1;
997 
998 	/* Zero-terminate output buffer */
999 	if (mbstr && sizeInBytes) {
1000 		if (n >= sizeInBytes) {
1001 			n = sizeInBytes - 1;
1002 		}
1003 		mbstr[n] = '\0';
1004 	}
1005 
1006 	/* Length of resulting multi-bytes string WITH zero-terminator */
1007 	if (pReturnValue) {
1008 		*pReturnValue = n + 1;
1009 	}
1010 
1011 	/* Success */
1012 	return 0;
1013 }
1014 #endif
1015 
1016 /* Set errno variable */
1017 #if !defined(_MSC_VER) || _MSC_VER < 1400
dirent_set_errno(int error)1018 static void dirent_set_errno(int error)
1019 {
1020 	/* Non-Microsoft compiler or older Microsoft compiler */
1021 	errno = error;
1022 }
1023 #endif
1024 
1025 #ifdef __cplusplus
1026 }
1027 #endif
1028 #endif /*DIRENT_H*/
1029