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