- errno = 0;
- if (*ctx == NULL)
- {
- *ctx = (LP_DIR_CTX *)malloc(sizeof(LP_DIR_CTX));
- if (*ctx == NULL)
- {
- errno = ENOMEM;
- free(*ctx);
- return 0;
- }
- memset(*ctx, '\0', sizeof(LP_DIR_CTX));
-
-#ifdef LP_SYS_WINCE
- {
- WCHAR *wdir = NULL;
- size_t index = 0;
-
- wdir = (WCHAR *)malloc((strlen(directory) + 1) * 2);
- if (wdir == NULL)
- {
- errno = ENOMEM;
- free(*ctx);
- free(wdir);
- return 0;
- }
-
- for (index = 0; index < strlen(directory) + 1; index++)
- wdir[index] = (short)directory[index];
-
- (*ctx)->handle = FindFirstFile(wdir, &(*ctx)->ctx);
-
- free(wdir);
- }
-#else
- (*ctx)->handle = FindFirstFile(directory, &(*ctx)->ctx);
+ errno = 0;
+ if (*ctx == NULL) {
+ const char *extdir = directory;
+ char *extdirbuf = NULL;
+ size_t dirlen = strlen(directory);
+
+ if (dirlen == 0) {
+ errno = ENOENT;
+ return 0;
+ }
+
+ *ctx = malloc(sizeof(**ctx));
+ if (*ctx == NULL) {
+ errno = ENOMEM;
+ return 0;
+ }
+ memset(*ctx, 0, sizeof(**ctx));
+
+ if (directory[dirlen - 1] != '*') {
+ extdirbuf = (char *)malloc(dirlen + 3);
+ if (extdirbuf == NULL) {
+ free(*ctx);
+ *ctx = NULL;
+ errno = ENOMEM;
+ return 0;
+ }
+ if (directory[dirlen - 1] != '/' && directory[dirlen - 1] != '\\')
+ extdir = strcat(strcpy(extdirbuf, directory), "/*");
+ else
+ extdir = strcat(strcpy(extdirbuf, directory), "*");
+ }
+
+ if (sizeof(TCHAR) != sizeof(char)) {
+ TCHAR *wdir = NULL;
+ /* len_0 denotes string length *with* trailing 0 */
+ size_t index = 0, len_0 = strlen(extdir) + 1;
+
+ wdir = (TCHAR *)calloc(len_0, sizeof(TCHAR));
+ if (wdir == NULL) {
+ if (extdirbuf != NULL) {
+ free(extdirbuf);
+ }
+ free(*ctx);
+ *ctx = NULL;
+ errno = ENOMEM;
+ return 0;
+ }
+#ifdef LP_MULTIBYTE_AVAILABLE
+ if (!MultiByteToWideChar
+ (CP_ACP, 0, extdir, len_0, (WCHAR *)wdir, len_0))