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