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