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