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