dbghelp: Use local declarations of r_debug and link_map structs.
[wine.git] / dlls / ntdll / directory.c
blobbe55a5a8c1f1628afeb8c91eeef10347c7ff85c2
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 MAJOR_IN_MKDEV
51 # include <sys/mkdev.h>
52 #elif defined(MAJOR_IN_SYSMACROS)
53 # include <sys/sysmacros.h>
54 #endif
55 #ifdef HAVE_SYS_VNODE_H
56 # ifdef HAVE_STDINT_H
57 # include <stdint.h> /* needed for kfreebsd */
58 # endif
59 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
60 #define list SYSLIST
61 #define list_next SYSLIST_NEXT
62 #define list_prev SYSLIST_PREV
63 #define list_head SYSLIST_HEAD
64 #define list_tail SYSLIST_TAIL
65 #define list_move_tail SYSLIST_MOVE_TAIL
66 #define list_remove SYSLIST_REMOVE
67 #include <sys/vnode.h>
68 #undef list
69 #undef list_next
70 #undef list_prev
71 #undef list_head
72 #undef list_tail
73 #undef list_move_tail
74 #undef list_remove
75 #endif
76 #ifdef HAVE_SYS_IOCTL_H
77 #include <sys/ioctl.h>
78 #endif
79 #ifdef HAVE_LINUX_IOCTL_H
80 #include <linux/ioctl.h>
81 #endif
82 #ifdef HAVE_LINUX_MAJOR_H
83 # include <linux/major.h>
84 #endif
85 #ifdef HAVE_SYS_PARAM_H
86 #include <sys/param.h>
87 #endif
88 #ifdef HAVE_SYS_MOUNT_H
89 #include <sys/mount.h>
90 #endif
91 #ifdef HAVE_SYS_STATFS_H
92 #include <sys/statfs.h>
93 #endif
94 #include <time.h>
95 #ifdef HAVE_UNISTD_H
96 # include <unistd.h>
97 #endif
99 #include "ntstatus.h"
100 #define WIN32_NO_STATUS
101 #define NONAMELESSUNION
102 #include "windef.h"
103 #include "winnt.h"
104 #include "winternl.h"
105 #include "ddk/wdm.h"
106 #include "ntdll_misc.h"
107 #include "wine/server.h"
108 #include "wine/list.h"
109 #include "wine/library.h"
110 #include "wine/debug.h"
111 #include "wine/exception.h"
113 WINE_DEFAULT_DEBUG_CHANNEL(file);
115 /* just in case... */
116 #undef VFAT_IOCTL_READDIR_BOTH
117 #undef EXT2_IOC_GETFLAGS
118 #undef EXT4_CASEFOLD_FL
120 #ifdef linux
122 /* We want the real kernel dirent structure, not the libc one */
123 typedef struct
125 long d_ino;
126 long d_off;
127 unsigned short d_reclen;
128 char d_name[256];
129 } KERNEL_DIRENT;
131 /* Define the VFAT ioctl to get both short and long file names */
132 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
134 /* Define the ext2 ioctl for handling extra attributes */
135 #define EXT2_IOC_GETFLAGS _IOR('f', 1, long)
137 /* Case-insensitivity attribute */
138 #define EXT4_CASEFOLD_FL 0x40000000
140 #ifndef O_DIRECTORY
141 # define O_DIRECTORY 0200000 /* must be directory */
142 #endif
144 #ifndef AT_NO_AUTOMOUNT
145 #define AT_NO_AUTOMOUNT 0x800
146 #endif
148 #endif /* linux */
150 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
151 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
153 #define INVALID_NT_CHARS '*','?','<','>','|','"'
154 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
156 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
158 #define MAX_IGNORED_FILES 4
160 struct file_identity
162 dev_t dev;
163 ino_t ino;
166 static struct file_identity ignored_files[MAX_IGNORED_FILES];
167 static unsigned int ignored_files_count;
169 union file_directory_info
171 ULONG next;
172 FILE_DIRECTORY_INFORMATION dir;
173 FILE_BOTH_DIRECTORY_INFORMATION both;
174 FILE_FULL_DIRECTORY_INFORMATION full;
175 FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
176 FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
177 FILE_ID_GLOBAL_TX_DIR_INFORMATION id_tx;
178 FILE_NAMES_INFORMATION names;
181 struct dir_data_buffer
183 struct dir_data_buffer *next; /* next buffer in the list */
184 unsigned int size; /* total size of the buffer */
185 unsigned int pos; /* current position in the buffer */
186 char data[1];
189 struct dir_data_names
191 const WCHAR *long_name; /* long file name in Unicode */
192 const WCHAR *short_name; /* short file name in Unicode */
193 const char *unix_name; /* Unix file name in host encoding */
196 struct dir_data
198 unsigned int size; /* size of the names array */
199 unsigned int count; /* count of used entries in the names array */
200 unsigned int pos; /* current reading position in the names array */
201 struct file_identity id; /* directory file identity */
202 struct dir_data_names *names; /* directory file names */
203 struct dir_data_buffer *buffer; /* head of data buffers list */
206 static const unsigned int dir_data_buffer_initial_size = 4096;
207 static const unsigned int dir_data_cache_initial_size = 256;
208 static const unsigned int dir_data_names_initial_size = 64;
210 static struct dir_data **dir_data_cache;
211 static unsigned int dir_data_cache_size;
213 static BOOL show_dot_files;
214 static RTL_RUN_ONCE init_once = RTL_RUN_ONCE_INIT;
216 /* at some point we may want to allow Winelib apps to set this */
217 static const BOOL is_case_sensitive = FALSE;
219 static struct file_identity windir;
221 static RTL_CRITICAL_SECTION dir_section;
222 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
224 0, 0, &dir_section,
225 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
226 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
228 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
231 /* check if a given Unicode char is OK in a DOS short name */
232 static inline BOOL is_invalid_dos_char( WCHAR ch )
234 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
235 if (ch > 0x7f) return TRUE;
236 return wcschr( invalid_chars, ch ) != NULL;
239 /* check if the device can be a mounted volume */
240 static inline BOOL is_valid_mounted_device( const struct stat *st )
242 #if defined(linux) || defined(__sun__)
243 return S_ISBLK( st->st_mode );
244 #else
245 /* disks are char devices on *BSD */
246 return S_ISCHR( st->st_mode );
247 #endif
250 static inline void ignore_file( const char *name )
252 struct stat st;
253 assert( ignored_files_count < MAX_IGNORED_FILES );
254 if (!stat( name, &st ))
256 ignored_files[ignored_files_count].dev = st.st_dev;
257 ignored_files[ignored_files_count].ino = st.st_ino;
258 ignored_files_count++;
262 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
264 return st->st_dev == file->dev && st->st_ino == file->ino;
267 static inline BOOL is_ignored_file( const struct stat *st )
269 unsigned int i;
271 for (i = 0; i < ignored_files_count; i++)
272 if (is_same_file( &ignored_files[i], st )) return TRUE;
273 return FALSE;
276 static inline unsigned int dir_info_align( unsigned int len )
278 return (len + 7) & ~7;
281 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
283 switch (class)
285 case FileDirectoryInformation:
286 return offsetof( FILE_DIRECTORY_INFORMATION, FileName[len] );
287 case FileBothDirectoryInformation:
288 return offsetof( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] );
289 case FileFullDirectoryInformation:
290 return offsetof( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] );
291 case FileIdBothDirectoryInformation:
292 return offsetof( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] );
293 case FileIdFullDirectoryInformation:
294 return offsetof( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] );
295 case FileIdGlobalTxDirectoryInformation:
296 return offsetof( FILE_ID_GLOBAL_TX_DIR_INFORMATION, FileName[len] );
297 case FileNamesInformation:
298 return offsetof( FILE_NAMES_INFORMATION, FileName[len] );
299 default:
300 assert(0);
301 return 0;
305 static inline BOOL has_wildcard( const UNICODE_STRING *mask )
307 int i;
309 if (!mask) return TRUE;
310 for (i = 0; i < mask->Length / sizeof(WCHAR); i++)
311 if (mask->Buffer[i] == '*' || mask->Buffer[i] == '?') return TRUE;
312 return FALSE;
315 /* get space from the current directory data buffer, allocating a new one if necessary */
316 static void *get_dir_data_space( struct dir_data *data, unsigned int size )
318 struct dir_data_buffer *buffer = data->buffer;
319 void *ret;
321 if (!buffer || size > buffer->size - buffer->pos)
323 unsigned int new_size = buffer ? buffer->size * 2 : dir_data_buffer_initial_size;
324 if (new_size < size) new_size = size;
325 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0,
326 offsetof( struct dir_data_buffer, data[new_size] ) ))) return NULL;
327 buffer->pos = 0;
328 buffer->size = new_size;
329 buffer->next = data->buffer;
330 data->buffer = buffer;
332 ret = buffer->data + buffer->pos;
333 buffer->pos += size;
334 return ret;
337 /* add a string to the directory data buffer */
338 static const char *add_dir_data_nameA( struct dir_data *data, const char *name )
340 /* keep buffer data WCHAR-aligned */
341 char *ptr = get_dir_data_space( data, (strlen( name ) + sizeof(WCHAR)) & ~(sizeof(WCHAR) - 1) );
342 if (ptr) strcpy( ptr, name );
343 return ptr;
346 /* add a Unicode string to the directory data buffer */
347 static const WCHAR *add_dir_data_nameW( struct dir_data *data, const WCHAR *name )
349 WCHAR *ptr = get_dir_data_space( data, (wcslen( name ) + 1) * sizeof(WCHAR) );
350 if (ptr) wcscpy( ptr, name );
351 return ptr;
354 /* add an entry to the directory names array */
355 static BOOL add_dir_data_names( struct dir_data *data, const WCHAR *long_name,
356 const WCHAR *short_name, const char *unix_name )
358 static const WCHAR empty[1];
359 struct dir_data_names *names = data->names;
361 if (data->count >= data->size)
363 unsigned int new_size = max( data->size * 2, dir_data_names_initial_size );
365 if (names) names = RtlReAllocateHeap( GetProcessHeap(), 0, names, new_size * sizeof(*names) );
366 else names = RtlAllocateHeap( GetProcessHeap(), 0, new_size * sizeof(*names) );
367 if (!names) return FALSE;
368 data->size = new_size;
369 data->names = names;
372 if (short_name[0])
374 if (!(names[data->count].short_name = add_dir_data_nameW( data, short_name ))) return FALSE;
376 else names[data->count].short_name = empty;
378 if (!(names[data->count].long_name = add_dir_data_nameW( data, long_name ))) return FALSE;
379 if (!(names[data->count].unix_name = add_dir_data_nameA( data, unix_name ))) return FALSE;
380 data->count++;
381 return TRUE;
384 /* free the complete directory data structure */
385 static void free_dir_data( struct dir_data *data )
387 struct dir_data_buffer *buffer, *next;
389 if (!data) return;
391 for (buffer = data->buffer; buffer; buffer = next)
393 next = buffer->next;
394 RtlFreeHeap( GetProcessHeap(), 0, buffer );
396 RtlFreeHeap( GetProcessHeap(), 0, data->names );
397 RtlFreeHeap( GetProcessHeap(), 0, data );
401 /* support for a directory queue for filesystem searches */
403 struct dir_name
405 struct list entry;
406 char name[1];
409 static struct list dir_queue = LIST_INIT( dir_queue );
411 static NTSTATUS add_dir_to_queue( const char *name )
413 int len = strlen( name ) + 1;
414 struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
415 FIELD_OFFSET( struct dir_name, name[len] ));
416 if (!dir) return STATUS_NO_MEMORY;
417 strcpy( dir->name, name );
418 list_add_tail( &dir_queue, &dir->entry );
419 return STATUS_SUCCESS;
422 static NTSTATUS next_dir_in_queue( char *name )
424 struct list *head = list_head( &dir_queue );
425 if (head)
427 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
428 strcpy( name, dir->name );
429 list_remove( &dir->entry );
430 RtlFreeHeap( GetProcessHeap(), 0, dir );
431 return STATUS_SUCCESS;
433 return STATUS_OBJECT_NAME_NOT_FOUND;
436 static void flush_dir_queue(void)
438 struct list *head;
440 while ((head = list_head( &dir_queue )))
442 struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
443 list_remove( &dir->entry );
444 RtlFreeHeap( GetProcessHeap(), 0, dir );
449 #ifdef __ANDROID__
451 static char *unescape_field( char *str )
453 char *in, *out;
455 for (in = out = str; *in; in++, out++)
457 *out = *in;
458 if (in[0] == '\\')
460 if (in[1] == '\\')
462 out[0] = '\\';
463 in++;
465 else if (in[1] == '0' && in[2] == '4' && in[3] == '0')
467 out[0] = ' ';
468 in += 3;
470 else if (in[1] == '0' && in[2] == '1' && in[3] == '1')
472 out[0] = '\t';
473 in += 3;
475 else if (in[1] == '0' && in[2] == '1' && in[3] == '2')
477 out[0] = '\n';
478 in += 3;
480 else if (in[1] == '1' && in[2] == '3' && in[3] == '4')
482 out[0] = '\\';
483 in += 3;
487 *out = '\0';
489 return str;
492 static inline char *get_field( char **str )
494 char *ret;
496 ret = strsep( str, " \t" );
497 if (*str) *str += strspn( *str, " \t" );
499 return ret;
501 /************************************************************************
502 * getmntent_replacement
504 * getmntent replacement for Android.
506 * NB returned static buffer is not thread safe; protect with dir_section.
508 static struct mntent *getmntent_replacement( FILE *f )
510 static struct mntent entry;
511 static char buf[4096];
512 char *p, *start;
516 if (!fgets( buf, sizeof(buf), f )) return NULL;
517 p = strchr( buf, '\n' );
518 if (p) *p = '\0';
519 else /* Partially unread line, move file ptr to end */
521 char tmp[1024];
522 while (fgets( tmp, sizeof(tmp), f ))
523 if (strchr( tmp, '\n' )) break;
525 start = buf + strspn( buf, " \t" );
526 } while (start[0] == '\0' || start[0] == '#');
528 p = get_field( &start );
529 entry.mnt_fsname = p ? unescape_field( p ) : (char *)"";
531 p = get_field( &start );
532 entry.mnt_dir = p ? unescape_field( p ) : (char *)"";
534 p = get_field( &start );
535 entry.mnt_type = p ? unescape_field( p ) : (char *)"";
537 p = get_field( &start );
538 entry.mnt_opts = p ? unescape_field( p ) : (char *)"";
540 p = get_field( &start );
541 entry.mnt_freq = p ? atoi(p) : 0;
543 p = get_field( &start );
544 entry.mnt_passno = p ? atoi(p) : 0;
546 return &entry;
548 #define getmntent getmntent_replacement
549 #endif
551 /***********************************************************************
552 * DIR_get_drives_info
554 * Retrieve device/inode number for all the drives. Helper for find_drive_root.
556 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
558 static struct drive_info cache[MAX_DOS_DRIVES];
559 static time_t last_update;
560 static unsigned int nb_drives;
561 unsigned int ret;
562 time_t now = time(NULL);
564 RtlEnterCriticalSection( &dir_section );
565 if (now != last_update)
567 const char *config_dir = wine_get_config_dir();
568 char *buffer, *p;
569 struct stat st;
570 unsigned int i;
572 if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
573 strlen(config_dir) + sizeof("/dosdevices/a:") )))
575 strcpy( buffer, config_dir );
576 strcat( buffer, "/dosdevices/a:" );
577 p = buffer + strlen(buffer) - 2;
579 for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
581 *p = 'a' + i;
582 if (!stat( buffer, &st ))
584 cache[i].dev = st.st_dev;
585 cache[i].ino = st.st_ino;
586 nb_drives++;
588 else
590 cache[i].dev = 0;
591 cache[i].ino = 0;
594 RtlFreeHeap( GetProcessHeap(), 0, buffer );
596 last_update = now;
598 memcpy( info, cache, sizeof(cache) );
599 ret = nb_drives;
600 RtlLeaveCriticalSection( &dir_section );
601 return ret;
605 /***********************************************************************
606 * parse_mount_entries
608 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
611 #ifdef sun
612 #include <sys/vfstab.h>
613 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
615 struct vfstab entry;
616 struct stat st;
617 char *device;
619 while (! getvfsent( f, &entry ))
621 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
622 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
623 !strcmp( entry.vfs_fstype, "smbfs" ) ||
624 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
626 if (stat( entry.vfs_mountp, &st ) == -1) continue;
627 if (st.st_dev != dev || st.st_ino != ino) continue;
628 if (!strcmp( entry.vfs_fstype, "fd" ))
630 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
632 char *p = strchr( device + 4, ',' );
633 if (p) *p = 0;
634 return device + 4;
637 else
638 return entry.vfs_special;
640 return NULL;
642 #endif
644 #ifdef linux
645 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
647 struct mntent *entry;
648 struct stat st;
649 char *device;
651 while ((entry = getmntent( f )))
653 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
654 if (!strcmp( entry->mnt_type, "nfs" ) ||
655 !strcmp( entry->mnt_type, "cifs" ) ||
656 !strcmp( entry->mnt_type, "smbfs" ) ||
657 !strcmp( entry->mnt_type, "ncpfs" )) continue;
659 if (stat( entry->mnt_dir, &st ) == -1) continue;
660 if (st.st_dev != dev || st.st_ino != ino) continue;
661 if (!strcmp( entry->mnt_type, "supermount" ))
663 if ((device = strstr( entry->mnt_opts, "dev=" )))
665 char *p = strchr( device + 4, ',' );
666 if (p) *p = 0;
667 return device + 4;
670 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
672 /* if device is a regular file check for a loop mount */
673 if ((device = strstr( entry->mnt_opts, "loop=" )))
675 char *p = strchr( device + 5, ',' );
676 if (p) *p = 0;
677 return device + 5;
680 else
681 return entry->mnt_fsname;
683 return NULL;
685 #endif
687 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
688 #include <fstab.h>
689 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
691 struct fstab *entry;
692 struct stat st;
694 while ((entry = getfsent()))
696 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
697 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
698 !strcmp( entry->fs_vfstype, "smbfs" ) ||
699 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
701 if (stat( entry->fs_file, &st ) == -1) continue;
702 if (st.st_dev != dev || st.st_ino != ino) continue;
703 return entry->fs_spec;
705 return NULL;
707 #endif
709 #ifdef sun
710 #include <sys/mnttab.h>
711 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
713 struct mnttab entry;
714 struct stat st;
715 char *device;
718 while (( ! getmntent( f, &entry) ))
720 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
721 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
722 !strcmp( entry.mnt_fstype, "smbfs" ) ||
723 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
725 if (stat( entry.mnt_mountp, &st ) == -1) continue;
726 if (st.st_dev != dev || st.st_ino != ino) continue;
727 if (!strcmp( entry.mnt_fstype, "fd" ))
729 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
731 char *p = strchr( device + 4, ',' );
732 if (p) *p = 0;
733 return device + 4;
736 else
737 return entry.mnt_special;
739 return NULL;
741 #endif
743 /***********************************************************************
744 * get_default_drive_device
746 * Return the default device to use for a given drive mount point.
748 static char *get_default_drive_device( const char *root )
750 char *ret = NULL;
752 #ifdef linux
753 FILE *f;
754 char *device = NULL;
755 int fd, res = -1;
756 struct stat st;
758 /* try to open it first to force it to get mounted */
759 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
761 res = fstat( fd, &st );
762 close( fd );
764 /* now try normal stat just in case */
765 if (res == -1) res = stat( root, &st );
766 if (res == -1) return NULL;
768 RtlEnterCriticalSection( &dir_section );
770 #ifdef __ANDROID__
771 if ((f = fopen( "/proc/mounts", "r" )))
773 device = parse_mount_entries( f, st.st_dev, st.st_ino );
774 fclose( f );
776 #else
777 if ((f = fopen( "/etc/mtab", "r" )))
779 device = parse_mount_entries( f, st.st_dev, st.st_ino );
780 fclose( f );
782 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
783 if (!device && (f = fopen( "/etc/fstab", "r" )))
785 device = parse_mount_entries( f, st.st_dev, st.st_ino );
786 fclose( f );
788 #endif
789 if (device)
791 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
792 if (ret) strcpy( ret, device );
794 RtlLeaveCriticalSection( &dir_section );
796 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ ) || defined(__DragonFly__)
797 char *device = NULL;
798 int fd, res = -1;
799 struct stat st;
801 /* try to open it first to force it to get mounted */
802 if ((fd = open( root, O_RDONLY )) != -1)
804 res = fstat( fd, &st );
805 close( fd );
807 /* now try normal stat just in case */
808 if (res == -1) res = stat( root, &st );
809 if (res == -1) return NULL;
811 RtlEnterCriticalSection( &dir_section );
813 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
814 * pass NULL. Leave the argument in for symmetry.
816 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
817 if (device)
819 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
820 if (ret) strcpy( ret, device );
822 RtlLeaveCriticalSection( &dir_section );
824 #elif defined( sun )
825 FILE *f;
826 char *device = NULL;
827 int fd, res = -1;
828 struct stat st;
830 /* try to open it first to force it to get mounted */
831 if ((fd = open( root, O_RDONLY )) != -1)
833 res = fstat( fd, &st );
834 close( fd );
836 /* now try normal stat just in case */
837 if (res == -1) res = stat( root, &st );
838 if (res == -1) return NULL;
840 RtlEnterCriticalSection( &dir_section );
842 if ((f = fopen( "/etc/mnttab", "r" )))
844 device = parse_mount_entries( f, st.st_dev, st.st_ino);
845 fclose( f );
847 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
848 if (!device && (f = fopen( "/etc/vfstab", "r" )))
850 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
851 fclose( f );
853 if (device)
855 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
856 if (ret) strcpy( ret, device );
858 RtlLeaveCriticalSection( &dir_section );
860 #elif defined(__APPLE__)
861 struct statfs *mntStat;
862 struct stat st;
863 int i;
864 int mntSize;
865 dev_t dev;
866 ino_t ino;
867 static const char path_bsd_device[] = "/dev/disk";
868 int res;
870 res = stat( root, &st );
871 if (res == -1) return NULL;
873 dev = st.st_dev;
874 ino = st.st_ino;
876 RtlEnterCriticalSection( &dir_section );
878 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
880 for (i = 0; i < mntSize && !ret; i++)
882 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
883 if (st.st_dev != dev || st.st_ino != ino) continue;
885 /* FIXME add support for mounted network drive */
886 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
888 /* set return value to the corresponding raw BSD node */
889 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
890 if (ret)
892 strcpy(ret, "/dev/r");
893 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
897 RtlLeaveCriticalSection( &dir_section );
898 #else
899 static int warned;
900 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
901 #endif
902 return ret;
906 /***********************************************************************
907 * get_device_mount_point
909 * Return the current mount point for a device.
911 static char *get_device_mount_point( dev_t dev )
913 char *ret = NULL;
915 #ifdef linux
916 FILE *f;
918 RtlEnterCriticalSection( &dir_section );
920 #ifdef __ANDROID__
921 if ((f = fopen( "/proc/mounts", "r" )))
922 #else
923 if ((f = fopen( "/etc/mtab", "r" )))
924 #endif
926 struct mntent *entry;
927 struct stat st;
928 char *p, *device;
930 while ((entry = getmntent( f )))
932 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
933 if (!strcmp( entry->mnt_type, "nfs" ) ||
934 !strcmp( entry->mnt_type, "cifs" ) ||
935 !strcmp( entry->mnt_type, "smbfs" ) ||
936 !strcmp( entry->mnt_type, "ncpfs" )) continue;
938 if (!strcmp( entry->mnt_type, "supermount" ))
940 if ((device = strstr( entry->mnt_opts, "dev=" )))
942 device += 4;
943 if ((p = strchr( device, ',' ))) *p = 0;
946 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
948 /* if device is a regular file check for a loop mount */
949 if ((device = strstr( entry->mnt_opts, "loop=" )))
951 device += 5;
952 if ((p = strchr( device, ',' ))) *p = 0;
955 else device = entry->mnt_fsname;
957 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
959 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
960 if (ret) strcpy( ret, entry->mnt_dir );
961 break;
964 fclose( f );
966 RtlLeaveCriticalSection( &dir_section );
967 #elif defined(__APPLE__)
968 struct statfs *entry;
969 struct stat st;
970 int i, size;
972 RtlEnterCriticalSection( &dir_section );
974 size = getmntinfo( &entry, MNT_NOWAIT );
975 for (i = 0; i < size; i++)
977 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
978 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
980 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntonname) + 1 );
981 if (ret) strcpy( ret, entry[i].f_mntonname );
982 break;
985 RtlLeaveCriticalSection( &dir_section );
986 #else
987 static int warned;
988 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
989 #endif
990 return ret;
994 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
995 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
997 struct get_fsid
999 ULONG size;
1000 dev_t dev;
1001 fsid_t fsid;
1004 struct fs_cache
1006 dev_t dev;
1007 fsid_t fsid;
1008 BOOLEAN case_sensitive;
1009 } fs_cache[64];
1011 struct vol_caps
1013 ULONG size;
1014 vol_capabilities_attr_t caps;
1017 /***********************************************************************
1018 * look_up_fs_cache
1020 * Checks if the specified file system is in the cache.
1022 static struct fs_cache *look_up_fs_cache( dev_t dev )
1024 int i;
1025 for (i = 0; i < ARRAY_SIZE( fs_cache ); i++)
1026 if (fs_cache[i].dev == dev)
1027 return fs_cache+i;
1028 return NULL;
1031 /***********************************************************************
1032 * add_fs_cache
1034 * Adds the specified file system to the cache.
1036 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
1038 int i;
1039 struct fs_cache *entry = look_up_fs_cache( dev );
1040 static int once = 0;
1041 if (entry)
1043 /* Update the cache */
1044 entry->fsid = fsid;
1045 entry->case_sensitive = case_sensitive;
1046 return;
1049 /* Add a new entry */
1050 for (i = 0; i < ARRAY_SIZE( fs_cache ); i++)
1051 if (fs_cache[i].dev == 0)
1053 /* This entry is empty, use it */
1054 fs_cache[i].dev = dev;
1055 fs_cache[i].fsid = fsid;
1056 fs_cache[i].case_sensitive = case_sensitive;
1057 return;
1060 /* Cache is out of space, warn */
1061 if (!once++)
1062 WARN( "FS cache is out of space, expect performance problems\n" );
1065 /***********************************************************************
1066 * get_dir_case_sensitivity_attr
1068 * Checks if the volume containing the specified directory is case
1069 * sensitive or not. Uses getattrlist(2).
1071 static int get_dir_case_sensitivity_attr( const char *dir )
1073 char *mntpoint;
1074 struct attrlist attr;
1075 struct vol_caps caps;
1076 struct get_fsid get_fsid;
1077 struct fs_cache *entry;
1079 /* First get the FS ID of the volume */
1080 attr.bitmapcount = ATTR_BIT_MAP_COUNT;
1081 attr.reserved = 0;
1082 attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
1083 attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
1084 get_fsid.size = 0;
1085 if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
1086 get_fsid.size != sizeof(get_fsid))
1087 return -1;
1088 /* Try to look it up in the cache */
1089 entry = look_up_fs_cache( get_fsid.dev );
1090 if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
1091 /* Cache lookup succeeded */
1092 return entry->case_sensitive;
1093 /* Cache is stale at this point, we have to update it */
1095 mntpoint = get_device_mount_point( get_fsid.dev );
1096 /* Now look up the case-sensitivity */
1097 attr.commonattr = 0;
1098 attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
1099 if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
1101 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1102 add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
1103 return TRUE;
1105 RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
1106 if (caps.size == sizeof(caps) &&
1107 (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
1108 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
1109 (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
1111 BOOLEAN ret;
1113 if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
1114 VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
1115 ret = FALSE;
1116 else
1117 ret = TRUE;
1118 /* Update the cache */
1119 add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
1120 return ret;
1122 return FALSE;
1124 #endif
1126 /***********************************************************************
1127 * get_dir_case_sensitivity_stat
1129 * Checks if the volume containing the specified directory is case
1130 * sensitive or not. Uses (f)statfs(2), statvfs(2), fstatat(2), or ioctl(2).
1132 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
1134 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1135 struct statfs stfs;
1137 if (statfs( dir, &stfs ) == -1) return FALSE;
1138 /* Assume these file systems are always case insensitive on Mac OS.
1139 * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
1140 * is the only UNIX that supports case-insensitive lookup).
1142 if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
1143 !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1144 return FALSE;
1145 #ifdef __APPLE__
1146 if (!strcmp( stfs.f_fstypename, "msdos" ) ||
1147 !strcmp( stfs.f_fstypename, "cd9660" ) ||
1148 !strcmp( stfs.f_fstypename, "udf" ) ||
1149 !strcmp( stfs.f_fstypename, "ntfs" ) ||
1150 !strcmp( stfs.f_fstypename, "smbfs" ))
1151 return FALSE;
1152 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1153 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
1154 stfs.f_fssubtype == 1 ||
1155 stfs.f_fssubtype == 128))
1156 return FALSE;
1157 #else
1158 /* The field says "reserved", but a quick look at the kernel source
1159 * tells us that this "reserved" field is really the same as the
1160 * "fssubtype" field from the inode64 structure (see munge_statfs()
1161 * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
1163 if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
1164 stfs.f_reserved1 == 1 ||
1165 stfs.f_reserved1 == 128))
1166 return FALSE;
1167 #endif
1168 #endif
1169 return TRUE;
1171 #elif defined(__NetBSD__)
1172 struct statvfs stfs;
1174 if (statvfs( dir, &stfs ) == -1) return FALSE;
1175 /* Only assume CIOPFS is case insensitive. */
1176 if (strcmp( stfs.f_fstypename, "fusefs" ) ||
1177 strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
1178 return TRUE;
1179 return FALSE;
1181 #elif defined(__linux__)
1182 BOOLEAN sens = TRUE;
1183 struct statfs stfs;
1184 struct stat st;
1185 int fd, flags;
1187 if ((fd = open( dir, O_RDONLY | O_NONBLOCK | O_LARGEFILE )) == -1)
1188 return TRUE;
1190 if (ioctl( fd, EXT2_IOC_GETFLAGS, &flags ) != -1 && (flags & EXT4_CASEFOLD_FL))
1192 sens = FALSE;
1194 else if (fstatfs( fd, &stfs ) == 0 && /* CIOPFS is case insensitive. Instead of */
1195 stfs.f_type == 0x65735546 /* FUSE_SUPER_MAGIC */ && /* parsing mtab to discover if the FUSE FS */
1196 fstatat( fd, ".ciopfs", &st, AT_NO_AUTOMOUNT ) == 0) /* is CIOPFS, look for .ciopfs in the dir. */
1198 sens = FALSE;
1201 close( fd );
1202 return sens;
1203 #else
1204 return TRUE;
1205 #endif
1209 /***********************************************************************
1210 * get_dir_case_sensitivity
1212 * Checks if the volume containing the specified directory is case
1213 * sensitive or not. Uses multiple methods, depending on platform.
1215 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1217 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1218 defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1219 int case_sensitive = get_dir_case_sensitivity_attr( dir );
1220 if (case_sensitive != -1) return case_sensitive;
1221 #endif
1222 return get_dir_case_sensitivity_stat( dir );
1226 /***********************************************************************
1227 * init_options
1229 * Initialize the show_dot_files options.
1231 static DWORD WINAPI init_options( RTL_RUN_ONCE *once, void *param, void **context )
1233 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1234 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1235 char tmp[80];
1236 HANDLE root, hkey;
1237 DWORD dummy;
1238 OBJECT_ATTRIBUTES attr;
1239 UNICODE_STRING nameW;
1241 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1242 attr.Length = sizeof(attr);
1243 attr.RootDirectory = root;
1244 attr.ObjectName = &nameW;
1245 attr.Attributes = 0;
1246 attr.SecurityDescriptor = NULL;
1247 attr.SecurityQualityOfService = NULL;
1248 RtlInitUnicodeString( &nameW, WineW );
1250 /* @@ Wine registry key: HKCU\Software\Wine */
1251 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1253 RtlInitUnicodeString( &nameW, ShowDotFilesW );
1254 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1256 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1257 show_dot_files = IS_OPTION_TRUE( str[0] );
1259 NtClose( hkey );
1261 NtClose( root );
1263 /* a couple of directories that we don't want to return in directory searches */
1264 ignore_file( wine_get_config_dir() );
1265 ignore_file( "/dev" );
1266 ignore_file( "/proc" );
1267 #ifdef linux
1268 ignore_file( "/sys" );
1269 #endif
1270 return TRUE;
1274 /***********************************************************************
1275 * DIR_is_hidden_file
1277 * Check if the specified file should be hidden based on its name and the show dot files option.
1279 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1281 WCHAR *p, *end;
1283 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1285 if (show_dot_files) return FALSE;
1287 end = p = name->Buffer + name->Length/sizeof(WCHAR);
1288 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1289 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1290 if (p == end || *p != '.') return FALSE;
1291 /* make sure it isn't '.' or '..' */
1292 if (p + 1 == end) return FALSE;
1293 if (p[1] == '.' && p + 2 == end) return FALSE;
1294 return TRUE;
1298 /***********************************************************************
1299 * hash_short_file_name
1301 * Transform a Unix file name into a hashed DOS name. If the name is not a valid
1302 * DOS name, it is replaced by a hashed version that fits in 8.3 format.
1303 * 'buffer' must be at least 12 characters long.
1304 * Returns length of short name in bytes; short name is NOT null-terminated.
1306 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1308 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1310 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1311 LPWSTR dst;
1312 unsigned short hash;
1313 int i;
1315 /* Compute the hash code of the file name */
1316 /* If you know something about hash functions, feel free to */
1317 /* insert a better algorithm here... */
1318 if (!is_case_sensitive)
1320 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1321 hash = (hash<<3) ^ (hash>>5) ^ RtlDowncaseUnicodeChar(*p) ^ (RtlDowncaseUnicodeChar(p[1]) << 8);
1322 hash = (hash<<3) ^ (hash>>5) ^ RtlDowncaseUnicodeChar(*p); /* Last character */
1324 else
1326 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1327 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1328 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
1331 /* Find last dot for start of the extension */
1332 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1334 /* Copy first 4 chars, replacing invalid chars with '_' */
1335 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1337 if (p == end || p == ext) break;
1338 *dst++ = is_invalid_dos_char(*p) ? '_' : *p;
1340 /* Pad to 5 chars with '~' */
1341 while (i-- >= 0) *dst++ = '~';
1343 /* Insert hash code converted to 3 ASCII chars */
1344 *dst++ = hash_chars[(hash >> 10) & 0x1f];
1345 *dst++ = hash_chars[(hash >> 5) & 0x1f];
1346 *dst++ = hash_chars[hash & 0x1f];
1348 /* Copy the first 3 chars of the extension (if any) */
1349 if (ext)
1351 *dst++ = '.';
1352 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1353 *dst++ = is_invalid_dos_char(*ext) ? '_' : *ext;
1355 return dst - buffer;
1359 /***********************************************************************
1360 * match_filename
1362 * Check a long file name against a mask.
1364 * Tests (done in W95 DOS shell - case insensitive):
1365 * *.txt test1.test.txt *
1366 * *st1* test1.txt *
1367 * *.t??????.t* test1.ta.tornado.txt *
1368 * *tornado* test1.ta.tornado.txt *
1369 * t*t test1.ta.tornado.txt *
1370 * ?est* test1.txt *
1371 * ?est??? test1.txt -
1372 * *test1.txt* test1.txt *
1373 * h?l?o*t.dat hellothisisatest.dat *
1375 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1377 BOOL mismatch;
1378 const WCHAR *name = name_str->Buffer;
1379 const WCHAR *mask = mask_str->Buffer;
1380 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1381 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1382 const WCHAR *lastjoker = NULL;
1383 const WCHAR *next_to_retry = NULL;
1385 while (name < name_end && mask < mask_end)
1387 switch(*mask)
1389 case '*':
1390 mask++;
1391 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
1392 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1393 lastjoker = mask;
1395 /* skip to the next match after the joker(s) */
1396 if (is_case_sensitive)
1397 while (name < name_end && (*name != *mask)) name++;
1398 else
1399 while (name < name_end && (towupper(*name) != towupper(*mask))) name++;
1400 next_to_retry = name;
1401 break;
1402 case '?':
1403 mask++;
1404 name++;
1405 break;
1406 default:
1407 if (is_case_sensitive) mismatch = (*mask != *name);
1408 else mismatch = (towupper(*mask) != towupper(*name));
1410 if (!mismatch)
1412 mask++;
1413 name++;
1414 if (mask == mask_end)
1416 if (name == name_end) return TRUE;
1417 if (lastjoker) mask = lastjoker;
1420 else /* mismatch ! */
1422 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1424 mask = lastjoker;
1426 /* this scan sequence was a mismatch, so restart
1427 * 1 char after the first char we checked last time */
1428 next_to_retry++;
1429 name = next_to_retry;
1431 else return FALSE; /* bad luck */
1433 break;
1436 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1437 mask++; /* Ignore trailing '.' or '*' in mask */
1438 return (name == name_end && mask == mask_end);
1442 /***********************************************************************
1443 * append_entry
1445 * Add a file to the directory data if it matches the mask.
1447 static BOOL append_entry( struct dir_data *data, const char *long_name,
1448 const char *short_name, const UNICODE_STRING *mask )
1450 int long_len, short_len;
1451 WCHAR long_nameW[MAX_DIR_ENTRY_LEN + 1];
1452 WCHAR short_nameW[13];
1453 UNICODE_STRING str;
1455 long_len = ntdll_umbstowcs( long_name, strlen(long_name), long_nameW, ARRAY_SIZE(long_nameW) );
1456 if (long_len == ARRAY_SIZE(long_nameW)) return TRUE;
1457 long_nameW[long_len] = 0;
1459 str.Buffer = long_nameW;
1460 str.Length = long_len * sizeof(WCHAR);
1461 str.MaximumLength = sizeof(long_nameW);
1463 if (short_name)
1465 short_len = ntdll_umbstowcs( short_name, strlen(short_name),
1466 short_nameW, ARRAY_SIZE( short_nameW ) - 1 );
1468 else /* generate a short name if necessary */
1470 BOOLEAN spaces;
1472 short_len = 0;
1473 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1474 short_len = hash_short_file_name( &str, short_nameW );
1476 short_nameW[short_len] = 0;
1477 wcsupr( short_nameW );
1479 TRACE( "long %s short %s mask %s\n",
1480 debugstr_w( long_nameW ), debugstr_w( short_nameW ), debugstr_us( mask ));
1482 if (mask && !match_filename( &str, mask ))
1484 if (!short_len) return TRUE; /* no short name to match */
1485 str.Buffer = short_nameW;
1486 str.Length = short_len * sizeof(WCHAR);
1487 str.MaximumLength = sizeof(short_nameW);
1488 if (!match_filename( &str, mask )) return TRUE;
1491 return add_dir_data_names( data, long_nameW, short_nameW, long_name );
1495 /***********************************************************************
1496 * get_dir_data_entry
1498 * Return a directory entry from the cached data.
1500 static NTSTATUS get_dir_data_entry( struct dir_data *dir_data, void *info_ptr, IO_STATUS_BLOCK *io,
1501 ULONG max_length, FILE_INFORMATION_CLASS class,
1502 union file_directory_info **last_info )
1504 const struct dir_data_names *names = &dir_data->names[dir_data->pos];
1505 union file_directory_info *info;
1506 struct stat st;
1507 ULONG name_len, start, dir_size, attributes;
1509 if (get_file_info( names->unix_name, &st, &attributes ) == -1)
1511 TRACE( "file no longer exists %s\n", names->unix_name );
1512 return STATUS_SUCCESS;
1514 if (is_ignored_file( &st ))
1516 TRACE( "ignoring file %s\n", names->unix_name );
1517 return STATUS_SUCCESS;
1519 start = dir_info_align( io->Information );
1520 dir_size = dir_info_size( class, 0 );
1521 if (start + dir_size > max_length) return STATUS_MORE_ENTRIES;
1523 max_length -= start + dir_size;
1524 name_len = wcslen( names->long_name ) * sizeof(WCHAR);
1525 /* if this is not the first entry, fail; the first entry is always returned (but truncated) */
1526 if (*last_info && name_len > max_length) return STATUS_MORE_ENTRIES;
1528 info = (union file_directory_info *)((char *)info_ptr + start);
1529 info->dir.NextEntryOffset = 0;
1530 info->dir.FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1532 /* all the structures except FileNamesInformation start with a FileDirectoryInformation layout */
1533 if (class != FileNamesInformation)
1535 if (st.st_dev != dir_data->id.dev) st.st_ino = 0; /* ignore inode if on a different device */
1537 if (!show_dot_files && names->long_name[0] == '.' && names->long_name[1] &&
1538 (names->long_name[1] != '.' || names->long_name[2]))
1539 attributes |= FILE_ATTRIBUTE_HIDDEN;
1541 fill_file_info( &st, attributes, info, class );
1544 switch (class)
1546 case FileDirectoryInformation:
1547 info->dir.FileNameLength = name_len;
1548 break;
1550 case FileFullDirectoryInformation:
1551 info->full.EaSize = 0; /* FIXME */
1552 info->full.FileNameLength = name_len;
1553 break;
1555 case FileIdFullDirectoryInformation:
1556 info->id_full.EaSize = 0; /* FIXME */
1557 info->id_full.FileNameLength = name_len;
1558 break;
1560 case FileBothDirectoryInformation:
1561 info->both.EaSize = 0; /* FIXME */
1562 info->both.ShortNameLength = wcslen( names->short_name ) * sizeof(WCHAR);
1563 memcpy( info->both.ShortName, names->short_name, info->both.ShortNameLength );
1564 info->both.FileNameLength = name_len;
1565 break;
1567 case FileIdBothDirectoryInformation:
1568 info->id_both.EaSize = 0; /* FIXME */
1569 info->id_both.ShortNameLength = wcslen( names->short_name ) * sizeof(WCHAR);
1570 memcpy( info->id_both.ShortName, names->short_name, info->id_both.ShortNameLength );
1571 info->id_both.FileNameLength = name_len;
1572 break;
1574 case FileIdGlobalTxDirectoryInformation:
1575 info->id_tx.TxInfoFlags = 0;
1576 info->id_tx.FileNameLength = name_len;
1577 break;
1579 case FileNamesInformation:
1580 info->names.FileNameLength = name_len;
1581 break;
1583 default:
1584 assert(0);
1585 return 0;
1588 memcpy( (char *)info + dir_size, names->long_name, min( name_len, max_length ) );
1589 io->Information = start + dir_size + min( name_len, max_length );
1590 if (*last_info) (*last_info)->next = (char *)info - (char *)*last_info;
1591 *last_info = info;
1592 return name_len > max_length ? STATUS_BUFFER_OVERFLOW : STATUS_SUCCESS;
1595 #ifdef VFAT_IOCTL_READDIR_BOTH
1597 /***********************************************************************
1598 * start_vfat_ioctl
1600 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1601 * dir_section must be held by caller.
1603 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1605 static KERNEL_DIRENT *de;
1606 int res;
1608 if (!de)
1610 SIZE_T size = 2 * sizeof(*de) + page_size;
1611 void *addr = NULL;
1613 if (virtual_alloc_aligned( &addr, 0, &size, MEM_RESERVE, PAGE_READWRITE, 1 ))
1614 return NULL;
1615 /* commit only the size needed for the dir entries */
1616 /* this leaves an extra unaccessible page, which should make the kernel */
1617 /* fail with -EFAULT before it stomps all over our memory */
1618 de = addr;
1619 size = 2 * sizeof(*de);
1620 virtual_alloc_aligned( &addr, 0, &size, MEM_COMMIT, PAGE_READWRITE, 1 );
1623 /* set d_reclen to 65535 to work around an AFS kernel bug */
1624 de[0].d_reclen = 65535;
1625 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1626 if (res == -1)
1628 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1629 de[0].d_reclen = 0; /* eof */
1631 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1633 return de;
1637 /***********************************************************************
1638 * read_directory_vfat
1640 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1642 static NTSTATUS read_directory_data_vfat( struct dir_data *data, int fd, const UNICODE_STRING *mask )
1644 char *short_name, *long_name;
1645 size_t len;
1646 KERNEL_DIRENT *de;
1647 NTSTATUS status = STATUS_NO_MEMORY;
1648 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1650 if (!(de = start_vfat_ioctl( fd ))) return STATUS_NOT_SUPPORTED;
1652 lseek( fd, 0, SEEK_SET );
1654 if (!append_entry( data, ".", NULL, mask )) goto done;
1655 if (!append_entry( data, "..", NULL, mask )) goto done;
1657 while (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
1659 if (!de[0].d_reclen) break; /* eof */
1661 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1662 len = min( de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1663 de[0].d_name[len] = 0;
1664 len = min( de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1665 de[1].d_name[len] = 0;
1667 if (!strcmp( de[0].d_name, "." ) || !strcmp( de[0].d_name, ".." )) continue;
1668 if (de[1].d_name[0])
1670 short_name = de[0].d_name;
1671 long_name = de[1].d_name;
1673 else
1675 long_name = de[0].d_name;
1676 short_name = NULL;
1678 if (!append_entry( data, long_name, short_name, mask )) goto done;
1680 status = STATUS_SUCCESS;
1681 done:
1682 lseek( fd, old_pos, SEEK_SET );
1683 return status;
1685 #endif /* VFAT_IOCTL_READDIR_BOTH */
1688 #ifdef HAVE_GETATTRLIST
1689 /***********************************************************************
1690 * read_directory_getattrlist
1692 * Read a single file from a directory by determining whether the file
1693 * identified by mask exists using getattrlist.
1695 static NTSTATUS read_directory_data_getattrlist( struct dir_data *data, const char *unix_name )
1697 struct attrlist attrlist;
1698 #include "pshpack4.h"
1699 struct
1701 u_int32_t length;
1702 struct attrreference name_reference;
1703 fsobj_type_t type;
1704 char name[NAME_MAX * 3 + 1];
1705 } buffer;
1706 #include "poppack.h"
1708 memset( &attrlist, 0, sizeof(attrlist) );
1709 attrlist.bitmapcount = ATTR_BIT_MAP_COUNT;
1710 attrlist.commonattr = ATTR_CMN_NAME | ATTR_CMN_OBJTYPE;
1711 if (getattrlist( unix_name, &attrlist, &buffer, sizeof(buffer), FSOPT_NOFOLLOW ) == -1)
1712 return STATUS_NO_SUCH_FILE;
1713 /* If unix_name named a symlink, the above may have succeeded even if the symlink is broken.
1714 Check that with another call without FSOPT_NOFOLLOW. We don't ask for any attributes. */
1715 if (buffer.type == VLNK)
1717 u_int32_t dummy;
1718 attrlist.commonattr = 0;
1719 if (getattrlist( unix_name, &attrlist, &dummy, sizeof(dummy), 0 ) == -1)
1720 return STATUS_NO_SUCH_FILE;
1723 TRACE( "found %s\n", buffer.name );
1725 if (!append_entry( data, buffer.name, NULL, NULL )) return STATUS_NO_MEMORY;
1727 return STATUS_SUCCESS;
1729 #endif /* HAVE_GETATTRLIST */
1732 /***********************************************************************
1733 * read_directory_stat
1735 * Read a single file from a directory by determining whether the file
1736 * identified by mask exists using stat.
1738 static NTSTATUS read_directory_data_stat( struct dir_data *data, const char *unix_name )
1740 struct stat st;
1742 /* if the file system is not case sensitive we can't find the actual name through stat() */
1743 if (!get_dir_case_sensitivity(".")) return STATUS_NO_SUCH_FILE;
1744 if (stat( unix_name, &st ) == -1) return STATUS_NO_SUCH_FILE;
1746 TRACE( "found %s\n", unix_name );
1748 if (!append_entry( data, unix_name, NULL, NULL )) return STATUS_NO_MEMORY;
1750 return STATUS_SUCCESS;
1754 /***********************************************************************
1755 * read_directory_readdir
1757 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1759 static NTSTATUS read_directory_data_readdir( struct dir_data *data, const UNICODE_STRING *mask )
1761 struct dirent *de;
1762 NTSTATUS status = STATUS_NO_MEMORY;
1763 DIR *dir = opendir( "." );
1765 if (!dir) return STATUS_NO_SUCH_FILE;
1767 if (!append_entry( data, ".", NULL, mask )) goto done;
1768 if (!append_entry( data, "..", NULL, mask )) goto done;
1769 while ((de = readdir( dir )))
1771 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
1772 if (!append_entry( data, de->d_name, NULL, mask )) goto done;
1774 status = STATUS_SUCCESS;
1776 done:
1777 closedir( dir );
1778 return status;
1782 /***********************************************************************
1783 * read_directory_data
1785 * Read the full contents of a directory, using one of the above helper functions.
1787 static NTSTATUS read_directory_data( struct dir_data *data, int fd, const UNICODE_STRING *mask )
1789 NTSTATUS status;
1791 #ifdef VFAT_IOCTL_READDIR_BOTH
1792 if (!(status = read_directory_data_vfat( data, fd, mask ))) return status;
1793 #endif
1795 if (!has_wildcard( mask ))
1797 /* convert the mask to a Unix name and check for it */
1798 char unix_name[MAX_DIR_ENTRY_LEN * 3 + 1];
1799 int ret = ntdll_wcstoumbs( mask->Buffer, mask->Length / sizeof(WCHAR),
1800 unix_name, sizeof(unix_name) - 1, TRUE );
1801 if (ret > 0)
1803 unix_name[ret] = 0;
1804 #ifdef HAVE_GETATTRLIST
1805 if (!(status = read_directory_data_getattrlist( data, unix_name ))) return status;
1806 #endif
1807 if (!(status = read_directory_data_stat( data, unix_name ))) return status;
1811 return read_directory_data_readdir( data, mask );
1815 /* compare file names for directory sorting */
1816 static int name_compare( const void *a, const void *b )
1818 const struct dir_data_names *file_a = (const struct dir_data_names *)a;
1819 const struct dir_data_names *file_b = (const struct dir_data_names *)b;
1820 int ret = RtlCompareUnicodeStrings( file_a->long_name, wcslen(file_a->long_name),
1821 file_b->long_name, wcslen(file_b->long_name), TRUE );
1822 if (!ret) ret = wcscmp( file_a->long_name, file_b->long_name );
1823 return ret;
1827 /***********************************************************************
1828 * init_cached_dir_data
1830 * Initialize the cached directory contents.
1832 static NTSTATUS init_cached_dir_data( struct dir_data **data_ret, int fd, const UNICODE_STRING *mask )
1834 struct dir_data *data;
1835 struct stat st;
1836 NTSTATUS status;
1837 unsigned int i;
1839 if (!(data = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) )))
1840 return STATUS_NO_MEMORY;
1842 if ((status = read_directory_data( data, fd, mask )))
1844 free_dir_data( data );
1845 return status;
1848 /* sort filenames, but not "." and ".." */
1849 i = 0;
1850 if (i < data->count && !strcmp( data->names[i].unix_name, "." )) i++;
1851 if (i < data->count && !strcmp( data->names[i].unix_name, ".." )) i++;
1852 if (i < data->count) qsort( data->names + i, data->count - i, sizeof(*data->names), name_compare );
1854 if (data->count)
1856 /* release unused space */
1857 if (data->buffer)
1858 RtlReAllocateHeap( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, data->buffer,
1859 offsetof( struct dir_data_buffer, data[data->buffer->pos] ));
1860 if (data->count < data->size)
1861 RtlReAllocateHeap( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, data->names,
1862 data->count * sizeof(*data->names) );
1863 if (!fstat( fd, &st ))
1865 data->id.dev = st.st_dev;
1866 data->id.ino = st.st_ino;
1870 TRACE( "mask %s found %u files\n", debugstr_us( mask ), data->count );
1871 for (i = 0; i < data->count; i++)
1872 TRACE( "%s %s\n", debugstr_w(data->names[i].long_name), debugstr_w(data->names[i].short_name) );
1874 *data_ret = data;
1875 return data->count ? STATUS_SUCCESS : STATUS_NO_SUCH_FILE;
1879 /***********************************************************************
1880 * get_cached_dir_data
1882 * Retrieve the cached directory data, or initialize it if necessary.
1884 static NTSTATUS get_cached_dir_data( HANDLE handle, struct dir_data **data_ret, int fd,
1885 const UNICODE_STRING *mask )
1887 unsigned int i;
1888 int entry = -1, free_entries[16];
1889 NTSTATUS status;
1891 SERVER_START_REQ( get_directory_cache_entry )
1893 req->handle = wine_server_obj_handle( handle );
1894 wine_server_set_reply( req, free_entries, sizeof(free_entries) );
1895 if (!(status = wine_server_call( req ))) entry = reply->entry;
1897 for (i = 0; i < wine_server_reply_size( reply ) / sizeof(*free_entries); i++)
1899 int free_idx = free_entries[i];
1900 if (free_idx < dir_data_cache_size)
1902 free_dir_data( dir_data_cache[free_idx] );
1903 dir_data_cache[free_idx] = NULL;
1907 SERVER_END_REQ;
1909 if (status)
1911 if (status == STATUS_SHARING_VIOLATION) FIXME( "shared directory handle not supported yet\n" );
1912 return status;
1915 if (entry >= dir_data_cache_size)
1917 unsigned int size = max( dir_data_cache_initial_size, max( dir_data_cache_size * 2, entry + 1 ) );
1918 struct dir_data **new_cache;
1920 if (dir_data_cache)
1921 new_cache = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, dir_data_cache,
1922 size * sizeof(*new_cache) );
1923 else
1924 new_cache = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, size * sizeof(*new_cache) );
1925 if (!new_cache) return STATUS_NO_MEMORY;
1926 dir_data_cache = new_cache;
1927 dir_data_cache_size = size;
1930 if (!dir_data_cache[entry]) status = init_cached_dir_data( &dir_data_cache[entry], fd, mask );
1932 *data_ret = dir_data_cache[entry];
1933 return status;
1937 /******************************************************************************
1938 * NtQueryDirectoryFile [NTDLL.@]
1939 * ZwQueryDirectoryFile [NTDLL.@]
1941 NTSTATUS WINAPI DECLSPEC_HOTPATCH NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1942 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1943 PIO_STATUS_BLOCK io,
1944 PVOID buffer, ULONG length,
1945 FILE_INFORMATION_CLASS info_class,
1946 BOOLEAN single_entry,
1947 PUNICODE_STRING mask,
1948 BOOLEAN restart_scan )
1950 int cwd, fd, needs_close;
1951 struct dir_data *data;
1952 NTSTATUS status;
1954 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1955 handle, event, apc_routine, apc_context, io, buffer,
1956 length, info_class, single_entry, debugstr_us(mask),
1957 restart_scan);
1959 if (event || apc_routine)
1961 FIXME( "Unsupported yet option\n" );
1962 return STATUS_NOT_IMPLEMENTED;
1964 switch (info_class)
1966 case FileDirectoryInformation:
1967 case FileBothDirectoryInformation:
1968 case FileFullDirectoryInformation:
1969 case FileIdBothDirectoryInformation:
1970 case FileIdFullDirectoryInformation:
1971 case FileIdGlobalTxDirectoryInformation:
1972 case FileNamesInformation:
1973 if (length < dir_info_align( dir_info_size( info_class, 1 ))) return STATUS_INFO_LENGTH_MISMATCH;
1974 break;
1975 case FileObjectIdInformation:
1976 if (length != sizeof(FILE_OBJECTID_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1977 return STATUS_INVALID_INFO_CLASS;
1978 case FileQuotaInformation:
1979 if (length != sizeof(FILE_QUOTA_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1980 return STATUS_INVALID_INFO_CLASS;
1981 case FileReparsePointInformation:
1982 if (length != sizeof(FILE_REPARSE_POINT_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1983 return STATUS_INVALID_INFO_CLASS;
1984 default:
1985 return STATUS_INVALID_INFO_CLASS;
1987 if (!buffer) return STATUS_ACCESS_VIOLATION;
1989 if ((status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1990 return status;
1992 io->Information = 0;
1994 RtlRunOnceExecuteOnce( &init_once, init_options, NULL, NULL );
1996 RtlEnterCriticalSection( &dir_section );
1998 cwd = open( ".", O_RDONLY );
1999 if (fchdir( fd ) != -1)
2001 if (!(status = get_cached_dir_data( handle, &data, fd, mask )))
2003 union file_directory_info *last_info = NULL;
2005 if (restart_scan) data->pos = 0;
2007 while (!status && data->pos < data->count)
2009 status = get_dir_data_entry( data, buffer, io, length, info_class, &last_info );
2010 if (!status || status == STATUS_BUFFER_OVERFLOW) data->pos++;
2011 if (single_entry) break;
2014 if (!last_info) status = STATUS_NO_MORE_FILES;
2015 else if (status == STATUS_MORE_ENTRIES) status = STATUS_SUCCESS;
2017 io->u.Status = status;
2019 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2021 else status = FILE_GetNtStatus();
2023 RtlLeaveCriticalSection( &dir_section );
2025 if (needs_close) close( fd );
2026 if (cwd != -1) close( cwd );
2027 TRACE( "=> %x (%ld)\n", status, io->Information );
2028 return status;
2032 /***********************************************************************
2033 * find_file_in_dir
2035 * Find a file in a directory the hard way, by doing a case-insensitive search.
2036 * The file found is appended to unix_name at pos.
2037 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2039 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2040 BOOLEAN check_case, BOOLEAN *is_win_dir )
2042 WCHAR buffer[MAX_DIR_ENTRY_LEN];
2043 UNICODE_STRING str;
2044 BOOLEAN spaces, is_name_8_dot_3;
2045 DIR *dir;
2046 struct dirent *de;
2047 struct stat st;
2048 int ret;
2050 /* try a shortcut for this directory */
2052 unix_name[pos++] = '/';
2053 ret = ntdll_wcstoumbs( name, length, unix_name + pos, MAX_DIR_ENTRY_LEN + 1, TRUE );
2054 if (ret >= 0 && ret <= MAX_DIR_ENTRY_LEN)
2056 unix_name[pos + ret] = 0;
2057 if (!stat( unix_name, &st ))
2059 if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2060 return STATUS_SUCCESS;
2063 if (check_case) goto not_found; /* we want an exact match */
2065 if (pos > 1) unix_name[pos - 1] = 0;
2066 else unix_name[1] = 0; /* keep the initial slash */
2068 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2070 str.Buffer = (WCHAR *)name;
2071 str.Length = length * sizeof(WCHAR);
2072 str.MaximumLength = str.Length;
2073 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2074 #ifndef VFAT_IOCTL_READDIR_BOTH
2075 is_name_8_dot_3 = is_name_8_dot_3 && length >= 8 && name[4] == '~';
2076 #endif
2078 if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2080 /* now look for it through the directory */
2082 #ifdef VFAT_IOCTL_READDIR_BOTH
2083 if (is_name_8_dot_3)
2085 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2086 if (fd != -1)
2088 KERNEL_DIRENT *kde;
2090 RtlEnterCriticalSection( &dir_section );
2091 if ((kde = start_vfat_ioctl( fd )))
2093 unix_name[pos - 1] = '/';
2094 while (kde[0].d_reclen)
2096 /* make sure names are null-terminated to work around an x86-64 kernel bug */
2097 size_t len = min(kde[0].d_reclen, sizeof(kde[0].d_name) - 1 );
2098 kde[0].d_name[len] = 0;
2099 len = min(kde[1].d_reclen, sizeof(kde[1].d_name) - 1 );
2100 kde[1].d_name[len] = 0;
2102 if (kde[1].d_name[0])
2104 ret = ntdll_umbstowcs( kde[1].d_name, strlen(kde[1].d_name),
2105 buffer, MAX_DIR_ENTRY_LEN );
2106 if (ret == length && !RtlCompareUnicodeStrings( buffer, ret, name, ret, TRUE ))
2108 strcpy( unix_name + pos, kde[1].d_name );
2109 RtlLeaveCriticalSection( &dir_section );
2110 close( fd );
2111 goto success;
2114 ret = ntdll_umbstowcs( kde[0].d_name, strlen(kde[0].d_name),
2115 buffer, MAX_DIR_ENTRY_LEN );
2116 if (ret == length && !RtlCompareUnicodeStrings( buffer, ret, name, ret, TRUE ))
2118 strcpy( unix_name + pos,
2119 kde[1].d_name[0] ? kde[1].d_name : kde[0].d_name );
2120 RtlLeaveCriticalSection( &dir_section );
2121 close( fd );
2122 goto success;
2124 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)kde ) == -1)
2126 RtlLeaveCriticalSection( &dir_section );
2127 close( fd );
2128 goto not_found;
2132 RtlLeaveCriticalSection( &dir_section );
2133 close( fd );
2135 /* fall through to normal handling */
2137 #endif /* VFAT_IOCTL_READDIR_BOTH */
2139 if (!(dir = opendir( unix_name )))
2141 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2142 else return FILE_GetNtStatus();
2144 unix_name[pos - 1] = '/';
2145 str.Buffer = buffer;
2146 str.MaximumLength = sizeof(buffer);
2147 while ((de = readdir( dir )))
2149 ret = ntdll_umbstowcs( de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2150 if (ret == length && !RtlCompareUnicodeStrings( buffer, ret, name, ret, TRUE ))
2152 strcpy( unix_name + pos, de->d_name );
2153 closedir( dir );
2154 goto success;
2157 if (!is_name_8_dot_3) continue;
2159 str.Length = ret * sizeof(WCHAR);
2160 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2162 WCHAR short_nameW[12];
2163 ret = hash_short_file_name( &str, short_nameW );
2164 if (ret == length && !wcsnicmp( short_nameW, name, length ))
2166 strcpy( unix_name + pos, de->d_name );
2167 closedir( dir );
2168 goto success;
2172 closedir( dir );
2174 not_found:
2175 unix_name[pos - 1] = 0;
2176 return STATUS_OBJECT_PATH_NOT_FOUND;
2178 success:
2179 if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2180 return STATUS_SUCCESS;
2184 #ifndef _WIN64
2186 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2187 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2188 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};
2189 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2190 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2191 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2192 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2193 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2194 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2196 static struct
2198 const WCHAR *source;
2199 const char *unix_target;
2200 } redirects[] =
2202 { catrootW, NULL },
2203 { catroot2W, NULL },
2204 { driversstoreW, NULL },
2205 { driversetcW, NULL },
2206 { logfilesW, NULL },
2207 { spoolW, NULL },
2208 { system32W, "syswow64" },
2209 { sysnativeW, "system32" },
2210 { regeditW, "syswow64/regedit.exe" }
2213 static unsigned int nb_redirects;
2216 /***********************************************************************
2217 * init_redirects
2219 static void init_redirects(void)
2221 static const char windows_dir[] = "/dosdevices/c:/windows";
2222 const char *config_dir = wine_get_config_dir();
2223 char *dir;
2224 struct stat st;
2226 if (!(dir = RtlAllocateHeap( GetProcessHeap(), 0, strlen(config_dir) + sizeof(windows_dir) ))) return;
2227 strcpy( dir, config_dir );
2228 strcat( dir, windows_dir );
2229 if (!stat( dir, &st ))
2231 windir.dev = st.st_dev;
2232 windir.ino = st.st_ino;
2233 nb_redirects = ARRAY_SIZE( redirects );
2235 else ERR( "%s: %s\n", dir, strerror(errno) );
2236 RtlFreeHeap( GetProcessHeap(), 0, dir );
2241 /***********************************************************************
2242 * match_redirect
2244 * Check if path matches a redirect name. If yes, return matched length.
2246 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, BOOLEAN check_case )
2248 int i = 0;
2250 while (i < len)
2252 int start = i;
2253 while (i < len && !IS_SEPARATOR(path[i])) i++;
2254 if (check_case)
2256 if (wcsncmp( path + start, redir, i - start )) return 0;
2258 else
2260 if (wcsnicmp( path + start, redir, i - start )) return 0;
2262 redir += i - start;
2263 while (i < len && IS_SEPARATOR(path[i])) i++;
2264 if (!*redir) return i;
2265 if (*redir++ != '\\') return 0;
2267 return 0;
2271 /***********************************************************************
2272 * get_redirect_path
2274 * Retrieve the Unix path corresponding to a redirected path if any.
2276 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2278 unsigned int i;
2279 int len;
2281 for (i = 0; i < nb_redirects; i++)
2283 if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2285 if (!redirects[i].unix_target) break;
2286 unix_name[pos++] = '/';
2287 strcpy( unix_name + pos, redirects[i].unix_target );
2288 return len;
2291 return 0;
2294 #else /* _WIN64 */
2296 /* there are no redirects on 64-bit */
2298 static const unsigned int nb_redirects = 0;
2300 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, BOOLEAN check_case )
2302 return 0;
2305 #endif
2307 /***********************************************************************
2308 * init_directories
2310 void init_directories(void)
2312 #ifndef _WIN64
2313 if (is_wow64) init_redirects();
2314 #endif
2318 /******************************************************************************
2319 * get_dos_device
2321 * Get the Unix path of a DOS device.
2323 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2325 const char *config_dir = wine_get_config_dir();
2326 struct stat st;
2327 char *unix_name, *new_name, *dev;
2328 unsigned int i;
2329 int unix_len;
2331 /* make sure the device name is ASCII */
2332 for (i = 0; i < name_len; i++)
2333 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2335 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2337 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2338 return STATUS_NO_MEMORY;
2340 strcpy( unix_name, config_dir );
2341 strcat( unix_name, "/dosdevices/" );
2342 dev = unix_name + strlen(unix_name);
2344 for (i = 0; i < name_len; i++) dev[i] = (name[i] >= 'A' && name[i] <= 'Z' ? name[i] + 32 : name[i]);
2345 dev[i] = 0;
2347 /* special case for drive devices */
2348 if (name_len == 2 && dev[1] == ':')
2350 dev[i++] = ':';
2351 dev[i] = 0;
2354 for (;;)
2356 if (!stat( unix_name, &st ))
2358 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2359 unix_name_ret->Buffer = unix_name;
2360 unix_name_ret->Length = strlen(unix_name);
2361 unix_name_ret->MaximumLength = unix_len;
2362 return STATUS_SUCCESS;
2364 if (!dev) break;
2366 /* now try some defaults for it */
2367 if (!strcmp( dev, "aux" ))
2369 strcpy( dev, "com1" );
2370 continue;
2372 if (!strcmp( dev, "prn" ))
2374 strcpy( dev, "lpt1" );
2375 continue;
2378 new_name = NULL;
2379 if (dev[1] == ':' && dev[2] == ':') /* drive device */
2381 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
2382 new_name = get_default_drive_device( unix_name );
2385 if (!new_name) break;
2387 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2388 unix_name = new_name;
2389 unix_len = strlen(unix_name) + 1;
2390 dev = NULL; /* last try */
2392 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2393 return STATUS_BAD_DEVICE_TYPE;
2397 /* return the length of the DOS namespace prefix if any */
2398 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2400 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2401 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2403 if (name->Length >= sizeof(nt_prefixW) &&
2404 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2405 return ARRAY_SIZE( nt_prefixW );
2407 if (name->Length >= sizeof(dosdev_prefixW) &&
2408 !wcsnicmp( name->Buffer, dosdev_prefixW, ARRAY_SIZE( dosdev_prefixW )))
2409 return ARRAY_SIZE( dosdev_prefixW );
2411 return 0;
2415 /******************************************************************************
2416 * find_file_id
2418 * Recursively search directories from the dir queue for a given inode.
2420 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2422 unsigned int pos;
2423 DIR *dir;
2424 struct dirent *de;
2425 NTSTATUS status;
2426 struct stat st;
2428 while (!(status = next_dir_in_queue( unix_name->Buffer )))
2430 if (!(dir = opendir( unix_name->Buffer ))) continue;
2431 TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2432 pos = strlen( unix_name->Buffer );
2433 if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2435 char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2436 unix_name->MaximumLength * 2 );
2437 if (!new)
2439 closedir( dir );
2440 return STATUS_NO_MEMORY;
2442 unix_name->MaximumLength *= 2;
2443 unix_name->Buffer = new;
2445 unix_name->Buffer[pos++] = '/';
2446 while ((de = readdir( dir )))
2448 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2449 strcpy( unix_name->Buffer + pos, de->d_name );
2450 if (lstat( unix_name->Buffer, &st ) == -1) continue;
2451 if (st.st_dev != dev) continue;
2452 if (st.st_ino == file_id)
2454 closedir( dir );
2455 return STATUS_SUCCESS;
2457 if (!S_ISDIR( st.st_mode )) continue;
2458 if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2460 closedir( dir );
2461 return status;
2464 closedir( dir );
2466 return status;
2470 /******************************************************************************
2471 * file_id_to_unix_file_name
2473 * Lookup a file from its file id instead of its name.
2475 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2477 enum server_fd_type type;
2478 int old_cwd, root_fd, needs_close;
2479 NTSTATUS status;
2480 ULONGLONG file_id;
2481 struct stat st, root_st;
2483 if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2484 if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2485 memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2487 unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2488 if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2489 return STATUS_NO_MEMORY;
2490 strcpy( unix_name->Buffer, "." );
2492 if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2493 goto done;
2495 if (type != FD_TYPE_DIR)
2497 status = STATUS_OBJECT_TYPE_MISMATCH;
2498 goto done;
2501 fstat( root_fd, &root_st );
2502 if (root_st.st_ino == file_id) /* shortcut for "." */
2504 status = STATUS_SUCCESS;
2505 goto done;
2508 RtlEnterCriticalSection( &dir_section );
2509 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2511 /* shortcut for ".." */
2512 if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2514 strcpy( unix_name->Buffer, ".." );
2515 status = STATUS_SUCCESS;
2517 else
2519 status = add_dir_to_queue( "." );
2520 if (!status)
2521 status = find_file_id( unix_name, file_id, root_st.st_dev );
2522 if (!status) /* get rid of "./" prefix */
2523 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2524 flush_dir_queue();
2526 if (fchdir( old_cwd ) == -1) chdir( "/" );
2528 else status = FILE_GetNtStatus();
2529 RtlLeaveCriticalSection( &dir_section );
2530 if (old_cwd != -1) close( old_cwd );
2532 done:
2533 if (status == STATUS_SUCCESS)
2535 TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2536 unix_name->Length = strlen( unix_name->Buffer );
2538 else
2540 TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2541 RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2543 if (needs_close) close( root_fd );
2544 return status;
2548 /******************************************************************************
2549 * lookup_unix_name
2551 * Helper for nt_to_unix_file_name
2553 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2554 UINT disposition, BOOLEAN check_case )
2556 NTSTATUS status;
2557 int ret, len;
2558 struct stat st;
2559 char *unix_name = *buffer;
2560 const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2562 /* try a shortcut first */
2564 while (name_len && IS_SEPARATOR(*name))
2566 name++;
2567 name_len--;
2570 unix_name[pos] = '/';
2571 ret = ntdll_wcstoumbs( name, name_len, unix_name + pos + 1, unix_len - pos - 1, TRUE );
2572 if (ret >= 0 && ret < unix_len - pos - 1)
2574 char *p;
2575 unix_name[pos + 1 + ret] = 0;
2576 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2577 if (!name_len || !redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2579 if (!stat( unix_name, &st ))
2581 if (disposition == FILE_CREATE)
2582 return STATUS_OBJECT_NAME_COLLISION;
2583 return STATUS_SUCCESS;
2588 if (!name_len) /* empty name -> drive root doesn't exist */
2589 return STATUS_OBJECT_PATH_NOT_FOUND;
2590 if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2591 return STATUS_OBJECT_NAME_NOT_FOUND;
2593 /* now do it component by component */
2595 while (name_len)
2597 const WCHAR *end, *next;
2598 BOOLEAN is_win_dir = FALSE;
2600 end = name;
2601 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2602 next = end;
2603 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2604 name_len -= next - name;
2606 /* grow the buffer if needed */
2608 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2610 char *new_name;
2611 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2612 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2613 return STATUS_NO_MEMORY;
2614 unix_name = *buffer = new_name;
2617 status = find_file_in_dir( unix_name, pos, name, end - name,
2618 check_case, redirect ? &is_win_dir : NULL );
2620 /* if this is the last element, not finding it is not necessarily fatal */
2621 if (!name_len)
2623 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2625 status = STATUS_OBJECT_NAME_NOT_FOUND;
2626 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2628 ret = ntdll_wcstoumbs( name, end - name, unix_name + pos + 1, MAX_DIR_ENTRY_LEN + 1, TRUE );
2629 if (ret > 0 && ret <= MAX_DIR_ENTRY_LEN)
2631 unix_name[pos] = '/';
2632 unix_name[pos + 1 + ret] = 0;
2633 status = STATUS_NO_SUCH_FILE;
2634 break;
2638 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2640 status = STATUS_OBJECT_NAME_COLLISION;
2644 if (status != STATUS_SUCCESS) break;
2646 pos += strlen( unix_name + pos );
2647 name = next;
2649 if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2651 name += len;
2652 name_len -= len;
2653 pos += strlen( unix_name + pos );
2654 TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2658 return status;
2662 /******************************************************************************
2663 * nt_to_unix_file_name_attr
2665 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2666 UINT disposition )
2668 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2669 enum server_fd_type type;
2670 int old_cwd, root_fd, needs_close;
2671 const WCHAR *name, *p;
2672 char *unix_name;
2673 int name_len, unix_len;
2674 NTSTATUS status;
2675 BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2677 if (!attr->RootDirectory) /* without root dir fall back to normal lookup */
2678 return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2680 name = attr->ObjectName->Buffer;
2681 name_len = attr->ObjectName->Length / sizeof(WCHAR);
2683 if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2685 /* check for invalid characters */
2686 for (p = name; p < name + name_len; p++)
2687 if (*p < 32 || wcschr( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2689 unix_len = name_len * 3 + MAX_DIR_ENTRY_LEN + 3;
2690 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2691 return STATUS_NO_MEMORY;
2692 unix_name[0] = '.';
2694 if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2696 if (type != FD_TYPE_DIR)
2698 if (needs_close) close( root_fd );
2699 status = STATUS_BAD_DEVICE_TYPE;
2701 else
2703 RtlEnterCriticalSection( &dir_section );
2704 if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2706 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2707 disposition, check_case );
2708 if (fchdir( old_cwd ) == -1) chdir( "/" );
2710 else status = FILE_GetNtStatus();
2711 RtlLeaveCriticalSection( &dir_section );
2712 if (old_cwd != -1) close( old_cwd );
2713 if (needs_close) close( root_fd );
2716 else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2718 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2720 TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2721 unix_name_ret->Buffer = unix_name;
2722 unix_name_ret->Length = strlen(unix_name);
2723 unix_name_ret->MaximumLength = unix_len;
2725 else
2727 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2728 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2730 return status;
2734 /******************************************************************************
2735 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2737 * Convert a file name from NT namespace to Unix namespace.
2739 * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2740 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2741 * returned, but the unix name is still filled in properly.
2743 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2744 UINT disposition, BOOLEAN check_case )
2746 static const WCHAR unixW[] = {'u','n','i','x'};
2747 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2749 NTSTATUS status = STATUS_SUCCESS;
2750 const char *config_dir = wine_get_config_dir();
2751 const WCHAR *name, *p;
2752 struct stat st;
2753 char *unix_name;
2754 int pos, ret, name_len, unix_len, prefix_len;
2755 WCHAR prefix[MAX_DIR_ENTRY_LEN + 1];
2756 BOOLEAN is_unix = FALSE;
2758 name = nameW->Buffer;
2759 name_len = nameW->Length / sizeof(WCHAR);
2761 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2763 if (!(pos = get_dos_prefix_len( nameW )))
2764 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2766 name += pos;
2767 name_len -= pos;
2769 if (!name_len) return STATUS_OBJECT_NAME_INVALID;
2771 /* check for sub-directory */
2772 for (pos = 0; pos < name_len; pos++)
2774 if (IS_SEPARATOR(name[pos])) break;
2775 if (name[pos] < 32 || wcschr( invalid_charsW, name[pos] ))
2776 return STATUS_OBJECT_NAME_INVALID;
2778 if (pos > MAX_DIR_ENTRY_LEN)
2779 return STATUS_OBJECT_NAME_INVALID;
2781 if (pos == name_len) /* no subdir, plain DOS device */
2782 return get_dos_device( name, name_len, unix_name_ret );
2784 prefix_len = pos;
2785 memcpy( prefix, name, prefix_len * sizeof(WCHAR) );
2786 prefix[prefix_len] = 0;
2787 wcslwr( prefix );
2789 name += prefix_len;
2790 name_len -= prefix_len;
2792 /* check for invalid characters (all chars except 0 are valid for unix) */
2793 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2794 if (is_unix)
2796 for (p = name; p < name + name_len; p++)
2797 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2798 check_case = TRUE;
2800 else
2802 for (p = name; p < name + name_len; p++)
2803 if (*p < 32 || wcschr( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2806 unix_len = (prefix_len + name_len) * 3 + MAX_DIR_ENTRY_LEN + 3;
2807 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2808 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2809 return STATUS_NO_MEMORY;
2810 strcpy( unix_name, config_dir );
2811 strcat( unix_name, "/dosdevices/" );
2812 pos = strlen(unix_name);
2814 ret = ntdll_wcstoumbs( prefix, prefix_len, unix_name + pos, unix_len - pos - 1, TRUE );
2815 if (ret <= 0)
2817 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2818 return STATUS_OBJECT_NAME_INVALID;
2820 pos += ret;
2822 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2824 if (prefix_len != 2 || prefix[1] != ':')
2826 unix_name[pos] = 0;
2827 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2829 if (!is_unix)
2831 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2832 return STATUS_BAD_DEVICE_TYPE;
2834 pos = 0; /* fall back to unix root */
2838 status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2839 if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2841 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2842 unix_name_ret->Buffer = unix_name;
2843 unix_name_ret->Length = strlen(unix_name);
2844 unix_name_ret->MaximumLength = unix_len;
2846 else
2848 TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2849 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2851 return status;
2855 /******************************************************************
2856 * RtlWow64EnableFsRedirection (NTDLL.@)
2858 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2860 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2861 ntdll_get_thread_data()->wow64_redir = enable;
2862 return STATUS_SUCCESS;
2866 /******************************************************************
2867 * RtlWow64EnableFsRedirectionEx (NTDLL.@)
2869 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2871 if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2873 __TRY
2875 *old_value = !ntdll_get_thread_data()->wow64_redir;
2877 __EXCEPT_PAGE_FAULT
2879 return STATUS_ACCESS_VIOLATION;
2881 __ENDTRY
2883 ntdll_get_thread_data()->wow64_redir = !disable;
2884 return STATUS_SUCCESS;
2888 /******************************************************************
2889 * RtlDoesFileExists_U (NTDLL.@)
2891 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2893 UNICODE_STRING nt_name;
2894 FILE_BASIC_INFORMATION basic_info;
2895 OBJECT_ATTRIBUTES attr;
2896 BOOLEAN ret;
2898 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2900 attr.Length = sizeof(attr);
2901 attr.RootDirectory = 0;
2902 attr.ObjectName = &nt_name;
2903 attr.Attributes = OBJ_CASE_INSENSITIVE;
2904 attr.SecurityDescriptor = NULL;
2905 attr.SecurityQualityOfService = NULL;
2907 ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2909 RtlFreeUnicodeString( &nt_name );
2910 return ret;
2914 /***********************************************************************
2915 * DIR_unmount_device
2917 * Unmount the specified device.
2919 NTSTATUS DIR_unmount_device( HANDLE handle )
2921 NTSTATUS status;
2922 int unix_fd, needs_close;
2924 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2926 struct stat st;
2927 char *mount_point = NULL;
2929 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2930 status = STATUS_INVALID_PARAMETER;
2931 else
2933 if ((mount_point = get_device_mount_point( st.st_rdev )))
2935 #ifdef __APPLE__
2936 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2937 #else
2938 static const char umount[] = "umount >/dev/null 2>&1 ";
2939 #endif
2940 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2941 if (cmd)
2943 strcpy( cmd, umount );
2944 strcat( cmd, mount_point );
2945 system( cmd );
2946 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2947 #ifdef linux
2948 /* umount will fail to release the loop device since we still have
2949 a handle to it, so we release it here */
2950 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2951 #endif
2953 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2956 if (needs_close) close( unix_fd );
2958 return status;
2962 /******************************************************************************
2963 * DIR_get_unix_cwd
2965 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2966 * Returned value must be freed by caller.
2968 NTSTATUS DIR_get_unix_cwd( char **cwd )
2970 int old_cwd, unix_fd, needs_close;
2971 CURDIR *curdir;
2972 HANDLE handle;
2973 NTSTATUS status;
2975 RtlAcquirePebLock();
2977 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2978 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2979 else
2980 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2982 if (!(handle = curdir->Handle))
2984 UNICODE_STRING dirW;
2985 OBJECT_ATTRIBUTES attr;
2986 IO_STATUS_BLOCK io;
2988 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2990 status = STATUS_OBJECT_NAME_INVALID;
2991 goto done;
2993 attr.Length = sizeof(attr);
2994 attr.RootDirectory = 0;
2995 attr.Attributes = OBJ_CASE_INSENSITIVE;
2996 attr.ObjectName = &dirW;
2997 attr.SecurityDescriptor = NULL;
2998 attr.SecurityQualityOfService = NULL;
3000 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0,
3001 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3002 RtlFreeUnicodeString( &dirW );
3003 if (status != STATUS_SUCCESS) goto done;
3006 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3008 RtlEnterCriticalSection( &dir_section );
3010 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3012 unsigned int size = 512;
3014 for (;;)
3016 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3018 status = STATUS_NO_MEMORY;
3019 break;
3021 if (getcwd( *cwd, size )) break;
3022 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3023 if (errno != ERANGE)
3025 status = STATUS_OBJECT_PATH_INVALID;
3026 break;
3028 size *= 2;
3030 if (fchdir( old_cwd ) == -1) chdir( "/" );
3032 else status = FILE_GetNtStatus();
3034 RtlLeaveCriticalSection( &dir_section );
3035 if (old_cwd != -1) close( old_cwd );
3036 if (needs_close) close( unix_fd );
3038 if (!curdir->Handle) NtClose( handle );
3040 done:
3041 RtlReleasePebLock();
3042 return status;