include: Add missing local attributes to shobjidl.idl.
[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     /* FIXME: NtWriteFile does not always cause page faults, generate them now */
564     if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
565     {
566         status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
567                              buffer, bytesToWrite, poffset, NULL);
568         if (status != STATUS_INVALID_USER_BUFFER)
569             FIXME("Could not access memory (%p,%d) at first, now OK. Protected by DIBSection code?\n",
570                   buffer, bytesToWrite);
571     }
572
573     if (status == STATUS_PENDING && !overlapped)
574     {
575         WaitForSingleObject( hFile, INFINITE );
576         status = piosb->u.Status;
577     }
578
579     if (status != STATUS_PENDING && bytesWritten)
580         *bytesWritten = piosb->Information;
581
582     if (status && status != STATUS_TIMEOUT)
583     {
584         SetLastError( RtlNtStatusToDosError(status) );
585         return FALSE;
586     }
587     return TRUE;
588 }
589
590
591 /***********************************************************************
592  *              GetOverlappedResult     (KERNEL32.@)
593  *
594  * Check the result of an Asynchronous data transfer from a file.
595  *
596  * Parameters
597  *   HANDLE hFile                 [in] handle of file to check on
598  *   LPOVERLAPPED lpOverlapped    [in/out] pointer to overlapped
599  *   LPDWORD lpTransferred        [in/out] number of bytes transferred
600  *   BOOL bWait                   [in] wait for the transfer to complete ?
601  *
602  * RETURNS
603  *   TRUE on success
604  *   FALSE on failure
605  *
606  *  If successful (and relevant) lpTransferred will hold the number of
607  *   bytes transferred during the async operation.
608  */
609 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
610                                 LPDWORD lpTransferred, BOOL bWait)
611 {
612     NTSTATUS status;
613
614     TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
615
616     if ( lpOverlapped == NULL )
617     {
618         ERR("lpOverlapped was null\n");
619         return FALSE;
620     }
621
622     status = lpOverlapped->Internal;
623     if (status == STATUS_PENDING)
624     {
625         if (!bWait)
626         {
627             SetLastError( ERROR_IO_INCOMPLETE );
628             return FALSE;
629         }
630
631         if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
632                                  INFINITE ) == WAIT_FAILED)
633             return FALSE;
634         status = lpOverlapped->Internal;
635     }
636
637     if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
638
639     if (status) SetLastError( RtlNtStatusToDosError(status) );
640     return !status;
641 }
642
643 /***********************************************************************
644  *             CancelIo                   (KERNEL32.@)
645  *
646  * Cancels pending I/O operations initiated by the current thread on a file.
647  *
648  * PARAMS
649  *  handle [I] File handle.
650  *
651  * RETURNS
652  *  Success: TRUE.
653  *  Failure: FALSE, check GetLastError().
654  */
655 BOOL WINAPI CancelIo(HANDLE handle)
656 {
657     IO_STATUS_BLOCK    io_status;
658
659     NtCancelIoFile(handle, &io_status);
660     if (io_status.u.Status)
661     {
662         SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
663         return FALSE;
664     }
665     return TRUE;
666 }
667
668 /***********************************************************************
669  *           _hread   (KERNEL32.@)
670  */
671 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
672 {
673     return _lread( hFile, buffer, count );
674 }
675
676
677 /***********************************************************************
678  *           _hwrite   (KERNEL32.@)
679  *
680  *      experimentation yields that _lwrite:
681  *              o truncates the file at the current position with
682  *                a 0 len write
683  *              o returns 0 on a 0 length write
684  *              o works with console handles
685  *
686  */
687 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
688 {
689     DWORD result;
690
691     TRACE("%d %p %d\n", handle, buffer, count );
692
693     if (!count)
694     {
695         /* Expand or truncate at current position */
696         if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
697         return 0;
698     }
699     if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
700         return HFILE_ERROR;
701     return result;
702 }
703
704
705 /***********************************************************************
706  *           _lclose   (KERNEL32.@)
707  */
708 HFILE WINAPI _lclose( HFILE hFile )
709 {
710     TRACE("handle %d\n", hFile );
711     return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
712 }
713
714
715 /***********************************************************************
716  *           _lcreat   (KERNEL32.@)
717  */
718 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
719 {
720     HANDLE hfile;
721
722     /* Mask off all flags not explicitly allowed by the doc */
723     attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
724     TRACE("%s %02x\n", path, attr );
725     hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
726                                FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
727                                CREATE_ALWAYS, attr, 0 );
728     return HandleToLong(hfile);
729 }
730
731
732 /***********************************************************************
733  *           _lopen   (KERNEL32.@)
734  */
735 HFILE WINAPI _lopen( LPCSTR path, INT mode )
736 {
737     HANDLE hfile;
738
739     TRACE("(%s,%04x)\n", debugstr_a(path), mode );
740     hfile = create_file_OF( path, mode & ~OF_CREATE );
741     return HandleToLong(hfile);
742 }
743
744 /***********************************************************************
745  *           _lread   (KERNEL32.@)
746  */
747 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
748 {
749     DWORD result;
750     if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
751         return HFILE_ERROR;
752     return result;
753 }
754
755
756 /***********************************************************************
757  *           _llseek   (KERNEL32.@)
758  */
759 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
760 {
761     return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
762 }
763
764
765 /***********************************************************************
766  *           _lwrite   (KERNEL32.@)
767  */
768 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
769 {
770     return (UINT)_hwrite( hFile, buffer, (LONG)count );
771 }
772
773
774 /***********************************************************************
775  *           FlushFileBuffers   (KERNEL32.@)
776  */
777 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
778 {
779     NTSTATUS            nts;
780     IO_STATUS_BLOCK     ioblk;
781
782     if (is_console_handle( hFile ))
783     {
784         /* this will fail (as expected) for an output handle */
785         return FlushConsoleInputBuffer( hFile );
786     }
787     nts = NtFlushBuffersFile( hFile, &ioblk );
788     if (nts != STATUS_SUCCESS)
789     {
790         SetLastError( RtlNtStatusToDosError( nts ) );
791         return FALSE;
792     }
793
794     return TRUE;
795 }
796
797
798 /***********************************************************************
799  *           GetFileType   (KERNEL32.@)
800  */
801 DWORD WINAPI GetFileType( HANDLE hFile )
802 {
803     FILE_FS_DEVICE_INFORMATION info;
804     IO_STATUS_BLOCK io;
805     NTSTATUS status;
806
807     if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
808
809     status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
810     if (status != STATUS_SUCCESS)
811     {
812         SetLastError( RtlNtStatusToDosError(status) );
813         return FILE_TYPE_UNKNOWN;
814     }
815
816     switch(info.DeviceType)
817     {
818     case FILE_DEVICE_NULL:
819     case FILE_DEVICE_SERIAL_PORT:
820     case FILE_DEVICE_PARALLEL_PORT:
821     case FILE_DEVICE_TAPE:
822     case FILE_DEVICE_UNKNOWN:
823         return FILE_TYPE_CHAR;
824     case FILE_DEVICE_NAMED_PIPE:
825         return FILE_TYPE_PIPE;
826     default:
827         return FILE_TYPE_DISK;
828     }
829 }
830
831
832 /***********************************************************************
833  *             GetFileInformationByHandle   (KERNEL32.@)
834  */
835 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
836 {
837     FILE_ALL_INFORMATION all_info;
838     IO_STATUS_BLOCK io;
839     NTSTATUS status;
840
841     status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
842     if (status == STATUS_SUCCESS)
843     {
844         info->dwFileAttributes                = all_info.BasicInformation.FileAttributes;
845         info->ftCreationTime.dwHighDateTime   = all_info.BasicInformation.CreationTime.u.HighPart;
846         info->ftCreationTime.dwLowDateTime    = all_info.BasicInformation.CreationTime.u.LowPart;
847         info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
848         info->ftLastAccessTime.dwLowDateTime  = all_info.BasicInformation.LastAccessTime.u.LowPart;
849         info->ftLastWriteTime.dwHighDateTime  = all_info.BasicInformation.LastWriteTime.u.HighPart;
850         info->ftLastWriteTime.dwLowDateTime   = all_info.BasicInformation.LastWriteTime.u.LowPart;
851         info->dwVolumeSerialNumber            = 0;  /* FIXME */
852         info->nFileSizeHigh                   = all_info.StandardInformation.EndOfFile.u.HighPart;
853         info->nFileSizeLow                    = all_info.StandardInformation.EndOfFile.u.LowPart;
854         info->nNumberOfLinks                  = all_info.StandardInformation.NumberOfLinks;
855         info->nFileIndexHigh                  = all_info.InternalInformation.IndexNumber.u.HighPart;
856         info->nFileIndexLow                   = all_info.InternalInformation.IndexNumber.u.LowPart;
857         return TRUE;
858     }
859     SetLastError( RtlNtStatusToDosError(status) );
860     return FALSE;
861 }
862
863
864 /***********************************************************************
865  *           GetFileSize   (KERNEL32.@)
866  *
867  * Retrieve the size of a file.
868  *
869  * PARAMS
870  *  hFile        [I] File to retrieve size of.
871  *  filesizehigh [O] On return, the high bits of the file size.
872  *
873  * RETURNS
874  *  Success: The low bits of the file size.
875  *  Failure: INVALID_FILE_SIZE. As this is could also be a success value,
876  *           check GetLastError() for values other than ERROR_SUCCESS.
877  */
878 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
879 {
880     LARGE_INTEGER size;
881     if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
882     if (filesizehigh) *filesizehigh = size.u.HighPart;
883     if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
884     return size.u.LowPart;
885 }
886
887
888 /***********************************************************************
889  *           GetFileSizeEx   (KERNEL32.@)
890  *
891  * Retrieve the size of a file.
892  *
893  * PARAMS
894  *  hFile        [I] File to retrieve size of.
895  *  lpFileSIze   [O] On return, the size of the file.
896  *
897  * RETURNS
898  *  Success: TRUE.
899  *  Failure: FALSE, check GetLastError().
900  */
901 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
902 {
903     FILE_STANDARD_INFORMATION info;
904     IO_STATUS_BLOCK io;
905     NTSTATUS status;
906
907     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
908     if (status == STATUS_SUCCESS)
909     {
910         *lpFileSize = info.EndOfFile;
911         return TRUE;
912     }
913     SetLastError( RtlNtStatusToDosError(status) );
914     return FALSE;
915 }
916
917
918 /**************************************************************************
919  *           SetEndOfFile   (KERNEL32.@)
920  *
921  * Sets the current position as the end of the file.
922  *
923  * PARAMS
924  *  hFile [I] File handle.
925  *
926  * RETURNS
927  *  Success: TRUE.
928  *  Failure: FALSE, check GetLastError().
929  */
930 BOOL WINAPI SetEndOfFile( HANDLE hFile )
931 {
932     FILE_POSITION_INFORMATION pos;
933     FILE_END_OF_FILE_INFORMATION eof;
934     IO_STATUS_BLOCK io;
935     NTSTATUS status;
936
937     status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
938     if (status == STATUS_SUCCESS)
939     {
940         eof.EndOfFile = pos.CurrentByteOffset;
941         status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
942     }
943     if (status == STATUS_SUCCESS) return TRUE;
944     SetLastError( RtlNtStatusToDosError(status) );
945     return FALSE;
946 }
947
948
949 /***********************************************************************
950  *           SetFilePointer   (KERNEL32.@)
951  */
952 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
953 {
954     LARGE_INTEGER dist, newpos;
955
956     if (highword)
957     {
958         dist.u.LowPart  = distance;
959         dist.u.HighPart = *highword;
960     }
961     else dist.QuadPart = distance;
962
963     if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
964
965     if (highword) *highword = newpos.u.HighPart;
966     if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
967     return newpos.u.LowPart;
968 }
969
970
971 /***********************************************************************
972  *           SetFilePointerEx   (KERNEL32.@)
973  */
974 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
975                               LARGE_INTEGER *newpos, DWORD method )
976 {
977     LONGLONG pos;
978     IO_STATUS_BLOCK io;
979     FILE_POSITION_INFORMATION info;
980
981     switch(method)
982     {
983     case FILE_BEGIN:
984         pos = distance.QuadPart;
985         break;
986     case FILE_CURRENT:
987         if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
988             goto error;
989         pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
990         break;
991     case FILE_END:
992         {
993             FILE_END_OF_FILE_INFORMATION eof;
994             if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
995                 goto error;
996             pos = eof.EndOfFile.QuadPart + distance.QuadPart;
997         }
998         break;
999     default:
1000         SetLastError( ERROR_INVALID_PARAMETER );
1001         return FALSE;
1002     }
1003
1004     if (pos < 0)
1005     {
1006         SetLastError( ERROR_NEGATIVE_SEEK );
1007         return FALSE;
1008     }
1009
1010     info.CurrentByteOffset.QuadPart = pos;
1011     if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1012         goto error;
1013     if (newpos) newpos->QuadPart = pos;
1014     return TRUE;
1015
1016 error:
1017     SetLastError( RtlNtStatusToDosError(io.u.Status) );
1018     return FALSE;
1019 }
1020
1021 /***********************************************************************
1022  *           GetFileTime   (KERNEL32.@)
1023  */
1024 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1025                          FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1026 {
1027     FILE_BASIC_INFORMATION info;
1028     IO_STATUS_BLOCK io;
1029     NTSTATUS status;
1030
1031     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1032     if (status == STATUS_SUCCESS)
1033     {
1034         if (lpCreationTime)
1035         {
1036             lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1037             lpCreationTime->dwLowDateTime  = info.CreationTime.u.LowPart;
1038         }
1039         if (lpLastAccessTime)
1040         {
1041             lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1042             lpLastAccessTime->dwLowDateTime  = info.LastAccessTime.u.LowPart;
1043         }
1044         if (lpLastWriteTime)
1045         {
1046             lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1047             lpLastWriteTime->dwLowDateTime  = info.LastWriteTime.u.LowPart;
1048         }
1049         return TRUE;
1050     }
1051     SetLastError( RtlNtStatusToDosError(status) );
1052     return FALSE;
1053 }
1054
1055
1056 /***********************************************************************
1057  *              SetFileTime   (KERNEL32.@)
1058  */
1059 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1060                          const FILETIME *atime, const FILETIME *mtime )
1061 {
1062     FILE_BASIC_INFORMATION info;
1063     IO_STATUS_BLOCK io;
1064     NTSTATUS status;
1065
1066     memset( &info, 0, sizeof(info) );
1067     if (ctime)
1068     {
1069         info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1070         info.CreationTime.u.LowPart  = ctime->dwLowDateTime;
1071     }
1072     if (atime)
1073     {
1074         info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1075         info.LastAccessTime.u.LowPart  = atime->dwLowDateTime;
1076     }
1077     if (mtime)
1078     {
1079         info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1080         info.LastWriteTime.u.LowPart  = mtime->dwLowDateTime;
1081     }
1082
1083     status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1084     if (status == STATUS_SUCCESS) return TRUE;
1085     SetLastError( RtlNtStatusToDosError(status) );
1086     return FALSE;
1087 }
1088
1089
1090 /**************************************************************************
1091  *           LockFile   (KERNEL32.@)
1092  */
1093 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1094                       DWORD count_low, DWORD count_high )
1095 {
1096     NTSTATUS            status;
1097     LARGE_INTEGER       count, offset;
1098
1099     TRACE( "%p %x%08x %x%08x\n",
1100            hFile, offset_high, offset_low, count_high, count_low );
1101
1102     count.u.LowPart = count_low;
1103     count.u.HighPart = count_high;
1104     offset.u.LowPart = offset_low;
1105     offset.u.HighPart = offset_high;
1106
1107     status = NtLockFile( hFile, 0, NULL, NULL,
1108                          NULL, &offset, &count, NULL, TRUE, TRUE );
1109
1110     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1111     return !status;
1112 }
1113
1114
1115 /**************************************************************************
1116  * LockFileEx [KERNEL32.@]
1117  *
1118  * Locks a byte range within an open file for shared or exclusive access.
1119  *
1120  * RETURNS
1121  *   success: TRUE
1122  *   failure: FALSE
1123  *
1124  * NOTES
1125  * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1126  */
1127 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1128                         DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1129 {
1130     NTSTATUS status;
1131     LARGE_INTEGER count, offset;
1132     LPVOID   cvalue = NULL;
1133
1134     if (reserved)
1135     {
1136         SetLastError( ERROR_INVALID_PARAMETER );
1137         return FALSE;
1138     }
1139
1140     TRACE( "%p %x%08x %x%08x flags %x\n",
1141            hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset, 
1142            count_high, count_low, flags );
1143
1144     count.u.LowPart = count_low;
1145     count.u.HighPart = count_high;
1146     offset.u.LowPart = overlapped->u.s.Offset;
1147     offset.u.HighPart = overlapped->u.s.OffsetHigh;
1148
1149     if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1150
1151     status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1152                          NULL, &offset, &count, NULL,
1153                          flags & LOCKFILE_FAIL_IMMEDIATELY,
1154                          flags & LOCKFILE_EXCLUSIVE_LOCK );
1155
1156     if (status) SetLastError( RtlNtStatusToDosError(status) );
1157     return !status;
1158 }
1159
1160
1161 /**************************************************************************
1162  *           UnlockFile   (KERNEL32.@)
1163  */
1164 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1165                         DWORD count_low, DWORD count_high )
1166 {
1167     NTSTATUS    status;
1168     LARGE_INTEGER count, offset;
1169
1170     count.u.LowPart = count_low;
1171     count.u.HighPart = count_high;
1172     offset.u.LowPart = offset_low;
1173     offset.u.HighPart = offset_high;
1174
1175     status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1176     if (status) SetLastError( RtlNtStatusToDosError(status) );
1177     return !status;
1178 }
1179
1180
1181 /**************************************************************************
1182  *           UnlockFileEx   (KERNEL32.@)
1183  */
1184 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1185                           LPOVERLAPPED overlapped )
1186 {
1187     if (reserved)
1188     {
1189         SetLastError( ERROR_INVALID_PARAMETER );
1190         return FALSE;
1191     }
1192     if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1193
1194     return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1195 }
1196
1197
1198 /***********************************************************************
1199  *           Win32HandleToDosFileHandle   (KERNEL32.21)
1200  *
1201  * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1202  * longer valid after this function (even on failure).
1203  *
1204  * Note: this is not exactly right, since on Win95 the Win32 handles
1205  *       are on top of DOS handles and we do it the other way
1206  *       around. Should be good enough though.
1207  */
1208 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1209 {
1210     int i;
1211
1212     if (!handle || (handle == INVALID_HANDLE_VALUE))
1213         return HFILE_ERROR;
1214
1215     FILE_InitProcessDosHandles();
1216     for (i = 0; i < DOS_TABLE_SIZE; i++)
1217         if (!dos_handles[i])
1218         {
1219             dos_handles[i] = handle;
1220             TRACE("Got %d for h32 %p\n", i, handle );
1221             return (HFILE)i;
1222         }
1223     CloseHandle( handle );
1224     SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1225     return HFILE_ERROR;
1226 }
1227
1228
1229 /***********************************************************************
1230  *           DosFileHandleToWin32Handle   (KERNEL32.20)
1231  *
1232  * Return the Win32 handle for a DOS handle.
1233  *
1234  * Note: this is not exactly right, since on Win95 the Win32 handles
1235  *       are on top of DOS handles and we do it the other way
1236  *       around. Should be good enough though.
1237  */
1238 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1239 {
1240     HFILE16 hfile = (HFILE16)handle;
1241     if (hfile < 5) FILE_InitProcessDosHandles();
1242     if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1243     {
1244         SetLastError( ERROR_INVALID_HANDLE );
1245         return INVALID_HANDLE_VALUE;
1246     }
1247     return dos_handles[hfile];
1248 }
1249
1250
1251 /*************************************************************************
1252  *           SetHandleCount   (KERNEL32.@)
1253  */
1254 UINT WINAPI SetHandleCount( UINT count )
1255 {
1256     return min( 256, count );
1257 }
1258
1259
1260 /***********************************************************************
1261  *           DisposeLZ32Handle   (KERNEL32.22)
1262  *
1263  * Note: this is not entirely correct, we should only close the
1264  *       32-bit handle and not the 16-bit one, but we cannot do
1265  *       this because of the way our DOS handles are implemented.
1266  *       It shouldn't break anything though.
1267  */
1268 void WINAPI DisposeLZ32Handle( HANDLE handle )
1269 {
1270     int i;
1271
1272     if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1273
1274     for (i = 5; i < DOS_TABLE_SIZE; i++)
1275         if (dos_handles[i] == handle)
1276         {
1277             dos_handles[i] = 0;
1278             CloseHandle( handle );
1279             break;
1280         }
1281 }
1282
1283 /**************************************************************************
1284  *                      Operations on file names                          *
1285  **************************************************************************/
1286
1287
1288 /*************************************************************************
1289  * CreateFileW [KERNEL32.@]  Creates or opens a file or other object
1290  *
1291  * Creates or opens an object, and returns a handle that can be used to
1292  * access that object.
1293  *
1294  * PARAMS
1295  *
1296  * filename     [in] pointer to filename to be accessed
1297  * access       [in] access mode requested
1298  * sharing      [in] share mode
1299  * sa           [in] pointer to security attributes
1300  * creation     [in] how to create the file
1301  * attributes   [in] attributes for newly created file
1302  * template     [in] handle to file with extended attributes to copy
1303  *
1304  * RETURNS
1305  *   Success: Open handle to specified file
1306  *   Failure: INVALID_HANDLE_VALUE
1307  */
1308 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1309                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1310                               DWORD attributes, HANDLE template )
1311 {
1312     NTSTATUS status;
1313     UINT options;
1314     OBJECT_ATTRIBUTES attr;
1315     UNICODE_STRING nameW;
1316     IO_STATUS_BLOCK io;
1317     HANDLE ret;
1318     DWORD dosdev;
1319     const WCHAR *vxd_name = NULL;
1320     static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1321     static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1322     static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1323     SECURITY_QUALITY_OF_SERVICE qos;
1324
1325     static const UINT nt_disposition[5] =
1326     {
1327         FILE_CREATE,        /* CREATE_NEW */
1328         FILE_OVERWRITE_IF,  /* CREATE_ALWAYS */
1329         FILE_OPEN,          /* OPEN_EXISTING */
1330         FILE_OPEN_IF,       /* OPEN_ALWAYS */
1331         FILE_OVERWRITE      /* TRUNCATE_EXISTING */
1332     };
1333
1334
1335     /* sanity checks */
1336
1337     if (!filename || !filename[0])
1338     {
1339         SetLastError( ERROR_PATH_NOT_FOUND );
1340         return INVALID_HANDLE_VALUE;
1341     }
1342
1343     TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1344           (access & GENERIC_READ)?"GENERIC_READ ":"",
1345           (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1346           (!access)?"QUERY_ACCESS ":"",
1347           (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1348           (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1349           (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1350           creation, attributes);
1351
1352     /* Open a console for CONIN$ or CONOUT$ */
1353
1354     if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1355     {
1356         ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1357         goto done;
1358     }
1359
1360     if (!strncmpW(filename, bkslashes_with_dotW, 4))
1361     {
1362         static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1363         static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1364
1365         if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1366             !strncmpiW( filename + 4, pipeW, 5 ) ||
1367             !strncmpiW( filename + 4, mailslotW, 9 ))
1368         {
1369             dosdev = 0;
1370         }
1371         else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1372         {
1373             dosdev += MAKELONG( 0, 4*sizeof(WCHAR) );  /* adjust position to start of filename */
1374         }
1375         else if (GetVersion() & 0x80000000)
1376         {
1377             vxd_name = filename + 4;
1378         }
1379     }
1380     else dosdev = RtlIsDosDeviceName_U( filename );
1381
1382     if (dosdev)
1383     {
1384         static const WCHAR conW[] = {'C','O','N'};
1385
1386         if (LOWORD(dosdev) == sizeof(conW) &&
1387             !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1388         {
1389             switch (access & (GENERIC_READ|GENERIC_WRITE))
1390             {
1391             case GENERIC_READ:
1392                 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1393                 goto done;
1394             case GENERIC_WRITE:
1395                 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1396                 goto done;
1397             default:
1398                 SetLastError( ERROR_FILE_NOT_FOUND );
1399                 return INVALID_HANDLE_VALUE;
1400             }
1401         }
1402     }
1403
1404     if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1405     {
1406         SetLastError( ERROR_INVALID_PARAMETER );
1407         return INVALID_HANDLE_VALUE;
1408     }
1409
1410     if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1411     {
1412         SetLastError( ERROR_PATH_NOT_FOUND );
1413         return INVALID_HANDLE_VALUE;
1414     }
1415
1416     /* now call NtCreateFile */
1417
1418     options = 0;
1419     if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1420         options |= FILE_OPEN_FOR_BACKUP_INTENT;
1421     else
1422         options |= FILE_NON_DIRECTORY_FILE;
1423     if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1424     {
1425         options |= FILE_DELETE_ON_CLOSE;
1426         access |= DELETE;
1427     }
1428     if (attributes & FILE_FLAG_NO_BUFFERING)
1429         options |= FILE_NO_INTERMEDIATE_BUFFERING;
1430     if (!(attributes & FILE_FLAG_OVERLAPPED))
1431         options |= FILE_SYNCHRONOUS_IO_ALERT;
1432     if (attributes & FILE_FLAG_RANDOM_ACCESS)
1433         options |= FILE_RANDOM_ACCESS;
1434     attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1435
1436     attr.Length = sizeof(attr);
1437     attr.RootDirectory = 0;
1438     attr.Attributes = OBJ_CASE_INSENSITIVE;
1439     attr.ObjectName = &nameW;
1440     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1441     if (attributes & SECURITY_SQOS_PRESENT)
1442     {
1443         qos.Length = sizeof(qos);
1444         qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1445         qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1446         qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1447         attr.SecurityQualityOfService = &qos;
1448     }
1449     else
1450         attr.SecurityQualityOfService = NULL;
1451
1452     if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1453
1454     status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1455                            sharing, nt_disposition[creation - CREATE_NEW],
1456                            options, NULL, 0 );
1457     if (status)
1458     {
1459         if (vxd_name && vxd_name[0] && (ret = VXD_Open( vxd_name, access, sa ))) goto done;
1460
1461         WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1462         ret = INVALID_HANDLE_VALUE;
1463
1464         /* In the case file creation was rejected due to CREATE_NEW flag
1465          * was specified and file with that name already exists, correct
1466          * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1467          * Note: RtlNtStatusToDosError is not the subject to blame here.
1468          */
1469         if (status == STATUS_OBJECT_NAME_COLLISION)
1470             SetLastError( ERROR_FILE_EXISTS );
1471         else
1472             SetLastError( RtlNtStatusToDosError(status) );
1473     }
1474     else
1475     {
1476         if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1477             (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1478             SetLastError( ERROR_ALREADY_EXISTS );
1479         else
1480             SetLastError( 0 );
1481     }
1482     RtlFreeUnicodeString( &nameW );
1483
1484  done:
1485     if (!ret) ret = INVALID_HANDLE_VALUE;
1486     TRACE("returning %p\n", ret);
1487     return ret;
1488 }
1489
1490
1491
1492 /*************************************************************************
1493  *              CreateFileA              (KERNEL32.@)
1494  *
1495  * See CreateFileW.
1496  */
1497 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1498                            LPSECURITY_ATTRIBUTES sa, DWORD creation,
1499                            DWORD attributes, HANDLE template)
1500 {
1501     WCHAR *nameW;
1502
1503     if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1504     return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1505 }
1506
1507
1508 /***********************************************************************
1509  *           DeleteFileW   (KERNEL32.@)
1510  *
1511  * Delete a file.
1512  *
1513  * PARAMS
1514  *  path [I] Path to the file to delete.
1515  *
1516  * RETURNS
1517  *  Success: TRUE.
1518  *  Failure: FALSE, check GetLastError().
1519  */
1520 BOOL WINAPI DeleteFileW( LPCWSTR path )
1521 {
1522     UNICODE_STRING nameW;
1523     OBJECT_ATTRIBUTES attr;
1524     NTSTATUS status;
1525     HANDLE hFile;
1526     IO_STATUS_BLOCK io;
1527
1528     TRACE("%s\n", debugstr_w(path) );
1529
1530     if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1531     {
1532         SetLastError( ERROR_PATH_NOT_FOUND );
1533         return FALSE;
1534     }
1535
1536     attr.Length = sizeof(attr);
1537     attr.RootDirectory = 0;
1538     attr.Attributes = OBJ_CASE_INSENSITIVE;
1539     attr.ObjectName = &nameW;
1540     attr.SecurityDescriptor = NULL;
1541     attr.SecurityQualityOfService = NULL;
1542
1543     status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1544                           &attr, &io, NULL, 0,
1545                           FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1546                           FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1547     if (status == STATUS_SUCCESS) status = NtClose(hFile);
1548
1549     RtlFreeUnicodeString( &nameW );
1550     if (status)
1551     {
1552         SetLastError( RtlNtStatusToDosError(status) );
1553         return FALSE;
1554     }
1555     return TRUE;
1556 }
1557
1558
1559 /***********************************************************************
1560  *           DeleteFileA   (KERNEL32.@)
1561  *
1562  * See DeleteFileW.
1563  */
1564 BOOL WINAPI DeleteFileA( LPCSTR path )
1565 {
1566     WCHAR *pathW;
1567
1568     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1569     return DeleteFileW( pathW );
1570 }
1571
1572
1573 /**************************************************************************
1574  *           ReplaceFileW   (KERNEL32.@)
1575  *           ReplaceFile    (KERNEL32.@)
1576  */
1577 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1578                          LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1579                          LPVOID lpExclude, LPVOID lpReserved)
1580 {
1581     UNICODE_STRING nt_replaced_name, nt_replacement_name;
1582     ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1583     HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1584     DWORD error = ERROR_SUCCESS;
1585     UINT replaced_flags;
1586     BOOL ret = FALSE;
1587     NTSTATUS status;
1588     IO_STATUS_BLOCK io;
1589     OBJECT_ATTRIBUTES attr;
1590
1591     if (dwReplaceFlags)
1592         FIXME("Ignoring flags %x\n", dwReplaceFlags);
1593
1594     /* First two arguments are mandatory */
1595     if (!lpReplacedFileName || !lpReplacementFileName)
1596     {
1597         SetLastError(ERROR_INVALID_PARAMETER);
1598         return FALSE;
1599     }
1600
1601     unix_replaced_name.Buffer = NULL;
1602     unix_replacement_name.Buffer = NULL;
1603     unix_backup_name.Buffer = NULL;
1604
1605     attr.Length = sizeof(attr);
1606     attr.RootDirectory = 0;
1607     attr.Attributes = OBJ_CASE_INSENSITIVE;
1608     attr.ObjectName = NULL;
1609     attr.SecurityDescriptor = NULL;
1610     attr.SecurityQualityOfService = NULL;
1611
1612     /* Open the "replaced" file for reading and writing */
1613     if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1614     {
1615         error = ERROR_PATH_NOT_FOUND;
1616         goto fail;
1617     }
1618     replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1619     attr.ObjectName = &nt_replaced_name;
1620     status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1621                         &attr, &io,
1622                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1623                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1624     if (status == STATUS_SUCCESS)
1625         status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1626     RtlFreeUnicodeString(&nt_replaced_name);
1627     if (status != STATUS_SUCCESS)
1628     {
1629         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1630             error = ERROR_FILE_NOT_FOUND;
1631         else
1632             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1633         goto fail;
1634     }
1635
1636     /*
1637      * Open the replacement file for reading, writing, and deleting
1638      * (writing and deleting are needed when finished)
1639      */
1640     if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1641     {
1642         error = ERROR_PATH_NOT_FOUND;
1643         goto fail;
1644     }
1645     attr.ObjectName = &nt_replacement_name;
1646     status = NtOpenFile(&hReplacement,
1647                         GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1648                         &attr, &io, 0,
1649                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1650     if (status == STATUS_SUCCESS)
1651         status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1652     RtlFreeUnicodeString(&nt_replacement_name);
1653     if (status != STATUS_SUCCESS)
1654     {
1655         error = RtlNtStatusToDosError(status);
1656         goto fail;
1657     }
1658
1659     /* If the user wants a backup then that needs to be performed first */
1660     if (lpBackupFileName)
1661     {
1662         UNICODE_STRING nt_backup_name;
1663         FILE_BASIC_INFORMATION replaced_info;
1664
1665         /* Obtain the file attributes from the "replaced" file */
1666         status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1667                                         sizeof(replaced_info),
1668                                         FileBasicInformation);
1669         if (status != STATUS_SUCCESS)
1670         {
1671             error = RtlNtStatusToDosError(status);
1672             goto fail;
1673         }
1674
1675         if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1676         {
1677             error = ERROR_PATH_NOT_FOUND;
1678             goto fail;
1679         }
1680         attr.ObjectName = &nt_backup_name;
1681         /* Open the backup with permissions to write over it */
1682         status = NtCreateFile(&hBackup, GENERIC_WRITE,
1683                               &attr, &io, NULL, replaced_info.FileAttributes,
1684                               FILE_SHARE_WRITE, FILE_OPEN_IF,
1685                               FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1686                               NULL, 0);
1687         if (status == STATUS_SUCCESS)
1688             status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1689         if (status != STATUS_SUCCESS)
1690         {
1691             error = RtlNtStatusToDosError(status);
1692             goto fail;
1693         }
1694
1695         /* If an existing backup exists then copy over it */
1696         if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1697         {
1698             error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1699             goto fail;
1700         }
1701     }
1702
1703     /*
1704      * Now that the backup has been performed (if requested), copy the replacement
1705      * into place
1706      */
1707     if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1708     {
1709         if (errno == EACCES)
1710         {
1711             /* Inappropriate permissions on "replaced", rename will fail */
1712             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1713             goto fail;
1714         }
1715         /* on failure we need to indicate whether a backup was made */
1716         if (!lpBackupFileName)
1717             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1718         else
1719             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1720         goto fail;
1721     }
1722     /* Success! */
1723     ret = TRUE;
1724
1725     /* Perform resource cleanup */
1726 fail:
1727     if (hBackup) CloseHandle(hBackup);
1728     if (hReplaced) CloseHandle(hReplaced);
1729     if (hReplacement) CloseHandle(hReplacement);
1730     RtlFreeAnsiString(&unix_backup_name);
1731     RtlFreeAnsiString(&unix_replacement_name);
1732     RtlFreeAnsiString(&unix_replaced_name);
1733
1734     /* If there was an error, set the error code */
1735     if(!ret)
1736         SetLastError(error);
1737     return ret;
1738 }
1739
1740
1741 /**************************************************************************
1742  *           ReplaceFileA (KERNEL32.@)
1743  */
1744 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1745                          LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1746                          LPVOID lpExclude, LPVOID lpReserved)
1747 {
1748     WCHAR *replacedW, *replacementW, *backupW = NULL;
1749     BOOL ret;
1750
1751     /* This function only makes sense when the first two parameters are defined */
1752     if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1753     {
1754         SetLastError(ERROR_INVALID_PARAMETER);
1755         return FALSE;
1756     }
1757     if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1758     {
1759         HeapFree( GetProcessHeap(), 0, replacedW );
1760         SetLastError(ERROR_INVALID_PARAMETER);
1761         return FALSE;
1762     }
1763     /* The backup parameter, however, is optional */
1764     if (lpBackupFileName)
1765     {
1766         if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1767         {
1768             HeapFree( GetProcessHeap(), 0, replacedW );
1769             HeapFree( GetProcessHeap(), 0, replacementW );
1770             SetLastError(ERROR_INVALID_PARAMETER);
1771             return FALSE;
1772         }
1773     }
1774     ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1775     HeapFree( GetProcessHeap(), 0, replacedW );
1776     HeapFree( GetProcessHeap(), 0, replacementW );
1777     HeapFree( GetProcessHeap(), 0, backupW );
1778     return ret;
1779 }
1780
1781
1782 /*************************************************************************
1783  *           FindFirstFileExW  (KERNEL32.@)
1784  *
1785  * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1786  * results as FindExSearchNameMatch
1787  */
1788 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1789                                 LPVOID data, FINDEX_SEARCH_OPS search_op,
1790                                 LPVOID filter, DWORD flags)
1791 {
1792     WCHAR *mask, *p;
1793     FIND_FIRST_INFO *info = NULL;
1794     UNICODE_STRING nt_name;
1795     OBJECT_ATTRIBUTES attr;
1796     IO_STATUS_BLOCK io;
1797     NTSTATUS status;
1798     DWORD device = 0;
1799
1800     TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1801
1802     if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1803         || flags != 0)
1804     {
1805         FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1806         return INVALID_HANDLE_VALUE;
1807     }
1808     if (level != FindExInfoStandard)
1809     {
1810         FIXME("info level %d not implemented\n", level );
1811         return INVALID_HANDLE_VALUE;
1812     }
1813
1814     if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1815     {
1816         SetLastError( ERROR_PATH_NOT_FOUND );
1817         return INVALID_HANDLE_VALUE;
1818     }
1819
1820     if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1821     {
1822         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1823         goto error;
1824     }
1825
1826     if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1827     {
1828         static const WCHAR dotW[] = {'.',0};
1829         WCHAR *dir = NULL;
1830
1831         /* we still need to check that the directory can be opened */
1832
1833         if (HIWORD(device))
1834         {
1835             if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1836             {
1837                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1838                 goto error;
1839             }
1840             memcpy( dir, filename, HIWORD(device) );
1841             dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1842         }
1843         RtlFreeUnicodeString( &nt_name );
1844         if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1845         {
1846             HeapFree( GetProcessHeap(), 0, dir );
1847             SetLastError( ERROR_PATH_NOT_FOUND );
1848             goto error;
1849         }
1850         HeapFree( GetProcessHeap(), 0, dir );
1851         RtlInitUnicodeString( &info->mask, NULL );
1852     }
1853     else if (!mask || !*mask)
1854     {
1855         SetLastError( ERROR_FILE_NOT_FOUND );
1856         goto error;
1857     }
1858     else
1859     {
1860         if (!RtlCreateUnicodeString( &info->mask, mask ))
1861         {
1862             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1863             goto error;
1864         }
1865
1866         /* truncate dir name before mask */
1867         *mask = 0;
1868         nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1869     }
1870
1871     /* check if path is the root of the drive */
1872     info->is_root = FALSE;
1873     p = nt_name.Buffer + 4;  /* skip \??\ prefix */
1874     if (p[0] && p[1] == ':')
1875     {
1876         p += 2;
1877         while (*p == '\\') p++;
1878         info->is_root = (*p == 0);
1879     }
1880
1881     attr.Length = sizeof(attr);
1882     attr.RootDirectory = 0;
1883     attr.Attributes = OBJ_CASE_INSENSITIVE;
1884     attr.ObjectName = &nt_name;
1885     attr.SecurityDescriptor = NULL;
1886     attr.SecurityQualityOfService = NULL;
1887
1888     status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1889                          FILE_SHARE_READ | FILE_SHARE_WRITE,
1890                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1891
1892     if (status != STATUS_SUCCESS)
1893     {
1894         RtlFreeUnicodeString( &info->mask );
1895         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1896             SetLastError( ERROR_PATH_NOT_FOUND );
1897         else
1898             SetLastError( RtlNtStatusToDosError(status) );
1899         goto error;
1900     }
1901
1902     RtlInitializeCriticalSection( &info->cs );
1903     info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1904     info->path     = nt_name;
1905     info->magic    = FIND_FIRST_MAGIC;
1906     info->data_pos = 0;
1907     info->data_len = 0;
1908     info->search_op = search_op;
1909
1910     if (device)
1911     {
1912         WIN32_FIND_DATAW *wfd = data;
1913
1914         memset( wfd, 0, sizeof(*wfd) );
1915         memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1916         wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1917         CloseHandle( info->handle );
1918         info->handle = 0;
1919     }
1920     else
1921     {
1922         IO_STATUS_BLOCK io;
1923
1924         NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1925                               FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1926         if (io.u.Status)
1927         {
1928             FindClose( info );
1929             SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1930             return INVALID_HANDLE_VALUE;
1931         }
1932         info->data_len = io.Information;
1933         if (!FindNextFileW( info, data ))
1934         {
1935             TRACE( "%s not found\n", debugstr_w(filename) );
1936             FindClose( info );
1937             SetLastError( ERROR_FILE_NOT_FOUND );
1938             return INVALID_HANDLE_VALUE;
1939         }
1940         if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1941         {
1942             /* we can't find two files with the same name */
1943             CloseHandle( info->handle );
1944             info->handle = 0;
1945         }
1946     }
1947     return info;
1948
1949 error:
1950     HeapFree( GetProcessHeap(), 0, info );
1951     RtlFreeUnicodeString( &nt_name );
1952     return INVALID_HANDLE_VALUE;
1953 }
1954
1955
1956 /*************************************************************************
1957  *           FindNextFileW   (KERNEL32.@)
1958  */
1959 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1960 {
1961     FIND_FIRST_INFO *info;
1962     FILE_BOTH_DIR_INFORMATION *dir_info;
1963     BOOL ret = FALSE;
1964
1965     TRACE("%p %p\n", handle, data);
1966
1967     if (!handle || handle == INVALID_HANDLE_VALUE)
1968     {
1969         SetLastError( ERROR_INVALID_HANDLE );
1970         return ret;
1971     }
1972     info = (FIND_FIRST_INFO *)handle;
1973     if (info->magic != FIND_FIRST_MAGIC)
1974     {
1975         SetLastError( ERROR_INVALID_HANDLE );
1976         return ret;
1977     }
1978
1979     RtlEnterCriticalSection( &info->cs );
1980
1981     if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1982     else for (;;)
1983     {
1984         if (info->data_pos >= info->data_len)  /* need to read some more data */
1985         {
1986             IO_STATUS_BLOCK io;
1987
1988             NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1989                                   FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1990             if (io.u.Status)
1991             {
1992                 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1993                 if (io.u.Status == STATUS_NO_MORE_FILES)
1994                 {
1995                     CloseHandle( info->handle );
1996                     info->handle = 0;
1997                 }
1998                 break;
1999             }
2000             info->data_len = io.Information;
2001             info->data_pos = 0;
2002         }
2003
2004         dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2005
2006         if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2007         else info->data_pos = info->data_len;
2008
2009         /* don't return '.' and '..' in the root of the drive */
2010         if (info->is_root)
2011         {
2012             if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2013             if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2014                 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2015         }
2016
2017         /* check for dir symlink */
2018         if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2019             (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2020             strpbrkW( info->mask.Buffer, wildcardsW ))
2021         {
2022             if (!check_dir_symlink( info, dir_info )) continue;
2023         }
2024
2025         data->dwFileAttributes = dir_info->FileAttributes;
2026         data->ftCreationTime   = *(FILETIME *)&dir_info->CreationTime;
2027         data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2028         data->ftLastWriteTime  = *(FILETIME *)&dir_info->LastWriteTime;
2029         data->nFileSizeHigh    = dir_info->EndOfFile.QuadPart >> 32;
2030         data->nFileSizeLow     = (DWORD)dir_info->EndOfFile.QuadPart;
2031         data->dwReserved0      = 0;
2032         data->dwReserved1      = 0;
2033
2034         memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2035         data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2036         memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2037         data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2038
2039         TRACE("returning %s (%s)\n",
2040               debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2041
2042         ret = TRUE;
2043         break;
2044     }
2045
2046     RtlLeaveCriticalSection( &info->cs );
2047     return ret;
2048 }
2049
2050
2051 /*************************************************************************
2052  *           FindClose   (KERNEL32.@)
2053  */
2054 BOOL WINAPI FindClose( HANDLE handle )
2055 {
2056     FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
2057
2058     if (!handle || handle == INVALID_HANDLE_VALUE)
2059     {
2060         SetLastError( ERROR_INVALID_HANDLE );
2061         return FALSE;
2062     }
2063
2064     __TRY
2065     {
2066         if (info->magic == FIND_FIRST_MAGIC)
2067         {
2068             RtlEnterCriticalSection( &info->cs );
2069             if (info->magic == FIND_FIRST_MAGIC)  /* in case someone else freed it in the meantime */
2070             {
2071                 info->magic = 0;
2072                 if (info->handle) CloseHandle( info->handle );
2073                 info->handle = 0;
2074                 RtlFreeUnicodeString( &info->mask );
2075                 info->mask.Buffer = NULL;
2076                 RtlFreeUnicodeString( &info->path );
2077                 info->data_pos = 0;
2078                 info->data_len = 0;
2079                 RtlLeaveCriticalSection( &info->cs );
2080                 info->cs.DebugInfo->Spare[0] = 0;
2081                 RtlDeleteCriticalSection( &info->cs );
2082                 HeapFree( GetProcessHeap(), 0, info );
2083             }
2084         }
2085     }
2086     __EXCEPT_PAGE_FAULT
2087     {
2088         WARN("Illegal handle %p\n", handle);
2089         SetLastError( ERROR_INVALID_HANDLE );
2090         return FALSE;
2091     }
2092     __ENDTRY
2093
2094     return TRUE;
2095 }
2096
2097
2098 /*************************************************************************
2099  *           FindFirstFileA   (KERNEL32.@)
2100  */
2101 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2102 {
2103     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2104                             FindExSearchNameMatch, NULL, 0);
2105 }
2106
2107 /*************************************************************************
2108  *           FindFirstFileExA   (KERNEL32.@)
2109  */
2110 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2111                                 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2112                                 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2113 {
2114     HANDLE handle;
2115     WIN32_FIND_DATAA *dataA;
2116     WIN32_FIND_DATAW dataW;
2117     WCHAR *nameW;
2118
2119     if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2120
2121     handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2122     if (handle == INVALID_HANDLE_VALUE) return handle;
2123
2124     dataA = (WIN32_FIND_DATAA *) lpFindFileData;
2125     dataA->dwFileAttributes = dataW.dwFileAttributes;
2126     dataA->ftCreationTime   = dataW.ftCreationTime;
2127     dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2128     dataA->ftLastWriteTime  = dataW.ftLastWriteTime;
2129     dataA->nFileSizeHigh    = dataW.nFileSizeHigh;
2130     dataA->nFileSizeLow     = dataW.nFileSizeLow;
2131     FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2132     FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2133                     sizeof(dataA->cAlternateFileName) );
2134     return handle;
2135 }
2136
2137
2138 /*************************************************************************
2139  *           FindFirstFileW   (KERNEL32.@)
2140  */
2141 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2142 {
2143     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2144                             FindExSearchNameMatch, NULL, 0);
2145 }
2146
2147
2148 /*************************************************************************
2149  *           FindNextFileA   (KERNEL32.@)
2150  */
2151 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2152 {
2153     WIN32_FIND_DATAW dataW;
2154
2155     if (!FindNextFileW( handle, &dataW )) return FALSE;
2156     data->dwFileAttributes = dataW.dwFileAttributes;
2157     data->ftCreationTime   = dataW.ftCreationTime;
2158     data->ftLastAccessTime = dataW.ftLastAccessTime;
2159     data->ftLastWriteTime  = dataW.ftLastWriteTime;
2160     data->nFileSizeHigh    = dataW.nFileSizeHigh;
2161     data->nFileSizeLow     = dataW.nFileSizeLow;
2162     FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2163     FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2164                     sizeof(data->cAlternateFileName) );
2165     return TRUE;
2166 }
2167
2168
2169 /**************************************************************************
2170  *           GetFileAttributesW   (KERNEL32.@)
2171  */
2172 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2173 {
2174     FILE_BASIC_INFORMATION info;
2175     UNICODE_STRING nt_name;
2176     OBJECT_ATTRIBUTES attr;
2177     NTSTATUS status;
2178
2179     TRACE("%s\n", debugstr_w(name));
2180
2181     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2182     {
2183         SetLastError( ERROR_PATH_NOT_FOUND );
2184         return INVALID_FILE_ATTRIBUTES;
2185     }
2186
2187     attr.Length = sizeof(attr);
2188     attr.RootDirectory = 0;
2189     attr.Attributes = OBJ_CASE_INSENSITIVE;
2190     attr.ObjectName = &nt_name;
2191     attr.SecurityDescriptor = NULL;
2192     attr.SecurityQualityOfService = NULL;
2193
2194     status = NtQueryAttributesFile( &attr, &info );
2195     RtlFreeUnicodeString( &nt_name );
2196
2197     if (status == STATUS_SUCCESS) return info.FileAttributes;
2198
2199     /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2200     if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2201
2202     SetLastError( RtlNtStatusToDosError(status) );
2203     return INVALID_FILE_ATTRIBUTES;
2204 }
2205
2206
2207 /**************************************************************************
2208  *           GetFileAttributesA   (KERNEL32.@)
2209  */
2210 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2211 {
2212     WCHAR *nameW;
2213
2214     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2215     return GetFileAttributesW( nameW );
2216 }
2217
2218
2219 /**************************************************************************
2220  *              SetFileAttributesW      (KERNEL32.@)
2221  */
2222 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2223 {
2224     UNICODE_STRING nt_name;
2225     OBJECT_ATTRIBUTES attr;
2226     IO_STATUS_BLOCK io;
2227     NTSTATUS status;
2228     HANDLE handle;
2229
2230     TRACE("%s %x\n", debugstr_w(name), attributes);
2231
2232     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2233     {
2234         SetLastError( ERROR_PATH_NOT_FOUND );
2235         return FALSE;
2236     }
2237
2238     attr.Length = sizeof(attr);
2239     attr.RootDirectory = 0;
2240     attr.Attributes = OBJ_CASE_INSENSITIVE;
2241     attr.ObjectName = &nt_name;
2242     attr.SecurityDescriptor = NULL;
2243     attr.SecurityQualityOfService = NULL;
2244
2245     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2246     RtlFreeUnicodeString( &nt_name );
2247
2248     if (status == STATUS_SUCCESS)
2249     {
2250         FILE_BASIC_INFORMATION info;
2251
2252         memset( &info, 0, sizeof(info) );
2253         info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL;  /* make sure it's not zero */
2254         status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2255         NtClose( handle );
2256     }
2257
2258     if (status == STATUS_SUCCESS) return TRUE;
2259     SetLastError( RtlNtStatusToDosError(status) );
2260     return FALSE;
2261 }
2262
2263
2264 /**************************************************************************
2265  *              SetFileAttributesA      (KERNEL32.@)
2266  */
2267 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2268 {
2269     WCHAR *nameW;
2270
2271     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2272     return SetFileAttributesW( nameW, attributes );
2273 }
2274
2275
2276 /**************************************************************************
2277  *           GetFileAttributesExW   (KERNEL32.@)
2278  */
2279 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2280 {
2281     FILE_NETWORK_OPEN_INFORMATION info;
2282     WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2283     UNICODE_STRING nt_name;
2284     OBJECT_ATTRIBUTES attr;
2285     NTSTATUS status;
2286     
2287     TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2288
2289     if (level != GetFileExInfoStandard)
2290     {
2291         SetLastError( ERROR_INVALID_PARAMETER );
2292         return FALSE;
2293     }
2294
2295     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2296     {
2297         SetLastError( ERROR_PATH_NOT_FOUND );
2298         return FALSE;
2299     }
2300
2301     attr.Length = sizeof(attr);
2302     attr.RootDirectory = 0;
2303     attr.Attributes = OBJ_CASE_INSENSITIVE;
2304     attr.ObjectName = &nt_name;
2305     attr.SecurityDescriptor = NULL;
2306     attr.SecurityQualityOfService = NULL;
2307
2308     status = NtQueryFullAttributesFile( &attr, &info );
2309     RtlFreeUnicodeString( &nt_name );
2310
2311     if (status != STATUS_SUCCESS)
2312     {
2313         SetLastError( RtlNtStatusToDosError(status) );
2314         return FALSE;
2315     }
2316
2317     data->dwFileAttributes = info.FileAttributes;
2318     data->ftCreationTime.dwLowDateTime    = info.CreationTime.u.LowPart;
2319     data->ftCreationTime.dwHighDateTime   = info.CreationTime.u.HighPart;
2320     data->ftLastAccessTime.dwLowDateTime  = info.LastAccessTime.u.LowPart;
2321     data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2322     data->ftLastWriteTime.dwLowDateTime   = info.LastWriteTime.u.LowPart;
2323     data->ftLastWriteTime.dwHighDateTime  = info.LastWriteTime.u.HighPart;
2324     data->nFileSizeLow                    = info.EndOfFile.u.LowPart;
2325     data->nFileSizeHigh                   = info.EndOfFile.u.HighPart;
2326     return TRUE;
2327 }
2328
2329
2330 /**************************************************************************
2331  *           GetFileAttributesExA   (KERNEL32.@)
2332  */
2333 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2334 {
2335     WCHAR *nameW;
2336
2337     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2338     return GetFileAttributesExW( nameW, level, ptr );
2339 }
2340
2341
2342 /******************************************************************************
2343  *           GetCompressedFileSizeW   (KERNEL32.@)
2344  *
2345  * Get the actual number of bytes used on disk.
2346  *
2347  * RETURNS
2348  *    Success: Low-order doubleword of number of bytes
2349  *    Failure: INVALID_FILE_SIZE
2350  */
2351 DWORD WINAPI GetCompressedFileSizeW(
2352     LPCWSTR name,       /* [in]  Pointer to name of file */
2353     LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2354 {
2355     UNICODE_STRING nt_name;
2356     OBJECT_ATTRIBUTES attr;
2357     IO_STATUS_BLOCK io;
2358     NTSTATUS status;
2359     HANDLE handle;
2360     DWORD ret = INVALID_FILE_SIZE;
2361
2362     TRACE("%s %p\n", debugstr_w(name), size_high);
2363
2364     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2365     {
2366         SetLastError( ERROR_PATH_NOT_FOUND );
2367         return INVALID_FILE_SIZE;
2368     }
2369
2370     attr.Length = sizeof(attr);
2371     attr.RootDirectory = 0;
2372     attr.Attributes = OBJ_CASE_INSENSITIVE;
2373     attr.ObjectName = &nt_name;
2374     attr.SecurityDescriptor = NULL;
2375     attr.SecurityQualityOfService = NULL;
2376
2377     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2378     RtlFreeUnicodeString( &nt_name );
2379
2380     if (status == STATUS_SUCCESS)
2381     {
2382         /* we don't support compressed files, simply return the file size */
2383         ret = GetFileSize( handle, size_high );
2384         NtClose( handle );
2385     }
2386     else SetLastError( RtlNtStatusToDosError(status) );
2387
2388     return ret;
2389 }
2390
2391
2392 /******************************************************************************
2393  *           GetCompressedFileSizeA   (KERNEL32.@)
2394  *
2395  * See GetCompressedFileSizeW.
2396  */
2397 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2398 {
2399     WCHAR *nameW;
2400
2401     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2402     return GetCompressedFileSizeW( nameW, size_high );
2403 }
2404
2405
2406 /***********************************************************************
2407  *           OpenFile   (KERNEL32.@)
2408  */
2409 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2410 {
2411     HANDLE handle;
2412     FILETIME filetime;
2413     WORD filedatetime[2];
2414
2415     if (!ofs) return HFILE_ERROR;
2416
2417     TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2418           ((mode & 0x3 )==OF_READ)?"OF_READ":
2419           ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2420           ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2421           ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2422           ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2423           ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2424           ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2425           ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2426           ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2427           ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2428           ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2429           ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2430           ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2431           ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2432           ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2433           ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2434           ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2435         );
2436
2437
2438     ofs->cBytes = sizeof(OFSTRUCT);
2439     ofs->nErrCode = 0;
2440     if (mode & OF_REOPEN) name = ofs->szPathName;
2441
2442     if (!name) return HFILE_ERROR;
2443
2444     TRACE("%s %04x\n", name, mode );
2445
2446     /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2447        Are there any cases where getting the path here is wrong?
2448        Uwe Bonnes 1997 Apr 2 */
2449     if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2450
2451     /* OF_PARSE simply fills the structure */
2452
2453     if (mode & OF_PARSE)
2454     {
2455         ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2456         TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2457         return 0;
2458     }
2459
2460     /* OF_CREATE is completely different from all other options, so
2461        handle it first */
2462
2463     if (mode & OF_CREATE)
2464     {
2465         if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2466             goto error;
2467     }
2468     else
2469     {
2470         /* Now look for the file */
2471
2472         if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2473             goto error;
2474
2475         TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2476
2477         if (mode & OF_DELETE)
2478         {
2479             if (!DeleteFileA( ofs->szPathName )) goto error;
2480             TRACE("(%s): OF_DELETE return = OK\n", name);
2481             return TRUE;
2482         }
2483
2484         handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2485         if (handle == INVALID_HANDLE_VALUE) goto error;
2486
2487         GetFileTime( handle, NULL, NULL, &filetime );
2488         FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2489         if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2490         {
2491             if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2492             {
2493                 CloseHandle( handle );
2494                 WARN("(%s): OF_VERIFY failed\n", name );
2495                 /* FIXME: what error here? */
2496                 SetLastError( ERROR_FILE_NOT_FOUND );
2497                 goto error;
2498             }
2499         }
2500         ofs->Reserved1 = filedatetime[0];
2501         ofs->Reserved2 = filedatetime[1];
2502     }
2503     TRACE("(%s): OK, return = %p\n", name, handle );
2504     if (mode & OF_EXIST)  /* Return TRUE instead of a handle */
2505     {
2506         CloseHandle( handle );
2507         return TRUE;
2508     }
2509     return HandleToLong(handle);
2510
2511 error:  /* We get here if there was an error opening the file */
2512     ofs->nErrCode = GetLastError();
2513     WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2514     return HFILE_ERROR;
2515 }