2 * DOS file system functions
4 * Copyright 1993 Erik Bos
5 * Copyright 1996 Alexandre Julliard
13 #ifdef HAVE_SYS_ERRNO_H
14 #include <sys/errno.h>
20 #include <sys/ioctl.h>
26 #include "wine/winbase16.h"
27 #include "wine/unicode.h"
28 #include "wine/winestring.h"
37 #include "debugtools.h"
39 DEFAULT_DEBUG_CHANNEL(dosfs);
40 DECLARE_DEBUG_CHANNEL(file);
42 /* Define the VFAT ioctl to get both short and long file names */
43 /* FIXME: is it possible to get this to work on other systems? */
45 /* We want the real kernel dirent structure, not the libc one */
50 unsigned short d_reclen;
54 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
57 #undef VFAT_IOCTL_READDIR_BOTH /* just in case... */
60 /* Chars we don't want to see in DOS file names */
61 #define INVALID_DOS_CHARS "*?<>|\"+=,;[] \345"
63 static const DOS_DEVICE DOSFS_Devices[] =
64 /* name, device flags (see Int 21/AX=0x4400) */
78 { "SCSIMGR$", 0xc0c0 },
82 #define GET_DRIVE(path) \
83 (((path)[1] == ':') ? toupper((path)[0]) - 'A' : DOSFS_CurDrive)
85 /* Directory info for DOSFS_ReadDir */
89 #ifdef VFAT_IOCTL_READDIR_BOTH
92 KERNEL_DIRENT dirent[2];
96 /* Info structure for FindFirstFile handle */
110 /***********************************************************************
113 * Return 1 if Unix file 'name' is also a valid MS-DOS name
114 * (i.e. contains only valid DOS chars, lower-case only, fits in 8.3 format).
115 * File name can be terminated by '\0', '\\' or '/'.
117 static int DOSFS_ValidDOSName( const char *name, int ignore_case )
119 static const char invalid_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" INVALID_DOS_CHARS;
120 const char *p = name;
121 const char *invalid = ignore_case ? (invalid_chars + 26) : invalid_chars;
126 /* Check for "." and ".." */
129 /* All other names beginning with '.' are invalid */
130 return (IS_END_OF_NAME(*p));
132 while (!IS_END_OF_NAME(*p))
134 if (strchr( invalid, *p )) return 0; /* Invalid char */
135 if (*p == '.') break; /* Start of the extension */
136 if (++len > 8) return 0; /* Name too long */
139 if (*p != '.') return 1; /* End of name */
141 if (IS_END_OF_NAME(*p)) return 0; /* Empty extension not allowed */
143 while (!IS_END_OF_NAME(*p))
145 if (strchr( invalid, *p )) return 0; /* Invalid char */
146 if (*p == '.') return 0; /* Second extension not allowed */
147 if (++len > 3) return 0; /* Extension too long */
154 /***********************************************************************
155 * DOSFS_ToDosFCBFormat
157 * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
158 * expanding wild cards and converting to upper-case in the process.
159 * File name can be terminated by '\0', '\\' or '/'.
160 * Return FALSE if the name is not a valid DOS name.
161 * 'buffer' must be at least 12 characters long.
163 BOOL DOSFS_ToDosFCBFormat( LPCSTR name, LPSTR buffer )
165 static const char invalid_chars[] = INVALID_DOS_CHARS;
166 const char *p = name;
169 /* Check for "." and ".." */
173 strcpy( buffer, ". " );
179 return (!*p || (*p == '/') || (*p == '\\'));
182 for (i = 0; i < 8; i++)
199 if (strchr( invalid_chars, *p )) return FALSE;
200 buffer[i] = toupper(*p);
208 /* Skip all chars after wildcard up to first dot */
209 while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
213 /* Check if name too long */
214 if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
216 if (*p == '.') p++; /* Skip dot */
218 for (i = 8; i < 11; i++)
228 return FALSE; /* Second extension not allowed */
236 if (strchr( invalid_chars, *p )) return FALSE;
237 buffer[i] = toupper(*p);
244 /* at most 3 character of the extension are processed
245 * is something behind this ?
247 while (*p == '*' || *p == ' ') p++; /* skip wildcards and spaces */
248 return IS_END_OF_NAME(*p);
252 /***********************************************************************
253 * DOSFS_ToDosDTAFormat
255 * Convert a file name from FCB to DTA format (name.ext, null-terminated)
256 * converting to upper-case in the process.
257 * File name can be terminated by '\0', '\\' or '/'.
258 * 'buffer' must be at least 13 characters long.
260 static void DOSFS_ToDosDTAFormat( LPCSTR name, LPSTR buffer )
264 memcpy( buffer, name, 8 );
265 for (p = buffer + 8; (p > buffer) && (p[-1] == ' '); p--);
267 memcpy( p, name + 8, 3 );
268 for (p += 3; p[-1] == ' '; p--);
269 if (p[-1] == '.') p--;
274 /***********************************************************************
277 * Check a DOS file name against a mask (both in FCB format).
279 static int DOSFS_MatchShort( const char *mask, const char *name )
282 for (i = 11; i > 0; i--, mask++, name++)
283 if ((*mask != '?') && (*mask != *name)) return 0;
288 /***********************************************************************
291 * Check a long file name against a mask.
293 * Tests (done in W95 DOS shell - case insensitive):
294 * *.txt test1.test.txt *
296 * *.t??????.t* test1.ta.tornado.txt *
297 * *tornado* test1.ta.tornado.txt *
298 * t*t test1.ta.tornado.txt *
300 * ?est??? test1.txt -
301 * *test1.txt* test1.txt *
302 * h?l?o*t.dat hellothisisatest.dat *
304 static int DOSFS_MatchLong( const char *mask, const char *name,
307 const char *lastjoker = NULL;
308 const char *next_to_retry = NULL;
310 if (!strcmp( mask, "*.*" )) return 1;
311 while (*name && *mask)
316 while (*mask == '*') mask++; /* Skip consecutive '*' */
318 if (!*mask) return 1; /* end of mask is all '*', so match */
320 /* skip to the next match after the joker(s) */
321 if (case_sensitive) while (*name && (*name != *mask)) name++;
322 else while (*name && (toupper(*name) != toupper(*mask))) name++;
325 next_to_retry = name;
327 else if (*mask != '?')
332 if (*mask != *name) mismatch = 1;
336 if (toupper(*mask) != toupper(*name)) mismatch = 1;
350 else /* mismatch ! */
352 if (lastjoker) /* we had an '*', so we can try unlimitedly */
356 /* this scan sequence was a mismatch, so restart
357 * 1 char after the first char we checked last time */
359 name = next_to_retry;
362 return 0; /* bad luck */
371 while ((*mask == '.') || (*mask == '*'))
372 mask++; /* Ignore trailing '.' or '*' in mask */
373 return (!*name && !*mask);
377 /***********************************************************************
380 static DOS_DIR *DOSFS_OpenDir( LPCSTR path )
382 DOS_DIR *dir = HeapAlloc( GetProcessHeap(), 0, sizeof(*dir) );
385 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
389 /* Treat empty path as root directory. This simplifies path split into
390 directory and mask in several other places */
391 if (!*path) path = "/";
393 #ifdef VFAT_IOCTL_READDIR_BOTH
395 /* Check if the VFAT ioctl is supported on this directory */
397 if ((dir->fd = open( path, O_RDONLY )) != -1)
399 if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) == -1)
406 /* Set the file pointer back at the start of the directory */
407 lseek( dir->fd, 0, SEEK_SET );
412 #endif /* VFAT_IOCTL_READDIR_BOTH */
414 /* Now use the standard opendir/readdir interface */
416 if (!(dir->dir = opendir( path )))
418 HeapFree( GetProcessHeap(), 0, dir );
425 /***********************************************************************
428 static void DOSFS_CloseDir( DOS_DIR *dir )
430 #ifdef VFAT_IOCTL_READDIR_BOTH
431 if (dir->fd != -1) close( dir->fd );
432 #endif /* VFAT_IOCTL_READDIR_BOTH */
433 if (dir->dir) closedir( dir->dir );
434 HeapFree( GetProcessHeap(), 0, dir );
438 /***********************************************************************
441 static BOOL DOSFS_ReadDir( DOS_DIR *dir, LPCSTR *long_name,
444 struct dirent *dirent;
446 #ifdef VFAT_IOCTL_READDIR_BOTH
449 if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) != -1) {
450 if (!dir->dirent[0].d_reclen) return FALSE;
451 if (!DOSFS_ToDosFCBFormat( dir->dirent[0].d_name, dir->short_name ))
452 dir->short_name[0] = '\0';
453 *short_name = dir->short_name;
454 if (dir->dirent[1].d_name[0]) *long_name = dir->dirent[1].d_name;
455 else *long_name = dir->dirent[0].d_name;
459 #endif /* VFAT_IOCTL_READDIR_BOTH */
461 if (!(dirent = readdir( dir->dir ))) return FALSE;
462 *long_name = dirent->d_name;
468 /***********************************************************************
471 * Transform a Unix file name into a hashed DOS name. If the name is a valid
472 * DOS name, it is converted to upper-case; otherwise it is replaced by a
473 * hashed version that fits in 8.3 format.
474 * File name can be terminated by '\0', '\\' or '/'.
475 * 'buffer' must be at least 13 characters long.
477 static void DOSFS_Hash( LPCSTR name, LPSTR buffer, BOOL dir_format,
480 static const char invalid_chars[] = INVALID_DOS_CHARS "~.";
481 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
488 if (dir_format) strcpy( buffer, " " );
490 if (DOSFS_ValidDOSName( name, ignore_case ))
492 /* Check for '.' and '..' */
496 if (!dir_format) buffer[1] = buffer[2] = '\0';
497 if (name[1] == '.') buffer[1] = '.';
501 /* Simply copy the name, converting to uppercase */
503 for (dst = buffer; !IS_END_OF_NAME(*name) && (*name != '.'); name++)
504 *dst++ = toupper(*name);
507 if (dir_format) dst = buffer + 8;
509 for (name++; !IS_END_OF_NAME(*name); name++)
510 *dst++ = toupper(*name);
512 if (!dir_format) *dst = '\0';
516 /* Compute the hash code of the file name */
517 /* If you know something about hash functions, feel free to */
518 /* insert a better algorithm here... */
521 for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
522 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p) ^ (tolower(p[1]) << 8);
523 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p); /* Last character*/
527 for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
528 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
529 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
532 /* Find last dot for start of the extension */
533 for (p = name+1, ext = NULL; !IS_END_OF_NAME(*p); p++)
534 if (*p == '.') ext = p;
535 if (ext && IS_END_OF_NAME(ext[1]))
536 ext = NULL; /* Empty extension ignored */
538 /* Copy first 4 chars, replacing invalid chars with '_' */
539 for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
541 if (IS_END_OF_NAME(*p) || (p == ext)) break;
542 *dst++ = strchr( invalid_chars, *p ) ? '_' : toupper(*p);
544 /* Pad to 5 chars with '~' */
545 while (i-- >= 0) *dst++ = '~';
547 /* Insert hash code converted to 3 ASCII chars */
548 *dst++ = hash_chars[(hash >> 10) & 0x1f];
549 *dst++ = hash_chars[(hash >> 5) & 0x1f];
550 *dst++ = hash_chars[hash & 0x1f];
552 /* Copy the first 3 chars of the extension (if any) */
555 if (!dir_format) *dst++ = '.';
556 for (i = 3, ext++; (i > 0) && !IS_END_OF_NAME(*ext); i--, ext++)
557 *dst++ = strchr( invalid_chars, *ext ) ? '_' : toupper(*ext);
559 if (!dir_format) *dst = '\0';
563 /***********************************************************************
566 * Find the Unix file name in a given directory that corresponds to
567 * a file name (either in Unix or DOS format).
568 * File name can be terminated by '\0', '\\' or '/'.
569 * Return TRUE if OK, FALSE if no file name matches.
571 * 'long_buf' must be at least 'long_len' characters long. If the long name
572 * turns out to be larger than that, the function returns FALSE.
573 * 'short_buf' must be at least 13 characters long.
575 BOOL DOSFS_FindUnixName( LPCSTR path, LPCSTR name, LPSTR long_buf,
576 INT long_len, LPSTR short_buf, BOOL ignore_case)
579 LPCSTR long_name, short_name;
580 char dos_name[12], tmp_buf[13];
583 const char *p = strchr( name, '/' );
584 int len = p ? (int)(p - name) : strlen(name);
585 if ((p = strchr( name, '\\' ))) len = min( (int)(p - name), len );
586 /* Ignore trailing dots and spaces */
587 while (len > 1 && (name[len-1] == '.' || name[len-1] == ' ')) len--;
588 if (long_len < len + 1) return FALSE;
590 TRACE("%s,%s\n", path, name );
592 if (!DOSFS_ToDosFCBFormat( name, dos_name )) dos_name[0] = '\0';
594 if (!(dir = DOSFS_OpenDir( path )))
596 WARN("(%s,%s): can't open dir: %s\n",
597 path, name, strerror(errno) );
601 while ((ret = DOSFS_ReadDir( dir, &long_name, &short_name )))
603 /* Check against Unix name */
604 if (len == strlen(long_name))
608 if (!strncmp( long_name, name, len )) break;
612 if (!strncasecmp( long_name, name, len )) break;
617 /* Check against hashed DOS name */
620 DOSFS_Hash( long_name, tmp_buf, TRUE, ignore_case );
621 short_name = tmp_buf;
623 if (!strcmp( dos_name, short_name )) break;
628 if (long_buf) strcpy( long_buf, long_name );
632 DOSFS_ToDosDTAFormat( short_name, short_buf );
634 DOSFS_Hash( long_name, short_buf, FALSE, ignore_case );
636 TRACE("(%s,%s) -> %s (%s)\n",
637 path, name, long_name, short_buf ? short_buf : "***");
640 WARN("'%s' not found in '%s'\n", name, path);
641 DOSFS_CloseDir( dir );
646 /***********************************************************************
649 * Check if a DOS file name represents a DOS device and return the device.
651 const DOS_DEVICE *DOSFS_GetDevice( const char *name )
656 if (!name) return NULL; /* if FILE_DupUnixHandle was used */
657 if (name[0] && (name[1] == ':')) name += 2;
658 if ((p = strrchr( name, '/' ))) name = p + 1;
659 if ((p = strrchr( name, '\\' ))) name = p + 1;
660 for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
662 const char *dev = DOSFS_Devices[i].name;
663 if (!strncasecmp( dev, name, strlen(dev) ))
665 p = name + strlen( dev );
666 if (!*p || (*p == '.')) return &DOSFS_Devices[i];
673 /***********************************************************************
674 * DOSFS_GetDeviceByHandle
676 const DOS_DEVICE *DOSFS_GetDeviceByHandle( HFILE hFile )
678 const DOS_DEVICE *ret = NULL;
681 struct get_file_info_request *req = server_alloc_req( sizeof(*req), 0 );
684 if (!server_call( REQ_GET_FILE_INFO ) && (req->type == FILE_TYPE_UNKNOWN))
686 if ((req->attr >= 0) &&
687 (req->attr < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0])))
688 ret = &DOSFS_Devices[req->attr];
696 /**************************************************************************
697 * DOSFS_CreateCommPort
699 static HANDLE DOSFS_CreateCommPort(LPCSTR name, DWORD access)
701 HANDLE ret = INVALID_HANDLE_VALUE;
704 TRACE("%s %lx\n", name, access);
706 PROFILE_GetWineIniString("serialports",name,"",devname,sizeof devname);
710 TRACE("opening %s as %s\n", devname, name);
714 size_t len = strlen(devname);
715 struct create_serial_request *req = server_alloc_req( sizeof(*req), len );
717 req->access = access;
718 req->inherit = 0; /*FIXME*/
719 req->sharing = FILE_SHARE_READ|FILE_SHARE_WRITE;
720 memcpy( server_data_ptr(req), devname, len );
722 if (!(server_call( REQ_CREATE_SERIAL ))) ret = req->handle;
726 TRACE("return %08X\n", ret );
730 /***********************************************************************
733 * Open a DOS device. This might not map 1:1 into the UNIX device concept.
735 HFILE DOSFS_OpenDevice( const char *name, DWORD access )
741 if (!name) return (HFILE)NULL; /* if FILE_DupUnixHandle was used */
742 if (name[0] && (name[1] == ':')) name += 2;
743 if ((p = strrchr( name, '/' ))) name = p + 1;
744 if ((p = strrchr( name, '\\' ))) name = p + 1;
745 for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
747 const char *dev = DOSFS_Devices[i].name;
748 if (!strncasecmp( dev, name, strlen(dev) ))
750 p = name + strlen( dev );
751 if (!*p || (*p == '.')) {
753 if (!strcmp(DOSFS_Devices[i].name,"NUL"))
754 return FILE_CreateFile( "/dev/null", access,
755 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
756 OPEN_EXISTING, 0, -1, TRUE );
757 if (!strcmp(DOSFS_Devices[i].name,"CON")) {
759 switch (access & (GENERIC_READ|GENERIC_WRITE)) {
761 to_dup = GetStdHandle( STD_INPUT_HANDLE );
764 to_dup = GetStdHandle( STD_OUTPUT_HANDLE );
767 FIXME("can't open CON read/write\n");
771 if (!DuplicateHandle( GetCurrentProcess(), to_dup, GetCurrentProcess(),
772 &handle, 0, FALSE, DUPLICATE_SAME_ACCESS ))
773 handle = HFILE_ERROR;
776 if (!strcmp(DOSFS_Devices[i].name,"SCSIMGR$") ||
777 !strcmp(DOSFS_Devices[i].name,"HPSCAN"))
779 return FILE_CreateDevice( i, access, NULL );
782 if( (handle=DOSFS_CreateCommPort(name,access)) )
785 FIXME("device open %s not supported (yet)\n",DOSFS_Devices[i].name);
794 /***********************************************************************
797 * Get the drive specified by a given path name (DOS or Unix format).
799 static int DOSFS_GetPathDrive( const char **name )
802 const char *p = *name;
804 if (*p && (p[1] == ':'))
806 drive = toupper(*p) - 'A';
809 else if (*p == '/') /* Absolute Unix path? */
811 if ((drive = DRIVE_FindDriveRoot( name )) == -1)
813 MESSAGE("Warning: %s not accessible from a DOS drive\n", *name );
814 /* Assume it really was a DOS name */
815 drive = DRIVE_GetCurrentDrive();
818 else drive = DRIVE_GetCurrentDrive();
820 if (!DRIVE_IsValid(drive))
822 SetLastError( ERROR_INVALID_DRIVE );
829 /***********************************************************************
832 * Convert a file name (DOS or mixed DOS/Unix format) to a valid
833 * Unix name / short DOS name pair.
834 * Return FALSE if one of the path components does not exist. The last path
835 * component is only checked if 'check_last' is non-zero.
836 * The buffers pointed to by 'long_buf' and 'short_buf' must be
837 * at least MAX_PATHNAME_LEN long.
839 BOOL DOSFS_GetFullName( LPCSTR name, BOOL check_last, DOS_FULL_NAME *full )
843 char *p_l, *p_s, *root;
845 TRACE("%s (last=%d)\n", name, check_last );
847 if ((full->drive = DOSFS_GetPathDrive( &name )) == -1) return FALSE;
848 flags = DRIVE_GetFlags( full->drive );
850 lstrcpynA( full->long_name, DRIVE_GetRoot( full->drive ),
851 sizeof(full->long_name) );
852 if (full->long_name[1]) root = full->long_name + strlen(full->long_name);
853 else root = full->long_name; /* root directory */
855 strcpy( full->short_name, "A:\\" );
856 full->short_name[0] += full->drive;
858 if ((*name == '\\') || (*name == '/')) /* Absolute path */
860 while ((*name == '\\') || (*name == '/')) name++;
862 else /* Relative path */
864 lstrcpynA( root + 1, DRIVE_GetUnixCwd( full->drive ),
865 sizeof(full->long_name) - (root - full->long_name) - 1 );
866 if (root[1]) *root = '/';
867 lstrcpynA( full->short_name + 3, DRIVE_GetDosCwd( full->drive ),
868 sizeof(full->short_name) - 3 );
871 p_l = full->long_name[1] ? full->long_name + strlen(full->long_name)
873 p_s = full->short_name[3] ? full->short_name + strlen(full->short_name)
874 : full->short_name + 2;
877 while (*name && found)
879 /* Check for '.' and '..' */
883 if (IS_END_OF_NAME(name[1]))
886 while ((*name == '\\') || (*name == '/')) name++;
889 else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
892 while ((*name == '\\') || (*name == '/')) name++;
893 while ((p_l > root) && (*p_l != '/')) p_l--;
894 while ((p_s > full->short_name + 2) && (*p_s != '\\')) p_s--;
895 *p_l = *p_s = '\0'; /* Remove trailing separator */
900 /* Make sure buffers are large enough */
902 if ((p_s >= full->short_name + sizeof(full->short_name) - 14) ||
903 (p_l >= full->long_name + sizeof(full->long_name) - 1))
905 SetLastError( ERROR_PATH_NOT_FOUND );
909 /* Get the long and short name matching the file name */
911 if ((found = DOSFS_FindUnixName( full->long_name, name, p_l + 1,
912 sizeof(full->long_name) - (p_l - full->long_name) - 1,
913 p_s + 1, !(flags & DRIVE_CASE_SENSITIVE) )))
919 while (!IS_END_OF_NAME(*name)) name++;
921 else if (!check_last)
925 while (!IS_END_OF_NAME(*name) &&
926 (p_s < full->short_name + sizeof(full->short_name) - 1) &&
927 (p_l < full->long_name + sizeof(full->long_name) - 1))
929 *p_s++ = tolower(*name);
930 /* If the drive is case-sensitive we want to create new */
931 /* files in lower-case otherwise we can't reopen them */
932 /* under the same short name. */
933 if (flags & DRIVE_CASE_SENSITIVE) *p_l++ = tolower(*name);
937 /* Ignore trailing dots and spaces */
938 while(p_l[-1] == '.' || p_l[-1] == ' ') {
944 while ((*name == '\\') || (*name == '/')) name++;
951 SetLastError( ERROR_FILE_NOT_FOUND );
954 if (*name) /* Not last */
956 SetLastError( ERROR_PATH_NOT_FOUND );
960 if (!full->long_name[0]) strcpy( full->long_name, "/" );
961 if (!full->short_name[2]) strcpy( full->short_name + 2, "\\" );
962 TRACE("returning %s = %s\n", full->long_name, full->short_name );
967 /***********************************************************************
968 * GetShortPathNameA (KERNEL32.271)
972 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
973 * *longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
975 * more observations ( with NT 3.51 (WinDD) ):
976 * longpath <= 8.3 -> just copy longpath to shortpath
978 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
979 * b) file does exist -> set the short filename.
980 * - trailing slashes are reproduced in the short name, even if the
981 * file is not a directory
982 * - the absolute/relative path of the short name is reproduced like found
984 * - longpath and shortpath may have the same adress
987 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath,
990 DOS_FULL_NAME full_name;
992 DWORD sp = 0, lp = 0;
996 TRACE("%s\n", debugstr_a(longpath));
999 SetLastError(ERROR_INVALID_PARAMETER);
1003 SetLastError(ERROR_BAD_PATHNAME);
1007 if ( ( tmpshortpath = HeapAlloc ( GetProcessHeap(), 0, MAX_PATHNAME_LEN ) ) == NULL ) {
1008 SetLastError ( ERROR_NOT_ENOUGH_MEMORY );
1012 /* check for drive letter */
1013 if ( longpath[1] == ':' ) {
1014 tmpshortpath[0] = longpath[0];
1015 tmpshortpath[1] = ':';
1019 if ( ( drive = DOSFS_GetPathDrive ( &longpath )) == -1 ) return 0;
1020 flags = DRIVE_GetFlags ( drive );
1022 while ( longpath[lp] ) {
1024 /* check for path delimiters and reproduce them */
1025 if ( longpath[lp] == '\\' || longpath[lp] == '/' ) {
1026 if (!sp || tmpshortpath[sp-1]!= '\\')
1028 /* strip double "\\" */
1029 tmpshortpath[sp] = '\\';
1032 tmpshortpath[sp]=0;/*terminate string*/
1037 tmplen = strcspn ( longpath + lp, "\\/" );
1038 lstrcpynA ( tmpshortpath+sp, longpath + lp, tmplen+1 );
1040 /* Check, if the current element is a valid dos name */
1041 if ( DOSFS_ValidDOSName ( longpath + lp, !(flags & DRIVE_CASE_SENSITIVE) ) ) {
1047 /* Check if the file exists and use the existing file name */
1048 if ( DOSFS_GetFullName ( tmpshortpath, TRUE, &full_name ) ) {
1049 strcpy( tmpshortpath+sp, strrchr ( full_name.short_name, '\\' ) + 1 );
1050 sp += strlen ( tmpshortpath+sp );
1055 TRACE("not found!\n" );
1056 SetLastError ( ERROR_FILE_NOT_FOUND );
1059 tmpshortpath[sp] = 0;
1061 lstrcpynA ( shortpath, tmpshortpath, shortlen );
1062 TRACE("returning %s\n", debugstr_a(shortpath) );
1063 tmplen = strlen ( tmpshortpath );
1064 HeapFree ( GetProcessHeap(), 0, tmpshortpath );
1070 /***********************************************************************
1071 * GetShortPathNameW (KERNEL32.272)
1073 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath,
1076 LPSTR longpathA, shortpathA;
1079 longpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, longpath );
1080 shortpathA = HeapAlloc ( GetProcessHeap(), 0, shortlen );
1082 ret = GetShortPathNameA ( longpathA, shortpathA, shortlen );
1083 lstrcpynAtoW ( shortpath, shortpathA, shortlen );
1085 HeapFree( GetProcessHeap(), 0, longpathA );
1086 HeapFree( GetProcessHeap(), 0, shortpathA );
1092 /***********************************************************************
1093 * GetLongPathNameA (KERNEL32.xxx)
1095 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath,
1098 DOS_FULL_NAME full_name;
1099 char *p, *r, *ll, *ss;
1101 if (!DOSFS_GetFullName( shortpath, TRUE, &full_name )) return 0;
1102 lstrcpynA( longpath, full_name.short_name, longlen );
1104 /* Do some hackery to get the long filename. */
1107 ss=longpath+strlen(longpath);
1108 ll=full_name.long_name+strlen(full_name.long_name);
1110 while (ss>=longpath)
1112 /* FIXME: aren't we more paranoid, than needed? */
1113 while ((ss[0]=='\\') && (ss>=longpath)) ss--;
1115 while ((ss[0]!='\\') && (ss>=longpath)) ss--;
1118 /* FIXME: aren't we more paranoid, than needed? */
1119 while ((ll[0]=='/') && (ll>=full_name.long_name)) ll--;
1120 while ((ll[0]!='/') && (ll>=full_name.long_name)) ll--;
1121 if (ll<full_name.long_name)
1123 ERR("Bad longname! (ss=%s ll=%s)\n This should never happen !\n"
1130 /* FIXME: fix for names like "C:\\" (ie. with more '\'s) */
1134 if ((p-longpath)>0) longlen -= (p-longpath);
1135 lstrcpynA( p, ll , longlen);
1137 /* Now, change all '/' to '\' */
1138 for (r=p; r<(p+longlen); r++ )
1139 if (r[0]=='/') r[0]='\\';
1140 return strlen(longpath) - strlen(p) + longlen;
1144 return strlen(longpath);
1148 /***********************************************************************
1149 * GetLongPathNameW (KERNEL32.269)
1151 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath,
1154 DOS_FULL_NAME full_name;
1156 LPSTR shortpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, shortpath );
1158 /* FIXME: is it correct to always return a fully qualified short path? */
1159 if (DOSFS_GetFullName( shortpathA, TRUE, &full_name ))
1161 ret = strlen( full_name.short_name );
1162 lstrcpynAtoW( longpath, full_name.long_name, longlen );
1164 HeapFree( GetProcessHeap(), 0, shortpathA );
1169 /***********************************************************************
1170 * DOSFS_DoGetFullPathName
1172 * Implementation of GetFullPathNameA/W.
1174 * bon@elektron 000331:
1175 * A test for GetFullPathName with many patholotical case
1176 * gives now identical output for Wine and OSR2
1178 static DWORD DOSFS_DoGetFullPathName( LPCSTR name, DWORD len, LPSTR result,
1182 DOS_FULL_NAME full_name;
1185 char drivecur[]="c:.";
1187 int namelen,drive=0;
1189 if ((strlen(name) >1)&& (name[1]==':'))
1190 /*drive letter given */
1192 driveletter = name[0];
1194 if ((strlen(name) >2)&& (name[1]==':') &&
1195 ((name[2]=='\\') || (name[2]=='/')))
1196 /*absolute path given */
1198 lstrcpynA(full_name.short_name,name,MAX_PATHNAME_LEN);
1199 drive = (int)toupper(name[0]) - 'A';
1204 drivecur[0]=driveletter;
1206 strcpy(drivecur,".");
1207 if (!DOSFS_GetFullName( drivecur, FALSE, &full_name ))
1209 FIXME("internal: error getting drive/path\n");
1212 /* find path that drive letter substitutes*/
1213 drive = (int)toupper(full_name.short_name[0]) -0x41;
1214 root= DRIVE_GetRoot(drive);
1217 FIXME("internal: error getting DOS Drive Root\n");
1220 p= full_name.long_name +strlen(root);
1221 /* append long name (= unix name) to drive */
1222 lstrcpynA(full_name.short_name+2,p,MAX_PATHNAME_LEN-3);
1223 /* append name to treat */
1224 namelen= strlen(full_name.short_name);
1227 p += +2; /* skip drive name when appending */
1228 if (namelen +2 + strlen(p) > MAX_PATHNAME_LEN)
1230 FIXME("internal error: buffer too small\n");
1233 full_name.short_name[namelen++] ='\\';
1234 full_name.short_name[namelen] = 0;
1235 lstrcpynA(full_name.short_name +namelen,p,MAX_PATHNAME_LEN-namelen);
1237 /* reverse all slashes */
1238 for (p=full_name.short_name;
1239 p < full_name.short_name+strlen(full_name.short_name);
1245 /* Use memmove, as areas overlap*/
1247 while ((p = strstr(full_name.short_name,"\\..\\")))
1249 if (p > full_name.short_name+2)
1252 q = strrchr(full_name.short_name,'\\');
1253 memmove(q+1,p+4,strlen(p+4)+1);
1257 memmove(full_name.short_name+3,p+4,strlen(p+4)+1);
1260 if ((full_name.short_name[2]=='.')&&(full_name.short_name[3]=='.'))
1262 /* This case istn't treated yet : c:..\test */
1263 memmove(full_name.short_name+2,full_name.short_name+4,
1264 strlen(full_name.short_name+4)+1);
1267 while ((p = strstr(full_name.short_name,"\\.\\")))
1270 memmove(p+1,p+3,strlen(p+3)+1);
1272 if (!(DRIVE_GetFlags(drive) & DRIVE_CASE_PRESERVING))
1273 _strupr( full_name.short_name );
1274 namelen=strlen(full_name.short_name);
1275 if (!strcmp(full_name.short_name+namelen-3,"\\.."))
1277 /* one more starnge case: "c:\test\test1\.."
1279 *(full_name.short_name+namelen-3)=0;
1280 q = strrchr(full_name.short_name,'\\');
1283 if (full_name.short_name[namelen-1]=='.')
1284 full_name.short_name[(namelen--)-1] =0;
1286 if (full_name.short_name[namelen-1]=='\\')
1287 full_name.short_name[(namelen--)-1] =0;
1288 TRACE("got %s\n",full_name.short_name);
1290 /* If the lpBuffer buffer is too small, the return value is the
1291 size of the buffer, in characters, required to hold the path
1292 plus the terminating \0 (tested against win95osr, bon 001118)
1294 ret = strlen(full_name.short_name);
1297 /* don't touch anything when the buffer is not large enough */
1298 SetLastError( ERROR_INSUFFICIENT_BUFFER );
1304 lstrcpynAtoW( (LPWSTR)result, full_name.short_name, len );
1306 lstrcpynA( result, full_name.short_name, len );
1309 TRACE("returning '%s'\n", full_name.short_name );
1314 /***********************************************************************
1315 * GetFullPathNameA (KERNEL32.272)
1317 * if the path closed with '\', *lastpart is 0
1319 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
1322 DWORD ret = DOSFS_DoGetFullPathName( name, len, buffer, FALSE );
1323 if (ret && (ret<=len) && buffer && lastpart)
1325 LPSTR p = buffer + strlen(buffer);
1329 while ((p > buffer + 2) && (*p != '\\')) p--;
1332 else *lastpart = NULL;
1338 /***********************************************************************
1339 * GetFullPathNameW (KERNEL32.273)
1341 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
1344 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1345 DWORD ret = DOSFS_DoGetFullPathName( nameA, len, (LPSTR)buffer, TRUE );
1346 HeapFree( GetProcessHeap(), 0, nameA );
1347 if (ret && (ret<=len) && buffer && lastpart)
1349 LPWSTR p = buffer + strlenW(buffer);
1350 if (*p != (WCHAR)'\\')
1352 while ((p > buffer + 2) && (*p != (WCHAR)'\\')) p--;
1355 else *lastpart = NULL;
1360 /***********************************************************************
1363 static int DOSFS_FindNextEx( FIND_FIRST_INFO *info, WIN32_FIND_DATAA *entry )
1365 BYTE attr = info->attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
1366 UINT flags = DRIVE_GetFlags( info->drive );
1367 char *p, buffer[MAX_PATHNAME_LEN];
1368 const char *drive_path;
1370 LPCSTR long_name, short_name;
1371 BY_HANDLE_FILE_INFORMATION fileinfo;
1374 if ((info->attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
1376 if (info->cur_pos) return 0;
1377 entry->dwFileAttributes = FILE_ATTRIBUTE_LABEL;
1378 RtlSecondsSince1970ToTime( (time_t)0, &entry->ftCreationTime );
1379 RtlSecondsSince1970ToTime( (time_t)0, &entry->ftLastAccessTime );
1380 RtlSecondsSince1970ToTime( (time_t)0, &entry->ftLastWriteTime );
1381 entry->nFileSizeHigh = 0;
1382 entry->nFileSizeLow = 0;
1383 entry->dwReserved0 = 0;
1384 entry->dwReserved1 = 0;
1385 DOSFS_ToDosDTAFormat( DRIVE_GetLabel( info->drive ), entry->cFileName );
1386 strcpy( entry->cAlternateFileName, entry->cFileName );
1388 TRACE("returning %s (%s) as label\n",
1389 entry->cFileName, entry->cAlternateFileName);
1393 drive_path = info->path + strlen(DRIVE_GetRoot( info->drive ));
1394 while ((*drive_path == '/') || (*drive_path == '\\')) drive_path++;
1395 drive_root = !*drive_path;
1397 lstrcpynA( buffer, info->path, sizeof(buffer) - 1 );
1398 strcat( buffer, "/" );
1399 p = buffer + strlen(buffer);
1401 while (DOSFS_ReadDir( info->dir, &long_name, &short_name ))
1405 /* Don't return '.' and '..' in the root of the drive */
1406 if (drive_root && (long_name[0] == '.') &&
1407 (!long_name[1] || ((long_name[1] == '.') && !long_name[2])))
1410 /* Check the long mask */
1412 if (info->long_mask)
1414 if (!DOSFS_MatchLong( info->long_mask, long_name,
1415 flags & DRIVE_CASE_SENSITIVE )) continue;
1418 /* Check the short mask */
1420 if (info->short_mask)
1424 DOSFS_Hash( long_name, dos_name, TRUE,
1425 !(flags & DRIVE_CASE_SENSITIVE) );
1426 short_name = dos_name;
1428 if (!DOSFS_MatchShort( info->short_mask, short_name )) continue;
1431 /* Check the file attributes */
1433 lstrcpynA( p, long_name, sizeof(buffer) - (int)(p - buffer) );
1434 if (!FILE_Stat( buffer, &fileinfo ))
1436 WARN("can't stat %s\n", buffer);
1439 if (fileinfo.dwFileAttributes & ~attr) continue;
1441 /* We now have a matching entry; fill the result and return */
1443 entry->dwFileAttributes = fileinfo.dwFileAttributes;
1444 entry->ftCreationTime = fileinfo.ftCreationTime;
1445 entry->ftLastAccessTime = fileinfo.ftLastAccessTime;
1446 entry->ftLastWriteTime = fileinfo.ftLastWriteTime;
1447 entry->nFileSizeHigh = fileinfo.nFileSizeHigh;
1448 entry->nFileSizeLow = fileinfo.nFileSizeLow;
1451 DOSFS_ToDosDTAFormat( short_name, entry->cAlternateFileName );
1453 DOSFS_Hash( long_name, entry->cAlternateFileName, FALSE,
1454 !(flags & DRIVE_CASE_SENSITIVE) );
1456 lstrcpynA( entry->cFileName, long_name, sizeof(entry->cFileName) );
1457 if (!(flags & DRIVE_CASE_PRESERVING)) _strlwr( entry->cFileName );
1458 TRACE("returning %s (%s) %02lx %ld\n",
1459 entry->cFileName, entry->cAlternateFileName,
1460 entry->dwFileAttributes, entry->nFileSizeLow );
1463 return 0; /* End of directory */
1466 /***********************************************************************
1469 * Find the next matching file. Return the number of entries read to find
1470 * the matching one, or 0 if no more entries.
1471 * 'short_mask' is the 8.3 mask (in FCB format), 'long_mask' is the long
1472 * file name mask. Either or both can be NULL.
1474 * NOTE: This is supposed to be only called by the int21 emulation
1475 * routines. Thus, we should own the Win16Mutex anyway.
1476 * Nevertheless, we explicitly enter it to ensure the static
1477 * directory cache is protected.
1479 int DOSFS_FindNext( const char *path, const char *short_mask,
1480 const char *long_mask, int drive, BYTE attr,
1481 int skip, WIN32_FIND_DATAA *entry )
1483 static FIND_FIRST_INFO info = { NULL };
1484 LPCSTR short_name, long_name;
1487 SYSLEVEL_EnterWin16Lock();
1489 /* Check the cached directory */
1490 if (!(info.dir && info.path == path && info.short_mask == short_mask
1491 && info.long_mask == long_mask && info.drive == drive
1492 && info.attr == attr && info.cur_pos <= skip))
1494 /* Not in the cache, open it anew */
1495 if (info.dir) DOSFS_CloseDir( info.dir );
1497 info.path = (LPSTR)path;
1498 info.long_mask = (LPSTR)long_mask;
1499 info.short_mask = (LPSTR)short_mask;
1503 info.dir = DOSFS_OpenDir( info.path );
1506 /* Skip to desired position */
1507 while (info.cur_pos < skip)
1508 if (info.dir && DOSFS_ReadDir( info.dir, &long_name, &short_name ))
1513 if (info.dir && info.cur_pos == skip && DOSFS_FindNextEx( &info, entry ))
1514 count = info.cur_pos - skip;
1520 if (info.dir) DOSFS_CloseDir( info.dir );
1521 memset( &info, '\0', sizeof(info) );
1524 SYSLEVEL_LeaveWin16Lock();
1529 /*************************************************************************
1530 * FindFirstFileExA (KERNEL32)
1532 HANDLE WINAPI FindFirstFileExA(
1534 FINDEX_INFO_LEVELS fInfoLevelId,
1535 LPVOID lpFindFileData,
1536 FINDEX_SEARCH_OPS fSearchOp,
1537 LPVOID lpSearchFilter,
1538 DWORD dwAdditionalFlags)
1540 DOS_FULL_NAME full_name;
1542 FIND_FIRST_INFO *info;
1544 if ((fSearchOp != FindExSearchNameMatch) || (dwAdditionalFlags != 0))
1546 FIXME("options not implemented 0x%08x 0x%08lx\n", fSearchOp, dwAdditionalFlags );
1547 return INVALID_HANDLE_VALUE;
1550 switch(fInfoLevelId)
1552 case FindExInfoStandard:
1554 WIN32_FIND_DATAA * data = (WIN32_FIND_DATAA *) lpFindFileData;
1555 data->dwReserved0 = data->dwReserved1 = 0x0;
1556 if (!lpFileName) return 0;
1557 if (!DOSFS_GetFullName( lpFileName, FALSE, &full_name )) break;
1558 if (!(handle = GlobalAlloc(GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO)))) break;
1559 info = (FIND_FIRST_INFO *)GlobalLock( handle );
1560 info->path = HEAP_strdupA( GetProcessHeap(), 0, full_name.long_name );
1561 info->long_mask = strrchr( info->path, '/' );
1562 *(info->long_mask++) = '\0';
1563 info->short_mask = NULL;
1565 if (lpFileName[0] && (lpFileName[1] == ':'))
1566 info->drive = toupper(*lpFileName) - 'A';
1567 else info->drive = DRIVE_GetCurrentDrive();
1570 info->dir = DOSFS_OpenDir( info->path );
1572 GlobalUnlock( handle );
1573 if (!FindNextFileA( handle, data ))
1575 FindClose( handle );
1576 SetLastError( ERROR_NO_MORE_FILES );
1583 FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1585 return INVALID_HANDLE_VALUE;
1588 /*************************************************************************
1589 * FindFirstFileA (KERNEL32.123)
1591 HANDLE WINAPI FindFirstFileA(
1593 WIN32_FIND_DATAA *lpFindData )
1595 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1596 FindExSearchNameMatch, NULL, 0);
1599 /*************************************************************************
1600 * FindFirstFileExW (KERNEL32)
1602 HANDLE WINAPI FindFirstFileExW(
1604 FINDEX_INFO_LEVELS fInfoLevelId,
1605 LPVOID lpFindFileData,
1606 FINDEX_SEARCH_OPS fSearchOp,
1607 LPVOID lpSearchFilter,
1608 DWORD dwAdditionalFlags)
1611 WIN32_FIND_DATAA dataA;
1612 LPVOID _lpFindFileData;
1615 switch(fInfoLevelId)
1617 case FindExInfoStandard:
1619 _lpFindFileData = &dataA;
1623 FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1624 return INVALID_HANDLE_VALUE;
1627 pathA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
1628 handle = FindFirstFileExA(pathA, fInfoLevelId, _lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1629 HeapFree( GetProcessHeap(), 0, pathA );
1630 if (handle == INVALID_HANDLE_VALUE) return handle;
1632 switch(fInfoLevelId)
1634 case FindExInfoStandard:
1636 WIN32_FIND_DATAW *dataW = (WIN32_FIND_DATAW*) lpFindFileData;
1637 dataW->dwFileAttributes = dataA.dwFileAttributes;
1638 dataW->ftCreationTime = dataA.ftCreationTime;
1639 dataW->ftLastAccessTime = dataA.ftLastAccessTime;
1640 dataW->ftLastWriteTime = dataA.ftLastWriteTime;
1641 dataW->nFileSizeHigh = dataA.nFileSizeHigh;
1642 dataW->nFileSizeLow = dataA.nFileSizeLow;
1643 MultiByteToWideChar( CP_ACP, 0, dataA.cFileName, -1,
1644 dataW->cFileName, sizeof(dataW->cFileName)/sizeof(WCHAR) );
1645 MultiByteToWideChar( CP_ACP, 0, dataA.cAlternateFileName, -1,
1646 dataW->cAlternateFileName,
1647 sizeof(dataW->cAlternateFileName)/sizeof(WCHAR) );
1651 FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1652 return INVALID_HANDLE_VALUE;
1657 /*************************************************************************
1658 * FindFirstFileW (KERNEL32.124)
1660 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1662 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1663 FindExSearchNameMatch, NULL, 0);
1666 /*************************************************************************
1667 * FindNextFileA (KERNEL32.126)
1669 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1671 FIND_FIRST_INFO *info;
1673 if ((handle == INVALID_HANDLE_VALUE) ||
1674 !(info = (FIND_FIRST_INFO *)GlobalLock( handle )))
1676 SetLastError( ERROR_INVALID_HANDLE );
1679 GlobalUnlock( handle );
1680 if (!info->path || !info->dir)
1682 SetLastError( ERROR_NO_MORE_FILES );
1685 if (!DOSFS_FindNextEx( info, data ))
1687 DOSFS_CloseDir( info->dir ); info->dir = NULL;
1688 HeapFree( GetProcessHeap(), 0, info->path );
1689 info->path = info->long_mask = NULL;
1690 SetLastError( ERROR_NO_MORE_FILES );
1697 /*************************************************************************
1698 * FindNextFileW (KERNEL32.127)
1700 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1702 WIN32_FIND_DATAA dataA;
1703 if (!FindNextFileA( handle, &dataA )) return FALSE;
1704 data->dwFileAttributes = dataA.dwFileAttributes;
1705 data->ftCreationTime = dataA.ftCreationTime;
1706 data->ftLastAccessTime = dataA.ftLastAccessTime;
1707 data->ftLastWriteTime = dataA.ftLastWriteTime;
1708 data->nFileSizeHigh = dataA.nFileSizeHigh;
1709 data->nFileSizeLow = dataA.nFileSizeLow;
1710 MultiByteToWideChar( CP_ACP, 0, dataA.cFileName, -1,
1711 data->cFileName, sizeof(data->cFileName)/sizeof(WCHAR) );
1712 MultiByteToWideChar( CP_ACP, 0, dataA.cAlternateFileName, -1,
1713 data->cAlternateFileName,
1714 sizeof(data->cAlternateFileName)/sizeof(WCHAR) );
1718 /*************************************************************************
1719 * FindClose (KERNEL32.119)
1721 BOOL WINAPI FindClose( HANDLE handle )
1723 FIND_FIRST_INFO *info;
1725 if ((handle == INVALID_HANDLE_VALUE) ||
1726 !(info = (FIND_FIRST_INFO *)GlobalLock( handle )))
1728 SetLastError( ERROR_INVALID_HANDLE );
1731 if (info->dir) DOSFS_CloseDir( info->dir );
1732 if (info->path) HeapFree( GetProcessHeap(), 0, info->path );
1733 GlobalUnlock( handle );
1734 GlobalFree( handle );
1738 /***********************************************************************
1739 * DOSFS_UnixTimeToFileTime
1741 * Convert a Unix time to FILETIME format.
1742 * The FILETIME structure is a 64-bit value representing the number of
1743 * 100-nanosecond intervals since January 1, 1601, 0:00.
1744 * 'remainder' is the nonnegative number of 100-ns intervals
1745 * corresponding to the time fraction smaller than 1 second that
1746 * couldn't be stored in the time_t value.
1748 void DOSFS_UnixTimeToFileTime( time_t unix_time, FILETIME *filetime,
1754 The time difference between 1 January 1601, 00:00:00 and
1755 1 January 1970, 00:00:00 is 369 years, plus the leap years
1756 from 1604 to 1968, excluding 1700, 1800, 1900.
1757 This makes (1968 - 1600) / 4 - 3 = 89 leap days, and a total
1760 Any day in that period had 24 * 60 * 60 = 86400 seconds.
1762 The time difference is 134774 * 86400 * 10000000, which can be written
1764 27111902 * 2^32 + 3577643008
1765 413 * 2^48 + 45534 * 2^32 + 54590 * 2^16 + 32768
1767 If you find that these constants are buggy, please change them in all
1768 instances in both conversion functions.
1771 There are two versions, one of them uses long long variables and
1772 is presumably faster but not ISO C. The other one uses standard C
1773 data types and operations but relies on the assumption that negative
1774 numbers are stored as 2's complement (-1 is 0xffff....). If this
1775 assumption is violated, dates before 1970 will not convert correctly.
1776 This should however work on any reasonable architecture where WINE
1781 Take care not to remove the casts. I have tested these functions
1782 (in both versions) for a lot of numbers. I would be interested in
1783 results on other compilers than GCC.
1785 The operations have been designed to account for the possibility
1786 of 64-bit time_t in future UNICES. Even the versions without
1787 internal long long numbers will work if time_t only is 64 bit.
1788 A 32-bit shift, which was necessary for that operation, turned out
1789 not to work correctly in GCC, besides giving the warning. So I
1790 used a double 16-bit shift instead. Numbers are in the ISO version
1791 represented by three limbs, the most significant with 32 bit, the
1792 other two with 16 bit each.
1794 As the modulo-operator % is not well-defined for negative numbers,
1795 negative divisors have been avoided in DOSFS_FileTimeToUnixTime.
1797 There might be quicker ways to do this in C. Certainly so in
1800 Claus Fischer, fischer@iue.tuwien.ac.at
1803 #if SIZEOF_LONG_LONG >= 8
1804 # define USE_LONG_LONG 1
1806 # define USE_LONG_LONG 0
1809 #if USE_LONG_LONG /* gcc supports long long type */
1811 long long int t = unix_time;
1813 t += 116444736000000000LL;
1815 filetime->dwLowDateTime = (UINT)t;
1816 filetime->dwHighDateTime = (UINT)(t >> 32);
1818 #else /* ISO version */
1820 UINT a0; /* 16 bit, low bits */
1821 UINT a1; /* 16 bit, medium bits */
1822 UINT a2; /* 32 bit, high bits */
1824 /* Copy the unix time to a2/a1/a0 */
1825 a0 = unix_time & 0xffff;
1826 a1 = (unix_time >> 16) & 0xffff;
1827 /* This is obsolete if unix_time is only 32 bits, but it does not hurt.
1828 Do not replace this by >> 32, it gives a compiler warning and it does
1830 a2 = (unix_time >= 0 ? (unix_time >> 16) >> 16 :
1831 ~((~unix_time >> 16) >> 16));
1833 /* Multiply a by 10000000 (a = a2/a1/a0)
1834 Split the factor into 10000 * 1000 which are both less than 0xffff. */
1836 a1 = a1 * 10000 + (a0 >> 16);
1837 a2 = a2 * 10000 + (a1 >> 16);
1842 a1 = a1 * 1000 + (a0 >> 16);
1843 a2 = a2 * 1000 + (a1 >> 16);
1847 /* Add the time difference and the remainder */
1848 a0 += 32768 + (remainder & 0xffff);
1849 a1 += 54590 + (remainder >> 16 ) + (a0 >> 16);
1850 a2 += 27111902 + (a1 >> 16);
1855 filetime->dwLowDateTime = (a1 << 16) + a0;
1856 filetime->dwHighDateTime = a2;
1861 /***********************************************************************
1862 * DOSFS_FileTimeToUnixTime
1864 * Convert a FILETIME format to Unix time.
1865 * If not NULL, 'remainder' contains the fractional part of the filetime,
1866 * in the range of [0..9999999] (even if time_t is negative).
1868 time_t DOSFS_FileTimeToUnixTime( const FILETIME *filetime, DWORD *remainder )
1870 /* Read the comment in the function DOSFS_UnixTimeToFileTime. */
1873 long long int t = filetime->dwHighDateTime;
1875 t += (UINT)filetime->dwLowDateTime;
1876 t -= 116444736000000000LL;
1879 if (remainder) *remainder = 9999999 - (-t - 1) % 10000000;
1880 return -1 - ((-t - 1) / 10000000);
1884 if (remainder) *remainder = t % 10000000;
1885 return t / 10000000;
1888 #else /* ISO version */
1890 UINT a0; /* 16 bit, low bits */
1891 UINT a1; /* 16 bit, medium bits */
1892 UINT a2; /* 32 bit, high bits */
1893 UINT r; /* remainder of division */
1894 unsigned int carry; /* carry bit for subtraction */
1895 int negative; /* whether a represents a negative value */
1897 /* Copy the time values to a2/a1/a0 */
1898 a2 = (UINT)filetime->dwHighDateTime;
1899 a1 = ((UINT)filetime->dwLowDateTime ) >> 16;
1900 a0 = ((UINT)filetime->dwLowDateTime ) & 0xffff;
1902 /* Subtract the time difference */
1903 if (a0 >= 32768 ) a0 -= 32768 , carry = 0;
1904 else a0 += (1 << 16) - 32768 , carry = 1;
1906 if (a1 >= 54590 + carry) a1 -= 54590 + carry, carry = 0;
1907 else a1 += (1 << 16) - 54590 - carry, carry = 1;
1909 a2 -= 27111902 + carry;
1911 /* If a is negative, replace a by (-1-a) */
1912 negative = (a2 >= ((UINT)1) << 31);
1915 /* Set a to -a - 1 (a is a2/a1/a0) */
1921 /* Divide a by 10000000 (a = a2/a1/a0), put the rest into r.
1922 Split the divisor into 10000 * 1000 which are both less than 0xffff. */
1923 a1 += (a2 % 10000) << 16;
1925 a0 += (a1 % 10000) << 16;
1930 a1 += (a2 % 1000) << 16;
1932 a0 += (a1 % 1000) << 16;
1934 r += (a0 % 1000) * 10000;
1937 /* If a was negative, replace a by (-1-a) and r by (9999999 - r) */
1940 /* Set a to -a - 1 (a is a2/a1/a0) */
1948 if (remainder) *remainder = r;
1950 /* Do not replace this by << 32, it gives a compiler warning and it does
1952 return ((((time_t)a2) << 16) << 16) + (a1 << 16) + a0;
1957 /***********************************************************************
1958 * MulDiv (KERNEL32.391)
1960 * Result of multiplication and division
1961 * -1: Overflow occurred or Divisor was 0
1968 #if SIZEOF_LONG_LONG >= 8
1971 if (!nDivisor) return -1;
1973 /* We want to deal with a positive divisor to simplify the logic. */
1976 nMultiplicand = - nMultiplicand;
1977 nDivisor = -nDivisor;
1980 /* If the result is positive, we "add" to round. else, we subtract to round. */
1981 if ( ( (nMultiplicand < 0) && (nMultiplier < 0) ) ||
1982 ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
1983 ret = (((long long)nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
1985 ret = (((long long)nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
1987 if ((ret > 2147483647) || (ret < -2147483647)) return -1;
1990 if (!nDivisor) return -1;
1992 /* We want to deal with a positive divisor to simplify the logic. */
1995 nMultiplicand = - nMultiplicand;
1996 nDivisor = -nDivisor;
1999 /* If the result is positive, we "add" to round. else, we subtract to round. */
2000 if ( ( (nMultiplicand < 0) && (nMultiplier < 0) ) ||
2001 ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
2002 return ((nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
2004 return ((nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
2010 /***********************************************************************
2011 * DosDateTimeToFileTime (KERNEL32.76)
2013 BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, LPFILETIME ft)
2017 newtm.tm_sec = (fattime & 0x1f) * 2;
2018 newtm.tm_min = (fattime >> 5) & 0x3f;
2019 newtm.tm_hour = (fattime >> 11);
2020 newtm.tm_mday = (fatdate & 0x1f);
2021 newtm.tm_mon = ((fatdate >> 5) & 0x0f) - 1;
2022 newtm.tm_year = (fatdate >> 9) + 80;
2023 RtlSecondsSince1970ToTime( mktime( &newtm ), ft );
2028 /***********************************************************************
2029 * FileTimeToDosDateTime (KERNEL32.111)
2031 BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, LPWORD fatdate,
2034 time_t unixtime = DOSFS_FileTimeToUnixTime( ft, NULL );
2035 struct tm *tm = localtime( &unixtime );
2037 *fattime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
2039 *fatdate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5)
2045 /***********************************************************************
2046 * LocalFileTimeToFileTime (KERNEL32.373)
2048 BOOL WINAPI LocalFileTimeToFileTime( const FILETIME *localft,
2054 /* convert from local to UTC. Perhaps not correct. FIXME */
2055 time_t unixtime = DOSFS_FileTimeToUnixTime( localft, &remainder );
2056 xtm = gmtime( &unixtime );
2057 DOSFS_UnixTimeToFileTime( mktime(xtm), utcft, remainder );
2062 /***********************************************************************
2063 * FileTimeToLocalFileTime (KERNEL32.112)
2065 BOOL WINAPI FileTimeToLocalFileTime( const FILETIME *utcft,
2066 LPFILETIME localft )
2069 /* convert from UTC to local. Perhaps not correct. FIXME */
2070 time_t unixtime = DOSFS_FileTimeToUnixTime( utcft, &remainder );
2072 struct tm *xtm = localtime( &unixtime );
2075 localtime = timegm(xtm);
2076 DOSFS_UnixTimeToFileTime( localtime, localft, remainder );
2079 struct tm *xtm,*gtm;
2082 xtm = localtime( &unixtime );
2083 gtm = gmtime( &unixtime );
2084 time1 = mktime(xtm);
2085 time2 = mktime(gtm);
2086 DOSFS_UnixTimeToFileTime( 2*time1-time2, localft, remainder );
2092 /***********************************************************************
2093 * FileTimeToSystemTime (KERNEL32.113)
2095 BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst )
2099 time_t xtime = DOSFS_FileTimeToUnixTime( ft, &remainder );
2100 xtm = gmtime(&xtime);
2101 syst->wYear = xtm->tm_year+1900;
2102 syst->wMonth = xtm->tm_mon + 1;
2103 syst->wDayOfWeek = xtm->tm_wday;
2104 syst->wDay = xtm->tm_mday;
2105 syst->wHour = xtm->tm_hour;
2106 syst->wMinute = xtm->tm_min;
2107 syst->wSecond = xtm->tm_sec;
2108 syst->wMilliseconds = remainder / 10000;
2112 /***********************************************************************
2113 * QueryDosDeviceA (KERNEL32.413)
2115 * returns array of strings terminated by \0, terminated by \0
2117 DWORD WINAPI QueryDosDeviceA(LPCSTR devname,LPSTR target,DWORD bufsize)
2122 TRACE("(%s,...)\n", devname ? devname : "<null>");
2124 /* return known MSDOS devices */
2125 strcpy(buffer,"CON COM1 COM2 LPT1 NUL ");
2126 while ((s=strchr(buffer,' ')))
2129 lstrcpynA(target,buffer,bufsize);
2130 return strlen(buffer);
2132 strcpy(buffer,"\\DEV\\");
2133 strcat(buffer,devname);
2134 if ((s=strchr(buffer,':'))) *s='\0';
2135 lstrcpynA(target,buffer,bufsize);
2136 return strlen(buffer);
2140 /***********************************************************************
2141 * QueryDosDeviceW (KERNEL32.414)
2143 * returns array of strings terminated by \0, terminated by \0
2145 DWORD WINAPI QueryDosDeviceW(LPCWSTR devname,LPWSTR target,DWORD bufsize)
2147 LPSTR devnameA = devname?HEAP_strdupWtoA(GetProcessHeap(),0,devname):NULL;
2148 LPSTR targetA = (LPSTR)HeapAlloc(GetProcessHeap(),0,bufsize);
2149 DWORD ret = QueryDosDeviceA(devnameA,targetA,bufsize);
2151 lstrcpynAtoW(target,targetA,bufsize);
2152 if (devnameA) HeapFree(GetProcessHeap(),0,devnameA);
2153 if (targetA) HeapFree(GetProcessHeap(),0,targetA);
2158 /***********************************************************************
2159 * SystemTimeToFileTime (KERNEL32.526)
2161 BOOL WINAPI SystemTimeToFileTime( const SYSTEMTIME *syst, LPFILETIME ft )
2167 struct tm xtm,*local_tm,*utc_tm;
2168 time_t localtim,utctime;
2171 xtm.tm_year = syst->wYear-1900;
2172 xtm.tm_mon = syst->wMonth - 1;
2173 xtm.tm_wday = syst->wDayOfWeek;
2174 xtm.tm_mday = syst->wDay;
2175 xtm.tm_hour = syst->wHour;
2176 xtm.tm_min = syst->wMinute;
2177 xtm.tm_sec = syst->wSecond; /* this is UTC */
2180 utctime = timegm(&xtm);
2181 DOSFS_UnixTimeToFileTime( utctime, ft,
2182 syst->wMilliseconds * 10000 );
2184 localtim = mktime(&xtm); /* now we've got local time */
2185 local_tm = localtime(&localtim);
2186 utc_tm = gmtime(&localtim);
2187 utctime = mktime(utc_tm);
2188 DOSFS_UnixTimeToFileTime( 2*localtim -utctime, ft,
2189 syst->wMilliseconds * 10000 );
2194 /***********************************************************************
2195 * DefineDosDeviceA (KERNEL32.182)
2197 BOOL WINAPI DefineDosDeviceA(DWORD flags,LPCSTR devname,LPCSTR targetpath) {
2198 FIXME("(0x%08lx,%s,%s),stub!\n",flags,devname,targetpath);
2199 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2204 --- 16 bit functions ---
2207 /*************************************************************************
2208 * FindFirstFile16 (KERNEL.413)
2210 HANDLE16 WINAPI FindFirstFile16( LPCSTR path, WIN32_FIND_DATAA *data )
2212 DOS_FULL_NAME full_name;
2214 FIND_FIRST_INFO *info;
2216 data->dwReserved0 = data->dwReserved1 = 0x0;
2217 if (!path) return 0;
2218 if (!DOSFS_GetFullName( path, FALSE, &full_name ))
2219 return INVALID_HANDLE_VALUE16;
2220 if (!(handle = GlobalAlloc16( GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO) )))
2221 return INVALID_HANDLE_VALUE16;
2222 info = (FIND_FIRST_INFO *)GlobalLock16( handle );
2223 info->path = HEAP_strdupA( SystemHeap, 0, full_name.long_name );
2224 info->long_mask = strrchr( info->path, '/' );
2225 if (info->long_mask )
2226 *(info->long_mask++) = '\0';
2227 info->short_mask = NULL;
2229 if (path[0] && (path[1] == ':')) info->drive = toupper(*path) - 'A';
2230 else info->drive = DRIVE_GetCurrentDrive();
2233 info->dir = DOSFS_OpenDir( info->path );
2235 GlobalUnlock16( handle );
2236 if (!FindNextFile16( handle, data ))
2238 FindClose16( handle );
2239 SetLastError( ERROR_NO_MORE_FILES );
2240 return INVALID_HANDLE_VALUE16;
2245 /*************************************************************************
2246 * FindNextFile16 (KERNEL.414)
2248 BOOL16 WINAPI FindNextFile16( HANDLE16 handle, WIN32_FIND_DATAA *data )
2250 FIND_FIRST_INFO *info;
2252 if ((handle == INVALID_HANDLE_VALUE16) ||
2253 !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
2255 SetLastError( ERROR_INVALID_HANDLE );
2258 GlobalUnlock16( handle );
2259 if (!info->path || !info->dir)
2261 SetLastError( ERROR_NO_MORE_FILES );
2264 if (!DOSFS_FindNextEx( info, data ))
2266 DOSFS_CloseDir( info->dir ); info->dir = NULL;
2267 HeapFree( SystemHeap, 0, info->path );
2268 info->path = info->long_mask = NULL;
2269 SetLastError( ERROR_NO_MORE_FILES );
2275 /*************************************************************************
2276 * FindClose16 (KERNEL.415)
2278 BOOL16 WINAPI FindClose16( HANDLE16 handle )
2280 FIND_FIRST_INFO *info;
2282 if ((handle == INVALID_HANDLE_VALUE16) ||
2283 !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
2285 SetLastError( ERROR_INVALID_HANDLE );
2288 if (info->dir) DOSFS_CloseDir( info->dir );
2289 if (info->path) HeapFree( SystemHeap, 0, info->path );
2290 GlobalUnlock16( handle );
2291 GlobalFree16( handle );