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