winex11: Fix missing unlock & free on an error path (Smatch).
[wine] / dlls / kernel32 / file.c
1 /*
2  * File handling functions
3  *
4  * Copyright 1993 John Burton
5  * Copyright 1996, 2004 Alexandre Julliard
6  * Copyright 2008 Jeff Zaroyko
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #ifdef HAVE_SYS_STAT_H
30 # include <sys/stat.h>
31 #endif
32
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "winerror.h"
36 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #include "windef.h"
39 #include "winbase.h"
40 #include "winternl.h"
41 #include "winioctl.h"
42 #include "wincon.h"
43 #include "wine/winbase16.h"
44 #include "kernel_private.h"
45
46 #include "wine/exception.h"
47 #include "wine/unicode.h"
48 #include "wine/debug.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(file);
51
52 /* info structure for FindFirstFile handle */
53 typedef struct
54 {
55     DWORD             magic;       /* magic number */
56     HANDLE            handle;      /* handle to directory */
57     CRITICAL_SECTION  cs;          /* crit section protecting this structure */
58     FINDEX_SEARCH_OPS search_op;   /* Flags passed to FindFirst.  */
59     UNICODE_STRING    mask;        /* file mask */
60     UNICODE_STRING    path;        /* NT path used to open the directory */
61     BOOL              is_root;     /* is directory the root of the drive? */
62     UINT              data_pos;    /* current position in dir data */
63     UINT              data_len;    /* length of dir data */
64     BYTE              data[8192];  /* directory data */
65 } FIND_FIRST_INFO;
66
67 #define FIND_FIRST_MAGIC  0xc0ffee11
68
69 static BOOL oem_file_apis;
70
71 static const WCHAR wildcardsW[] = { '*','?',0 };
72
73 /***********************************************************************
74  *              create_file_OF
75  *
76  * Wrapper for CreateFile that takes OF_* mode flags.
77  */
78 static HANDLE create_file_OF( LPCSTR path, INT mode )
79 {
80     DWORD access, sharing, creation;
81
82     if (mode & OF_CREATE)
83     {
84         creation = CREATE_ALWAYS;
85         access = GENERIC_READ | GENERIC_WRITE;
86     }
87     else
88     {
89         creation = OPEN_EXISTING;
90         switch(mode & 0x03)
91         {
92         case OF_READ:      access = GENERIC_READ; break;
93         case OF_WRITE:     access = GENERIC_WRITE; break;
94         case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
95         default:           access = 0; break;
96         }
97     }
98
99     switch(mode & 0x70)
100     {
101     case OF_SHARE_EXCLUSIVE:  sharing = 0; break;
102     case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
103     case OF_SHARE_DENY_READ:  sharing = FILE_SHARE_WRITE; break;
104     case OF_SHARE_DENY_NONE:
105     case OF_SHARE_COMPAT:
106     default:                  sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
107     }
108     return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
109 }
110
111
112 /***********************************************************************
113  *              check_dir_symlink
114  *
115  * Check if a dir symlink should be returned by FindNextFile.
116  */
117 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
118 {
119     UNICODE_STRING str;
120     ANSI_STRING unix_name;
121     struct stat st, parent_st;
122     BOOL ret = TRUE;
123     DWORD len;
124
125     str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
126     if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
127     memcpy( str.Buffer, info->path.Buffer, info->path.Length );
128     len = info->path.Length / sizeof(WCHAR);
129     if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
130     memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
131     str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
132
133     unix_name.Buffer = NULL;
134     if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
135         !stat( unix_name.Buffer, &st ))
136     {
137         char *p = unix_name.Buffer + unix_name.Length - 1;
138
139         /* skip trailing slashes */
140         while (p > unix_name.Buffer && *p == '/') p--;
141
142         while (ret && p > unix_name.Buffer)
143         {
144             while (p > unix_name.Buffer && *p != '/') p--;
145             while (p > unix_name.Buffer && *p == '/') p--;
146             p[1] = 0;
147             if (!stat( unix_name.Buffer, &parent_st ) &&
148                 parent_st.st_dev == st.st_dev &&
149                 parent_st.st_ino == st.st_ino)
150             {
151                 WARN( "suppressing dir symlink %s pointing to parent %s\n",
152                       debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
153                       debugstr_a( unix_name.Buffer ));
154                 ret = FALSE;
155             }
156         }
157     }
158     RtlFreeAnsiString( &unix_name );
159     RtlFreeUnicodeString( &str );
160     return ret;
161 }
162
163
164 /***********************************************************************
165  *           FILE_SetDosError
166  *
167  * Set the DOS error code from errno.
168  */
169 void FILE_SetDosError(void)
170 {
171     int save_errno = errno; /* errno gets overwritten by printf */
172
173     TRACE("errno = %d %s\n", errno, strerror(errno));
174     switch (save_errno)
175     {
176     case EAGAIN:
177         SetLastError( ERROR_SHARING_VIOLATION );
178         break;
179     case EBADF:
180         SetLastError( ERROR_INVALID_HANDLE );
181         break;
182     case ENOSPC:
183         SetLastError( ERROR_HANDLE_DISK_FULL );
184         break;
185     case EACCES:
186     case EPERM:
187     case EROFS:
188         SetLastError( ERROR_ACCESS_DENIED );
189         break;
190     case EBUSY:
191         SetLastError( ERROR_LOCK_VIOLATION );
192         break;
193     case ENOENT:
194         SetLastError( ERROR_FILE_NOT_FOUND );
195         break;
196     case EISDIR:
197         SetLastError( ERROR_CANNOT_MAKE );
198         break;
199     case ENFILE:
200     case EMFILE:
201         SetLastError( ERROR_TOO_MANY_OPEN_FILES );
202         break;
203     case EEXIST:
204         SetLastError( ERROR_FILE_EXISTS );
205         break;
206     case EINVAL:
207     case ESPIPE:
208         SetLastError( ERROR_SEEK );
209         break;
210     case ENOTEMPTY:
211         SetLastError( ERROR_DIR_NOT_EMPTY );
212         break;
213     case ENOEXEC:
214         SetLastError( ERROR_BAD_FORMAT );
215         break;
216     case ENOTDIR:
217         SetLastError( ERROR_PATH_NOT_FOUND );
218         break;
219     case EXDEV:
220         SetLastError( ERROR_NOT_SAME_DEVICE );
221         break;
222     default:
223         WARN("unknown file error: %s\n", strerror(save_errno) );
224         SetLastError( ERROR_GEN_FAILURE );
225         break;
226     }
227     errno = save_errno;
228 }
229
230
231 /***********************************************************************
232  *           FILE_name_AtoW
233  *
234  * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
235  *
236  * If alloc is FALSE uses the TEB static buffer, so it can only be used when
237  * there is no possibility for the function to do that twice, taking into
238  * account any called function.
239  */
240 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
241 {
242     ANSI_STRING str;
243     UNICODE_STRING strW, *pstrW;
244     NTSTATUS status;
245
246     RtlInitAnsiString( &str, name );
247     pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
248     if (oem_file_apis)
249         status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
250     else
251         status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
252     if (status == STATUS_SUCCESS) return pstrW->Buffer;
253
254     if (status == STATUS_BUFFER_OVERFLOW)
255         SetLastError( ERROR_FILENAME_EXCED_RANGE );
256     else
257         SetLastError( RtlNtStatusToDosError(status) );
258     return NULL;
259 }
260
261
262 /***********************************************************************
263  *           FILE_name_WtoA
264  *
265  * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
266  */
267 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
268 {
269     DWORD ret;
270
271     if (srclen < 0) srclen = strlenW( src ) + 1;
272     if (oem_file_apis)
273         RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
274     else
275         RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
276     return ret;
277 }
278
279
280 /**************************************************************************
281  *              SetFileApisToOEM   (KERNEL32.@)
282  */
283 VOID WINAPI SetFileApisToOEM(void)
284 {
285     oem_file_apis = TRUE;
286 }
287
288
289 /**************************************************************************
290  *              SetFileApisToANSI   (KERNEL32.@)
291  */
292 VOID WINAPI SetFileApisToANSI(void)
293 {
294     oem_file_apis = FALSE;
295 }
296
297
298 /******************************************************************************
299  *              AreFileApisANSI   (KERNEL32.@)
300  *
301  *  Determines if file functions are using ANSI
302  *
303  * RETURNS
304  *    TRUE:  Set of file functions is using ANSI code page
305  *    FALSE: Set of file functions is using OEM code page
306  */
307 BOOL WINAPI AreFileApisANSI(void)
308 {
309     return !oem_file_apis;
310 }
311
312
313 /**************************************************************************
314  *                      Operations on file handles                        *
315  **************************************************************************/
316
317 /******************************************************************
318  *              FILE_ReadWriteApc (internal)
319  */
320 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
321 {
322     LPOVERLAPPED_COMPLETION_ROUTINE  cr = apc_user;
323
324     cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
325 }
326
327
328 /***********************************************************************
329  *              ReadFileEx                (KERNEL32.@)
330  */
331 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
332                        LPOVERLAPPED overlapped,
333                        LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
334 {
335     LARGE_INTEGER       offset;
336     NTSTATUS            status;
337     PIO_STATUS_BLOCK    io_status;
338
339     TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
340
341     if (!overlapped)
342     {
343         SetLastError(ERROR_INVALID_PARAMETER);
344         return FALSE;
345     }
346
347     offset.u.LowPart = overlapped->u.s.Offset;
348     offset.u.HighPart = overlapped->u.s.OffsetHigh;
349     io_status = (PIO_STATUS_BLOCK)overlapped;
350     io_status->u.Status = STATUS_PENDING;
351     io_status->Information = 0;
352
353     status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
354                         io_status, buffer, bytesToRead, &offset, NULL);
355
356     if (status)
357     {
358         SetLastError( RtlNtStatusToDosError(status) );
359         return FALSE;
360     }
361     return TRUE;
362 }
363
364
365 /***********************************************************************
366  *              ReadFileScatter                (KERNEL32.@)
367  */
368 BOOL WINAPI ReadFileScatter( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
369                              LPDWORD reserved, LPOVERLAPPED overlapped )
370 {
371     PIO_STATUS_BLOCK io_status;
372     LARGE_INTEGER offset;
373     NTSTATUS status;
374
375     TRACE( "(%p %p %u %p)\n", file, segments, count, overlapped );
376
377     offset.u.LowPart = overlapped->u.s.Offset;
378     offset.u.HighPart = overlapped->u.s.OffsetHigh;
379     io_status = (PIO_STATUS_BLOCK)overlapped;
380     io_status->u.Status = STATUS_PENDING;
381     io_status->Information = 0;
382
383     status = NtReadFileScatter( file, NULL, NULL, NULL, io_status, segments, count, &offset, NULL );
384     if (status) SetLastError( RtlNtStatusToDosError(status) );
385     return !status;
386 }
387
388
389 /***********************************************************************
390  *              ReadFile                (KERNEL32.@)
391  */
392 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
393                       LPDWORD bytesRead, LPOVERLAPPED overlapped )
394 {
395     LARGE_INTEGER       offset;
396     PLARGE_INTEGER      poffset = NULL;
397     IO_STATUS_BLOCK     iosb;
398     PIO_STATUS_BLOCK    io_status = &iosb;
399     HANDLE              hEvent = 0;
400     NTSTATUS            status;
401     LPVOID              cvalue = NULL;
402
403     TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
404           bytesRead, overlapped );
405
406     if (bytesRead) *bytesRead = 0;  /* Do this before anything else */
407     if (!bytesToRead) return TRUE;
408
409     if (is_console_handle(hFile))
410         return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
411
412     if (overlapped != NULL)
413     {
414         offset.u.LowPart = overlapped->u.s.Offset;
415         offset.u.HighPart = overlapped->u.s.OffsetHigh;
416         poffset = &offset;
417         hEvent = overlapped->hEvent;
418         io_status = (PIO_STATUS_BLOCK)overlapped;
419         if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
420     }
421     io_status->u.Status = STATUS_PENDING;
422     io_status->Information = 0;
423
424     status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
425
426     if (status == STATUS_PENDING && !overlapped)
427     {
428         WaitForSingleObject( hFile, INFINITE );
429         status = io_status->u.Status;
430     }
431
432     if (status != STATUS_PENDING && bytesRead)
433         *bytesRead = io_status->Information;
434
435     if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
436     {
437         SetLastError( RtlNtStatusToDosError(status) );
438         return FALSE;
439     }
440     return TRUE;
441 }
442
443
444 /***********************************************************************
445  *              WriteFileEx                (KERNEL32.@)
446  */
447 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
448                         LPOVERLAPPED overlapped,
449                         LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
450 {
451     LARGE_INTEGER       offset;
452     NTSTATUS            status;
453     PIO_STATUS_BLOCK    io_status;
454
455     TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
456
457     if (overlapped == NULL)
458     {
459         SetLastError(ERROR_INVALID_PARAMETER);
460         return FALSE;
461     }
462     offset.u.LowPart = overlapped->u.s.Offset;
463     offset.u.HighPart = overlapped->u.s.OffsetHigh;
464
465     io_status = (PIO_STATUS_BLOCK)overlapped;
466     io_status->u.Status = STATUS_PENDING;
467     io_status->Information = 0;
468
469     status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
470                          io_status, buffer, bytesToWrite, &offset, NULL);
471
472     if (status) SetLastError( RtlNtStatusToDosError(status) );
473     return !status;
474 }
475
476
477 /***********************************************************************
478  *              WriteFileGather                (KERNEL32.@)
479  */
480 BOOL WINAPI WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
481                              LPDWORD reserved, LPOVERLAPPED overlapped )
482 {
483     PIO_STATUS_BLOCK io_status;
484     LARGE_INTEGER offset;
485     NTSTATUS status;
486
487     TRACE( "%p %p %u %p\n", file, segments, count, overlapped );
488
489     offset.u.LowPart = overlapped->u.s.Offset;
490     offset.u.HighPart = overlapped->u.s.OffsetHigh;
491     io_status = (PIO_STATUS_BLOCK)overlapped;
492     io_status->u.Status = STATUS_PENDING;
493     io_status->Information = 0;
494
495     status = NtWriteFileGather( file, NULL, NULL, NULL, io_status, segments, count, &offset, NULL );
496     if (status) SetLastError( RtlNtStatusToDosError(status) );
497     return !status;
498 }
499
500
501 /***********************************************************************
502  *             WriteFile               (KERNEL32.@)
503  */
504 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
505                        LPDWORD bytesWritten, LPOVERLAPPED overlapped )
506 {
507     HANDLE hEvent = NULL;
508     LARGE_INTEGER offset;
509     PLARGE_INTEGER poffset = NULL;
510     NTSTATUS status;
511     IO_STATUS_BLOCK iosb;
512     PIO_STATUS_BLOCK piosb = &iosb;
513     LPVOID cvalue = NULL;
514
515     TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
516
517     if (is_console_handle(hFile))
518         return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
519
520     if (overlapped)
521     {
522         offset.u.LowPart = overlapped->u.s.Offset;
523         offset.u.HighPart = overlapped->u.s.OffsetHigh;
524         poffset = &offset;
525         hEvent = overlapped->hEvent;
526         piosb = (PIO_STATUS_BLOCK)overlapped;
527         if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
528     }
529     piosb->u.Status = STATUS_PENDING;
530     piosb->Information = 0;
531
532     status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
533                          buffer, bytesToWrite, poffset, NULL);
534
535     if (status == STATUS_PENDING && !overlapped)
536     {
537         WaitForSingleObject( hFile, INFINITE );
538         status = piosb->u.Status;
539     }
540
541     if (status != STATUS_PENDING && bytesWritten)
542         *bytesWritten = piosb->Information;
543
544     if (status && status != STATUS_TIMEOUT)
545     {
546         SetLastError( RtlNtStatusToDosError(status) );
547         return FALSE;
548     }
549     return TRUE;
550 }
551
552
553 /***********************************************************************
554  *              GetOverlappedResult     (KERNEL32.@)
555  *
556  * Check the result of an Asynchronous data transfer from a file.
557  *
558  * Parameters
559  *   HANDLE hFile                 [in] handle of file to check on
560  *   LPOVERLAPPED lpOverlapped    [in/out] pointer to overlapped
561  *   LPDWORD lpTransferred        [in/out] number of bytes transferred
562  *   BOOL bWait                   [in] wait for the transfer to complete ?
563  *
564  * RETURNS
565  *   TRUE on success
566  *   FALSE on failure
567  *
568  *  If successful (and relevant) lpTransferred will hold the number of
569  *   bytes transferred during the async operation.
570  */
571 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
572                                 LPDWORD lpTransferred, BOOL bWait)
573 {
574     NTSTATUS status;
575
576     TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
577
578     status = lpOverlapped->Internal;
579     if (status == STATUS_PENDING)
580     {
581         if (!bWait)
582         {
583             SetLastError( ERROR_IO_INCOMPLETE );
584             return FALSE;
585         }
586
587         if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
588                                  INFINITE ) == WAIT_FAILED)
589             return FALSE;
590         status = lpOverlapped->Internal;
591     }
592
593     *lpTransferred = lpOverlapped->InternalHigh;
594
595     if (status) SetLastError( RtlNtStatusToDosError(status) );
596     return !status;
597 }
598
599 /***********************************************************************
600  *             CancelIoEx                 (KERNEL32.@)
601  *
602  * Cancels pending I/O operations on a file given the overlapped used.
603  *
604  * PARAMS
605  *  handle        [I] File handle.
606  *  lpOverlapped  [I,OPT] pointer to overlapped (if null, cancel all)
607  *
608  * RETURNS
609  *  Success: TRUE.
610  *  Failure: FALSE, check GetLastError().
611  */
612 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
613 {
614     IO_STATUS_BLOCK    io_status;
615
616     NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
617     if (io_status.u.Status)
618     {
619         SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
620         return FALSE;
621     }
622     return TRUE;
623 }
624
625 /***********************************************************************
626  *             CancelIo                   (KERNEL32.@)
627  *
628  * Cancels pending I/O operations initiated by the current thread on a file.
629  *
630  * PARAMS
631  *  handle [I] File handle.
632  *
633  * RETURNS
634  *  Success: TRUE.
635  *  Failure: FALSE, check GetLastError().
636  */
637 BOOL WINAPI CancelIo(HANDLE handle)
638 {
639     IO_STATUS_BLOCK    io_status;
640
641     NtCancelIoFile(handle, &io_status);
642     if (io_status.u.Status)
643     {
644         SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
645         return FALSE;
646     }
647     return TRUE;
648 }
649
650 /***********************************************************************
651  *           _hread   (KERNEL32.@)
652  */
653 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
654 {
655     return _lread( hFile, buffer, count );
656 }
657
658
659 /***********************************************************************
660  *           _hwrite   (KERNEL32.@)
661  *
662  *      experimentation yields that _lwrite:
663  *              o truncates the file at the current position with
664  *                a 0 len write
665  *              o returns 0 on a 0 length write
666  *              o works with console handles
667  *
668  */
669 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
670 {
671     DWORD result;
672
673     TRACE("%d %p %d\n", handle, buffer, count );
674
675     if (!count)
676     {
677         /* Expand or truncate at current position */
678         if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
679         return 0;
680     }
681     if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
682         return HFILE_ERROR;
683     return result;
684 }
685
686
687 /***********************************************************************
688  *           _lclose   (KERNEL32.@)
689  */
690 HFILE WINAPI _lclose( HFILE hFile )
691 {
692     TRACE("handle %d\n", hFile );
693     return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
694 }
695
696
697 /***********************************************************************
698  *           _lcreat   (KERNEL32.@)
699  */
700 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
701 {
702     HANDLE hfile;
703
704     /* Mask off all flags not explicitly allowed by the doc */
705     attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
706     TRACE("%s %02x\n", path, attr );
707     hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
708                                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
709                                CREATE_ALWAYS, attr, 0 );
710     return HandleToLong(hfile);
711 }
712
713
714 /***********************************************************************
715  *           _lopen   (KERNEL32.@)
716  */
717 HFILE WINAPI _lopen( LPCSTR path, INT mode )
718 {
719     HANDLE hfile;
720
721     TRACE("(%s,%04x)\n", debugstr_a(path), mode );
722     hfile = create_file_OF( path, mode & ~OF_CREATE );
723     return HandleToLong(hfile);
724 }
725
726 /***********************************************************************
727  *           _lread   (KERNEL32.@)
728  */
729 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
730 {
731     DWORD result;
732     if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
733         return HFILE_ERROR;
734     return result;
735 }
736
737
738 /***********************************************************************
739  *           _llseek   (KERNEL32.@)
740  */
741 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
742 {
743     return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
744 }
745
746
747 /***********************************************************************
748  *           _lwrite   (KERNEL32.@)
749  */
750 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
751 {
752     return (UINT)_hwrite( hFile, buffer, (LONG)count );
753 }
754
755
756 /***********************************************************************
757  *           FlushFileBuffers   (KERNEL32.@)
758  */
759 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
760 {
761     NTSTATUS            nts;
762     IO_STATUS_BLOCK     ioblk;
763
764     if (is_console_handle( hFile ))
765     {
766         /* this will fail (as expected) for an output handle */
767         return FlushConsoleInputBuffer( hFile );
768     }
769     nts = NtFlushBuffersFile( hFile, &ioblk );
770     if (nts != STATUS_SUCCESS)
771     {
772         SetLastError( RtlNtStatusToDosError( nts ) );
773         return FALSE;
774     }
775
776     return TRUE;
777 }
778
779
780 /***********************************************************************
781  *           GetFileType   (KERNEL32.@)
782  */
783 DWORD WINAPI GetFileType( HANDLE hFile )
784 {
785     FILE_FS_DEVICE_INFORMATION info;
786     IO_STATUS_BLOCK io;
787     NTSTATUS status;
788
789     if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
790
791     status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
792     if (status != STATUS_SUCCESS)
793     {
794         SetLastError( RtlNtStatusToDosError(status) );
795         return FILE_TYPE_UNKNOWN;
796     }
797
798     switch(info.DeviceType)
799     {
800     case FILE_DEVICE_NULL:
801     case FILE_DEVICE_SERIAL_PORT:
802     case FILE_DEVICE_PARALLEL_PORT:
803     case FILE_DEVICE_TAPE:
804     case FILE_DEVICE_UNKNOWN:
805         return FILE_TYPE_CHAR;
806     case FILE_DEVICE_NAMED_PIPE:
807         return FILE_TYPE_PIPE;
808     default:
809         return FILE_TYPE_DISK;
810     }
811 }
812
813
814 /***********************************************************************
815  *             GetFileInformationByHandle   (KERNEL32.@)
816  */
817 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
818 {
819     FILE_ALL_INFORMATION all_info;
820     IO_STATUS_BLOCK io;
821     NTSTATUS status;
822
823     status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
824     if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
825     if (status == STATUS_SUCCESS)
826     {
827         info->dwFileAttributes                = all_info.BasicInformation.FileAttributes;
828         info->ftCreationTime.dwHighDateTime   = all_info.BasicInformation.CreationTime.u.HighPart;
829         info->ftCreationTime.dwLowDateTime    = all_info.BasicInformation.CreationTime.u.LowPart;
830         info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
831         info->ftLastAccessTime.dwLowDateTime  = all_info.BasicInformation.LastAccessTime.u.LowPart;
832         info->ftLastWriteTime.dwHighDateTime  = all_info.BasicInformation.LastWriteTime.u.HighPart;
833         info->ftLastWriteTime.dwLowDateTime   = all_info.BasicInformation.LastWriteTime.u.LowPart;
834         info->dwVolumeSerialNumber            = 0;  /* FIXME */
835         info->nFileSizeHigh                   = all_info.StandardInformation.EndOfFile.u.HighPart;
836         info->nFileSizeLow                    = all_info.StandardInformation.EndOfFile.u.LowPart;
837         info->nNumberOfLinks                  = all_info.StandardInformation.NumberOfLinks;
838         info->nFileIndexHigh                  = all_info.InternalInformation.IndexNumber.u.HighPart;
839         info->nFileIndexLow                   = all_info.InternalInformation.IndexNumber.u.LowPart;
840         return TRUE;
841     }
842     SetLastError( RtlNtStatusToDosError(status) );
843     return FALSE;
844 }
845
846
847 /***********************************************************************
848  *           GetFileSize   (KERNEL32.@)
849  *
850  * Retrieve the size of a file.
851  *
852  * PARAMS
853  *  hFile        [I] File to retrieve size of.
854  *  filesizehigh [O] On return, the high bits of the file size.
855  *
856  * RETURNS
857  *  Success: The low bits of the file size.
858  *  Failure: INVALID_FILE_SIZE. As this is could also be a success value,
859  *           check GetLastError() for values other than ERROR_SUCCESS.
860  */
861 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
862 {
863     LARGE_INTEGER size;
864     if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
865     if (filesizehigh) *filesizehigh = size.u.HighPart;
866     if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
867     return size.u.LowPart;
868 }
869
870
871 /***********************************************************************
872  *           GetFileSizeEx   (KERNEL32.@)
873  *
874  * Retrieve the size of a file.
875  *
876  * PARAMS
877  *  hFile        [I] File to retrieve size of.
878  *  lpFileSIze   [O] On return, the size of the file.
879  *
880  * RETURNS
881  *  Success: TRUE.
882  *  Failure: FALSE, check GetLastError().
883  */
884 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
885 {
886     FILE_STANDARD_INFORMATION info;
887     IO_STATUS_BLOCK io;
888     NTSTATUS status;
889
890     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
891     if (status == STATUS_SUCCESS)
892     {
893         *lpFileSize = info.EndOfFile;
894         return TRUE;
895     }
896     SetLastError( RtlNtStatusToDosError(status) );
897     return FALSE;
898 }
899
900
901 /**************************************************************************
902  *           SetEndOfFile   (KERNEL32.@)
903  *
904  * Sets the current position as the end of the file.
905  *
906  * PARAMS
907  *  hFile [I] File handle.
908  *
909  * RETURNS
910  *  Success: TRUE.
911  *  Failure: FALSE, check GetLastError().
912  */
913 BOOL WINAPI SetEndOfFile( HANDLE hFile )
914 {
915     FILE_POSITION_INFORMATION pos;
916     FILE_END_OF_FILE_INFORMATION eof;
917     IO_STATUS_BLOCK io;
918     NTSTATUS status;
919
920     status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
921     if (status == STATUS_SUCCESS)
922     {
923         eof.EndOfFile = pos.CurrentByteOffset;
924         status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
925     }
926     if (status == STATUS_SUCCESS) return TRUE;
927     SetLastError( RtlNtStatusToDosError(status) );
928     return FALSE;
929 }
930
931
932 /***********************************************************************
933  *           SetFilePointer   (KERNEL32.@)
934  */
935 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
936 {
937     LARGE_INTEGER dist, newpos;
938
939     if (highword)
940     {
941         dist.u.LowPart  = distance;
942         dist.u.HighPart = *highword;
943     }
944     else dist.QuadPart = distance;
945
946     if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
947
948     if (highword) *highword = newpos.u.HighPart;
949     if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
950     return newpos.u.LowPart;
951 }
952
953
954 /***********************************************************************
955  *           SetFilePointerEx   (KERNEL32.@)
956  */
957 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
958                               LARGE_INTEGER *newpos, DWORD method )
959 {
960     LONGLONG pos;
961     IO_STATUS_BLOCK io;
962     FILE_POSITION_INFORMATION info;
963
964     switch(method)
965     {
966     case FILE_BEGIN:
967         pos = distance.QuadPart;
968         break;
969     case FILE_CURRENT:
970         if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
971             goto error;
972         pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
973         break;
974     case FILE_END:
975         {
976             FILE_END_OF_FILE_INFORMATION eof;
977             if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
978                 goto error;
979             pos = eof.EndOfFile.QuadPart + distance.QuadPart;
980         }
981         break;
982     default:
983         SetLastError( ERROR_INVALID_PARAMETER );
984         return FALSE;
985     }
986
987     if (pos < 0)
988     {
989         SetLastError( ERROR_NEGATIVE_SEEK );
990         return FALSE;
991     }
992
993     info.CurrentByteOffset.QuadPart = pos;
994     if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
995         goto error;
996     if (newpos) newpos->QuadPart = pos;
997     return TRUE;
998
999 error:
1000     SetLastError( RtlNtStatusToDosError(io.u.Status) );
1001     return FALSE;
1002 }
1003
1004 /***********************************************************************
1005  *           GetFileTime   (KERNEL32.@)
1006  */
1007 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1008                          FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1009 {
1010     FILE_BASIC_INFORMATION info;
1011     IO_STATUS_BLOCK io;
1012     NTSTATUS status;
1013
1014     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1015     if (status == STATUS_SUCCESS)
1016     {
1017         if (lpCreationTime)
1018         {
1019             lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1020             lpCreationTime->dwLowDateTime  = info.CreationTime.u.LowPart;
1021         }
1022         if (lpLastAccessTime)
1023         {
1024             lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1025             lpLastAccessTime->dwLowDateTime  = info.LastAccessTime.u.LowPart;
1026         }
1027         if (lpLastWriteTime)
1028         {
1029             lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1030             lpLastWriteTime->dwLowDateTime  = info.LastWriteTime.u.LowPart;
1031         }
1032         return TRUE;
1033     }
1034     SetLastError( RtlNtStatusToDosError(status) );
1035     return FALSE;
1036 }
1037
1038
1039 /***********************************************************************
1040  *              SetFileTime   (KERNEL32.@)
1041  */
1042 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1043                          const FILETIME *atime, const FILETIME *mtime )
1044 {
1045     FILE_BASIC_INFORMATION info;
1046     IO_STATUS_BLOCK io;
1047     NTSTATUS status;
1048
1049     memset( &info, 0, sizeof(info) );
1050     if (ctime)
1051     {
1052         info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1053         info.CreationTime.u.LowPart  = ctime->dwLowDateTime;
1054     }
1055     if (atime)
1056     {
1057         info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1058         info.LastAccessTime.u.LowPart  = atime->dwLowDateTime;
1059     }
1060     if (mtime)
1061     {
1062         info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1063         info.LastWriteTime.u.LowPart  = mtime->dwLowDateTime;
1064     }
1065
1066     status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1067     if (status == STATUS_SUCCESS) return TRUE;
1068     SetLastError( RtlNtStatusToDosError(status) );
1069     return FALSE;
1070 }
1071
1072
1073 /**************************************************************************
1074  *           LockFile   (KERNEL32.@)
1075  */
1076 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1077                       DWORD count_low, DWORD count_high )
1078 {
1079     NTSTATUS            status;
1080     LARGE_INTEGER       count, offset;
1081
1082     TRACE( "%p %x%08x %x%08x\n",
1083            hFile, offset_high, offset_low, count_high, count_low );
1084
1085     count.u.LowPart = count_low;
1086     count.u.HighPart = count_high;
1087     offset.u.LowPart = offset_low;
1088     offset.u.HighPart = offset_high;
1089
1090     status = NtLockFile( hFile, 0, NULL, NULL,
1091                          NULL, &offset, &count, NULL, TRUE, TRUE );
1092
1093     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1094     return !status;
1095 }
1096
1097
1098 /**************************************************************************
1099  * LockFileEx [KERNEL32.@]
1100  *
1101  * Locks a byte range within an open file for shared or exclusive access.
1102  *
1103  * RETURNS
1104  *   success: TRUE
1105  *   failure: FALSE
1106  *
1107  * NOTES
1108  * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1109  */
1110 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1111                         DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1112 {
1113     NTSTATUS status;
1114     LARGE_INTEGER count, offset;
1115     LPVOID   cvalue = NULL;
1116
1117     if (reserved)
1118     {
1119         SetLastError( ERROR_INVALID_PARAMETER );
1120         return FALSE;
1121     }
1122
1123     TRACE( "%p %x%08x %x%08x flags %x\n",
1124            hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset, 
1125            count_high, count_low, flags );
1126
1127     count.u.LowPart = count_low;
1128     count.u.HighPart = count_high;
1129     offset.u.LowPart = overlapped->u.s.Offset;
1130     offset.u.HighPart = overlapped->u.s.OffsetHigh;
1131
1132     if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1133
1134     status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1135                          NULL, &offset, &count, NULL,
1136                          flags & LOCKFILE_FAIL_IMMEDIATELY,
1137                          flags & LOCKFILE_EXCLUSIVE_LOCK );
1138
1139     if (status) SetLastError( RtlNtStatusToDosError(status) );
1140     return !status;
1141 }
1142
1143
1144 /**************************************************************************
1145  *           UnlockFile   (KERNEL32.@)
1146  */
1147 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1148                         DWORD count_low, DWORD count_high )
1149 {
1150     NTSTATUS    status;
1151     LARGE_INTEGER count, offset;
1152
1153     count.u.LowPart = count_low;
1154     count.u.HighPart = count_high;
1155     offset.u.LowPart = offset_low;
1156     offset.u.HighPart = offset_high;
1157
1158     status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1159     if (status) SetLastError( RtlNtStatusToDosError(status) );
1160     return !status;
1161 }
1162
1163
1164 /**************************************************************************
1165  *           UnlockFileEx   (KERNEL32.@)
1166  */
1167 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1168                           LPOVERLAPPED overlapped )
1169 {
1170     if (reserved)
1171     {
1172         SetLastError( ERROR_INVALID_PARAMETER );
1173         return FALSE;
1174     }
1175     if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1176
1177     return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1178 }
1179
1180
1181 /*************************************************************************
1182  *           SetHandleCount   (KERNEL32.@)
1183  */
1184 UINT WINAPI SetHandleCount( UINT count )
1185 {
1186     return min( 256, count );
1187 }
1188
1189
1190 /**************************************************************************
1191  *                      Operations on file names                          *
1192  **************************************************************************/
1193
1194
1195 /*************************************************************************
1196  * CreateFileW [KERNEL32.@]  Creates or opens a file or other object
1197  *
1198  * Creates or opens an object, and returns a handle that can be used to
1199  * access that object.
1200  *
1201  * PARAMS
1202  *
1203  * filename     [in] pointer to filename to be accessed
1204  * access       [in] access mode requested
1205  * sharing      [in] share mode
1206  * sa           [in] pointer to security attributes
1207  * creation     [in] how to create the file
1208  * attributes   [in] attributes for newly created file
1209  * template     [in] handle to file with extended attributes to copy
1210  *
1211  * RETURNS
1212  *   Success: Open handle to specified file
1213  *   Failure: INVALID_HANDLE_VALUE
1214  */
1215 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1216                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1217                               DWORD attributes, HANDLE template )
1218 {
1219     NTSTATUS status;
1220     UINT options;
1221     OBJECT_ATTRIBUTES attr;
1222     UNICODE_STRING nameW;
1223     IO_STATUS_BLOCK io;
1224     HANDLE ret;
1225     DWORD dosdev;
1226     const WCHAR *vxd_name = NULL;
1227     static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1228     static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1229     static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1230     SECURITY_QUALITY_OF_SERVICE qos;
1231
1232     static const UINT nt_disposition[5] =
1233     {
1234         FILE_CREATE,        /* CREATE_NEW */
1235         FILE_OVERWRITE_IF,  /* CREATE_ALWAYS */
1236         FILE_OPEN,          /* OPEN_EXISTING */
1237         FILE_OPEN_IF,       /* OPEN_ALWAYS */
1238         FILE_OVERWRITE      /* TRUNCATE_EXISTING */
1239     };
1240
1241
1242     /* sanity checks */
1243
1244     if (!filename || !filename[0])
1245     {
1246         SetLastError( ERROR_PATH_NOT_FOUND );
1247         return INVALID_HANDLE_VALUE;
1248     }
1249
1250     TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1251           (access & GENERIC_READ)?"GENERIC_READ ":"",
1252           (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1253           (!access)?"QUERY_ACCESS ":"",
1254           (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1255           (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1256           (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1257           creation, attributes);
1258
1259     /* Open a console for CONIN$ or CONOUT$ */
1260
1261     if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1262     {
1263         ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1264         goto done;
1265     }
1266
1267     if (!strncmpW(filename, bkslashes_with_dotW, 4))
1268     {
1269         static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1270         static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1271
1272         if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1273             !strncmpiW( filename + 4, pipeW, 5 ) ||
1274             !strncmpiW( filename + 4, mailslotW, 9 ))
1275         {
1276             dosdev = 0;
1277         }
1278         else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1279         {
1280             dosdev += MAKELONG( 0, 4*sizeof(WCHAR) );  /* adjust position to start of filename */
1281         }
1282         else if (GetVersion() & 0x80000000)
1283         {
1284             vxd_name = filename + 4;
1285         }
1286     }
1287     else dosdev = RtlIsDosDeviceName_U( filename );
1288
1289     if (dosdev)
1290     {
1291         static const WCHAR conW[] = {'C','O','N'};
1292
1293         if (LOWORD(dosdev) == sizeof(conW) &&
1294             !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1295         {
1296             switch (access & (GENERIC_READ|GENERIC_WRITE))
1297             {
1298             case GENERIC_READ:
1299                 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1300                 goto done;
1301             case GENERIC_WRITE:
1302                 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1303                 goto done;
1304             default:
1305                 SetLastError( ERROR_FILE_NOT_FOUND );
1306                 return INVALID_HANDLE_VALUE;
1307             }
1308         }
1309     }
1310
1311     if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1312     {
1313         SetLastError( ERROR_INVALID_PARAMETER );
1314         return INVALID_HANDLE_VALUE;
1315     }
1316
1317     if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1318     {
1319         SetLastError( ERROR_PATH_NOT_FOUND );
1320         return INVALID_HANDLE_VALUE;
1321     }
1322
1323     /* now call NtCreateFile */
1324
1325     options = 0;
1326     if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1327         options |= FILE_OPEN_FOR_BACKUP_INTENT;
1328     else
1329         options |= FILE_NON_DIRECTORY_FILE;
1330     if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1331     {
1332         options |= FILE_DELETE_ON_CLOSE;
1333         access |= DELETE;
1334     }
1335     if (attributes & FILE_FLAG_NO_BUFFERING)
1336         options |= FILE_NO_INTERMEDIATE_BUFFERING;
1337     if (!(attributes & FILE_FLAG_OVERLAPPED))
1338         options |= FILE_SYNCHRONOUS_IO_ALERT;
1339     if (attributes & FILE_FLAG_RANDOM_ACCESS)
1340         options |= FILE_RANDOM_ACCESS;
1341     attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1342
1343     attr.Length = sizeof(attr);
1344     attr.RootDirectory = 0;
1345     attr.Attributes = OBJ_CASE_INSENSITIVE;
1346     attr.ObjectName = &nameW;
1347     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1348     if (attributes & SECURITY_SQOS_PRESENT)
1349     {
1350         qos.Length = sizeof(qos);
1351         qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1352         qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1353         qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1354         attr.SecurityQualityOfService = &qos;
1355     }
1356     else
1357         attr.SecurityQualityOfService = NULL;
1358
1359     if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1360
1361     status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1362                            sharing, nt_disposition[creation - CREATE_NEW],
1363                            options, NULL, 0 );
1364     if (status)
1365     {
1366         if (vxd_name && vxd_name[0] && (ret = VXD_Open( vxd_name, access, sa ))) goto done;
1367
1368         WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1369         ret = INVALID_HANDLE_VALUE;
1370
1371         /* In the case file creation was rejected due to CREATE_NEW flag
1372          * was specified and file with that name already exists, correct
1373          * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1374          * Note: RtlNtStatusToDosError is not the subject to blame here.
1375          */
1376         if (status == STATUS_OBJECT_NAME_COLLISION)
1377             SetLastError( ERROR_FILE_EXISTS );
1378         else
1379             SetLastError( RtlNtStatusToDosError(status) );
1380     }
1381     else
1382     {
1383         if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1384             (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1385             SetLastError( ERROR_ALREADY_EXISTS );
1386         else
1387             SetLastError( 0 );
1388     }
1389     RtlFreeUnicodeString( &nameW );
1390
1391  done:
1392     if (!ret) ret = INVALID_HANDLE_VALUE;
1393     TRACE("returning %p\n", ret);
1394     return ret;
1395 }
1396
1397
1398
1399 /*************************************************************************
1400  *              CreateFileA              (KERNEL32.@)
1401  *
1402  * See CreateFileW.
1403  */
1404 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1405                            LPSECURITY_ATTRIBUTES sa, DWORD creation,
1406                            DWORD attributes, HANDLE template)
1407 {
1408     WCHAR *nameW;
1409
1410     if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1411     return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1412 }
1413
1414
1415 /***********************************************************************
1416  *           DeleteFileW   (KERNEL32.@)
1417  *
1418  * Delete a file.
1419  *
1420  * PARAMS
1421  *  path [I] Path to the file to delete.
1422  *
1423  * RETURNS
1424  *  Success: TRUE.
1425  *  Failure: FALSE, check GetLastError().
1426  */
1427 BOOL WINAPI DeleteFileW( LPCWSTR path )
1428 {
1429     UNICODE_STRING nameW;
1430     OBJECT_ATTRIBUTES attr;
1431     NTSTATUS status;
1432     HANDLE hFile;
1433     IO_STATUS_BLOCK io;
1434
1435     TRACE("%s\n", debugstr_w(path) );
1436
1437     if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1438     {
1439         SetLastError( ERROR_PATH_NOT_FOUND );
1440         return FALSE;
1441     }
1442
1443     attr.Length = sizeof(attr);
1444     attr.RootDirectory = 0;
1445     attr.Attributes = OBJ_CASE_INSENSITIVE;
1446     attr.ObjectName = &nameW;
1447     attr.SecurityDescriptor = NULL;
1448     attr.SecurityQualityOfService = NULL;
1449
1450     status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1451                           &attr, &io, NULL, 0,
1452                           FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1453                           FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1454     if (status == STATUS_SUCCESS) status = NtClose(hFile);
1455
1456     RtlFreeUnicodeString( &nameW );
1457     if (status)
1458     {
1459         SetLastError( RtlNtStatusToDosError(status) );
1460         return FALSE;
1461     }
1462     return TRUE;
1463 }
1464
1465
1466 /***********************************************************************
1467  *           DeleteFileA   (KERNEL32.@)
1468  *
1469  * See DeleteFileW.
1470  */
1471 BOOL WINAPI DeleteFileA( LPCSTR path )
1472 {
1473     WCHAR *pathW;
1474
1475     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1476     return DeleteFileW( pathW );
1477 }
1478
1479
1480 /**************************************************************************
1481  *           ReplaceFileW   (KERNEL32.@)
1482  *           ReplaceFile    (KERNEL32.@)
1483  */
1484 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1485                          LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1486                          LPVOID lpExclude, LPVOID lpReserved)
1487 {
1488     UNICODE_STRING nt_replaced_name, nt_replacement_name;
1489     ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1490     HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1491     DWORD error = ERROR_SUCCESS;
1492     UINT replaced_flags;
1493     BOOL ret = FALSE;
1494     NTSTATUS status;
1495     IO_STATUS_BLOCK io;
1496     OBJECT_ATTRIBUTES attr;
1497
1498     if (dwReplaceFlags)
1499         FIXME("Ignoring flags %x\n", dwReplaceFlags);
1500
1501     /* First two arguments are mandatory */
1502     if (!lpReplacedFileName || !lpReplacementFileName)
1503     {
1504         SetLastError(ERROR_INVALID_PARAMETER);
1505         return FALSE;
1506     }
1507
1508     unix_replaced_name.Buffer = NULL;
1509     unix_replacement_name.Buffer = NULL;
1510     unix_backup_name.Buffer = NULL;
1511
1512     attr.Length = sizeof(attr);
1513     attr.RootDirectory = 0;
1514     attr.Attributes = OBJ_CASE_INSENSITIVE;
1515     attr.ObjectName = NULL;
1516     attr.SecurityDescriptor = NULL;
1517     attr.SecurityQualityOfService = NULL;
1518
1519     /* Open the "replaced" file for reading and writing */
1520     if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1521     {
1522         error = ERROR_PATH_NOT_FOUND;
1523         goto fail;
1524     }
1525     replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1526     attr.ObjectName = &nt_replaced_name;
1527     status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1528                         &attr, &io,
1529                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1530                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1531     if (status == STATUS_SUCCESS)
1532         status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1533     RtlFreeUnicodeString(&nt_replaced_name);
1534     if (status != STATUS_SUCCESS)
1535     {
1536         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1537             error = ERROR_FILE_NOT_FOUND;
1538         else
1539             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1540         goto fail;
1541     }
1542
1543     /*
1544      * Open the replacement file for reading, writing, and deleting
1545      * (writing and deleting are needed when finished)
1546      */
1547     if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1548     {
1549         error = ERROR_PATH_NOT_FOUND;
1550         goto fail;
1551     }
1552     attr.ObjectName = &nt_replacement_name;
1553     status = NtOpenFile(&hReplacement,
1554                         GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1555                         &attr, &io, 0,
1556                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1557     if (status == STATUS_SUCCESS)
1558         status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1559     RtlFreeUnicodeString(&nt_replacement_name);
1560     if (status != STATUS_SUCCESS)
1561     {
1562         error = RtlNtStatusToDosError(status);
1563         goto fail;
1564     }
1565
1566     /* If the user wants a backup then that needs to be performed first */
1567     if (lpBackupFileName)
1568     {
1569         UNICODE_STRING nt_backup_name;
1570         FILE_BASIC_INFORMATION replaced_info;
1571
1572         /* Obtain the file attributes from the "replaced" file */
1573         status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1574                                         sizeof(replaced_info),
1575                                         FileBasicInformation);
1576         if (status != STATUS_SUCCESS)
1577         {
1578             error = RtlNtStatusToDosError(status);
1579             goto fail;
1580         }
1581
1582         if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1583         {
1584             error = ERROR_PATH_NOT_FOUND;
1585             goto fail;
1586         }
1587         attr.ObjectName = &nt_backup_name;
1588         /* Open the backup with permissions to write over it */
1589         status = NtCreateFile(&hBackup, GENERIC_WRITE,
1590                               &attr, &io, NULL, replaced_info.FileAttributes,
1591                               FILE_SHARE_WRITE, FILE_OPEN_IF,
1592                               FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1593                               NULL, 0);
1594         if (status == STATUS_SUCCESS)
1595             status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1596         if (status != STATUS_SUCCESS)
1597         {
1598             error = RtlNtStatusToDosError(status);
1599             goto fail;
1600         }
1601
1602         /* If an existing backup exists then copy over it */
1603         if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1604         {
1605             error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1606             goto fail;
1607         }
1608     }
1609
1610     /*
1611      * Now that the backup has been performed (if requested), copy the replacement
1612      * into place
1613      */
1614     if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1615     {
1616         if (errno == EACCES)
1617         {
1618             /* Inappropriate permissions on "replaced", rename will fail */
1619             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1620             goto fail;
1621         }
1622         /* on failure we need to indicate whether a backup was made */
1623         if (!lpBackupFileName)
1624             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1625         else
1626             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1627         goto fail;
1628     }
1629     /* Success! */
1630     ret = TRUE;
1631
1632     /* Perform resource cleanup */
1633 fail:
1634     if (hBackup) CloseHandle(hBackup);
1635     if (hReplaced) CloseHandle(hReplaced);
1636     if (hReplacement) CloseHandle(hReplacement);
1637     RtlFreeAnsiString(&unix_backup_name);
1638     RtlFreeAnsiString(&unix_replacement_name);
1639     RtlFreeAnsiString(&unix_replaced_name);
1640
1641     /* If there was an error, set the error code */
1642     if(!ret)
1643         SetLastError(error);
1644     return ret;
1645 }
1646
1647
1648 /**************************************************************************
1649  *           ReplaceFileA (KERNEL32.@)
1650  */
1651 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1652                          LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1653                          LPVOID lpExclude, LPVOID lpReserved)
1654 {
1655     WCHAR *replacedW, *replacementW, *backupW = NULL;
1656     BOOL ret;
1657
1658     /* This function only makes sense when the first two parameters are defined */
1659     if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1660     {
1661         SetLastError(ERROR_INVALID_PARAMETER);
1662         return FALSE;
1663     }
1664     if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1665     {
1666         HeapFree( GetProcessHeap(), 0, replacedW );
1667         SetLastError(ERROR_INVALID_PARAMETER);
1668         return FALSE;
1669     }
1670     /* The backup parameter, however, is optional */
1671     if (lpBackupFileName)
1672     {
1673         if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1674         {
1675             HeapFree( GetProcessHeap(), 0, replacedW );
1676             HeapFree( GetProcessHeap(), 0, replacementW );
1677             SetLastError(ERROR_INVALID_PARAMETER);
1678             return FALSE;
1679         }
1680     }
1681     ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1682     HeapFree( GetProcessHeap(), 0, replacedW );
1683     HeapFree( GetProcessHeap(), 0, replacementW );
1684     HeapFree( GetProcessHeap(), 0, backupW );
1685     return ret;
1686 }
1687
1688
1689 /*************************************************************************
1690  *           FindFirstFileExW  (KERNEL32.@)
1691  *
1692  * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1693  * results as FindExSearchNameMatch
1694  */
1695 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1696                                 LPVOID data, FINDEX_SEARCH_OPS search_op,
1697                                 LPVOID filter, DWORD flags)
1698 {
1699     WCHAR *mask, *p;
1700     FIND_FIRST_INFO *info = NULL;
1701     UNICODE_STRING nt_name;
1702     OBJECT_ATTRIBUTES attr;
1703     IO_STATUS_BLOCK io;
1704     NTSTATUS status;
1705     DWORD device = 0;
1706
1707     TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1708
1709     if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1710         || flags != 0)
1711     {
1712         FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1713         return INVALID_HANDLE_VALUE;
1714     }
1715     if (level != FindExInfoStandard)
1716     {
1717         FIXME("info level %d not implemented\n", level );
1718         return INVALID_HANDLE_VALUE;
1719     }
1720
1721     if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1722     {
1723         SetLastError( ERROR_PATH_NOT_FOUND );
1724         return INVALID_HANDLE_VALUE;
1725     }
1726
1727     if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1728     {
1729         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1730         goto error;
1731     }
1732
1733     if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1734     {
1735         static const WCHAR dotW[] = {'.',0};
1736         WCHAR *dir = NULL;
1737
1738         /* we still need to check that the directory can be opened */
1739
1740         if (HIWORD(device))
1741         {
1742             if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1743             {
1744                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1745                 goto error;
1746             }
1747             memcpy( dir, filename, HIWORD(device) );
1748             dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1749         }
1750         RtlFreeUnicodeString( &nt_name );
1751         if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1752         {
1753             HeapFree( GetProcessHeap(), 0, dir );
1754             SetLastError( ERROR_PATH_NOT_FOUND );
1755             goto error;
1756         }
1757         HeapFree( GetProcessHeap(), 0, dir );
1758         RtlInitUnicodeString( &info->mask, NULL );
1759     }
1760     else if (!mask || !*mask)
1761     {
1762         SetLastError( ERROR_FILE_NOT_FOUND );
1763         goto error;
1764     }
1765     else
1766     {
1767         if (!RtlCreateUnicodeString( &info->mask, mask ))
1768         {
1769             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1770             goto error;
1771         }
1772
1773         /* truncate dir name before mask */
1774         *mask = 0;
1775         nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1776     }
1777
1778     /* check if path is the root of the drive */
1779     info->is_root = FALSE;
1780     p = nt_name.Buffer + 4;  /* skip \??\ prefix */
1781     if (p[0] && p[1] == ':')
1782     {
1783         p += 2;
1784         while (*p == '\\') p++;
1785         info->is_root = (*p == 0);
1786     }
1787
1788     attr.Length = sizeof(attr);
1789     attr.RootDirectory = 0;
1790     attr.Attributes = OBJ_CASE_INSENSITIVE;
1791     attr.ObjectName = &nt_name;
1792     attr.SecurityDescriptor = NULL;
1793     attr.SecurityQualityOfService = NULL;
1794
1795     status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1796                          FILE_SHARE_READ | FILE_SHARE_WRITE,
1797                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1798
1799     if (status != STATUS_SUCCESS)
1800     {
1801         RtlFreeUnicodeString( &info->mask );
1802         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1803             SetLastError( ERROR_PATH_NOT_FOUND );
1804         else
1805             SetLastError( RtlNtStatusToDosError(status) );
1806         goto error;
1807     }
1808
1809     RtlInitializeCriticalSection( &info->cs );
1810     info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1811     info->path     = nt_name;
1812     info->magic    = FIND_FIRST_MAGIC;
1813     info->data_pos = 0;
1814     info->data_len = 0;
1815     info->search_op = search_op;
1816
1817     if (device)
1818     {
1819         WIN32_FIND_DATAW *wfd = data;
1820
1821         memset( wfd, 0, sizeof(*wfd) );
1822         memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1823         wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1824         CloseHandle( info->handle );
1825         info->handle = 0;
1826     }
1827     else
1828     {
1829         IO_STATUS_BLOCK io;
1830
1831         NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1832                               FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1833         if (io.u.Status)
1834         {
1835             FindClose( info );
1836             SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1837             return INVALID_HANDLE_VALUE;
1838         }
1839         info->data_len = io.Information;
1840         if (!FindNextFileW( info, data ))
1841         {
1842             TRACE( "%s not found\n", debugstr_w(filename) );
1843             FindClose( info );
1844             SetLastError( ERROR_FILE_NOT_FOUND );
1845             return INVALID_HANDLE_VALUE;
1846         }
1847         if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1848         {
1849             /* we can't find two files with the same name */
1850             CloseHandle( info->handle );
1851             info->handle = 0;
1852         }
1853     }
1854     return info;
1855
1856 error:
1857     HeapFree( GetProcessHeap(), 0, info );
1858     RtlFreeUnicodeString( &nt_name );
1859     return INVALID_HANDLE_VALUE;
1860 }
1861
1862
1863 /*************************************************************************
1864  *           FindNextFileW   (KERNEL32.@)
1865  */
1866 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1867 {
1868     FIND_FIRST_INFO *info;
1869     FILE_BOTH_DIR_INFORMATION *dir_info;
1870     BOOL ret = FALSE;
1871
1872     TRACE("%p %p\n", handle, data);
1873
1874     if (!handle || handle == INVALID_HANDLE_VALUE)
1875     {
1876         SetLastError( ERROR_INVALID_HANDLE );
1877         return ret;
1878     }
1879     info = handle;
1880     if (info->magic != FIND_FIRST_MAGIC)
1881     {
1882         SetLastError( ERROR_INVALID_HANDLE );
1883         return ret;
1884     }
1885
1886     RtlEnterCriticalSection( &info->cs );
1887
1888     if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1889     else for (;;)
1890     {
1891         if (info->data_pos >= info->data_len)  /* need to read some more data */
1892         {
1893             IO_STATUS_BLOCK io;
1894
1895             NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1896                                   FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1897             if (io.u.Status)
1898             {
1899                 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1900                 if (io.u.Status == STATUS_NO_MORE_FILES)
1901                 {
1902                     CloseHandle( info->handle );
1903                     info->handle = 0;
1904                 }
1905                 break;
1906             }
1907             info->data_len = io.Information;
1908             info->data_pos = 0;
1909         }
1910
1911         dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1912
1913         if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1914         else info->data_pos = info->data_len;
1915
1916         /* don't return '.' and '..' in the root of the drive */
1917         if (info->is_root)
1918         {
1919             if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1920             if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1921                 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1922         }
1923
1924         /* check for dir symlink */
1925         if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1926             (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1927             strpbrkW( info->mask.Buffer, wildcardsW ))
1928         {
1929             if (!check_dir_symlink( info, dir_info )) continue;
1930         }
1931
1932         data->dwFileAttributes = dir_info->FileAttributes;
1933         data->ftCreationTime   = *(FILETIME *)&dir_info->CreationTime;
1934         data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1935         data->ftLastWriteTime  = *(FILETIME *)&dir_info->LastWriteTime;
1936         data->nFileSizeHigh    = dir_info->EndOfFile.QuadPart >> 32;
1937         data->nFileSizeLow     = (DWORD)dir_info->EndOfFile.QuadPart;
1938         data->dwReserved0      = 0;
1939         data->dwReserved1      = 0;
1940
1941         memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1942         data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1943         memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1944         data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1945
1946         TRACE("returning %s (%s)\n",
1947               debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1948
1949         ret = TRUE;
1950         break;
1951     }
1952
1953     RtlLeaveCriticalSection( &info->cs );
1954     return ret;
1955 }
1956
1957
1958 /*************************************************************************
1959  *           FindClose   (KERNEL32.@)
1960  */
1961 BOOL WINAPI FindClose( HANDLE handle )
1962 {
1963     FIND_FIRST_INFO *info = handle;
1964
1965     if (!handle || handle == INVALID_HANDLE_VALUE)
1966     {
1967         SetLastError( ERROR_INVALID_HANDLE );
1968         return FALSE;
1969     }
1970
1971     __TRY
1972     {
1973         if (info->magic == FIND_FIRST_MAGIC)
1974         {
1975             RtlEnterCriticalSection( &info->cs );
1976             if (info->magic == FIND_FIRST_MAGIC)  /* in case someone else freed it in the meantime */
1977             {
1978                 info->magic = 0;
1979                 if (info->handle) CloseHandle( info->handle );
1980                 info->handle = 0;
1981                 RtlFreeUnicodeString( &info->mask );
1982                 info->mask.Buffer = NULL;
1983                 RtlFreeUnicodeString( &info->path );
1984                 info->data_pos = 0;
1985                 info->data_len = 0;
1986                 RtlLeaveCriticalSection( &info->cs );
1987                 info->cs.DebugInfo->Spare[0] = 0;
1988                 RtlDeleteCriticalSection( &info->cs );
1989                 HeapFree( GetProcessHeap(), 0, info );
1990             }
1991         }
1992     }
1993     __EXCEPT_PAGE_FAULT
1994     {
1995         WARN("Illegal handle %p\n", handle);
1996         SetLastError( ERROR_INVALID_HANDLE );
1997         return FALSE;
1998     }
1999     __ENDTRY
2000
2001     return TRUE;
2002 }
2003
2004
2005 /*************************************************************************
2006  *           FindFirstFileA   (KERNEL32.@)
2007  */
2008 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2009 {
2010     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2011                             FindExSearchNameMatch, NULL, 0);
2012 }
2013
2014 /*************************************************************************
2015  *           FindFirstFileExA   (KERNEL32.@)
2016  */
2017 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2018                                 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2019                                 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2020 {
2021     HANDLE handle;
2022     WIN32_FIND_DATAA *dataA;
2023     WIN32_FIND_DATAW dataW;
2024     WCHAR *nameW;
2025
2026     if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2027
2028     handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2029     if (handle == INVALID_HANDLE_VALUE) return handle;
2030
2031     dataA = lpFindFileData;
2032     dataA->dwFileAttributes = dataW.dwFileAttributes;
2033     dataA->ftCreationTime   = dataW.ftCreationTime;
2034     dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2035     dataA->ftLastWriteTime  = dataW.ftLastWriteTime;
2036     dataA->nFileSizeHigh    = dataW.nFileSizeHigh;
2037     dataA->nFileSizeLow     = dataW.nFileSizeLow;
2038     FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2039     FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2040                     sizeof(dataA->cAlternateFileName) );
2041     return handle;
2042 }
2043
2044
2045 /*************************************************************************
2046  *           FindFirstFileW   (KERNEL32.@)
2047  */
2048 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2049 {
2050     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2051                             FindExSearchNameMatch, NULL, 0);
2052 }
2053
2054
2055 /*************************************************************************
2056  *           FindNextFileA   (KERNEL32.@)
2057  */
2058 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2059 {
2060     WIN32_FIND_DATAW dataW;
2061
2062     if (!FindNextFileW( handle, &dataW )) return FALSE;
2063     data->dwFileAttributes = dataW.dwFileAttributes;
2064     data->ftCreationTime   = dataW.ftCreationTime;
2065     data->ftLastAccessTime = dataW.ftLastAccessTime;
2066     data->ftLastWriteTime  = dataW.ftLastWriteTime;
2067     data->nFileSizeHigh    = dataW.nFileSizeHigh;
2068     data->nFileSizeLow     = dataW.nFileSizeLow;
2069     FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2070     FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2071                     sizeof(data->cAlternateFileName) );
2072     return TRUE;
2073 }
2074
2075
2076 /**************************************************************************
2077  *           GetFileAttributesW   (KERNEL32.@)
2078  */
2079 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2080 {
2081     FILE_BASIC_INFORMATION info;
2082     UNICODE_STRING nt_name;
2083     OBJECT_ATTRIBUTES attr;
2084     NTSTATUS status;
2085
2086     TRACE("%s\n", debugstr_w(name));
2087
2088     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2089     {
2090         SetLastError( ERROR_PATH_NOT_FOUND );
2091         return INVALID_FILE_ATTRIBUTES;
2092     }
2093
2094     attr.Length = sizeof(attr);
2095     attr.RootDirectory = 0;
2096     attr.Attributes = OBJ_CASE_INSENSITIVE;
2097     attr.ObjectName = &nt_name;
2098     attr.SecurityDescriptor = NULL;
2099     attr.SecurityQualityOfService = NULL;
2100
2101     status = NtQueryAttributesFile( &attr, &info );
2102     RtlFreeUnicodeString( &nt_name );
2103
2104     if (status == STATUS_SUCCESS) return info.FileAttributes;
2105
2106     /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2107     if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2108
2109     SetLastError( RtlNtStatusToDosError(status) );
2110     return INVALID_FILE_ATTRIBUTES;
2111 }
2112
2113
2114 /**************************************************************************
2115  *           GetFileAttributesA   (KERNEL32.@)
2116  */
2117 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2118 {
2119     WCHAR *nameW;
2120
2121     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2122     return GetFileAttributesW( nameW );
2123 }
2124
2125
2126 /**************************************************************************
2127  *              SetFileAttributesW      (KERNEL32.@)
2128  */
2129 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2130 {
2131     UNICODE_STRING nt_name;
2132     OBJECT_ATTRIBUTES attr;
2133     IO_STATUS_BLOCK io;
2134     NTSTATUS status;
2135     HANDLE handle;
2136
2137     TRACE("%s %x\n", debugstr_w(name), attributes);
2138
2139     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2140     {
2141         SetLastError( ERROR_PATH_NOT_FOUND );
2142         return FALSE;
2143     }
2144
2145     attr.Length = sizeof(attr);
2146     attr.RootDirectory = 0;
2147     attr.Attributes = OBJ_CASE_INSENSITIVE;
2148     attr.ObjectName = &nt_name;
2149     attr.SecurityDescriptor = NULL;
2150     attr.SecurityQualityOfService = NULL;
2151
2152     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2153     RtlFreeUnicodeString( &nt_name );
2154
2155     if (status == STATUS_SUCCESS)
2156     {
2157         FILE_BASIC_INFORMATION info;
2158
2159         memset( &info, 0, sizeof(info) );
2160         info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL;  /* make sure it's not zero */
2161         status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2162         NtClose( handle );
2163     }
2164
2165     if (status == STATUS_SUCCESS) return TRUE;
2166     SetLastError( RtlNtStatusToDosError(status) );
2167     return FALSE;
2168 }
2169
2170
2171 /**************************************************************************
2172  *              SetFileAttributesA      (KERNEL32.@)
2173  */
2174 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2175 {
2176     WCHAR *nameW;
2177
2178     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2179     return SetFileAttributesW( nameW, attributes );
2180 }
2181
2182
2183 /**************************************************************************
2184  *           GetFileAttributesExW   (KERNEL32.@)
2185  */
2186 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2187 {
2188     FILE_NETWORK_OPEN_INFORMATION info;
2189     WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2190     UNICODE_STRING nt_name;
2191     OBJECT_ATTRIBUTES attr;
2192     NTSTATUS status;
2193     
2194     TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2195
2196     if (level != GetFileExInfoStandard)
2197     {
2198         SetLastError( ERROR_INVALID_PARAMETER );
2199         return FALSE;
2200     }
2201
2202     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2203     {
2204         SetLastError( ERROR_PATH_NOT_FOUND );
2205         return FALSE;
2206     }
2207
2208     attr.Length = sizeof(attr);
2209     attr.RootDirectory = 0;
2210     attr.Attributes = OBJ_CASE_INSENSITIVE;
2211     attr.ObjectName = &nt_name;
2212     attr.SecurityDescriptor = NULL;
2213     attr.SecurityQualityOfService = NULL;
2214
2215     status = NtQueryFullAttributesFile( &attr, &info );
2216     RtlFreeUnicodeString( &nt_name );
2217
2218     if (status != STATUS_SUCCESS)
2219     {
2220         SetLastError( RtlNtStatusToDosError(status) );
2221         return FALSE;
2222     }
2223
2224     data->dwFileAttributes = info.FileAttributes;
2225     data->ftCreationTime.dwLowDateTime    = info.CreationTime.u.LowPart;
2226     data->ftCreationTime.dwHighDateTime   = info.CreationTime.u.HighPart;
2227     data->ftLastAccessTime.dwLowDateTime  = info.LastAccessTime.u.LowPart;
2228     data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2229     data->ftLastWriteTime.dwLowDateTime   = info.LastWriteTime.u.LowPart;
2230     data->ftLastWriteTime.dwHighDateTime  = info.LastWriteTime.u.HighPart;
2231     data->nFileSizeLow                    = info.EndOfFile.u.LowPart;
2232     data->nFileSizeHigh                   = info.EndOfFile.u.HighPart;
2233     return TRUE;
2234 }
2235
2236
2237 /**************************************************************************
2238  *           GetFileAttributesExA   (KERNEL32.@)
2239  */
2240 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2241 {
2242     WCHAR *nameW;
2243
2244     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2245     return GetFileAttributesExW( nameW, level, ptr );
2246 }
2247
2248
2249 /******************************************************************************
2250  *           GetCompressedFileSizeW   (KERNEL32.@)
2251  *
2252  * Get the actual number of bytes used on disk.
2253  *
2254  * RETURNS
2255  *    Success: Low-order doubleword of number of bytes
2256  *    Failure: INVALID_FILE_SIZE
2257  */
2258 DWORD WINAPI GetCompressedFileSizeW(
2259     LPCWSTR name,       /* [in]  Pointer to name of file */
2260     LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2261 {
2262     UNICODE_STRING nt_name;
2263     OBJECT_ATTRIBUTES attr;
2264     IO_STATUS_BLOCK io;
2265     NTSTATUS status;
2266     HANDLE handle;
2267     DWORD ret = INVALID_FILE_SIZE;
2268
2269     TRACE("%s %p\n", debugstr_w(name), size_high);
2270
2271     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2272     {
2273         SetLastError( ERROR_PATH_NOT_FOUND );
2274         return INVALID_FILE_SIZE;
2275     }
2276
2277     attr.Length = sizeof(attr);
2278     attr.RootDirectory = 0;
2279     attr.Attributes = OBJ_CASE_INSENSITIVE;
2280     attr.ObjectName = &nt_name;
2281     attr.SecurityDescriptor = NULL;
2282     attr.SecurityQualityOfService = NULL;
2283
2284     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2285     RtlFreeUnicodeString( &nt_name );
2286
2287     if (status == STATUS_SUCCESS)
2288     {
2289         /* we don't support compressed files, simply return the file size */
2290         ret = GetFileSize( handle, size_high );
2291         NtClose( handle );
2292     }
2293     else SetLastError( RtlNtStatusToDosError(status) );
2294
2295     return ret;
2296 }
2297
2298
2299 /******************************************************************************
2300  *           GetCompressedFileSizeA   (KERNEL32.@)
2301  *
2302  * See GetCompressedFileSizeW.
2303  */
2304 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2305 {
2306     WCHAR *nameW;
2307
2308     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2309     return GetCompressedFileSizeW( nameW, size_high );
2310 }
2311
2312
2313 /***********************************************************************
2314  *              OpenVxDHandle (KERNEL32.@)
2315  *
2316  *      This function is supposed to return the corresponding Ring 0
2317  *      ("kernel") handle for a Ring 3 handle in Win9x.
2318  *      Evidently, Wine will have problems with this. But we try anyway,
2319  *      maybe it helps...
2320  */
2321 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2322 {
2323     FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2324     return hHandleRing3;
2325 }
2326
2327
2328 /****************************************************************************
2329  *              DeviceIoControl (KERNEL32.@)
2330  */
2331 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2332                             LPVOID lpvInBuffer, DWORD cbInBuffer,
2333                             LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2334                             LPDWORD lpcbBytesReturned,
2335                             LPOVERLAPPED lpOverlapped)
2336 {
2337     NTSTATUS status;
2338
2339     TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2340            hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2341            lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2342
2343     /* Check if this is a user defined control code for a VxD */
2344
2345     if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2346     {
2347         DeviceIoProc proc = VXD_get_proc( hDevice );
2348         if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2349                                lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2350     }
2351
2352     /* Not a VxD, let ntdll handle it */
2353
2354     if (lpOverlapped)
2355     {
2356         LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2357         lpOverlapped->Internal = STATUS_PENDING;
2358         lpOverlapped->InternalHigh = 0;
2359         if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2360             status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2361                                      NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2362                                      dwIoControlCode, lpvInBuffer, cbInBuffer,
2363                                      lpvOutBuffer, cbOutBuffer);
2364         else
2365             status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2366                                            NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2367                                            dwIoControlCode, lpvInBuffer, cbInBuffer,
2368                                            lpvOutBuffer, cbOutBuffer);
2369         if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2370     }
2371     else
2372     {
2373         IO_STATUS_BLOCK iosb;
2374
2375         if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2376             status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2377                                      dwIoControlCode, lpvInBuffer, cbInBuffer,
2378                                      lpvOutBuffer, cbOutBuffer);
2379         else
2380             status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2381                                            dwIoControlCode, lpvInBuffer, cbInBuffer,
2382                                            lpvOutBuffer, cbOutBuffer);
2383         if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2384     }
2385     if (status) SetLastError( RtlNtStatusToDosError(status) );
2386     return !status;
2387 }
2388
2389
2390 /***********************************************************************
2391  *           OpenFile   (KERNEL32.@)
2392  */
2393 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2394 {
2395     HANDLE handle;
2396     FILETIME filetime;
2397     WORD filedatetime[2];
2398
2399     if (!ofs) return HFILE_ERROR;
2400
2401     TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2402           ((mode & 0x3 )==OF_READ)?"OF_READ":
2403           ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2404           ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2405           ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2406           ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2407           ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2408           ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2409           ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2410           ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2411           ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2412           ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2413           ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2414           ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2415           ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2416           ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2417           ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2418           ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2419         );
2420
2421
2422     ofs->cBytes = sizeof(OFSTRUCT);
2423     ofs->nErrCode = 0;
2424     if (mode & OF_REOPEN) name = ofs->szPathName;
2425
2426     if (!name) return HFILE_ERROR;
2427
2428     TRACE("%s %04x\n", name, mode );
2429
2430     /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2431        Are there any cases where getting the path here is wrong?
2432        Uwe Bonnes 1997 Apr 2 */
2433     if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2434
2435     /* OF_PARSE simply fills the structure */
2436
2437     if (mode & OF_PARSE)
2438     {
2439         ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2440         TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2441         return 0;
2442     }
2443
2444     /* OF_CREATE is completely different from all other options, so
2445        handle it first */
2446
2447     if (mode & OF_CREATE)
2448     {
2449         if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2450             goto error;
2451     }
2452     else
2453     {
2454         /* Now look for the file */
2455
2456         if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2457             goto error;
2458
2459         TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2460
2461         if (mode & OF_DELETE)
2462         {
2463             if (!DeleteFileA( ofs->szPathName )) goto error;
2464             TRACE("(%s): OF_DELETE return = OK\n", name);
2465             return TRUE;
2466         }
2467
2468         handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2469         if (handle == INVALID_HANDLE_VALUE) goto error;
2470
2471         GetFileTime( handle, NULL, NULL, &filetime );
2472         FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2473         if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2474         {
2475             if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2476             {
2477                 CloseHandle( handle );
2478                 WARN("(%s): OF_VERIFY failed\n", name );
2479                 /* FIXME: what error here? */
2480                 SetLastError( ERROR_FILE_NOT_FOUND );
2481                 goto error;
2482             }
2483         }
2484         ofs->Reserved1 = filedatetime[0];
2485         ofs->Reserved2 = filedatetime[1];
2486     }
2487     TRACE("(%s): OK, return = %p\n", name, handle );
2488     if (mode & OF_EXIST)  /* Return TRUE instead of a handle */
2489     {
2490         CloseHandle( handle );
2491         return TRUE;
2492     }
2493     return HandleToLong(handle);
2494
2495 error:  /* We get here if there was an error opening the file */
2496     ofs->nErrCode = GetLastError();
2497     WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2498     return HFILE_ERROR;
2499 }