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