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