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