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