msi/test: Add tests for MsiGetFeatureState.
[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  *           SetFileValidData   (KERNEL32.@)
1005  */
1006 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1007 {
1008     FIXME("stub: %p, %s\n", hFile, wine_dbgstr_longlong(ValidDataLength));
1009     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1010     return FALSE;
1011 }
1012
1013 /***********************************************************************
1014  *           GetFileTime   (KERNEL32.@)
1015  */
1016 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1017                          FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1018 {
1019     FILE_BASIC_INFORMATION info;
1020     IO_STATUS_BLOCK io;
1021     NTSTATUS status;
1022
1023     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1024     if (status == STATUS_SUCCESS)
1025     {
1026         if (lpCreationTime)
1027         {
1028             lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1029             lpCreationTime->dwLowDateTime  = info.CreationTime.u.LowPart;
1030         }
1031         if (lpLastAccessTime)
1032         {
1033             lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1034             lpLastAccessTime->dwLowDateTime  = info.LastAccessTime.u.LowPart;
1035         }
1036         if (lpLastWriteTime)
1037         {
1038             lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1039             lpLastWriteTime->dwLowDateTime  = info.LastWriteTime.u.LowPart;
1040         }
1041         return TRUE;
1042     }
1043     SetLastError( RtlNtStatusToDosError(status) );
1044     return FALSE;
1045 }
1046
1047
1048 /***********************************************************************
1049  *              SetFileTime   (KERNEL32.@)
1050  */
1051 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1052                          const FILETIME *atime, const FILETIME *mtime )
1053 {
1054     FILE_BASIC_INFORMATION info;
1055     IO_STATUS_BLOCK io;
1056     NTSTATUS status;
1057
1058     memset( &info, 0, sizeof(info) );
1059     if (ctime)
1060     {
1061         info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1062         info.CreationTime.u.LowPart  = ctime->dwLowDateTime;
1063     }
1064     if (atime)
1065     {
1066         info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1067         info.LastAccessTime.u.LowPart  = atime->dwLowDateTime;
1068     }
1069     if (mtime)
1070     {
1071         info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1072         info.LastWriteTime.u.LowPart  = mtime->dwLowDateTime;
1073     }
1074
1075     status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1076     if (status == STATUS_SUCCESS) return TRUE;
1077     SetLastError( RtlNtStatusToDosError(status) );
1078     return FALSE;
1079 }
1080
1081
1082 /**************************************************************************
1083  *           LockFile   (KERNEL32.@)
1084  */
1085 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1086                       DWORD count_low, DWORD count_high )
1087 {
1088     NTSTATUS            status;
1089     LARGE_INTEGER       count, offset;
1090
1091     TRACE( "%p %x%08x %x%08x\n",
1092            hFile, offset_high, offset_low, count_high, count_low );
1093
1094     count.u.LowPart = count_low;
1095     count.u.HighPart = count_high;
1096     offset.u.LowPart = offset_low;
1097     offset.u.HighPart = offset_high;
1098
1099     status = NtLockFile( hFile, 0, NULL, NULL,
1100                          NULL, &offset, &count, NULL, TRUE, TRUE );
1101
1102     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1103     return !status;
1104 }
1105
1106
1107 /**************************************************************************
1108  * LockFileEx [KERNEL32.@]
1109  *
1110  * Locks a byte range within an open file for shared or exclusive access.
1111  *
1112  * RETURNS
1113  *   success: TRUE
1114  *   failure: FALSE
1115  *
1116  * NOTES
1117  * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1118  */
1119 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1120                         DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1121 {
1122     NTSTATUS status;
1123     LARGE_INTEGER count, offset;
1124     LPVOID   cvalue = NULL;
1125
1126     if (reserved)
1127     {
1128         SetLastError( ERROR_INVALID_PARAMETER );
1129         return FALSE;
1130     }
1131
1132     TRACE( "%p %x%08x %x%08x flags %x\n",
1133            hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset, 
1134            count_high, count_low, flags );
1135
1136     count.u.LowPart = count_low;
1137     count.u.HighPart = count_high;
1138     offset.u.LowPart = overlapped->u.s.Offset;
1139     offset.u.HighPart = overlapped->u.s.OffsetHigh;
1140
1141     if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1142
1143     status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1144                          NULL, &offset, &count, NULL,
1145                          flags & LOCKFILE_FAIL_IMMEDIATELY,
1146                          flags & LOCKFILE_EXCLUSIVE_LOCK );
1147
1148     if (status) SetLastError( RtlNtStatusToDosError(status) );
1149     return !status;
1150 }
1151
1152
1153 /**************************************************************************
1154  *           UnlockFile   (KERNEL32.@)
1155  */
1156 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1157                         DWORD count_low, DWORD count_high )
1158 {
1159     NTSTATUS    status;
1160     LARGE_INTEGER count, offset;
1161
1162     count.u.LowPart = count_low;
1163     count.u.HighPart = count_high;
1164     offset.u.LowPart = offset_low;
1165     offset.u.HighPart = offset_high;
1166
1167     status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1168     if (status) SetLastError( RtlNtStatusToDosError(status) );
1169     return !status;
1170 }
1171
1172
1173 /**************************************************************************
1174  *           UnlockFileEx   (KERNEL32.@)
1175  */
1176 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1177                           LPOVERLAPPED overlapped )
1178 {
1179     if (reserved)
1180     {
1181         SetLastError( ERROR_INVALID_PARAMETER );
1182         return FALSE;
1183     }
1184     if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1185
1186     return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1187 }
1188
1189
1190 /*************************************************************************
1191  *           SetHandleCount   (KERNEL32.@)
1192  */
1193 UINT WINAPI SetHandleCount( UINT count )
1194 {
1195     return count;
1196 }
1197
1198
1199 /**************************************************************************
1200  *                      Operations on file names                          *
1201  **************************************************************************/
1202
1203
1204 /*************************************************************************
1205  * CreateFileW [KERNEL32.@]  Creates or opens a file or other object
1206  *
1207  * Creates or opens an object, and returns a handle that can be used to
1208  * access that object.
1209  *
1210  * PARAMS
1211  *
1212  * filename     [in] pointer to filename to be accessed
1213  * access       [in] access mode requested
1214  * sharing      [in] share mode
1215  * sa           [in] pointer to security attributes
1216  * creation     [in] how to create the file
1217  * attributes   [in] attributes for newly created file
1218  * template     [in] handle to file with extended attributes to copy
1219  *
1220  * RETURNS
1221  *   Success: Open handle to specified file
1222  *   Failure: INVALID_HANDLE_VALUE
1223  */
1224 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1225                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1226                               DWORD attributes, HANDLE template )
1227 {
1228     NTSTATUS status;
1229     UINT options;
1230     OBJECT_ATTRIBUTES attr;
1231     UNICODE_STRING nameW;
1232     IO_STATUS_BLOCK io;
1233     HANDLE ret;
1234     DWORD dosdev;
1235     const WCHAR *vxd_name = NULL;
1236     static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1237     static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1238     static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1239     SECURITY_QUALITY_OF_SERVICE qos;
1240
1241     static const UINT nt_disposition[5] =
1242     {
1243         FILE_CREATE,        /* CREATE_NEW */
1244         FILE_OVERWRITE_IF,  /* CREATE_ALWAYS */
1245         FILE_OPEN,          /* OPEN_EXISTING */
1246         FILE_OPEN_IF,       /* OPEN_ALWAYS */
1247         FILE_OVERWRITE      /* TRUNCATE_EXISTING */
1248     };
1249
1250
1251     /* sanity checks */
1252
1253     if (!filename || !filename[0])
1254     {
1255         SetLastError( ERROR_PATH_NOT_FOUND );
1256         return INVALID_HANDLE_VALUE;
1257     }
1258
1259     TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1260           (access & GENERIC_READ)?"GENERIC_READ ":"",
1261           (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1262           (!access)?"QUERY_ACCESS ":"",
1263           (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1264           (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1265           (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1266           creation, attributes);
1267
1268     /* Open a console for CONIN$ or CONOUT$ */
1269
1270     if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1271     {
1272         ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1273         goto done;
1274     }
1275
1276     if (!strncmpW(filename, bkslashes_with_dotW, 4))
1277     {
1278         static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1279         static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1280
1281         if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1282             !strncmpiW( filename + 4, pipeW, 5 ) ||
1283             !strncmpiW( filename + 4, mailslotW, 9 ))
1284         {
1285             dosdev = 0;
1286         }
1287         else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1288         {
1289             dosdev += MAKELONG( 0, 4*sizeof(WCHAR) );  /* adjust position to start of filename */
1290         }
1291         else if (GetVersion() & 0x80000000)
1292         {
1293             vxd_name = filename + 4;
1294         }
1295     }
1296     else dosdev = RtlIsDosDeviceName_U( filename );
1297
1298     if (dosdev)
1299     {
1300         static const WCHAR conW[] = {'C','O','N'};
1301
1302         if (LOWORD(dosdev) == sizeof(conW) &&
1303             !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1304         {
1305             switch (access & (GENERIC_READ|GENERIC_WRITE))
1306             {
1307             case GENERIC_READ:
1308                 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1309                 goto done;
1310             case GENERIC_WRITE:
1311                 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1312                 goto done;
1313             default:
1314                 SetLastError( ERROR_FILE_NOT_FOUND );
1315                 return INVALID_HANDLE_VALUE;
1316             }
1317         }
1318     }
1319
1320     if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1321     {
1322         SetLastError( ERROR_INVALID_PARAMETER );
1323         return INVALID_HANDLE_VALUE;
1324     }
1325
1326     if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1327     {
1328         SetLastError( ERROR_PATH_NOT_FOUND );
1329         return INVALID_HANDLE_VALUE;
1330     }
1331
1332     /* now call NtCreateFile */
1333
1334     options = 0;
1335     if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1336         options |= FILE_OPEN_FOR_BACKUP_INTENT;
1337     else
1338         options |= FILE_NON_DIRECTORY_FILE;
1339     if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1340     {
1341         options |= FILE_DELETE_ON_CLOSE;
1342         access |= DELETE;
1343     }
1344     if (attributes & FILE_FLAG_NO_BUFFERING)
1345         options |= FILE_NO_INTERMEDIATE_BUFFERING;
1346     if (!(attributes & FILE_FLAG_OVERLAPPED))
1347         options |= FILE_SYNCHRONOUS_IO_ALERT;
1348     if (attributes & FILE_FLAG_RANDOM_ACCESS)
1349         options |= FILE_RANDOM_ACCESS;
1350     attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1351
1352     attr.Length = sizeof(attr);
1353     attr.RootDirectory = 0;
1354     attr.Attributes = OBJ_CASE_INSENSITIVE;
1355     attr.ObjectName = &nameW;
1356     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1357     if (attributes & SECURITY_SQOS_PRESENT)
1358     {
1359         qos.Length = sizeof(qos);
1360         qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1361         qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1362         qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1363         attr.SecurityQualityOfService = &qos;
1364     }
1365     else
1366         attr.SecurityQualityOfService = NULL;
1367
1368     if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1369
1370     status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1371                            sharing, nt_disposition[creation - CREATE_NEW],
1372                            options, NULL, 0 );
1373     if (status)
1374     {
1375         if (vxd_name && vxd_name[0])
1376         {
1377             static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1378             if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1379                                                               "__wine_vxd_open" );
1380             if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1381         }
1382
1383         WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1384         ret = INVALID_HANDLE_VALUE;
1385
1386         /* In the case file creation was rejected due to CREATE_NEW flag
1387          * was specified and file with that name already exists, correct
1388          * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1389          * Note: RtlNtStatusToDosError is not the subject to blame here.
1390          */
1391         if (status == STATUS_OBJECT_NAME_COLLISION)
1392             SetLastError( ERROR_FILE_EXISTS );
1393         else
1394             SetLastError( RtlNtStatusToDosError(status) );
1395     }
1396     else
1397     {
1398         if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1399             (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1400             SetLastError( ERROR_ALREADY_EXISTS );
1401         else
1402             SetLastError( 0 );
1403     }
1404     RtlFreeUnicodeString( &nameW );
1405
1406  done:
1407     if (!ret) ret = INVALID_HANDLE_VALUE;
1408     TRACE("returning %p\n", ret);
1409     return ret;
1410 }
1411
1412
1413
1414 /*************************************************************************
1415  *              CreateFileA              (KERNEL32.@)
1416  *
1417  * See CreateFileW.
1418  */
1419 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1420                            LPSECURITY_ATTRIBUTES sa, DWORD creation,
1421                            DWORD attributes, HANDLE template)
1422 {
1423     WCHAR *nameW;
1424
1425     if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1426     return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1427 }
1428
1429
1430 /***********************************************************************
1431  *           DeleteFileW   (KERNEL32.@)
1432  *
1433  * Delete a file.
1434  *
1435  * PARAMS
1436  *  path [I] Path to the file to delete.
1437  *
1438  * RETURNS
1439  *  Success: TRUE.
1440  *  Failure: FALSE, check GetLastError().
1441  */
1442 BOOL WINAPI DeleteFileW( LPCWSTR path )
1443 {
1444     UNICODE_STRING nameW;
1445     OBJECT_ATTRIBUTES attr;
1446     NTSTATUS status;
1447     HANDLE hFile;
1448     IO_STATUS_BLOCK io;
1449
1450     TRACE("%s\n", debugstr_w(path) );
1451
1452     if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1453     {
1454         SetLastError( ERROR_PATH_NOT_FOUND );
1455         return FALSE;
1456     }
1457
1458     attr.Length = sizeof(attr);
1459     attr.RootDirectory = 0;
1460     attr.Attributes = OBJ_CASE_INSENSITIVE;
1461     attr.ObjectName = &nameW;
1462     attr.SecurityDescriptor = NULL;
1463     attr.SecurityQualityOfService = NULL;
1464
1465     status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1466                           &attr, &io, NULL, 0,
1467                           FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1468                           FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1469     if (status == STATUS_SUCCESS) status = NtClose(hFile);
1470
1471     RtlFreeUnicodeString( &nameW );
1472     if (status)
1473     {
1474         SetLastError( RtlNtStatusToDosError(status) );
1475         return FALSE;
1476     }
1477     return TRUE;
1478 }
1479
1480
1481 /***********************************************************************
1482  *           DeleteFileA   (KERNEL32.@)
1483  *
1484  * See DeleteFileW.
1485  */
1486 BOOL WINAPI DeleteFileA( LPCSTR path )
1487 {
1488     WCHAR *pathW;
1489
1490     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1491     return DeleteFileW( pathW );
1492 }
1493
1494
1495 /**************************************************************************
1496  *           ReplaceFileW   (KERNEL32.@)
1497  *           ReplaceFile    (KERNEL32.@)
1498  */
1499 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1500                          LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1501                          LPVOID lpExclude, LPVOID lpReserved)
1502 {
1503     UNICODE_STRING nt_replaced_name, nt_replacement_name;
1504     ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1505     HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1506     DWORD error = ERROR_SUCCESS;
1507     UINT replaced_flags;
1508     BOOL ret = FALSE;
1509     NTSTATUS status;
1510     IO_STATUS_BLOCK io;
1511     OBJECT_ATTRIBUTES attr;
1512
1513     if (dwReplaceFlags)
1514         FIXME("Ignoring flags %x\n", dwReplaceFlags);
1515
1516     /* First two arguments are mandatory */
1517     if (!lpReplacedFileName || !lpReplacementFileName)
1518     {
1519         SetLastError(ERROR_INVALID_PARAMETER);
1520         return FALSE;
1521     }
1522
1523     unix_replaced_name.Buffer = NULL;
1524     unix_replacement_name.Buffer = NULL;
1525     unix_backup_name.Buffer = NULL;
1526
1527     attr.Length = sizeof(attr);
1528     attr.RootDirectory = 0;
1529     attr.Attributes = OBJ_CASE_INSENSITIVE;
1530     attr.ObjectName = NULL;
1531     attr.SecurityDescriptor = NULL;
1532     attr.SecurityQualityOfService = NULL;
1533
1534     /* Open the "replaced" file for reading and writing */
1535     if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1536     {
1537         error = ERROR_PATH_NOT_FOUND;
1538         goto fail;
1539     }
1540     replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1541     attr.ObjectName = &nt_replaced_name;
1542     status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1543                         &attr, &io,
1544                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1545                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1546     if (status == STATUS_SUCCESS)
1547         status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1548     RtlFreeUnicodeString(&nt_replaced_name);
1549     if (status != STATUS_SUCCESS)
1550     {
1551         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1552             error = ERROR_FILE_NOT_FOUND;
1553         else
1554             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1555         goto fail;
1556     }
1557
1558     /*
1559      * Open the replacement file for reading, writing, and deleting
1560      * (writing and deleting are needed when finished)
1561      */
1562     if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1563     {
1564         error = ERROR_PATH_NOT_FOUND;
1565         goto fail;
1566     }
1567     attr.ObjectName = &nt_replacement_name;
1568     status = NtOpenFile(&hReplacement,
1569                         GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1570                         &attr, &io, 0,
1571                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1572     if (status == STATUS_SUCCESS)
1573         status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1574     RtlFreeUnicodeString(&nt_replacement_name);
1575     if (status != STATUS_SUCCESS)
1576     {
1577         error = RtlNtStatusToDosError(status);
1578         goto fail;
1579     }
1580
1581     /* If the user wants a backup then that needs to be performed first */
1582     if (lpBackupFileName)
1583     {
1584         UNICODE_STRING nt_backup_name;
1585         FILE_BASIC_INFORMATION replaced_info;
1586
1587         /* Obtain the file attributes from the "replaced" file */
1588         status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1589                                         sizeof(replaced_info),
1590                                         FileBasicInformation);
1591         if (status != STATUS_SUCCESS)
1592         {
1593             error = RtlNtStatusToDosError(status);
1594             goto fail;
1595         }
1596
1597         if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1598         {
1599             error = ERROR_PATH_NOT_FOUND;
1600             goto fail;
1601         }
1602         attr.ObjectName = &nt_backup_name;
1603         /* Open the backup with permissions to write over it */
1604         status = NtCreateFile(&hBackup, GENERIC_WRITE,
1605                               &attr, &io, NULL, replaced_info.FileAttributes,
1606                               FILE_SHARE_WRITE, FILE_OPEN_IF,
1607                               FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1608                               NULL, 0);
1609         if (status == STATUS_SUCCESS)
1610             status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1611         RtlFreeUnicodeString(&nt_backup_name);
1612         if (status != STATUS_SUCCESS)
1613         {
1614             error = RtlNtStatusToDosError(status);
1615             goto fail;
1616         }
1617
1618         /* If an existing backup exists then copy over it */
1619         if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1620         {
1621             error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1622             goto fail;
1623         }
1624     }
1625
1626     /*
1627      * Now that the backup has been performed (if requested), copy the replacement
1628      * into place
1629      */
1630     if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1631     {
1632         if (errno == EACCES)
1633         {
1634             /* Inappropriate permissions on "replaced", rename will fail */
1635             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1636             goto fail;
1637         }
1638         /* on failure we need to indicate whether a backup was made */
1639         if (!lpBackupFileName)
1640             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1641         else
1642             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1643         goto fail;
1644     }
1645     /* Success! */
1646     ret = TRUE;
1647
1648     /* Perform resource cleanup */
1649 fail:
1650     if (hBackup) CloseHandle(hBackup);
1651     if (hReplaced) CloseHandle(hReplaced);
1652     if (hReplacement) CloseHandle(hReplacement);
1653     RtlFreeAnsiString(&unix_backup_name);
1654     RtlFreeAnsiString(&unix_replacement_name);
1655     RtlFreeAnsiString(&unix_replaced_name);
1656
1657     /* If there was an error, set the error code */
1658     if(!ret)
1659         SetLastError(error);
1660     return ret;
1661 }
1662
1663
1664 /**************************************************************************
1665  *           ReplaceFileA (KERNEL32.@)
1666  */
1667 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1668                          LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1669                          LPVOID lpExclude, LPVOID lpReserved)
1670 {
1671     WCHAR *replacedW, *replacementW, *backupW = NULL;
1672     BOOL ret;
1673
1674     /* This function only makes sense when the first two parameters are defined */
1675     if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1676     {
1677         SetLastError(ERROR_INVALID_PARAMETER);
1678         return FALSE;
1679     }
1680     if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1681     {
1682         HeapFree( GetProcessHeap(), 0, replacedW );
1683         SetLastError(ERROR_INVALID_PARAMETER);
1684         return FALSE;
1685     }
1686     /* The backup parameter, however, is optional */
1687     if (lpBackupFileName)
1688     {
1689         if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1690         {
1691             HeapFree( GetProcessHeap(), 0, replacedW );
1692             HeapFree( GetProcessHeap(), 0, replacementW );
1693             SetLastError(ERROR_INVALID_PARAMETER);
1694             return FALSE;
1695         }
1696     }
1697     ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1698     HeapFree( GetProcessHeap(), 0, replacedW );
1699     HeapFree( GetProcessHeap(), 0, replacementW );
1700     HeapFree( GetProcessHeap(), 0, backupW );
1701     return ret;
1702 }
1703
1704
1705 /*************************************************************************
1706  *           FindFirstFileExW  (KERNEL32.@)
1707  *
1708  * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1709  * results as FindExSearchNameMatch
1710  */
1711 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1712                                 LPVOID data, FINDEX_SEARCH_OPS search_op,
1713                                 LPVOID filter, DWORD flags)
1714 {
1715     WCHAR *mask, *p;
1716     FIND_FIRST_INFO *info = NULL;
1717     UNICODE_STRING nt_name;
1718     OBJECT_ATTRIBUTES attr;
1719     IO_STATUS_BLOCK io;
1720     NTSTATUS status;
1721     DWORD device = 0;
1722
1723     TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1724
1725     if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1726         || flags != 0)
1727     {
1728         FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1729         return INVALID_HANDLE_VALUE;
1730     }
1731     if (level != FindExInfoStandard)
1732     {
1733         FIXME("info level %d not implemented\n", level );
1734         return INVALID_HANDLE_VALUE;
1735     }
1736
1737     if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1738     {
1739         SetLastError( ERROR_PATH_NOT_FOUND );
1740         return INVALID_HANDLE_VALUE;
1741     }
1742
1743     if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1744     {
1745         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1746         goto error;
1747     }
1748
1749     if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1750     {
1751         static const WCHAR dotW[] = {'.',0};
1752         WCHAR *dir = NULL;
1753
1754         /* we still need to check that the directory can be opened */
1755
1756         if (HIWORD(device))
1757         {
1758             if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1759             {
1760                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1761                 goto error;
1762             }
1763             memcpy( dir, filename, HIWORD(device) );
1764             dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1765         }
1766         RtlFreeUnicodeString( &nt_name );
1767         if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1768         {
1769             HeapFree( GetProcessHeap(), 0, dir );
1770             SetLastError( ERROR_PATH_NOT_FOUND );
1771             goto error;
1772         }
1773         HeapFree( GetProcessHeap(), 0, dir );
1774         RtlInitUnicodeString( &info->mask, NULL );
1775     }
1776     else if (!mask || !*mask)
1777     {
1778         SetLastError( ERROR_FILE_NOT_FOUND );
1779         goto error;
1780     }
1781     else
1782     {
1783         if (!RtlCreateUnicodeString( &info->mask, mask ))
1784         {
1785             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1786             goto error;
1787         }
1788
1789         /* truncate dir name before mask */
1790         *mask = 0;
1791         nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1792     }
1793
1794     /* check if path is the root of the drive */
1795     info->is_root = FALSE;
1796     p = nt_name.Buffer + 4;  /* skip \??\ prefix */
1797     if (p[0] && p[1] == ':')
1798     {
1799         p += 2;
1800         while (*p == '\\') p++;
1801         info->is_root = (*p == 0);
1802     }
1803
1804     attr.Length = sizeof(attr);
1805     attr.RootDirectory = 0;
1806     attr.Attributes = OBJ_CASE_INSENSITIVE;
1807     attr.ObjectName = &nt_name;
1808     attr.SecurityDescriptor = NULL;
1809     attr.SecurityQualityOfService = NULL;
1810
1811     status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1812                          FILE_SHARE_READ | FILE_SHARE_WRITE,
1813                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1814
1815     if (status != STATUS_SUCCESS)
1816     {
1817         RtlFreeUnicodeString( &info->mask );
1818         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1819             SetLastError( ERROR_PATH_NOT_FOUND );
1820         else
1821             SetLastError( RtlNtStatusToDosError(status) );
1822         goto error;
1823     }
1824
1825     RtlInitializeCriticalSection( &info->cs );
1826     info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1827     info->path     = nt_name;
1828     info->magic    = FIND_FIRST_MAGIC;
1829     info->data_pos = 0;
1830     info->data_len = 0;
1831     info->search_op = search_op;
1832
1833     if (device)
1834     {
1835         WIN32_FIND_DATAW *wfd = data;
1836
1837         memset( wfd, 0, sizeof(*wfd) );
1838         memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1839         wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1840         CloseHandle( info->handle );
1841         info->handle = 0;
1842     }
1843     else
1844     {
1845         IO_STATUS_BLOCK io;
1846
1847         NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1848                               FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1849         if (io.u.Status)
1850         {
1851             FindClose( info );
1852             SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1853             return INVALID_HANDLE_VALUE;
1854         }
1855         info->data_len = io.Information;
1856         if (!FindNextFileW( info, data ))
1857         {
1858             TRACE( "%s not found\n", debugstr_w(filename) );
1859             FindClose( info );
1860             SetLastError( ERROR_FILE_NOT_FOUND );
1861             return INVALID_HANDLE_VALUE;
1862         }
1863         if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1864         {
1865             /* we can't find two files with the same name */
1866             CloseHandle( info->handle );
1867             info->handle = 0;
1868         }
1869     }
1870     return info;
1871
1872 error:
1873     HeapFree( GetProcessHeap(), 0, info );
1874     RtlFreeUnicodeString( &nt_name );
1875     return INVALID_HANDLE_VALUE;
1876 }
1877
1878
1879 /*************************************************************************
1880  *           FindNextFileW   (KERNEL32.@)
1881  */
1882 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1883 {
1884     FIND_FIRST_INFO *info;
1885     FILE_BOTH_DIR_INFORMATION *dir_info;
1886     BOOL ret = FALSE;
1887
1888     TRACE("%p %p\n", handle, data);
1889
1890     if (!handle || handle == INVALID_HANDLE_VALUE)
1891     {
1892         SetLastError( ERROR_INVALID_HANDLE );
1893         return ret;
1894     }
1895     info = handle;
1896     if (info->magic != FIND_FIRST_MAGIC)
1897     {
1898         SetLastError( ERROR_INVALID_HANDLE );
1899         return ret;
1900     }
1901
1902     RtlEnterCriticalSection( &info->cs );
1903
1904     if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1905     else for (;;)
1906     {
1907         if (info->data_pos >= info->data_len)  /* need to read some more data */
1908         {
1909             IO_STATUS_BLOCK io;
1910
1911             NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1912                                   FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1913             if (io.u.Status)
1914             {
1915                 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1916                 if (io.u.Status == STATUS_NO_MORE_FILES)
1917                 {
1918                     CloseHandle( info->handle );
1919                     info->handle = 0;
1920                 }
1921                 break;
1922             }
1923             info->data_len = io.Information;
1924             info->data_pos = 0;
1925         }
1926
1927         dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1928
1929         if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1930         else info->data_pos = info->data_len;
1931
1932         /* don't return '.' and '..' in the root of the drive */
1933         if (info->is_root)
1934         {
1935             if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1936             if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1937                 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1938         }
1939
1940         /* check for dir symlink */
1941         if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1942             (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1943             strpbrkW( info->mask.Buffer, wildcardsW ))
1944         {
1945             if (!check_dir_symlink( info, dir_info )) continue;
1946         }
1947
1948         data->dwFileAttributes = dir_info->FileAttributes;
1949         data->ftCreationTime   = *(FILETIME *)&dir_info->CreationTime;
1950         data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1951         data->ftLastWriteTime  = *(FILETIME *)&dir_info->LastWriteTime;
1952         data->nFileSizeHigh    = dir_info->EndOfFile.QuadPart >> 32;
1953         data->nFileSizeLow     = (DWORD)dir_info->EndOfFile.QuadPart;
1954         data->dwReserved0      = 0;
1955         data->dwReserved1      = 0;
1956
1957         memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1958         data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1959         memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1960         data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1961
1962         TRACE("returning %s (%s)\n",
1963               debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1964
1965         ret = TRUE;
1966         break;
1967     }
1968
1969     RtlLeaveCriticalSection( &info->cs );
1970     return ret;
1971 }
1972
1973
1974 /*************************************************************************
1975  *           FindClose   (KERNEL32.@)
1976  */
1977 BOOL WINAPI FindClose( HANDLE handle )
1978 {
1979     FIND_FIRST_INFO *info = handle;
1980
1981     if (!handle || handle == INVALID_HANDLE_VALUE)
1982     {
1983         SetLastError( ERROR_INVALID_HANDLE );
1984         return FALSE;
1985     }
1986
1987     __TRY
1988     {
1989         if (info->magic == FIND_FIRST_MAGIC)
1990         {
1991             RtlEnterCriticalSection( &info->cs );
1992             if (info->magic == FIND_FIRST_MAGIC)  /* in case someone else freed it in the meantime */
1993             {
1994                 info->magic = 0;
1995                 if (info->handle) CloseHandle( info->handle );
1996                 info->handle = 0;
1997                 RtlFreeUnicodeString( &info->mask );
1998                 info->mask.Buffer = NULL;
1999                 RtlFreeUnicodeString( &info->path );
2000                 info->data_pos = 0;
2001                 info->data_len = 0;
2002                 RtlLeaveCriticalSection( &info->cs );
2003                 info->cs.DebugInfo->Spare[0] = 0;
2004                 RtlDeleteCriticalSection( &info->cs );
2005                 HeapFree( GetProcessHeap(), 0, info );
2006             }
2007         }
2008     }
2009     __EXCEPT_PAGE_FAULT
2010     {
2011         WARN("Illegal handle %p\n", handle);
2012         SetLastError( ERROR_INVALID_HANDLE );
2013         return FALSE;
2014     }
2015     __ENDTRY
2016
2017     return TRUE;
2018 }
2019
2020
2021 /*************************************************************************
2022  *           FindFirstFileA   (KERNEL32.@)
2023  */
2024 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2025 {
2026     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2027                             FindExSearchNameMatch, NULL, 0);
2028 }
2029
2030 /*************************************************************************
2031  *           FindFirstFileExA   (KERNEL32.@)
2032  */
2033 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2034                                 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2035                                 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2036 {
2037     HANDLE handle;
2038     WIN32_FIND_DATAA *dataA;
2039     WIN32_FIND_DATAW dataW;
2040     WCHAR *nameW;
2041
2042     if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2043
2044     handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2045     if (handle == INVALID_HANDLE_VALUE) return handle;
2046
2047     dataA = lpFindFileData;
2048     dataA->dwFileAttributes = dataW.dwFileAttributes;
2049     dataA->ftCreationTime   = dataW.ftCreationTime;
2050     dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2051     dataA->ftLastWriteTime  = dataW.ftLastWriteTime;
2052     dataA->nFileSizeHigh    = dataW.nFileSizeHigh;
2053     dataA->nFileSizeLow     = dataW.nFileSizeLow;
2054     FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2055     FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2056                     sizeof(dataA->cAlternateFileName) );
2057     return handle;
2058 }
2059
2060
2061 /*************************************************************************
2062  *           FindFirstFileW   (KERNEL32.@)
2063  */
2064 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2065 {
2066     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2067                             FindExSearchNameMatch, NULL, 0);
2068 }
2069
2070
2071 /*************************************************************************
2072  *           FindNextFileA   (KERNEL32.@)
2073  */
2074 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2075 {
2076     WIN32_FIND_DATAW dataW;
2077
2078     if (!FindNextFileW( handle, &dataW )) return FALSE;
2079     data->dwFileAttributes = dataW.dwFileAttributes;
2080     data->ftCreationTime   = dataW.ftCreationTime;
2081     data->ftLastAccessTime = dataW.ftLastAccessTime;
2082     data->ftLastWriteTime  = dataW.ftLastWriteTime;
2083     data->nFileSizeHigh    = dataW.nFileSizeHigh;
2084     data->nFileSizeLow     = dataW.nFileSizeLow;
2085     FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2086     FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2087                     sizeof(data->cAlternateFileName) );
2088     return TRUE;
2089 }
2090
2091
2092 /**************************************************************************
2093  *           GetFileAttributesW   (KERNEL32.@)
2094  */
2095 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2096 {
2097     FILE_BASIC_INFORMATION info;
2098     UNICODE_STRING nt_name;
2099     OBJECT_ATTRIBUTES attr;
2100     NTSTATUS status;
2101
2102     TRACE("%s\n", debugstr_w(name));
2103
2104     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2105     {
2106         SetLastError( ERROR_PATH_NOT_FOUND );
2107         return INVALID_FILE_ATTRIBUTES;
2108     }
2109
2110     attr.Length = sizeof(attr);
2111     attr.RootDirectory = 0;
2112     attr.Attributes = OBJ_CASE_INSENSITIVE;
2113     attr.ObjectName = &nt_name;
2114     attr.SecurityDescriptor = NULL;
2115     attr.SecurityQualityOfService = NULL;
2116
2117     status = NtQueryAttributesFile( &attr, &info );
2118     RtlFreeUnicodeString( &nt_name );
2119
2120     if (status == STATUS_SUCCESS) return info.FileAttributes;
2121
2122     /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2123     if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2124
2125     SetLastError( RtlNtStatusToDosError(status) );
2126     return INVALID_FILE_ATTRIBUTES;
2127 }
2128
2129
2130 /**************************************************************************
2131  *           GetFileAttributesA   (KERNEL32.@)
2132  */
2133 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2134 {
2135     WCHAR *nameW;
2136
2137     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2138     return GetFileAttributesW( nameW );
2139 }
2140
2141
2142 /**************************************************************************
2143  *              SetFileAttributesW      (KERNEL32.@)
2144  */
2145 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2146 {
2147     UNICODE_STRING nt_name;
2148     OBJECT_ATTRIBUTES attr;
2149     IO_STATUS_BLOCK io;
2150     NTSTATUS status;
2151     HANDLE handle;
2152
2153     TRACE("%s %x\n", debugstr_w(name), attributes);
2154
2155     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2156     {
2157         SetLastError( ERROR_PATH_NOT_FOUND );
2158         return FALSE;
2159     }
2160
2161     attr.Length = sizeof(attr);
2162     attr.RootDirectory = 0;
2163     attr.Attributes = OBJ_CASE_INSENSITIVE;
2164     attr.ObjectName = &nt_name;
2165     attr.SecurityDescriptor = NULL;
2166     attr.SecurityQualityOfService = NULL;
2167
2168     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2169     RtlFreeUnicodeString( &nt_name );
2170
2171     if (status == STATUS_SUCCESS)
2172     {
2173         FILE_BASIC_INFORMATION info;
2174
2175         memset( &info, 0, sizeof(info) );
2176         info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL;  /* make sure it's not zero */
2177         status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2178         NtClose( handle );
2179     }
2180
2181     if (status == STATUS_SUCCESS) return TRUE;
2182     SetLastError( RtlNtStatusToDosError(status) );
2183     return FALSE;
2184 }
2185
2186
2187 /**************************************************************************
2188  *              SetFileAttributesA      (KERNEL32.@)
2189  */
2190 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2191 {
2192     WCHAR *nameW;
2193
2194     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2195     return SetFileAttributesW( nameW, attributes );
2196 }
2197
2198
2199 /**************************************************************************
2200  *           GetFileAttributesExW   (KERNEL32.@)
2201  */
2202 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2203 {
2204     FILE_NETWORK_OPEN_INFORMATION info;
2205     WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2206     UNICODE_STRING nt_name;
2207     OBJECT_ATTRIBUTES attr;
2208     NTSTATUS status;
2209     
2210     TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2211
2212     if (level != GetFileExInfoStandard)
2213     {
2214         SetLastError( ERROR_INVALID_PARAMETER );
2215         return FALSE;
2216     }
2217
2218     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2219     {
2220         SetLastError( ERROR_PATH_NOT_FOUND );
2221         return FALSE;
2222     }
2223
2224     attr.Length = sizeof(attr);
2225     attr.RootDirectory = 0;
2226     attr.Attributes = OBJ_CASE_INSENSITIVE;
2227     attr.ObjectName = &nt_name;
2228     attr.SecurityDescriptor = NULL;
2229     attr.SecurityQualityOfService = NULL;
2230
2231     status = NtQueryFullAttributesFile( &attr, &info );
2232     RtlFreeUnicodeString( &nt_name );
2233
2234     if (status != STATUS_SUCCESS)
2235     {
2236         SetLastError( RtlNtStatusToDosError(status) );
2237         return FALSE;
2238     }
2239
2240     data->dwFileAttributes = info.FileAttributes;
2241     data->ftCreationTime.dwLowDateTime    = info.CreationTime.u.LowPart;
2242     data->ftCreationTime.dwHighDateTime   = info.CreationTime.u.HighPart;
2243     data->ftLastAccessTime.dwLowDateTime  = info.LastAccessTime.u.LowPart;
2244     data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2245     data->ftLastWriteTime.dwLowDateTime   = info.LastWriteTime.u.LowPart;
2246     data->ftLastWriteTime.dwHighDateTime  = info.LastWriteTime.u.HighPart;
2247     data->nFileSizeLow                    = info.EndOfFile.u.LowPart;
2248     data->nFileSizeHigh                   = info.EndOfFile.u.HighPart;
2249     return TRUE;
2250 }
2251
2252
2253 /**************************************************************************
2254  *           GetFileAttributesExA   (KERNEL32.@)
2255  */
2256 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2257 {
2258     WCHAR *nameW;
2259
2260     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2261     return GetFileAttributesExW( nameW, level, ptr );
2262 }
2263
2264
2265 /******************************************************************************
2266  *           GetCompressedFileSizeW   (KERNEL32.@)
2267  *
2268  * Get the actual number of bytes used on disk.
2269  *
2270  * RETURNS
2271  *    Success: Low-order doubleword of number of bytes
2272  *    Failure: INVALID_FILE_SIZE
2273  */
2274 DWORD WINAPI GetCompressedFileSizeW(
2275     LPCWSTR name,       /* [in]  Pointer to name of file */
2276     LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2277 {
2278     UNICODE_STRING nt_name;
2279     OBJECT_ATTRIBUTES attr;
2280     IO_STATUS_BLOCK io;
2281     NTSTATUS status;
2282     HANDLE handle;
2283     DWORD ret = INVALID_FILE_SIZE;
2284
2285     TRACE("%s %p\n", debugstr_w(name), size_high);
2286
2287     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2288     {
2289         SetLastError( ERROR_PATH_NOT_FOUND );
2290         return INVALID_FILE_SIZE;
2291     }
2292
2293     attr.Length = sizeof(attr);
2294     attr.RootDirectory = 0;
2295     attr.Attributes = OBJ_CASE_INSENSITIVE;
2296     attr.ObjectName = &nt_name;
2297     attr.SecurityDescriptor = NULL;
2298     attr.SecurityQualityOfService = NULL;
2299
2300     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2301     RtlFreeUnicodeString( &nt_name );
2302
2303     if (status == STATUS_SUCCESS)
2304     {
2305         /* we don't support compressed files, simply return the file size */
2306         ret = GetFileSize( handle, size_high );
2307         NtClose( handle );
2308     }
2309     else SetLastError( RtlNtStatusToDosError(status) );
2310
2311     return ret;
2312 }
2313
2314
2315 /******************************************************************************
2316  *           GetCompressedFileSizeA   (KERNEL32.@)
2317  *
2318  * See GetCompressedFileSizeW.
2319  */
2320 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2321 {
2322     WCHAR *nameW;
2323
2324     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2325     return GetCompressedFileSizeW( nameW, size_high );
2326 }
2327
2328
2329 /***********************************************************************
2330  *              OpenVxDHandle (KERNEL32.@)
2331  *
2332  *      This function is supposed to return the corresponding Ring 0
2333  *      ("kernel") handle for a Ring 3 handle in Win9x.
2334  *      Evidently, Wine will have problems with this. But we try anyway,
2335  *      maybe it helps...
2336  */
2337 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2338 {
2339     FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2340     return hHandleRing3;
2341 }
2342
2343
2344 /****************************************************************************
2345  *              DeviceIoControl (KERNEL32.@)
2346  */
2347 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2348                             LPVOID lpvInBuffer, DWORD cbInBuffer,
2349                             LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2350                             LPDWORD lpcbBytesReturned,
2351                             LPOVERLAPPED lpOverlapped)
2352 {
2353     NTSTATUS status;
2354
2355     TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2356            hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2357            lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2358
2359     /* Check if this is a user defined control code for a VxD */
2360
2361     if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2362     {
2363         typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2364         static DeviceIoProc (*vxd_get_proc)(HANDLE);
2365         DeviceIoProc proc = NULL;
2366
2367         if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2368                                                                   "__wine_vxd_get_proc" );
2369         if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2370         if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2371                                lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2372     }
2373
2374     /* Not a VxD, let ntdll handle it */
2375
2376     if (lpOverlapped)
2377     {
2378         LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2379         lpOverlapped->Internal = STATUS_PENDING;
2380         lpOverlapped->InternalHigh = 0;
2381         if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2382             status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2383                                      NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2384                                      dwIoControlCode, lpvInBuffer, cbInBuffer,
2385                                      lpvOutBuffer, cbOutBuffer);
2386         else
2387             status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2388                                            NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2389                                            dwIoControlCode, lpvInBuffer, cbInBuffer,
2390                                            lpvOutBuffer, cbOutBuffer);
2391         if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2392     }
2393     else
2394     {
2395         IO_STATUS_BLOCK iosb;
2396
2397         if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2398             status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2399                                      dwIoControlCode, lpvInBuffer, cbInBuffer,
2400                                      lpvOutBuffer, cbOutBuffer);
2401         else
2402             status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2403                                            dwIoControlCode, lpvInBuffer, cbInBuffer,
2404                                            lpvOutBuffer, cbOutBuffer);
2405         if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2406     }
2407     if (status) SetLastError( RtlNtStatusToDosError(status) );
2408     return !status;
2409 }
2410
2411
2412 /***********************************************************************
2413  *           OpenFile   (KERNEL32.@)
2414  */
2415 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2416 {
2417     HANDLE handle;
2418     FILETIME filetime;
2419     WORD filedatetime[2];
2420
2421     if (!ofs) return HFILE_ERROR;
2422
2423     TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2424           ((mode & 0x3 )==OF_READ)?"OF_READ":
2425           ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2426           ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2427           ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2428           ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2429           ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2430           ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2431           ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2432           ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2433           ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2434           ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2435           ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2436           ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2437           ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2438           ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2439           ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2440           ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2441         );
2442
2443
2444     ofs->cBytes = sizeof(OFSTRUCT);
2445     ofs->nErrCode = 0;
2446     if (mode & OF_REOPEN) name = ofs->szPathName;
2447
2448     if (!name) return HFILE_ERROR;
2449
2450     TRACE("%s %04x\n", name, mode );
2451
2452     /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2453        Are there any cases where getting the path here is wrong?
2454        Uwe Bonnes 1997 Apr 2 */
2455     if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2456
2457     /* OF_PARSE simply fills the structure */
2458
2459     if (mode & OF_PARSE)
2460     {
2461         ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2462         TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2463         return 0;
2464     }
2465
2466     /* OF_CREATE is completely different from all other options, so
2467        handle it first */
2468
2469     if (mode & OF_CREATE)
2470     {
2471         if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2472             goto error;
2473     }
2474     else
2475     {
2476         /* Now look for the file */
2477
2478         if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2479             goto error;
2480
2481         TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2482
2483         if (mode & OF_DELETE)
2484         {
2485             if (!DeleteFileA( ofs->szPathName )) goto error;
2486             TRACE("(%s): OF_DELETE return = OK\n", name);
2487             return TRUE;
2488         }
2489
2490         handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2491         if (handle == INVALID_HANDLE_VALUE) goto error;
2492
2493         GetFileTime( handle, NULL, NULL, &filetime );
2494         FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2495         if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2496         {
2497             if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2498             {
2499                 CloseHandle( handle );
2500                 WARN("(%s): OF_VERIFY failed\n", name );
2501                 /* FIXME: what error here? */
2502                 SetLastError( ERROR_FILE_NOT_FOUND );
2503                 goto error;
2504             }
2505         }
2506         ofs->Reserved1 = filedatetime[0];
2507         ofs->Reserved2 = filedatetime[1];
2508     }
2509     TRACE("(%s): OK, return = %p\n", name, handle );
2510     if (mode & OF_EXIST)  /* Return TRUE instead of a handle */
2511     {
2512         CloseHandle( handle );
2513         return TRUE;
2514     }
2515     return HandleToLong(handle);
2516
2517 error:  /* We get here if there was an error opening the file */
2518     ofs->nErrCode = GetLastError();
2519     WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2520     return HFILE_ERROR;
2521 }