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