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