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