kernel32: Don't skip directory symlinks when looking for a specific file.
[wine] / dlls / kernel32 / file.c
1 /*
2  * File handling functions
3  *
4  * Copyright 1993 John Burton
5  * Copyright 1996, 2004 Alexandre Julliard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
30 #endif
31
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34 #include "winerror.h"
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winternl.h"
40 #include "winioctl.h"
41 #include "wincon.h"
42 #include "wine/winbase16.h"
43 #include "kernel_private.h"
44
45 #include "wine/exception.h"
46 #include "excpt.h"
47 #include "wine/unicode.h"
48 #include "wine/debug.h"
49 #include "thread.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(file);
52
53 HANDLE dos_handles[DOS_TABLE_SIZE];
54
55 /* info structure for FindFirstFile handle */
56 typedef struct
57 {
58     DWORD             magic;       /* magic number */
59     HANDLE            handle;      /* handle to directory */
60     CRITICAL_SECTION  cs;          /* crit section protecting this structure */
61     FINDEX_SEARCH_OPS search_op;   /* Flags passed to FindFirst.  */
62     UNICODE_STRING    mask;        /* file mask */
63     UNICODE_STRING    path;        /* NT path used to open the directory */
64     BOOL              is_root;     /* is directory the root of the drive? */
65     UINT              data_pos;    /* current position in dir data */
66     UINT              data_len;    /* length of dir data */
67     BYTE              data[8192];  /* directory data */
68 } FIND_FIRST_INFO;
69
70 #define FIND_FIRST_MAGIC  0xc0ffee11
71
72 static BOOL oem_file_apis;
73
74 static const WCHAR wildcardsW[] = { '*','?',0 };
75
76 /***********************************************************************
77  *              create_file_OF
78  *
79  * Wrapper for CreateFile that takes OF_* mode flags.
80  */
81 static HANDLE create_file_OF( LPCSTR path, INT mode )
82 {
83     DWORD access, sharing, creation;
84
85     if (mode & OF_CREATE)
86     {
87         creation = CREATE_ALWAYS;
88         access = GENERIC_READ | GENERIC_WRITE;
89     }
90     else
91     {
92         creation = OPEN_EXISTING;
93         switch(mode & 0x03)
94         {
95         case OF_READ:      access = GENERIC_READ; break;
96         case OF_WRITE:     access = GENERIC_WRITE; break;
97         case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
98         default:           access = 0; break;
99         }
100     }
101
102     switch(mode & 0x70)
103     {
104     case OF_SHARE_EXCLUSIVE:  sharing = 0; break;
105     case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
106     case OF_SHARE_DENY_READ:  sharing = FILE_SHARE_WRITE; break;
107     case OF_SHARE_DENY_NONE:
108     case OF_SHARE_COMPAT:
109     default:                  sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
110     }
111     return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
112 }
113
114
115 /***********************************************************************
116  *              check_dir_symlink
117  *
118  * Check if a dir symlink should be returned by FindNextFile.
119  */
120 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
121 {
122     UNICODE_STRING str;
123     ANSI_STRING unix_name;
124     struct stat st, parent_st;
125     BOOL ret = TRUE;
126     DWORD len;
127
128     str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
129     if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
130     memcpy( str.Buffer, info->path.Buffer, info->path.Length );
131     len = info->path.Length / sizeof(WCHAR);
132     if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
133     memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
134     str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
135
136     unix_name.Buffer = NULL;
137     if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
138         !stat( unix_name.Buffer, &st ))
139     {
140         char *p = unix_name.Buffer + unix_name.Length - 1;
141
142         /* skip trailing slashes */
143         while (p > unix_name.Buffer && *p == '/') p--;
144
145         while (ret && p > unix_name.Buffer)
146         {
147             while (p > unix_name.Buffer && *p != '/') p--;
148             while (p > unix_name.Buffer && *p == '/') p--;
149             p[1] = 0;
150             if (!stat( unix_name.Buffer, &parent_st ) &&
151                 parent_st.st_dev == st.st_dev &&
152                 parent_st.st_ino == st.st_ino)
153             {
154                 WARN( "suppressing dir symlink %s pointing to parent %s\n",
155                       debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
156                       debugstr_a( unix_name.Buffer ));
157                 ret = FALSE;
158             }
159         }
160     }
161     RtlFreeAnsiString( &unix_name );
162     RtlFreeUnicodeString( &str );
163     return ret;
164 }
165
166
167 /***********************************************************************
168  *           FILE_SetDosError
169  *
170  * Set the DOS error code from errno.
171  */
172 void FILE_SetDosError(void)
173 {
174     int save_errno = errno; /* errno gets overwritten by printf */
175
176     TRACE("errno = %d %s\n", errno, strerror(errno));
177     switch (save_errno)
178     {
179     case EAGAIN:
180         SetLastError( ERROR_SHARING_VIOLATION );
181         break;
182     case EBADF:
183         SetLastError( ERROR_INVALID_HANDLE );
184         break;
185     case ENOSPC:
186         SetLastError( ERROR_HANDLE_DISK_FULL );
187         break;
188     case EACCES:
189     case EPERM:
190     case EROFS:
191         SetLastError( ERROR_ACCESS_DENIED );
192         break;
193     case EBUSY:
194         SetLastError( ERROR_LOCK_VIOLATION );
195         break;
196     case ENOENT:
197         SetLastError( ERROR_FILE_NOT_FOUND );
198         break;
199     case EISDIR:
200         SetLastError( ERROR_CANNOT_MAKE );
201         break;
202     case ENFILE:
203     case EMFILE:
204         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
205         break;
206     case EEXIST:
207         SetLastError( ERROR_FILE_EXISTS );
208         break;
209     case EINVAL:
210     case ESPIPE:
211         SetLastError( ERROR_SEEK );
212         break;
213     case ENOTEMPTY:
214         SetLastError( ERROR_DIR_NOT_EMPTY );
215         break;
216     case ENOEXEC:
217         SetLastError( ERROR_BAD_FORMAT );
218         break;
219     case ENOTDIR:
220         SetLastError( ERROR_PATH_NOT_FOUND );
221         break;
222     case EXDEV:
223         SetLastError( ERROR_NOT_SAME_DEVICE );
224         break;
225     default:
226         WARN("unknown file error: %s\n", strerror(save_errno) );
227         SetLastError( ERROR_GEN_FAILURE );
228         break;
229     }
230     errno = save_errno;
231 }
232
233
234 /***********************************************************************
235  *           FILE_name_AtoW
236  *
237  * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
238  *
239  * If alloc is FALSE uses the TEB static buffer, so it can only be used when
240  * there is no possibility for the function to do that twice, taking into
241  * account any called function.
242  */
243 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
244 {
245     ANSI_STRING str;
246     UNICODE_STRING strW, *pstrW;
247     NTSTATUS status;
248
249     RtlInitAnsiString( &str, name );
250     pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
251     if (oem_file_apis)
252         status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
253     else
254         status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
255     if (status == STATUS_SUCCESS) return pstrW->Buffer;
256
257     if (status == STATUS_BUFFER_OVERFLOW)
258         SetLastError( ERROR_FILENAME_EXCED_RANGE );
259     else
260         SetLastError( RtlNtStatusToDosError(status) );
261     return NULL;
262 }
263
264
265 /***********************************************************************
266  *           FILE_name_WtoA
267  *
268  * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
269  */
270 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
271 {
272     DWORD ret;
273
274     if (srclen < 0) srclen = strlenW( src ) + 1;
275     if (oem_file_apis)
276         RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
277     else
278         RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
279     return ret;
280 }
281
282
283 /**************************************************************************
284  *              SetFileApisToOEM   (KERNEL32.@)
285  */
286 VOID WINAPI SetFileApisToOEM(void)
287 {
288     oem_file_apis = TRUE;
289 }
290
291
292 /**************************************************************************
293  *              SetFileApisToANSI   (KERNEL32.@)
294  */
295 VOID WINAPI SetFileApisToANSI(void)
296 {
297     oem_file_apis = FALSE;
298 }
299
300
301 /******************************************************************************
302  *              AreFileApisANSI   (KERNEL32.@)
303  *
304  *  Determines if file functions are using ANSI
305  *
306  * RETURNS
307  *    TRUE:  Set of file functions is using ANSI code page
308  *    FALSE: Set of file functions is using OEM code page
309  */
310 BOOL WINAPI AreFileApisANSI(void)
311 {
312     return !oem_file_apis;
313 }
314
315
316 /**************************************************************************
317  *                      Operations on file handles                        *
318  **************************************************************************/
319
320 /***********************************************************************
321  *           FILE_InitProcessDosHandles
322  *
323  * Allocates the default DOS handles for a process. Called either by
324  * Win32HandleToDosFileHandle below or by the DOSVM stuff.
325  */
326 static void FILE_InitProcessDosHandles( void )
327 {
328     static BOOL init_done /* = FALSE */;
329     HANDLE cp = GetCurrentProcess();
330
331     if (init_done) return;
332     init_done = TRUE;
333     DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
334                     0, TRUE, DUPLICATE_SAME_ACCESS);
335     DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
336                     0, TRUE, DUPLICATE_SAME_ACCESS);
337     DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
338                     0, TRUE, DUPLICATE_SAME_ACCESS);
339     DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
340                     0, TRUE, DUPLICATE_SAME_ACCESS);
341     DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
342                     0, TRUE, DUPLICATE_SAME_ACCESS);
343 }
344
345
346 /******************************************************************
347  *              FILE_ReadWriteApc (internal)
348  */
349 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
350 {
351     LPOVERLAPPED_COMPLETION_ROUTINE  cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
352
353     cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
354 }
355
356
357 /***********************************************************************
358  *              ReadFileEx                (KERNEL32.@)
359  */
360 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
361                        LPOVERLAPPED overlapped,
362                        LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
363 {
364     LARGE_INTEGER       offset;
365     NTSTATUS            status;
366     PIO_STATUS_BLOCK    io_status;
367
368     TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
369
370     if (!overlapped)
371     {
372         SetLastError(ERROR_INVALID_PARAMETER);
373         return FALSE;
374     }
375
376     offset.u.LowPart = overlapped->u.s.Offset;
377     offset.u.HighPart = overlapped->u.s.OffsetHigh;
378     io_status = (PIO_STATUS_BLOCK)overlapped;
379     io_status->u.Status = STATUS_PENDING;
380
381     status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
382                         io_status, buffer, bytesToRead, &offset, NULL);
383
384     if (status)
385     {
386         SetLastError( RtlNtStatusToDosError(status) );
387         return FALSE;
388     }
389     return TRUE;
390 }
391
392
393 /***********************************************************************
394  *              ReadFile                (KERNEL32.@)
395  */
396 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
397                       LPDWORD bytesRead, LPOVERLAPPED overlapped )
398 {
399     LARGE_INTEGER       offset;
400     PLARGE_INTEGER      poffset = NULL;
401     IO_STATUS_BLOCK     iosb;
402     PIO_STATUS_BLOCK    io_status = &iosb;
403     HANDLE              hEvent = 0;
404     NTSTATUS            status;
405
406     TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
407           bytesRead, overlapped );
408
409     if (bytesRead) *bytesRead = 0;  /* Do this before anything else */
410     if (!bytesToRead) return TRUE;
411
412     if (is_console_handle(hFile))
413         return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
414
415     if (overlapped != NULL)
416     {
417         offset.u.LowPart = overlapped->u.s.Offset;
418         offset.u.HighPart = overlapped->u.s.OffsetHigh;
419         poffset = &offset;
420         hEvent = overlapped->hEvent;
421         io_status = (PIO_STATUS_BLOCK)overlapped;
422     }
423     io_status->u.Status = STATUS_PENDING;
424     io_status->Information = 0;
425
426     status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
427
428     if (status != STATUS_PENDING && bytesRead)
429         *bytesRead = io_status->Information;
430
431     if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
432     {
433         SetLastError( RtlNtStatusToDosError(status) );
434         return FALSE;
435     }
436     return TRUE;
437 }
438
439
440 /***********************************************************************
441  *              WriteFileEx                (KERNEL32.@)
442  */
443 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
444                         LPOVERLAPPED overlapped,
445                         LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
446 {
447     LARGE_INTEGER       offset;
448     NTSTATUS            status;
449     PIO_STATUS_BLOCK    io_status;
450
451     TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
452
453     if (overlapped == NULL)
454     {
455         SetLastError(ERROR_INVALID_PARAMETER);
456         return FALSE;
457     }
458     offset.u.LowPart = overlapped->u.s.Offset;
459     offset.u.HighPart = overlapped->u.s.OffsetHigh;
460
461     io_status = (PIO_STATUS_BLOCK)overlapped;
462     io_status->u.Status = STATUS_PENDING;
463
464     status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
465                          io_status, buffer, bytesToWrite, &offset, NULL);
466
467     if (status) SetLastError( RtlNtStatusToDosError(status) );
468     return !status;
469 }
470
471
472 /***********************************************************************
473  *             WriteFile               (KERNEL32.@)
474  */
475 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
476                        LPDWORD bytesWritten, LPOVERLAPPED overlapped )
477 {
478     HANDLE hEvent = NULL;
479     LARGE_INTEGER offset;
480     PLARGE_INTEGER poffset = NULL;
481     NTSTATUS status;
482     IO_STATUS_BLOCK iosb;
483     PIO_STATUS_BLOCK piosb = &iosb;
484
485     TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
486
487     if (is_console_handle(hFile))
488         return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
489
490     if (overlapped)
491     {
492         offset.u.LowPart = overlapped->u.s.Offset;
493         offset.u.HighPart = overlapped->u.s.OffsetHigh;
494         poffset = &offset;
495         hEvent = overlapped->hEvent;
496         piosb = (PIO_STATUS_BLOCK)overlapped;
497     }
498     piosb->u.Status = STATUS_PENDING;
499     piosb->Information = 0;
500
501     status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
502                          buffer, bytesToWrite, poffset, NULL);
503
504     /* FIXME: NtWriteFile does not always cause page faults, generate them now */
505     if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
506     {
507         status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
508                              buffer, bytesToWrite, poffset, NULL);
509         if (status != STATUS_INVALID_USER_BUFFER)
510             FIXME("Could not access memory (%p,%d) at first, now OK. Protected by DIBSection code?\n",
511                   buffer, bytesToWrite);
512     }
513
514     if (status != STATUS_PENDING && bytesWritten)
515         *bytesWritten = piosb->Information;
516
517     if (status && status != STATUS_TIMEOUT)
518     {
519         SetLastError( RtlNtStatusToDosError(status) );
520         return FALSE;
521     }
522     return TRUE;
523 }
524
525
526 /***********************************************************************
527  *              GetOverlappedResult     (KERNEL32.@)
528  *
529  * Check the result of an Asynchronous data transfer from a file.
530  *
531  * Parameters
532  *   HANDLE hFile                 [in] handle of file to check on
533  *   LPOVERLAPPED lpOverlapped    [in/out] pointer to overlapped
534  *   LPDWORD lpTransferred        [in/out] number of bytes transferred
535  *   BOOL bWait                   [in] wait for the transfer to complete ?
536  *
537  * RETURNS
538  *   TRUE on success
539  *   FALSE on failure
540  *
541  *  If successful (and relevant) lpTransferred will hold the number of
542  *   bytes transferred during the async operation.
543  *
544  * BUGS
545  *
546  * Currently only works for WaitCommEvent, ReadFile, WriteFile
547  *   with communications ports.
548  *
549  */
550 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
551                                 LPDWORD lpTransferred, BOOL bWait)
552 {
553     DWORD r = WAIT_OBJECT_0;
554
555     TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
556
557     if ( lpOverlapped == NULL )
558     {
559         ERR("lpOverlapped was null\n");
560         return FALSE;
561     }
562     if ( bWait )
563     {
564         if ( lpOverlapped->hEvent )
565         {
566             do
567             {
568                 TRACE( "waiting on %p\n", lpOverlapped );
569                 r = WaitForSingleObjectEx( lpOverlapped->hEvent, INFINITE, TRUE );
570                 TRACE( "wait on %p returned %d\n", lpOverlapped, r );
571             } while ( r == WAIT_IO_COMPLETION );
572         }
573         else
574         {
575             /* busy loop */
576             while ( ((volatile OVERLAPPED*)lpOverlapped)->Internal == STATUS_PENDING )
577                 Sleep( 10 );
578         }
579     }
580     else if ( lpOverlapped->Internal == STATUS_PENDING )
581     {
582         /* Wait in order to give APCs a chance to run. */
583         /* This is cheating, so we must set the event again in case of success -
584            it may be a non-manual reset event. */
585         do
586         {
587             TRACE( "waiting on %p\n", lpOverlapped );
588             r = WaitForSingleObjectEx( lpOverlapped->hEvent, 0, TRUE );
589             TRACE( "wait on %p returned %d\n", lpOverlapped, r );
590         } while ( r == WAIT_IO_COMPLETION );
591         if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
592             NtSetEvent( lpOverlapped->hEvent, NULL );
593     }
594     if ( r == WAIT_FAILED )
595     {
596         WARN("wait operation failed\n");
597         return FALSE;
598     }
599     if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
600
601     switch ( lpOverlapped->Internal )
602     {
603     case STATUS_SUCCESS:
604         return TRUE;
605     case STATUS_PENDING:
606         SetLastError( ERROR_IO_INCOMPLETE );
607         if ( bWait ) ERR("PENDING status after waiting!\n");
608         return FALSE;
609     default:
610         SetLastError( RtlNtStatusToDosError( lpOverlapped->Internal ) );
611         return FALSE;
612     }
613 }
614
615 /***********************************************************************
616  *             CancelIo                   (KERNEL32.@)
617  *
618  * Cancels pending I/O operations initiated by the current thread on a file.
619  *
620  * PARAMS
621  *  handle [I] File handle.
622  *
623  * RETURNS
624  *  Success: TRUE.
625  *  Failure: FALSE, check GetLastError().
626  */
627 BOOL WINAPI CancelIo(HANDLE handle)
628 {
629     IO_STATUS_BLOCK    io_status;
630
631     NtCancelIoFile(handle, &io_status);
632     if (io_status.u.Status)
633     {
634         SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
635         return FALSE;
636     }
637     return TRUE;
638 }
639
640 /***********************************************************************
641  *           _hread   (KERNEL32.@)
642  */
643 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
644 {
645     return _lread( hFile, buffer, count );
646 }
647
648
649 /***********************************************************************
650  *           _hwrite   (KERNEL32.@)
651  *
652  *      experimentation yields that _lwrite:
653  *              o truncates the file at the current position with
654  *                a 0 len write
655  *              o returns 0 on a 0 length write
656  *              o works with console handles
657  *
658  */
659 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
660 {
661     DWORD result;
662
663     TRACE("%d %p %d\n", handle, buffer, count );
664
665     if (!count)
666     {
667         /* Expand or truncate at current position */
668         if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
669         return 0;
670     }
671     if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
672         return HFILE_ERROR;
673     return result;
674 }
675
676
677 /***********************************************************************
678  *           _lclose   (KERNEL32.@)
679  */
680 HFILE WINAPI _lclose( HFILE hFile )
681 {
682     TRACE("handle %d\n", hFile );
683     return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
684 }
685
686
687 /***********************************************************************
688  *           _lcreat   (KERNEL32.@)
689  */
690 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
691 {
692     /* Mask off all flags not explicitly allowed by the doc */
693     attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
694     TRACE("%s %02x\n", path, attr );
695     return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
696                                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
697                                CREATE_ALWAYS, attr, 0 );
698 }
699
700
701 /***********************************************************************
702  *           _lopen   (KERNEL32.@)
703  */
704 HFILE WINAPI _lopen( LPCSTR path, INT mode )
705 {
706     TRACE("(%s,%04x)\n", debugstr_a(path), mode );
707     return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
708 }
709
710 /***********************************************************************
711  *           _lread   (KERNEL32.@)
712  */
713 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
714 {
715     DWORD result;
716     if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
717         return HFILE_ERROR;
718     return result;
719 }
720
721
722 /***********************************************************************
723  *           _llseek   (KERNEL32.@)
724  */
725 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
726 {
727     return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
728 }
729
730
731 /***********************************************************************
732  *           _lwrite   (KERNEL32.@)
733  */
734 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
735 {
736     return (UINT)_hwrite( hFile, buffer, (LONG)count );
737 }
738
739
740 /***********************************************************************
741  *           FlushFileBuffers   (KERNEL32.@)
742  */
743 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
744 {
745     NTSTATUS            nts;
746     IO_STATUS_BLOCK     ioblk;
747
748     if (is_console_handle( hFile ))
749     {
750         /* this will fail (as expected) for an output handle */
751         return FlushConsoleInputBuffer( hFile );
752     }
753     nts = NtFlushBuffersFile( hFile, &ioblk );
754     if (nts != STATUS_SUCCESS)
755     {
756         SetLastError( RtlNtStatusToDosError( nts ) );
757         return FALSE;
758     }
759
760     return TRUE;
761 }
762
763
764 /***********************************************************************
765  *           GetFileType   (KERNEL32.@)
766  */
767 DWORD WINAPI GetFileType( HANDLE hFile )
768 {
769     FILE_FS_DEVICE_INFORMATION info;
770     IO_STATUS_BLOCK io;
771     NTSTATUS status;
772
773     if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
774
775     status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
776     if (status != STATUS_SUCCESS)
777     {
778         SetLastError( RtlNtStatusToDosError(status) );
779         return FILE_TYPE_UNKNOWN;
780     }
781
782     switch(info.DeviceType)
783     {
784     case FILE_DEVICE_NULL:
785     case FILE_DEVICE_SERIAL_PORT:
786     case FILE_DEVICE_PARALLEL_PORT:
787     case FILE_DEVICE_TAPE:
788     case FILE_DEVICE_UNKNOWN:
789         return FILE_TYPE_CHAR;
790     case FILE_DEVICE_NAMED_PIPE:
791         return FILE_TYPE_PIPE;
792     default:
793         return FILE_TYPE_DISK;
794     }
795 }
796
797
798 /***********************************************************************
799  *             GetFileInformationByHandle   (KERNEL32.@)
800  */
801 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
802 {
803     FILE_ALL_INFORMATION all_info;
804     IO_STATUS_BLOCK io;
805     NTSTATUS status;
806
807     status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
808     if (status == STATUS_SUCCESS)
809     {
810         info->dwFileAttributes                = all_info.BasicInformation.FileAttributes;
811         info->ftCreationTime.dwHighDateTime   = all_info.BasicInformation.CreationTime.u.HighPart;
812         info->ftCreationTime.dwLowDateTime    = all_info.BasicInformation.CreationTime.u.LowPart;
813         info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
814         info->ftLastAccessTime.dwLowDateTime  = all_info.BasicInformation.LastAccessTime.u.LowPart;
815         info->ftLastWriteTime.dwHighDateTime  = all_info.BasicInformation.LastWriteTime.u.HighPart;
816         info->ftLastWriteTime.dwLowDateTime   = all_info.BasicInformation.LastWriteTime.u.LowPart;
817         info->dwVolumeSerialNumber            = 0;  /* FIXME */
818         info->nFileSizeHigh                   = all_info.StandardInformation.EndOfFile.u.HighPart;
819         info->nFileSizeLow                    = all_info.StandardInformation.EndOfFile.u.LowPart;
820         info->nNumberOfLinks                  = all_info.StandardInformation.NumberOfLinks;
821         info->nFileIndexHigh                  = all_info.InternalInformation.IndexNumber.u.HighPart;
822         info->nFileIndexLow                   = all_info.InternalInformation.IndexNumber.u.LowPart;
823         return TRUE;
824     }
825     SetLastError( RtlNtStatusToDosError(status) );
826     return FALSE;
827 }
828
829
830 /***********************************************************************
831  *           GetFileSize   (KERNEL32.@)
832  *
833  * Retrieve the size of a file.
834  *
835  * PARAMS
836  *  hFile        [I] File to retrieve size of.
837  *  filesizehigh [O] On return, the high bits of the file size.
838  *
839  * RETURNS
840  *  Success: The low bits of the file size.
841  *  Failure: INVALID_FILE_SIZE. As this is could also be a success value,
842  *           check GetLastError() for values other than ERROR_SUCCESS.
843  */
844 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
845 {
846     LARGE_INTEGER size;
847     if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
848     if (filesizehigh) *filesizehigh = size.u.HighPart;
849     if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
850     return size.u.LowPart;
851 }
852
853
854 /***********************************************************************
855  *           GetFileSizeEx   (KERNEL32.@)
856  *
857  * Retrieve the size of a file.
858  *
859  * PARAMS
860  *  hFile        [I] File to retrieve size of.
861  *  lpFileSIze   [O] On return, the size of the file.
862  *
863  * RETURNS
864  *  Success: TRUE.
865  *  Failure: FALSE, check GetLastError().
866  */
867 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
868 {
869     FILE_END_OF_FILE_INFORMATION info;
870     IO_STATUS_BLOCK io;
871     NTSTATUS status;
872
873     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
874     if (status == STATUS_SUCCESS)
875     {
876         *lpFileSize = info.EndOfFile;
877         return TRUE;
878     }
879     SetLastError( RtlNtStatusToDosError(status) );
880     return FALSE;
881 }
882
883
884 /**************************************************************************
885  *           SetEndOfFile   (KERNEL32.@)
886  *
887  * Sets the current position as the end of the file.
888  *
889  * PARAMS
890  *  hFile [I] File handle.
891  *
892  * RETURNS
893  *  Success: TRUE.
894  *  Failure: FALSE, check GetLastError().
895  */
896 BOOL WINAPI SetEndOfFile( HANDLE hFile )
897 {
898     FILE_POSITION_INFORMATION pos;
899     FILE_END_OF_FILE_INFORMATION eof;
900     IO_STATUS_BLOCK io;
901     NTSTATUS status;
902
903     status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
904     if (status == STATUS_SUCCESS)
905     {
906         eof.EndOfFile = pos.CurrentByteOffset;
907         status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
908     }
909     if (status == STATUS_SUCCESS) return TRUE;
910     SetLastError( RtlNtStatusToDosError(status) );
911     return FALSE;
912 }
913
914
915 /***********************************************************************
916  *           SetFilePointer   (KERNEL32.@)
917  */
918 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
919 {
920     LARGE_INTEGER dist, newpos;
921
922     if (highword)
923     {
924         dist.u.LowPart  = distance;
925         dist.u.HighPart = *highword;
926     }
927     else dist.QuadPart = distance;
928
929     if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
930
931     if (highword) *highword = newpos.u.HighPart;
932     if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
933     return newpos.u.LowPart;
934 }
935
936
937 /***********************************************************************
938  *           SetFilePointerEx   (KERNEL32.@)
939  */
940 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
941                               LARGE_INTEGER *newpos, DWORD method )
942 {
943     LONGLONG pos;
944     IO_STATUS_BLOCK io;
945     FILE_POSITION_INFORMATION info;
946
947     switch(method)
948     {
949     case FILE_BEGIN:
950         pos = distance.QuadPart;
951         break;
952     case FILE_CURRENT:
953         if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
954             goto error;
955         pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
956         break;
957     case FILE_END:
958         {
959             FILE_END_OF_FILE_INFORMATION eof;
960             if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
961                 goto error;
962             pos = eof.EndOfFile.QuadPart + distance.QuadPart;
963         }
964         break;
965     default:
966         SetLastError( ERROR_INVALID_PARAMETER );
967         return FALSE;
968     }
969
970     if (pos < 0)
971     {
972         SetLastError( ERROR_NEGATIVE_SEEK );
973         return FALSE;
974     }
975
976     info.CurrentByteOffset.QuadPart = pos;
977     if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
978         goto error;
979     if (newpos) newpos->QuadPart = pos;
980     return TRUE;
981
982 error:
983     SetLastError( RtlNtStatusToDosError(io.u.Status) );
984     return FALSE;
985 }
986
987 /***********************************************************************
988  *           GetFileTime   (KERNEL32.@)
989  */
990 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
991                          FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
992 {
993     FILE_BASIC_INFORMATION info;
994     IO_STATUS_BLOCK io;
995     NTSTATUS status;
996
997     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
998     if (status == STATUS_SUCCESS)
999     {
1000         if (lpCreationTime)
1001         {
1002             lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1003             lpCreationTime->dwLowDateTime  = info.CreationTime.u.LowPart;
1004         }
1005         if (lpLastAccessTime)
1006         {
1007             lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1008             lpLastAccessTime->dwLowDateTime  = info.LastAccessTime.u.LowPart;
1009         }
1010         if (lpLastWriteTime)
1011         {
1012             lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1013             lpLastWriteTime->dwLowDateTime  = info.LastWriteTime.u.LowPart;
1014         }
1015         return TRUE;
1016     }
1017     SetLastError( RtlNtStatusToDosError(status) );
1018     return FALSE;
1019 }
1020
1021
1022 /***********************************************************************
1023  *              SetFileTime   (KERNEL32.@)
1024  */
1025 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1026                          const FILETIME *atime, const FILETIME *mtime )
1027 {
1028     FILE_BASIC_INFORMATION info;
1029     IO_STATUS_BLOCK io;
1030     NTSTATUS status;
1031
1032     memset( &info, 0, sizeof(info) );
1033     if (ctime)
1034     {
1035         info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1036         info.CreationTime.u.LowPart  = ctime->dwLowDateTime;
1037     }
1038     if (atime)
1039     {
1040         info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1041         info.LastAccessTime.u.LowPart  = atime->dwLowDateTime;
1042     }
1043     if (mtime)
1044     {
1045         info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1046         info.LastWriteTime.u.LowPart  = mtime->dwLowDateTime;
1047     }
1048
1049     status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1050     if (status == STATUS_SUCCESS) return TRUE;
1051     SetLastError( RtlNtStatusToDosError(status) );
1052     return FALSE;
1053 }
1054
1055
1056 /**************************************************************************
1057  *           LockFile   (KERNEL32.@)
1058  */
1059 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1060                       DWORD count_low, DWORD count_high )
1061 {
1062     NTSTATUS            status;
1063     LARGE_INTEGER       count, offset;
1064
1065     TRACE( "%p %x%08x %x%08x\n",
1066            hFile, offset_high, offset_low, count_high, count_low );
1067
1068     count.u.LowPart = count_low;
1069     count.u.HighPart = count_high;
1070     offset.u.LowPart = offset_low;
1071     offset.u.HighPart = offset_high;
1072
1073     status = NtLockFile( hFile, 0, NULL, NULL, 
1074                          NULL, &offset, &count, NULL, TRUE, TRUE );
1075     
1076     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1077     return !status;
1078 }
1079
1080
1081 /**************************************************************************
1082  * LockFileEx [KERNEL32.@]
1083  *
1084  * Locks a byte range within an open file for shared or exclusive access.
1085  *
1086  * RETURNS
1087  *   success: TRUE
1088  *   failure: FALSE
1089  *
1090  * NOTES
1091  * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1092  */
1093 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1094                         DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1095 {
1096     NTSTATUS status;
1097     LARGE_INTEGER count, offset;
1098
1099     if (reserved)
1100     {
1101         SetLastError( ERROR_INVALID_PARAMETER );
1102         return FALSE;
1103     }
1104
1105     TRACE( "%p %x%08x %x%08x flags %x\n",
1106            hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset, 
1107            count_high, count_low, flags );
1108
1109     count.u.LowPart = count_low;
1110     count.u.HighPart = count_high;
1111     offset.u.LowPart = overlapped->u.s.Offset;
1112     offset.u.HighPart = overlapped->u.s.OffsetHigh;
1113
1114     status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL, 
1115                          NULL, &offset, &count, NULL, 
1116                          flags & LOCKFILE_FAIL_IMMEDIATELY,
1117                          flags & LOCKFILE_EXCLUSIVE_LOCK );
1118     
1119     if (status) SetLastError( RtlNtStatusToDosError(status) );
1120     return !status;
1121 }
1122
1123
1124 /**************************************************************************
1125  *           UnlockFile   (KERNEL32.@)
1126  */
1127 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1128                         DWORD count_low, DWORD count_high )
1129 {
1130     NTSTATUS    status;
1131     LARGE_INTEGER count, offset;
1132
1133     count.u.LowPart = count_low;
1134     count.u.HighPart = count_high;
1135     offset.u.LowPart = offset_low;
1136     offset.u.HighPart = offset_high;
1137
1138     status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1139     if (status) SetLastError( RtlNtStatusToDosError(status) );
1140     return !status;
1141 }
1142
1143
1144 /**************************************************************************
1145  *           UnlockFileEx   (KERNEL32.@)
1146  */
1147 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1148                           LPOVERLAPPED overlapped )
1149 {
1150     if (reserved)
1151     {
1152         SetLastError( ERROR_INVALID_PARAMETER );
1153         return FALSE;
1154     }
1155     if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1156
1157     return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1158 }
1159
1160
1161 /***********************************************************************
1162  *           Win32HandleToDosFileHandle   (KERNEL32.21)
1163  *
1164  * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1165  * longer valid after this function (even on failure).
1166  *
1167  * Note: this is not exactly right, since on Win95 the Win32 handles
1168  *       are on top of DOS handles and we do it the other way
1169  *       around. Should be good enough though.
1170  */
1171 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1172 {
1173     int i;
1174
1175     if (!handle || (handle == INVALID_HANDLE_VALUE))
1176         return HFILE_ERROR;
1177
1178     FILE_InitProcessDosHandles();
1179     for (i = 0; i < DOS_TABLE_SIZE; i++)
1180         if (!dos_handles[i])
1181         {
1182             dos_handles[i] = handle;
1183             TRACE("Got %d for h32 %p\n", i, handle );
1184             return (HFILE)i;
1185         }
1186     CloseHandle( handle );
1187     SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1188     return HFILE_ERROR;
1189 }
1190
1191
1192 /***********************************************************************
1193  *           DosFileHandleToWin32Handle   (KERNEL32.20)
1194  *
1195  * Return the Win32 handle for a DOS handle.
1196  *
1197  * Note: this is not exactly right, since on Win95 the Win32 handles
1198  *       are on top of DOS handles and we do it the other way
1199  *       around. Should be good enough though.
1200  */
1201 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1202 {
1203     HFILE16 hfile = (HFILE16)handle;
1204     if (hfile < 5) FILE_InitProcessDosHandles();
1205     if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1206     {
1207         SetLastError( ERROR_INVALID_HANDLE );
1208         return INVALID_HANDLE_VALUE;
1209     }
1210     return dos_handles[hfile];
1211 }
1212
1213
1214 /*************************************************************************
1215  *           SetHandleCount   (KERNEL32.@)
1216  */
1217 UINT WINAPI SetHandleCount( UINT count )
1218 {
1219     return min( 256, count );
1220 }
1221
1222
1223 /***********************************************************************
1224  *           DisposeLZ32Handle   (KERNEL32.22)
1225  *
1226  * Note: this is not entirely correct, we should only close the
1227  *       32-bit handle and not the 16-bit one, but we cannot do
1228  *       this because of the way our DOS handles are implemented.
1229  *       It shouldn't break anything though.
1230  */
1231 void WINAPI DisposeLZ32Handle( HANDLE handle )
1232 {
1233     int i;
1234
1235     if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1236
1237     for (i = 5; i < DOS_TABLE_SIZE; i++)
1238         if (dos_handles[i] == handle)
1239         {
1240             dos_handles[i] = 0;
1241             CloseHandle( handle );
1242             break;
1243         }
1244 }
1245
1246 /**************************************************************************
1247  *                      Operations on file names                          *
1248  **************************************************************************/
1249
1250
1251 /*************************************************************************
1252  * CreateFileW [KERNEL32.@]  Creates or opens a file or other object
1253  *
1254  * Creates or opens an object, and returns a handle that can be used to
1255  * access that object.
1256  *
1257  * PARAMS
1258  *
1259  * filename     [in] pointer to filename to be accessed
1260  * access       [in] access mode requested
1261  * sharing      [in] share mode
1262  * sa           [in] pointer to security attributes
1263  * creation     [in] how to create the file
1264  * attributes   [in] attributes for newly created file
1265  * template     [in] handle to file with extended attributes to copy
1266  *
1267  * RETURNS
1268  *   Success: Open handle to specified file
1269  *   Failure: INVALID_HANDLE_VALUE
1270  */
1271 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1272                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1273                               DWORD attributes, HANDLE template )
1274 {
1275     NTSTATUS status;
1276     UINT options;
1277     OBJECT_ATTRIBUTES attr;
1278     UNICODE_STRING nameW;
1279     IO_STATUS_BLOCK io;
1280     HANDLE ret;
1281     DWORD dosdev;
1282     static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1283     static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1284     static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1285     SECURITY_QUALITY_OF_SERVICE qos;
1286
1287     static const UINT nt_disposition[5] =
1288     {
1289         FILE_CREATE,        /* CREATE_NEW */
1290         FILE_OVERWRITE_IF,  /* CREATE_ALWAYS */
1291         FILE_OPEN,          /* OPEN_EXISTING */
1292         FILE_OPEN_IF,       /* OPEN_ALWAYS */
1293         FILE_OVERWRITE      /* TRUNCATE_EXISTING */
1294     };
1295
1296
1297     /* sanity checks */
1298
1299     if (!filename || !filename[0])
1300     {
1301         SetLastError( ERROR_PATH_NOT_FOUND );
1302         return INVALID_HANDLE_VALUE;
1303     }
1304
1305     TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1306           (access & GENERIC_READ)?"GENERIC_READ ":"",
1307           (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1308           (!access)?"QUERY_ACCESS ":"",
1309           (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1310           (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1311           (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1312           creation, attributes);
1313
1314     /* Open a console for CONIN$ or CONOUT$ */
1315
1316     if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1317     {
1318         ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1319         goto done;
1320     }
1321
1322     if (!strncmpW(filename, bkslashes_with_dotW, 4))
1323     {
1324         static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1325         static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1326
1327         if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1328             !strncmpiW( filename + 4, pipeW, 5 ) ||
1329             !strncmpiW( filename + 4, mailslotW, 9 ))
1330         {
1331             dosdev = 0;
1332         }
1333         else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1334         {
1335             dosdev += MAKELONG( 0, 4*sizeof(WCHAR) );  /* adjust position to start of filename */
1336         }
1337         else if (!(GetVersion() & 0x80000000))
1338         {
1339             dosdev = 0;
1340         }
1341         else if (filename[4])
1342         {
1343             ret = VXD_Open( filename+4, access, sa );
1344             goto done;
1345         }
1346         else
1347         {
1348             SetLastError( ERROR_INVALID_NAME );
1349             return INVALID_HANDLE_VALUE;
1350         }
1351     }
1352     else dosdev = RtlIsDosDeviceName_U( filename );
1353
1354     if (dosdev)
1355     {
1356         static const WCHAR conW[] = {'C','O','N'};
1357
1358         if (LOWORD(dosdev) == sizeof(conW) &&
1359             !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1360         {
1361             switch (access & (GENERIC_READ|GENERIC_WRITE))
1362             {
1363             case GENERIC_READ:
1364                 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1365                 goto done;
1366             case GENERIC_WRITE:
1367                 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1368                 goto done;
1369             default:
1370                 SetLastError( ERROR_FILE_NOT_FOUND );
1371                 return INVALID_HANDLE_VALUE;
1372             }
1373         }
1374     }
1375
1376     if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1377     {
1378         SetLastError( ERROR_INVALID_PARAMETER );
1379         return INVALID_HANDLE_VALUE;
1380     }
1381
1382     if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1383     {
1384         SetLastError( ERROR_PATH_NOT_FOUND );
1385         return INVALID_HANDLE_VALUE;
1386     }
1387
1388     /* now call NtCreateFile */
1389
1390     options = 0;
1391     if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1392         options |= FILE_OPEN_FOR_BACKUP_INTENT;
1393     else
1394         options |= FILE_NON_DIRECTORY_FILE;
1395     if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1396     {
1397         options |= FILE_DELETE_ON_CLOSE;
1398         access |= DELETE;
1399     }
1400     if (!(attributes & FILE_FLAG_OVERLAPPED))
1401         options |= FILE_SYNCHRONOUS_IO_ALERT;
1402     if (attributes & FILE_FLAG_RANDOM_ACCESS)
1403         options |= FILE_RANDOM_ACCESS;
1404     attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1405
1406     attr.Length = sizeof(attr);
1407     attr.RootDirectory = 0;
1408     attr.Attributes = OBJ_CASE_INSENSITIVE;
1409     attr.ObjectName = &nameW;
1410     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1411     if (attributes & SECURITY_SQOS_PRESENT)
1412     {
1413         qos.Length = sizeof(qos);
1414         qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1415         qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1416         qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1417         attr.SecurityQualityOfService = &qos;
1418     }
1419     else
1420         attr.SecurityQualityOfService = NULL;
1421
1422     if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1423
1424     status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1425                            sharing, nt_disposition[creation - CREATE_NEW],
1426                            options, NULL, 0 );
1427     if (status)
1428     {
1429         WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1430         ret = INVALID_HANDLE_VALUE;
1431
1432         /* In the case file creation was rejected due to CREATE_NEW flag
1433          * was specified and file with that name already exists, correct
1434          * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1435          * Note: RtlNtStatusToDosError is not the subject to blame here.
1436          */
1437         if (status == STATUS_OBJECT_NAME_COLLISION)
1438             SetLastError( ERROR_FILE_EXISTS );
1439         else
1440             SetLastError( RtlNtStatusToDosError(status) );
1441     }
1442     else SetLastError(0);
1443     RtlFreeUnicodeString( &nameW );
1444
1445  done:
1446     if (!ret) ret = INVALID_HANDLE_VALUE;
1447     TRACE("returning %p\n", ret);
1448     return ret;
1449 }
1450
1451
1452
1453 /*************************************************************************
1454  *              CreateFileA              (KERNEL32.@)
1455  *
1456  * See CreateFileW.
1457  */
1458 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1459                            LPSECURITY_ATTRIBUTES sa, DWORD creation,
1460                            DWORD attributes, HANDLE template)
1461 {
1462     WCHAR *nameW;
1463
1464     if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1465     return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1466 }
1467
1468
1469 /***********************************************************************
1470  *           DeleteFileW   (KERNEL32.@)
1471  *
1472  * Delete a file.
1473  *
1474  * PARAMS
1475  *  path [I] Path to the file to delete.
1476  *
1477  * RETURNS
1478  *  Success: TRUE.
1479  *  Failure: FALSE, check GetLastError().
1480  */
1481 BOOL WINAPI DeleteFileW( LPCWSTR path )
1482 {
1483     UNICODE_STRING nameW;
1484     OBJECT_ATTRIBUTES attr;
1485     NTSTATUS status;
1486
1487     TRACE("%s\n", debugstr_w(path) );
1488
1489     if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1490     {
1491         SetLastError( ERROR_PATH_NOT_FOUND );
1492         return FALSE;
1493     }
1494
1495     attr.Length = sizeof(attr);
1496     attr.RootDirectory = 0;
1497     attr.Attributes = OBJ_CASE_INSENSITIVE;
1498     attr.ObjectName = &nameW;
1499     attr.SecurityDescriptor = NULL;
1500     attr.SecurityQualityOfService = NULL;
1501
1502     status = NtDeleteFile(&attr);
1503     RtlFreeUnicodeString( &nameW );
1504     if (status)
1505     {
1506         SetLastError( RtlNtStatusToDosError(status) );
1507         return FALSE;
1508     }
1509     return TRUE;
1510 }
1511
1512
1513 /***********************************************************************
1514  *           DeleteFileA   (KERNEL32.@)
1515  *
1516  * See DeleteFileW.
1517  */
1518 BOOL WINAPI DeleteFileA( LPCSTR path )
1519 {
1520     WCHAR *pathW;
1521
1522     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1523     return DeleteFileW( pathW );
1524 }
1525
1526
1527 /**************************************************************************
1528  *           ReplaceFileW   (KERNEL32.@)
1529  *           ReplaceFile    (KERNEL32.@)
1530  */
1531 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1532                          LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1533                          LPVOID lpExclude, LPVOID lpReserved)
1534 {
1535     FIXME("(%s,%s,%s,%08x,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1536                                           debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1537     SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1538     return FALSE;
1539 }
1540
1541
1542 /**************************************************************************
1543  *           ReplaceFileA (KERNEL32.@)
1544  */
1545 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1546                          LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1547                          LPVOID lpExclude, LPVOID lpReserved)
1548 {
1549     FIXME("(%s,%s,%s,%08x,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1550                                           lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1551     SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1552     return FALSE;
1553 }
1554
1555
1556 /*************************************************************************
1557  *           FindFirstFileExW  (KERNEL32.@)
1558  */
1559 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1560                                 LPVOID data, FINDEX_SEARCH_OPS search_op,
1561                                 LPVOID filter, DWORD flags)
1562 {
1563     WCHAR *mask, *p;
1564     FIND_FIRST_INFO *info = NULL;
1565     UNICODE_STRING nt_name;
1566     OBJECT_ATTRIBUTES attr;
1567     IO_STATUS_BLOCK io;
1568     NTSTATUS status;
1569     DWORD device = 0;
1570
1571     TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1572
1573     if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1574         || flags != 0)
1575     {
1576         FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1577         return INVALID_HANDLE_VALUE;
1578     }
1579     if (level != FindExInfoStandard)
1580     {
1581         FIXME("info level %d not implemented\n", level );
1582         return INVALID_HANDLE_VALUE;
1583     }
1584
1585     if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1586     {
1587         SetLastError( ERROR_PATH_NOT_FOUND );
1588         return INVALID_HANDLE_VALUE;
1589     }
1590
1591     if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1592     {
1593         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1594         goto error;
1595     }
1596
1597     if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1598     {
1599         static const WCHAR dotW[] = {'.',0};
1600         WCHAR *dir = NULL;
1601
1602         /* we still need to check that the directory can be opened */
1603
1604         if (HIWORD(device))
1605         {
1606             if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1607             {
1608                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1609                 goto error;
1610             }
1611             memcpy( dir, filename, HIWORD(device) );
1612             dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1613         }
1614         RtlFreeUnicodeString( &nt_name );
1615         if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1616         {
1617             HeapFree( GetProcessHeap(), 0, dir );
1618             SetLastError( ERROR_PATH_NOT_FOUND );
1619             goto error;
1620         }
1621         HeapFree( GetProcessHeap(), 0, dir );
1622         RtlInitUnicodeString( &info->mask, NULL );
1623     }
1624     else if (!mask || !*mask)
1625     {
1626         SetLastError( ERROR_FILE_NOT_FOUND );
1627         goto error;
1628     }
1629     else
1630     {
1631         if (!RtlCreateUnicodeString( &info->mask, mask ))
1632         {
1633             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1634             goto error;
1635         }
1636
1637         /* truncate dir name before mask */
1638         *mask = 0;
1639         nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1640     }
1641
1642     /* check if path is the root of the drive */
1643     info->is_root = FALSE;
1644     p = nt_name.Buffer + 4;  /* skip \??\ prefix */
1645     if (p[0] && p[1] == ':')
1646     {
1647         p += 2;
1648         while (*p == '\\') p++;
1649         info->is_root = (*p == 0);
1650     }
1651
1652     attr.Length = sizeof(attr);
1653     attr.RootDirectory = 0;
1654     attr.Attributes = OBJ_CASE_INSENSITIVE;
1655     attr.ObjectName = &nt_name;
1656     attr.SecurityDescriptor = NULL;
1657     attr.SecurityQualityOfService = NULL;
1658
1659     status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1660                          FILE_SHARE_READ | FILE_SHARE_WRITE,
1661                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1662
1663     if (status != STATUS_SUCCESS)
1664     {
1665         RtlFreeUnicodeString( &info->mask );
1666         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1667             SetLastError( ERROR_PATH_NOT_FOUND );
1668         else
1669             SetLastError( RtlNtStatusToDosError(status) );
1670         goto error;
1671     }
1672
1673     RtlInitializeCriticalSection( &info->cs );
1674     info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1675     info->path     = nt_name;
1676     info->magic    = FIND_FIRST_MAGIC;
1677     info->data_pos = 0;
1678     info->data_len = 0;
1679     info->search_op = search_op;
1680
1681     if (device)
1682     {
1683         WIN32_FIND_DATAW *wfd = data;
1684
1685         memset( wfd, 0, sizeof(*wfd) );
1686         memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1687         wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1688         CloseHandle( info->handle );
1689         info->handle = 0;
1690     }
1691     else
1692     {
1693         IO_STATUS_BLOCK io;
1694
1695         NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1696                               FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1697         if (io.u.Status)
1698         {
1699             FindClose( info );
1700             SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1701             return INVALID_HANDLE_VALUE;
1702         }
1703         info->data_len = io.Information;
1704         if (!FindNextFileW( info, data ))
1705         {
1706             TRACE( "%s not found\n", debugstr_w(filename) );
1707             FindClose( info );
1708             SetLastError( ERROR_FILE_NOT_FOUND );
1709             return INVALID_HANDLE_VALUE;
1710         }
1711         if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1712         {
1713             /* we can't find two files with the same name */
1714             CloseHandle( info->handle );
1715             info->handle = 0;
1716         }
1717     }
1718     return info;
1719
1720 error:
1721     HeapFree( GetProcessHeap(), 0, info );
1722     RtlFreeUnicodeString( &nt_name );
1723     return INVALID_HANDLE_VALUE;
1724 }
1725
1726
1727 /*************************************************************************
1728  *           FindNextFileW   (KERNEL32.@)
1729  */
1730 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1731 {
1732     FIND_FIRST_INFO *info;
1733     FILE_BOTH_DIR_INFORMATION *dir_info;
1734     BOOL ret = FALSE;
1735
1736     TRACE("%p %p\n", handle, data);
1737
1738     if (!handle || handle == INVALID_HANDLE_VALUE)
1739     {
1740         SetLastError( ERROR_INVALID_HANDLE );
1741         return ret;
1742     }
1743     info = (FIND_FIRST_INFO *)handle;
1744     if (info->magic != FIND_FIRST_MAGIC)
1745     {
1746         SetLastError( ERROR_INVALID_HANDLE );
1747         return ret;
1748     }
1749
1750     RtlEnterCriticalSection( &info->cs );
1751
1752     if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1753     else for (;;)
1754     {
1755         if (info->data_pos >= info->data_len)  /* need to read some more data */
1756         {
1757             IO_STATUS_BLOCK io;
1758
1759             NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1760                                   FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1761             if (io.u.Status)
1762             {
1763                 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1764                 if (io.u.Status == STATUS_NO_MORE_FILES)
1765                 {
1766                     CloseHandle( info->handle );
1767                     info->handle = 0;
1768                 }
1769                 break;
1770             }
1771             info->data_len = io.Information;
1772             info->data_pos = 0;
1773         }
1774
1775         dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1776
1777         if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1778         else info->data_pos = info->data_len;
1779
1780         /* don't return '.' and '..' in the root of the drive */
1781         if (info->is_root)
1782         {
1783             if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1784             if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1785                 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1786         }
1787
1788         /* check for dir symlink */
1789         if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1790             (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1791             strpbrkW( info->mask.Buffer, wildcardsW ))
1792         {
1793             if (!check_dir_symlink( info, dir_info )) continue;
1794         }
1795         if (info->search_op == FindExSearchLimitToDirectories &&
1796             (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1797             continue;
1798
1799         data->dwFileAttributes = dir_info->FileAttributes;
1800         data->ftCreationTime   = *(FILETIME *)&dir_info->CreationTime;
1801         data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1802         data->ftLastWriteTime  = *(FILETIME *)&dir_info->LastWriteTime;
1803         data->nFileSizeHigh    = dir_info->EndOfFile.QuadPart >> 32;
1804         data->nFileSizeLow     = (DWORD)dir_info->EndOfFile.QuadPart;
1805         data->dwReserved0      = 0;
1806         data->dwReserved1      = 0;
1807
1808         memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1809         data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1810         memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1811         data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1812
1813         TRACE("returning %s (%s)\n",
1814               debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1815
1816         ret = TRUE;
1817         break;
1818     }
1819
1820     RtlLeaveCriticalSection( &info->cs );
1821     return ret;
1822 }
1823
1824
1825 /*************************************************************************
1826  *           FindClose   (KERNEL32.@)
1827  */
1828 BOOL WINAPI FindClose( HANDLE handle )
1829 {
1830     FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1831
1832     if (!handle || handle == INVALID_HANDLE_VALUE)
1833     {
1834         SetLastError( ERROR_INVALID_HANDLE );
1835         return FALSE;
1836     }
1837
1838     __TRY
1839     {
1840         if (info->magic == FIND_FIRST_MAGIC)
1841         {
1842             RtlEnterCriticalSection( &info->cs );
1843             if (info->magic == FIND_FIRST_MAGIC)  /* in case someone else freed it in the meantime */
1844             {
1845                 info->magic = 0;
1846                 if (info->handle) CloseHandle( info->handle );
1847                 info->handle = 0;
1848                 RtlFreeUnicodeString( &info->mask );
1849                 info->mask.Buffer = NULL;
1850                 RtlFreeUnicodeString( &info->path );
1851                 info->data_pos = 0;
1852                 info->data_len = 0;
1853                 RtlLeaveCriticalSection( &info->cs );
1854                 info->cs.DebugInfo->Spare[0] = 0;
1855                 RtlDeleteCriticalSection( &info->cs );
1856                 HeapFree( GetProcessHeap(), 0, info );
1857             }
1858         }
1859     }
1860     __EXCEPT_PAGE_FAULT
1861     {
1862         WARN("Illegal handle %p\n", handle);
1863         SetLastError( ERROR_INVALID_HANDLE );
1864         return FALSE;
1865     }
1866     __ENDTRY
1867
1868     return TRUE;
1869 }
1870
1871
1872 /*************************************************************************
1873  *           FindFirstFileA   (KERNEL32.@)
1874  */
1875 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1876 {
1877     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1878                             FindExSearchNameMatch, NULL, 0);
1879 }
1880
1881 /*************************************************************************
1882  *           FindFirstFileExA   (KERNEL32.@)
1883  */
1884 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1885                                 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1886                                 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1887 {
1888     HANDLE handle;
1889     WIN32_FIND_DATAA *dataA;
1890     WIN32_FIND_DATAW dataW;
1891     WCHAR *nameW;
1892
1893     if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1894
1895     handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1896     if (handle == INVALID_HANDLE_VALUE) return handle;
1897
1898     dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1899     dataA->dwFileAttributes = dataW.dwFileAttributes;
1900     dataA->ftCreationTime   = dataW.ftCreationTime;
1901     dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1902     dataA->ftLastWriteTime  = dataW.ftLastWriteTime;
1903     dataA->nFileSizeHigh    = dataW.nFileSizeHigh;
1904     dataA->nFileSizeLow     = dataW.nFileSizeLow;
1905     FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1906     FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1907                     sizeof(dataA->cAlternateFileName) );
1908     return handle;
1909 }
1910
1911
1912 /*************************************************************************
1913  *           FindFirstFileW   (KERNEL32.@)
1914  */
1915 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1916 {
1917     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1918                             FindExSearchNameMatch, NULL, 0);
1919 }
1920
1921
1922 /*************************************************************************
1923  *           FindNextFileA   (KERNEL32.@)
1924  */
1925 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1926 {
1927     WIN32_FIND_DATAW dataW;
1928
1929     if (!FindNextFileW( handle, &dataW )) return FALSE;
1930     data->dwFileAttributes = dataW.dwFileAttributes;
1931     data->ftCreationTime   = dataW.ftCreationTime;
1932     data->ftLastAccessTime = dataW.ftLastAccessTime;
1933     data->ftLastWriteTime  = dataW.ftLastWriteTime;
1934     data->nFileSizeHigh    = dataW.nFileSizeHigh;
1935     data->nFileSizeLow     = dataW.nFileSizeLow;
1936     FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1937     FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1938                     sizeof(data->cAlternateFileName) );
1939     return TRUE;
1940 }
1941
1942
1943 /**************************************************************************
1944  *           GetFileAttributesW   (KERNEL32.@)
1945  */
1946 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1947 {
1948     FILE_BASIC_INFORMATION info;
1949     UNICODE_STRING nt_name;
1950     OBJECT_ATTRIBUTES attr;
1951     NTSTATUS status;
1952
1953     TRACE("%s\n", debugstr_w(name));
1954
1955     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1956     {
1957         SetLastError( ERROR_PATH_NOT_FOUND );
1958         return INVALID_FILE_ATTRIBUTES;
1959     }
1960
1961     attr.Length = sizeof(attr);
1962     attr.RootDirectory = 0;
1963     attr.Attributes = OBJ_CASE_INSENSITIVE;
1964     attr.ObjectName = &nt_name;
1965     attr.SecurityDescriptor = NULL;
1966     attr.SecurityQualityOfService = NULL;
1967
1968     status = NtQueryAttributesFile( &attr, &info );
1969     RtlFreeUnicodeString( &nt_name );
1970
1971     if (status == STATUS_SUCCESS) return info.FileAttributes;
1972
1973     /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1974     if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1975
1976     SetLastError( RtlNtStatusToDosError(status) );
1977     return INVALID_FILE_ATTRIBUTES;
1978 }
1979
1980
1981 /**************************************************************************
1982  *           GetFileAttributesA   (KERNEL32.@)
1983  */
1984 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1985 {
1986     WCHAR *nameW;
1987
1988     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1989     return GetFileAttributesW( nameW );
1990 }
1991
1992
1993 /**************************************************************************
1994  *              SetFileAttributesW      (KERNEL32.@)
1995  */
1996 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1997 {
1998     UNICODE_STRING nt_name;
1999     OBJECT_ATTRIBUTES attr;
2000     IO_STATUS_BLOCK io;
2001     NTSTATUS status;
2002     HANDLE handle;
2003
2004     TRACE("%s %x\n", debugstr_w(name), attributes);
2005
2006     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2007     {
2008         SetLastError( ERROR_PATH_NOT_FOUND );
2009         return FALSE;
2010     }
2011
2012     attr.Length = sizeof(attr);
2013     attr.RootDirectory = 0;
2014     attr.Attributes = OBJ_CASE_INSENSITIVE;
2015     attr.ObjectName = &nt_name;
2016     attr.SecurityDescriptor = NULL;
2017     attr.SecurityQualityOfService = NULL;
2018
2019     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2020     RtlFreeUnicodeString( &nt_name );
2021
2022     if (status == STATUS_SUCCESS)
2023     {
2024         FILE_BASIC_INFORMATION info;
2025
2026         memset( &info, 0, sizeof(info) );
2027         info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL;  /* make sure it's not zero */
2028         status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2029         NtClose( handle );
2030     }
2031
2032     if (status == STATUS_SUCCESS) return TRUE;
2033     SetLastError( RtlNtStatusToDosError(status) );
2034     return FALSE;
2035 }
2036
2037
2038 /**************************************************************************
2039  *              SetFileAttributesA      (KERNEL32.@)
2040  */
2041 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2042 {
2043     WCHAR *nameW;
2044
2045     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2046     return SetFileAttributesW( nameW, attributes );
2047 }
2048
2049
2050 /**************************************************************************
2051  *           GetFileAttributesExW   (KERNEL32.@)
2052  */
2053 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2054 {
2055     FILE_NETWORK_OPEN_INFORMATION info;
2056     WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2057     UNICODE_STRING nt_name;
2058     OBJECT_ATTRIBUTES attr;
2059     NTSTATUS status;
2060     
2061     TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2062
2063     if (level != GetFileExInfoStandard)
2064     {
2065         SetLastError( ERROR_INVALID_PARAMETER );
2066         return FALSE;
2067     }
2068
2069     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2070     {
2071         SetLastError( ERROR_PATH_NOT_FOUND );
2072         return FALSE;
2073     }
2074
2075     attr.Length = sizeof(attr);
2076     attr.RootDirectory = 0;
2077     attr.Attributes = OBJ_CASE_INSENSITIVE;
2078     attr.ObjectName = &nt_name;
2079     attr.SecurityDescriptor = NULL;
2080     attr.SecurityQualityOfService = NULL;
2081
2082     status = NtQueryFullAttributesFile( &attr, &info );
2083     RtlFreeUnicodeString( &nt_name );
2084
2085     if (status != STATUS_SUCCESS)
2086     {
2087         SetLastError( RtlNtStatusToDosError(status) );
2088         return FALSE;
2089     }
2090
2091     data->dwFileAttributes = info.FileAttributes;
2092     data->ftCreationTime.dwLowDateTime    = info.CreationTime.u.LowPart;
2093     data->ftCreationTime.dwHighDateTime   = info.CreationTime.u.HighPart;
2094     data->ftLastAccessTime.dwLowDateTime  = info.LastAccessTime.u.LowPart;
2095     data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2096     data->ftLastWriteTime.dwLowDateTime   = info.LastWriteTime.u.LowPart;
2097     data->ftLastWriteTime.dwHighDateTime  = info.LastWriteTime.u.HighPart;
2098     data->nFileSizeLow                    = info.EndOfFile.u.LowPart;
2099     data->nFileSizeHigh                   = info.EndOfFile.u.HighPart;
2100     return TRUE;
2101 }
2102
2103
2104 /**************************************************************************
2105  *           GetFileAttributesExA   (KERNEL32.@)
2106  */
2107 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2108 {
2109     WCHAR *nameW;
2110
2111     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2112     return GetFileAttributesExW( nameW, level, ptr );
2113 }
2114
2115
2116 /******************************************************************************
2117  *           GetCompressedFileSizeW   (KERNEL32.@)
2118  *
2119  * Get the actual number of bytes used on disk.
2120  *
2121  * RETURNS
2122  *    Success: Low-order doubleword of number of bytes
2123  *    Failure: INVALID_FILE_SIZE
2124  */
2125 DWORD WINAPI GetCompressedFileSizeW(
2126     LPCWSTR name,       /* [in]  Pointer to name of file */
2127     LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2128 {
2129     UNICODE_STRING nt_name;
2130     OBJECT_ATTRIBUTES attr;
2131     IO_STATUS_BLOCK io;
2132     NTSTATUS status;
2133     HANDLE handle;
2134     DWORD ret = INVALID_FILE_SIZE;
2135
2136     TRACE("%s %p\n", debugstr_w(name), size_high);
2137
2138     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2139     {
2140         SetLastError( ERROR_PATH_NOT_FOUND );
2141         return INVALID_FILE_SIZE;
2142     }
2143
2144     attr.Length = sizeof(attr);
2145     attr.RootDirectory = 0;
2146     attr.Attributes = OBJ_CASE_INSENSITIVE;
2147     attr.ObjectName = &nt_name;
2148     attr.SecurityDescriptor = NULL;
2149     attr.SecurityQualityOfService = NULL;
2150
2151     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2152     RtlFreeUnicodeString( &nt_name );
2153
2154     if (status == STATUS_SUCCESS)
2155     {
2156         /* we don't support compressed files, simply return the file size */
2157         ret = GetFileSize( handle, size_high );
2158         NtClose( handle );
2159     }
2160     else SetLastError( RtlNtStatusToDosError(status) );
2161
2162     return ret;
2163 }
2164
2165
2166 /******************************************************************************
2167  *           GetCompressedFileSizeA   (KERNEL32.@)
2168  *
2169  * See GetCompressedFileSizeW.
2170  */
2171 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2172 {
2173     WCHAR *nameW;
2174
2175     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2176     return GetCompressedFileSizeW( nameW, size_high );
2177 }
2178
2179
2180 /***********************************************************************
2181  *           OpenFile   (KERNEL32.@)
2182  */
2183 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2184 {
2185     HANDLE handle;
2186     FILETIME filetime;
2187     WORD filedatetime[2];
2188
2189     if (!ofs) return HFILE_ERROR;
2190
2191     TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2192           ((mode & 0x3 )==OF_READ)?"OF_READ":
2193           ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2194           ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2195           ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2196           ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2197           ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2198           ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2199           ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2200           ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2201           ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2202           ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2203           ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2204           ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2205           ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2206           ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2207           ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2208           ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2209         );
2210
2211
2212     ofs->cBytes = sizeof(OFSTRUCT);
2213     ofs->nErrCode = 0;
2214     if (mode & OF_REOPEN) name = ofs->szPathName;
2215
2216     if (!name) return HFILE_ERROR;
2217
2218     TRACE("%s %04x\n", name, mode );
2219
2220     /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2221        Are there any cases where getting the path here is wrong?
2222        Uwe Bonnes 1997 Apr 2 */
2223     if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2224
2225     /* OF_PARSE simply fills the structure */
2226
2227     if (mode & OF_PARSE)
2228     {
2229         ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2230         TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2231         return 0;
2232     }
2233
2234     /* OF_CREATE is completely different from all other options, so
2235        handle it first */
2236
2237     if (mode & OF_CREATE)
2238     {
2239         if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2240             goto error;
2241     }
2242     else
2243     {
2244         /* Now look for the file */
2245
2246         if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2247             goto error;
2248
2249         TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2250
2251         if (mode & OF_DELETE)
2252         {
2253             if (!DeleteFileA( ofs->szPathName )) goto error;
2254             TRACE("(%s): OF_DELETE return = OK\n", name);
2255             return TRUE;
2256         }
2257
2258         handle = (HANDLE)_lopen( ofs->szPathName, mode );
2259         if (handle == INVALID_HANDLE_VALUE) goto error;
2260
2261         GetFileTime( handle, NULL, NULL, &filetime );
2262         FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2263         if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2264         {
2265             if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2266             {
2267                 CloseHandle( handle );
2268                 WARN("(%s): OF_VERIFY failed\n", name );
2269                 /* FIXME: what error here? */
2270                 SetLastError( ERROR_FILE_NOT_FOUND );
2271                 goto error;
2272             }
2273         }
2274         ofs->Reserved1 = filedatetime[0];
2275         ofs->Reserved2 = filedatetime[1];
2276     }
2277     TRACE("(%s): OK, return = %p\n", name, handle );
2278     if (mode & OF_EXIST)  /* Return TRUE instead of a handle */
2279     {
2280         CloseHandle( handle );
2281         return TRUE;
2282     }
2283     else return (HFILE)handle;
2284
2285 error:  /* We get here if there was an error opening the file */
2286     ofs->nErrCode = GetLastError();
2287     WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2288     return HFILE_ERROR;
2289 }