🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1166 lines
26 KiB

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