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