Basic support for WIN32 serial communications API.
[wine.git] / files / dos_fs.c
blob9572a4854839cdf5cd37ad1f4760b4e7679a7e62
1 /*
2 * DOS file system functions
4 * Copyright 1993 Erik Bos
5 * Copyright 1996 Alexandre Julliard
6 */
8 #include "config.h"
9 #include <sys/types.h>
10 #include <ctype.h>
11 #include <dirent.h>
12 #include <errno.h>
13 #include <sys/errno.h>
14 #include <fcntl.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <sys/stat.h>
18 #include <sys/ioctl.h>
19 #include <time.h>
20 #include <unistd.h>
22 #include "windef.h"
23 #include "winuser.h"
24 #include "wine/winbase16.h"
25 #include "winerror.h"
26 #include "drive.h"
27 #include "file.h"
28 #include "heap.h"
29 #include "msdos.h"
30 #include "syslevel.h"
31 #include "server.h"
32 #include "process.h"
33 #include "debug.h"
35 /* Define the VFAT ioctl to get both short and long file names */
36 /* FIXME: is it possible to get this to work on other systems? */
37 #ifdef linux
38 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, long)
39 /* We want the real kernel dirent structure, not the libc one */
40 typedef struct
42 long d_ino;
43 long d_off;
44 unsigned short d_reclen;
45 char d_name[256];
46 } KERNEL_DIRENT;
48 #else /* linux */
49 #undef VFAT_IOCTL_READDIR_BOTH /* just in case... */
50 #endif /* linux */
52 /* Chars we don't want to see in DOS file names */
53 #define INVALID_DOS_CHARS "*?<>|\"+=,;[] \345"
55 static const DOS_DEVICE DOSFS_Devices[] =
56 /* name, device flags (see Int 21/AX=0x4400) */
58 { "CON", 0xc0d3 },
59 { "PRN", 0xa0c0 },
60 { "NUL", 0x80c4 },
61 { "AUX", 0x80c0 },
62 { "LPT1", 0xa0c0 },
63 { "LPT2", 0xa0c0 },
64 { "LPT3", 0xa0c0 },
65 { "LPT4", 0xc0d3 },
66 { "COM1", 0x80c0 },
67 { "COM2", 0x80c0 },
68 { "COM3", 0x80c0 },
69 { "COM4", 0x80c0 },
70 { "SCSIMGR$", 0xc0c0 },
71 { "HPSCAN", 0xc0c0 }
74 #define GET_DRIVE(path) \
75 (((path)[1] == ':') ? toupper((path)[0]) - 'A' : DOSFS_CurDrive)
77 /* Directory info for DOSFS_ReadDir */
78 typedef struct
80 DIR *dir;
81 #ifdef VFAT_IOCTL_READDIR_BOTH
82 int fd;
83 char short_name[12];
84 KERNEL_DIRENT dirent[2];
85 #endif
86 } DOS_DIR;
88 /* Info structure for FindFirstFile handle */
89 typedef struct
91 LPSTR path;
92 LPSTR long_mask;
93 LPSTR short_mask;
94 BYTE attr;
95 int drive;
96 int cur_pos;
97 DOS_DIR *dir;
98 } FIND_FIRST_INFO;
102 /***********************************************************************
103 * DOSFS_ValidDOSName
105 * Return 1 if Unix file 'name' is also a valid MS-DOS name
106 * (i.e. contains only valid DOS chars, lower-case only, fits in 8.3 format).
107 * File name can be terminated by '\0', '\\' or '/'.
109 static int DOSFS_ValidDOSName( const char *name, int ignore_case )
111 static const char invalid_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" INVALID_DOS_CHARS;
112 const char *p = name;
113 const char *invalid = ignore_case ? (invalid_chars + 26) : invalid_chars;
114 int len = 0;
116 if (*p == '.')
118 /* Check for "." and ".." */
119 p++;
120 if (*p == '.') p++;
121 /* All other names beginning with '.' are invalid */
122 return (IS_END_OF_NAME(*p));
124 while (!IS_END_OF_NAME(*p))
126 if (strchr( invalid, *p )) return 0; /* Invalid char */
127 if (*p == '.') break; /* Start of the extension */
128 if (++len > 8) return 0; /* Name too long */
129 p++;
131 if (*p != '.') return 1; /* End of name */
132 p++;
133 if (IS_END_OF_NAME(*p)) return 0; /* Empty extension not allowed */
134 len = 0;
135 while (!IS_END_OF_NAME(*p))
137 if (strchr( invalid, *p )) return 0; /* Invalid char */
138 if (*p == '.') return 0; /* Second extension not allowed */
139 if (++len > 3) return 0; /* Extension too long */
140 p++;
142 return 1;
146 /***********************************************************************
147 * DOSFS_ToDosFCBFormat
149 * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
150 * expanding wild cards and converting to upper-case in the process.
151 * File name can be terminated by '\0', '\\' or '/'.
152 * Return FALSE if the name is not a valid DOS name.
153 * 'buffer' must be at least 12 characters long.
155 BOOL DOSFS_ToDosFCBFormat( LPCSTR name, LPSTR buffer )
157 static const char invalid_chars[] = INVALID_DOS_CHARS;
158 const char *p = name;
159 int i;
161 /* Check for "." and ".." */
162 if (*p == '.')
164 p++;
165 strcpy( buffer, ". " );
166 if (*p == '.')
168 buffer[1] = '.';
169 p++;
171 return (!*p || (*p == '/') || (*p == '\\'));
174 for (i = 0; i < 8; i++)
176 switch(*p)
178 case '\0':
179 case '\\':
180 case '/':
181 case '.':
182 buffer[i] = ' ';
183 break;
184 case '?':
185 p++;
186 /* fall through */
187 case '*':
188 buffer[i] = '?';
189 break;
190 default:
191 if (strchr( invalid_chars, *p )) return FALSE;
192 buffer[i] = toupper(*p);
193 p++;
194 break;
198 if (*p == '*')
200 /* Skip all chars after wildcard up to first dot */
201 while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
203 else
205 /* Check if name too long */
206 if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
208 if (*p == '.') p++; /* Skip dot */
210 for (i = 8; i < 11; i++)
212 switch(*p)
214 case '\0':
215 case '\\':
216 case '/':
217 buffer[i] = ' ';
218 break;
219 case '.':
220 return FALSE; /* Second extension not allowed */
221 case '?':
222 p++;
223 /* fall through */
224 case '*':
225 buffer[i] = '?';
226 break;
227 default:
228 if (strchr( invalid_chars, *p )) return FALSE;
229 buffer[i] = toupper(*p);
230 p++;
231 break;
234 buffer[11] = '\0';
235 return TRUE;
239 /***********************************************************************
240 * DOSFS_ToDosDTAFormat
242 * Convert a file name from FCB to DTA format (name.ext, null-terminated)
243 * converting to upper-case in the process.
244 * File name can be terminated by '\0', '\\' or '/'.
245 * 'buffer' must be at least 13 characters long.
247 static void DOSFS_ToDosDTAFormat( LPCSTR name, LPSTR buffer )
249 char *p;
251 memcpy( buffer, name, 8 );
252 for (p = buffer + 8; (p > buffer) && (p[-1] == ' '); p--);
253 *p++ = '.';
254 memcpy( p, name + 8, 3 );
255 for (p += 3; p[-1] == ' '; p--);
256 if (p[-1] == '.') p--;
257 *p = '\0';
261 /***********************************************************************
262 * DOSFS_MatchShort
264 * Check a DOS file name against a mask (both in FCB format).
266 static int DOSFS_MatchShort( const char *mask, const char *name )
268 int i;
269 for (i = 11; i > 0; i--, mask++, name++)
270 if ((*mask != '?') && (*mask != *name)) return 0;
271 return 1;
275 /***********************************************************************
276 * DOSFS_MatchLong
278 * Check a long file name against a mask.
280 static int DOSFS_MatchLong( const char *mask, const char *name,
281 int case_sensitive )
283 if (!strcmp( mask, "*.*" )) return 1;
284 while (*name && *mask)
286 if (*mask == '*')
288 mask++;
289 while (*mask == '*') mask++; /* Skip consecutive '*' */
290 if (!*mask) return 1;
291 if (case_sensitive) while (*name && (*name != *mask)) name++;
292 else while (*name && (toupper(*name) != toupper(*mask))) name++;
293 if (!*name) return 0;
295 else if (*mask != '?')
297 if (case_sensitive)
299 if (*mask != *name) return 0;
301 else if (toupper(*mask) != toupper(*name)) return 0;
303 mask++;
304 name++;
306 return (!*name && !*mask);
310 /***********************************************************************
311 * DOSFS_OpenDir
313 static DOS_DIR *DOSFS_OpenDir( LPCSTR path )
315 DOS_DIR *dir = HeapAlloc( SystemHeap, 0, sizeof(*dir) );
316 if (!dir)
318 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
319 return NULL;
322 /* Treat empty path as root directory. This simplifies path split into
323 directory and mask in several other places */
324 if (!*path) path = "/";
326 #ifdef VFAT_IOCTL_READDIR_BOTH
328 /* Check if the VFAT ioctl is supported on this directory */
330 if ((dir->fd = open( path, O_RDONLY )) != -1)
332 if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) == -1)
334 close( dir->fd );
335 dir->fd = -1;
337 else
339 /* Set the file pointer back at the start of the directory */
340 lseek( dir->fd, 0, SEEK_SET );
341 dir->dir = NULL;
342 return dir;
345 #endif /* VFAT_IOCTL_READDIR_BOTH */
347 /* Now use the standard opendir/readdir interface */
349 if (!(dir->dir = opendir( path )))
351 HeapFree( SystemHeap, 0, dir );
352 return NULL;
354 return dir;
358 /***********************************************************************
359 * DOSFS_CloseDir
361 static void DOSFS_CloseDir( DOS_DIR *dir )
363 #ifdef VFAT_IOCTL_READDIR_BOTH
364 if (dir->fd != -1) close( dir->fd );
365 #endif /* VFAT_IOCTL_READDIR_BOTH */
366 if (dir->dir) closedir( dir->dir );
367 HeapFree( SystemHeap, 0, dir );
371 /***********************************************************************
372 * DOSFS_ReadDir
374 static BOOL DOSFS_ReadDir( DOS_DIR *dir, LPCSTR *long_name,
375 LPCSTR *short_name )
377 struct dirent *dirent;
379 #ifdef VFAT_IOCTL_READDIR_BOTH
380 if (dir->fd != -1)
382 if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) != -1) {
383 if (!dir->dirent[0].d_reclen) return FALSE;
384 if (!DOSFS_ToDosFCBFormat( dir->dirent[0].d_name, dir->short_name ))
385 dir->short_name[0] = '\0';
386 *short_name = dir->short_name;
387 if (dir->dirent[1].d_name[0]) *long_name = dir->dirent[1].d_name;
388 else *long_name = dir->dirent[0].d_name;
389 return TRUE;
392 #endif /* VFAT_IOCTL_READDIR_BOTH */
394 if (!(dirent = readdir( dir->dir ))) return FALSE;
395 *long_name = dirent->d_name;
396 *short_name = NULL;
397 return TRUE;
401 /***********************************************************************
402 * DOSFS_Hash
404 * Transform a Unix file name into a hashed DOS name. If the name is a valid
405 * DOS name, it is converted to upper-case; otherwise it is replaced by a
406 * hashed version that fits in 8.3 format.
407 * File name can be terminated by '\0', '\\' or '/'.
408 * 'buffer' must be at least 13 characters long.
410 static void DOSFS_Hash( LPCSTR name, LPSTR buffer, BOOL dir_format,
411 BOOL ignore_case )
413 static const char invalid_chars[] = INVALID_DOS_CHARS "~.";
414 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
416 const char *p, *ext;
417 char *dst;
418 unsigned short hash;
419 int i;
421 if (dir_format) strcpy( buffer, " " );
423 if (DOSFS_ValidDOSName( name, ignore_case ))
425 /* Check for '.' and '..' */
426 if (*name == '.')
428 buffer[0] = '.';
429 if (!dir_format) buffer[1] = buffer[2] = '\0';
430 if (name[1] == '.') buffer[1] = '.';
431 return;
434 /* Simply copy the name, converting to uppercase */
436 for (dst = buffer; !IS_END_OF_NAME(*name) && (*name != '.'); name++)
437 *dst++ = toupper(*name);
438 if (*name == '.')
440 if (dir_format) dst = buffer + 8;
441 else *dst++ = '.';
442 for (name++; !IS_END_OF_NAME(*name); name++)
443 *dst++ = toupper(*name);
445 if (!dir_format) *dst = '\0';
446 return;
449 /* Compute the hash code of the file name */
450 /* If you know something about hash functions, feel free to */
451 /* insert a better algorithm here... */
452 if (ignore_case)
454 for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
455 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p) ^ (tolower(p[1]) << 8);
456 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p); /* Last character*/
458 else
460 for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
461 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
462 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
465 /* Find last dot for start of the extension */
466 for (p = name+1, ext = NULL; !IS_END_OF_NAME(*p); p++)
467 if (*p == '.') ext = p;
468 if (ext && IS_END_OF_NAME(ext[1]))
469 ext = NULL; /* Empty extension ignored */
471 /* Copy first 4 chars, replacing invalid chars with '_' */
472 for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
474 if (IS_END_OF_NAME(*p) || (p == ext)) break;
475 *dst++ = strchr( invalid_chars, *p ) ? '_' : toupper(*p);
477 /* Pad to 5 chars with '~' */
478 while (i-- >= 0) *dst++ = '~';
480 /* Insert hash code converted to 3 ASCII chars */
481 *dst++ = hash_chars[(hash >> 10) & 0x1f];
482 *dst++ = hash_chars[(hash >> 5) & 0x1f];
483 *dst++ = hash_chars[hash & 0x1f];
485 /* Copy the first 3 chars of the extension (if any) */
486 if (ext)
488 if (!dir_format) *dst++ = '.';
489 for (i = 3, ext++; (i > 0) && !IS_END_OF_NAME(*ext); i--, ext++)
490 *dst++ = strchr( invalid_chars, *ext ) ? '_' : toupper(*ext);
492 if (!dir_format) *dst = '\0';
496 /***********************************************************************
497 * DOSFS_FindUnixName
499 * Find the Unix file name in a given directory that corresponds to
500 * a file name (either in Unix or DOS format).
501 * File name can be terminated by '\0', '\\' or '/'.
502 * Return TRUE if OK, FALSE if no file name matches.
504 * 'long_buf' must be at least 'long_len' characters long. If the long name
505 * turns out to be larger than that, the function returns FALSE.
506 * 'short_buf' must be at least 13 characters long.
508 BOOL DOSFS_FindUnixName( LPCSTR path, LPCSTR name, LPSTR long_buf,
509 INT long_len, LPSTR short_buf, BOOL ignore_case)
511 DOS_DIR *dir;
512 LPCSTR long_name, short_name;
513 char dos_name[12], tmp_buf[13];
514 BOOL ret;
516 const char *p = strchr( name, '/' );
517 int len = p ? (int)(p - name) : strlen(name);
518 if ((p = strchr( name, '\\' ))) len = MIN( (int)(p - name), len );
519 if (long_len < len + 1) return FALSE;
521 TRACE(dosfs, "%s,%s\n", path, name );
523 if (!DOSFS_ToDosFCBFormat( name, dos_name )) dos_name[0] = '\0';
525 if (!(dir = DOSFS_OpenDir( path )))
527 WARN(dosfs, "(%s,%s): can't open dir: %s\n",
528 path, name, strerror(errno) );
529 return FALSE;
532 while ((ret = DOSFS_ReadDir( dir, &long_name, &short_name )))
534 /* Check against Unix name */
535 if (len == strlen(long_name))
537 if (!ignore_case)
539 if (!lstrncmpA( long_name, name, len )) break;
541 else
543 if (!lstrncmpiA( long_name, name, len )) break;
546 if (dos_name[0])
548 /* Check against hashed DOS name */
549 if (!short_name)
551 DOSFS_Hash( long_name, tmp_buf, TRUE, ignore_case );
552 short_name = tmp_buf;
554 if (!strcmp( dos_name, short_name )) break;
557 if (ret)
559 if (long_buf) strcpy( long_buf, long_name );
560 if (short_buf)
562 if (short_name)
563 DOSFS_ToDosDTAFormat( short_name, short_buf );
564 else
565 DOSFS_Hash( long_name, short_buf, FALSE, ignore_case );
567 TRACE(dosfs, "(%s,%s) -> %s (%s)\n",
568 path, name, long_name, short_buf ? short_buf : "***");
570 else
571 WARN(dosfs, "'%s' not found in '%s'\n", name, path);
572 DOSFS_CloseDir( dir );
573 return ret;
577 /***********************************************************************
578 * DOSFS_GetDevice
580 * Check if a DOS file name represents a DOS device and return the device.
582 const DOS_DEVICE *DOSFS_GetDevice( const char *name )
584 int i;
585 const char *p;
587 if (!name) return NULL; /* if FILE_DupUnixHandle was used */
588 if (name[0] && (name[1] == ':')) name += 2;
589 if ((p = strrchr( name, '/' ))) name = p + 1;
590 if ((p = strrchr( name, '\\' ))) name = p + 1;
591 for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
593 const char *dev = DOSFS_Devices[i].name;
594 if (!lstrncmpiA( dev, name, strlen(dev) ))
596 p = name + strlen( dev );
597 if (!*p || (*p == '.')) return &DOSFS_Devices[i];
600 return NULL;
604 /***********************************************************************
605 * DOSFS_GetDeviceByHandle
607 const DOS_DEVICE *DOSFS_GetDeviceByHandle( HFILE hFile )
609 struct get_file_info_request req;
610 struct get_file_info_reply reply;
612 req.handle = hFile;
613 CLIENT_SendRequest( REQ_GET_FILE_INFO, -1, 1, &req, sizeof(req) );
614 if (!CLIENT_WaitSimpleReply( &reply, sizeof(reply), NULL ) &&
615 (reply.type == FILE_TYPE_UNKNOWN))
617 if ((reply.attr >= 0) &&
618 (reply.attr < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0])))
619 return &DOSFS_Devices[reply.attr];
621 return NULL;
625 /***********************************************************************
626 * DOSFS_OpenDevice
628 * Open a DOS device. This might not map 1:1 into the UNIX device concept.
630 HFILE DOSFS_OpenDevice( const char *name, DWORD access )
632 int i;
633 const char *p;
635 if (!name) return (HFILE)NULL; /* if FILE_DupUnixHandle was used */
636 if (name[0] && (name[1] == ':')) name += 2;
637 if ((p = strrchr( name, '/' ))) name = p + 1;
638 if ((p = strrchr( name, '\\' ))) name = p + 1;
639 for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
641 const char *dev = DOSFS_Devices[i].name;
642 if (!lstrncmpiA( dev, name, strlen(dev) ))
644 p = name + strlen( dev );
645 if (!*p || (*p == '.')) {
646 /* got it */
647 if (!strcmp(DOSFS_Devices[i].name,"NUL"))
648 return FILE_CreateFile( "/dev/null", access,
649 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
650 OPEN_EXISTING, 0, -1 );
651 if (!strcmp(DOSFS_Devices[i].name,"CON")) {
652 HFILE to_dup;
653 HFILE handle;
654 switch (access & (GENERIC_READ|GENERIC_WRITE)) {
655 case GENERIC_READ:
656 to_dup = GetStdHandle( STD_INPUT_HANDLE );
657 break;
658 case GENERIC_WRITE:
659 to_dup = GetStdHandle( STD_OUTPUT_HANDLE );
660 break;
661 default:
662 FIXME(dosfs,"can't open CON read/write\n");
663 return HFILE_ERROR;
664 break;
666 if (!DuplicateHandle( GetCurrentProcess(), to_dup, GetCurrentProcess(),
667 &handle, 0, FALSE, DUPLICATE_SAME_ACCESS ))
668 handle = HFILE_ERROR;
669 return handle;
671 if (!strcmp(DOSFS_Devices[i].name,"SCSIMGR$") ||
672 !strcmp(DOSFS_Devices[i].name,"HPSCAN"))
674 return FILE_CreateDevice( i, access, NULL );
677 HFILE r;
678 char devname[40];
679 PROFILE_GetWineIniString("serialports",name,"",devname,sizeof devname);
681 if(devname[0])
683 TRACE(file,"DOSFS_OpenDevice %s is %s\n",
684 DOSFS_Devices[i].name,devname);
685 r = FILE_CreateFile( devname, access,
686 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
687 OPEN_EXISTING, 0, -1 );
688 TRACE(file,"Create_File return %08X\n",r);
689 return r;
693 FIXME(dosfs,"device open %s not supported (yet)\n",DOSFS_Devices[i].name);
694 return HFILE_ERROR;
698 return HFILE_ERROR;
702 /***********************************************************************
703 * DOSFS_GetPathDrive
705 * Get the drive specified by a given path name (DOS or Unix format).
707 static int DOSFS_GetPathDrive( const char **name )
709 int drive;
710 const char *p = *name;
712 if (*p && (p[1] == ':'))
714 drive = toupper(*p) - 'A';
715 *name += 2;
717 else if (*p == '/') /* Absolute Unix path? */
719 if ((drive = DRIVE_FindDriveRoot( name )) == -1)
721 MSG("Warning: %s not accessible from a DOS drive\n", *name );
722 /* Assume it really was a DOS name */
723 drive = DRIVE_GetCurrentDrive();
726 else drive = DRIVE_GetCurrentDrive();
728 if (!DRIVE_IsValid(drive))
730 SetLastError( ERROR_INVALID_DRIVE );
731 return -1;
733 return drive;
737 /***********************************************************************
738 * DOSFS_GetFullName
740 * Convert a file name (DOS or mixed DOS/Unix format) to a valid
741 * Unix name / short DOS name pair.
742 * Return FALSE if one of the path components does not exist. The last path
743 * component is only checked if 'check_last' is non-zero.
744 * The buffers pointed to by 'long_buf' and 'short_buf' must be
745 * at least MAX_PATHNAME_LEN long.
747 BOOL DOSFS_GetFullName( LPCSTR name, BOOL check_last, DOS_FULL_NAME *full )
749 BOOL found;
750 UINT flags;
751 char *p_l, *p_s, *root;
753 TRACE(dosfs, "%s (last=%d)\n",
754 name, check_last );
756 if ((full->drive = DOSFS_GetPathDrive( &name )) == -1) return FALSE;
757 flags = DRIVE_GetFlags( full->drive );
759 lstrcpynA( full->long_name, DRIVE_GetRoot( full->drive ),
760 sizeof(full->long_name) );
761 if (full->long_name[1]) root = full->long_name + strlen(full->long_name);
762 else root = full->long_name; /* root directory */
764 strcpy( full->short_name, "A:\\" );
765 full->short_name[0] += full->drive;
767 if ((*name == '\\') || (*name == '/')) /* Absolute path */
769 while ((*name == '\\') || (*name == '/')) name++;
771 else /* Relative path */
773 lstrcpynA( root + 1, DRIVE_GetUnixCwd( full->drive ),
774 sizeof(full->long_name) - (root - full->long_name) - 1 );
775 if (root[1]) *root = '/';
776 lstrcpynA( full->short_name + 3, DRIVE_GetDosCwd( full->drive ),
777 sizeof(full->short_name) - 3 );
780 p_l = full->long_name[1] ? full->long_name + strlen(full->long_name)
781 : full->long_name;
782 p_s = full->short_name[3] ? full->short_name + strlen(full->short_name)
783 : full->short_name + 2;
784 found = TRUE;
786 while (*name && found)
788 /* Check for '.' and '..' */
790 if (*name == '.')
792 if (IS_END_OF_NAME(name[1]))
794 name++;
795 while ((*name == '\\') || (*name == '/')) name++;
796 continue;
798 else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
800 name += 2;
801 while ((*name == '\\') || (*name == '/')) name++;
802 while ((p_l > root) && (*p_l != '/')) p_l--;
803 while ((p_s > full->short_name + 2) && (*p_s != '\\')) p_s--;
804 *p_l = *p_s = '\0'; /* Remove trailing separator */
805 continue;
809 /* Make sure buffers are large enough */
811 if ((p_s >= full->short_name + sizeof(full->short_name) - 14) ||
812 (p_l >= full->long_name + sizeof(full->long_name) - 1))
814 SetLastError( ERROR_PATH_NOT_FOUND );
815 return FALSE;
818 /* Get the long and short name matching the file name */
820 if ((found = DOSFS_FindUnixName( full->long_name, name, p_l + 1,
821 sizeof(full->long_name) - (p_l - full->long_name) - 1,
822 p_s + 1, !(flags & DRIVE_CASE_SENSITIVE) )))
824 *p_l++ = '/';
825 p_l += strlen(p_l);
826 *p_s++ = '\\';
827 p_s += strlen(p_s);
828 while (!IS_END_OF_NAME(*name)) name++;
830 else if (!check_last)
832 *p_l++ = '/';
833 *p_s++ = '\\';
834 while (!IS_END_OF_NAME(*name) &&
835 (p_s < full->short_name + sizeof(full->short_name) - 1) &&
836 (p_l < full->long_name + sizeof(full->long_name) - 1))
838 *p_s++ = tolower(*name);
839 /* If the drive is case-sensitive we want to create new */
840 /* files in lower-case otherwise we can't reopen them */
841 /* under the same short name. */
842 if (flags & DRIVE_CASE_SENSITIVE) *p_l++ = tolower(*name);
843 else *p_l++ = *name;
844 name++;
846 *p_l = *p_s = '\0';
848 while ((*name == '\\') || (*name == '/')) name++;
851 if (!found)
853 if (check_last)
855 SetLastError( ERROR_FILE_NOT_FOUND );
856 return FALSE;
858 if (*name) /* Not last */
860 SetLastError( ERROR_PATH_NOT_FOUND );
861 return FALSE;
864 if (!full->long_name[0]) strcpy( full->long_name, "/" );
865 if (!full->short_name[2]) strcpy( full->short_name + 2, "\\" );
866 TRACE(dosfs, "returning %s = %s\n",
867 full->long_name, full->short_name );
868 return TRUE;
872 /***********************************************************************
873 * GetShortPathName32A (KERNEL32.271)
875 * NOTES
876 * observed:
877 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
878 * *longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
880 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath,
881 DWORD shortlen )
883 DOS_FULL_NAME full_name;
885 if (!longpath)
887 SetLastError(ERROR_INVALID_PARAMETER);
888 return 0;
891 if (!longpath[0])
893 SetLastError(ERROR_BAD_PATHNAME);
894 return 0;
897 /* FIXME: is it correct to always return a fully qualified short path? */
898 if (!DOSFS_GetFullName( longpath, TRUE, &full_name ))
900 SetLastError(ERROR_BAD_PATHNAME);
901 return 0;
903 lstrcpynA( shortpath, full_name.short_name, shortlen );
904 return strlen( full_name.short_name );
908 /***********************************************************************
909 * GetShortPathName32W (KERNEL32.272)
911 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath,
912 DWORD shortlen )
914 DOS_FULL_NAME full_name;
915 LPSTR longpathA ;
916 DWORD ret = 0;
918 if (!longpath)
919 { SetLastError(ERROR_INVALID_PARAMETER);
920 return 0;
923 if (!longpath[0])
924 { SetLastError(ERROR_BAD_PATHNAME);
925 return 0;
929 longpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, longpath );
931 /* FIXME: is it correct to always return a fully qualified short path? */
932 if (DOSFS_GetFullName( longpathA, TRUE, &full_name ))
934 ret = strlen( full_name.short_name );
935 lstrcpynAtoW( shortpath, full_name.short_name, shortlen );
938 SetLastError(ERROR_BAD_PATHNAME);
939 HeapFree( GetProcessHeap(), 0, longpathA );
940 return 0;
944 /***********************************************************************
945 * GetLongPathName32A (KERNEL32.xxx)
947 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath,
948 DWORD longlen )
950 DOS_FULL_NAME full_name;
951 char *p;
952 char *longfilename;
953 DWORD shortpathlen;
955 if (!DOSFS_GetFullName( shortpath, TRUE, &full_name )) return 0;
956 lstrcpynA( longpath, full_name.short_name, longlen );
957 /* Do some hackery to get the long filename.
958 * FIXME: Would be better if it returned the
959 * long version of the directories too
961 longfilename = strrchr(full_name.long_name, '/')+1;
962 if (longpath != NULL) {
963 if ((p = strrchr( longpath, '\\' )) != NULL) {
964 p++;
965 longlen -= (p-longpath);
966 lstrcpynA( p, longfilename , longlen);
969 shortpathlen =
970 ((strrchr( full_name.short_name, '\\' ) - full_name.short_name) + 1);
971 return shortpathlen + strlen( longfilename );
975 /***********************************************************************
976 * GetLongPathName32W (KERNEL32.269)
978 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath,
979 DWORD longlen )
981 DOS_FULL_NAME full_name;
982 DWORD ret = 0;
983 LPSTR shortpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, shortpath );
985 /* FIXME: is it correct to always return a fully qualified short path? */
986 if (DOSFS_GetFullName( shortpathA, TRUE, &full_name ))
988 ret = strlen( full_name.short_name );
989 lstrcpynAtoW( longpath, full_name.long_name, longlen );
991 HeapFree( GetProcessHeap(), 0, shortpathA );
992 return ret;
996 /***********************************************************************
997 * DOSFS_DoGetFullPathName
999 * Implementation of GetFullPathName32A/W.
1001 static DWORD DOSFS_DoGetFullPathName( LPCSTR name, DWORD len, LPSTR result,
1002 BOOL unicode )
1004 char buffer[MAX_PATHNAME_LEN];
1005 int drive;
1006 char *p;
1007 DWORD ret;
1009 /* last possible position for a char != 0 */
1010 char *endchar = buffer + sizeof(buffer) - 2;
1011 *endchar = '\0';
1013 TRACE(dosfs, "converting '%s'\n", name );
1015 if (!name || !result || ((drive = DOSFS_GetPathDrive( &name )) == -1) )
1016 { SetLastError( ERROR_INVALID_PARAMETER );
1017 return 0;
1020 p = buffer;
1021 *p++ = 'A' + drive;
1022 *p++ = ':';
1023 if (IS_END_OF_NAME(*name) && (*name)) /* Absolute path */
1025 while (((*name == '\\') || (*name == '/')) && (!*endchar) )
1026 *p++ = *name++;
1028 else /* Relative path or empty path */
1030 *p++ = '\\';
1031 lstrcpynA( p, DRIVE_GetDosCwd(drive), sizeof(buffer) - 4 );
1032 if ( *p )
1034 p += strlen(p);
1035 *p++ = '\\';
1038 *p = '\0';
1040 while (*name)
1042 if (*name == '.')
1044 if (IS_END_OF_NAME(name[1]))
1046 name++;
1047 while ((*name == '\\') || (*name == '/')) name++;
1048 continue;
1050 else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
1052 name += 2;
1053 while ((*name == '\\') || (*name == '/')) name++;
1055 if (p < buffer + 3) /* no previous dir component */
1056 continue;
1057 p--; /* skip previously added '\\' */
1058 while ((*p == '\\') || (*p == '/')) p--;
1059 /* skip previous dir component */
1060 while ((*p != '\\') && (*p != '/')) p--;
1061 p++;
1062 continue;
1065 if ( *endchar )
1066 { SetLastError( ERROR_PATH_NOT_FOUND );
1067 return 0;
1069 while (!IS_END_OF_NAME(*name) && (!*endchar) )
1070 *p++ = *name++;
1071 while (((*name == '\\') || (*name == '/')) && (!*endchar) )
1072 *p++ = *name++;
1074 *p = '\0';
1076 if (!(DRIVE_GetFlags(drive) & DRIVE_CASE_PRESERVING))
1077 CharUpperA( buffer );
1079 if (unicode)
1080 lstrcpynAtoW( (LPWSTR)result, buffer, len );
1081 else
1082 lstrcpynA( result, buffer, len );
1084 TRACE(dosfs, "returning '%s'\n", buffer );
1086 /* If the lpBuffer buffer is too small, the return value is the
1087 size of the buffer, in characters, required to hold the path. */
1089 ret = strlen(buffer);
1091 if (ret >= len )
1092 SetLastError( ERROR_INSUFFICIENT_BUFFER );
1094 return ret;
1098 /***********************************************************************
1099 * GetFullPathName32A (KERNEL32.272)
1100 * NOTES
1101 * if the path closed with '\', *lastpart is 0
1103 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
1104 LPSTR *lastpart )
1106 DWORD ret = DOSFS_DoGetFullPathName( name, len, buffer, FALSE );
1107 if (ret && lastpart)
1109 LPSTR p = buffer + strlen(buffer);
1111 if (*p != '\\')
1113 while ((p > buffer + 2) && (*p != '\\')) p--;
1114 *lastpart = p + 1;
1116 else *lastpart = NULL;
1118 return ret;
1122 /***********************************************************************
1123 * GetFullPathName32W (KERNEL32.273)
1125 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
1126 LPWSTR *lastpart )
1128 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1129 DWORD ret = DOSFS_DoGetFullPathName( nameA, len, (LPSTR)buffer, TRUE );
1130 HeapFree( GetProcessHeap(), 0, nameA );
1131 if (ret && lastpart)
1133 LPWSTR p = buffer + lstrlenW(buffer);
1134 if (*p != (WCHAR)'\\')
1136 while ((p > buffer + 2) && (*p != (WCHAR)'\\')) p--;
1137 *lastpart = p + 1;
1139 else *lastpart = NULL;
1141 return ret;
1144 /***********************************************************************
1145 * DOSFS_FindNextEx
1147 static int DOSFS_FindNextEx( FIND_FIRST_INFO *info, WIN32_FIND_DATAA *entry )
1149 BYTE attr = info->attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
1150 UINT flags = DRIVE_GetFlags( info->drive );
1151 char *p, buffer[MAX_PATHNAME_LEN];
1152 const char *drive_path;
1153 int drive_root;
1154 LPCSTR long_name, short_name;
1155 BY_HANDLE_FILE_INFORMATION fileinfo;
1156 char dos_name[13];
1158 if ((info->attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
1160 if (info->cur_pos) return 0;
1161 entry->dwFileAttributes = FILE_ATTRIBUTE_LABEL;
1162 DOSFS_UnixTimeToFileTime( (time_t)0, &entry->ftCreationTime, 0 );
1163 DOSFS_UnixTimeToFileTime( (time_t)0, &entry->ftLastAccessTime, 0 );
1164 DOSFS_UnixTimeToFileTime( (time_t)0, &entry->ftLastWriteTime, 0 );
1165 entry->nFileSizeHigh = 0;
1166 entry->nFileSizeLow = 0;
1167 entry->dwReserved0 = 0;
1168 entry->dwReserved1 = 0;
1169 DOSFS_ToDosDTAFormat( DRIVE_GetLabel( info->drive ), entry->cFileName );
1170 strcpy( entry->cAlternateFileName, entry->cFileName );
1171 info->cur_pos++;
1172 return 1;
1175 drive_path = info->path + strlen(DRIVE_GetRoot( info->drive ));
1176 while ((*drive_path == '/') || (*drive_path == '\\')) drive_path++;
1177 drive_root = !*drive_path;
1179 lstrcpynA( buffer, info->path, sizeof(buffer) - 1 );
1180 strcat( buffer, "/" );
1181 p = buffer + strlen(buffer);
1183 while (DOSFS_ReadDir( info->dir, &long_name, &short_name ))
1185 info->cur_pos++;
1187 /* Don't return '.' and '..' in the root of the drive */
1188 if (drive_root && (long_name[0] == '.') &&
1189 (!long_name[1] || ((long_name[1] == '.') && !long_name[2])))
1190 continue;
1192 /* Check the long mask */
1194 if (info->long_mask)
1196 if (!DOSFS_MatchLong( info->long_mask, long_name,
1197 flags & DRIVE_CASE_SENSITIVE )) continue;
1200 /* Check the short mask */
1202 if (info->short_mask)
1204 if (!short_name)
1206 DOSFS_Hash( long_name, dos_name, TRUE,
1207 !(flags & DRIVE_CASE_SENSITIVE) );
1208 short_name = dos_name;
1210 if (!DOSFS_MatchShort( info->short_mask, short_name )) continue;
1213 /* Check the file attributes */
1215 lstrcpynA( p, long_name, sizeof(buffer) - (int)(p - buffer) );
1216 if (!FILE_Stat( buffer, &fileinfo ))
1218 WARN(dosfs, "can't stat %s\n", buffer);
1219 continue;
1221 if (fileinfo.dwFileAttributes & ~attr) continue;
1223 /* We now have a matching entry; fill the result and return */
1225 entry->dwFileAttributes = fileinfo.dwFileAttributes;
1226 entry->ftCreationTime = fileinfo.ftCreationTime;
1227 entry->ftLastAccessTime = fileinfo.ftLastAccessTime;
1228 entry->ftLastWriteTime = fileinfo.ftLastWriteTime;
1229 entry->nFileSizeHigh = fileinfo.nFileSizeHigh;
1230 entry->nFileSizeLow = fileinfo.nFileSizeLow;
1232 if (short_name)
1233 DOSFS_ToDosDTAFormat( short_name, entry->cAlternateFileName );
1234 else
1235 DOSFS_Hash( long_name, entry->cAlternateFileName, FALSE,
1236 !(flags & DRIVE_CASE_SENSITIVE) );
1238 lstrcpynA( entry->cFileName, long_name, sizeof(entry->cFileName) );
1239 if (!(flags & DRIVE_CASE_PRESERVING)) CharLowerA( entry->cFileName );
1240 TRACE(dosfs, "returning %s (%s) %02lx %ld\n",
1241 entry->cFileName, entry->cAlternateFileName,
1242 entry->dwFileAttributes, entry->nFileSizeLow );
1243 return 1;
1245 return 0; /* End of directory */
1248 /***********************************************************************
1249 * DOSFS_FindNext
1251 * Find the next matching file. Return the number of entries read to find
1252 * the matching one, or 0 if no more entries.
1253 * 'short_mask' is the 8.3 mask (in FCB format), 'long_mask' is the long
1254 * file name mask. Either or both can be NULL.
1256 * NOTE: This is supposed to be only called by the int21 emulation
1257 * routines. Thus, we should own the Win16Mutex anyway.
1258 * Nevertheless, we explicitly enter it to ensure the static
1259 * directory cache is protected.
1261 int DOSFS_FindNext( const char *path, const char *short_mask,
1262 const char *long_mask, int drive, BYTE attr,
1263 int skip, WIN32_FIND_DATAA *entry )
1265 static FIND_FIRST_INFO info = { NULL };
1266 LPCSTR short_name, long_name;
1267 int count;
1269 SYSLEVEL_EnterWin16Lock();
1271 /* Check the cached directory */
1272 if (!(info.dir && info.path == path && info.short_mask == short_mask
1273 && info.long_mask == long_mask && info.drive == drive
1274 && info.attr == attr && info.cur_pos <= skip))
1276 /* Not in the cache, open it anew */
1277 if (info.dir) DOSFS_CloseDir( info.dir );
1279 info.path = (LPSTR)path;
1280 info.long_mask = (LPSTR)long_mask;
1281 info.short_mask = (LPSTR)short_mask;
1282 info.attr = attr;
1283 info.drive = drive;
1284 info.cur_pos = 0;
1285 info.dir = DOSFS_OpenDir( info.path );
1288 /* Skip to desired position */
1289 while (info.cur_pos < skip)
1290 if (info.dir && DOSFS_ReadDir( info.dir, &long_name, &short_name ))
1291 info.cur_pos++;
1292 else
1293 break;
1295 if (info.dir && info.cur_pos == skip && DOSFS_FindNextEx( &info, entry ))
1296 count = info.cur_pos - skip;
1297 else
1298 count = 0;
1300 if (!count)
1302 if (info.dir) DOSFS_CloseDir( info.dir );
1303 memset( &info, '\0', sizeof(info) );
1306 SYSLEVEL_LeaveWin16Lock();
1308 return count;
1313 /*************************************************************************
1314 * FindFirstFile16 (KERNEL.413)
1316 HANDLE16 WINAPI FindFirstFile16( LPCSTR path, WIN32_FIND_DATAA *data )
1318 DOS_FULL_NAME full_name;
1319 HGLOBAL16 handle;
1320 FIND_FIRST_INFO *info;
1322 data->dwReserved0 = data->dwReserved1 = 0x0;
1323 if (!path) return 0;
1324 if (!DOSFS_GetFullName( path, FALSE, &full_name ))
1325 return INVALID_HANDLE_VALUE16;
1326 if (!(handle = GlobalAlloc16( GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO) )))
1327 return INVALID_HANDLE_VALUE16;
1328 info = (FIND_FIRST_INFO *)GlobalLock16( handle );
1329 info->path = HEAP_strdupA( SystemHeap, 0, full_name.long_name );
1330 info->long_mask = strrchr( info->path, '/' );
1331 *(info->long_mask++) = '\0';
1332 info->short_mask = NULL;
1333 info->attr = 0xff;
1334 if (path[0] && (path[1] == ':')) info->drive = toupper(*path) - 'A';
1335 else info->drive = DRIVE_GetCurrentDrive();
1336 info->cur_pos = 0;
1338 info->dir = DOSFS_OpenDir( info->path );
1340 GlobalUnlock16( handle );
1341 if (!FindNextFile16( handle, data ))
1343 FindClose16( handle );
1344 SetLastError( ERROR_NO_MORE_FILES );
1345 return INVALID_HANDLE_VALUE16;
1347 return handle;
1351 /*************************************************************************
1352 * FindFirstFile32A (KERNEL32.123)
1354 HANDLE WINAPI FindFirstFileA( LPCSTR path, WIN32_FIND_DATAA *data )
1356 HANDLE handle = FindFirstFile16( path, data );
1357 if (handle == INVALID_HANDLE_VALUE16) return INVALID_HANDLE_VALUE;
1358 return handle;
1362 /*************************************************************************
1363 * FindFirstFile32W (KERNEL32.124)
1365 HANDLE WINAPI FindFirstFileW( LPCWSTR path, WIN32_FIND_DATAW *data )
1367 WIN32_FIND_DATAA dataA;
1368 LPSTR pathA = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1369 HANDLE handle = FindFirstFileA( pathA, &dataA );
1370 HeapFree( GetProcessHeap(), 0, pathA );
1371 if (handle != INVALID_HANDLE_VALUE)
1373 data->dwFileAttributes = dataA.dwFileAttributes;
1374 data->ftCreationTime = dataA.ftCreationTime;
1375 data->ftLastAccessTime = dataA.ftLastAccessTime;
1376 data->ftLastWriteTime = dataA.ftLastWriteTime;
1377 data->nFileSizeHigh = dataA.nFileSizeHigh;
1378 data->nFileSizeLow = dataA.nFileSizeLow;
1379 lstrcpyAtoW( data->cFileName, dataA.cFileName );
1380 lstrcpyAtoW( data->cAlternateFileName, dataA.cAlternateFileName );
1382 return handle;
1386 /*************************************************************************
1387 * FindNextFile16 (KERNEL.414)
1389 BOOL16 WINAPI FindNextFile16( HANDLE16 handle, WIN32_FIND_DATAA *data )
1391 FIND_FIRST_INFO *info;
1393 if (!(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
1395 SetLastError( ERROR_INVALID_HANDLE );
1396 return FALSE;
1398 GlobalUnlock16( handle );
1399 if (!info->path || !info->dir)
1401 SetLastError( ERROR_NO_MORE_FILES );
1402 return FALSE;
1404 if (!DOSFS_FindNextEx( info, data ))
1406 DOSFS_CloseDir( info->dir ); info->dir = NULL;
1407 HeapFree( SystemHeap, 0, info->path );
1408 info->path = info->long_mask = NULL;
1409 SetLastError( ERROR_NO_MORE_FILES );
1410 return FALSE;
1412 return TRUE;
1416 /*************************************************************************
1417 * FindNextFile32A (KERNEL32.126)
1419 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1421 return FindNextFile16( handle, data );
1425 /*************************************************************************
1426 * FindNextFile32W (KERNEL32.127)
1428 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1430 WIN32_FIND_DATAA dataA;
1431 if (!FindNextFileA( handle, &dataA )) return FALSE;
1432 data->dwFileAttributes = dataA.dwFileAttributes;
1433 data->ftCreationTime = dataA.ftCreationTime;
1434 data->ftLastAccessTime = dataA.ftLastAccessTime;
1435 data->ftLastWriteTime = dataA.ftLastWriteTime;
1436 data->nFileSizeHigh = dataA.nFileSizeHigh;
1437 data->nFileSizeLow = dataA.nFileSizeLow;
1438 lstrcpyAtoW( data->cFileName, dataA.cFileName );
1439 lstrcpyAtoW( data->cAlternateFileName, dataA.cAlternateFileName );
1440 return TRUE;
1444 /*************************************************************************
1445 * FindClose16 (KERNEL.415)
1447 BOOL16 WINAPI FindClose16( HANDLE16 handle )
1449 FIND_FIRST_INFO *info;
1451 if ((handle == INVALID_HANDLE_VALUE16) ||
1452 !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
1454 SetLastError( ERROR_INVALID_HANDLE );
1455 return FALSE;
1457 if (info->dir) DOSFS_CloseDir( info->dir );
1458 if (info->path) HeapFree( SystemHeap, 0, info->path );
1459 GlobalUnlock16( handle );
1460 GlobalFree16( handle );
1461 return TRUE;
1465 /*************************************************************************
1466 * FindClose32 (KERNEL32.119)
1468 BOOL WINAPI FindClose( HANDLE handle )
1470 return FindClose16( (HANDLE16)handle );
1474 /***********************************************************************
1475 * DOSFS_UnixTimeToFileTime
1477 * Convert a Unix time to FILETIME format.
1478 * The FILETIME structure is a 64-bit value representing the number of
1479 * 100-nanosecond intervals since January 1, 1601, 0:00.
1480 * 'remainder' is the nonnegative number of 100-ns intervals
1481 * corresponding to the time fraction smaller than 1 second that
1482 * couldn't be stored in the time_t value.
1484 void DOSFS_UnixTimeToFileTime( time_t unix_time, FILETIME *filetime,
1485 DWORD remainder )
1487 /* NOTES:
1489 CONSTANTS:
1490 The time difference between 1 January 1601, 00:00:00 and
1491 1 January 1970, 00:00:00 is 369 years, plus the leap years
1492 from 1604 to 1968, excluding 1700, 1800, 1900.
1493 This makes (1968 - 1600) / 4 - 3 = 89 leap days, and a total
1494 of 134774 days.
1496 Any day in that period had 24 * 60 * 60 = 86400 seconds.
1498 The time difference is 134774 * 86400 * 10000000, which can be written
1499 116444736000000000
1500 27111902 * 2^32 + 3577643008
1501 413 * 2^48 + 45534 * 2^32 + 54590 * 2^16 + 32768
1503 If you find that these constants are buggy, please change them in all
1504 instances in both conversion functions.
1506 VERSIONS:
1507 There are two versions, one of them uses long long variables and
1508 is presumably faster but not ISO C. The other one uses standard C
1509 data types and operations but relies on the assumption that negative
1510 numbers are stored as 2's complement (-1 is 0xffff....). If this
1511 assumption is violated, dates before 1970 will not convert correctly.
1512 This should however work on any reasonable architecture where WINE
1513 will run.
1515 DETAILS:
1517 Take care not to remove the casts. I have tested these functions
1518 (in both versions) for a lot of numbers. I would be interested in
1519 results on other compilers than GCC.
1521 The operations have been designed to account for the possibility
1522 of 64-bit time_t in future UNICES. Even the versions without
1523 internal long long numbers will work if time_t only is 64 bit.
1524 A 32-bit shift, which was necessary for that operation, turned out
1525 not to work correctly in GCC, besides giving the warning. So I
1526 used a double 16-bit shift instead. Numbers are in the ISO version
1527 represented by three limbs, the most significant with 32 bit, the
1528 other two with 16 bit each.
1530 As the modulo-operator % is not well-defined for negative numbers,
1531 negative divisors have been avoided in DOSFS_FileTimeToUnixTime.
1533 There might be quicker ways to do this in C. Certainly so in
1534 assembler.
1536 Claus Fischer, fischer@iue.tuwien.ac.at
1539 #if (SIZEOF_LONG_LONG >= 8)
1540 # define USE_LONG_LONG 1
1541 #else
1542 # define USE_LONG_LONG 0
1543 #endif
1545 #if USE_LONG_LONG /* gcc supports long long type */
1547 long long int t = unix_time;
1548 t *= 10000000;
1549 t += 116444736000000000LL;
1550 t += remainder;
1551 filetime->dwLowDateTime = (UINT)t;
1552 filetime->dwHighDateTime = (UINT)(t >> 32);
1554 #else /* ISO version */
1556 UINT a0; /* 16 bit, low bits */
1557 UINT a1; /* 16 bit, medium bits */
1558 UINT a2; /* 32 bit, high bits */
1560 /* Copy the unix time to a2/a1/a0 */
1561 a0 = unix_time & 0xffff;
1562 a1 = (unix_time >> 16) & 0xffff;
1563 /* This is obsolete if unix_time is only 32 bits, but it does not hurt.
1564 Do not replace this by >> 32, it gives a compiler warning and it does
1565 not work. */
1566 a2 = (unix_time >= 0 ? (unix_time >> 16) >> 16 :
1567 ~((~unix_time >> 16) >> 16));
1569 /* Multiply a by 10000000 (a = a2/a1/a0)
1570 Split the factor into 10000 * 1000 which are both less than 0xffff. */
1571 a0 *= 10000;
1572 a1 = a1 * 10000 + (a0 >> 16);
1573 a2 = a2 * 10000 + (a1 >> 16);
1574 a0 &= 0xffff;
1575 a1 &= 0xffff;
1577 a0 *= 1000;
1578 a1 = a1 * 1000 + (a0 >> 16);
1579 a2 = a2 * 1000 + (a1 >> 16);
1580 a0 &= 0xffff;
1581 a1 &= 0xffff;
1583 /* Add the time difference and the remainder */
1584 a0 += 32768 + (remainder & 0xffff);
1585 a1 += 54590 + (remainder >> 16 ) + (a0 >> 16);
1586 a2 += 27111902 + (a1 >> 16);
1587 a0 &= 0xffff;
1588 a1 &= 0xffff;
1590 /* Set filetime */
1591 filetime->dwLowDateTime = (a1 << 16) + a0;
1592 filetime->dwHighDateTime = a2;
1593 #endif
1597 /***********************************************************************
1598 * DOSFS_FileTimeToUnixTime
1600 * Convert a FILETIME format to Unix time.
1601 * If not NULL, 'remainder' contains the fractional part of the filetime,
1602 * in the range of [0..9999999] (even if time_t is negative).
1604 time_t DOSFS_FileTimeToUnixTime( const FILETIME *filetime, DWORD *remainder )
1606 /* Read the comment in the function DOSFS_UnixTimeToFileTime. */
1607 #if USE_LONG_LONG
1609 long long int t = filetime->dwHighDateTime;
1610 t <<= 32;
1611 t += (UINT)filetime->dwLowDateTime;
1612 t -= 116444736000000000LL;
1613 if (t < 0)
1615 if (remainder) *remainder = 9999999 - (-t - 1) % 10000000;
1616 return -1 - ((-t - 1) / 10000000);
1618 else
1620 if (remainder) *remainder = t % 10000000;
1621 return t / 10000000;
1624 #else /* ISO version */
1626 UINT a0; /* 16 bit, low bits */
1627 UINT a1; /* 16 bit, medium bits */
1628 UINT a2; /* 32 bit, high bits */
1629 UINT r; /* remainder of division */
1630 unsigned int carry; /* carry bit for subtraction */
1631 int negative; /* whether a represents a negative value */
1633 /* Copy the time values to a2/a1/a0 */
1634 a2 = (UINT)filetime->dwHighDateTime;
1635 a1 = ((UINT)filetime->dwLowDateTime ) >> 16;
1636 a0 = ((UINT)filetime->dwLowDateTime ) & 0xffff;
1638 /* Subtract the time difference */
1639 if (a0 >= 32768 ) a0 -= 32768 , carry = 0;
1640 else a0 += (1 << 16) - 32768 , carry = 1;
1642 if (a1 >= 54590 + carry) a1 -= 54590 + carry, carry = 0;
1643 else a1 += (1 << 16) - 54590 - carry, carry = 1;
1645 a2 -= 27111902 + carry;
1647 /* If a is negative, replace a by (-1-a) */
1648 negative = (a2 >= ((UINT)1) << 31);
1649 if (negative)
1651 /* Set a to -a - 1 (a is a2/a1/a0) */
1652 a0 = 0xffff - a0;
1653 a1 = 0xffff - a1;
1654 a2 = ~a2;
1657 /* Divide a by 10000000 (a = a2/a1/a0), put the rest into r.
1658 Split the divisor into 10000 * 1000 which are both less than 0xffff. */
1659 a1 += (a2 % 10000) << 16;
1660 a2 /= 10000;
1661 a0 += (a1 % 10000) << 16;
1662 a1 /= 10000;
1663 r = a0 % 10000;
1664 a0 /= 10000;
1666 a1 += (a2 % 1000) << 16;
1667 a2 /= 1000;
1668 a0 += (a1 % 1000) << 16;
1669 a1 /= 1000;
1670 r += (a0 % 1000) * 10000;
1671 a0 /= 1000;
1673 /* If a was negative, replace a by (-1-a) and r by (9999999 - r) */
1674 if (negative)
1676 /* Set a to -a - 1 (a is a2/a1/a0) */
1677 a0 = 0xffff - a0;
1678 a1 = 0xffff - a1;
1679 a2 = ~a2;
1681 r = 9999999 - r;
1684 if (remainder) *remainder = r;
1686 /* Do not replace this by << 32, it gives a compiler warning and it does
1687 not work. */
1688 return ((((time_t)a2) << 16) << 16) + (a1 << 16) + a0;
1689 #endif
1693 /***********************************************************************
1694 * DosDateTimeToFileTime (KERNEL32.76)
1696 BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, LPFILETIME ft)
1698 struct tm newtm;
1700 newtm.tm_sec = (fattime & 0x1f) * 2;
1701 newtm.tm_min = (fattime >> 5) & 0x3f;
1702 newtm.tm_hour = (fattime >> 11);
1703 newtm.tm_mday = (fatdate & 0x1f);
1704 newtm.tm_mon = ((fatdate >> 5) & 0x0f) - 1;
1705 newtm.tm_year = (fatdate >> 9) + 80;
1706 DOSFS_UnixTimeToFileTime( mktime( &newtm ), ft, 0 );
1707 return TRUE;
1711 /***********************************************************************
1712 * FileTimeToDosDateTime (KERNEL32.111)
1714 BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, LPWORD fatdate,
1715 LPWORD fattime )
1717 time_t unixtime = DOSFS_FileTimeToUnixTime( ft, NULL );
1718 struct tm *tm = localtime( &unixtime );
1719 if (fattime)
1720 *fattime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
1721 if (fatdate)
1722 *fatdate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5)
1723 + tm->tm_mday;
1724 return TRUE;
1728 /***********************************************************************
1729 * LocalFileTimeToFileTime (KERNEL32.373)
1731 BOOL WINAPI LocalFileTimeToFileTime( const FILETIME *localft,
1732 LPFILETIME utcft )
1734 struct tm *xtm;
1735 DWORD remainder;
1737 /* convert from local to UTC. Perhaps not correct. FIXME */
1738 time_t unixtime = DOSFS_FileTimeToUnixTime( localft, &remainder );
1739 xtm = gmtime( &unixtime );
1740 DOSFS_UnixTimeToFileTime( mktime(xtm), utcft, remainder );
1741 return TRUE;
1745 /***********************************************************************
1746 * FileTimeToLocalFileTime (KERNEL32.112)
1748 BOOL WINAPI FileTimeToLocalFileTime( const FILETIME *utcft,
1749 LPFILETIME localft )
1751 DWORD remainder;
1752 /* convert from UTC to local. Perhaps not correct. FIXME */
1753 time_t unixtime = DOSFS_FileTimeToUnixTime( utcft, &remainder );
1754 #ifdef HAVE_TIMEGM
1755 struct tm *xtm = localtime( &unixtime );
1756 time_t localtime;
1758 localtime = timegm(xtm);
1759 DOSFS_UnixTimeToFileTime( localtime, localft, remainder );
1761 #else
1762 struct tm *xtm,*gtm;
1763 time_t time1,time2;
1765 xtm = localtime( &unixtime );
1766 gtm = gmtime( &unixtime );
1767 time1 = mktime(xtm);
1768 time2 = mktime(gtm);
1769 DOSFS_UnixTimeToFileTime( 2*time1-time2, localft, remainder );
1770 #endif
1771 return TRUE;
1775 /***********************************************************************
1776 * FileTimeToSystemTime (KERNEL32.113)
1778 BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst )
1780 struct tm *xtm;
1781 DWORD remainder;
1782 time_t xtime = DOSFS_FileTimeToUnixTime( ft, &remainder );
1783 xtm = gmtime(&xtime);
1784 syst->wYear = xtm->tm_year+1900;
1785 syst->wMonth = xtm->tm_mon + 1;
1786 syst->wDayOfWeek = xtm->tm_wday;
1787 syst->wDay = xtm->tm_mday;
1788 syst->wHour = xtm->tm_hour;
1789 syst->wMinute = xtm->tm_min;
1790 syst->wSecond = xtm->tm_sec;
1791 syst->wMilliseconds = remainder / 10000;
1792 return TRUE;
1795 /***********************************************************************
1796 * QueryDosDeviceA (KERNEL32.413)
1798 * returns array of strings terminated by \0, terminated by \0
1800 DWORD WINAPI QueryDosDeviceA(LPCSTR devname,LPSTR target,DWORD bufsize)
1802 LPSTR s;
1803 char buffer[200];
1805 TRACE(dosfs,"(%s,...)\n",devname?devname:"<null>");
1806 if (!devname) {
1807 /* return known MSDOS devices */
1808 lstrcpyA(buffer,"CON COM1 COM2 LPT1 NUL ");
1809 while ((s=strchr(buffer,' ')))
1810 *s='\0';
1812 lstrcpynA(target,buffer,bufsize);
1813 return strlen(buffer);
1815 lstrcpyA(buffer,"\\DEV\\");
1816 lstrcatA(buffer,devname);
1817 if ((s=strchr(buffer,':'))) *s='\0';
1818 lstrcpynA(target,buffer,bufsize);
1819 return strlen(buffer);
1823 /***********************************************************************
1824 * QueryDosDeviceW (KERNEL32.414)
1826 * returns array of strings terminated by \0, terminated by \0
1828 DWORD WINAPI QueryDosDeviceW(LPCWSTR devname,LPWSTR target,DWORD bufsize)
1830 LPSTR devnameA = devname?HEAP_strdupWtoA(GetProcessHeap(),0,devname):NULL;
1831 LPSTR targetA = (LPSTR)HEAP_xalloc(GetProcessHeap(),0,bufsize);
1832 DWORD ret = QueryDosDeviceA(devnameA,targetA,bufsize);
1834 lstrcpynAtoW(target,targetA,bufsize);
1835 if (devnameA) HeapFree(GetProcessHeap(),0,devnameA);
1836 if (targetA) HeapFree(GetProcessHeap(),0,targetA);
1837 return ret;
1841 /***********************************************************************
1842 * SystemTimeToFileTime (KERNEL32.526)
1844 BOOL WINAPI SystemTimeToFileTime( const SYSTEMTIME *syst, LPFILETIME ft )
1846 #ifdef HAVE_TIMEGM
1847 struct tm xtm;
1848 time_t utctime;
1849 #else
1850 struct tm xtm,*local_tm,*utc_tm;
1851 time_t localtim,utctime;
1852 #endif
1854 xtm.tm_year = syst->wYear-1900;
1855 xtm.tm_mon = syst->wMonth - 1;
1856 xtm.tm_wday = syst->wDayOfWeek;
1857 xtm.tm_mday = syst->wDay;
1858 xtm.tm_hour = syst->wHour;
1859 xtm.tm_min = syst->wMinute;
1860 xtm.tm_sec = syst->wSecond; /* this is UTC */
1861 xtm.tm_isdst = -1;
1862 #ifdef HAVE_TIMEGM
1863 utctime = timegm(&xtm);
1864 DOSFS_UnixTimeToFileTime( utctime, ft,
1865 syst->wMilliseconds * 10000 );
1866 #else
1867 localtim = mktime(&xtm); /* now we've got local time */
1868 local_tm = localtime(&localtim);
1869 utc_tm = gmtime(&localtim);
1870 utctime = mktime(utc_tm);
1871 DOSFS_UnixTimeToFileTime( 2*localtim -utctime, ft,
1872 syst->wMilliseconds * 10000 );
1873 #endif
1874 return TRUE;
1877 BOOL WINAPI DefineDosDeviceA(DWORD flags,LPCSTR devname,LPCSTR targetpath) {
1878 FIXME(dosfs,"(0x%08lx,%s,%s),stub!\n",flags,devname,targetpath);
1879 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1880 return FALSE;