Collection of DPF-based plugins for packaging
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.

1161 lines
26KB

  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. DWORD n;
  286. wchar_t *p;
  287. /* Must have directory name */
  288. if (dirname == NULL || dirname[0] == '\0') {
  289. dirent_set_errno (ENOENT);
  290. return NULL;
  291. }
  292. /* Allocate new _WDIR structure */
  293. dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
  294. if (!dirp) {
  295. return NULL;
  296. }
  297. /* Reset _WDIR structure */
  298. dirp->handle = INVALID_HANDLE_VALUE;
  299. dirp->patt = NULL;
  300. dirp->cached = 0;
  301. /*
  302. * Compute the length of full path plus zero terminator
  303. *
  304. * Note that on WinRT there's no way to convert relative paths
  305. * into absolute paths, so just assume it is an absolute path.
  306. */
  307. #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  308. /* Desktop */
  309. n = GetFullPathNameW (dirname, 0, NULL, NULL);
  310. #else
  311. /* WinRT */
  312. n = wcslen (dirname);
  313. #endif
  314. /* Allocate room for absolute directory name and search pattern */
  315. dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
  316. if (dirp->patt == NULL) {
  317. goto exit_closedir;
  318. }
  319. /*
  320. * Convert relative directory name to an absolute one. This
  321. * allows rewinddir() to function correctly even when current
  322. * working directory is changed between opendir() and rewinddir().
  323. *
  324. * Note that on WinRT there's no way to convert relative paths
  325. * into absolute paths, so just assume it is an absolute path.
  326. */
  327. #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  328. /* Desktop */
  329. n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
  330. if (n <= 0) {
  331. goto exit_closedir;
  332. }
  333. #else
  334. /* WinRT */
  335. wcsncpy_s (dirp->patt, n+1, dirname, n);
  336. #endif
  337. /* Append search pattern \* to the directory name */
  338. p = dirp->patt + n;
  339. switch (p[-1]) {
  340. case '\\':
  341. case '/':
  342. case ':':
  343. /* Directory ends in path separator, e.g. c:\temp\ */
  344. /*NOP*/;
  345. break;
  346. default:
  347. /* Directory name doesn't end in path separator */
  348. *p++ = '\\';
  349. }
  350. *p++ = '*';
  351. *p = '\0';
  352. /* Open directory stream and retrieve the first entry */
  353. if (!dirent_first (dirp)) {
  354. goto exit_closedir;
  355. }
  356. /* Success */
  357. return dirp;
  358. /* Failure */
  359. exit_closedir:
  360. _wclosedir (dirp);
  361. return NULL;
  362. }
  363. /*
  364. * Read next directory entry.
  365. *
  366. * Returns pointer to static directory entry which may be overwritten by
  367. * subsequent calls to _wreaddir().
  368. */
  369. static struct _wdirent*
  370. _wreaddir(
  371. _WDIR *dirp)
  372. {
  373. struct _wdirent *entry;
  374. /*
  375. * Read directory entry to buffer. We can safely ignore the return value
  376. * as entry will be set to NULL in case of error.
  377. */
  378. (void) _wreaddir_r (dirp, &dirp->ent, &entry);
  379. /* Return pointer to statically allocated directory entry */
  380. return entry;
  381. }
  382. /*
  383. * Read next directory entry.
  384. *
  385. * Returns zero on success. If end of directory stream is reached, then sets
  386. * result to NULL and returns zero.
  387. */
  388. static int
  389. _wreaddir_r(
  390. _WDIR *dirp,
  391. struct _wdirent *entry,
  392. struct _wdirent **result)
  393. {
  394. WIN32_FIND_DATAW *datap;
  395. /* Read next directory entry */
  396. datap = dirent_next (dirp);
  397. if (datap) {
  398. size_t n;
  399. DWORD attr;
  400. /*
  401. * Copy file name as wide-character string. If the file name is too
  402. * long to fit in to the destination buffer, then truncate file name
  403. * to PATH_MAX characters and zero-terminate the buffer.
  404. */
  405. n = 0;
  406. while (n < PATH_MAX && datap->cFileName[n] != 0) {
  407. entry->d_name[n] = datap->cFileName[n];
  408. n++;
  409. }
  410. entry->d_name[n] = 0;
  411. /* Length of file name excluding zero terminator */
  412. entry->d_namlen = n;
  413. /* File type */
  414. attr = datap->dwFileAttributes;
  415. if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
  416. entry->d_type = DT_CHR;
  417. } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  418. entry->d_type = DT_DIR;
  419. } else {
  420. entry->d_type = DT_REG;
  421. }
  422. /* Reset dummy fields */
  423. entry->d_ino = 0;
  424. entry->d_off = 0;
  425. entry->d_reclen = sizeof (struct _wdirent);
  426. /* Set result address */
  427. *result = entry;
  428. } else {
  429. /* Return NULL to indicate end of directory */
  430. *result = NULL;
  431. }
  432. return /*OK*/0;
  433. }
  434. /*
  435. * Close directory stream opened by opendir() function. This invalidates the
  436. * DIR structure as well as any directory entry read previously by
  437. * _wreaddir().
  438. */
  439. static int
  440. _wclosedir(
  441. _WDIR *dirp)
  442. {
  443. int ok;
  444. if (dirp) {
  445. /* Release search handle */
  446. if (dirp->handle != INVALID_HANDLE_VALUE) {
  447. FindClose (dirp->handle);
  448. }
  449. /* Release search pattern */
  450. free (dirp->patt);
  451. /* Release directory structure */
  452. free (dirp);
  453. ok = /*success*/0;
  454. } else {
  455. /* Invalid directory stream */
  456. dirent_set_errno (EBADF);
  457. ok = /*failure*/-1;
  458. }
  459. return ok;
  460. }
  461. /*
  462. * Rewind directory stream such that _wreaddir() returns the very first
  463. * file name again.
  464. */
  465. static void
  466. _wrewinddir(
  467. _WDIR* dirp)
  468. {
  469. if (dirp) {
  470. /* Release existing search handle */
  471. if (dirp->handle != INVALID_HANDLE_VALUE) {
  472. FindClose (dirp->handle);
  473. }
  474. /* Open new search handle */
  475. dirent_first (dirp);
  476. }
  477. }
  478. /* Get first directory entry (internal) */
  479. static WIN32_FIND_DATAW*
  480. dirent_first(
  481. _WDIR *dirp)
  482. {
  483. WIN32_FIND_DATAW *datap;
  484. DWORD error;
  485. /* Open directory and retrieve the first entry */
  486. dirp->handle = FindFirstFileExW(
  487. dirp->patt, FindExInfoStandard, &dirp->data,
  488. FindExSearchNameMatch, NULL, 0);
  489. if (dirp->handle != INVALID_HANDLE_VALUE) {
  490. /* a directory entry is now waiting in memory */
  491. datap = &dirp->data;
  492. dirp->cached = 1;
  493. } else {
  494. /* Failed to open directory: no directory entry in memory */
  495. dirp->cached = 0;
  496. datap = NULL;
  497. /* Set error code */
  498. error = GetLastError ();
  499. switch (error) {
  500. case ERROR_ACCESS_DENIED:
  501. /* No read access to directory */
  502. dirent_set_errno (EACCES);
  503. break;
  504. case ERROR_DIRECTORY:
  505. /* Directory name is invalid */
  506. dirent_set_errno (ENOTDIR);
  507. break;
  508. case ERROR_PATH_NOT_FOUND:
  509. default:
  510. /* Cannot find the file */
  511. dirent_set_errno (ENOENT);
  512. }
  513. }
  514. return datap;
  515. }
  516. /*
  517. * Get next directory entry (internal).
  518. *
  519. * Returns
  520. */
  521. static WIN32_FIND_DATAW*
  522. dirent_next(
  523. _WDIR *dirp)
  524. {
  525. WIN32_FIND_DATAW *p;
  526. /* Get next directory entry */
  527. if (dirp->cached != 0) {
  528. /* A valid directory entry already in memory */
  529. p = &dirp->data;
  530. dirp->cached = 0;
  531. } else if (dirp->handle != INVALID_HANDLE_VALUE) {
  532. /* Get the next directory entry from stream */
  533. if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
  534. /* Got a file */
  535. p = &dirp->data;
  536. } else {
  537. /* The very last entry has been processed or an error occurred */
  538. FindClose (dirp->handle);
  539. dirp->handle = INVALID_HANDLE_VALUE;
  540. p = NULL;
  541. }
  542. } else {
  543. /* End of directory stream reached */
  544. p = NULL;
  545. }
  546. return p;
  547. }
  548. /*
  549. * Open directory stream using plain old C-string.
  550. */
  551. static DIR*
  552. opendir(
  553. const char *dirname)
  554. {
  555. struct DIR *dirp;
  556. /* Must have directory name */
  557. if (dirname == NULL || dirname[0] == '\0') {
  558. dirent_set_errno (ENOENT);
  559. return NULL;
  560. }
  561. /* Allocate memory for DIR structure */
  562. dirp = (DIR*) malloc (sizeof (struct DIR));
  563. if (!dirp) {
  564. return NULL;
  565. }
  566. {
  567. int error;
  568. wchar_t wname[PATH_MAX + 1];
  569. size_t n;
  570. /* Convert directory name to wide-character string */
  571. error = dirent_mbstowcs_s(
  572. &n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1);
  573. if (error) {
  574. /*
  575. * Cannot convert file name to wide-character string. This
  576. * occurs if the string contains invalid multi-byte sequences or
  577. * the output buffer is too small to contain the resulting
  578. * string.
  579. */
  580. goto exit_free;
  581. }
  582. /* Open directory stream using wide-character name */
  583. dirp->wdirp = _wopendir (wname);
  584. if (!dirp->wdirp) {
  585. goto exit_free;
  586. }
  587. }
  588. /* Success */
  589. return dirp;
  590. /* Failure */
  591. exit_free:
  592. free (dirp);
  593. return NULL;
  594. }
  595. /*
  596. * Read next directory entry.
  597. */
  598. static struct dirent*
  599. readdir(
  600. DIR *dirp)
  601. {
  602. struct dirent *entry;
  603. /*
  604. * Read directory entry to buffer. We can safely ignore the return value
  605. * as entry will be set to NULL in case of error.
  606. */
  607. (void) readdir_r (dirp, &dirp->ent, &entry);
  608. /* Return pointer to statically allocated directory entry */
  609. return entry;
  610. }
  611. /*
  612. * Read next directory entry into called-allocated buffer.
  613. *
  614. * Returns zero on success. If the end of directory stream is reached, then
  615. * sets result to NULL and returns zero.
  616. */
  617. static int
  618. readdir_r(
  619. DIR *dirp,
  620. struct dirent *entry,
  621. struct dirent **result)
  622. {
  623. WIN32_FIND_DATAW *datap;
  624. /* Read next directory entry */
  625. datap = dirent_next (dirp->wdirp);
  626. if (datap) {
  627. size_t n;
  628. int error;
  629. /* Attempt to convert file name to multi-byte string */
  630. error = dirent_wcstombs_s(
  631. &n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1);
  632. /*
  633. * If the file name cannot be represented by a multi-byte string,
  634. * then attempt to use old 8+3 file name. This allows traditional
  635. * Unix-code to access some file names despite of unicode
  636. * characters, although file names may seem unfamiliar to the user.
  637. *
  638. * Be ware that the code below cannot come up with a short file
  639. * name unless the file system provides one. At least
  640. * VirtualBox shared folders fail to do this.
  641. */
  642. if (error && datap->cAlternateFileName[0] != '\0') {
  643. error = dirent_wcstombs_s(
  644. &n, entry->d_name, PATH_MAX + 1,
  645. datap->cAlternateFileName, PATH_MAX + 1);
  646. }
  647. if (!error) {
  648. DWORD attr;
  649. /* Length of file name excluding zero terminator */
  650. entry->d_namlen = n - 1;
  651. /* File attributes */
  652. attr = datap->dwFileAttributes;
  653. if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
  654. entry->d_type = DT_CHR;
  655. } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
  656. entry->d_type = DT_DIR;
  657. } else {
  658. entry->d_type = DT_REG;
  659. }
  660. /* Reset dummy fields */
  661. entry->d_ino = 0;
  662. entry->d_off = 0;
  663. entry->d_reclen = sizeof (struct dirent);
  664. } else {
  665. /*
  666. * Cannot convert file name to multi-byte string so construct
  667. * an erroneous directory entry and return that. Note that
  668. * we cannot return NULL as that would stop the processing
  669. * of directory entries completely.
  670. */
  671. entry->d_name[0] = '?';
  672. entry->d_name[1] = '\0';
  673. entry->d_namlen = 1;
  674. entry->d_type = DT_UNKNOWN;
  675. entry->d_ino = 0;
  676. entry->d_off = -1;
  677. entry->d_reclen = 0;
  678. }
  679. /* Return pointer to directory entry */
  680. *result = entry;
  681. } else {
  682. /* No more directory entries */
  683. *result = NULL;
  684. }
  685. return /*OK*/0;
  686. }
  687. /*
  688. * Close directory stream.
  689. */
  690. static int
  691. closedir(
  692. DIR *dirp)
  693. {
  694. int ok;
  695. if (dirp) {
  696. /* Close wide-character directory stream */
  697. ok = _wclosedir (dirp->wdirp);
  698. dirp->wdirp = NULL;
  699. /* Release multi-byte character version */
  700. free (dirp);
  701. } else {
  702. /* Invalid directory stream */
  703. dirent_set_errno (EBADF);
  704. ok = /*failure*/-1;
  705. }
  706. return ok;
  707. }
  708. /*
  709. * Rewind directory stream to beginning.
  710. */
  711. static void
  712. rewinddir(
  713. DIR* dirp)
  714. {
  715. /* Rewind wide-character string directory stream */
  716. _wrewinddir (dirp->wdirp);
  717. }
  718. /*
  719. * Scan directory for entries.
  720. */
  721. static int
  722. scandir(
  723. const char *dirname,
  724. struct dirent ***namelist,
  725. int (*filter)(const struct dirent*),
  726. int (*compare)(const struct dirent**, const struct dirent**))
  727. {
  728. struct dirent **files = NULL;
  729. size_t size = 0;
  730. size_t allocated = 0;
  731. const size_t init_size = 1;
  732. DIR *dir = NULL;
  733. struct dirent *entry;
  734. struct dirent *tmp = NULL;
  735. size_t i;
  736. int result = 0;
  737. /* Open directory stream */
  738. dir = opendir (dirname);
  739. if (dir) {
  740. /* Read directory entries to memory */
  741. while (1) {
  742. /* Enlarge pointer table to make room for another pointer */
  743. if (size >= allocated) {
  744. void *p;
  745. size_t num_entries;
  746. /* Compute number of entries in the enlarged pointer table */
  747. if (size < init_size) {
  748. /* Allocate initial pointer table */
  749. num_entries = init_size;
  750. } else {
  751. /* Double the size */
  752. num_entries = size * 2;
  753. }
  754. /* Allocate first pointer table or enlarge existing table */
  755. p = realloc (files, sizeof (void*) * num_entries);
  756. if (p != NULL) {
  757. /* Got the memory */
  758. files = (dirent**) p;
  759. allocated = num_entries;
  760. } else {
  761. /* Out of memory */
  762. result = -1;
  763. break;
  764. }
  765. }
  766. /* Allocate room for temporary directory entry */
  767. if (tmp == NULL) {
  768. tmp = (struct dirent*) malloc (sizeof (struct dirent));
  769. if (tmp == NULL) {
  770. /* Cannot allocate temporary directory entry */
  771. result = -1;
  772. break;
  773. }
  774. }
  775. /* Read directory entry to temporary area */
  776. if (readdir_r (dir, tmp, &entry) == /*OK*/0) {
  777. /* Did we get an entry? */
  778. if (entry != NULL) {
  779. int pass;
  780. /* Determine whether to include the entry in result */
  781. if (filter) {
  782. /* Let the filter function decide */
  783. pass = filter (tmp);
  784. } else {
  785. /* No filter function, include everything */
  786. pass = 1;
  787. }
  788. if (pass) {
  789. /* Store the temporary entry to pointer table */
  790. files[size++] = tmp;
  791. tmp = NULL;
  792. /* Keep up with the number of files */
  793. result++;
  794. }
  795. } else {
  796. /*
  797. * End of directory stream reached => sort entries and
  798. * exit.
  799. */
  800. qsort (files, size, sizeof (void*),
  801. (int (*) (const void*, const void*)) compare);
  802. break;
  803. }
  804. } else {
  805. /* Error reading directory entry */
  806. result = /*Error*/ -1;
  807. break;
  808. }
  809. }
  810. } else {
  811. /* Cannot open directory */
  812. result = /*Error*/ -1;
  813. }
  814. /* Release temporary directory entry */
  815. free (tmp);
  816. /* Release allocated memory on error */
  817. if (result < 0) {
  818. for (i = 0; i < size; i++) {
  819. free (files[i]);
  820. }
  821. free (files);
  822. files = NULL;
  823. }
  824. /* Close directory stream */
  825. if (dir) {
  826. closedir (dir);
  827. }
  828. /* Pass pointer table to caller */
  829. if (namelist) {
  830. *namelist = files;
  831. }
  832. return result;
  833. }
  834. /* Alphabetical sorting */
  835. static int
  836. alphasort(
  837. const struct dirent **a, const struct dirent **b)
  838. {
  839. return strcoll ((*a)->d_name, (*b)->d_name);
  840. }
  841. /* Sort versions */
  842. static int
  843. versionsort(
  844. const struct dirent **a, const struct dirent **b)
  845. {
  846. /* FIXME: implement strverscmp and use that */
  847. return alphasort (a, b);
  848. }
  849. /* Convert multi-byte string to wide character string */
  850. static int
  851. dirent_mbstowcs_s(
  852. size_t *pReturnValue,
  853. wchar_t *wcstr,
  854. size_t sizeInWords,
  855. const char *mbstr,
  856. size_t count)
  857. {
  858. int error;
  859. #if defined(_MSC_VER) && _MSC_VER >= 1400
  860. /* Microsoft Visual Studio 2005 or later */
  861. error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count);
  862. #else
  863. /* Older Visual Studio or non-Microsoft compiler */
  864. size_t n;
  865. /* Convert to wide-character string (or count characters) */
  866. n = mbstowcs (wcstr, mbstr, sizeInWords);
  867. if (!wcstr || n < count) {
  868. /* Zero-terminate output buffer */
  869. if (wcstr && sizeInWords) {
  870. if (n >= sizeInWords) {
  871. n = sizeInWords - 1;
  872. }
  873. wcstr[n] = 0;
  874. }
  875. /* Length of resulting multi-byte string WITH zero terminator */
  876. if (pReturnValue) {
  877. *pReturnValue = n + 1;
  878. }
  879. /* Success */
  880. error = 0;
  881. } else {
  882. /* Could not convert string */
  883. error = 1;
  884. }
  885. #endif
  886. return error;
  887. }
  888. /* Convert wide-character string to multi-byte string */
  889. static int
  890. dirent_wcstombs_s(
  891. size_t *pReturnValue,
  892. char *mbstr,
  893. size_t sizeInBytes, /* max size of mbstr */
  894. const wchar_t *wcstr,
  895. size_t count)
  896. {
  897. int error;
  898. #if defined(_MSC_VER) && _MSC_VER >= 1400
  899. /* Microsoft Visual Studio 2005 or later */
  900. error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count);
  901. #else
  902. /* Older Visual Studio or non-Microsoft compiler */
  903. size_t n;
  904. /* Convert to multi-byte string (or count the number of bytes needed) */
  905. n = wcstombs (mbstr, wcstr, sizeInBytes);
  906. if (!mbstr || n < count) {
  907. /* Zero-terminate output buffer */
  908. if (mbstr && sizeInBytes) {
  909. if (n >= sizeInBytes) {
  910. n = sizeInBytes - 1;
  911. }
  912. mbstr[n] = '\0';
  913. }
  914. /* Length of resulting multi-bytes string WITH zero-terminator */
  915. if (pReturnValue) {
  916. *pReturnValue = n + 1;
  917. }
  918. /* Success */
  919. error = 0;
  920. } else {
  921. /* Cannot convert string */
  922. error = 1;
  923. }
  924. #endif
  925. return error;
  926. }
  927. /* Set errno variable */
  928. static void
  929. dirent_set_errno(
  930. int error)
  931. {
  932. #if defined(_MSC_VER) && _MSC_VER >= 1400
  933. /* Microsoft Visual Studio 2005 and later */
  934. _set_errno (error);
  935. #else
  936. /* Non-Microsoft compiler or older Microsoft compiler */
  937. errno = error;
  938. #endif
  939. }
  940. #ifdef __cplusplus
  941. }
  942. #endif
  943. #endif /*DIRENT_H*/