wined3d: Recognize SM4 ftou opcode.
[wine.git] / dlls / ntdll / directory.c
blobf3c6aa21dd138809e49e7d48d16f91f20b3aa447
1 /*
2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 #endif
47 #ifdef HAVE_SYS_ATTR_H
48 #include <sys/attr.h>
49 #endif
50 #ifdef HAVE_SYS_VNODE_H
51 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
52 #define list SYSLIST
53 #define list_next SYSLIST_NEXT
54 #define list_prev SYSLIST_PREV
55 #define list_head SYSLIST_HEAD
56 #define list_tail SYSLIST_TAIL
57 #define list_move_tail SYSLIST_MOVE_TAIL
58 #define list_remove SYSLIST_REMOVE
59 #include <sys/vnode.h>
60 #undef list
61 #undef list_next
62 #undef list_prev
63 #undef list_head
64 #undef list_tail
65 #undef list_move_tail
66 #undef list_remove
67 #endif
68 #ifdef HAVE_SYS_IOCTL_H
69 #include <sys/ioctl.h>
70 #endif
71 #ifdef HAVE_LINUX_IOCTL_H
72 #include <linux/ioctl.h>
73 #endif
74 #ifdef HAVE_LINUX_MAJOR_H
75 # include <linux/major.h>
76 #endif
77 #ifdef HAVE_SYS_PARAM_H
78 #include <sys/param.h>
79 #endif
80 #ifdef HAVE_SYS_MOUNT_H
81 #include <sys/mount.h>
82 #endif
83 #ifdef HAVE_SYS_STATFS_H
84 #include <sys/statfs.h>
85 #endif
86 #include <time.h>
87 #ifdef HAVE_UNISTD_H
88 # include <unistd.h>
89 #endif
91 #include "ntstatus.h"
92 #define WIN32_NO_STATUS
93 #define NONAMELESSUNION
94 #include "windef.h"
95 #include "winnt.h"
96 #include "winternl.h"
97 #include "ddk/wdm.h"
98 #include "ntdll_misc.h"
99 #include "wine/unicode.h"
100 #include "wine/server.h"
101 #include "wine/list.h"
102 #include "wine/library.h"
103 #include "wine/debug.h"
105 WINE_DEFAULT_DEBUG_CHANNEL(file);
107 /* just in case... */
108 #undef VFAT_IOCTL_READDIR_BOTH
109 #undef USE_GETDENTS
111 #ifdef linux
113 /* We want the real kernel dirent structure, not the libc one */
114 typedef struct
116 long d_ino;
117 long d_off;
118 unsigned short d_reclen;
119 char d_name[256];
120 } KERNEL_DIRENT;
122 /* Define the VFAT ioctl to get both short and long file names */
123 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
125 #ifndef O_DIRECTORY
126 # define O_DIRECTORY 0200000 /* must be directory */
127 #endif
129 #ifdef __NR_getdents64
130 typedef struct
132 ULONG64 d_ino;
133 LONG64 d_off;
134 unsigned short d_reclen;
135 unsigned char d_type;
136 char d_name[256];
137 } KERNEL_DIRENT64;
139 #undef getdents64
140 static inline int getdents64( int fd, char *de, unsigned int size )
142 return syscall( __NR_getdents64, fd, de, size );
144 #define USE_GETDENTS
145 #endif
147 #endif /* linux */
149 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
150 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
152 #define INVALID_NT_CHARS '*','?','<','>','|','"'
153 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
155 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
157 #define MAX_IGNORED_FILES 4
159 struct file_identity
161 dev_t dev;
162 ino_t ino;
165 static struct file_identity ignored_files[MAX_IGNORED_FILES];
166 static unsigned int ignored_files_count;
168 union file_directory_info
170 ULONG next;
171 FILE_DIRECTORY_INFORMATION dir;
172 FILE_BOTH_DIRECTORY_INFORMATION both;
173 FILE_FULL_DIRECTORY_INFORMATION full;
174 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
175 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
178 static BOOL show_dot_files;
179 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
181 /* at some point we may want to allow Winelib apps to set this */
182 static const BOOL is_case_sensitive = FALSE;
184 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
186 static struct file_identity curdir;
187 static struct file_identity windir;
189 static RTL_CRITICAL_SECTION dir_section;
190 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
192 0, 0, &dir_section,
193 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
194 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
196 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
199 /* check if a given Unicode char is OK in a DOS short name */
200 static inline BOOL is_invalid_dos_char( WCHAR ch )
202 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
203 if (ch > 0x7f) return TRUE;
204 return strchrW( invalid_chars, ch ) != NULL;
207 /* check if the device can be a mounted volume */
208 static inline BOOL is_valid_mounted_device( const struct stat *st )
210 #if defined(linux) || defined(__sun__)
211 return S_ISBLK( st->st_mode );
212 #else
213 /* disks are char devices on *BSD */
214 return S_ISCHR( st->st_mode );
215 #endif
218 static inline void ignore_file( const char *name )
220 struct stat st;
221 assert( ignored_files_count < MAX_IGNORED_FILES );
222 if (!stat( name, &st ))
224 ignored_files[ignored_files_count].dev = st.st_dev;
225 ignored_files[ignored_files_count].ino = st.st_ino;
226 ignored_files_count++;
230 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
232 return st->st_dev == file->dev && st->st_ino == file->ino;
235 static inline BOOL is_ignored_file( const struct stat *st )
237 unsigned int i;
239 for (i = 0; i < ignored_files_count; i++)
240 if (is_same_file( &ignored_files[i], st )) return TRUE;
241 return FALSE;
244 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
246 switch (class)
248 case FileDirectoryInformation:
249 return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
250 case FileBothDirectoryInformation:
251 return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
252 case FileFullDirectoryInformation:
253 return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
254 case FileIdBothDirectoryInformation:
255 return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
256 case FileIdFullDirectoryInformation:
257 return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 7) & ~7;
258 default:
259 assert(0);
260 return 0;
264 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
266 return dir_info_size( class, MAX_DIR_ENTRY_LEN );
269 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
271 return (!mask ||
272 memchrW( mask->Buffer, '*', mask->Length / sizeof(WCHAR) ) ||
273 memchrW( mask->Buffer, '?', mask->Length / sizeof(WCHAR) ));
277 /* support for a directory queue for filesystem searches */
279 struct dir_name
281 struct list entry;
282 char name[1];
285 static struct list dir_queue = LIST_INIT( dir_queue );
287 static NTSTATUS add_dir_to_queue( const char *name )
289 int len = strlen( name ) + 1;
290 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
291 FIELD_OFFSET( struct dir_name, name[len] ));
292 if (!dir) return STATUS_NO_MEMORY;
293 strcpy( dir->name, name );
294 list_add_tail( &dir_queue, &dir->entry );
295 return STATUS_SUCCESS;
298 static NTSTATUS next_dir_in_queue( char *name )
300 struct list *head = list_head( &dir_queue );
301 if (head)
303 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
304 strcpy( name, dir->name );
305 list_remove( &dir->entry );
306 RtlFreeHeap( GetProcessHeap(), 0, dir );
307 return STATUS_SUCCESS;
309 return STATUS_OBJECT_NAME_NOT_FOUND;
312 static void flush_dir_queue(void)
314 struct list *head;
316 while ((head = list_head( &dir_queue )))
318 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
319 list_remove( &dir->entry );
320 RtlFreeHeap( GetProcessHeap(), 0, dir );
325 /***********************************************************************
326 * get_default_com_device
328 * Return the default device to use for serial ports.
330 static char *get_default_com_device( int num )
332 char *ret = NULL;
334 if (num < 1 || num > 256) return NULL;
335 #ifdef linux
336 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS256") );
337 if (!ret) return NULL;
338 sprintf( ret, "/dev/ttyS%d", num - 1 );
339 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
340 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuau256") );
341 if (!ret) return NULL;
342 sprintf( ret, "/dev/cuau%d", num - 1 );
343 #elif defined(__DragonFly__)
344 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuaa256") );
345 if (!ret) return NULL;
346 sprintf( ret, "/dev/cuaa%d", num - 1 );
347 #else
348 FIXME( "no known default for device com%d\n", num );
349 #endif
350 return ret;
354 /***********************************************************************
355 * get_default_lpt_device
357 * Return the default device to use for parallel ports.
359 static char *get_default_lpt_device( int num )
361 char *ret = NULL;
363 if (num < 1 || num > 256) return NULL;
364 #ifdef linux
365 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp256") );
366 if (!ret) return NULL;
367 sprintf( ret, "/dev/lp%d", num - 1 );
368 #else
369 FIXME( "no known default for device lpt%d\n", num );
370 #endif
371 return ret;
374 #ifdef __ANDROID__
376 static char *unescape_field( char *str )
378 char *in, *out;
380 for (in = out = str; *in; in++, out++)
382 *out = *in;
383 if (in[0] == '\\')
385 if (in[1] == '\\')
387 out[0] = '\\';
388 in++;
390 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
392 out[0] = ' ';
393 in += 3;
395 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
397 out[0] = '\t';
398 in += 3;
400 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
402 out[0] = '\n';
403 in += 3;
405 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
407 out[0] = '\\';
408 in += 3;
412 *out = '\0';
414 return str;
417 static inline char *get_field( char **str )
419 char *ret;
421 ret = strsep( str, " \t" );
422 if (*str) *str += strspn( *str, " \t" );
424 return ret;
426 /************************************************************************
427 * getmntent_replacement
429 * getmntent replacement for Android.
431 * NB returned static buffer is not thread safe; protect with dir_section.
433 static struct mntent *getmntent_replacement( FILE *f )
435 static struct mntent entry;
436 static char buf[4096];
437 char *p, *start;
441 if (!fgets( buf, sizeof(buf), f )) return NULL;
442 p = strchr( buf, '\n' );
443 if (p) *p = '\0';
444 else /* Partially unread line, move file ptr to end */
446 char tmp[1024];
447 while (fgets( tmp, sizeof(tmp), f ))
448 if (strchr( tmp, '\n' )) break;
450 start = buf + strspn( buf, " \t" );
451 } while (start[0] == '\0' || start[0] == '#');
453 p = get_field( &start );
454 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
456 p = get_field( &start );
457 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
459 p = get_field( &start );
460 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
462 p = get_field( &start );
463 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
465 p = get_field( &start );
466 entry.mnt_freq = p ? atoi(p) : 0;
468 p = get_field( &start );
469 entry.mnt_passno = p ? atoi(p) : 0;
471 return &entry;
473 #define getmntent getmntent_replacement
474 #endif
476 /***********************************************************************
477 * DIR_get_drives_info
479 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
481 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
483 static struct drive_info cache[MAX_DOS_DRIVES];
484 static time_t last_update;
485 static unsigned int nb_drives;
486 unsigned int ret;
487 time_t now = time(NULL);
489 RtlEnterCriticalSection( &dir_section );
490 if (now != last_update)
492 const char *config_dir = wine_get_config_dir();
493 char *buffer, *p;
494 struct stat st;
495 unsigned int i;
497 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
498 strlen(config_dir) + sizeof("/dosdevices/a:") )))
500 strcpy( buffer, config_dir );
501 strcat( buffer, "/dosdevices/a:" );
502 p = buffer + strlen(buffer) - 2;
504 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
506 *p = 'a' + i;
507 if (!stat( buffer, &st ))
509 cache[i].dev = st.st_dev;
510 cache[i].ino = st.st_ino;
511 nb_drives++;
513 else
515 cache[i].dev = 0;
516 cache[i].ino = 0;
519 RtlFreeHeap( GetProcessHeap(), 0, buffer );
521 last_update = now;
523 memcpy( info, cache, sizeof(cache) );
524 ret = nb_drives;
525 RtlLeaveCriticalSection( &dir_section );
526 return ret;
530 /***********************************************************************
531 * parse_mount_entries
533 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
536 #ifdef sun
537 #include <sys/vfstab.h>
538 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
540 struct vfstab entry;
541 struct stat st;
542 char *device;
544 while (! getvfsent( f, &entry ))
546 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
547 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
548 !strcmp( entry.vfs_fstype, "smbfs" ) ||
549 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
551 if (stat( entry.vfs_mountp, &st ) == -1) continue;
552 if (st.st_dev != dev || st.st_ino != ino) continue;
553 if (!strcmp( entry.vfs_fstype, "fd" ))
555 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
557 char *p = strchr( device + 4, ',' );
558 if (p) *p = 0;
559 return device + 4;
562 else
563 return entry.vfs_special;
565 return NULL;
567 #endif
569 #ifdef linux
570 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
572 struct mntent *entry;
573 struct stat st;
574 char *device;
576 while ((entry = getmntent( f )))
578 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
579 if (!strcmp( entry->mnt_type, "nfs" ) ||
580 !strcmp( entry->mnt_type, "smbfs" ) ||
581 !strcmp( entry->mnt_type, "ncpfs" )) continue;
583 if (stat( entry->mnt_dir, &st ) == -1) continue;
584 if (st.st_dev != dev || st.st_ino != ino) continue;
585 if (!strcmp( entry->mnt_type, "supermount" ))
587 if ((device = strstr( entry->mnt_opts, "dev=" )))
589 char *p = strchr( device + 4, ',' );
590 if (p) *p = 0;
591 return device + 4;
594 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
596 /* if device is a regular file check for a loop mount */
597 if ((device = strstr( entry->mnt_opts, "loop=" )))
599 char *p = strchr( device + 5, ',' );
600 if (p) *p = 0;
601 return device + 5;
604 else
605 return entry->mnt_fsname;
607 return NULL;
609 #endif
611 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
612 #include <fstab.h>
613 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
615 struct fstab *entry;
616 struct stat st;
618 while ((entry = getfsent()))
620 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
621 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
622 !strcmp( entry->fs_vfstype, "smbfs" ) ||
623 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
625 if (stat( entry->fs_file, &st ) == -1) continue;
626 if (st.st_dev != dev || st.st_ino != ino) continue;
627 return entry->fs_spec;
629 return NULL;
631 #endif
633 #ifdef sun
634 #include <sys/mnttab.h>
635 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
637 struct mnttab entry;
638 struct stat st;
639 char *device;
642 while (( ! getmntent( f, &entry) ))
644 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
645 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
646 !strcmp( entry.mnt_fstype, "smbfs" ) ||
647 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
649 if (stat( entry.mnt_mountp, &st ) == -1) continue;
650 if (st.st_dev != dev || st.st_ino != ino) continue;
651 if (!strcmp( entry.mnt_fstype, "fd" ))
653 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
655 char *p = strchr( device + 4, ',' );
656 if (p) *p = 0;
657 return device + 4;
660 else
661 return entry.mnt_special;
663 return NULL;
665 #endif
667 /***********************************************************************
668 * get_default_drive_device
670 * Return the default device to use for a given drive mount point.
672 static char *get_default_drive_device( const char *root )
674 char *ret = NULL;
676 #ifdef linux
677 FILE *f;
678 char *device = NULL;
679 int fd, res = -1;
680 struct stat st;
682 /* try to open it first to force it to get mounted */
683 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
685 res = fstat( fd, &st );
686 close( fd );
688 /* now try normal stat just in case */
689 if (res == -1) res = stat( root, &st );
690 if (res == -1) return NULL;
692 RtlEnterCriticalSection( &dir_section );
694 #ifdef __ANDROID__
695 if ((f = fopen( "/proc/mounts", "r" )))
697 device = parse_mount_entries( f, st.st_dev, st.st_ino );
698 fclose( f );
700 #else
701 if ((f = fopen( "/etc/mtab", "r" )))
703 device = parse_mount_entries( f, st.st_dev, st.st_ino );
704 fclose( f );
706 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
707 if (!device && (f = fopen( "/etc/fstab", "r" )))
709 device = parse_mount_entries( f, st.st_dev, st.st_ino );
710 fclose( f );
712 #endif
713 if (device)
715 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
716 if (ret) strcpy( ret, device );
718 RtlLeaveCriticalSection( &dir_section );
720 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
721 char *device = NULL;
722 int fd, res = -1;
723 struct stat st;
725 /* try to open it first to force it to get mounted */
726 if ((fd = open( root, O_RDONLY )) != -1)
728 res = fstat( fd, &st );
729 close( fd );
731 /* now try normal stat just in case */
732 if (res == -1) res = stat( root, &st );
733 if (res == -1) return NULL;
735 RtlEnterCriticalSection( &dir_section );
737 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
738 * pass NULL. Leave the argument in for symmetry.
740 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
741 if (device)
743 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
744 if (ret) strcpy( ret, device );
746 RtlLeaveCriticalSection( &dir_section );
748 #elif defined( sun )
749 FILE *f;
750 char *device = NULL;
751 int fd, res = -1;
752 struct stat st;
754 /* try to open it first to force it to get mounted */
755 if ((fd = open( root, O_RDONLY )) != -1)
757 res = fstat( fd, &st );
758 close( fd );
760 /* now try normal stat just in case */
761 if (res == -1) res = stat( root, &st );
762 if (res == -1) return NULL;
764 RtlEnterCriticalSection( &dir_section );
766 if ((f = fopen( "/etc/mnttab", "r" )))
768 device = parse_mount_entries( f, st.st_dev, st.st_ino);
769 fclose( f );
771 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
772 if (!device && (f = fopen( "/etc/vfstab", "r" )))
774 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
775 fclose( f );
777 if (device)
779 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
780 if (ret) strcpy( ret, device );
782 RtlLeaveCriticalSection( &dir_section );
784 #elif defined(__APPLE__)
785 struct statfs *mntStat;
786 struct stat st;
787 int i;
788 int mntSize;
789 dev_t dev;
790 ino_t ino;
791 static const char path_bsd_device[] = "/dev/disk";
792 int res;
794 res = stat( root, &st );
795 if (res == -1) return NULL;
797 dev = st.st_dev;
798 ino = st.st_ino;
800 RtlEnterCriticalSection( &dir_section );
802 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
804 for (i = 0; i < mntSize && !ret; i++)
806 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
807 if (st.st_dev != dev || st.st_ino != ino) continue;
809 /* FIXME add support for mounted network drive */
810 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
812 /* set return value to the corresponding raw BSD node */
813 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
814 if (ret)
816 strcpy(ret, "/dev/r");
817 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
821 RtlLeaveCriticalSection( &dir_section );
822 #else
823 static int warned;
824 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
825 #endif
826 return ret;
830 /***********************************************************************
831 * get_device_mount_point
833 * Return the current mount point for a device.
835 static char *get_device_mount_point( dev_t dev )
837 char *ret = NULL;
839 #ifdef linux
840 FILE *f;
842 RtlEnterCriticalSection( &dir_section );
844 #ifdef __ANDROID__
845 if ((f = fopen( "/proc/mounts", "r" )))
846 #else
847 if ((f = fopen( "/etc/mtab", "r" )))
848 #endif
850 struct mntent *entry;
851 struct stat st;
852 char *p, *device;
854 while ((entry = getmntent( f )))
856 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
857 if (!strcmp( entry->mnt_type, "nfs" ) ||
858 !strcmp( entry->mnt_type, "smbfs" ) ||
859 !strcmp( entry->mnt_type, "ncpfs" )) continue;
861 if (!strcmp( entry->mnt_type, "supermount" ))
863 if ((device = strstr( entry->mnt_opts, "dev=" )))
865 device += 4;
866 if ((p = strchr( device, ',' ))) *p = 0;
869 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
871 /* if device is a regular file check for a loop mount */
872 if ((device = strstr( entry->mnt_opts, "loop=" )))
874 device += 5;
875 if ((p = strchr( device, ',' ))) *p = 0;
878 else device = entry->mnt_fsname;
880 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
882 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
883 if (ret) strcpy( ret, entry->mnt_dir );
884 break;
887 fclose( f );
889 RtlLeaveCriticalSection( &dir_section );
890 #elif defined(__APPLE__)
891 struct statfs *entry;
892 struct stat st;
893 int i, size;
895 RtlEnterCriticalSection( &dir_section );
897 size = getmntinfo( &entry, MNT_NOWAIT );
898 for (i = 0; i < size; i++)
900 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
901 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
903 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
904 if (ret) strcpy( ret, entry[i].f_mntonname );
905 break;
908 RtlLeaveCriticalSection( &dir_section );
909 #else
910 static int warned;
911 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
912 #endif
913 return ret;
917 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
918 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
920 struct get_fsid
922 ULONG size;
923 dev_t dev;
924 fsid_t fsid;
927 struct fs_cache
929 dev_t dev;
930 fsid_t fsid;
931 BOOLEAN case_sensitive;
932 } fs_cache[64];
934 struct vol_caps
936 ULONG size;
937 vol_capabilities_attr_t caps;
940 /***********************************************************************
941 * look_up_fs_cache
943 * Checks if the specified file system is in the cache.
945 static struct fs_cache *look_up_fs_cache( dev_t dev )
947 int i;
948 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
949 if (fs_cache[i].dev == dev)
950 return fs_cache+i;
951 return NULL;
954 /***********************************************************************
955 * add_fs_cache
957 * Adds the specified file system to the cache.
959 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
961 int i;
962 struct fs_cache *entry = look_up_fs_cache( dev );
963 static int once = 0;
964 if (entry)
966 /* Update the cache */
967 entry->fsid = fsid;
968 entry->case_sensitive = case_sensitive;
969 return;
972 /* Add a new entry */
973 for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
974 if (fs_cache[i].dev == 0)
976 /* This entry is empty, use it */
977 fs_cache[i].dev = dev;
978 fs_cache[i].fsid = fsid;
979 fs_cache[i].case_sensitive = case_sensitive;
980 return;
983 /* Cache is out of space, warn */
984 if (!once++)
985 WARN( "FS cache is out of space, expect performance problems\n" );
988 /***********************************************************************
989 * get_dir_case_sensitivity_attr
991 * Checks if the volume containing the specified directory is case
992 * sensitive or not. Uses getattrlist(2).
994 static int get_dir_case_sensitivity_attr( const char *dir )
996 char *mntpoint = NULL;
997 struct attrlist attr;
998 struct vol_caps caps;
999 struct get_fsid get_fsid;
1000 struct fs_cache *entry;
1002 /* First get the FS ID of the volume */
1003 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1004 attr.reserved = 0;
1005 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1006 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1007 get_fsid.size = 0;
1008 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1009 get_fsid.size != sizeof(get_fsid))
1010 return -1;
1011 /* Try to look it up in the cache */
1012 entry = look_up_fs_cache( get_fsid.dev );
1013 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1014 /* Cache lookup succeeded */
1015 return entry->case_sensitive;
1016 /* Cache is stale at this point, we have to update it */
1018 mntpoint = get_device_mount_point( get_fsid.dev );
1019 /* Now look up the case-sensitivity */
1020 attr.commonattr = 0;
1021 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1022 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1024 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1025 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1026 return TRUE;
1028 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1029 if (caps.size == sizeof(caps) &&
1030 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1031 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1032 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1034 BOOLEAN ret;
1036 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1037 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1038 ret = FALSE;
1039 else
1040 ret = TRUE;
1041 /* Update the cache */
1042 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1043 return ret;
1045 return FALSE;
1047 #endif
1049 /***********************************************************************
1050 * get_dir_case_sensitivity_stat
1052 * Checks if the volume containing the specified directory is case
1053 * sensitive or not. Uses statfs(2) or statvfs(2).
1055 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1057 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1058 struct statfs stfs;
1060 if (statfs( dir, &stfs ) == -1) return FALSE;
1061 /* Assume these file systems are always case insensitive on Mac OS.
1062 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1063 * is the only UNIX that supports case-insensitive lookup).
1065 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1066 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1067 return FALSE;
1068 #ifdef __APPLE__
1069 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1070 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1071 !strcmp( stfs.f_fstypename, "udf" ) ||
1072 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1073 !strcmp( stfs.f_fstypename, "smbfs" ))
1074 return FALSE;
1075 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1076 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1077 stfs.f_fssubtype == 1 ||
1078 stfs.f_fssubtype == 128))
1079 return FALSE;
1080 #else
1081 /* The field says "reserved", but a quick look at the kernel source
1082 * tells us that this "reserved" field is really the same as the
1083 * "fssubtype" field from the inode64 structure (see munge_statfs()
1084 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1086 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1087 stfs.f_reserved1 == 1 ||
1088 stfs.f_reserved1 == 128))
1089 return FALSE;
1090 #endif
1091 #endif
1092 return TRUE;
1094 #elif defined(__NetBSD__)
1095 struct statvfs stfs;
1097 if (statvfs( dir, &stfs ) == -1) return FALSE;
1098 /* Only assume CIOPFS is case insensitive. */
1099 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1100 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1101 return TRUE;
1102 return FALSE;
1104 #elif defined(__linux__)
1105 struct statfs stfs;
1106 struct stat st;
1107 char *cifile;
1109 /* Only assume CIOPFS is case insensitive. */
1110 if (statfs( dir, &stfs ) == -1) return FALSE;
1111 if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
1112 return TRUE;
1113 /* Normally, we'd have to parse the mtab to find out exactly what
1114 * kind of FUSE FS this is. But, someone on wine-devel suggested
1115 * a shortcut. We'll stat a special file in the directory. If it's
1116 * there, we'll assume it's a CIOPFS, else not.
1117 * This will break if somebody puts a file named ".ciopfs" in a non-
1118 * CIOPFS directory.
1120 cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
1121 if (!cifile) return TRUE;
1122 strcpy( cifile, dir );
1123 strcat( cifile, "/.ciopfs" );
1124 if (stat( cifile, &st ) == 0)
1126 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1127 return FALSE;
1129 RtlFreeHeap( GetProcessHeap(), 0, cifile );
1130 return TRUE;
1131 #else
1132 return TRUE;
1133 #endif
1137 /***********************************************************************
1138 * get_dir_case_sensitivity
1140 * Checks if the volume containing the specified directory is case
1141 * sensitive or not. Uses statfs(2) or statvfs(2).
1143 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1145 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1146 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1147 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1148 if (case_sensitive != -1) return case_sensitive;
1149 #endif
1150 return get_dir_case_sensitivity_stat( dir );
1154 /***********************************************************************
1155 * init_options
1157 * Initialize the show_dot_files options.
1159 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1161 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1162 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1163 char tmp[80];
1164 HANDLE root, hkey;
1165 DWORD dummy;
1166 OBJECT_ATTRIBUTES attr;
1167 UNICODE_STRING nameW;
1169 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1170 attr.Length = sizeof(attr);
1171 attr.RootDirectory = root;
1172 attr.ObjectName = &nameW;
1173 attr.Attributes = 0;
1174 attr.SecurityDescriptor = NULL;
1175 attr.SecurityQualityOfService = NULL;
1176 RtlInitUnicodeString( &nameW, WineW );
1178 /* @@ Wine registry key: HKCU\Software\Wine */
1179 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1181 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1182 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1184 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1185 show_dot_files = IS_OPTION_TRUE( str[0] );
1187 NtClose( hkey );
1189 NtClose( root );
1191 /* a couple of directories that we don't want to return in directory searches */
1192 ignore_file( wine_get_config_dir() );
1193 ignore_file( "/dev" );
1194 ignore_file( "/proc" );
1195 #ifdef linux
1196 ignore_file( "/sys" );
1197 #endif
1198 return TRUE;
1202 /***********************************************************************
1203 * DIR_is_hidden_file
1205 * Check if the specified file should be hidden based on its name and the show dot files option.
1207 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1209 WCHAR *p, *end;
1211 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1213 if (show_dot_files) return FALSE;
1215 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1216 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1217 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1218 if (p == end || *p != '.') return FALSE;
1219 /* make sure it isn't '.' or '..' */
1220 if (p + 1 == end) return FALSE;
1221 if (p[1] == '.' && p + 2 == end) return FALSE;
1222 return TRUE;
1226 /***********************************************************************
1227 * hash_short_file_name
1229 * Transform a Unix file name into a hashed DOS name. If the name is a valid
1230 * DOS name, it is converted to upper-case; otherwise it is replaced by a
1231 * hashed version that fits in 8.3 format.
1232 * 'buffer' must be at least 12 characters long.
1233 * Returns length of short name in bytes; short name is NOT null-terminated.
1235 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1237 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1239 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1240 LPWSTR dst;
1241 unsigned short hash;
1242 int i;
1244 /* Compute the hash code of the file name */
1245 /* If you know something about hash functions, feel free to */
1246 /* insert a better algorithm here... */
1247 if (!is_case_sensitive)
1249 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1250 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1251 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1253 else
1255 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1256 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1257 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1260 /* Find last dot for start of the extension */
1261 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1263 /* Copy first 4 chars, replacing invalid chars with '_' */
1264 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1266 if (p == end || p == ext) break;
1267 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1269 /* Pad to 5 chars with '~' */
1270 while (i-- >= 0) *dst++ = '~';
1272 /* Insert hash code converted to 3 ASCII chars */
1273 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1274 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1275 *dst++ = hash_chars[hash & 0x1f];
1277 /* Copy the first 3 chars of the extension (if any) */
1278 if (ext)
1280 *dst++ = '.';
1281 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1282 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1284 return dst - buffer;
1288 /***********************************************************************
1289 * match_filename
1291 * Check a long file name against a mask.
1293 * Tests (done in W95 DOS shell - case insensitive):
1294 * *.txt test1.test.txt *
1295 * *st1* test1.txt *
1296 * *.t??????.t* test1.ta.tornado.txt *
1297 * *tornado* test1.ta.tornado.txt *
1298 * t*t test1.ta.tornado.txt *
1299 * ?est* test1.txt *
1300 * ?est??? test1.txt -
1301 * *test1.txt* test1.txt *
1302 * h?l?o*t.dat hellothisisatest.dat *
1304 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1306 BOOL mismatch;
1307 const WCHAR *name = name_str->Buffer;
1308 const WCHAR *mask = mask_str->Buffer;
1309 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1310 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1311 const WCHAR *lastjoker = NULL;
1312 const WCHAR *next_to_retry = NULL;
1314 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1316 while (name < name_end && mask < mask_end)
1318 switch(*mask)
1320 case '*':
1321 mask++;
1322 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1323 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1324 lastjoker = mask;
1326 /* skip to the next match after the joker(s) */
1327 if (is_case_sensitive)
1328 while (name < name_end && (*name != *mask)) name++;
1329 else
1330 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1331 next_to_retry = name;
1332 break;
1333 case '?':
1334 mask++;
1335 name++;
1336 break;
1337 default:
1338 if (is_case_sensitive) mismatch = (*mask != *name);
1339 else mismatch = (toupperW(*mask) != toupperW(*name));
1341 if (!mismatch)
1343 mask++;
1344 name++;
1345 if (mask == mask_end)
1347 if (name == name_end) return TRUE;
1348 if (lastjoker) mask = lastjoker;
1351 else /* mismatch ! */
1353 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1355 mask = lastjoker;
1357 /* this scan sequence was a mismatch, so restart
1358 * 1 char after the first char we checked last time */
1359 next_to_retry++;
1360 name = next_to_retry;
1362 else return FALSE; /* bad luck */
1364 break;
1367 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1368 mask++; /* Ignore trailing '.' or '*' in mask */
1369 return (name == name_end && mask == mask_end);
1373 /***********************************************************************
1374 * append_entry
1376 * helper for NtQueryDirectoryFile
1378 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1379 const char *long_name, const char *short_name,
1380 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1382 union file_directory_info *info;
1383 int i, long_len, short_len, total_len;
1384 struct stat st;
1385 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1386 WCHAR short_nameW[12];
1387 WCHAR *filename;
1388 UNICODE_STRING str;
1389 ULONG attributes;
1391 io->u.Status = STATUS_SUCCESS;
1392 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1393 if (long_len == -1) return NULL;
1395 str.Buffer = long_nameW;
1396 str.Length = long_len * sizeof(WCHAR);
1397 str.MaximumLength = sizeof(long_nameW);
1399 if (short_name)
1401 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1402 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1403 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1405 else /* generate a short name if necessary */
1407 BOOLEAN spaces;
1409 short_len = 0;
1410 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1411 short_len = hash_short_file_name( &str, short_nameW );
1414 TRACE( "long %s short %s mask %s\n",
1415 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1417 if (mask && !match_filename( &str, mask ))
1419 if (!short_len) return NULL; /* no short name to match */
1420 str.Buffer = short_nameW;
1421 str.Length = short_len * sizeof(WCHAR);
1422 str.MaximumLength = sizeof(short_nameW);
1423 if (!match_filename( &str, mask )) return NULL;
1426 if (get_file_info( long_name, &st, &attributes ) == -1) return NULL;
1427 if (is_ignored_file( &st ))
1429 TRACE( "ignoring file %s\n", long_name );
1430 return NULL;
1432 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1433 attributes |= FILE_ATTRIBUTE_HIDDEN;
1435 total_len = dir_info_size( class, long_len );
1436 if (io->Information + total_len > max_length)
1438 total_len = max_length - io->Information;
1439 io->u.Status = STATUS_BUFFER_OVERFLOW;
1441 info = (union file_directory_info *)((char *)info_ptr + io->Information);
1442 if (st.st_dev != curdir.dev) st.st_ino = 0; /* ignore inode if on a different device */
1443 /* all the structures start with a FileDirectoryInformation layout */
1444 fill_file_info( &st, attributes, info, class );
1445 info->dir.NextEntryOffset = total_len;
1446 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1448 switch (class)
1450 case FileDirectoryInformation:
1451 info->dir.FileNameLength = long_len * sizeof(WCHAR);
1452 filename = info->dir.FileName;
1453 break;
1455 case FileFullDirectoryInformation:
1456 info->full.EaSize = 0; /* FIXME */
1457 info->full.FileNameLength = long_len * sizeof(WCHAR);
1458 filename = info->full.FileName;
1459 break;
1461 case FileIdFullDirectoryInformation:
1462 info->id_full.EaSize = 0; /* FIXME */
1463 info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1464 filename = info->id_full.FileName;
1465 break;
1467 case FileBothDirectoryInformation:
1468 info->both.EaSize = 0; /* FIXME */
1469 info->both.ShortNameLength = short_len * sizeof(WCHAR);
1470 for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1471 info->both.FileNameLength = long_len * sizeof(WCHAR);
1472 filename = info->both.FileName;
1473 break;
1475 case FileIdBothDirectoryInformation:
1476 info->id_both.EaSize = 0; /* FIXME */
1477 info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1478 for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1479 info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1480 filename = info->id_both.FileName;
1481 break;
1483 default:
1484 assert(0);
1485 return NULL;
1487 memcpy( filename, long_nameW, long_len * sizeof(WCHAR) );
1488 io->Information += total_len;
1489 return info;
1493 #ifdef VFAT_IOCTL_READDIR_BOTH
1495 /***********************************************************************
1496 * start_vfat_ioctl
1498 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1499 * dir_section must be held by caller.
1501 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1503 static KERNEL_DIRENT *de;
1504 int res;
1506 if (!de)
1508 SIZE_T size = 2 * sizeof(*de) + page_size;
1509 void *addr = NULL;
1511 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1512 return NULL;
1513 /* commit only the size needed for the dir entries */
1514 /* this leaves an extra unaccessible page, which should make the kernel */
1515 /* fail with -EFAULT before it stomps all over our memory */
1516 de = addr;
1517 size = 2 * sizeof(*de);
1518 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1521 /* set d_reclen to 65535 to work around an AFS kernel bug */
1522 de[0].d_reclen = 65535;
1523 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1524 if (res == -1)
1526 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1527 de[0].d_reclen = 0; /* eof */
1529 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1531 return de;
1535 /***********************************************************************
1536 * read_directory_vfat
1538 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1540 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1541 BOOLEAN single_entry, const UNICODE_STRING *mask,
1542 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1545 size_t len;
1546 KERNEL_DIRENT *de;
1547 union file_directory_info *info, *last_info = NULL;
1549 io->u.Status = STATUS_SUCCESS;
1551 if (restart_scan) lseek( fd, 0, SEEK_SET );
1553 if (length < max_dir_info_size(class)) /* we may have to return a partial entry here */
1555 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1557 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1559 while (de[0].d_reclen)
1561 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1562 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1563 de[0].d_name[len] = 0;
1564 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1565 de[1].d_name[len] = 0;
1567 if (de[1].d_name[0])
1568 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1569 else
1570 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1571 if (info)
1573 last_info = info;
1574 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1575 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1576 break;
1578 old_pos = lseek( fd, 0, SEEK_CUR );
1579 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1582 else /* we'll only return full entries, no need to worry about overflow */
1584 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1586 while (de[0].d_reclen)
1588 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1589 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1590 de[0].d_name[len] = 0;
1591 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1592 de[1].d_name[len] = 0;
1594 if (de[1].d_name[0])
1595 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1596 else
1597 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1598 if (info)
1600 last_info = info;
1601 if (single_entry) break;
1602 /* check if we still have enough space for the largest possible entry */
1603 if (io->Information + max_dir_info_size(class) > length) break;
1605 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1609 if (last_info) last_info->next = 0;
1610 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1611 return 0;
1613 #endif /* VFAT_IOCTL_READDIR_BOTH */
1616 #ifdef USE_GETDENTS
1617 /***********************************************************************
1618 * read_first_dent_name
1620 * reads name of first or second dentry (if they have inodes).
1622 static char *read_first_dent_name( int which, int fd, off_t second_offs, KERNEL_DIRENT64 *de_first_two,
1623 char *buffer, size_t size, BOOL *buffer_changed )
1625 KERNEL_DIRENT64 *de;
1626 int res;
1628 de = de_first_two;
1629 if (de != NULL)
1631 if (which == 1)
1632 de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1634 return de->d_ino ? de->d_name : NULL;
1637 *buffer_changed = TRUE;
1638 lseek( fd, which == 1 ? second_offs : 0, SEEK_SET );
1639 res = getdents64( fd, buffer, size );
1640 if (res <= 0)
1641 return NULL;
1643 de = (KERNEL_DIRENT64 *)buffer;
1644 return de->d_ino ? de->d_name : NULL;
1647 /***********************************************************************
1648 * read_directory_getdents
1650 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1652 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1653 BOOLEAN single_entry, const UNICODE_STRING *mask,
1654 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1656 static off_t second_entry_pos;
1657 static struct file_identity last_dir_id;
1658 off_t old_pos = 0, next_pos;
1659 size_t size = length;
1660 char *data, local_buffer[8192];
1661 KERNEL_DIRENT64 *de, *de_first_two = NULL;
1662 union file_directory_info *info, *last_info = NULL;
1663 const char *filename;
1664 BOOL data_buffer_changed;
1665 int res, swap_to;
1667 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1669 size = sizeof(local_buffer);
1670 data = local_buffer;
1673 if (restart_scan) lseek( fd, 0, SEEK_SET );
1674 else
1676 old_pos = lseek( fd, 0, SEEK_CUR );
1677 if (old_pos == -1)
1679 io->u.Status = (errno == ENOENT) ? STATUS_NO_MORE_FILES : FILE_GetNtStatus();
1680 res = 0;
1681 goto done;
1685 io->u.Status = STATUS_SUCCESS;
1686 de = (KERNEL_DIRENT64 *)data;
1688 /* if old_pos is not 0 we don't know how many entries have been returned already,
1689 * so maintain second_entry_pos to know when to return '..' */
1690 if (old_pos != 0 && (last_dir_id.dev != curdir.dev || last_dir_id.ino != curdir.ino))
1692 lseek( fd, 0, SEEK_SET );
1693 res = getdents64( fd, data, size );
1694 if (res > 0)
1696 second_entry_pos = de->d_off;
1697 last_dir_id = curdir;
1699 lseek( fd, old_pos, SEEK_SET );
1702 res = getdents64( fd, data, size );
1703 if (res == -1)
1705 if (errno != ENOSYS)
1707 io->u.Status = FILE_GetNtStatus();
1708 res = 0;
1710 goto done;
1713 if (old_pos == 0 && res > 0)
1715 second_entry_pos = de->d_off;
1716 last_dir_id = curdir;
1717 if (res > de->d_reclen)
1718 de_first_two = de;
1721 while (res > 0)
1723 res -= de->d_reclen;
1724 next_pos = de->d_off;
1725 filename = NULL;
1727 /* we must return first 2 entries as "." and "..", but getdents64()
1728 * can return them anywhere, so swap first entries with "." and ".." */
1729 if (old_pos == 0)
1730 filename = ".";
1731 else if (old_pos == second_entry_pos)
1732 filename = "..";
1733 else if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))
1735 swap_to = !strcmp( de->d_name, "." ) ? 0 : 1;
1736 data_buffer_changed = FALSE;
1738 filename = read_first_dent_name( swap_to, fd, second_entry_pos, de_first_two,
1739 data, size, &data_buffer_changed );
1740 if (filename != NULL && (!strcmp( filename, "." ) || !strcmp( filename, ".." )))
1741 filename = read_first_dent_name( swap_to ^ 1, fd, second_entry_pos, NULL,
1742 data, size, &data_buffer_changed );
1743 if (data_buffer_changed)
1745 lseek( fd, next_pos, SEEK_SET );
1746 res = 0;
1749 else if (de->d_ino)
1750 filename = de->d_name;
1752 if (filename && (info = append_entry( buffer, io, length, filename, NULL, mask, class )))
1754 last_info = info;
1755 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1757 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1758 break;
1760 /* check if we still have enough space for the largest possible entry */
1761 if (single_entry || io->Information + max_dir_info_size(class) > length)
1763 if (res > 0) lseek( fd, next_pos, SEEK_SET ); /* set pos to next entry */
1764 break;
1767 old_pos = next_pos;
1768 /* move on to the next entry */
1769 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1770 else
1772 res = getdents64( fd, data, size );
1773 de = (KERNEL_DIRENT64 *)data;
1774 de_first_two = NULL;
1778 if (last_info) last_info->next = 0;
1779 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1780 res = 0;
1781 done:
1782 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1783 return res;
1786 #elif defined HAVE_GETDIRENTRIES
1788 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1790 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1791 * inodes. When 64-bit inodes are enabled, the getdirentries symbol is mapped
1792 * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1793 * we get link errors if we try to use it. We still need getdirentries, but we
1794 * don't need it to support 64-bit inodes. So, we use the legacy getdirentries
1795 * with 32-bit inodes. We have to be careful to use a corresponding dirent
1796 * structure, too.
1798 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1799 #define getdirentries darwin_legacy_getdirentries
1801 struct darwin_legacy_dirent {
1802 __uint32_t d_ino;
1803 __uint16_t d_reclen;
1804 __uint8_t d_type;
1805 __uint8_t d_namlen;
1806 char d_name[__DARWIN_MAXNAMLEN + 1];
1808 #define dirent darwin_legacy_dirent
1810 #endif
1812 /***********************************************************************
1813 * wine_getdirentries
1815 * Wrapper for the BSD getdirentries system call to fix a bug in the
1816 * Mac OS X version. For some file systems (at least Apple Filing
1817 * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1818 * when it's about to return 0 (no more entries). So, a subsequent
1819 * getdirentries call starts over at the beginning again, causing an
1820 * infinite loop.
1822 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1824 int res = getdirentries(fd, buf, nbytes, basep);
1825 #ifdef __APPLE__
1826 if (res == 0)
1827 lseek(fd, *basep, SEEK_SET);
1828 #endif
1829 return res;
1832 static inline int dir_reclen(struct dirent *de)
1834 #ifdef HAVE_STRUCT_DIRENT_D_RECLEN
1835 return de->d_reclen;
1836 #else
1837 return _DIRENT_RECLEN(de->d_namlen);
1838 #endif
1841 /***********************************************************************
1842 * read_directory_getdirentries
1844 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1846 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1847 BOOLEAN single_entry, const UNICODE_STRING *mask,
1848 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1850 long restart_pos;
1851 ULONG_PTR restart_info_pos = 0;
1852 size_t size, initial_size = length;
1853 int res, fake_dot_dot = 1;
1854 char *data, local_buffer[8192];
1855 struct dirent *de;
1856 union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1858 size = initial_size;
1859 data = local_buffer;
1860 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1862 io->u.Status = STATUS_NO_MEMORY;
1863 return io->u.Status;
1866 if (restart_scan) lseek( fd, 0, SEEK_SET );
1868 io->u.Status = STATUS_SUCCESS;
1870 /* FIXME: should make sure size is larger than filesystem block size */
1871 res = wine_getdirentries( fd, data, size, &restart_pos );
1872 if (res == -1)
1874 io->u.Status = FILE_GetNtStatus();
1875 res = 0;
1876 goto done;
1879 de = (struct dirent *)data;
1881 if (restart_scan)
1883 /* check if we got . and .. from getdirentries */
1884 if (res > 0)
1886 if (!strcmp( de->d_name, "." ) && res > dir_reclen(de))
1888 struct dirent *next_de = (struct dirent *)(data + dir_reclen(de));
1889 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1892 /* make sure we have enough room for both entries */
1893 if (fake_dot_dot)
1895 const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1896 if (length < min_info_size || single_entry)
1898 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1899 fake_dot_dot = 0;
1903 if (fake_dot_dot)
1905 if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1906 last_info = info;
1907 if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1908 last_info = info;
1910 restart_last_info = last_info;
1911 restart_info_pos = io->Information;
1913 /* check if we still have enough space for the largest possible entry */
1914 if (last_info && io->Information + max_dir_info_size(class) > length)
1916 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1917 res = 0;
1922 while (res > 0)
1924 res -= dir_reclen(de);
1925 if (de->d_fileno &&
1926 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1927 ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1929 last_info = info;
1930 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1932 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1933 if (restart_info_pos) /* if we have a complete read already, return it */
1935 io->u.Status = STATUS_SUCCESS;
1936 io->Information = restart_info_pos;
1937 last_info = restart_last_info;
1938 break;
1940 /* otherwise restart from the start with a smaller size */
1941 size = (char *)de - data;
1942 if (!size) break;
1943 io->Information = 0;
1944 last_info = NULL;
1945 goto restart;
1947 if (!has_wildcard( mask )) break;
1948 /* if we have to return but the buffer contains more data, restart with a smaller size */
1949 if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1951 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1952 size = (char *)de + dir_reclen(de) - data;
1953 io->Information = restart_info_pos;
1954 last_info = restart_last_info;
1955 goto restart;
1958 /* move on to the next entry */
1959 if (res > 0)
1961 de = (struct dirent *)((char *)de + dir_reclen(de));
1962 continue;
1964 if (size < initial_size) break; /* already restarted once, give up now */
1965 restart_last_info = last_info;
1966 restart_info_pos = io->Information;
1967 restart:
1968 res = wine_getdirentries( fd, data, size, &restart_pos );
1969 de = (struct dirent *)data;
1972 if (last_info) last_info->next = 0;
1973 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1974 res = 0;
1975 done:
1976 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1977 return res;
1980 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1981 #undef getdirentries
1982 #undef dirent
1983 #endif
1985 #endif /* HAVE_GETDIRENTRIES */
1988 /***********************************************************************
1989 * read_directory_readdir
1991 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1993 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1994 BOOLEAN single_entry, const UNICODE_STRING *mask,
1995 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1997 DIR *dir;
1998 off_t i, old_pos = 0;
1999 struct dirent *de;
2000 union file_directory_info *info, *last_info = NULL;
2002 if (!(dir = opendir( "." )))
2004 io->u.Status = FILE_GetNtStatus();
2005 return;
2008 if (!restart_scan)
2010 old_pos = lseek( fd, 0, SEEK_CUR );
2011 /* skip the right number of entries */
2012 for (i = 0; i < old_pos - 2; i++)
2014 if (!readdir( dir ))
2016 closedir( dir );
2017 io->u.Status = STATUS_NO_MORE_FILES;
2018 return;
2022 io->u.Status = STATUS_SUCCESS;
2024 for (;;)
2026 if (old_pos == 0)
2027 info = append_entry( buffer, io, length, ".", NULL, mask, class );
2028 else if (old_pos == 1)
2029 info = append_entry( buffer, io, length, "..", NULL, mask, class );
2030 else if ((de = readdir( dir )))
2032 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
2033 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
2034 else
2035 info = NULL;
2037 else
2038 break;
2039 old_pos++;
2040 if (info)
2042 last_info = info;
2043 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
2045 old_pos--; /* restore pos to previous entry */
2046 break;
2048 if (single_entry) break;
2049 /* check if we still have enough space for the largest possible entry */
2050 if (io->Information + max_dir_info_size(class) > length) break;
2054 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
2055 closedir( dir );
2057 if (last_info) last_info->next = 0;
2058 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2061 /***********************************************************************
2062 * read_directory_stat
2064 * Read a single file from a directory by determining whether the file
2065 * identified by mask exists using stat.
2067 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2068 BOOLEAN single_entry, const UNICODE_STRING *mask,
2069 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2071 int unix_len, ret, used_default;
2072 char *unix_name;
2073 struct stat st;
2074 BOOL case_sensitive = get_dir_case_sensitivity(".");
2076 TRACE("looking up file %s\n", debugstr_us( mask ));
2078 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2079 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2081 io->u.Status = STATUS_NO_MEMORY;
2082 return 0;
2084 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2085 NULL, &used_default );
2086 if (ret > 0 && !used_default)
2088 unix_name[ret] = 0;
2089 if (restart_scan)
2091 lseek( fd, 0, SEEK_SET );
2093 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2095 io->u.Status = STATUS_NO_MORE_FILES;
2096 ret = 0;
2097 goto done;
2100 ret = stat( unix_name, &st );
2101 if (case_sensitive && !ret)
2103 union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
2104 if (info)
2106 info->next = 0;
2107 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2109 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2111 else
2113 ret = -1;
2116 else ret = -1;
2118 done:
2119 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2121 TRACE("returning %d\n", ret);
2123 return ret;
2126 #ifdef HAVE_GETATTRLIST
2127 /***********************************************************************
2128 * read_directory_getattrlist
2130 * Read a single file from a directory by determining whether the file
2131 * identified by mask exists using getattrlist.
2133 static int read_directory_getattrlist( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
2134 BOOLEAN single_entry, const UNICODE_STRING *mask,
2135 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
2137 int unix_len, ret, used_default;
2138 char *unix_name;
2139 struct attrlist attrlist;
2140 #include "pshpack4.h"
2141 struct
2143 u_int32_t length;
2144 struct attrreference name_reference;
2145 fsobj_type_t type;
2146 char name[NAME_MAX * 3 + 1];
2147 } attrlist_buffer;
2148 #include "poppack.h"
2150 TRACE("looking up file %s\n", debugstr_us( mask ));
2152 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
2153 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
2155 io->u.Status = STATUS_NO_MEMORY;
2156 return 0;
2158 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
2159 NULL, &used_default );
2160 if (ret > 0 && !used_default)
2162 unix_name[ret] = 0;
2163 if (restart_scan)
2165 lseek( fd, 0, SEEK_SET );
2167 else if (lseek( fd, 0, SEEK_CUR ) != 0)
2169 io->u.Status = STATUS_NO_MORE_FILES;
2170 ret = 0;
2171 goto done;
2174 memset( &attrlist, 0, sizeof(attrlist) );
2175 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
2176 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
2177 ret = getattrlist( unix_name, &attrlist, &attrlist_buffer, sizeof(attrlist_buffer), FSOPT_NOFOLLOW );
2178 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
2179 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
2180 if (!ret && attrlist_buffer.type == VLNK)
2182 u_int32_t dummy;
2183 attrlist.commonattr = 0;
2184 ret = getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 );
2186 if (!ret)
2188 union file_directory_info *info = append_entry( buffer, io, length, attrlist_buffer.name, NULL, NULL, class );
2189 if (info)
2191 info->next = 0;
2192 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
2194 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
2197 else ret = -1;
2199 done:
2200 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2202 TRACE("returning %d\n", ret);
2204 return ret;
2206 #endif
2209 /******************************************************************************
2210 * NtQueryDirectoryFile [NTDLL.@]
2211 * ZwQueryDirectoryFile [NTDLL.@]
2213 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
2214 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
2215 PIO_STATUS_BLOCK io,
2216 PVOID buffer, ULONG length,
2217 FILE_INFORMATION_CLASS info_class,
2218 BOOLEAN single_entry,
2219 PUNICODE_STRING mask,
2220 BOOLEAN restart_scan )
2222 int cwd, fd, needs_close;
2224 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
2225 handle, event, apc_routine, apc_context, io, buffer,
2226 length, info_class, single_entry, debugstr_us(mask),
2227 restart_scan);
2229 if (event || apc_routine)
2231 FIXME( "Unsupported yet option\n" );
2232 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2234 switch (info_class)
2236 case FileDirectoryInformation:
2237 case FileBothDirectoryInformation:
2238 case FileFullDirectoryInformation:
2239 case FileIdBothDirectoryInformation:
2240 case FileIdFullDirectoryInformation:
2241 if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2242 if (!buffer) return io->u.Status = STATUS_ACCESS_VIOLATION;
2243 break;
2244 default:
2245 FIXME( "Unsupported file info class %d\n", info_class );
2246 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2249 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2250 return io->u.Status;
2252 io->Information = 0;
2254 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
2256 RtlEnterCriticalSection( &dir_section );
2258 cwd = open( ".", O_RDONLY );
2259 if (fchdir( fd ) != -1)
2261 struct stat st;
2262 fstat( fd, &st );
2263 curdir.dev = st.st_dev;
2264 curdir.ino = st.st_ino;
2265 #ifdef VFAT_IOCTL_READDIR_BOTH
2266 if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2267 mask, restart_scan, info_class )) != -1) goto done;
2268 #endif
2269 if (!has_wildcard( mask ))
2271 #ifdef HAVE_GETATTRLIST
2272 if (read_directory_getattrlist( fd, io, buffer, length, single_entry,
2273 mask, restart_scan, info_class ) != -1) goto done;
2274 #endif
2275 if (read_directory_stat( fd, io, buffer, length, single_entry,
2276 mask, restart_scan, info_class ) != -1) goto done;
2278 #ifdef USE_GETDENTS
2279 if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2280 mask, restart_scan, info_class )) != -1) goto done;
2281 #elif defined HAVE_GETDIRENTRIES
2282 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2283 mask, restart_scan, info_class )) != -1) goto done;
2284 #endif
2285 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2287 done:
2288 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2290 else io->u.Status = FILE_GetNtStatus();
2292 RtlLeaveCriticalSection( &dir_section );
2294 if (needs_close) close( fd );
2295 if (cwd != -1) close( cwd );
2296 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
2297 return io->u.Status;
2301 /***********************************************************************
2302 * find_file_in_dir
2304 * Find a file in a directory the hard way, by doing a case-insensitive search.
2305 * The file found is appended to unix_name at pos.
2306 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2308 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2309 BOOLEAN check_case, BOOLEAN *is_win_dir )
2311 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2312 UNICODE_STRING str;
2313 BOOLEAN spaces, is_name_8_dot_3;
2314 DIR *dir;
2315 struct dirent *de;
2316 struct stat st;
2317 int ret, used_default;
2319 /* try a shortcut for this directory */
2321 unix_name[pos++] = '/';
2322 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2323 NULL, &used_default );
2324 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2325 /* so it cannot match the file we are looking for */
2326 if (ret >= 0 && !used_default)
2328 unix_name[pos + ret] = 0;
2329 if (!stat( unix_name, &st ))
2331 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2332 return STATUS_SUCCESS;
2335 if (check_case) goto not_found; /* we want an exact match */
2337 if (pos > 1) unix_name[pos - 1] = 0;
2338 else unix_name[1] = 0; /* keep the initial slash */
2340 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2342 str.Buffer = (WCHAR *)name;
2343 str.Length = length * sizeof(WCHAR);
2344 str.MaximumLength = str.Length;
2345 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2346 #ifndef VFAT_IOCTL_READDIR_BOTH
2347 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2348 #endif
2350 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2352 /* now look for it through the directory */
2354 #ifdef VFAT_IOCTL_READDIR_BOTH
2355 if (is_name_8_dot_3)
2357 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2358 if (fd != -1)
2360 KERNEL_DIRENT *kde;
2362 RtlEnterCriticalSection( &dir_section );
2363 if ((kde = start_vfat_ioctl( fd )))
2365 unix_name[pos - 1] = '/';
2366 while (kde[0].d_reclen)
2368 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2369 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2370 kde[0].d_name[len] = 0;
2371 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2372 kde[1].d_name[len] = 0;
2374 if (kde[1].d_name[0])
2376 ret = ntdll_umbstowcs( 0, kde[1].d_name, strlen(kde[1].d_name),
2377 buffer, MAX_DIR_ENTRY_LEN );
2378 if (ret == length && !memicmpW( buffer, name, length))
2380 strcpy( unix_name + pos, kde[1].d_name );
2381 RtlLeaveCriticalSection( &dir_section );
2382 close( fd );
2383 goto success;
2386 ret = ntdll_umbstowcs( 0, kde[0].d_name, strlen(kde[0].d_name),
2387 buffer, MAX_DIR_ENTRY_LEN );
2388 if (ret == length && !memicmpW( buffer, name, length))
2390 strcpy( unix_name + pos,
2391 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2392 RtlLeaveCriticalSection( &dir_section );
2393 close( fd );
2394 goto success;
2396 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2398 RtlLeaveCriticalSection( &dir_section );
2399 close( fd );
2400 goto not_found;
2404 RtlLeaveCriticalSection( &dir_section );
2405 close( fd );
2407 /* fall through to normal handling */
2409 #endif /* VFAT_IOCTL_READDIR_BOTH */
2411 if (!(dir = opendir( unix_name )))
2413 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2414 else return FILE_GetNtStatus();
2416 unix_name[pos - 1] = '/';
2417 str.Buffer = buffer;
2418 str.MaximumLength = sizeof(buffer);
2419 while ((de = readdir( dir )))
2421 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2422 if (ret == length && !memicmpW( buffer, name, length ))
2424 strcpy( unix_name + pos, de->d_name );
2425 closedir( dir );
2426 goto success;
2429 if (!is_name_8_dot_3) continue;
2431 str.Length = ret * sizeof(WCHAR);
2432 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2434 WCHAR short_nameW[12];
2435 ret = hash_short_file_name( &str, short_nameW );
2436 if (ret == length && !memicmpW( short_nameW, name, length ))
2438 strcpy( unix_name + pos, de->d_name );
2439 closedir( dir );
2440 goto success;
2444 closedir( dir );
2446 not_found:
2447 unix_name[pos - 1] = 0;
2448 return STATUS_OBJECT_PATH_NOT_FOUND;
2450 success:
2451 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2452 return STATUS_SUCCESS;
2456 #ifndef _WIN64
2458 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2459 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2460 static const WCHAR driversstoreW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','s','t','o','r','e',0};
2461 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2462 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2463 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2464 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2465 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2466 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2467 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2468 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2470 static struct
2472 const WCHAR *source;
2473 const WCHAR *dos_target;
2474 const char *unix_target;
2475 } redirects[] =
2477 { catrootW, NULL, NULL },
2478 { catroot2W, NULL, NULL },
2479 { driversstoreW, NULL, NULL },
2480 { driversetcW, NULL, NULL },
2481 { logfilesW, NULL, NULL },
2482 { spoolW, NULL, NULL },
2483 { system32W, syswow64W, NULL },
2484 { sysnativeW, system32W, NULL },
2485 { regeditW, wow_regeditW, NULL }
2488 static unsigned int nb_redirects;
2491 /***********************************************************************
2492 * get_redirect_target
2494 * Find the target unix name for a redirected dir.
2496 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2498 int used_default, len, pos, win_len = strlen( windows_dir );
2499 char *unix_name, *unix_target = NULL;
2500 NTSTATUS status;
2502 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2503 return NULL;
2504 memcpy( unix_name, windows_dir, win_len );
2505 pos = win_len;
2507 while (*name)
2509 const WCHAR *end, *next;
2511 for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2512 for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2514 status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2515 if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next) /* not finding last element is ok */
2517 len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2518 MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2519 if (len > 0 && !used_default)
2521 unix_name[pos] = '/';
2522 pos += len + 1;
2523 unix_name[pos] = 0;
2524 break;
2527 if (status) goto done;
2528 pos += strlen( unix_name + pos );
2529 name = next;
2532 if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2533 memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2535 done:
2536 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2537 return unix_target;
2541 /***********************************************************************
2542 * init_redirects
2544 static void init_redirects(void)
2546 UNICODE_STRING nt_name;
2547 ANSI_STRING unix_name;
2548 NTSTATUS status;
2549 struct stat st;
2550 unsigned int i;
2552 if (!RtlDosPathNameToNtPathName_U( user_shared_data->NtSystemRoot, &nt_name, NULL, NULL ))
2554 ERR( "can't convert %s\n", debugstr_w(user_shared_data->NtSystemRoot) );
2555 return;
2557 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2558 RtlFreeUnicodeString( &nt_name );
2559 if (status)
2561 ERR( "cannot open %s (%x)\n", debugstr_w(user_shared_data->NtSystemRoot), status );
2562 return;
2564 if (!stat( unix_name.Buffer, &st ))
2566 windir.dev = st.st_dev;
2567 windir.ino = st.st_ino;
2568 nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2569 for (i = 0; i < nb_redirects; i++)
2571 if (!redirects[i].dos_target) continue;
2572 redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2573 TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2576 RtlFreeAnsiString( &unix_name );
2581 /***********************************************************************
2582 * match_redirect
2584 * Check if path matches a redirect name. If yes, return matched length.
2586 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2588 int i = 0;
2590 while (i < len && *redir)
2592 if (IS_SEPARATOR(path[i]))
2594 if (*redir++ != '\\') return 0;
2595 while (i < len && IS_SEPARATOR(path[i])) i++;
2596 continue; /* move on to next path component */
2598 else if (check_case)
2600 if (path[i] != *redir) return 0;
2602 else
2604 if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2606 i++;
2607 redir++;
2609 if (*redir) return 0;
2610 if (i < len && !IS_SEPARATOR(path[i])) return 0;
2611 while (i < len && IS_SEPARATOR(path[i])) i++;
2612 return i;
2616 /***********************************************************************
2617 * get_redirect_path
2619 * Retrieve the Unix path corresponding to a redirected path if any.
2621 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2623 unsigned int i;
2624 int len;
2626 for (i = 0; i < nb_redirects; i++)
2628 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2630 if (!redirects[i].unix_target) break;
2631 unix_name[pos++] = '/';
2632 strcpy( unix_name + pos, redirects[i].unix_target );
2633 return len;
2636 return 0;
2639 #else /* _WIN64 */
2641 /* there are no redirects on 64-bit */
2643 static const unsigned int nb_redirects = 0;
2645 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2647 return 0;
2650 #endif
2652 /***********************************************************************
2653 * DIR_init_windows_dir
2655 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2657 /* FIXME: should probably store paths as NT file names */
2659 RtlCreateUnicodeString( &system_dir, sys );
2661 #ifndef _WIN64
2662 if (is_wow64) init_redirects();
2663 #endif
2667 /******************************************************************************
2668 * get_dos_device
2670 * Get the Unix path of a DOS device.
2672 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2674 const char *config_dir = wine_get_config_dir();
2675 struct stat st;
2676 char *unix_name, *new_name, *dev;
2677 unsigned int i;
2678 int unix_len;
2680 /* make sure the device name is ASCII */
2681 for (i = 0; i < name_len; i++)
2682 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2684 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2686 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2687 return STATUS_NO_MEMORY;
2689 strcpy( unix_name, config_dir );
2690 strcat( unix_name, "/dosdevices/" );
2691 dev = unix_name + strlen(unix_name);
2693 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2694 dev[i] = 0;
2696 /* special case for drive devices */
2697 if (name_len == 2 && dev[1] == ':')
2699 dev[i++] = ':';
2700 dev[i] = 0;
2703 for (;;)
2705 if (!stat( unix_name, &st ))
2707 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2708 unix_name_ret->Buffer = unix_name;
2709 unix_name_ret->Length = strlen(unix_name);
2710 unix_name_ret->MaximumLength = unix_len;
2711 return STATUS_SUCCESS;
2713 if (!dev) break;
2715 /* now try some defaults for it */
2716 if (!strcmp( dev, "aux" ))
2718 strcpy( dev, "com1" );
2719 continue;
2721 if (!strcmp( dev, "prn" ))
2723 strcpy( dev, "lpt1" );
2724 continue;
2727 new_name = NULL;
2728 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2730 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2731 new_name = get_default_drive_device( unix_name );
2733 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2734 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2736 if (!new_name) break;
2738 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2739 unix_name = new_name;
2740 unix_len = strlen(unix_name) + 1;
2741 dev = NULL; /* last try */
2743 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2744 return STATUS_BAD_DEVICE_TYPE;
2748 /* return the length of the DOS namespace prefix if any */
2749 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2751 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2752 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2754 if (name->Length >= sizeof(nt_prefixW) &&
2755 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2756 return sizeof(nt_prefixW) / sizeof(WCHAR);
2758 if (name->Length >= sizeof(dosdev_prefixW) &&
2759 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2760 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2762 return 0;
2766 /******************************************************************************
2767 * find_file_id
2769 * Recursively search directories from the dir queue for a given inode.
2771 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2773 unsigned int pos;
2774 DIR *dir;
2775 struct dirent *de;
2776 NTSTATUS status;
2777 struct stat st;
2779 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2781 if (!(dir = opendir( unix_name->Buffer ))) continue;
2782 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2783 pos = strlen( unix_name->Buffer );
2784 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2786 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2787 unix_name->MaximumLength * 2 );
2788 if (!new)
2790 closedir( dir );
2791 return STATUS_NO_MEMORY;
2793 unix_name->MaximumLength *= 2;
2794 unix_name->Buffer = new;
2796 unix_name->Buffer[pos++] = '/';
2797 while ((de = readdir( dir )))
2799 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2800 strcpy( unix_name->Buffer + pos, de->d_name );
2801 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2802 if (st.st_dev != dev) continue;
2803 if (st.st_ino == file_id)
2805 closedir( dir );
2806 return STATUS_SUCCESS;
2808 if (!S_ISDIR( st.st_mode )) continue;
2809 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2811 closedir( dir );
2812 return status;
2815 closedir( dir );
2817 return status;
2821 /******************************************************************************
2822 * file_id_to_unix_file_name
2824 * Lookup a file from its file id instead of its name.
2826 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2828 enum server_fd_type type;
2829 int old_cwd, root_fd, needs_close;
2830 NTSTATUS status;
2831 ULONGLONG file_id;
2832 struct stat st, root_st;
2834 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2835 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2836 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2838 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2839 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2840 return STATUS_NO_MEMORY;
2841 strcpy( unix_name->Buffer, "." );
2843 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2844 goto done;
2846 if (type != FD_TYPE_DIR)
2848 status = STATUS_OBJECT_TYPE_MISMATCH;
2849 goto done;
2852 fstat( root_fd, &root_st );
2853 if (root_st.st_ino == file_id) /* shortcut for "." */
2855 status = STATUS_SUCCESS;
2856 goto done;
2859 RtlEnterCriticalSection( &dir_section );
2860 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2862 /* shortcut for ".." */
2863 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2865 strcpy( unix_name->Buffer, ".." );
2866 status = STATUS_SUCCESS;
2868 else
2870 status = add_dir_to_queue( "." );
2871 if (!status)
2872 status = find_file_id( unix_name, file_id, root_st.st_dev );
2873 if (!status) /* get rid of "./" prefix */
2874 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2875 flush_dir_queue();
2877 if (fchdir( old_cwd ) == -1) chdir( "/" );
2879 else status = FILE_GetNtStatus();
2880 RtlLeaveCriticalSection( &dir_section );
2881 if (old_cwd != -1) close( old_cwd );
2883 done:
2884 if (status == STATUS_SUCCESS)
2886 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2887 unix_name->Length = strlen( unix_name->Buffer );
2889 else
2891 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2892 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2894 if (needs_close) close( root_fd );
2895 return status;
2899 /******************************************************************************
2900 * lookup_unix_name
2902 * Helper for nt_to_unix_file_name
2904 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2905 UINT disposition, BOOLEAN check_case )
2907 NTSTATUS status;
2908 int ret, used_default, len;
2909 struct stat st;
2910 char *unix_name = *buffer;
2911 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2913 /* try a shortcut first */
2915 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2916 NULL, &used_default );
2918 while (name_len && IS_SEPARATOR(*name))
2920 name++;
2921 name_len--;
2924 if (ret >= 0 && !used_default) /* if we used the default char the name didn't convert properly */
2926 char *p;
2927 unix_name[pos + ret] = 0;
2928 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2929 if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2931 if (!stat( unix_name, &st ))
2933 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2934 if (disposition == FILE_CREATE)
2935 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2936 return STATUS_SUCCESS;
2941 if (!name_len) /* empty name -> drive root doesn't exist */
2942 return STATUS_OBJECT_PATH_NOT_FOUND;
2943 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2944 return STATUS_OBJECT_NAME_NOT_FOUND;
2946 /* now do it component by component */
2948 while (name_len)
2950 const WCHAR *end, *next;
2951 BOOLEAN is_win_dir = FALSE;
2953 end = name;
2954 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2955 next = end;
2956 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2957 name_len -= next - name;
2959 /* grow the buffer if needed */
2961 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2963 char *new_name;
2964 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2965 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2966 return STATUS_NO_MEMORY;
2967 unix_name = *buffer = new_name;
2970 status = find_file_in_dir( unix_name, pos, name, end - name,
2971 check_case, redirect ? &is_win_dir : NULL );
2973 /* if this is the last element, not finding it is not necessarily fatal */
2974 if (!name_len)
2976 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2978 status = STATUS_OBJECT_NAME_NOT_FOUND;
2979 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2981 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2982 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2983 if (ret > 0 && !used_default)
2985 unix_name[pos] = '/';
2986 unix_name[pos + 1 + ret] = 0;
2987 status = STATUS_NO_SUCH_FILE;
2988 break;
2992 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2994 status = STATUS_OBJECT_NAME_COLLISION;
2998 if (status != STATUS_SUCCESS) break;
3000 pos += strlen( unix_name + pos );
3001 name = next;
3003 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
3005 name += len;
3006 name_len -= len;
3007 pos += strlen( unix_name + pos );
3008 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
3012 return status;
3016 /******************************************************************************
3017 * nt_to_unix_file_name_attr
3019 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
3020 UINT disposition )
3022 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3023 enum server_fd_type type;
3024 int old_cwd, root_fd, needs_close;
3025 const WCHAR *name, *p;
3026 char *unix_name;
3027 int name_len, unix_len;
3028 NTSTATUS status;
3029 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
3031 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
3032 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
3034 name = attr->ObjectName->Buffer;
3035 name_len = attr->ObjectName->Length / sizeof(WCHAR);
3037 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
3039 /* check for invalid characters */
3040 for (p = name; p < name + name_len; p++)
3041 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3043 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3044 unix_len += MAX_DIR_ENTRY_LEN + 3;
3045 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3046 return STATUS_NO_MEMORY;
3047 unix_name[0] = '.';
3049 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
3051 if (type != FD_TYPE_DIR)
3053 if (needs_close) close( root_fd );
3054 status = STATUS_BAD_DEVICE_TYPE;
3056 else
3058 RtlEnterCriticalSection( &dir_section );
3059 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
3061 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
3062 disposition, check_case );
3063 if (fchdir( old_cwd ) == -1) chdir( "/" );
3065 else status = FILE_GetNtStatus();
3066 RtlLeaveCriticalSection( &dir_section );
3067 if (old_cwd != -1) close( old_cwd );
3068 if (needs_close) close( root_fd );
3071 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
3073 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3075 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
3076 unix_name_ret->Buffer = unix_name;
3077 unix_name_ret->Length = strlen(unix_name);
3078 unix_name_ret->MaximumLength = unix_len;
3080 else
3082 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3083 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3085 return status;
3089 /******************************************************************************
3090 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
3092 * Convert a file name from NT namespace to Unix namespace.
3094 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
3095 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
3096 * returned, but the unix name is still filled in properly.
3098 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
3099 UINT disposition, BOOLEAN check_case )
3101 static const WCHAR unixW[] = {'u','n','i','x'};
3102 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
3104 NTSTATUS status = STATUS_SUCCESS;
3105 const char *config_dir = wine_get_config_dir();
3106 const WCHAR *name, *p;
3107 struct stat st;
3108 char *unix_name;
3109 int pos, ret, name_len, unix_len, prefix_len, used_default;
3110 WCHAR prefix[MAX_DIR_ENTRY_LEN];
3111 BOOLEAN is_unix = FALSE;
3113 name = nameW->Buffer;
3114 name_len = nameW->Length / sizeof(WCHAR);
3116 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3118 if (!(pos = get_dos_prefix_len( nameW )))
3119 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
3121 name += pos;
3122 name_len -= pos;
3124 if (!name_len) return STATUS_OBJECT_NAME_INVALID;
3126 /* check for sub-directory */
3127 for (pos = 0; pos < name_len; pos++)
3129 if (IS_SEPARATOR(name[pos])) break;
3130 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
3131 return STATUS_OBJECT_NAME_INVALID;
3133 if (pos > MAX_DIR_ENTRY_LEN)
3134 return STATUS_OBJECT_NAME_INVALID;
3136 if (pos == name_len) /* no subdir, plain DOS device */
3137 return get_dos_device( name, name_len, unix_name_ret );
3139 for (prefix_len = 0; prefix_len < pos; prefix_len++)
3140 prefix[prefix_len] = tolowerW(name[prefix_len]);
3142 name += prefix_len;
3143 name_len -= prefix_len;
3145 /* check for invalid characters (all chars except 0 are valid for unix) */
3146 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
3147 if (is_unix)
3149 for (p = name; p < name + name_len; p++)
3150 if (!*p) return STATUS_OBJECT_NAME_INVALID;
3151 check_case = TRUE;
3153 else
3155 for (p = name; p < name + name_len; p++)
3156 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
3159 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
3160 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
3161 unix_len += MAX_DIR_ENTRY_LEN + 3;
3162 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
3163 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
3164 return STATUS_NO_MEMORY;
3165 strcpy( unix_name, config_dir );
3166 strcat( unix_name, "/dosdevices/" );
3167 pos = strlen(unix_name);
3169 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
3170 NULL, &used_default );
3171 if (!ret || used_default)
3173 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3174 return STATUS_OBJECT_NAME_INVALID;
3176 pos += ret;
3178 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
3180 if (prefix_len != 2 || prefix[1] != ':')
3182 unix_name[pos] = 0;
3183 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
3185 if (!is_unix)
3187 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3188 return STATUS_BAD_DEVICE_TYPE;
3190 pos = 0; /* fall back to unix root */
3194 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
3195 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
3197 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
3198 unix_name_ret->Buffer = unix_name;
3199 unix_name_ret->Length = strlen(unix_name);
3200 unix_name_ret->MaximumLength = unix_len;
3202 else
3204 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
3205 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
3207 return status;
3211 /******************************************************************
3212 * RtlWow64EnableFsRedirection (NTDLL.@)
3214 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
3216 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3217 ntdll_get_thread_data()->wow64_redir = enable;
3218 return STATUS_SUCCESS;
3222 /******************************************************************
3223 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
3225 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
3227 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
3228 if (((ULONG_PTR)old_value >> 16) == 0) return STATUS_ACCESS_VIOLATION;
3230 *old_value = !ntdll_get_thread_data()->wow64_redir;
3231 ntdll_get_thread_data()->wow64_redir = !disable;
3232 return STATUS_SUCCESS;
3236 /******************************************************************
3237 * RtlDoesFileExists_U (NTDLL.@)
3239 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
3241 UNICODE_STRING nt_name;
3242 FILE_BASIC_INFORMATION basic_info;
3243 OBJECT_ATTRIBUTES attr;
3244 BOOLEAN ret;
3246 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
3248 attr.Length = sizeof(attr);
3249 attr.RootDirectory = 0;
3250 attr.ObjectName = &nt_name;
3251 attr.Attributes = OBJ_CASE_INSENSITIVE;
3252 attr.SecurityDescriptor = NULL;
3253 attr.SecurityQualityOfService = NULL;
3255 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
3257 RtlFreeUnicodeString( &nt_name );
3258 return ret;
3262 /***********************************************************************
3263 * DIR_unmount_device
3265 * Unmount the specified device.
3267 NTSTATUS DIR_unmount_device( HANDLE handle )
3269 NTSTATUS status;
3270 int unix_fd, needs_close;
3272 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3274 struct stat st;
3275 char *mount_point = NULL;
3277 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3278 status = STATUS_INVALID_PARAMETER;
3279 else
3281 if ((mount_point = get_device_mount_point( st.st_rdev )))
3283 #ifdef __APPLE__
3284 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3285 #else
3286 static const char umount[] = "umount >/dev/null 2>&1 ";
3287 #endif
3288 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3289 if (cmd)
3291 strcpy( cmd, umount );
3292 strcat( cmd, mount_point );
3293 system( cmd );
3294 RtlFreeHeap( GetProcessHeap(), 0, cmd );
3295 #ifdef linux
3296 /* umount will fail to release the loop device since we still have
3297 a handle to it, so we release it here */
3298 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3299 #endif
3301 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3304 if (needs_close) close( unix_fd );
3306 return status;
3310 /******************************************************************************
3311 * DIR_get_unix_cwd
3313 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3314 * Returned value must be freed by caller.
3316 NTSTATUS DIR_get_unix_cwd( char **cwd )
3318 int old_cwd, unix_fd, needs_close;
3319 CURDIR *curdir;
3320 HANDLE handle;
3321 NTSTATUS status;
3323 RtlAcquirePebLock();
3325 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
3326 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3327 else
3328 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3330 if (!(handle = curdir->Handle))
3332 UNICODE_STRING dirW;
3333 OBJECT_ATTRIBUTES attr;
3334 IO_STATUS_BLOCK io;
3336 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3338 status = STATUS_OBJECT_NAME_INVALID;
3339 goto done;
3341 attr.Length = sizeof(attr);
3342 attr.RootDirectory = 0;
3343 attr.Attributes = OBJ_CASE_INSENSITIVE;
3344 attr.ObjectName = &dirW;
3345 attr.SecurityDescriptor = NULL;
3346 attr.SecurityQualityOfService = NULL;
3348 status = NtOpenFile( &handle, 0, &attr, &io, 0,
3349 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3350 RtlFreeUnicodeString( &dirW );
3351 if (status != STATUS_SUCCESS) goto done;
3354 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3356 RtlEnterCriticalSection( &dir_section );
3358 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3360 unsigned int size = 512;
3362 for (;;)
3364 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3366 status = STATUS_NO_MEMORY;
3367 break;
3369 if (getcwd( *cwd, size )) break;
3370 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3371 if (errno != ERANGE)
3373 status = STATUS_OBJECT_PATH_INVALID;
3374 break;
3376 size *= 2;
3378 if (fchdir( old_cwd ) == -1) chdir( "/" );
3380 else status = FILE_GetNtStatus();
3382 RtlLeaveCriticalSection( &dir_section );
3383 if (old_cwd != -1) close( old_cwd );
3384 if (needs_close) close( unix_fd );
3386 if (!curdir->Handle) NtClose( handle );
3388 done:
3389 RtlReleasePebLock();
3390 return status;