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