winemenubuilder: Fix encoder method argument.
[wine.git] / dlls / kernel32 / file.c
blobeeccf67e15e7aeb3b0cbe648c246d608b42a8aa6
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;
1069 /**************************************************************************
1070 * SetFileCompletionNotificationModes (KERNEL32.@)
1072 BOOL WINAPI SetFileCompletionNotificationModes( HANDLE file, UCHAR flags )
1074 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
1075 IO_STATUS_BLOCK io;
1076 NTSTATUS status;
1078 info.Flags = flags;
1079 status = NtSetInformationFile( file, &io, &info, sizeof(info), FileIoCompletionNotificationInformation );
1080 if (status == STATUS_SUCCESS) return TRUE;
1081 SetLastError( RtlNtStatusToDosError(status) );
1082 return FALSE;
1086 /***********************************************************************
1087 * SetFileInformationByHandle (KERNEL32.@)
1089 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1091 NTSTATUS status;
1092 IO_STATUS_BLOCK io;
1094 TRACE( "%p %u %p %u\n", file, class, info, size );
1096 switch (class)
1098 case FileBasicInfo:
1099 case FileNameInfo:
1100 case FileRenameInfo:
1101 case FileAllocationInfo:
1102 case FileEndOfFileInfo:
1103 case FileStreamInfo:
1104 case FileIdBothDirectoryInfo:
1105 case FileIdBothDirectoryRestartInfo:
1106 case FileIoPriorityHintInfo:
1107 case FileFullDirectoryInfo:
1108 case FileFullDirectoryRestartInfo:
1109 case FileStorageInfo:
1110 case FileAlignmentInfo:
1111 case FileIdInfo:
1112 case FileIdExtdDirectoryInfo:
1113 case FileIdExtdDirectoryRestartInfo:
1114 FIXME( "%p, %u, %p, %u\n", file, class, info, size );
1115 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1116 return FALSE;
1118 case FileDispositionInfo:
1119 status = NtSetInformationFile( file, &io, info, size, FileDispositionInformation );
1120 break;
1122 case FileStandardInfo:
1123 case FileCompressionInfo:
1124 case FileAttributeTagInfo:
1125 case FileRemoteProtocolInfo:
1126 default:
1127 SetLastError( ERROR_INVALID_PARAMETER );
1128 return FALSE;
1131 if (status != STATUS_SUCCESS)
1133 SetLastError( RtlNtStatusToDosError( status ) );
1134 return FALSE;
1136 return TRUE;
1140 /***********************************************************************
1141 * SetFilePointer (KERNEL32.@)
1143 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1145 LARGE_INTEGER dist, newpos;
1147 if (highword)
1149 dist.u.LowPart = distance;
1150 dist.u.HighPart = *highword;
1152 else dist.QuadPart = distance;
1154 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1156 if (highword) *highword = newpos.u.HighPart;
1157 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1158 return newpos.u.LowPart;
1162 /***********************************************************************
1163 * SetFilePointerEx (KERNEL32.@)
1165 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1166 LARGE_INTEGER *newpos, DWORD method )
1168 LONGLONG pos;
1169 IO_STATUS_BLOCK io;
1170 FILE_POSITION_INFORMATION info;
1172 switch(method)
1174 case FILE_BEGIN:
1175 pos = distance.QuadPart;
1176 break;
1177 case FILE_CURRENT:
1178 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1179 goto error;
1180 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1181 break;
1182 case FILE_END:
1184 FILE_END_OF_FILE_INFORMATION eof;
1185 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1186 goto error;
1187 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1189 break;
1190 default:
1191 SetLastError( ERROR_INVALID_PARAMETER );
1192 return FALSE;
1195 if (pos < 0)
1197 SetLastError( ERROR_NEGATIVE_SEEK );
1198 return FALSE;
1201 info.CurrentByteOffset.QuadPart = pos;
1202 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1203 goto error;
1204 if (newpos) newpos->QuadPart = pos;
1205 return TRUE;
1207 error:
1208 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1209 return FALSE;
1212 /***********************************************************************
1213 * SetFileValidData (KERNEL32.@)
1215 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1217 FILE_VALID_DATA_LENGTH_INFORMATION info;
1218 IO_STATUS_BLOCK io;
1219 NTSTATUS status;
1221 info.ValidDataLength.QuadPart = ValidDataLength;
1222 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1224 if (status == STATUS_SUCCESS) return TRUE;
1225 SetLastError( RtlNtStatusToDosError(status) );
1226 return FALSE;
1229 /***********************************************************************
1230 * GetFileTime (KERNEL32.@)
1232 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1233 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1235 FILE_BASIC_INFORMATION info;
1236 IO_STATUS_BLOCK io;
1237 NTSTATUS status;
1239 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1240 if (status == STATUS_SUCCESS)
1242 if (lpCreationTime)
1244 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1245 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1247 if (lpLastAccessTime)
1249 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1250 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1252 if (lpLastWriteTime)
1254 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1255 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1257 return TRUE;
1259 SetLastError( RtlNtStatusToDosError(status) );
1260 return FALSE;
1264 /***********************************************************************
1265 * SetFileTime (KERNEL32.@)
1267 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1268 const FILETIME *atime, const FILETIME *mtime )
1270 FILE_BASIC_INFORMATION info;
1271 IO_STATUS_BLOCK io;
1272 NTSTATUS status;
1274 memset( &info, 0, sizeof(info) );
1275 if (ctime)
1277 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1278 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1280 if (atime)
1282 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1283 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1285 if (mtime)
1287 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1288 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1291 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1292 if (status == STATUS_SUCCESS) return TRUE;
1293 SetLastError( RtlNtStatusToDosError(status) );
1294 return FALSE;
1298 /**************************************************************************
1299 * LockFile (KERNEL32.@)
1301 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1302 DWORD count_low, DWORD count_high )
1304 NTSTATUS status;
1305 LARGE_INTEGER count, offset;
1307 TRACE( "%p %x%08x %x%08x\n",
1308 hFile, offset_high, offset_low, count_high, count_low );
1310 count.u.LowPart = count_low;
1311 count.u.HighPart = count_high;
1312 offset.u.LowPart = offset_low;
1313 offset.u.HighPart = offset_high;
1315 status = NtLockFile( hFile, 0, NULL, NULL,
1316 NULL, &offset, &count, NULL, TRUE, TRUE );
1318 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1319 return !status;
1323 /**************************************************************************
1324 * LockFileEx [KERNEL32.@]
1326 * Locks a byte range within an open file for shared or exclusive access.
1328 * RETURNS
1329 * success: TRUE
1330 * failure: FALSE
1332 * NOTES
1333 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1335 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1336 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1338 NTSTATUS status;
1339 LARGE_INTEGER count, offset;
1340 LPVOID cvalue = NULL;
1342 if (reserved)
1344 SetLastError( ERROR_INVALID_PARAMETER );
1345 return FALSE;
1348 TRACE( "%p %x%08x %x%08x flags %x\n",
1349 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1350 count_high, count_low, flags );
1352 count.u.LowPart = count_low;
1353 count.u.HighPart = count_high;
1354 offset.u.LowPart = overlapped->u.s.Offset;
1355 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1357 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1359 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1360 NULL, &offset, &count, NULL,
1361 flags & LOCKFILE_FAIL_IMMEDIATELY,
1362 flags & LOCKFILE_EXCLUSIVE_LOCK );
1364 if (status) SetLastError( RtlNtStatusToDosError(status) );
1365 return !status;
1369 /**************************************************************************
1370 * UnlockFile (KERNEL32.@)
1372 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1373 DWORD count_low, DWORD count_high )
1375 NTSTATUS status;
1376 LARGE_INTEGER count, offset;
1378 count.u.LowPart = count_low;
1379 count.u.HighPart = count_high;
1380 offset.u.LowPart = offset_low;
1381 offset.u.HighPart = offset_high;
1383 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1384 if (status) SetLastError( RtlNtStatusToDosError(status) );
1385 return !status;
1389 /**************************************************************************
1390 * UnlockFileEx (KERNEL32.@)
1392 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1393 LPOVERLAPPED overlapped )
1395 if (reserved)
1397 SetLastError( ERROR_INVALID_PARAMETER );
1398 return FALSE;
1400 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1402 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1406 /*************************************************************************
1407 * SetHandleCount (KERNEL32.@)
1409 UINT WINAPI SetHandleCount( UINT count )
1411 return count;
1415 /**************************************************************************
1416 * Operations on file names *
1417 **************************************************************************/
1420 /*************************************************************************
1421 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1423 * Creates or opens an object, and returns a handle that can be used to
1424 * access that object.
1426 * PARAMS
1428 * filename [in] pointer to filename to be accessed
1429 * access [in] access mode requested
1430 * sharing [in] share mode
1431 * sa [in] pointer to security attributes
1432 * creation [in] how to create the file
1433 * attributes [in] attributes for newly created file
1434 * template [in] handle to file with extended attributes to copy
1436 * RETURNS
1437 * Success: Open handle to specified file
1438 * Failure: INVALID_HANDLE_VALUE
1440 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1441 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1442 DWORD attributes, HANDLE template )
1444 NTSTATUS status;
1445 UINT options;
1446 OBJECT_ATTRIBUTES attr;
1447 UNICODE_STRING nameW;
1448 IO_STATUS_BLOCK io;
1449 HANDLE ret;
1450 DWORD dosdev;
1451 const WCHAR *vxd_name = NULL;
1452 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1453 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1454 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1455 SECURITY_QUALITY_OF_SERVICE qos;
1457 static const UINT nt_disposition[5] =
1459 FILE_CREATE, /* CREATE_NEW */
1460 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1461 FILE_OPEN, /* OPEN_EXISTING */
1462 FILE_OPEN_IF, /* OPEN_ALWAYS */
1463 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1467 /* sanity checks */
1469 if (!filename || !filename[0])
1471 SetLastError( ERROR_PATH_NOT_FOUND );
1472 return INVALID_HANDLE_VALUE;
1475 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1476 (access & GENERIC_READ)?"GENERIC_READ ":"",
1477 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1478 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1479 (!access)?"QUERY_ACCESS ":"",
1480 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1481 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1482 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1483 creation, attributes);
1485 /* Open a console for CONIN$ or CONOUT$ */
1487 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1489 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1490 creation ? OPEN_EXISTING : 0);
1491 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1492 goto done;
1495 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1497 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1498 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1500 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1501 !strncmpiW( filename + 4, pipeW, 5 ) ||
1502 !strncmpiW( filename + 4, mailslotW, 9 ))
1504 dosdev = 0;
1506 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1508 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1510 else if (GetVersion() & 0x80000000)
1512 vxd_name = filename + 4;
1513 if (!creation) creation = OPEN_EXISTING;
1516 else dosdev = RtlIsDosDeviceName_U( filename );
1518 if (dosdev)
1520 static const WCHAR conW[] = {'C','O','N'};
1522 if (LOWORD(dosdev) == sizeof(conW) &&
1523 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, ARRAY_SIZE( conW )))
1525 switch (access & (GENERIC_READ|GENERIC_WRITE))
1527 case GENERIC_READ:
1528 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1529 goto done;
1530 case GENERIC_WRITE:
1531 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1532 goto done;
1533 default:
1534 SetLastError( ERROR_FILE_NOT_FOUND );
1535 return INVALID_HANDLE_VALUE;
1540 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1542 SetLastError( ERROR_INVALID_PARAMETER );
1543 return INVALID_HANDLE_VALUE;
1546 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1548 SetLastError( ERROR_PATH_NOT_FOUND );
1549 return INVALID_HANDLE_VALUE;
1552 /* now call NtCreateFile */
1554 options = 0;
1555 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1556 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1557 else
1558 options |= FILE_NON_DIRECTORY_FILE;
1559 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1561 options |= FILE_DELETE_ON_CLOSE;
1562 access |= DELETE;
1564 if (attributes & FILE_FLAG_NO_BUFFERING)
1565 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1566 if (!(attributes & FILE_FLAG_OVERLAPPED))
1567 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1568 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1569 options |= FILE_RANDOM_ACCESS;
1570 if (attributes & FILE_FLAG_WRITE_THROUGH)
1571 options |= FILE_WRITE_THROUGH;
1572 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1574 attr.Length = sizeof(attr);
1575 attr.RootDirectory = 0;
1576 attr.Attributes = OBJ_CASE_INSENSITIVE;
1577 attr.ObjectName = &nameW;
1578 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1579 if (attributes & SECURITY_SQOS_PRESENT)
1581 qos.Length = sizeof(qos);
1582 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1583 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1584 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1585 attr.SecurityQualityOfService = &qos;
1587 else
1588 attr.SecurityQualityOfService = NULL;
1590 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1592 status = NtCreateFile( &ret, access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attr, &io,
1593 NULL, attributes, sharing, nt_disposition[creation - CREATE_NEW],
1594 options, NULL, 0 );
1595 if (status)
1597 if (vxd_name && vxd_name[0])
1599 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1600 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleW(krnl386W),
1601 "__wine_vxd_open" );
1602 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1605 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1606 ret = INVALID_HANDLE_VALUE;
1608 /* In the case file creation was rejected due to CREATE_NEW flag
1609 * was specified and file with that name already exists, correct
1610 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1611 * Note: RtlNtStatusToDosError is not the subject to blame here.
1613 if (status == STATUS_OBJECT_NAME_COLLISION)
1614 SetLastError( ERROR_FILE_EXISTS );
1615 else
1616 SetLastError( RtlNtStatusToDosError(status) );
1618 else
1620 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1621 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1622 SetLastError( ERROR_ALREADY_EXISTS );
1623 else
1624 SetLastError( 0 );
1626 RtlFreeUnicodeString( &nameW );
1628 done:
1629 if (!ret) ret = INVALID_HANDLE_VALUE;
1630 TRACE("returning %p\n", ret);
1631 return ret;
1636 /*************************************************************************
1637 * CreateFileA (KERNEL32.@)
1639 * See CreateFileW.
1641 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1642 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1643 DWORD attributes, HANDLE template)
1645 WCHAR *nameW;
1647 if ((GetVersion() & 0x80000000) && IsBadStringPtrA(filename, -1)) return INVALID_HANDLE_VALUE;
1648 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1649 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1652 /*************************************************************************
1653 * CreateFile2 (KERNEL32.@)
1655 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1656 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1658 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1659 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1660 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1662 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1664 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1667 /***********************************************************************
1668 * DeleteFileW (KERNEL32.@)
1670 * Delete a file.
1672 * PARAMS
1673 * path [I] Path to the file to delete.
1675 * RETURNS
1676 * Success: TRUE.
1677 * Failure: FALSE, check GetLastError().
1679 BOOL WINAPI DeleteFileW( LPCWSTR path )
1681 UNICODE_STRING nameW;
1682 OBJECT_ATTRIBUTES attr;
1683 NTSTATUS status;
1684 HANDLE hFile;
1685 IO_STATUS_BLOCK io;
1687 TRACE("%s\n", debugstr_w(path) );
1689 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1691 SetLastError( ERROR_PATH_NOT_FOUND );
1692 return FALSE;
1695 attr.Length = sizeof(attr);
1696 attr.RootDirectory = 0;
1697 attr.Attributes = OBJ_CASE_INSENSITIVE;
1698 attr.ObjectName = &nameW;
1699 attr.SecurityDescriptor = NULL;
1700 attr.SecurityQualityOfService = NULL;
1702 status = NtCreateFile(&hFile, SYNCHRONIZE | DELETE, &attr, &io, NULL, 0,
1703 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1704 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1705 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1707 RtlFreeUnicodeString( &nameW );
1708 if (status)
1710 SetLastError( RtlNtStatusToDosError(status) );
1711 return FALSE;
1713 return TRUE;
1717 /***********************************************************************
1718 * DeleteFileA (KERNEL32.@)
1720 * See DeleteFileW.
1722 BOOL WINAPI DeleteFileA( LPCSTR path )
1724 WCHAR *pathW;
1726 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1727 return DeleteFileW( pathW );
1731 /**************************************************************************
1732 * ReplaceFileW (KERNEL32.@)
1733 * ReplaceFile (KERNEL32.@)
1735 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1736 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1737 LPVOID lpExclude, LPVOID lpReserved)
1739 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1740 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1741 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1742 DWORD error = ERROR_SUCCESS;
1743 UINT replaced_flags;
1744 BOOL ret = FALSE;
1745 NTSTATUS status;
1746 IO_STATUS_BLOCK io;
1747 OBJECT_ATTRIBUTES attr;
1749 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1750 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1751 dwReplaceFlags, lpExclude, lpReserved);
1753 if (dwReplaceFlags)
1754 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1756 /* First two arguments are mandatory */
1757 if (!lpReplacedFileName || !lpReplacementFileName)
1759 SetLastError(ERROR_INVALID_PARAMETER);
1760 return FALSE;
1763 unix_replaced_name.Buffer = NULL;
1764 unix_replacement_name.Buffer = NULL;
1765 unix_backup_name.Buffer = NULL;
1767 attr.Length = sizeof(attr);
1768 attr.RootDirectory = 0;
1769 attr.Attributes = OBJ_CASE_INSENSITIVE;
1770 attr.ObjectName = NULL;
1771 attr.SecurityDescriptor = NULL;
1772 attr.SecurityQualityOfService = NULL;
1774 /* Open the "replaced" file for reading and writing */
1775 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1777 error = ERROR_PATH_NOT_FOUND;
1778 goto fail;
1780 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1781 attr.ObjectName = &nt_replaced_name;
1782 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1783 &attr, &io,
1784 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1785 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1786 if (status == STATUS_SUCCESS)
1787 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1788 RtlFreeUnicodeString(&nt_replaced_name);
1789 if (status != STATUS_SUCCESS)
1791 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1792 error = ERROR_FILE_NOT_FOUND;
1793 else
1794 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1795 goto fail;
1799 * Open the replacement file for reading, writing, and deleting
1800 * (writing and deleting are needed when finished)
1802 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1804 error = ERROR_PATH_NOT_FOUND;
1805 goto fail;
1807 attr.ObjectName = &nt_replacement_name;
1808 status = NtOpenFile(&hReplacement,
1809 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1810 &attr, &io, 0,
1811 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1812 if (status == STATUS_SUCCESS)
1813 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1814 RtlFreeUnicodeString(&nt_replacement_name);
1815 if (status != STATUS_SUCCESS)
1817 error = RtlNtStatusToDosError(status);
1818 goto fail;
1821 /* If the user wants a backup then that needs to be performed first */
1822 if (lpBackupFileName)
1824 UNICODE_STRING nt_backup_name;
1825 FILE_BASIC_INFORMATION replaced_info;
1827 /* Obtain the file attributes from the "replaced" file */
1828 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1829 sizeof(replaced_info),
1830 FileBasicInformation);
1831 if (status != STATUS_SUCCESS)
1833 error = RtlNtStatusToDosError(status);
1834 goto fail;
1837 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1839 error = ERROR_PATH_NOT_FOUND;
1840 goto fail;
1842 attr.ObjectName = &nt_backup_name;
1843 /* Open the backup with permissions to write over it */
1844 status = NtCreateFile(&hBackup, GENERIC_WRITE | SYNCHRONIZE,
1845 &attr, &io, NULL, replaced_info.FileAttributes,
1846 FILE_SHARE_WRITE, FILE_OPEN_IF,
1847 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1848 NULL, 0);
1849 if (status == STATUS_SUCCESS)
1850 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1851 RtlFreeUnicodeString(&nt_backup_name);
1852 if (status != STATUS_SUCCESS)
1854 error = RtlNtStatusToDosError(status);
1855 goto fail;
1858 /* If an existing backup exists then copy over it */
1859 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1861 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1862 goto fail;
1867 * Now that the backup has been performed (if requested), copy the replacement
1868 * into place
1870 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1872 if (errno == EACCES)
1874 /* Inappropriate permissions on "replaced", rename will fail */
1875 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1876 goto fail;
1878 /* on failure we need to indicate whether a backup was made */
1879 if (!lpBackupFileName)
1880 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1881 else
1882 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1883 goto fail;
1885 /* Success! */
1886 ret = TRUE;
1888 /* Perform resource cleanup */
1889 fail:
1890 if (hBackup) CloseHandle(hBackup);
1891 if (hReplaced) CloseHandle(hReplaced);
1892 if (hReplacement) CloseHandle(hReplacement);
1893 RtlFreeAnsiString(&unix_backup_name);
1894 RtlFreeAnsiString(&unix_replacement_name);
1895 RtlFreeAnsiString(&unix_replaced_name);
1897 /* If there was an error, set the error code */
1898 if(!ret)
1899 SetLastError(error);
1900 return ret;
1904 /**************************************************************************
1905 * ReplaceFileA (KERNEL32.@)
1907 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1908 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1909 LPVOID lpExclude, LPVOID lpReserved)
1911 WCHAR *replacedW, *replacementW, *backupW = NULL;
1912 BOOL ret;
1914 /* This function only makes sense when the first two parameters are defined */
1915 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1917 SetLastError(ERROR_INVALID_PARAMETER);
1918 return FALSE;
1920 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1922 HeapFree( GetProcessHeap(), 0, replacedW );
1923 SetLastError(ERROR_INVALID_PARAMETER);
1924 return FALSE;
1926 /* The backup parameter, however, is optional */
1927 if (lpBackupFileName)
1929 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1931 HeapFree( GetProcessHeap(), 0, replacedW );
1932 HeapFree( GetProcessHeap(), 0, replacementW );
1933 SetLastError(ERROR_INVALID_PARAMETER);
1934 return FALSE;
1937 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1938 HeapFree( GetProcessHeap(), 0, replacedW );
1939 HeapFree( GetProcessHeap(), 0, replacementW );
1940 HeapFree( GetProcessHeap(), 0, backupW );
1941 return ret;
1945 /*************************************************************************
1946 * FindFirstFileExW (KERNEL32.@)
1948 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1949 * results as FindExSearchNameMatch
1951 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1952 LPVOID data, FINDEX_SEARCH_OPS search_op,
1953 LPVOID filter, DWORD flags)
1955 WCHAR *mask;
1956 BOOL has_wildcard = FALSE;
1957 FIND_FIRST_INFO *info = NULL;
1958 UNICODE_STRING nt_name;
1959 OBJECT_ATTRIBUTES attr;
1960 IO_STATUS_BLOCK io;
1961 NTSTATUS status;
1962 DWORD size, device = 0;
1964 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1966 if (flags != 0)
1968 FIXME("flags not implemented 0x%08x\n", flags );
1970 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1972 FIXME("search_op not implemented 0x%08x\n", search_op);
1973 SetLastError( ERROR_INVALID_PARAMETER );
1974 return INVALID_HANDLE_VALUE;
1976 if (level != FindExInfoStandard && level != FindExInfoBasic)
1978 FIXME("info level %d not implemented\n", level );
1979 SetLastError( ERROR_INVALID_PARAMETER );
1980 return INVALID_HANDLE_VALUE;
1983 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1985 SetLastError( ERROR_PATH_NOT_FOUND );
1986 return INVALID_HANDLE_VALUE;
1989 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1991 static const WCHAR dotW[] = {'.',0};
1992 WCHAR *dir = NULL;
1994 /* we still need to check that the directory can be opened */
1996 if (HIWORD(device))
1998 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
2000 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2001 goto error;
2003 memcpy( dir, filename, HIWORD(device) );
2004 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
2006 RtlFreeUnicodeString( &nt_name );
2007 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
2009 HeapFree( GetProcessHeap(), 0, dir );
2010 SetLastError( ERROR_PATH_NOT_FOUND );
2011 goto error;
2013 HeapFree( GetProcessHeap(), 0, dir );
2014 size = 0;
2016 else if (!mask || !*mask)
2018 SetLastError( ERROR_FILE_NOT_FOUND );
2019 goto error;
2021 else
2023 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
2024 has_wildcard = strpbrkW( mask, wildcardsW ) != NULL;
2025 size = has_wildcard ? 8192 : max_entry_size;
2028 if (!(info = HeapAlloc( GetProcessHeap(), 0, offsetof( FIND_FIRST_INFO, data[size] ))))
2030 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2031 goto error;
2034 /* check if path is the root of the drive, skipping the \??\ prefix */
2035 info->is_root = FALSE;
2036 if (nt_name.Length >= 6 * sizeof(WCHAR) && nt_name.Buffer[5] == ':')
2038 DWORD pos = 6;
2039 while (pos * sizeof(WCHAR) < nt_name.Length && nt_name.Buffer[pos] == '\\') pos++;
2040 info->is_root = (pos * sizeof(WCHAR) >= nt_name.Length);
2043 attr.Length = sizeof(attr);
2044 attr.RootDirectory = 0;
2045 attr.Attributes = OBJ_CASE_INSENSITIVE;
2046 attr.ObjectName = &nt_name;
2047 attr.SecurityDescriptor = NULL;
2048 attr.SecurityQualityOfService = NULL;
2050 status = NtOpenFile( &info->handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2051 FILE_SHARE_READ | FILE_SHARE_WRITE,
2052 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2054 if (status != STATUS_SUCCESS)
2056 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
2057 SetLastError( ERROR_PATH_NOT_FOUND );
2058 else
2059 SetLastError( RtlNtStatusToDosError(status) );
2060 goto error;
2063 RtlInitializeCriticalSection( &info->cs );
2064 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
2065 info->path = nt_name;
2066 info->magic = FIND_FIRST_MAGIC;
2067 info->wildcard = has_wildcard;
2068 info->data_pos = 0;
2069 info->data_len = 0;
2070 info->data_size = size;
2071 info->search_op = search_op;
2072 info->level = level;
2074 if (device)
2076 WIN32_FIND_DATAW *wfd = data;
2078 memset( wfd, 0, sizeof(*wfd) );
2079 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
2080 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
2081 CloseHandle( info->handle );
2082 info->handle = 0;
2084 else
2086 UNICODE_STRING mask_str;
2088 RtlInitUnicodeString( &mask_str, mask );
2089 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2090 FileBothDirectoryInformation, FALSE, &mask_str, TRUE );
2091 if (status)
2093 FindClose( info );
2094 SetLastError( RtlNtStatusToDosError( status ) );
2095 return INVALID_HANDLE_VALUE;
2098 info->data_len = io.Information;
2099 if (!has_wildcard || info->data_len < info->data_size - max_entry_size)
2101 if (has_wildcard) /* release unused buffer space */
2102 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY,
2103 info, offsetof( FIND_FIRST_INFO, data[info->data_len] ));
2104 info->data_size = 0; /* we read everything */
2107 if (!FindNextFileW( info, data ))
2109 TRACE( "%s not found\n", debugstr_w(filename) );
2110 FindClose( info );
2111 SetLastError( ERROR_FILE_NOT_FOUND );
2112 return INVALID_HANDLE_VALUE;
2114 if (!has_wildcard) /* we can't find two files with the same name */
2116 CloseHandle( info->handle );
2117 info->handle = 0;
2120 return info;
2122 error:
2123 HeapFree( GetProcessHeap(), 0, info );
2124 RtlFreeUnicodeString( &nt_name );
2125 return INVALID_HANDLE_VALUE;
2129 /*************************************************************************
2130 * FindNextFileW (KERNEL32.@)
2132 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2134 FIND_FIRST_INFO *info;
2135 FILE_BOTH_DIR_INFORMATION *dir_info;
2136 BOOL ret = FALSE;
2137 NTSTATUS status;
2139 TRACE("%p %p\n", handle, data);
2141 if (!handle || handle == INVALID_HANDLE_VALUE)
2143 SetLastError( ERROR_INVALID_HANDLE );
2144 return ret;
2146 info = handle;
2147 if (info->magic != FIND_FIRST_MAGIC)
2149 SetLastError( ERROR_INVALID_HANDLE );
2150 return ret;
2153 RtlEnterCriticalSection( &info->cs );
2155 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2156 else for (;;)
2158 if (info->data_pos >= info->data_len) /* need to read some more data */
2160 IO_STATUS_BLOCK io;
2162 if (info->data_size)
2163 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2164 FileBothDirectoryInformation, FALSE, NULL, FALSE );
2165 else
2166 status = STATUS_NO_MORE_FILES;
2168 if (status)
2170 SetLastError( RtlNtStatusToDosError( status ) );
2171 if (status == STATUS_NO_MORE_FILES)
2173 CloseHandle( info->handle );
2174 info->handle = 0;
2176 break;
2178 info->data_len = io.Information;
2179 info->data_pos = 0;
2182 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2184 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2185 else info->data_pos = info->data_len;
2187 /* don't return '.' and '..' in the root of the drive */
2188 if (info->is_root)
2190 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2191 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2192 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2195 /* check for dir symlink */
2196 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2197 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2198 info->wildcard)
2200 if (!check_dir_symlink( info, dir_info )) continue;
2203 data->dwFileAttributes = dir_info->FileAttributes;
2204 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2205 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2206 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2207 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2208 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2209 data->dwReserved0 = 0;
2210 data->dwReserved1 = 0;
2212 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2213 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2215 if (info->level != FindExInfoBasic)
2217 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2218 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2220 else
2221 data->cAlternateFileName[0] = 0;
2223 TRACE("returning %s (%s)\n",
2224 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2226 ret = TRUE;
2227 break;
2230 RtlLeaveCriticalSection( &info->cs );
2231 return ret;
2235 /*************************************************************************
2236 * FindClose (KERNEL32.@)
2238 BOOL WINAPI FindClose( HANDLE handle )
2240 FIND_FIRST_INFO *info = handle;
2242 if (!handle || handle == INVALID_HANDLE_VALUE)
2244 SetLastError( ERROR_INVALID_HANDLE );
2245 return FALSE;
2248 __TRY
2250 if (info->magic == FIND_FIRST_MAGIC)
2252 RtlEnterCriticalSection( &info->cs );
2253 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2255 info->magic = 0;
2256 if (info->handle) CloseHandle( info->handle );
2257 info->handle = 0;
2258 RtlFreeUnicodeString( &info->path );
2259 info->data_pos = 0;
2260 info->data_len = 0;
2261 RtlLeaveCriticalSection( &info->cs );
2262 info->cs.DebugInfo->Spare[0] = 0;
2263 RtlDeleteCriticalSection( &info->cs );
2264 HeapFree( GetProcessHeap(), 0, info );
2268 __EXCEPT_PAGE_FAULT
2270 WARN("Illegal handle %p\n", handle);
2271 SetLastError( ERROR_INVALID_HANDLE );
2272 return FALSE;
2274 __ENDTRY
2276 return TRUE;
2280 /*************************************************************************
2281 * FindFirstFileA (KERNEL32.@)
2283 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2285 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2286 FindExSearchNameMatch, NULL, 0);
2289 /*************************************************************************
2290 * FindFirstFileExA (KERNEL32.@)
2292 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2293 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2294 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2296 HANDLE handle;
2297 WIN32_FIND_DATAA *dataA;
2298 WIN32_FIND_DATAW dataW;
2299 WCHAR *nameW;
2301 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2303 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2304 if (handle == INVALID_HANDLE_VALUE) return handle;
2306 dataA = lpFindFileData;
2307 dataA->dwFileAttributes = dataW.dwFileAttributes;
2308 dataA->ftCreationTime = dataW.ftCreationTime;
2309 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2310 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2311 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2312 dataA->nFileSizeLow = dataW.nFileSizeLow;
2313 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2314 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2315 sizeof(dataA->cAlternateFileName) );
2316 return handle;
2320 /*************************************************************************
2321 * FindFirstFileW (KERNEL32.@)
2323 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2325 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2326 FindExSearchNameMatch, NULL, 0);
2330 /*************************************************************************
2331 * FindNextFileA (KERNEL32.@)
2333 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2335 WIN32_FIND_DATAW dataW;
2337 if (!FindNextFileW( handle, &dataW )) return FALSE;
2338 data->dwFileAttributes = dataW.dwFileAttributes;
2339 data->ftCreationTime = dataW.ftCreationTime;
2340 data->ftLastAccessTime = dataW.ftLastAccessTime;
2341 data->ftLastWriteTime = dataW.ftLastWriteTime;
2342 data->nFileSizeHigh = dataW.nFileSizeHigh;
2343 data->nFileSizeLow = dataW.nFileSizeLow;
2344 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2345 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2346 sizeof(data->cAlternateFileName) );
2347 return TRUE;
2351 /**************************************************************************
2352 * GetFileAttributesW (KERNEL32.@)
2354 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2356 FILE_BASIC_INFORMATION info;
2357 UNICODE_STRING nt_name;
2358 OBJECT_ATTRIBUTES attr;
2359 NTSTATUS status;
2361 TRACE("%s\n", debugstr_w(name));
2363 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2365 SetLastError( ERROR_PATH_NOT_FOUND );
2366 return INVALID_FILE_ATTRIBUTES;
2369 attr.Length = sizeof(attr);
2370 attr.RootDirectory = 0;
2371 attr.Attributes = OBJ_CASE_INSENSITIVE;
2372 attr.ObjectName = &nt_name;
2373 attr.SecurityDescriptor = NULL;
2374 attr.SecurityQualityOfService = NULL;
2376 status = NtQueryAttributesFile( &attr, &info );
2377 RtlFreeUnicodeString( &nt_name );
2379 if (status == STATUS_SUCCESS) return info.FileAttributes;
2381 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2382 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2384 SetLastError( RtlNtStatusToDosError(status) );
2385 return INVALID_FILE_ATTRIBUTES;
2389 /**************************************************************************
2390 * GetFileAttributesA (KERNEL32.@)
2392 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2394 WCHAR *nameW;
2396 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2397 return GetFileAttributesW( nameW );
2401 /**************************************************************************
2402 * SetFileAttributesW (KERNEL32.@)
2404 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2406 UNICODE_STRING nt_name;
2407 OBJECT_ATTRIBUTES attr;
2408 IO_STATUS_BLOCK io;
2409 NTSTATUS status;
2410 HANDLE handle;
2412 TRACE("%s %x\n", debugstr_w(name), attributes);
2414 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2416 SetLastError( ERROR_PATH_NOT_FOUND );
2417 return FALSE;
2420 attr.Length = sizeof(attr);
2421 attr.RootDirectory = 0;
2422 attr.Attributes = OBJ_CASE_INSENSITIVE;
2423 attr.ObjectName = &nt_name;
2424 attr.SecurityDescriptor = NULL;
2425 attr.SecurityQualityOfService = NULL;
2427 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2428 RtlFreeUnicodeString( &nt_name );
2430 if (status == STATUS_SUCCESS)
2432 FILE_BASIC_INFORMATION info;
2434 memset( &info, 0, sizeof(info) );
2435 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2436 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2437 NtClose( handle );
2440 if (status == STATUS_SUCCESS) return TRUE;
2441 SetLastError( RtlNtStatusToDosError(status) );
2442 return FALSE;
2446 /**************************************************************************
2447 * SetFileAttributesA (KERNEL32.@)
2449 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2451 WCHAR *nameW;
2453 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2454 return SetFileAttributesW( nameW, attributes );
2458 /**************************************************************************
2459 * GetFileAttributesExW (KERNEL32.@)
2461 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2463 FILE_NETWORK_OPEN_INFORMATION info;
2464 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2465 UNICODE_STRING nt_name;
2466 OBJECT_ATTRIBUTES attr;
2467 NTSTATUS status;
2469 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2471 if (level != GetFileExInfoStandard)
2473 SetLastError( ERROR_INVALID_PARAMETER );
2474 return FALSE;
2477 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2479 SetLastError( ERROR_PATH_NOT_FOUND );
2480 return FALSE;
2483 attr.Length = sizeof(attr);
2484 attr.RootDirectory = 0;
2485 attr.Attributes = OBJ_CASE_INSENSITIVE;
2486 attr.ObjectName = &nt_name;
2487 attr.SecurityDescriptor = NULL;
2488 attr.SecurityQualityOfService = NULL;
2490 status = NtQueryFullAttributesFile( &attr, &info );
2491 RtlFreeUnicodeString( &nt_name );
2493 if (status != STATUS_SUCCESS)
2495 SetLastError( RtlNtStatusToDosError(status) );
2496 return FALSE;
2499 data->dwFileAttributes = info.FileAttributes;
2500 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2501 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2502 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2503 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2504 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2505 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2506 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2507 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2508 return TRUE;
2512 /**************************************************************************
2513 * GetFileAttributesExA (KERNEL32.@)
2515 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2517 WCHAR *nameW;
2519 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2520 return GetFileAttributesExW( nameW, level, ptr );
2524 /******************************************************************************
2525 * GetCompressedFileSizeW (KERNEL32.@)
2527 * Get the actual number of bytes used on disk.
2529 * RETURNS
2530 * Success: Low-order doubleword of number of bytes
2531 * Failure: INVALID_FILE_SIZE
2533 DWORD WINAPI GetCompressedFileSizeW(
2534 LPCWSTR name, /* [in] Pointer to name of file */
2535 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2537 UNICODE_STRING nt_name;
2538 OBJECT_ATTRIBUTES attr;
2539 IO_STATUS_BLOCK io;
2540 NTSTATUS status;
2541 HANDLE handle;
2542 DWORD ret = INVALID_FILE_SIZE;
2544 TRACE("%s %p\n", debugstr_w(name), size_high);
2546 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2548 SetLastError( ERROR_PATH_NOT_FOUND );
2549 return INVALID_FILE_SIZE;
2552 attr.Length = sizeof(attr);
2553 attr.RootDirectory = 0;
2554 attr.Attributes = OBJ_CASE_INSENSITIVE;
2555 attr.ObjectName = &nt_name;
2556 attr.SecurityDescriptor = NULL;
2557 attr.SecurityQualityOfService = NULL;
2559 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2560 RtlFreeUnicodeString( &nt_name );
2562 if (status == STATUS_SUCCESS)
2564 /* we don't support compressed files, simply return the file size */
2565 ret = GetFileSize( handle, size_high );
2566 NtClose( handle );
2568 else SetLastError( RtlNtStatusToDosError(status) );
2570 return ret;
2574 /******************************************************************************
2575 * GetCompressedFileSizeA (KERNEL32.@)
2577 * See GetCompressedFileSizeW.
2579 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2581 WCHAR *nameW;
2583 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2584 return GetCompressedFileSizeW( nameW, size_high );
2588 /***********************************************************************
2589 * OpenVxDHandle (KERNEL32.@)
2591 * This function is supposed to return the corresponding Ring 0
2592 * ("kernel") handle for a Ring 3 handle in Win9x.
2593 * Evidently, Wine will have problems with this. But we try anyway,
2594 * maybe it helps...
2596 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2598 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2599 return hHandleRing3;
2603 /****************************************************************************
2604 * DeviceIoControl (KERNEL32.@)
2606 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2607 LPVOID lpvInBuffer, DWORD cbInBuffer,
2608 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2609 LPDWORD lpcbBytesReturned,
2610 LPOVERLAPPED lpOverlapped)
2612 NTSTATUS status;
2614 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2615 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2616 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2618 /* Check if this is a user defined control code for a VxD */
2620 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2622 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2623 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2624 DeviceIoProc proc = NULL;
2626 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleW(krnl386W),
2627 "__wine_vxd_get_proc" );
2628 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2629 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2630 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2633 /* Not a VxD, let ntdll handle it */
2635 if (lpOverlapped)
2637 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2638 lpOverlapped->Internal = STATUS_PENDING;
2639 lpOverlapped->InternalHigh = 0;
2640 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2641 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2642 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2643 dwIoControlCode, lpvInBuffer, cbInBuffer,
2644 lpvOutBuffer, cbOutBuffer);
2645 else
2646 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2647 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2648 dwIoControlCode, lpvInBuffer, cbInBuffer,
2649 lpvOutBuffer, cbOutBuffer);
2650 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2652 else
2654 IO_STATUS_BLOCK iosb;
2656 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2657 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2658 dwIoControlCode, lpvInBuffer, cbInBuffer,
2659 lpvOutBuffer, cbOutBuffer);
2660 else
2661 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2662 dwIoControlCode, lpvInBuffer, cbInBuffer,
2663 lpvOutBuffer, cbOutBuffer);
2664 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2666 if (status) SetLastError( RtlNtStatusToDosError(status) );
2667 return !status;
2671 /***********************************************************************
2672 * OpenFile (KERNEL32.@)
2674 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2676 HANDLE handle;
2677 FILETIME filetime;
2678 WORD filedatetime[2];
2680 if (!ofs) return HFILE_ERROR;
2682 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2683 ((mode & 0x3 )==OF_READ)?"OF_READ":
2684 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2685 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2686 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2687 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2688 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2689 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2690 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2691 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2692 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2693 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2694 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2695 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2696 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2697 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2698 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2699 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2703 ofs->cBytes = sizeof(OFSTRUCT);
2704 ofs->nErrCode = 0;
2705 if (mode & OF_REOPEN) name = ofs->szPathName;
2707 if (!name) return HFILE_ERROR;
2709 TRACE("%s %04x\n", name, mode );
2711 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2712 Are there any cases where getting the path here is wrong?
2713 Uwe Bonnes 1997 Apr 2 */
2714 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2716 /* OF_PARSE simply fills the structure */
2718 if (mode & OF_PARSE)
2720 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2721 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2722 return 0;
2725 /* OF_CREATE is completely different from all other options, so
2726 handle it first */
2728 if (mode & OF_CREATE)
2730 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2731 goto error;
2733 else
2735 /* Now look for the file */
2737 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2738 goto error;
2740 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2742 if (mode & OF_DELETE)
2744 if (!DeleteFileA( ofs->szPathName )) goto error;
2745 TRACE("(%s): OF_DELETE return = OK\n", name);
2746 return TRUE;
2749 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2750 if (handle == INVALID_HANDLE_VALUE) goto error;
2752 GetFileTime( handle, NULL, NULL, &filetime );
2753 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2754 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2756 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2758 CloseHandle( handle );
2759 WARN("(%s): OF_VERIFY failed\n", name );
2760 /* FIXME: what error here? */
2761 SetLastError( ERROR_FILE_NOT_FOUND );
2762 goto error;
2765 ofs->Reserved1 = filedatetime[0];
2766 ofs->Reserved2 = filedatetime[1];
2768 TRACE("(%s): OK, return = %p\n", name, handle );
2769 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2771 CloseHandle( handle );
2772 return TRUE;
2774 return HandleToLong(handle);
2776 error: /* We get here if there was an error opening the file */
2777 ofs->nErrCode = GetLastError();
2778 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2779 return HFILE_ERROR;
2783 /***********************************************************************
2784 * OpenFileById (KERNEL32.@)
2786 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2787 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2789 UINT options;
2790 HANDLE result;
2791 OBJECT_ATTRIBUTES attr;
2792 NTSTATUS status;
2793 IO_STATUS_BLOCK io;
2794 UNICODE_STRING objectName;
2796 if (!id)
2798 SetLastError( ERROR_INVALID_PARAMETER );
2799 return INVALID_HANDLE_VALUE;
2802 options = FILE_OPEN_BY_FILE_ID;
2803 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2804 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2805 else
2806 options |= FILE_NON_DIRECTORY_FILE;
2807 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2808 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2809 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2810 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2812 objectName.Length = sizeof(ULONGLONG);
2813 objectName.Buffer = (WCHAR *)&id->u.FileId;
2814 attr.Length = sizeof(attr);
2815 attr.RootDirectory = handle;
2816 attr.Attributes = 0;
2817 attr.ObjectName = &objectName;
2818 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2819 attr.SecurityQualityOfService = NULL;
2820 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2822 status = NtCreateFile( &result, access | SYNCHRONIZE, &attr, &io, NULL, flags,
2823 share, OPEN_EXISTING, options, NULL, 0 );
2824 if (status != STATUS_SUCCESS)
2826 SetLastError( RtlNtStatusToDosError( status ) );
2827 return INVALID_HANDLE_VALUE;
2829 return result;
2832 /***********************************************************************
2833 * ReOpenFile (KERNEL32.@)
2835 HANDLE WINAPI ReOpenFile(HANDLE handle_original, DWORD access, DWORD sharing, DWORD flags)
2837 FIXME("(%p, %d, %d, %d): stub\n", handle_original, access, sharing, flags);
2839 return INVALID_HANDLE_VALUE;
2843 /***********************************************************************
2844 * K32EnumDeviceDrivers (KERNEL32.@)
2846 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2848 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2850 if (needed)
2851 *needed = 0;
2853 return TRUE;
2856 /***********************************************************************
2857 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2859 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2861 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2863 if (base_name && size)
2864 base_name[0] = '\0';
2866 return 0;
2869 /***********************************************************************
2870 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2872 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2874 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2876 if (base_name && size)
2877 base_name[0] = '\0';
2879 return 0;
2882 /***********************************************************************
2883 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2885 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2887 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2889 if (file_name && size)
2890 file_name[0] = '\0';
2892 return 0;
2895 /***********************************************************************
2896 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2898 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2900 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2902 if (file_name && size)
2903 file_name[0] = '\0';
2905 return 0;
2908 /***********************************************************************
2909 * GetFinalPathNameByHandleW (KERNEL32.@)
2911 DWORD WINAPI GetFinalPathNameByHandleW(HANDLE file, LPWSTR path, DWORD charcount, DWORD flags)
2913 WCHAR buffer[sizeof(OBJECT_NAME_INFORMATION) + MAX_PATH + 1];
2914 OBJECT_NAME_INFORMATION *info = (OBJECT_NAME_INFORMATION*)&buffer;
2915 WCHAR drive_part[MAX_PATH];
2916 DWORD drive_part_len = 0;
2917 NTSTATUS status;
2918 DWORD result = 0;
2919 ULONG dummy;
2920 WCHAR *ptr;
2922 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags );
2924 if (flags & ~(FILE_NAME_OPENED | VOLUME_NAME_GUID | VOLUME_NAME_NONE | VOLUME_NAME_NT))
2926 WARN("Unknown flags: %x\n", flags);
2927 SetLastError( ERROR_INVALID_PARAMETER );
2928 return 0;
2931 /* get object name */
2932 status = NtQueryObject( file, ObjectNameInformation, &buffer, sizeof(buffer) - sizeof(WCHAR), &dummy );
2933 if (status != STATUS_SUCCESS)
2935 SetLastError( RtlNtStatusToDosError( status ) );
2936 return 0;
2938 if (!info->Name.Buffer)
2940 SetLastError( ERROR_INVALID_HANDLE );
2941 return 0;
2943 if (info->Name.Length < 4 * sizeof(WCHAR) || info->Name.Buffer[0] != '\\' ||
2944 info->Name.Buffer[1] != '?' || info->Name.Buffer[2] != '?' || info->Name.Buffer[3] != '\\' )
2946 FIXME("Unexpected object name: %s\n", debugstr_wn(info->Name.Buffer, info->Name.Length / sizeof(WCHAR)));
2947 SetLastError( ERROR_GEN_FAILURE );
2948 return 0;
2951 /* add terminating null character, remove "\\??\\" */
2952 info->Name.Buffer[info->Name.Length / sizeof(WCHAR)] = 0;
2953 info->Name.Length -= 4 * sizeof(WCHAR);
2954 info->Name.Buffer += 4;
2956 /* FILE_NAME_OPENED is not supported yet, and would require Wineserver changes */
2957 if (flags & FILE_NAME_OPENED)
2959 FIXME("FILE_NAME_OPENED not supported\n");
2960 flags &= ~FILE_NAME_OPENED;
2963 /* Get information required for VOLUME_NAME_NONE, VOLUME_NAME_GUID and VOLUME_NAME_NT */
2964 if (flags == VOLUME_NAME_NONE || flags == VOLUME_NAME_GUID || flags == VOLUME_NAME_NT)
2966 if (!GetVolumePathNameW( info->Name.Buffer, drive_part, MAX_PATH ))
2967 return 0;
2969 drive_part_len = strlenW(drive_part);
2970 if (!drive_part_len || drive_part_len > strlenW(info->Name.Buffer) ||
2971 drive_part[drive_part_len-1] != '\\' ||
2972 strncmpiW( info->Name.Buffer, drive_part, drive_part_len ))
2974 FIXME("Path %s returned by GetVolumePathNameW does not match file path %s\n",
2975 debugstr_w(drive_part), debugstr_w(info->Name.Buffer));
2976 SetLastError( ERROR_GEN_FAILURE );
2977 return 0;
2981 if (flags == VOLUME_NAME_NONE)
2983 ptr = info->Name.Buffer + drive_part_len - 1;
2984 result = strlenW(ptr);
2985 if (result < charcount)
2986 memcpy(path, ptr, (result + 1) * sizeof(WCHAR));
2987 else result++;
2989 else if (flags == VOLUME_NAME_GUID)
2991 WCHAR volume_prefix[51];
2993 /* GetVolumeNameForVolumeMountPointW sets error code on failure */
2994 if (!GetVolumeNameForVolumeMountPointW( drive_part, volume_prefix, 50 ))
2995 return 0;
2997 ptr = info->Name.Buffer + drive_part_len;
2998 result = strlenW(volume_prefix) + strlenW(ptr);
2999 if (result < charcount)
3001 path[0] = 0;
3002 strcatW(path, volume_prefix);
3003 strcatW(path, ptr);
3005 else
3007 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3008 result++;
3011 else if (flags == VOLUME_NAME_NT)
3013 WCHAR nt_prefix[MAX_PATH];
3015 /* QueryDosDeviceW sets error code on failure */
3016 drive_part[drive_part_len - 1] = 0;
3017 if (!QueryDosDeviceW( drive_part, nt_prefix, MAX_PATH ))
3018 return 0;
3020 ptr = info->Name.Buffer + drive_part_len - 1;
3021 result = strlenW(nt_prefix) + strlenW(ptr);
3022 if (result < charcount)
3024 path[0] = 0;
3025 strcatW(path, nt_prefix);
3026 strcatW(path, ptr);
3028 else
3030 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3031 result++;
3034 else if (flags == VOLUME_NAME_DOS)
3036 static const WCHAR dos_prefix[] = {'\\','\\','?','\\', '\0'};
3038 result = strlenW(dos_prefix) + strlenW(info->Name.Buffer);
3039 if (result < charcount)
3041 path[0] = 0;
3042 strcatW(path, dos_prefix);
3043 strcatW(path, info->Name.Buffer);
3045 else
3047 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3048 result++;
3051 else
3053 /* Windows crashes here, but we prefer returning ERROR_INVALID_PARAMETER */
3054 WARN("Invalid combination of flags: %x\n", flags);
3055 SetLastError( ERROR_INVALID_PARAMETER );
3058 return result;
3061 /***********************************************************************
3062 * GetFinalPathNameByHandleA (KERNEL32.@)
3064 DWORD WINAPI GetFinalPathNameByHandleA(HANDLE file, LPSTR path, DWORD charcount, DWORD flags)
3066 WCHAR *str;
3067 DWORD result, len, cp;
3069 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags);
3071 len = GetFinalPathNameByHandleW(file, NULL, 0, flags);
3072 if (len == 0)
3073 return 0;
3075 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3076 if (!str)
3078 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3079 return 0;
3082 result = GetFinalPathNameByHandleW(file, str, len, flags);
3083 if (result != len - 1)
3085 HeapFree(GetProcessHeap(), 0, str);
3086 WARN("GetFinalPathNameByHandleW failed unexpectedly: %u\n", result);
3087 return 0;
3090 cp = oem_file_apis ? CP_OEMCP : CP_ACP;
3092 len = WideCharToMultiByte(cp, 0, str, -1, NULL, 0, NULL, NULL);
3093 if (!len)
3095 HeapFree(GetProcessHeap(), 0, str);
3096 WARN("Failed to get multibyte length\n");
3097 return 0;
3100 if (charcount < len)
3102 HeapFree(GetProcessHeap(), 0, str);
3103 return len - 1;
3106 len = WideCharToMultiByte(cp, 0, str, -1, path, charcount, NULL, NULL);
3107 if (!len)
3109 HeapFree(GetProcessHeap(), 0, str);
3110 WARN("WideCharToMultiByte failed\n");
3111 return 0;
3114 HeapFree(GetProcessHeap(), 0, str);
3116 return len - 1;