wined3d: Implement multisample resolve for typed resources.
[wine.git] / dlls / kernel32 / file.c
blob1e5b9fe3e73e54dbe4e0821a653d5ffa9361c855
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996, 2004 Alexandre Julliard
6 * Copyright 2008 Jeff Zaroyko
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.
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.
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
23 #include "config.h"
24 #include "wine/port.h"
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
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "winerror.h"
36 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #include "windef.h"
39 #include "winbase.h"
40 #include "winternl.h"
41 #include "winioctl.h"
42 #include "wincon.h"
43 #include "ddk/ntddk.h"
44 #include "kernel_private.h"
45 #include "fileapi.h"
47 #include "wine/exception.h"
48 #include "wine/unicode.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(file);
53 /* info structure for FindFirstFile handle */
54 typedef struct
56 DWORD magic; /* magic number */
57 HANDLE handle; /* handle to directory */
58 CRITICAL_SECTION cs; /* crit section protecting this structure */
59 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
60 FINDEX_INFO_LEVELS level; /* Level passed to FindFirst */
61 UNICODE_STRING path; /* NT path used to open the directory */
62 BOOL is_root; /* is directory the root of the drive? */
63 BOOL wildcard; /* did the mask contain wildcard characters? */
64 UINT data_pos; /* current position in dir data */
65 UINT data_len; /* length of dir data */
66 UINT data_size; /* size of data buffer, or 0 when everything has been read */
67 BYTE data[1]; /* directory data */
68 } FIND_FIRST_INFO;
70 #define FIND_FIRST_MAGIC 0xc0ffee11
72 static const UINT max_entry_size = offsetof( FILE_BOTH_DIRECTORY_INFORMATION, FileName[256] );
74 static BOOL oem_file_apis;
76 static const WCHAR wildcardsW[] = { '*','?',0 };
77 static const WCHAR krnl386W[] = {'k','r','n','l','3','8','6','.','e','x','e','1','6',0};
79 /***********************************************************************
80 * create_file_OF
82 * Wrapper for CreateFile that takes OF_* mode flags.
84 static HANDLE create_file_OF( LPCSTR path, INT mode )
86 DWORD access, sharing, creation;
88 if (mode & OF_CREATE)
90 creation = CREATE_ALWAYS;
91 access = GENERIC_READ | GENERIC_WRITE;
93 else
95 creation = OPEN_EXISTING;
96 switch(mode & 0x03)
98 case OF_READ: access = GENERIC_READ; break;
99 case OF_WRITE: access = GENERIC_WRITE; break;
100 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
101 default: access = 0; break;
105 switch(mode & 0x70)
107 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
108 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
109 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
110 case OF_SHARE_DENY_NONE:
111 case OF_SHARE_COMPAT:
112 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
114 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
118 /***********************************************************************
119 * check_dir_symlink
121 * Check if a dir symlink should be returned by FindNextFile.
123 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
125 UNICODE_STRING str;
126 ANSI_STRING unix_name;
127 struct stat st, parent_st;
128 BOOL ret = TRUE;
129 DWORD len;
131 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
132 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
133 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
134 len = info->path.Length / sizeof(WCHAR);
135 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
136 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
137 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
139 unix_name.Buffer = NULL;
140 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
141 !stat( unix_name.Buffer, &st ))
143 char *p = unix_name.Buffer + unix_name.Length - 1;
145 /* skip trailing slashes */
146 while (p > unix_name.Buffer && *p == '/') p--;
148 while (ret && p > unix_name.Buffer)
150 while (p > unix_name.Buffer && *p != '/') p--;
151 while (p > unix_name.Buffer && *p == '/') p--;
152 p[1] = 0;
153 if (!stat( unix_name.Buffer, &parent_st ) &&
154 parent_st.st_dev == st.st_dev &&
155 parent_st.st_ino == st.st_ino)
157 WARN( "suppressing dir symlink %s pointing to parent %s\n",
158 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
159 debugstr_a( unix_name.Buffer ));
160 ret = FALSE;
164 RtlFreeAnsiString( &unix_name );
165 RtlFreeUnicodeString( &str );
166 return ret;
170 /***********************************************************************
171 * FILE_SetDosError
173 * Set the DOS error code from errno.
175 void FILE_SetDosError(void)
177 int save_errno = errno; /* errno gets overwritten by printf */
179 TRACE("errno = %d %s\n", errno, strerror(errno));
180 switch (save_errno)
182 case EAGAIN:
183 SetLastError( ERROR_SHARING_VIOLATION );
184 break;
185 case EBADF:
186 SetLastError( ERROR_INVALID_HANDLE );
187 break;
188 case ENOSPC:
189 SetLastError( ERROR_HANDLE_DISK_FULL );
190 break;
191 case EACCES:
192 case EPERM:
193 case EROFS:
194 SetLastError( ERROR_ACCESS_DENIED );
195 break;
196 case EBUSY:
197 SetLastError( ERROR_LOCK_VIOLATION );
198 break;
199 case ENOENT:
200 SetLastError( ERROR_FILE_NOT_FOUND );
201 break;
202 case EISDIR:
203 SetLastError( ERROR_CANNOT_MAKE );
204 break;
205 case ENFILE:
206 case EMFILE:
207 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
208 break;
209 case EEXIST:
210 SetLastError( ERROR_FILE_EXISTS );
211 break;
212 case EINVAL:
213 case ESPIPE:
214 SetLastError( ERROR_SEEK );
215 break;
216 case ENOTEMPTY:
217 SetLastError( ERROR_DIR_NOT_EMPTY );
218 break;
219 case ENOEXEC:
220 SetLastError( ERROR_BAD_FORMAT );
221 break;
222 case ENOTDIR:
223 SetLastError( ERROR_PATH_NOT_FOUND );
224 break;
225 case EXDEV:
226 SetLastError( ERROR_NOT_SAME_DEVICE );
227 break;
228 default:
229 WARN("unknown file error: %s\n", strerror(save_errno) );
230 SetLastError( ERROR_GEN_FAILURE );
231 break;
233 errno = save_errno;
237 /***********************************************************************
238 * FILE_name_AtoW
240 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
242 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
243 * there is no possibility for the function to do that twice, taking into
244 * account any called function.
246 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
248 ANSI_STRING str;
249 UNICODE_STRING strW, *pstrW;
250 NTSTATUS status;
252 RtlInitAnsiString( &str, name );
253 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
254 if (oem_file_apis)
255 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
256 else
257 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
258 if (status == STATUS_SUCCESS) return pstrW->Buffer;
260 if (status == STATUS_BUFFER_OVERFLOW)
261 SetLastError( ERROR_FILENAME_EXCED_RANGE );
262 else
263 SetLastError( RtlNtStatusToDosError(status) );
264 return NULL;
268 /***********************************************************************
269 * FILE_name_WtoA
271 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
273 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
275 DWORD ret;
277 if (srclen < 0) srclen = strlenW( src ) + 1;
278 if (oem_file_apis)
279 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
280 else
281 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
282 return ret;
286 /**************************************************************************
287 * SetFileApisToOEM (KERNEL32.@)
289 VOID WINAPI SetFileApisToOEM(void)
291 oem_file_apis = TRUE;
295 /**************************************************************************
296 * SetFileApisToANSI (KERNEL32.@)
298 VOID WINAPI SetFileApisToANSI(void)
300 oem_file_apis = FALSE;
304 /******************************************************************************
305 * AreFileApisANSI (KERNEL32.@)
307 * Determines if file functions are using ANSI
309 * RETURNS
310 * TRUE: Set of file functions is using ANSI code page
311 * FALSE: Set of file functions is using OEM code page
313 BOOL WINAPI AreFileApisANSI(void)
315 return !oem_file_apis;
319 /**************************************************************************
320 * Operations on file handles *
321 **************************************************************************/
323 /******************************************************************
324 * FILE_ReadWriteApc (internal)
326 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
328 LPOVERLAPPED_COMPLETION_ROUTINE cr = apc_user;
330 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
334 /***********************************************************************
335 * ReadFileEx (KERNEL32.@)
337 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
338 LPOVERLAPPED overlapped,
339 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
341 LARGE_INTEGER offset;
342 NTSTATUS status;
343 PIO_STATUS_BLOCK io_status;
345 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
347 if (!overlapped)
349 SetLastError(ERROR_INVALID_PARAMETER);
350 return FALSE;
353 offset.u.LowPart = overlapped->u.s.Offset;
354 offset.u.HighPart = overlapped->u.s.OffsetHigh;
355 io_status = (PIO_STATUS_BLOCK)overlapped;
356 io_status->u.Status = STATUS_PENDING;
357 io_status->Information = 0;
359 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
360 io_status, buffer, bytesToRead, &offset, NULL);
362 if (status && status != STATUS_PENDING)
364 SetLastError( RtlNtStatusToDosError(status) );
365 return FALSE;
367 return TRUE;
371 /***********************************************************************
372 * ReadFileScatter (KERNEL32.@)
374 BOOL WINAPI ReadFileScatter( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
375 LPDWORD reserved, LPOVERLAPPED overlapped )
377 PIO_STATUS_BLOCK io_status;
378 LARGE_INTEGER offset;
379 void *cvalue = NULL;
380 NTSTATUS status;
382 TRACE( "(%p %p %u %p)\n", file, segments, count, overlapped );
384 offset.u.LowPart = overlapped->u.s.Offset;
385 offset.u.HighPart = overlapped->u.s.OffsetHigh;
386 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
387 io_status = (PIO_STATUS_BLOCK)overlapped;
388 io_status->u.Status = STATUS_PENDING;
389 io_status->Information = 0;
391 status = NtReadFileScatter( file, overlapped->hEvent, NULL, cvalue, io_status,
392 segments, count, &offset, NULL );
393 if (status) SetLastError( RtlNtStatusToDosError(status) );
394 return !status;
398 /***********************************************************************
399 * ReadFile (KERNEL32.@)
401 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
402 LPDWORD bytesRead, LPOVERLAPPED overlapped )
404 LARGE_INTEGER offset;
405 PLARGE_INTEGER poffset = NULL;
406 IO_STATUS_BLOCK iosb;
407 PIO_STATUS_BLOCK io_status = &iosb;
408 HANDLE hEvent = 0;
409 NTSTATUS status;
410 LPVOID cvalue = NULL;
412 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
413 bytesRead, overlapped );
415 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
417 if (is_console_handle(hFile))
419 DWORD conread, mode;
420 if (!ReadConsoleA(hFile, buffer, bytesToRead, &conread, NULL) ||
421 !GetConsoleMode(hFile, &mode))
422 return FALSE;
423 /* ctrl-Z (26) means end of file on window (if at beginning of buffer)
424 * but Unix uses ctrl-D (4), and ctrl-Z is a bad idea on Unix :-/
425 * So map both ctrl-D ctrl-Z to EOF.
427 if ((mode & ENABLE_PROCESSED_INPUT) && conread > 0 &&
428 (((char*)buffer)[0] == 26 || ((char*)buffer)[0] == 4))
430 conread = 0;
432 if (bytesRead) *bytesRead = conread;
433 return TRUE;
436 if (overlapped != NULL)
438 offset.u.LowPart = overlapped->u.s.Offset;
439 offset.u.HighPart = overlapped->u.s.OffsetHigh;
440 poffset = &offset;
441 hEvent = overlapped->hEvent;
442 io_status = (PIO_STATUS_BLOCK)overlapped;
443 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
445 else io_status->Information = 0;
446 io_status->u.Status = STATUS_PENDING;
448 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
450 if (status == STATUS_PENDING && !overlapped)
452 WaitForSingleObject( hFile, INFINITE );
453 status = io_status->u.Status;
456 if (bytesRead)
457 *bytesRead = overlapped && status ? 0 : io_status->Information;
459 if (status == STATUS_END_OF_FILE)
461 if (overlapped != NULL)
463 SetLastError( RtlNtStatusToDosError(status) );
464 return FALSE;
467 else if (status && status != STATUS_TIMEOUT)
469 SetLastError( RtlNtStatusToDosError(status) );
470 return FALSE;
472 return TRUE;
476 /***********************************************************************
477 * WriteFileEx (KERNEL32.@)
479 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
480 LPOVERLAPPED overlapped,
481 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
483 LARGE_INTEGER offset;
484 NTSTATUS status;
485 PIO_STATUS_BLOCK io_status;
487 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
489 if (overlapped == NULL)
491 SetLastError(ERROR_INVALID_PARAMETER);
492 return FALSE;
494 offset.u.LowPart = overlapped->u.s.Offset;
495 offset.u.HighPart = overlapped->u.s.OffsetHigh;
497 io_status = (PIO_STATUS_BLOCK)overlapped;
498 io_status->u.Status = STATUS_PENDING;
499 io_status->Information = 0;
501 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
502 io_status, buffer, bytesToWrite, &offset, NULL);
504 if (status && status != STATUS_PENDING)
506 SetLastError( RtlNtStatusToDosError(status) );
507 return FALSE;
509 return TRUE;
513 /***********************************************************************
514 * WriteFileGather (KERNEL32.@)
516 BOOL WINAPI WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
517 LPDWORD reserved, LPOVERLAPPED overlapped )
519 PIO_STATUS_BLOCK io_status;
520 LARGE_INTEGER offset;
521 void *cvalue = NULL;
522 NTSTATUS status;
524 TRACE( "%p %p %u %p\n", file, segments, count, overlapped );
526 offset.u.LowPart = overlapped->u.s.Offset;
527 offset.u.HighPart = overlapped->u.s.OffsetHigh;
528 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
529 io_status = (PIO_STATUS_BLOCK)overlapped;
530 io_status->u.Status = STATUS_PENDING;
531 io_status->Information = 0;
533 status = NtWriteFileGather( file, overlapped->hEvent, NULL, cvalue, io_status,
534 segments, count, &offset, NULL );
535 if (status) SetLastError( RtlNtStatusToDosError(status) );
536 return !status;
540 /***********************************************************************
541 * WriteFile (KERNEL32.@)
543 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
544 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
546 HANDLE hEvent = NULL;
547 LARGE_INTEGER offset;
548 PLARGE_INTEGER poffset = NULL;
549 NTSTATUS status;
550 IO_STATUS_BLOCK iosb;
551 PIO_STATUS_BLOCK piosb = &iosb;
552 LPVOID cvalue = NULL;
554 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
556 if (is_console_handle(hFile))
557 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
559 if (overlapped)
561 offset.u.LowPart = overlapped->u.s.Offset;
562 offset.u.HighPart = overlapped->u.s.OffsetHigh;
563 poffset = &offset;
564 hEvent = overlapped->hEvent;
565 piosb = (PIO_STATUS_BLOCK)overlapped;
566 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
568 else piosb->Information = 0;
569 piosb->u.Status = STATUS_PENDING;
571 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
572 buffer, bytesToWrite, poffset, NULL);
574 if (status == STATUS_PENDING && !overlapped)
576 WaitForSingleObject( hFile, INFINITE );
577 status = piosb->u.Status;
580 if (bytesWritten)
581 *bytesWritten = overlapped && status ? 0 : piosb->Information;
583 if (status && status != STATUS_TIMEOUT)
585 SetLastError( RtlNtStatusToDosError(status) );
586 return FALSE;
588 return TRUE;
592 /***********************************************************************
593 * GetOverlappedResult (KERNEL32.@)
595 * Check the result of an Asynchronous data transfer from a file.
597 * Parameters
598 * HANDLE hFile [in] handle of file to check on
599 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
600 * LPDWORD lpTransferred [in/out] number of bytes transferred
601 * BOOL bWait [in] wait for the transfer to complete ?
603 * RETURNS
604 * TRUE on success
605 * FALSE on failure
607 * If successful (and relevant) lpTransferred will hold the number of
608 * bytes transferred during the async operation.
610 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
611 LPDWORD lpTransferred, BOOL bWait)
613 NTSTATUS status;
615 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
617 status = lpOverlapped->Internal;
618 if (status == STATUS_PENDING)
620 if (!bWait)
622 SetLastError( ERROR_IO_INCOMPLETE );
623 return FALSE;
626 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
627 INFINITE ) == WAIT_FAILED)
628 return FALSE;
630 status = lpOverlapped->Internal;
631 if (status == STATUS_PENDING) status = STATUS_SUCCESS;
634 *lpTransferred = lpOverlapped->InternalHigh;
636 if (status) SetLastError( RtlNtStatusToDosError(status) );
637 return !status;
640 /***********************************************************************
641 * CancelIoEx (KERNEL32.@)
643 * Cancels pending I/O operations on a file given the overlapped used.
645 * PARAMS
646 * handle [I] File handle.
647 * lpOverlapped [I,OPT] pointer to overlapped (if null, cancel all)
649 * RETURNS
650 * Success: TRUE.
651 * Failure: FALSE, check GetLastError().
653 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
655 IO_STATUS_BLOCK io_status;
657 NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
658 if (io_status.u.Status)
660 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
661 return FALSE;
663 return TRUE;
666 /***********************************************************************
667 * CancelIo (KERNEL32.@)
669 * Cancels pending I/O operations initiated by the current thread on a file.
671 * PARAMS
672 * handle [I] File handle.
674 * RETURNS
675 * Success: TRUE.
676 * Failure: FALSE, check GetLastError().
678 BOOL WINAPI CancelIo(HANDLE handle)
680 IO_STATUS_BLOCK io_status;
682 NtCancelIoFile(handle, &io_status);
683 if (io_status.u.Status)
685 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
686 return FALSE;
688 return TRUE;
691 /***********************************************************************
692 * CancelSynchronousIo (KERNEL32.@)
694 * Marks pending synchronous I/O operations issued by the specified thread as cancelled
696 * PARAMS
697 * handle [I] handle to the thread whose I/O operations should be cancelled
699 * RETURNS
700 * Success: TRUE.
701 * Failure: FALSE, check GetLastError().
703 BOOL WINAPI CancelSynchronousIo(HANDLE thread)
705 FIXME("(%p): stub\n", thread);
706 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
707 return FALSE;
710 /***********************************************************************
711 * _hread (KERNEL32.@)
713 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
715 return _lread( hFile, buffer, count );
719 /***********************************************************************
720 * _hwrite (KERNEL32.@)
722 * experimentation yields that _lwrite:
723 * o truncates the file at the current position with
724 * a 0 len write
725 * o returns 0 on a 0 length write
726 * o works with console handles
729 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
731 DWORD result;
733 TRACE("%d %p %d\n", handle, buffer, count );
735 if (!count)
737 /* Expand or truncate at current position */
738 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
739 return 0;
741 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
742 return HFILE_ERROR;
743 return result;
747 /***********************************************************************
748 * _lclose (KERNEL32.@)
750 HFILE WINAPI _lclose( HFILE hFile )
752 TRACE("handle %d\n", hFile );
753 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
757 /***********************************************************************
758 * _lcreat (KERNEL32.@)
760 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
762 HANDLE hfile;
764 /* Mask off all flags not explicitly allowed by the doc */
765 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
766 TRACE("%s %02x\n", path, attr );
767 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
768 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
769 CREATE_ALWAYS, attr, 0 );
770 return HandleToLong(hfile);
774 /***********************************************************************
775 * _lopen (KERNEL32.@)
777 HFILE WINAPI _lopen( LPCSTR path, INT mode )
779 HANDLE hfile;
781 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
782 hfile = create_file_OF( path, mode & ~OF_CREATE );
783 return HandleToLong(hfile);
786 /***********************************************************************
787 * _lread (KERNEL32.@)
789 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
791 DWORD result;
792 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
793 return HFILE_ERROR;
794 return result;
798 /***********************************************************************
799 * _llseek (KERNEL32.@)
801 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
803 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
807 /***********************************************************************
808 * _lwrite (KERNEL32.@)
810 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
812 return (UINT)_hwrite( hFile, buffer, (LONG)count );
816 /***********************************************************************
817 * FlushFileBuffers (KERNEL32.@)
819 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
821 NTSTATUS nts;
822 IO_STATUS_BLOCK ioblk;
824 if (is_console_handle( hFile ))
826 /* this will fail (as expected) for an output handle */
827 return FlushConsoleInputBuffer( hFile );
829 nts = NtFlushBuffersFile( hFile, &ioblk );
830 if (nts != STATUS_SUCCESS)
832 SetLastError( RtlNtStatusToDosError( nts ) );
833 return FALSE;
836 return TRUE;
840 /***********************************************************************
841 * GetFileType (KERNEL32.@)
843 DWORD WINAPI GetFileType( HANDLE hFile )
845 FILE_FS_DEVICE_INFORMATION info;
846 IO_STATUS_BLOCK io;
847 NTSTATUS status;
849 if (hFile == (HANDLE)STD_INPUT_HANDLE || hFile == (HANDLE)STD_OUTPUT_HANDLE
850 || hFile == (HANDLE)STD_ERROR_HANDLE)
851 hFile = GetStdHandle((DWORD_PTR)hFile);
853 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
855 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
856 if (status != STATUS_SUCCESS)
858 SetLastError( RtlNtStatusToDosError(status) );
859 return FILE_TYPE_UNKNOWN;
862 switch(info.DeviceType)
864 case FILE_DEVICE_NULL:
865 case FILE_DEVICE_SERIAL_PORT:
866 case FILE_DEVICE_PARALLEL_PORT:
867 case FILE_DEVICE_TAPE:
868 case FILE_DEVICE_UNKNOWN:
869 return FILE_TYPE_CHAR;
870 case FILE_DEVICE_NAMED_PIPE:
871 return FILE_TYPE_PIPE;
872 default:
873 return FILE_TYPE_DISK;
878 /***********************************************************************
879 * GetFileInformationByHandle (KERNEL32.@)
881 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
883 FILE_ALL_INFORMATION all_info;
884 IO_STATUS_BLOCK io;
885 NTSTATUS status;
887 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
888 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
889 if (status == STATUS_SUCCESS)
891 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
892 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
893 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
894 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
895 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
896 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
897 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
898 info->dwVolumeSerialNumber = 0; /* FIXME */
899 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
900 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
901 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
902 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
903 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
904 return TRUE;
906 SetLastError( RtlNtStatusToDosError(status) );
907 return FALSE;
911 /***********************************************************************
912 * GetFileInformationByHandleEx (KERNEL32.@)
914 BOOL WINAPI GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
915 LPVOID info, DWORD size )
917 NTSTATUS status;
918 IO_STATUS_BLOCK io;
920 switch (class)
922 case FileStreamInfo:
923 case FileCompressionInfo:
924 case FileAttributeTagInfo:
925 case FileRemoteProtocolInfo:
926 case FileFullDirectoryInfo:
927 case FileFullDirectoryRestartInfo:
928 case FileStorageInfo:
929 case FileAlignmentInfo:
930 case FileIdExtdDirectoryInfo:
931 case FileIdExtdDirectoryRestartInfo:
932 FIXME( "%p, %u, %p, %u\n", handle, class, info, size );
933 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
934 return FALSE;
936 case FileBasicInfo:
937 status = NtQueryInformationFile( handle, &io, info, size, FileBasicInformation );
938 break;
940 case FileStandardInfo:
941 status = NtQueryInformationFile( handle, &io, info, size, FileStandardInformation );
942 break;
944 case FileNameInfo:
945 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
946 break;
948 case FileIdInfo:
949 status = NtQueryInformationFile( handle, &io, info, size, FileIdInformation );
950 break;
952 case FileIdBothDirectoryRestartInfo:
953 case FileIdBothDirectoryInfo:
954 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
955 FileIdBothDirectoryInformation, FALSE, NULL,
956 (class == FileIdBothDirectoryRestartInfo) );
957 break;
959 case FileRenameInfo:
960 case FileDispositionInfo:
961 case FileAllocationInfo:
962 case FileIoPriorityHintInfo:
963 case FileEndOfFileInfo:
964 default:
965 SetLastError( ERROR_INVALID_PARAMETER );
966 return FALSE;
969 if (status != STATUS_SUCCESS)
971 SetLastError( RtlNtStatusToDosError( status ) );
972 return FALSE;
974 return TRUE;
978 /***********************************************************************
979 * GetFileSize (KERNEL32.@)
981 * Retrieve the size of a file.
983 * PARAMS
984 * hFile [I] File to retrieve size of.
985 * filesizehigh [O] On return, the high bits of the file size.
987 * RETURNS
988 * Success: The low bits of the file size.
989 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
990 * check GetLastError() for values other than ERROR_SUCCESS.
992 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
994 LARGE_INTEGER size;
995 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
996 if (filesizehigh) *filesizehigh = size.u.HighPart;
997 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
998 return size.u.LowPart;
1002 /***********************************************************************
1003 * GetFileSizeEx (KERNEL32.@)
1005 * Retrieve the size of a file.
1007 * PARAMS
1008 * hFile [I] File to retrieve size of.
1009 * lpFileSIze [O] On return, the size of the file.
1011 * RETURNS
1012 * Success: TRUE.
1013 * Failure: FALSE, check GetLastError().
1015 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
1017 FILE_STANDARD_INFORMATION info;
1018 IO_STATUS_BLOCK io;
1019 NTSTATUS status;
1021 if (is_console_handle( hFile ))
1023 SetLastError( ERROR_INVALID_HANDLE );
1024 return FALSE;
1027 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
1028 if (status == STATUS_SUCCESS)
1030 *lpFileSize = info.EndOfFile;
1031 return TRUE;
1033 SetLastError( RtlNtStatusToDosError(status) );
1034 return FALSE;
1038 /**************************************************************************
1039 * SetEndOfFile (KERNEL32.@)
1041 * Sets the current position as the end of the file.
1043 * PARAMS
1044 * hFile [I] File handle.
1046 * RETURNS
1047 * Success: TRUE.
1048 * Failure: FALSE, check GetLastError().
1050 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1052 FILE_POSITION_INFORMATION pos;
1053 FILE_END_OF_FILE_INFORMATION eof;
1054 IO_STATUS_BLOCK io;
1055 NTSTATUS status;
1057 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
1058 if (status == STATUS_SUCCESS)
1060 eof.EndOfFile = pos.CurrentByteOffset;
1061 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
1063 if (status == STATUS_SUCCESS) return TRUE;
1064 SetLastError( RtlNtStatusToDosError(status) );
1065 return FALSE;
1068 /**************************************************************************
1069 * SetFileCompletionNotificationModes (KERNEL32.@)
1071 BOOL WINAPI SetFileCompletionNotificationModes( HANDLE handle, UCHAR flags )
1073 FIXME("%p %x - stub\n", handle, flags);
1074 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1075 return FALSE;
1079 /***********************************************************************
1080 * SetFileInformationByHandle (KERNEL32.@)
1082 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1084 NTSTATUS status;
1085 IO_STATUS_BLOCK io;
1087 TRACE( "%p %u %p %u\n", file, class, info, size );
1089 switch (class)
1091 case FileBasicInfo:
1092 case FileNameInfo:
1093 case FileRenameInfo:
1094 case FileAllocationInfo:
1095 case FileEndOfFileInfo:
1096 case FileStreamInfo:
1097 case FileIdBothDirectoryInfo:
1098 case FileIdBothDirectoryRestartInfo:
1099 case FileIoPriorityHintInfo:
1100 case FileFullDirectoryInfo:
1101 case FileFullDirectoryRestartInfo:
1102 case FileStorageInfo:
1103 case FileAlignmentInfo:
1104 case FileIdInfo:
1105 case FileIdExtdDirectoryInfo:
1106 case FileIdExtdDirectoryRestartInfo:
1107 FIXME( "%p, %u, %p, %u\n", file, class, info, size );
1108 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1109 return FALSE;
1111 case FileDispositionInfo:
1112 status = NtSetInformationFile( file, &io, info, size, FileDispositionInformation );
1113 break;
1115 case FileStandardInfo:
1116 case FileCompressionInfo:
1117 case FileAttributeTagInfo:
1118 case FileRemoteProtocolInfo:
1119 default:
1120 SetLastError( ERROR_INVALID_PARAMETER );
1121 return FALSE;
1124 if (status != STATUS_SUCCESS)
1126 SetLastError( RtlNtStatusToDosError( status ) );
1127 return FALSE;
1129 return TRUE;
1133 /***********************************************************************
1134 * SetFilePointer (KERNEL32.@)
1136 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1138 LARGE_INTEGER dist, newpos;
1140 if (highword)
1142 dist.u.LowPart = distance;
1143 dist.u.HighPart = *highword;
1145 else dist.QuadPart = distance;
1147 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1149 if (highword) *highword = newpos.u.HighPart;
1150 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1151 return newpos.u.LowPart;
1155 /***********************************************************************
1156 * SetFilePointerEx (KERNEL32.@)
1158 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1159 LARGE_INTEGER *newpos, DWORD method )
1161 LONGLONG pos;
1162 IO_STATUS_BLOCK io;
1163 FILE_POSITION_INFORMATION info;
1165 switch(method)
1167 case FILE_BEGIN:
1168 pos = distance.QuadPart;
1169 break;
1170 case FILE_CURRENT:
1171 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1172 goto error;
1173 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1174 break;
1175 case FILE_END:
1177 FILE_END_OF_FILE_INFORMATION eof;
1178 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1179 goto error;
1180 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1182 break;
1183 default:
1184 SetLastError( ERROR_INVALID_PARAMETER );
1185 return FALSE;
1188 if (pos < 0)
1190 SetLastError( ERROR_NEGATIVE_SEEK );
1191 return FALSE;
1194 info.CurrentByteOffset.QuadPart = pos;
1195 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1196 goto error;
1197 if (newpos) newpos->QuadPart = pos;
1198 return TRUE;
1200 error:
1201 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1202 return FALSE;
1205 /***********************************************************************
1206 * SetFileValidData (KERNEL32.@)
1208 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1210 FILE_VALID_DATA_LENGTH_INFORMATION info;
1211 IO_STATUS_BLOCK io;
1212 NTSTATUS status;
1214 info.ValidDataLength.QuadPart = ValidDataLength;
1215 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1217 if (status == STATUS_SUCCESS) return TRUE;
1218 SetLastError( RtlNtStatusToDosError(status) );
1219 return FALSE;
1222 /***********************************************************************
1223 * GetFileTime (KERNEL32.@)
1225 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1226 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1228 FILE_BASIC_INFORMATION info;
1229 IO_STATUS_BLOCK io;
1230 NTSTATUS status;
1232 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1233 if (status == STATUS_SUCCESS)
1235 if (lpCreationTime)
1237 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1238 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1240 if (lpLastAccessTime)
1242 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1243 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1245 if (lpLastWriteTime)
1247 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1248 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1250 return TRUE;
1252 SetLastError( RtlNtStatusToDosError(status) );
1253 return FALSE;
1257 /***********************************************************************
1258 * SetFileTime (KERNEL32.@)
1260 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1261 const FILETIME *atime, const FILETIME *mtime )
1263 FILE_BASIC_INFORMATION info;
1264 IO_STATUS_BLOCK io;
1265 NTSTATUS status;
1267 memset( &info, 0, sizeof(info) );
1268 if (ctime)
1270 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1271 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1273 if (atime)
1275 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1276 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1278 if (mtime)
1280 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1281 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1284 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1285 if (status == STATUS_SUCCESS) return TRUE;
1286 SetLastError( RtlNtStatusToDosError(status) );
1287 return FALSE;
1291 /**************************************************************************
1292 * LockFile (KERNEL32.@)
1294 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1295 DWORD count_low, DWORD count_high )
1297 NTSTATUS status;
1298 LARGE_INTEGER count, offset;
1300 TRACE( "%p %x%08x %x%08x\n",
1301 hFile, offset_high, offset_low, count_high, count_low );
1303 count.u.LowPart = count_low;
1304 count.u.HighPart = count_high;
1305 offset.u.LowPart = offset_low;
1306 offset.u.HighPart = offset_high;
1308 status = NtLockFile( hFile, 0, NULL, NULL,
1309 NULL, &offset, &count, NULL, TRUE, TRUE );
1311 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1312 return !status;
1316 /**************************************************************************
1317 * LockFileEx [KERNEL32.@]
1319 * Locks a byte range within an open file for shared or exclusive access.
1321 * RETURNS
1322 * success: TRUE
1323 * failure: FALSE
1325 * NOTES
1326 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1328 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1329 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1331 NTSTATUS status;
1332 LARGE_INTEGER count, offset;
1333 LPVOID cvalue = NULL;
1335 if (reserved)
1337 SetLastError( ERROR_INVALID_PARAMETER );
1338 return FALSE;
1341 TRACE( "%p %x%08x %x%08x flags %x\n",
1342 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1343 count_high, count_low, flags );
1345 count.u.LowPart = count_low;
1346 count.u.HighPart = count_high;
1347 offset.u.LowPart = overlapped->u.s.Offset;
1348 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1350 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1352 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1353 NULL, &offset, &count, NULL,
1354 flags & LOCKFILE_FAIL_IMMEDIATELY,
1355 flags & LOCKFILE_EXCLUSIVE_LOCK );
1357 if (status) SetLastError( RtlNtStatusToDosError(status) );
1358 return !status;
1362 /**************************************************************************
1363 * UnlockFile (KERNEL32.@)
1365 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1366 DWORD count_low, DWORD count_high )
1368 NTSTATUS status;
1369 LARGE_INTEGER count, offset;
1371 count.u.LowPart = count_low;
1372 count.u.HighPart = count_high;
1373 offset.u.LowPart = offset_low;
1374 offset.u.HighPart = offset_high;
1376 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1377 if (status) SetLastError( RtlNtStatusToDosError(status) );
1378 return !status;
1382 /**************************************************************************
1383 * UnlockFileEx (KERNEL32.@)
1385 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1386 LPOVERLAPPED overlapped )
1388 if (reserved)
1390 SetLastError( ERROR_INVALID_PARAMETER );
1391 return FALSE;
1393 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1395 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1399 /*************************************************************************
1400 * SetHandleCount (KERNEL32.@)
1402 UINT WINAPI SetHandleCount( UINT count )
1404 return count;
1408 /**************************************************************************
1409 * Operations on file names *
1410 **************************************************************************/
1413 /*************************************************************************
1414 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1416 * Creates or opens an object, and returns a handle that can be used to
1417 * access that object.
1419 * PARAMS
1421 * filename [in] pointer to filename to be accessed
1422 * access [in] access mode requested
1423 * sharing [in] share mode
1424 * sa [in] pointer to security attributes
1425 * creation [in] how to create the file
1426 * attributes [in] attributes for newly created file
1427 * template [in] handle to file with extended attributes to copy
1429 * RETURNS
1430 * Success: Open handle to specified file
1431 * Failure: INVALID_HANDLE_VALUE
1433 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1434 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1435 DWORD attributes, HANDLE template )
1437 NTSTATUS status;
1438 UINT options;
1439 OBJECT_ATTRIBUTES attr;
1440 UNICODE_STRING nameW;
1441 IO_STATUS_BLOCK io;
1442 HANDLE ret;
1443 DWORD dosdev;
1444 const WCHAR *vxd_name = NULL;
1445 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1446 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1447 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1448 SECURITY_QUALITY_OF_SERVICE qos;
1450 static const UINT nt_disposition[5] =
1452 FILE_CREATE, /* CREATE_NEW */
1453 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1454 FILE_OPEN, /* OPEN_EXISTING */
1455 FILE_OPEN_IF, /* OPEN_ALWAYS */
1456 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1460 /* sanity checks */
1462 if (!filename || !filename[0])
1464 SetLastError( ERROR_PATH_NOT_FOUND );
1465 return INVALID_HANDLE_VALUE;
1468 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1469 (access & GENERIC_READ)?"GENERIC_READ ":"",
1470 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1471 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1472 (!access)?"QUERY_ACCESS ":"",
1473 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1474 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1475 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1476 creation, attributes);
1478 /* Open a console for CONIN$ or CONOUT$ */
1480 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1482 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1483 creation ? OPEN_EXISTING : 0);
1484 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1485 goto done;
1488 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1490 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1491 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1493 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1494 !strncmpiW( filename + 4, pipeW, 5 ) ||
1495 !strncmpiW( filename + 4, mailslotW, 9 ))
1497 dosdev = 0;
1499 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1501 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1503 else if (GetVersion() & 0x80000000)
1505 vxd_name = filename + 4;
1506 if (!creation) creation = OPEN_EXISTING;
1509 else dosdev = RtlIsDosDeviceName_U( filename );
1511 if (dosdev)
1513 static const WCHAR conW[] = {'C','O','N'};
1515 if (LOWORD(dosdev) == sizeof(conW) &&
1516 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1518 switch (access & (GENERIC_READ|GENERIC_WRITE))
1520 case GENERIC_READ:
1521 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1522 goto done;
1523 case GENERIC_WRITE:
1524 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1525 goto done;
1526 default:
1527 SetLastError( ERROR_FILE_NOT_FOUND );
1528 return INVALID_HANDLE_VALUE;
1533 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1535 SetLastError( ERROR_INVALID_PARAMETER );
1536 return INVALID_HANDLE_VALUE;
1539 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1541 SetLastError( ERROR_PATH_NOT_FOUND );
1542 return INVALID_HANDLE_VALUE;
1545 /* now call NtCreateFile */
1547 options = 0;
1548 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1549 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1550 else
1551 options |= FILE_NON_DIRECTORY_FILE;
1552 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1554 options |= FILE_DELETE_ON_CLOSE;
1555 access |= DELETE;
1557 if (attributes & FILE_FLAG_NO_BUFFERING)
1558 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1559 if (!(attributes & FILE_FLAG_OVERLAPPED))
1560 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1561 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1562 options |= FILE_RANDOM_ACCESS;
1563 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1565 attr.Length = sizeof(attr);
1566 attr.RootDirectory = 0;
1567 attr.Attributes = OBJ_CASE_INSENSITIVE;
1568 attr.ObjectName = &nameW;
1569 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1570 if (attributes & SECURITY_SQOS_PRESENT)
1572 qos.Length = sizeof(qos);
1573 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1574 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1575 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1576 attr.SecurityQualityOfService = &qos;
1578 else
1579 attr.SecurityQualityOfService = NULL;
1581 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1583 status = NtCreateFile( &ret, access | SYNCHRONIZE, &attr, &io, NULL, attributes,
1584 sharing, nt_disposition[creation - CREATE_NEW],
1585 options, NULL, 0 );
1586 if (status)
1588 if (vxd_name && vxd_name[0])
1590 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1591 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleW(krnl386W),
1592 "__wine_vxd_open" );
1593 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1596 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1597 ret = INVALID_HANDLE_VALUE;
1599 /* In the case file creation was rejected due to CREATE_NEW flag
1600 * was specified and file with that name already exists, correct
1601 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1602 * Note: RtlNtStatusToDosError is not the subject to blame here.
1604 if (status == STATUS_OBJECT_NAME_COLLISION)
1605 SetLastError( ERROR_FILE_EXISTS );
1606 else
1607 SetLastError( RtlNtStatusToDosError(status) );
1609 else
1611 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1612 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1613 SetLastError( ERROR_ALREADY_EXISTS );
1614 else
1615 SetLastError( 0 );
1617 RtlFreeUnicodeString( &nameW );
1619 done:
1620 if (!ret) ret = INVALID_HANDLE_VALUE;
1621 TRACE("returning %p\n", ret);
1622 return ret;
1627 /*************************************************************************
1628 * CreateFileA (KERNEL32.@)
1630 * See CreateFileW.
1632 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1633 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1634 DWORD attributes, HANDLE template)
1636 WCHAR *nameW;
1638 if ((GetVersion() & 0x80000000) && IsBadStringPtrA(filename, -1)) return INVALID_HANDLE_VALUE;
1639 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1640 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1643 /*************************************************************************
1644 * CreateFile2 (KERNEL32.@)
1646 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1647 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1649 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1650 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1651 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1653 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1655 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1658 /***********************************************************************
1659 * DeleteFileW (KERNEL32.@)
1661 * Delete a file.
1663 * PARAMS
1664 * path [I] Path to the file to delete.
1666 * RETURNS
1667 * Success: TRUE.
1668 * Failure: FALSE, check GetLastError().
1670 BOOL WINAPI DeleteFileW( LPCWSTR path )
1672 UNICODE_STRING nameW;
1673 OBJECT_ATTRIBUTES attr;
1674 NTSTATUS status;
1675 HANDLE hFile;
1676 IO_STATUS_BLOCK io;
1678 TRACE("%s\n", debugstr_w(path) );
1680 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1682 SetLastError( ERROR_PATH_NOT_FOUND );
1683 return FALSE;
1686 attr.Length = sizeof(attr);
1687 attr.RootDirectory = 0;
1688 attr.Attributes = OBJ_CASE_INSENSITIVE;
1689 attr.ObjectName = &nameW;
1690 attr.SecurityDescriptor = NULL;
1691 attr.SecurityQualityOfService = NULL;
1693 status = NtCreateFile(&hFile, SYNCHRONIZE | DELETE, &attr, &io, NULL, 0,
1694 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1695 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1696 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1698 RtlFreeUnicodeString( &nameW );
1699 if (status)
1701 SetLastError( RtlNtStatusToDosError(status) );
1702 return FALSE;
1704 return TRUE;
1708 /***********************************************************************
1709 * DeleteFileA (KERNEL32.@)
1711 * See DeleteFileW.
1713 BOOL WINAPI DeleteFileA( LPCSTR path )
1715 WCHAR *pathW;
1717 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1718 return DeleteFileW( pathW );
1722 /**************************************************************************
1723 * ReplaceFileW (KERNEL32.@)
1724 * ReplaceFile (KERNEL32.@)
1726 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1727 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1728 LPVOID lpExclude, LPVOID lpReserved)
1730 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1731 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1732 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1733 DWORD error = ERROR_SUCCESS;
1734 UINT replaced_flags;
1735 BOOL ret = FALSE;
1736 NTSTATUS status;
1737 IO_STATUS_BLOCK io;
1738 OBJECT_ATTRIBUTES attr;
1740 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1741 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1742 dwReplaceFlags, lpExclude, lpReserved);
1744 if (dwReplaceFlags)
1745 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1747 /* First two arguments are mandatory */
1748 if (!lpReplacedFileName || !lpReplacementFileName)
1750 SetLastError(ERROR_INVALID_PARAMETER);
1751 return FALSE;
1754 unix_replaced_name.Buffer = NULL;
1755 unix_replacement_name.Buffer = NULL;
1756 unix_backup_name.Buffer = NULL;
1758 attr.Length = sizeof(attr);
1759 attr.RootDirectory = 0;
1760 attr.Attributes = OBJ_CASE_INSENSITIVE;
1761 attr.ObjectName = NULL;
1762 attr.SecurityDescriptor = NULL;
1763 attr.SecurityQualityOfService = NULL;
1765 /* Open the "replaced" file for reading and writing */
1766 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1768 error = ERROR_PATH_NOT_FOUND;
1769 goto fail;
1771 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1772 attr.ObjectName = &nt_replaced_name;
1773 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1774 &attr, &io,
1775 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1776 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1777 if (status == STATUS_SUCCESS)
1778 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1779 RtlFreeUnicodeString(&nt_replaced_name);
1780 if (status != STATUS_SUCCESS)
1782 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1783 error = ERROR_FILE_NOT_FOUND;
1784 else
1785 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1786 goto fail;
1790 * Open the replacement file for reading, writing, and deleting
1791 * (writing and deleting are needed when finished)
1793 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1795 error = ERROR_PATH_NOT_FOUND;
1796 goto fail;
1798 attr.ObjectName = &nt_replacement_name;
1799 status = NtOpenFile(&hReplacement,
1800 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1801 &attr, &io, 0,
1802 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1803 if (status == STATUS_SUCCESS)
1804 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1805 RtlFreeUnicodeString(&nt_replacement_name);
1806 if (status != STATUS_SUCCESS)
1808 error = RtlNtStatusToDosError(status);
1809 goto fail;
1812 /* If the user wants a backup then that needs to be performed first */
1813 if (lpBackupFileName)
1815 UNICODE_STRING nt_backup_name;
1816 FILE_BASIC_INFORMATION replaced_info;
1818 /* Obtain the file attributes from the "replaced" file */
1819 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1820 sizeof(replaced_info),
1821 FileBasicInformation);
1822 if (status != STATUS_SUCCESS)
1824 error = RtlNtStatusToDosError(status);
1825 goto fail;
1828 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1830 error = ERROR_PATH_NOT_FOUND;
1831 goto fail;
1833 attr.ObjectName = &nt_backup_name;
1834 /* Open the backup with permissions to write over it */
1835 status = NtCreateFile(&hBackup, GENERIC_WRITE | SYNCHRONIZE,
1836 &attr, &io, NULL, replaced_info.FileAttributes,
1837 FILE_SHARE_WRITE, FILE_OPEN_IF,
1838 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1839 NULL, 0);
1840 if (status == STATUS_SUCCESS)
1841 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1842 RtlFreeUnicodeString(&nt_backup_name);
1843 if (status != STATUS_SUCCESS)
1845 error = RtlNtStatusToDosError(status);
1846 goto fail;
1849 /* If an existing backup exists then copy over it */
1850 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1852 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1853 goto fail;
1858 * Now that the backup has been performed (if requested), copy the replacement
1859 * into place
1861 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1863 if (errno == EACCES)
1865 /* Inappropriate permissions on "replaced", rename will fail */
1866 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1867 goto fail;
1869 /* on failure we need to indicate whether a backup was made */
1870 if (!lpBackupFileName)
1871 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1872 else
1873 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1874 goto fail;
1876 /* Success! */
1877 ret = TRUE;
1879 /* Perform resource cleanup */
1880 fail:
1881 if (hBackup) CloseHandle(hBackup);
1882 if (hReplaced) CloseHandle(hReplaced);
1883 if (hReplacement) CloseHandle(hReplacement);
1884 RtlFreeAnsiString(&unix_backup_name);
1885 RtlFreeAnsiString(&unix_replacement_name);
1886 RtlFreeAnsiString(&unix_replaced_name);
1888 /* If there was an error, set the error code */
1889 if(!ret)
1890 SetLastError(error);
1891 return ret;
1895 /**************************************************************************
1896 * ReplaceFileA (KERNEL32.@)
1898 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1899 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1900 LPVOID lpExclude, LPVOID lpReserved)
1902 WCHAR *replacedW, *replacementW, *backupW = NULL;
1903 BOOL ret;
1905 /* This function only makes sense when the first two parameters are defined */
1906 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1908 SetLastError(ERROR_INVALID_PARAMETER);
1909 return FALSE;
1911 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1913 HeapFree( GetProcessHeap(), 0, replacedW );
1914 SetLastError(ERROR_INVALID_PARAMETER);
1915 return FALSE;
1917 /* The backup parameter, however, is optional */
1918 if (lpBackupFileName)
1920 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1922 HeapFree( GetProcessHeap(), 0, replacedW );
1923 HeapFree( GetProcessHeap(), 0, replacementW );
1924 SetLastError(ERROR_INVALID_PARAMETER);
1925 return FALSE;
1928 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1929 HeapFree( GetProcessHeap(), 0, replacedW );
1930 HeapFree( GetProcessHeap(), 0, replacementW );
1931 HeapFree( GetProcessHeap(), 0, backupW );
1932 return ret;
1936 /*************************************************************************
1937 * FindFirstFileExW (KERNEL32.@)
1939 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1940 * results as FindExSearchNameMatch
1942 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1943 LPVOID data, FINDEX_SEARCH_OPS search_op,
1944 LPVOID filter, DWORD flags)
1946 WCHAR *mask;
1947 BOOL has_wildcard = FALSE;
1948 FIND_FIRST_INFO *info = NULL;
1949 UNICODE_STRING nt_name;
1950 OBJECT_ATTRIBUTES attr;
1951 IO_STATUS_BLOCK io;
1952 NTSTATUS status;
1953 DWORD size, device = 0;
1955 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1957 if (flags != 0)
1959 FIXME("flags not implemented 0x%08x\n", flags );
1961 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1963 FIXME("search_op not implemented 0x%08x\n", search_op);
1964 SetLastError( ERROR_INVALID_PARAMETER );
1965 return INVALID_HANDLE_VALUE;
1967 if (level != FindExInfoStandard && level != FindExInfoBasic)
1969 FIXME("info level %d not implemented\n", level );
1970 SetLastError( ERROR_INVALID_PARAMETER );
1971 return INVALID_HANDLE_VALUE;
1974 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1976 SetLastError( ERROR_PATH_NOT_FOUND );
1977 return INVALID_HANDLE_VALUE;
1980 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1982 static const WCHAR dotW[] = {'.',0};
1983 WCHAR *dir = NULL;
1985 /* we still need to check that the directory can be opened */
1987 if (HIWORD(device))
1989 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1991 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1992 goto error;
1994 memcpy( dir, filename, HIWORD(device) );
1995 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1997 RtlFreeUnicodeString( &nt_name );
1998 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
2000 HeapFree( GetProcessHeap(), 0, dir );
2001 SetLastError( ERROR_PATH_NOT_FOUND );
2002 goto error;
2004 HeapFree( GetProcessHeap(), 0, dir );
2005 size = 0;
2007 else if (!mask || !*mask)
2009 SetLastError( ERROR_FILE_NOT_FOUND );
2010 goto error;
2012 else
2014 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
2015 has_wildcard = strpbrkW( mask, wildcardsW ) != NULL;
2016 size = has_wildcard ? 8192 : max_entry_size;
2019 if (!(info = HeapAlloc( GetProcessHeap(), 0, offsetof( FIND_FIRST_INFO, data[size] ))))
2021 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2022 goto error;
2025 /* check if path is the root of the drive, skipping the \??\ prefix */
2026 info->is_root = FALSE;
2027 if (nt_name.Length >= 6 * sizeof(WCHAR) && nt_name.Buffer[5] == ':')
2029 DWORD pos = 6;
2030 while (pos * sizeof(WCHAR) < nt_name.Length && nt_name.Buffer[pos] == '\\') pos++;
2031 info->is_root = (pos * sizeof(WCHAR) >= nt_name.Length);
2034 attr.Length = sizeof(attr);
2035 attr.RootDirectory = 0;
2036 attr.Attributes = OBJ_CASE_INSENSITIVE;
2037 attr.ObjectName = &nt_name;
2038 attr.SecurityDescriptor = NULL;
2039 attr.SecurityQualityOfService = NULL;
2041 status = NtOpenFile( &info->handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2042 FILE_SHARE_READ | FILE_SHARE_WRITE,
2043 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2045 if (status != STATUS_SUCCESS)
2047 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
2048 SetLastError( ERROR_PATH_NOT_FOUND );
2049 else
2050 SetLastError( RtlNtStatusToDosError(status) );
2051 goto error;
2054 RtlInitializeCriticalSection( &info->cs );
2055 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
2056 info->path = nt_name;
2057 info->magic = FIND_FIRST_MAGIC;
2058 info->wildcard = has_wildcard;
2059 info->data_pos = 0;
2060 info->data_len = 0;
2061 info->data_size = size;
2062 info->search_op = search_op;
2063 info->level = level;
2065 if (device)
2067 WIN32_FIND_DATAW *wfd = data;
2069 memset( wfd, 0, sizeof(*wfd) );
2070 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
2071 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
2072 CloseHandle( info->handle );
2073 info->handle = 0;
2075 else
2077 UNICODE_STRING mask_str;
2079 RtlInitUnicodeString( &mask_str, mask );
2080 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2081 FileBothDirectoryInformation, FALSE, &mask_str, TRUE );
2082 if (status)
2084 FindClose( info );
2085 SetLastError( RtlNtStatusToDosError( status ) );
2086 return INVALID_HANDLE_VALUE;
2089 info->data_len = io.Information;
2090 if (!has_wildcard || info->data_len < info->data_size - max_entry_size)
2092 if (has_wildcard) /* release unused buffer space */
2093 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY,
2094 info, offsetof( FIND_FIRST_INFO, data[info->data_len] ));
2095 info->data_size = 0; /* we read everything */
2098 if (!FindNextFileW( info, data ))
2100 TRACE( "%s not found\n", debugstr_w(filename) );
2101 FindClose( info );
2102 SetLastError( ERROR_FILE_NOT_FOUND );
2103 return INVALID_HANDLE_VALUE;
2105 if (!has_wildcard) /* we can't find two files with the same name */
2107 CloseHandle( info->handle );
2108 info->handle = 0;
2111 return info;
2113 error:
2114 HeapFree( GetProcessHeap(), 0, info );
2115 RtlFreeUnicodeString( &nt_name );
2116 return INVALID_HANDLE_VALUE;
2120 /*************************************************************************
2121 * FindNextFileW (KERNEL32.@)
2123 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2125 FIND_FIRST_INFO *info;
2126 FILE_BOTH_DIR_INFORMATION *dir_info;
2127 BOOL ret = FALSE;
2128 NTSTATUS status;
2130 TRACE("%p %p\n", handle, data);
2132 if (!handle || handle == INVALID_HANDLE_VALUE)
2134 SetLastError( ERROR_INVALID_HANDLE );
2135 return ret;
2137 info = handle;
2138 if (info->magic != FIND_FIRST_MAGIC)
2140 SetLastError( ERROR_INVALID_HANDLE );
2141 return ret;
2144 RtlEnterCriticalSection( &info->cs );
2146 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2147 else for (;;)
2149 if (info->data_pos >= info->data_len) /* need to read some more data */
2151 IO_STATUS_BLOCK io;
2153 if (info->data_size)
2154 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2155 FileBothDirectoryInformation, FALSE, NULL, FALSE );
2156 else
2157 status = STATUS_NO_MORE_FILES;
2159 if (status)
2161 SetLastError( RtlNtStatusToDosError( status ) );
2162 if (status == STATUS_NO_MORE_FILES)
2164 CloseHandle( info->handle );
2165 info->handle = 0;
2167 break;
2169 info->data_len = io.Information;
2170 info->data_pos = 0;
2173 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2175 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2176 else info->data_pos = info->data_len;
2178 /* don't return '.' and '..' in the root of the drive */
2179 if (info->is_root)
2181 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2182 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2183 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2186 /* check for dir symlink */
2187 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2188 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2189 info->wildcard)
2191 if (!check_dir_symlink( info, dir_info )) continue;
2194 data->dwFileAttributes = dir_info->FileAttributes;
2195 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2196 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2197 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2198 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2199 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2200 data->dwReserved0 = 0;
2201 data->dwReserved1 = 0;
2203 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2204 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2206 if (info->level != FindExInfoBasic)
2208 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2209 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2211 else
2212 data->cAlternateFileName[0] = 0;
2214 TRACE("returning %s (%s)\n",
2215 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2217 ret = TRUE;
2218 break;
2221 RtlLeaveCriticalSection( &info->cs );
2222 return ret;
2226 /*************************************************************************
2227 * FindClose (KERNEL32.@)
2229 BOOL WINAPI FindClose( HANDLE handle )
2231 FIND_FIRST_INFO *info = handle;
2233 if (!handle || handle == INVALID_HANDLE_VALUE)
2235 SetLastError( ERROR_INVALID_HANDLE );
2236 return FALSE;
2239 __TRY
2241 if (info->magic == FIND_FIRST_MAGIC)
2243 RtlEnterCriticalSection( &info->cs );
2244 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2246 info->magic = 0;
2247 if (info->handle) CloseHandle( info->handle );
2248 info->handle = 0;
2249 RtlFreeUnicodeString( &info->path );
2250 info->data_pos = 0;
2251 info->data_len = 0;
2252 RtlLeaveCriticalSection( &info->cs );
2253 info->cs.DebugInfo->Spare[0] = 0;
2254 RtlDeleteCriticalSection( &info->cs );
2255 HeapFree( GetProcessHeap(), 0, info );
2259 __EXCEPT_PAGE_FAULT
2261 WARN("Illegal handle %p\n", handle);
2262 SetLastError( ERROR_INVALID_HANDLE );
2263 return FALSE;
2265 __ENDTRY
2267 return TRUE;
2271 /*************************************************************************
2272 * FindFirstFileA (KERNEL32.@)
2274 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2276 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2277 FindExSearchNameMatch, NULL, 0);
2280 /*************************************************************************
2281 * FindFirstFileExA (KERNEL32.@)
2283 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2284 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2285 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2287 HANDLE handle;
2288 WIN32_FIND_DATAA *dataA;
2289 WIN32_FIND_DATAW dataW;
2290 WCHAR *nameW;
2292 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2294 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2295 if (handle == INVALID_HANDLE_VALUE) return handle;
2297 dataA = lpFindFileData;
2298 dataA->dwFileAttributes = dataW.dwFileAttributes;
2299 dataA->ftCreationTime = dataW.ftCreationTime;
2300 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2301 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2302 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2303 dataA->nFileSizeLow = dataW.nFileSizeLow;
2304 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2305 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2306 sizeof(dataA->cAlternateFileName) );
2307 return handle;
2311 /*************************************************************************
2312 * FindFirstFileW (KERNEL32.@)
2314 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2316 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2317 FindExSearchNameMatch, NULL, 0);
2321 /*************************************************************************
2322 * FindNextFileA (KERNEL32.@)
2324 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2326 WIN32_FIND_DATAW dataW;
2328 if (!FindNextFileW( handle, &dataW )) return FALSE;
2329 data->dwFileAttributes = dataW.dwFileAttributes;
2330 data->ftCreationTime = dataW.ftCreationTime;
2331 data->ftLastAccessTime = dataW.ftLastAccessTime;
2332 data->ftLastWriteTime = dataW.ftLastWriteTime;
2333 data->nFileSizeHigh = dataW.nFileSizeHigh;
2334 data->nFileSizeLow = dataW.nFileSizeLow;
2335 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2336 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2337 sizeof(data->cAlternateFileName) );
2338 return TRUE;
2342 /**************************************************************************
2343 * GetFileAttributesW (KERNEL32.@)
2345 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2347 FILE_BASIC_INFORMATION info;
2348 UNICODE_STRING nt_name;
2349 OBJECT_ATTRIBUTES attr;
2350 NTSTATUS status;
2352 TRACE("%s\n", debugstr_w(name));
2354 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2356 SetLastError( ERROR_PATH_NOT_FOUND );
2357 return INVALID_FILE_ATTRIBUTES;
2360 attr.Length = sizeof(attr);
2361 attr.RootDirectory = 0;
2362 attr.Attributes = OBJ_CASE_INSENSITIVE;
2363 attr.ObjectName = &nt_name;
2364 attr.SecurityDescriptor = NULL;
2365 attr.SecurityQualityOfService = NULL;
2367 status = NtQueryAttributesFile( &attr, &info );
2368 RtlFreeUnicodeString( &nt_name );
2370 if (status == STATUS_SUCCESS) return info.FileAttributes;
2372 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2373 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2375 SetLastError( RtlNtStatusToDosError(status) );
2376 return INVALID_FILE_ATTRIBUTES;
2380 /**************************************************************************
2381 * GetFileAttributesA (KERNEL32.@)
2383 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2385 WCHAR *nameW;
2387 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2388 return GetFileAttributesW( nameW );
2392 /**************************************************************************
2393 * SetFileAttributesW (KERNEL32.@)
2395 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2397 UNICODE_STRING nt_name;
2398 OBJECT_ATTRIBUTES attr;
2399 IO_STATUS_BLOCK io;
2400 NTSTATUS status;
2401 HANDLE handle;
2403 TRACE("%s %x\n", debugstr_w(name), attributes);
2405 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2407 SetLastError( ERROR_PATH_NOT_FOUND );
2408 return FALSE;
2411 attr.Length = sizeof(attr);
2412 attr.RootDirectory = 0;
2413 attr.Attributes = OBJ_CASE_INSENSITIVE;
2414 attr.ObjectName = &nt_name;
2415 attr.SecurityDescriptor = NULL;
2416 attr.SecurityQualityOfService = NULL;
2418 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2419 RtlFreeUnicodeString( &nt_name );
2421 if (status == STATUS_SUCCESS)
2423 FILE_BASIC_INFORMATION info;
2425 memset( &info, 0, sizeof(info) );
2426 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2427 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2428 NtClose( handle );
2431 if (status == STATUS_SUCCESS) return TRUE;
2432 SetLastError( RtlNtStatusToDosError(status) );
2433 return FALSE;
2437 /**************************************************************************
2438 * SetFileAttributesA (KERNEL32.@)
2440 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2442 WCHAR *nameW;
2444 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2445 return SetFileAttributesW( nameW, attributes );
2449 /**************************************************************************
2450 * GetFileAttributesExW (KERNEL32.@)
2452 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2454 FILE_NETWORK_OPEN_INFORMATION info;
2455 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2456 UNICODE_STRING nt_name;
2457 OBJECT_ATTRIBUTES attr;
2458 NTSTATUS status;
2460 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2462 if (level != GetFileExInfoStandard)
2464 SetLastError( ERROR_INVALID_PARAMETER );
2465 return FALSE;
2468 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2470 SetLastError( ERROR_PATH_NOT_FOUND );
2471 return FALSE;
2474 attr.Length = sizeof(attr);
2475 attr.RootDirectory = 0;
2476 attr.Attributes = OBJ_CASE_INSENSITIVE;
2477 attr.ObjectName = &nt_name;
2478 attr.SecurityDescriptor = NULL;
2479 attr.SecurityQualityOfService = NULL;
2481 status = NtQueryFullAttributesFile( &attr, &info );
2482 RtlFreeUnicodeString( &nt_name );
2484 if (status != STATUS_SUCCESS)
2486 SetLastError( RtlNtStatusToDosError(status) );
2487 return FALSE;
2490 data->dwFileAttributes = info.FileAttributes;
2491 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2492 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2493 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2494 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2495 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2496 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2497 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2498 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2499 return TRUE;
2503 /**************************************************************************
2504 * GetFileAttributesExA (KERNEL32.@)
2506 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2508 WCHAR *nameW;
2510 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2511 return GetFileAttributesExW( nameW, level, ptr );
2515 /******************************************************************************
2516 * GetCompressedFileSizeW (KERNEL32.@)
2518 * Get the actual number of bytes used on disk.
2520 * RETURNS
2521 * Success: Low-order doubleword of number of bytes
2522 * Failure: INVALID_FILE_SIZE
2524 DWORD WINAPI GetCompressedFileSizeW(
2525 LPCWSTR name, /* [in] Pointer to name of file */
2526 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2528 UNICODE_STRING nt_name;
2529 OBJECT_ATTRIBUTES attr;
2530 IO_STATUS_BLOCK io;
2531 NTSTATUS status;
2532 HANDLE handle;
2533 DWORD ret = INVALID_FILE_SIZE;
2535 TRACE("%s %p\n", debugstr_w(name), size_high);
2537 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2539 SetLastError( ERROR_PATH_NOT_FOUND );
2540 return INVALID_FILE_SIZE;
2543 attr.Length = sizeof(attr);
2544 attr.RootDirectory = 0;
2545 attr.Attributes = OBJ_CASE_INSENSITIVE;
2546 attr.ObjectName = &nt_name;
2547 attr.SecurityDescriptor = NULL;
2548 attr.SecurityQualityOfService = NULL;
2550 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2551 RtlFreeUnicodeString( &nt_name );
2553 if (status == STATUS_SUCCESS)
2555 /* we don't support compressed files, simply return the file size */
2556 ret = GetFileSize( handle, size_high );
2557 NtClose( handle );
2559 else SetLastError( RtlNtStatusToDosError(status) );
2561 return ret;
2565 /******************************************************************************
2566 * GetCompressedFileSizeA (KERNEL32.@)
2568 * See GetCompressedFileSizeW.
2570 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2572 WCHAR *nameW;
2574 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2575 return GetCompressedFileSizeW( nameW, size_high );
2579 /***********************************************************************
2580 * OpenVxDHandle (KERNEL32.@)
2582 * This function is supposed to return the corresponding Ring 0
2583 * ("kernel") handle for a Ring 3 handle in Win9x.
2584 * Evidently, Wine will have problems with this. But we try anyway,
2585 * maybe it helps...
2587 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2589 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2590 return hHandleRing3;
2594 /****************************************************************************
2595 * DeviceIoControl (KERNEL32.@)
2597 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2598 LPVOID lpvInBuffer, DWORD cbInBuffer,
2599 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2600 LPDWORD lpcbBytesReturned,
2601 LPOVERLAPPED lpOverlapped)
2603 NTSTATUS status;
2605 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2606 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2607 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2609 /* Check if this is a user defined control code for a VxD */
2611 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2613 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2614 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2615 DeviceIoProc proc = NULL;
2617 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleW(krnl386W),
2618 "__wine_vxd_get_proc" );
2619 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2620 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2621 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2624 /* Not a VxD, let ntdll handle it */
2626 if (lpOverlapped)
2628 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2629 lpOverlapped->Internal = STATUS_PENDING;
2630 lpOverlapped->InternalHigh = 0;
2631 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2632 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2633 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2634 dwIoControlCode, lpvInBuffer, cbInBuffer,
2635 lpvOutBuffer, cbOutBuffer);
2636 else
2637 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2638 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2639 dwIoControlCode, lpvInBuffer, cbInBuffer,
2640 lpvOutBuffer, cbOutBuffer);
2641 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2643 else
2645 IO_STATUS_BLOCK iosb;
2647 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2648 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2649 dwIoControlCode, lpvInBuffer, cbInBuffer,
2650 lpvOutBuffer, cbOutBuffer);
2651 else
2652 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2653 dwIoControlCode, lpvInBuffer, cbInBuffer,
2654 lpvOutBuffer, cbOutBuffer);
2655 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2657 if (status) SetLastError( RtlNtStatusToDosError(status) );
2658 return !status;
2662 /***********************************************************************
2663 * OpenFile (KERNEL32.@)
2665 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2667 HANDLE handle;
2668 FILETIME filetime;
2669 WORD filedatetime[2];
2671 if (!ofs) return HFILE_ERROR;
2673 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2674 ((mode & 0x3 )==OF_READ)?"OF_READ":
2675 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2676 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2677 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2678 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2679 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2680 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2681 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2682 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2683 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2684 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2685 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2686 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2687 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2688 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2689 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2690 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2694 ofs->cBytes = sizeof(OFSTRUCT);
2695 ofs->nErrCode = 0;
2696 if (mode & OF_REOPEN) name = ofs->szPathName;
2698 if (!name) return HFILE_ERROR;
2700 TRACE("%s %04x\n", name, mode );
2702 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2703 Are there any cases where getting the path here is wrong?
2704 Uwe Bonnes 1997 Apr 2 */
2705 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2707 /* OF_PARSE simply fills the structure */
2709 if (mode & OF_PARSE)
2711 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2712 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2713 return 0;
2716 /* OF_CREATE is completely different from all other options, so
2717 handle it first */
2719 if (mode & OF_CREATE)
2721 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2722 goto error;
2724 else
2726 /* Now look for the file */
2728 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2729 goto error;
2731 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2733 if (mode & OF_DELETE)
2735 if (!DeleteFileA( ofs->szPathName )) goto error;
2736 TRACE("(%s): OF_DELETE return = OK\n", name);
2737 return TRUE;
2740 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2741 if (handle == INVALID_HANDLE_VALUE) goto error;
2743 GetFileTime( handle, NULL, NULL, &filetime );
2744 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2745 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2747 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2749 CloseHandle( handle );
2750 WARN("(%s): OF_VERIFY failed\n", name );
2751 /* FIXME: what error here? */
2752 SetLastError( ERROR_FILE_NOT_FOUND );
2753 goto error;
2756 ofs->Reserved1 = filedatetime[0];
2757 ofs->Reserved2 = filedatetime[1];
2759 TRACE("(%s): OK, return = %p\n", name, handle );
2760 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2762 CloseHandle( handle );
2763 return TRUE;
2765 return HandleToLong(handle);
2767 error: /* We get here if there was an error opening the file */
2768 ofs->nErrCode = GetLastError();
2769 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2770 return HFILE_ERROR;
2774 /***********************************************************************
2775 * OpenFileById (KERNEL32.@)
2777 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2778 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2780 UINT options;
2781 HANDLE result;
2782 OBJECT_ATTRIBUTES attr;
2783 NTSTATUS status;
2784 IO_STATUS_BLOCK io;
2785 UNICODE_STRING objectName;
2787 if (!id)
2789 SetLastError( ERROR_INVALID_PARAMETER );
2790 return INVALID_HANDLE_VALUE;
2793 options = FILE_OPEN_BY_FILE_ID;
2794 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2795 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2796 else
2797 options |= FILE_NON_DIRECTORY_FILE;
2798 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2799 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2800 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2801 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2803 objectName.Length = sizeof(ULONGLONG);
2804 objectName.Buffer = (WCHAR *)&id->u.FileId;
2805 attr.Length = sizeof(attr);
2806 attr.RootDirectory = handle;
2807 attr.Attributes = 0;
2808 attr.ObjectName = &objectName;
2809 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2810 attr.SecurityQualityOfService = NULL;
2811 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2813 status = NtCreateFile( &result, access | SYNCHRONIZE, &attr, &io, NULL, flags,
2814 share, OPEN_EXISTING, options, NULL, 0 );
2815 if (status != STATUS_SUCCESS)
2817 SetLastError( RtlNtStatusToDosError( status ) );
2818 return INVALID_HANDLE_VALUE;
2820 return result;
2823 /***********************************************************************
2824 * ReOpenFile (KERNEL32.@)
2826 HANDLE WINAPI ReOpenFile(HANDLE handle_original, DWORD access, DWORD sharing, DWORD flags)
2828 FIXME("(%p, %d, %d, %d): stub\n", handle_original, access, sharing, flags);
2830 return INVALID_HANDLE_VALUE;
2834 /***********************************************************************
2835 * K32EnumDeviceDrivers (KERNEL32.@)
2837 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2839 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2841 if (needed)
2842 *needed = 0;
2844 return TRUE;
2847 /***********************************************************************
2848 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2850 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2852 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2854 if (base_name && size)
2855 base_name[0] = '\0';
2857 return 0;
2860 /***********************************************************************
2861 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2863 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2865 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2867 if (base_name && size)
2868 base_name[0] = '\0';
2870 return 0;
2873 /***********************************************************************
2874 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2876 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2878 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2880 if (file_name && size)
2881 file_name[0] = '\0';
2883 return 0;
2886 /***********************************************************************
2887 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2889 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2891 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2893 if (file_name && size)
2894 file_name[0] = '\0';
2896 return 0;
2899 /***********************************************************************
2900 * GetFinalPathNameByHandleW (KERNEL32.@)
2902 DWORD WINAPI GetFinalPathNameByHandleW(HANDLE file, LPWSTR path, DWORD charcount, DWORD flags)
2904 WCHAR buffer[sizeof(OBJECT_NAME_INFORMATION) + MAX_PATH + 1];
2905 OBJECT_NAME_INFORMATION *info = (OBJECT_NAME_INFORMATION*)&buffer;
2906 WCHAR drive_part[MAX_PATH];
2907 DWORD drive_part_len = 0;
2908 NTSTATUS status;
2909 DWORD result = 0;
2910 ULONG dummy;
2911 WCHAR *ptr;
2913 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags );
2915 if (flags & ~(FILE_NAME_OPENED | VOLUME_NAME_GUID | VOLUME_NAME_NONE | VOLUME_NAME_NT))
2917 WARN("Unknown flags: %x\n", flags);
2918 SetLastError( ERROR_INVALID_PARAMETER );
2919 return 0;
2922 /* get object name */
2923 status = NtQueryObject( file, ObjectNameInformation, &buffer, sizeof(buffer) - sizeof(WCHAR), &dummy );
2924 if (status != STATUS_SUCCESS)
2926 SetLastError( RtlNtStatusToDosError( status ) );
2927 return 0;
2929 if (!info->Name.Buffer)
2931 SetLastError( ERROR_INVALID_HANDLE );
2932 return 0;
2934 if (info->Name.Length < 4 * sizeof(WCHAR) || info->Name.Buffer[0] != '\\' ||
2935 info->Name.Buffer[1] != '?' || info->Name.Buffer[2] != '?' || info->Name.Buffer[3] != '\\' )
2937 FIXME("Unexpected object name: %s\n", debugstr_wn(info->Name.Buffer, info->Name.Length / sizeof(WCHAR)));
2938 SetLastError( ERROR_GEN_FAILURE );
2939 return 0;
2942 /* add terminating null character, remove "\\??\\" */
2943 info->Name.Buffer[info->Name.Length / sizeof(WCHAR)] = 0;
2944 info->Name.Length -= 4 * sizeof(WCHAR);
2945 info->Name.Buffer += 4;
2947 /* FILE_NAME_OPENED is not supported yet, and would require Wineserver changes */
2948 if (flags & FILE_NAME_OPENED)
2950 FIXME("FILE_NAME_OPENED not supported\n");
2951 flags &= ~FILE_NAME_OPENED;
2954 /* Get information required for VOLUME_NAME_NONE, VOLUME_NAME_GUID and VOLUME_NAME_NT */
2955 if (flags == VOLUME_NAME_NONE || flags == VOLUME_NAME_GUID || flags == VOLUME_NAME_NT)
2957 if (!GetVolumePathNameW( info->Name.Buffer, drive_part, MAX_PATH ))
2958 return 0;
2960 drive_part_len = strlenW(drive_part);
2961 if (!drive_part_len || drive_part_len > strlenW(info->Name.Buffer) ||
2962 drive_part[drive_part_len-1] != '\\' ||
2963 strncmpiW( info->Name.Buffer, drive_part, drive_part_len ))
2965 FIXME("Path %s returned by GetVolumePathNameW does not match file path %s\n",
2966 debugstr_w(drive_part), debugstr_w(info->Name.Buffer));
2967 SetLastError( ERROR_GEN_FAILURE );
2968 return 0;
2972 if (flags == VOLUME_NAME_NONE)
2974 ptr = info->Name.Buffer + drive_part_len - 1;
2975 result = strlenW(ptr);
2976 if (result < charcount)
2977 memcpy(path, ptr, (result + 1) * sizeof(WCHAR));
2978 else result++;
2980 else if (flags == VOLUME_NAME_GUID)
2982 WCHAR volume_prefix[51];
2984 /* GetVolumeNameForVolumeMountPointW sets error code on failure */
2985 if (!GetVolumeNameForVolumeMountPointW( drive_part, volume_prefix, 50 ))
2986 return 0;
2988 ptr = info->Name.Buffer + drive_part_len;
2989 result = strlenW(volume_prefix) + strlenW(ptr);
2990 if (result < charcount)
2992 path[0] = 0;
2993 strcatW(path, volume_prefix);
2994 strcatW(path, ptr);
2996 else
2998 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2999 result++;
3002 else if (flags == VOLUME_NAME_NT)
3004 WCHAR nt_prefix[MAX_PATH];
3006 /* QueryDosDeviceW sets error code on failure */
3007 drive_part[drive_part_len - 1] = 0;
3008 if (!QueryDosDeviceW( drive_part, nt_prefix, MAX_PATH ))
3009 return 0;
3011 ptr = info->Name.Buffer + drive_part_len - 1;
3012 result = strlenW(nt_prefix) + strlenW(ptr);
3013 if (result < charcount)
3015 path[0] = 0;
3016 strcatW(path, nt_prefix);
3017 strcatW(path, ptr);
3019 else
3021 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3022 result++;
3025 else if (flags == VOLUME_NAME_DOS)
3027 static const WCHAR dos_prefix[] = {'\\','\\','?','\\', '\0'};
3029 result = strlenW(dos_prefix) + strlenW(info->Name.Buffer);
3030 if (result < charcount)
3032 path[0] = 0;
3033 strcatW(path, dos_prefix);
3034 strcatW(path, info->Name.Buffer);
3036 else
3038 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3039 result++;
3042 else
3044 /* Windows crashes here, but we prefer returning ERROR_INVALID_PARAMETER */
3045 WARN("Invalid combination of flags: %x\n", flags);
3046 SetLastError( ERROR_INVALID_PARAMETER );
3049 return result;
3052 /***********************************************************************
3053 * GetFinalPathNameByHandleA (KERNEL32.@)
3055 DWORD WINAPI GetFinalPathNameByHandleA(HANDLE file, LPSTR path, DWORD charcount, DWORD flags)
3057 WCHAR *str;
3058 DWORD result, len, cp;
3060 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags);
3062 len = GetFinalPathNameByHandleW(file, NULL, 0, flags);
3063 if (len == 0)
3064 return 0;
3066 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3067 if (!str)
3069 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3070 return 0;
3073 result = GetFinalPathNameByHandleW(file, str, len, flags);
3074 if (result != len - 1)
3076 HeapFree(GetProcessHeap(), 0, str);
3077 WARN("GetFinalPathNameByHandleW failed unexpectedly: %u\n", result);
3078 return 0;
3081 cp = oem_file_apis ? CP_OEMCP : CP_ACP;
3083 len = WideCharToMultiByte(cp, 0, str, -1, NULL, 0, NULL, NULL);
3084 if (!len)
3086 HeapFree(GetProcessHeap(), 0, str);
3087 WARN("Failed to get multibyte length\n");
3088 return 0;
3091 if (charcount < len)
3093 HeapFree(GetProcessHeap(), 0, str);
3094 return len - 1;
3097 len = WideCharToMultiByte(cp, 0, str, -1, path, charcount, NULL, NULL);
3098 if (!len)
3100 HeapFree(GetProcessHeap(), 0, str);
3101 WARN("WideCharToMultiByte failed\n");
3102 return 0;
3105 HeapFree(GetProcessHeap(), 0, str);
3107 return len - 1;