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