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