wbemprox: Return an empty object if the path is NULL or empty.
[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 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1013 {
1014     FIXME("%p %u %p %u - stub\n", file, class, info, size);
1015     return FALSE;
1016 }
1017
1018 /***********************************************************************
1019  *           SetFilePointer   (KERNEL32.@)
1020  */
1021 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1022 {
1023     LARGE_INTEGER dist, newpos;
1024
1025     if (highword)
1026     {
1027         dist.u.LowPart  = distance;
1028         dist.u.HighPart = *highword;
1029     }
1030     else dist.QuadPart = distance;
1031
1032     if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1033
1034     if (highword) *highword = newpos.u.HighPart;
1035     if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1036     return newpos.u.LowPart;
1037 }
1038
1039
1040 /***********************************************************************
1041  *           SetFilePointerEx   (KERNEL32.@)
1042  */
1043 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1044                               LARGE_INTEGER *newpos, DWORD method )
1045 {
1046     LONGLONG pos;
1047     IO_STATUS_BLOCK io;
1048     FILE_POSITION_INFORMATION info;
1049
1050     switch(method)
1051     {
1052     case FILE_BEGIN:
1053         pos = distance.QuadPart;
1054         break;
1055     case FILE_CURRENT:
1056         if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1057             goto error;
1058         pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1059         break;
1060     case FILE_END:
1061         {
1062             FILE_END_OF_FILE_INFORMATION eof;
1063             if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1064                 goto error;
1065             pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1066         }
1067         break;
1068     default:
1069         SetLastError( ERROR_INVALID_PARAMETER );
1070         return FALSE;
1071     }
1072
1073     if (pos < 0)
1074     {
1075         SetLastError( ERROR_NEGATIVE_SEEK );
1076         return FALSE;
1077     }
1078
1079     info.CurrentByteOffset.QuadPart = pos;
1080     if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1081         goto error;
1082     if (newpos) newpos->QuadPart = pos;
1083     return TRUE;
1084
1085 error:
1086     SetLastError( RtlNtStatusToDosError(io.u.Status) );
1087     return FALSE;
1088 }
1089
1090 /***********************************************************************
1091  *           SetFileValidData   (KERNEL32.@)
1092  */
1093 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1094 {
1095     FILE_VALID_DATA_LENGTH_INFORMATION info;
1096     IO_STATUS_BLOCK io;
1097     NTSTATUS status;
1098
1099     info.ValidDataLength.QuadPart = ValidDataLength;
1100     status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1101
1102     if (status == STATUS_SUCCESS) return TRUE;
1103     SetLastError( RtlNtStatusToDosError(status) );
1104     return FALSE;
1105 }
1106
1107 /***********************************************************************
1108  *           GetFileTime   (KERNEL32.@)
1109  */
1110 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1111                          FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1112 {
1113     FILE_BASIC_INFORMATION info;
1114     IO_STATUS_BLOCK io;
1115     NTSTATUS status;
1116
1117     status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1118     if (status == STATUS_SUCCESS)
1119     {
1120         if (lpCreationTime)
1121         {
1122             lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1123             lpCreationTime->dwLowDateTime  = info.CreationTime.u.LowPart;
1124         }
1125         if (lpLastAccessTime)
1126         {
1127             lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1128             lpLastAccessTime->dwLowDateTime  = info.LastAccessTime.u.LowPart;
1129         }
1130         if (lpLastWriteTime)
1131         {
1132             lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1133             lpLastWriteTime->dwLowDateTime  = info.LastWriteTime.u.LowPart;
1134         }
1135         return TRUE;
1136     }
1137     SetLastError( RtlNtStatusToDosError(status) );
1138     return FALSE;
1139 }
1140
1141
1142 /***********************************************************************
1143  *              SetFileTime   (KERNEL32.@)
1144  */
1145 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1146                          const FILETIME *atime, const FILETIME *mtime )
1147 {
1148     FILE_BASIC_INFORMATION info;
1149     IO_STATUS_BLOCK io;
1150     NTSTATUS status;
1151
1152     memset( &info, 0, sizeof(info) );
1153     if (ctime)
1154     {
1155         info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1156         info.CreationTime.u.LowPart  = ctime->dwLowDateTime;
1157     }
1158     if (atime)
1159     {
1160         info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1161         info.LastAccessTime.u.LowPart  = atime->dwLowDateTime;
1162     }
1163     if (mtime)
1164     {
1165         info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1166         info.LastWriteTime.u.LowPart  = mtime->dwLowDateTime;
1167     }
1168
1169     status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1170     if (status == STATUS_SUCCESS) return TRUE;
1171     SetLastError( RtlNtStatusToDosError(status) );
1172     return FALSE;
1173 }
1174
1175
1176 /**************************************************************************
1177  *           LockFile   (KERNEL32.@)
1178  */
1179 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1180                       DWORD count_low, DWORD count_high )
1181 {
1182     NTSTATUS            status;
1183     LARGE_INTEGER       count, offset;
1184
1185     TRACE( "%p %x%08x %x%08x\n",
1186            hFile, offset_high, offset_low, count_high, count_low );
1187
1188     count.u.LowPart = count_low;
1189     count.u.HighPart = count_high;
1190     offset.u.LowPart = offset_low;
1191     offset.u.HighPart = offset_high;
1192
1193     status = NtLockFile( hFile, 0, NULL, NULL,
1194                          NULL, &offset, &count, NULL, TRUE, TRUE );
1195
1196     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1197     return !status;
1198 }
1199
1200
1201 /**************************************************************************
1202  * LockFileEx [KERNEL32.@]
1203  *
1204  * Locks a byte range within an open file for shared or exclusive access.
1205  *
1206  * RETURNS
1207  *   success: TRUE
1208  *   failure: FALSE
1209  *
1210  * NOTES
1211  * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1212  */
1213 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1214                         DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1215 {
1216     NTSTATUS status;
1217     LARGE_INTEGER count, offset;
1218     LPVOID   cvalue = NULL;
1219
1220     if (reserved)
1221     {
1222         SetLastError( ERROR_INVALID_PARAMETER );
1223         return FALSE;
1224     }
1225
1226     TRACE( "%p %x%08x %x%08x flags %x\n",
1227            hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset, 
1228            count_high, count_low, flags );
1229
1230     count.u.LowPart = count_low;
1231     count.u.HighPart = count_high;
1232     offset.u.LowPart = overlapped->u.s.Offset;
1233     offset.u.HighPart = overlapped->u.s.OffsetHigh;
1234
1235     if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1236
1237     status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1238                          NULL, &offset, &count, NULL,
1239                          flags & LOCKFILE_FAIL_IMMEDIATELY,
1240                          flags & LOCKFILE_EXCLUSIVE_LOCK );
1241
1242     if (status) SetLastError( RtlNtStatusToDosError(status) );
1243     return !status;
1244 }
1245
1246
1247 /**************************************************************************
1248  *           UnlockFile   (KERNEL32.@)
1249  */
1250 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1251                         DWORD count_low, DWORD count_high )
1252 {
1253     NTSTATUS    status;
1254     LARGE_INTEGER count, offset;
1255
1256     count.u.LowPart = count_low;
1257     count.u.HighPart = count_high;
1258     offset.u.LowPart = offset_low;
1259     offset.u.HighPart = offset_high;
1260
1261     status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1262     if (status) SetLastError( RtlNtStatusToDosError(status) );
1263     return !status;
1264 }
1265
1266
1267 /**************************************************************************
1268  *           UnlockFileEx   (KERNEL32.@)
1269  */
1270 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1271                           LPOVERLAPPED overlapped )
1272 {
1273     if (reserved)
1274     {
1275         SetLastError( ERROR_INVALID_PARAMETER );
1276         return FALSE;
1277     }
1278     if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1279
1280     return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1281 }
1282
1283
1284 /*************************************************************************
1285  *           SetHandleCount   (KERNEL32.@)
1286  */
1287 UINT WINAPI SetHandleCount( UINT count )
1288 {
1289     return count;
1290 }
1291
1292
1293 /**************************************************************************
1294  *                      Operations on file names                          *
1295  **************************************************************************/
1296
1297
1298 /*************************************************************************
1299  * CreateFileW [KERNEL32.@]  Creates or opens a file or other object
1300  *
1301  * Creates or opens an object, and returns a handle that can be used to
1302  * access that object.
1303  *
1304  * PARAMS
1305  *
1306  * filename     [in] pointer to filename to be accessed
1307  * access       [in] access mode requested
1308  * sharing      [in] share mode
1309  * sa           [in] pointer to security attributes
1310  * creation     [in] how to create the file
1311  * attributes   [in] attributes for newly created file
1312  * template     [in] handle to file with extended attributes to copy
1313  *
1314  * RETURNS
1315  *   Success: Open handle to specified file
1316  *   Failure: INVALID_HANDLE_VALUE
1317  */
1318 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1319                               LPSECURITY_ATTRIBUTES sa, DWORD creation,
1320                               DWORD attributes, HANDLE template )
1321 {
1322     NTSTATUS status;
1323     UINT options;
1324     OBJECT_ATTRIBUTES attr;
1325     UNICODE_STRING nameW;
1326     IO_STATUS_BLOCK io;
1327     HANDLE ret;
1328     DWORD dosdev;
1329     const WCHAR *vxd_name = NULL;
1330     static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1331     static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1332     static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1333     SECURITY_QUALITY_OF_SERVICE qos;
1334
1335     static const UINT nt_disposition[5] =
1336     {
1337         FILE_CREATE,        /* CREATE_NEW */
1338         FILE_OVERWRITE_IF,  /* CREATE_ALWAYS */
1339         FILE_OPEN,          /* OPEN_EXISTING */
1340         FILE_OPEN_IF,       /* OPEN_ALWAYS */
1341         FILE_OVERWRITE      /* TRUNCATE_EXISTING */
1342     };
1343
1344
1345     /* sanity checks */
1346
1347     if (!filename || !filename[0])
1348     {
1349         SetLastError( ERROR_PATH_NOT_FOUND );
1350         return INVALID_HANDLE_VALUE;
1351     }
1352
1353     TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1354           (access & GENERIC_READ)?"GENERIC_READ ":"",
1355           (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1356           (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1357           (!access)?"QUERY_ACCESS ":"",
1358           (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1359           (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1360           (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1361           creation, attributes);
1362
1363     /* Open a console for CONIN$ or CONOUT$ */
1364
1365     if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1366     {
1367         ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1368                            creation ? OPEN_EXISTING : 0);
1369         if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1370         goto done;
1371     }
1372
1373     if (!strncmpW(filename, bkslashes_with_dotW, 4))
1374     {
1375         static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1376         static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1377
1378         if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1379             !strncmpiW( filename + 4, pipeW, 5 ) ||
1380             !strncmpiW( filename + 4, mailslotW, 9 ))
1381         {
1382             dosdev = 0;
1383         }
1384         else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1385         {
1386             dosdev += MAKELONG( 0, 4*sizeof(WCHAR) );  /* adjust position to start of filename */
1387         }
1388         else if (GetVersion() & 0x80000000)
1389         {
1390             vxd_name = filename + 4;
1391             if (!creation) creation = OPEN_EXISTING;
1392         }
1393     }
1394     else dosdev = RtlIsDosDeviceName_U( filename );
1395
1396     if (dosdev)
1397     {
1398         static const WCHAR conW[] = {'C','O','N'};
1399
1400         if (LOWORD(dosdev) == sizeof(conW) &&
1401             !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1402         {
1403             switch (access & (GENERIC_READ|GENERIC_WRITE))
1404             {
1405             case GENERIC_READ:
1406                 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1407                 goto done;
1408             case GENERIC_WRITE:
1409                 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1410                 goto done;
1411             default:
1412                 SetLastError( ERROR_FILE_NOT_FOUND );
1413                 return INVALID_HANDLE_VALUE;
1414             }
1415         }
1416     }
1417
1418     if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1419     {
1420         SetLastError( ERROR_INVALID_PARAMETER );
1421         return INVALID_HANDLE_VALUE;
1422     }
1423
1424     if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1425     {
1426         SetLastError( ERROR_PATH_NOT_FOUND );
1427         return INVALID_HANDLE_VALUE;
1428     }
1429
1430     /* now call NtCreateFile */
1431
1432     options = 0;
1433     if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1434         options |= FILE_OPEN_FOR_BACKUP_INTENT;
1435     else
1436         options |= FILE_NON_DIRECTORY_FILE;
1437     if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1438     {
1439         options |= FILE_DELETE_ON_CLOSE;
1440         access |= DELETE;
1441     }
1442     if (attributes & FILE_FLAG_NO_BUFFERING)
1443         options |= FILE_NO_INTERMEDIATE_BUFFERING;
1444     if (!(attributes & FILE_FLAG_OVERLAPPED))
1445         options |= FILE_SYNCHRONOUS_IO_NONALERT;
1446     if (attributes & FILE_FLAG_RANDOM_ACCESS)
1447         options |= FILE_RANDOM_ACCESS;
1448     attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1449
1450     attr.Length = sizeof(attr);
1451     attr.RootDirectory = 0;
1452     attr.Attributes = OBJ_CASE_INSENSITIVE;
1453     attr.ObjectName = &nameW;
1454     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1455     if (attributes & SECURITY_SQOS_PRESENT)
1456     {
1457         qos.Length = sizeof(qos);
1458         qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1459         qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1460         qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1461         attr.SecurityQualityOfService = &qos;
1462     }
1463     else
1464         attr.SecurityQualityOfService = NULL;
1465
1466     if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1467
1468     status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1469                            sharing, nt_disposition[creation - CREATE_NEW],
1470                            options, NULL, 0 );
1471     if (status)
1472     {
1473         if (vxd_name && vxd_name[0])
1474         {
1475             static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1476             if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1477                                                               "__wine_vxd_open" );
1478             if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1479         }
1480
1481         WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1482         ret = INVALID_HANDLE_VALUE;
1483
1484         /* In the case file creation was rejected due to CREATE_NEW flag
1485          * was specified and file with that name already exists, correct
1486          * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1487          * Note: RtlNtStatusToDosError is not the subject to blame here.
1488          */
1489         if (status == STATUS_OBJECT_NAME_COLLISION)
1490             SetLastError( ERROR_FILE_EXISTS );
1491         else
1492             SetLastError( RtlNtStatusToDosError(status) );
1493     }
1494     else
1495     {
1496         if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1497             (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1498             SetLastError( ERROR_ALREADY_EXISTS );
1499         else
1500             SetLastError( 0 );
1501     }
1502     RtlFreeUnicodeString( &nameW );
1503
1504  done:
1505     if (!ret) ret = INVALID_HANDLE_VALUE;
1506     TRACE("returning %p\n", ret);
1507     return ret;
1508 }
1509
1510
1511
1512 /*************************************************************************
1513  *              CreateFileA              (KERNEL32.@)
1514  *
1515  * See CreateFileW.
1516  */
1517 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1518                            LPSECURITY_ATTRIBUTES sa, DWORD creation,
1519                            DWORD attributes, HANDLE template)
1520 {
1521     WCHAR *nameW;
1522
1523     if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1524     return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1525 }
1526
1527
1528 /***********************************************************************
1529  *           DeleteFileW   (KERNEL32.@)
1530  *
1531  * Delete a file.
1532  *
1533  * PARAMS
1534  *  path [I] Path to the file to delete.
1535  *
1536  * RETURNS
1537  *  Success: TRUE.
1538  *  Failure: FALSE, check GetLastError().
1539  */
1540 BOOL WINAPI DeleteFileW( LPCWSTR path )
1541 {
1542     UNICODE_STRING nameW;
1543     OBJECT_ATTRIBUTES attr;
1544     NTSTATUS status;
1545     HANDLE hFile;
1546     IO_STATUS_BLOCK io;
1547
1548     TRACE("%s\n", debugstr_w(path) );
1549
1550     if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1551     {
1552         SetLastError( ERROR_PATH_NOT_FOUND );
1553         return FALSE;
1554     }
1555
1556     attr.Length = sizeof(attr);
1557     attr.RootDirectory = 0;
1558     attr.Attributes = OBJ_CASE_INSENSITIVE;
1559     attr.ObjectName = &nameW;
1560     attr.SecurityDescriptor = NULL;
1561     attr.SecurityQualityOfService = NULL;
1562
1563     status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1564                           &attr, &io, NULL, 0,
1565                           FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1566                           FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1567     if (status == STATUS_SUCCESS) status = NtClose(hFile);
1568
1569     RtlFreeUnicodeString( &nameW );
1570     if (status)
1571     {
1572         SetLastError( RtlNtStatusToDosError(status) );
1573         return FALSE;
1574     }
1575     return TRUE;
1576 }
1577
1578
1579 /***********************************************************************
1580  *           DeleteFileA   (KERNEL32.@)
1581  *
1582  * See DeleteFileW.
1583  */
1584 BOOL WINAPI DeleteFileA( LPCSTR path )
1585 {
1586     WCHAR *pathW;
1587
1588     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1589     return DeleteFileW( pathW );
1590 }
1591
1592
1593 /**************************************************************************
1594  *           ReplaceFileW   (KERNEL32.@)
1595  *           ReplaceFile    (KERNEL32.@)
1596  */
1597 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1598                          LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1599                          LPVOID lpExclude, LPVOID lpReserved)
1600 {
1601     UNICODE_STRING nt_replaced_name, nt_replacement_name;
1602     ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1603     HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1604     DWORD error = ERROR_SUCCESS;
1605     UINT replaced_flags;
1606     BOOL ret = FALSE;
1607     NTSTATUS status;
1608     IO_STATUS_BLOCK io;
1609     OBJECT_ATTRIBUTES attr;
1610
1611     TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1612           debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1613           dwReplaceFlags, lpExclude, lpReserved);
1614
1615     if (dwReplaceFlags)
1616         FIXME("Ignoring flags %x\n", dwReplaceFlags);
1617
1618     /* First two arguments are mandatory */
1619     if (!lpReplacedFileName || !lpReplacementFileName)
1620     {
1621         SetLastError(ERROR_INVALID_PARAMETER);
1622         return FALSE;
1623     }
1624
1625     unix_replaced_name.Buffer = NULL;
1626     unix_replacement_name.Buffer = NULL;
1627     unix_backup_name.Buffer = NULL;
1628
1629     attr.Length = sizeof(attr);
1630     attr.RootDirectory = 0;
1631     attr.Attributes = OBJ_CASE_INSENSITIVE;
1632     attr.ObjectName = NULL;
1633     attr.SecurityDescriptor = NULL;
1634     attr.SecurityQualityOfService = NULL;
1635
1636     /* Open the "replaced" file for reading and writing */
1637     if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1638     {
1639         error = ERROR_PATH_NOT_FOUND;
1640         goto fail;
1641     }
1642     replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1643     attr.ObjectName = &nt_replaced_name;
1644     status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1645                         &attr, &io,
1646                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1647                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1648     if (status == STATUS_SUCCESS)
1649         status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1650     RtlFreeUnicodeString(&nt_replaced_name);
1651     if (status != STATUS_SUCCESS)
1652     {
1653         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1654             error = ERROR_FILE_NOT_FOUND;
1655         else
1656             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1657         goto fail;
1658     }
1659
1660     /*
1661      * Open the replacement file for reading, writing, and deleting
1662      * (writing and deleting are needed when finished)
1663      */
1664     if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1665     {
1666         error = ERROR_PATH_NOT_FOUND;
1667         goto fail;
1668     }
1669     attr.ObjectName = &nt_replacement_name;
1670     status = NtOpenFile(&hReplacement,
1671                         GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1672                         &attr, &io, 0,
1673                         FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1674     if (status == STATUS_SUCCESS)
1675         status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1676     RtlFreeUnicodeString(&nt_replacement_name);
1677     if (status != STATUS_SUCCESS)
1678     {
1679         error = RtlNtStatusToDosError(status);
1680         goto fail;
1681     }
1682
1683     /* If the user wants a backup then that needs to be performed first */
1684     if (lpBackupFileName)
1685     {
1686         UNICODE_STRING nt_backup_name;
1687         FILE_BASIC_INFORMATION replaced_info;
1688
1689         /* Obtain the file attributes from the "replaced" file */
1690         status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1691                                         sizeof(replaced_info),
1692                                         FileBasicInformation);
1693         if (status != STATUS_SUCCESS)
1694         {
1695             error = RtlNtStatusToDosError(status);
1696             goto fail;
1697         }
1698
1699         if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1700         {
1701             error = ERROR_PATH_NOT_FOUND;
1702             goto fail;
1703         }
1704         attr.ObjectName = &nt_backup_name;
1705         /* Open the backup with permissions to write over it */
1706         status = NtCreateFile(&hBackup, GENERIC_WRITE,
1707                               &attr, &io, NULL, replaced_info.FileAttributes,
1708                               FILE_SHARE_WRITE, FILE_OPEN_IF,
1709                               FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1710                               NULL, 0);
1711         if (status == STATUS_SUCCESS)
1712             status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1713         RtlFreeUnicodeString(&nt_backup_name);
1714         if (status != STATUS_SUCCESS)
1715         {
1716             error = RtlNtStatusToDosError(status);
1717             goto fail;
1718         }
1719
1720         /* If an existing backup exists then copy over it */
1721         if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1722         {
1723             error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1724             goto fail;
1725         }
1726     }
1727
1728     /*
1729      * Now that the backup has been performed (if requested), copy the replacement
1730      * into place
1731      */
1732     if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1733     {
1734         if (errno == EACCES)
1735         {
1736             /* Inappropriate permissions on "replaced", rename will fail */
1737             error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1738             goto fail;
1739         }
1740         /* on failure we need to indicate whether a backup was made */
1741         if (!lpBackupFileName)
1742             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1743         else
1744             error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1745         goto fail;
1746     }
1747     /* Success! */
1748     ret = TRUE;
1749
1750     /* Perform resource cleanup */
1751 fail:
1752     if (hBackup) CloseHandle(hBackup);
1753     if (hReplaced) CloseHandle(hReplaced);
1754     if (hReplacement) CloseHandle(hReplacement);
1755     RtlFreeAnsiString(&unix_backup_name);
1756     RtlFreeAnsiString(&unix_replacement_name);
1757     RtlFreeAnsiString(&unix_replaced_name);
1758
1759     /* If there was an error, set the error code */
1760     if(!ret)
1761         SetLastError(error);
1762     return ret;
1763 }
1764
1765
1766 /**************************************************************************
1767  *           ReplaceFileA (KERNEL32.@)
1768  */
1769 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1770                          LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1771                          LPVOID lpExclude, LPVOID lpReserved)
1772 {
1773     WCHAR *replacedW, *replacementW, *backupW = NULL;
1774     BOOL ret;
1775
1776     /* This function only makes sense when the first two parameters are defined */
1777     if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1778     {
1779         SetLastError(ERROR_INVALID_PARAMETER);
1780         return FALSE;
1781     }
1782     if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1783     {
1784         HeapFree( GetProcessHeap(), 0, replacedW );
1785         SetLastError(ERROR_INVALID_PARAMETER);
1786         return FALSE;
1787     }
1788     /* The backup parameter, however, is optional */
1789     if (lpBackupFileName)
1790     {
1791         if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1792         {
1793             HeapFree( GetProcessHeap(), 0, replacedW );
1794             HeapFree( GetProcessHeap(), 0, replacementW );
1795             SetLastError(ERROR_INVALID_PARAMETER);
1796             return FALSE;
1797         }
1798     }
1799     ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1800     HeapFree( GetProcessHeap(), 0, replacedW );
1801     HeapFree( GetProcessHeap(), 0, replacementW );
1802     HeapFree( GetProcessHeap(), 0, backupW );
1803     return ret;
1804 }
1805
1806
1807 /*************************************************************************
1808  *           FindFirstFileExW  (KERNEL32.@)
1809  *
1810  * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1811  * results as FindExSearchNameMatch
1812  */
1813 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1814                                 LPVOID data, FINDEX_SEARCH_OPS search_op,
1815                                 LPVOID filter, DWORD flags)
1816 {
1817     WCHAR *mask, *p;
1818     FIND_FIRST_INFO *info = NULL;
1819     UNICODE_STRING nt_name;
1820     OBJECT_ATTRIBUTES attr;
1821     IO_STATUS_BLOCK io;
1822     NTSTATUS status;
1823     DWORD device = 0;
1824
1825     TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1826
1827     if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1828         || flags != 0)
1829     {
1830         FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1831         return INVALID_HANDLE_VALUE;
1832     }
1833     if (level != FindExInfoStandard)
1834     {
1835         FIXME("info level %d not implemented\n", level );
1836         return INVALID_HANDLE_VALUE;
1837     }
1838
1839     if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1840     {
1841         SetLastError( ERROR_PATH_NOT_FOUND );
1842         return INVALID_HANDLE_VALUE;
1843     }
1844
1845     if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1846     {
1847         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1848         goto error;
1849     }
1850
1851     if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1852     {
1853         static const WCHAR dotW[] = {'.',0};
1854         WCHAR *dir = NULL;
1855
1856         /* we still need to check that the directory can be opened */
1857
1858         if (HIWORD(device))
1859         {
1860             if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1861             {
1862                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1863                 goto error;
1864             }
1865             memcpy( dir, filename, HIWORD(device) );
1866             dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1867         }
1868         RtlFreeUnicodeString( &nt_name );
1869         if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1870         {
1871             HeapFree( GetProcessHeap(), 0, dir );
1872             SetLastError( ERROR_PATH_NOT_FOUND );
1873             goto error;
1874         }
1875         HeapFree( GetProcessHeap(), 0, dir );
1876         RtlInitUnicodeString( &info->mask, NULL );
1877     }
1878     else if (!mask || !*mask)
1879     {
1880         SetLastError( ERROR_FILE_NOT_FOUND );
1881         goto error;
1882     }
1883     else
1884     {
1885         if (!RtlCreateUnicodeString( &info->mask, mask ))
1886         {
1887             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1888             goto error;
1889         }
1890
1891         /* truncate dir name before mask */
1892         *mask = 0;
1893         nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1894     }
1895
1896     /* check if path is the root of the drive */
1897     info->is_root = FALSE;
1898     p = nt_name.Buffer + 4;  /* skip \??\ prefix */
1899     if (p[0] && p[1] == ':')
1900     {
1901         p += 2;
1902         while (*p == '\\') p++;
1903         info->is_root = (*p == 0);
1904     }
1905
1906     attr.Length = sizeof(attr);
1907     attr.RootDirectory = 0;
1908     attr.Attributes = OBJ_CASE_INSENSITIVE;
1909     attr.ObjectName = &nt_name;
1910     attr.SecurityDescriptor = NULL;
1911     attr.SecurityQualityOfService = NULL;
1912
1913     status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1914                          FILE_SHARE_READ | FILE_SHARE_WRITE,
1915                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1916
1917     if (status != STATUS_SUCCESS)
1918     {
1919         RtlFreeUnicodeString( &info->mask );
1920         if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1921             SetLastError( ERROR_PATH_NOT_FOUND );
1922         else
1923             SetLastError( RtlNtStatusToDosError(status) );
1924         goto error;
1925     }
1926
1927     RtlInitializeCriticalSection( &info->cs );
1928     info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1929     info->path     = nt_name;
1930     info->magic    = FIND_FIRST_MAGIC;
1931     info->data_pos = 0;
1932     info->data_len = 0;
1933     info->search_op = search_op;
1934
1935     if (device)
1936     {
1937         WIN32_FIND_DATAW *wfd = data;
1938
1939         memset( wfd, 0, sizeof(*wfd) );
1940         memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1941         wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1942         CloseHandle( info->handle );
1943         info->handle = 0;
1944     }
1945     else
1946     {
1947         IO_STATUS_BLOCK io;
1948
1949         NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1950                               FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1951         if (io.u.Status)
1952         {
1953             FindClose( info );
1954             SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1955             return INVALID_HANDLE_VALUE;
1956         }
1957         info->data_len = io.Information;
1958         if (!FindNextFileW( info, data ))
1959         {
1960             TRACE( "%s not found\n", debugstr_w(filename) );
1961             FindClose( info );
1962             SetLastError( ERROR_FILE_NOT_FOUND );
1963             return INVALID_HANDLE_VALUE;
1964         }
1965         if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1966         {
1967             /* we can't find two files with the same name */
1968             CloseHandle( info->handle );
1969             info->handle = 0;
1970         }
1971     }
1972     return info;
1973
1974 error:
1975     HeapFree( GetProcessHeap(), 0, info );
1976     RtlFreeUnicodeString( &nt_name );
1977     return INVALID_HANDLE_VALUE;
1978 }
1979
1980
1981 /*************************************************************************
1982  *           FindNextFileW   (KERNEL32.@)
1983  */
1984 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1985 {
1986     FIND_FIRST_INFO *info;
1987     FILE_BOTH_DIR_INFORMATION *dir_info;
1988     BOOL ret = FALSE;
1989
1990     TRACE("%p %p\n", handle, data);
1991
1992     if (!handle || handle == INVALID_HANDLE_VALUE)
1993     {
1994         SetLastError( ERROR_INVALID_HANDLE );
1995         return ret;
1996     }
1997     info = handle;
1998     if (info->magic != FIND_FIRST_MAGIC)
1999     {
2000         SetLastError( ERROR_INVALID_HANDLE );
2001         return ret;
2002     }
2003
2004     RtlEnterCriticalSection( &info->cs );
2005
2006     if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2007     else for (;;)
2008     {
2009         if (info->data_pos >= info->data_len)  /* need to read some more data */
2010         {
2011             IO_STATUS_BLOCK io;
2012
2013             NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
2014                                   FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
2015             if (io.u.Status)
2016             {
2017                 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2018                 if (io.u.Status == STATUS_NO_MORE_FILES)
2019                 {
2020                     CloseHandle( info->handle );
2021                     info->handle = 0;
2022                 }
2023                 break;
2024             }
2025             info->data_len = io.Information;
2026             info->data_pos = 0;
2027         }
2028
2029         dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2030
2031         if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2032         else info->data_pos = info->data_len;
2033
2034         /* don't return '.' and '..' in the root of the drive */
2035         if (info->is_root)
2036         {
2037             if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2038             if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2039                 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2040         }
2041
2042         /* check for dir symlink */
2043         if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2044             (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2045             strpbrkW( info->mask.Buffer, wildcardsW ))
2046         {
2047             if (!check_dir_symlink( info, dir_info )) continue;
2048         }
2049
2050         data->dwFileAttributes = dir_info->FileAttributes;
2051         data->ftCreationTime   = *(FILETIME *)&dir_info->CreationTime;
2052         data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2053         data->ftLastWriteTime  = *(FILETIME *)&dir_info->LastWriteTime;
2054         data->nFileSizeHigh    = dir_info->EndOfFile.QuadPart >> 32;
2055         data->nFileSizeLow     = (DWORD)dir_info->EndOfFile.QuadPart;
2056         data->dwReserved0      = 0;
2057         data->dwReserved1      = 0;
2058
2059         memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2060         data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2061         memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2062         data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2063
2064         TRACE("returning %s (%s)\n",
2065               debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2066
2067         ret = TRUE;
2068         break;
2069     }
2070
2071     RtlLeaveCriticalSection( &info->cs );
2072     return ret;
2073 }
2074
2075
2076 /*************************************************************************
2077  *           FindClose   (KERNEL32.@)
2078  */
2079 BOOL WINAPI FindClose( HANDLE handle )
2080 {
2081     FIND_FIRST_INFO *info = handle;
2082
2083     if (!handle || handle == INVALID_HANDLE_VALUE)
2084     {
2085         SetLastError( ERROR_INVALID_HANDLE );
2086         return FALSE;
2087     }
2088
2089     __TRY
2090     {
2091         if (info->magic == FIND_FIRST_MAGIC)
2092         {
2093             RtlEnterCriticalSection( &info->cs );
2094             if (info->magic == FIND_FIRST_MAGIC)  /* in case someone else freed it in the meantime */
2095             {
2096                 info->magic = 0;
2097                 if (info->handle) CloseHandle( info->handle );
2098                 info->handle = 0;
2099                 RtlFreeUnicodeString( &info->mask );
2100                 info->mask.Buffer = NULL;
2101                 RtlFreeUnicodeString( &info->path );
2102                 info->data_pos = 0;
2103                 info->data_len = 0;
2104                 RtlLeaveCriticalSection( &info->cs );
2105                 info->cs.DebugInfo->Spare[0] = 0;
2106                 RtlDeleteCriticalSection( &info->cs );
2107                 HeapFree( GetProcessHeap(), 0, info );
2108             }
2109         }
2110     }
2111     __EXCEPT_PAGE_FAULT
2112     {
2113         WARN("Illegal handle %p\n", handle);
2114         SetLastError( ERROR_INVALID_HANDLE );
2115         return FALSE;
2116     }
2117     __ENDTRY
2118
2119     return TRUE;
2120 }
2121
2122
2123 /*************************************************************************
2124  *           FindFirstFileA   (KERNEL32.@)
2125  */
2126 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2127 {
2128     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2129                             FindExSearchNameMatch, NULL, 0);
2130 }
2131
2132 /*************************************************************************
2133  *           FindFirstFileExA   (KERNEL32.@)
2134  */
2135 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2136                                 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2137                                 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2138 {
2139     HANDLE handle;
2140     WIN32_FIND_DATAA *dataA;
2141     WIN32_FIND_DATAW dataW;
2142     WCHAR *nameW;
2143
2144     if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2145
2146     handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2147     if (handle == INVALID_HANDLE_VALUE) return handle;
2148
2149     dataA = lpFindFileData;
2150     dataA->dwFileAttributes = dataW.dwFileAttributes;
2151     dataA->ftCreationTime   = dataW.ftCreationTime;
2152     dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2153     dataA->ftLastWriteTime  = dataW.ftLastWriteTime;
2154     dataA->nFileSizeHigh    = dataW.nFileSizeHigh;
2155     dataA->nFileSizeLow     = dataW.nFileSizeLow;
2156     FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2157     FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2158                     sizeof(dataA->cAlternateFileName) );
2159     return handle;
2160 }
2161
2162
2163 /*************************************************************************
2164  *           FindFirstFileW   (KERNEL32.@)
2165  */
2166 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2167 {
2168     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2169                             FindExSearchNameMatch, NULL, 0);
2170 }
2171
2172
2173 /*************************************************************************
2174  *           FindNextFileA   (KERNEL32.@)
2175  */
2176 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2177 {
2178     WIN32_FIND_DATAW dataW;
2179
2180     if (!FindNextFileW( handle, &dataW )) return FALSE;
2181     data->dwFileAttributes = dataW.dwFileAttributes;
2182     data->ftCreationTime   = dataW.ftCreationTime;
2183     data->ftLastAccessTime = dataW.ftLastAccessTime;
2184     data->ftLastWriteTime  = dataW.ftLastWriteTime;
2185     data->nFileSizeHigh    = dataW.nFileSizeHigh;
2186     data->nFileSizeLow     = dataW.nFileSizeLow;
2187     FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2188     FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2189                     sizeof(data->cAlternateFileName) );
2190     return TRUE;
2191 }
2192
2193
2194 /**************************************************************************
2195  *           GetFileAttributesW   (KERNEL32.@)
2196  */
2197 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2198 {
2199     FILE_BASIC_INFORMATION info;
2200     UNICODE_STRING nt_name;
2201     OBJECT_ATTRIBUTES attr;
2202     NTSTATUS status;
2203
2204     TRACE("%s\n", debugstr_w(name));
2205
2206     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2207     {
2208         SetLastError( ERROR_PATH_NOT_FOUND );
2209         return INVALID_FILE_ATTRIBUTES;
2210     }
2211
2212     attr.Length = sizeof(attr);
2213     attr.RootDirectory = 0;
2214     attr.Attributes = OBJ_CASE_INSENSITIVE;
2215     attr.ObjectName = &nt_name;
2216     attr.SecurityDescriptor = NULL;
2217     attr.SecurityQualityOfService = NULL;
2218
2219     status = NtQueryAttributesFile( &attr, &info );
2220     RtlFreeUnicodeString( &nt_name );
2221
2222     if (status == STATUS_SUCCESS) return info.FileAttributes;
2223
2224     /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2225     if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2226
2227     SetLastError( RtlNtStatusToDosError(status) );
2228     return INVALID_FILE_ATTRIBUTES;
2229 }
2230
2231
2232 /**************************************************************************
2233  *           GetFileAttributesA   (KERNEL32.@)
2234  */
2235 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2236 {
2237     WCHAR *nameW;
2238
2239     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2240     return GetFileAttributesW( nameW );
2241 }
2242
2243
2244 /**************************************************************************
2245  *              SetFileAttributesW      (KERNEL32.@)
2246  */
2247 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2248 {
2249     UNICODE_STRING nt_name;
2250     OBJECT_ATTRIBUTES attr;
2251     IO_STATUS_BLOCK io;
2252     NTSTATUS status;
2253     HANDLE handle;
2254
2255     TRACE("%s %x\n", debugstr_w(name), attributes);
2256
2257     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2258     {
2259         SetLastError( ERROR_PATH_NOT_FOUND );
2260         return FALSE;
2261     }
2262
2263     attr.Length = sizeof(attr);
2264     attr.RootDirectory = 0;
2265     attr.Attributes = OBJ_CASE_INSENSITIVE;
2266     attr.ObjectName = &nt_name;
2267     attr.SecurityDescriptor = NULL;
2268     attr.SecurityQualityOfService = NULL;
2269
2270     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2271     RtlFreeUnicodeString( &nt_name );
2272
2273     if (status == STATUS_SUCCESS)
2274     {
2275         FILE_BASIC_INFORMATION info;
2276
2277         memset( &info, 0, sizeof(info) );
2278         info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL;  /* make sure it's not zero */
2279         status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2280         NtClose( handle );
2281     }
2282
2283     if (status == STATUS_SUCCESS) return TRUE;
2284     SetLastError( RtlNtStatusToDosError(status) );
2285     return FALSE;
2286 }
2287
2288
2289 /**************************************************************************
2290  *              SetFileAttributesA      (KERNEL32.@)
2291  */
2292 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2293 {
2294     WCHAR *nameW;
2295
2296     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2297     return SetFileAttributesW( nameW, attributes );
2298 }
2299
2300
2301 /**************************************************************************
2302  *           GetFileAttributesExW   (KERNEL32.@)
2303  */
2304 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2305 {
2306     FILE_NETWORK_OPEN_INFORMATION info;
2307     WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2308     UNICODE_STRING nt_name;
2309     OBJECT_ATTRIBUTES attr;
2310     NTSTATUS status;
2311     
2312     TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2313
2314     if (level != GetFileExInfoStandard)
2315     {
2316         SetLastError( ERROR_INVALID_PARAMETER );
2317         return FALSE;
2318     }
2319
2320     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2321     {
2322         SetLastError( ERROR_PATH_NOT_FOUND );
2323         return FALSE;
2324     }
2325
2326     attr.Length = sizeof(attr);
2327     attr.RootDirectory = 0;
2328     attr.Attributes = OBJ_CASE_INSENSITIVE;
2329     attr.ObjectName = &nt_name;
2330     attr.SecurityDescriptor = NULL;
2331     attr.SecurityQualityOfService = NULL;
2332
2333     status = NtQueryFullAttributesFile( &attr, &info );
2334     RtlFreeUnicodeString( &nt_name );
2335
2336     if (status != STATUS_SUCCESS)
2337     {
2338         SetLastError( RtlNtStatusToDosError(status) );
2339         return FALSE;
2340     }
2341
2342     data->dwFileAttributes = info.FileAttributes;
2343     data->ftCreationTime.dwLowDateTime    = info.CreationTime.u.LowPart;
2344     data->ftCreationTime.dwHighDateTime   = info.CreationTime.u.HighPart;
2345     data->ftLastAccessTime.dwLowDateTime  = info.LastAccessTime.u.LowPart;
2346     data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2347     data->ftLastWriteTime.dwLowDateTime   = info.LastWriteTime.u.LowPart;
2348     data->ftLastWriteTime.dwHighDateTime  = info.LastWriteTime.u.HighPart;
2349     data->nFileSizeLow                    = info.EndOfFile.u.LowPart;
2350     data->nFileSizeHigh                   = info.EndOfFile.u.HighPart;
2351     return TRUE;
2352 }
2353
2354
2355 /**************************************************************************
2356  *           GetFileAttributesExA   (KERNEL32.@)
2357  */
2358 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2359 {
2360     WCHAR *nameW;
2361
2362     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2363     return GetFileAttributesExW( nameW, level, ptr );
2364 }
2365
2366
2367 /******************************************************************************
2368  *           GetCompressedFileSizeW   (KERNEL32.@)
2369  *
2370  * Get the actual number of bytes used on disk.
2371  *
2372  * RETURNS
2373  *    Success: Low-order doubleword of number of bytes
2374  *    Failure: INVALID_FILE_SIZE
2375  */
2376 DWORD WINAPI GetCompressedFileSizeW(
2377     LPCWSTR name,       /* [in]  Pointer to name of file */
2378     LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2379 {
2380     UNICODE_STRING nt_name;
2381     OBJECT_ATTRIBUTES attr;
2382     IO_STATUS_BLOCK io;
2383     NTSTATUS status;
2384     HANDLE handle;
2385     DWORD ret = INVALID_FILE_SIZE;
2386
2387     TRACE("%s %p\n", debugstr_w(name), size_high);
2388
2389     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2390     {
2391         SetLastError( ERROR_PATH_NOT_FOUND );
2392         return INVALID_FILE_SIZE;
2393     }
2394
2395     attr.Length = sizeof(attr);
2396     attr.RootDirectory = 0;
2397     attr.Attributes = OBJ_CASE_INSENSITIVE;
2398     attr.ObjectName = &nt_name;
2399     attr.SecurityDescriptor = NULL;
2400     attr.SecurityQualityOfService = NULL;
2401
2402     status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2403     RtlFreeUnicodeString( &nt_name );
2404
2405     if (status == STATUS_SUCCESS)
2406     {
2407         /* we don't support compressed files, simply return the file size */
2408         ret = GetFileSize( handle, size_high );
2409         NtClose( handle );
2410     }
2411     else SetLastError( RtlNtStatusToDosError(status) );
2412
2413     return ret;
2414 }
2415
2416
2417 /******************************************************************************
2418  *           GetCompressedFileSizeA   (KERNEL32.@)
2419  *
2420  * See GetCompressedFileSizeW.
2421  */
2422 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2423 {
2424     WCHAR *nameW;
2425
2426     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2427     return GetCompressedFileSizeW( nameW, size_high );
2428 }
2429
2430
2431 /***********************************************************************
2432  *              OpenVxDHandle (KERNEL32.@)
2433  *
2434  *      This function is supposed to return the corresponding Ring 0
2435  *      ("kernel") handle for a Ring 3 handle in Win9x.
2436  *      Evidently, Wine will have problems with this. But we try anyway,
2437  *      maybe it helps...
2438  */
2439 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2440 {
2441     FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2442     return hHandleRing3;
2443 }
2444
2445
2446 /****************************************************************************
2447  *              DeviceIoControl (KERNEL32.@)
2448  */
2449 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2450                             LPVOID lpvInBuffer, DWORD cbInBuffer,
2451                             LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2452                             LPDWORD lpcbBytesReturned,
2453                             LPOVERLAPPED lpOverlapped)
2454 {
2455     NTSTATUS status;
2456
2457     TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2458            hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2459            lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2460
2461     /* Check if this is a user defined control code for a VxD */
2462
2463     if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2464     {
2465         typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2466         static DeviceIoProc (*vxd_get_proc)(HANDLE);
2467         DeviceIoProc proc = NULL;
2468
2469         if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2470                                                                   "__wine_vxd_get_proc" );
2471         if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2472         if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2473                                lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2474     }
2475
2476     /* Not a VxD, let ntdll handle it */
2477
2478     if (lpOverlapped)
2479     {
2480         LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2481         lpOverlapped->Internal = STATUS_PENDING;
2482         lpOverlapped->InternalHigh = 0;
2483         if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2484             status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2485                                      NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2486                                      dwIoControlCode, lpvInBuffer, cbInBuffer,
2487                                      lpvOutBuffer, cbOutBuffer);
2488         else
2489             status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2490                                            NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2491                                            dwIoControlCode, lpvInBuffer, cbInBuffer,
2492                                            lpvOutBuffer, cbOutBuffer);
2493         if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2494     }
2495     else
2496     {
2497         IO_STATUS_BLOCK iosb;
2498
2499         if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2500             status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2501                                      dwIoControlCode, lpvInBuffer, cbInBuffer,
2502                                      lpvOutBuffer, cbOutBuffer);
2503         else
2504             status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2505                                            dwIoControlCode, lpvInBuffer, cbInBuffer,
2506                                            lpvOutBuffer, cbOutBuffer);
2507         if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2508     }
2509     if (status) SetLastError( RtlNtStatusToDosError(status) );
2510     return !status;
2511 }
2512
2513
2514 /***********************************************************************
2515  *           OpenFile   (KERNEL32.@)
2516  */
2517 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2518 {
2519     HANDLE handle;
2520     FILETIME filetime;
2521     WORD filedatetime[2];
2522
2523     if (!ofs) return HFILE_ERROR;
2524
2525     TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2526           ((mode & 0x3 )==OF_READ)?"OF_READ":
2527           ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2528           ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2529           ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2530           ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2531           ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2532           ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2533           ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2534           ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2535           ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2536           ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2537           ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2538           ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2539           ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2540           ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2541           ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2542           ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2543         );
2544
2545
2546     ofs->cBytes = sizeof(OFSTRUCT);
2547     ofs->nErrCode = 0;
2548     if (mode & OF_REOPEN) name = ofs->szPathName;
2549
2550     if (!name) return HFILE_ERROR;
2551
2552     TRACE("%s %04x\n", name, mode );
2553
2554     /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2555        Are there any cases where getting the path here is wrong?
2556        Uwe Bonnes 1997 Apr 2 */
2557     if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2558
2559     /* OF_PARSE simply fills the structure */
2560
2561     if (mode & OF_PARSE)
2562     {
2563         ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2564         TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2565         return 0;
2566     }
2567
2568     /* OF_CREATE is completely different from all other options, so
2569        handle it first */
2570
2571     if (mode & OF_CREATE)
2572     {
2573         if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2574             goto error;
2575     }
2576     else
2577     {
2578         /* Now look for the file */
2579
2580         if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2581             goto error;
2582
2583         TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2584
2585         if (mode & OF_DELETE)
2586         {
2587             if (!DeleteFileA( ofs->szPathName )) goto error;
2588             TRACE("(%s): OF_DELETE return = OK\n", name);
2589             return TRUE;
2590         }
2591
2592         handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2593         if (handle == INVALID_HANDLE_VALUE) goto error;
2594
2595         GetFileTime( handle, NULL, NULL, &filetime );
2596         FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2597         if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2598         {
2599             if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2600             {
2601                 CloseHandle( handle );
2602                 WARN("(%s): OF_VERIFY failed\n", name );
2603                 /* FIXME: what error here? */
2604                 SetLastError( ERROR_FILE_NOT_FOUND );
2605                 goto error;
2606             }
2607         }
2608         ofs->Reserved1 = filedatetime[0];
2609         ofs->Reserved2 = filedatetime[1];
2610     }
2611     TRACE("(%s): OK, return = %p\n", name, handle );
2612     if (mode & OF_EXIST)  /* Return TRUE instead of a handle */
2613     {
2614         CloseHandle( handle );
2615         return TRUE;
2616     }
2617     return HandleToLong(handle);
2618
2619 error:  /* We get here if there was an error opening the file */
2620     ofs->nErrCode = GetLastError();
2621     WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2622     return HFILE_ERROR;
2623 }
2624
2625
2626 /***********************************************************************
2627  *             OpenFileById (KERNEL32.@)
2628  */
2629 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2630                             DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2631 {
2632     UINT options;
2633     HANDLE result;
2634     OBJECT_ATTRIBUTES attr;
2635     NTSTATUS status;
2636     IO_STATUS_BLOCK io;
2637     UNICODE_STRING objectName;
2638
2639     if (!id)
2640     {
2641         SetLastError( ERROR_INVALID_PARAMETER );
2642         return INVALID_HANDLE_VALUE;
2643     }
2644
2645     options = FILE_OPEN_BY_FILE_ID;
2646     if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2647         options |= FILE_OPEN_FOR_BACKUP_INTENT;
2648     else
2649         options |= FILE_NON_DIRECTORY_FILE;
2650     if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2651     if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2652     if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2653     flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2654
2655     objectName.Length             = sizeof(ULONGLONG);
2656     objectName.Buffer             = (WCHAR *)&id->u.FileId;
2657     attr.Length                   = sizeof(attr);
2658     attr.RootDirectory            = handle;
2659     attr.Attributes               = 0;
2660     attr.ObjectName               = &objectName;
2661     attr.SecurityDescriptor       = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2662     attr.SecurityQualityOfService = NULL;
2663     if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2664
2665     status = NtCreateFile( &result, access, &attr, &io, NULL, flags,
2666                            share, OPEN_EXISTING, options, NULL, 0 );
2667     if (status != STATUS_SUCCESS)
2668     {
2669         SetLastError( RtlNtStatusToDosError( status ) );
2670         return INVALID_HANDLE_VALUE;
2671     }
2672     return result;
2673 }
2674
2675
2676 /***********************************************************************
2677  *           K32EnumDeviceDrivers (KERNEL32.@)
2678  */
2679 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2680 {
2681     FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2682
2683     if (needed)
2684         *needed = 0;
2685
2686     return TRUE;
2687 }
2688
2689 /***********************************************************************
2690  *          K32GetDeviceDriverBaseNameA (KERNEL32.@)
2691  */
2692 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2693 {
2694     FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2695
2696     if (base_name && size)
2697         base_name[0] = '\0';
2698
2699     return 0;
2700 }
2701
2702 /***********************************************************************
2703  *           K32GetDeviceDriverBaseNameW (KERNEL32.@)
2704  */
2705 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2706 {
2707     FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2708
2709     if (base_name && size)
2710         base_name[0] = '\0';
2711
2712     return 0;
2713 }
2714
2715 /***********************************************************************
2716  *           K32GetDeviceDriverFileNameA (KERNEL32.@)
2717  */
2718 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2719 {
2720     FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2721
2722     if (file_name && size)
2723         file_name[0] = '\0';
2724
2725     return 0;
2726 }
2727
2728 /***********************************************************************
2729  *           K32GetDeviceDriverFileNameW (KERNEL32.@)
2730  */
2731 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2732 {
2733     FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2734
2735     if (file_name && size)
2736         file_name[0] = '\0';
2737
2738     return 0;
2739 }