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