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