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