ntdll: Add stub for RtlGetUnloadEventTraceEx.
[wine.git] / dlls / kernel32 / file.c
blob3214d724cbb57b5e2a458eb4bbedcf7b0af56e0d
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 FileFullDirectoryInfo:
1107 case FileFullDirectoryRestartInfo:
1108 case FileStorageInfo:
1109 case FileAlignmentInfo:
1110 case FileIdInfo:
1111 case FileIdExtdDirectoryInfo:
1112 case FileIdExtdDirectoryRestartInfo:
1113 FIXME( "%p, %u, %p, %u\n", file, class, info, size );
1114 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1115 return FALSE;
1117 case FileDispositionInfo:
1118 status = NtSetInformationFile( file, &io, info, size, FileDispositionInformation );
1119 break;
1120 case FileIoPriorityHintInfo:
1121 status = NtSetInformationFile( file, &io, info, size, FileIoPriorityHintInformation );
1122 break;
1123 case FileStandardInfo:
1124 case FileCompressionInfo:
1125 case FileAttributeTagInfo:
1126 case FileRemoteProtocolInfo:
1127 default:
1128 SetLastError( ERROR_INVALID_PARAMETER );
1129 return FALSE;
1132 if (status != STATUS_SUCCESS)
1134 SetLastError( RtlNtStatusToDosError( status ) );
1135 return FALSE;
1137 return TRUE;
1141 /***********************************************************************
1142 * SetFilePointer (KERNEL32.@)
1144 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1146 LARGE_INTEGER dist, newpos;
1148 if (highword)
1150 dist.u.LowPart = distance;
1151 dist.u.HighPart = *highword;
1153 else dist.QuadPart = distance;
1155 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1157 if (highword) *highword = newpos.u.HighPart;
1158 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1159 return newpos.u.LowPart;
1163 /***********************************************************************
1164 * SetFilePointerEx (KERNEL32.@)
1166 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1167 LARGE_INTEGER *newpos, DWORD method )
1169 LONGLONG pos;
1170 IO_STATUS_BLOCK io;
1171 FILE_POSITION_INFORMATION info;
1173 switch(method)
1175 case FILE_BEGIN:
1176 pos = distance.QuadPart;
1177 break;
1178 case FILE_CURRENT:
1179 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1180 goto error;
1181 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1182 break;
1183 case FILE_END:
1185 FILE_END_OF_FILE_INFORMATION eof;
1186 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1187 goto error;
1188 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1190 break;
1191 default:
1192 SetLastError( ERROR_INVALID_PARAMETER );
1193 return FALSE;
1196 if (pos < 0)
1198 SetLastError( ERROR_NEGATIVE_SEEK );
1199 return FALSE;
1202 info.CurrentByteOffset.QuadPart = pos;
1203 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1204 goto error;
1205 if (newpos) newpos->QuadPart = pos;
1206 return TRUE;
1208 error:
1209 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1210 return FALSE;
1213 /***********************************************************************
1214 * SetFileValidData (KERNEL32.@)
1216 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1218 FILE_VALID_DATA_LENGTH_INFORMATION info;
1219 IO_STATUS_BLOCK io;
1220 NTSTATUS status;
1222 info.ValidDataLength.QuadPart = ValidDataLength;
1223 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1225 if (status == STATUS_SUCCESS) return TRUE;
1226 SetLastError( RtlNtStatusToDosError(status) );
1227 return FALSE;
1230 /***********************************************************************
1231 * GetFileTime (KERNEL32.@)
1233 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1234 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1236 FILE_BASIC_INFORMATION info;
1237 IO_STATUS_BLOCK io;
1238 NTSTATUS status;
1240 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1241 if (status == STATUS_SUCCESS)
1243 if (lpCreationTime)
1245 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1246 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1248 if (lpLastAccessTime)
1250 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1251 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1253 if (lpLastWriteTime)
1255 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1256 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1258 return TRUE;
1260 SetLastError( RtlNtStatusToDosError(status) );
1261 return FALSE;
1265 /***********************************************************************
1266 * SetFileTime (KERNEL32.@)
1268 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1269 const FILETIME *atime, const FILETIME *mtime )
1271 FILE_BASIC_INFORMATION info;
1272 IO_STATUS_BLOCK io;
1273 NTSTATUS status;
1275 memset( &info, 0, sizeof(info) );
1276 if (ctime)
1278 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1279 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1281 if (atime)
1283 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1284 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1286 if (mtime)
1288 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1289 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1292 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1293 if (status == STATUS_SUCCESS) return TRUE;
1294 SetLastError( RtlNtStatusToDosError(status) );
1295 return FALSE;
1299 /**************************************************************************
1300 * LockFile (KERNEL32.@)
1302 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1303 DWORD count_low, DWORD count_high )
1305 NTSTATUS status;
1306 LARGE_INTEGER count, offset;
1308 TRACE( "%p %x%08x %x%08x\n",
1309 hFile, offset_high, offset_low, count_high, count_low );
1311 count.u.LowPart = count_low;
1312 count.u.HighPart = count_high;
1313 offset.u.LowPart = offset_low;
1314 offset.u.HighPart = offset_high;
1316 status = NtLockFile( hFile, 0, NULL, NULL,
1317 NULL, &offset, &count, NULL, TRUE, TRUE );
1319 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1320 return !status;
1324 /**************************************************************************
1325 * LockFileEx [KERNEL32.@]
1327 * Locks a byte range within an open file for shared or exclusive access.
1329 * RETURNS
1330 * success: TRUE
1331 * failure: FALSE
1333 * NOTES
1334 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1336 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1337 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1339 NTSTATUS status;
1340 LARGE_INTEGER count, offset;
1341 LPVOID cvalue = NULL;
1343 if (reserved)
1345 SetLastError( ERROR_INVALID_PARAMETER );
1346 return FALSE;
1349 TRACE( "%p %x%08x %x%08x flags %x\n",
1350 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1351 count_high, count_low, flags );
1353 count.u.LowPart = count_low;
1354 count.u.HighPart = count_high;
1355 offset.u.LowPart = overlapped->u.s.Offset;
1356 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1358 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1360 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1361 NULL, &offset, &count, NULL,
1362 flags & LOCKFILE_FAIL_IMMEDIATELY,
1363 flags & LOCKFILE_EXCLUSIVE_LOCK );
1365 if (status) SetLastError( RtlNtStatusToDosError(status) );
1366 return !status;
1370 /**************************************************************************
1371 * UnlockFile (KERNEL32.@)
1373 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1374 DWORD count_low, DWORD count_high )
1376 NTSTATUS status;
1377 LARGE_INTEGER count, offset;
1379 count.u.LowPart = count_low;
1380 count.u.HighPart = count_high;
1381 offset.u.LowPart = offset_low;
1382 offset.u.HighPart = offset_high;
1384 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1385 if (status) SetLastError( RtlNtStatusToDosError(status) );
1386 return !status;
1390 /**************************************************************************
1391 * UnlockFileEx (KERNEL32.@)
1393 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1394 LPOVERLAPPED overlapped )
1396 if (reserved)
1398 SetLastError( ERROR_INVALID_PARAMETER );
1399 return FALSE;
1401 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1403 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1407 /*************************************************************************
1408 * SetHandleCount (KERNEL32.@)
1410 UINT WINAPI SetHandleCount( UINT count )
1412 return count;
1416 /**************************************************************************
1417 * Operations on file names *
1418 **************************************************************************/
1421 /*************************************************************************
1422 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1424 * Creates or opens an object, and returns a handle that can be used to
1425 * access that object.
1427 * PARAMS
1429 * filename [in] pointer to filename to be accessed
1430 * access [in] access mode requested
1431 * sharing [in] share mode
1432 * sa [in] pointer to security attributes
1433 * creation [in] how to create the file
1434 * attributes [in] attributes for newly created file
1435 * template [in] handle to file with extended attributes to copy
1437 * RETURNS
1438 * Success: Open handle to specified file
1439 * Failure: INVALID_HANDLE_VALUE
1441 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1442 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1443 DWORD attributes, HANDLE template )
1445 NTSTATUS status;
1446 UINT options;
1447 OBJECT_ATTRIBUTES attr;
1448 UNICODE_STRING nameW;
1449 IO_STATUS_BLOCK io;
1450 HANDLE ret;
1451 DWORD dosdev;
1452 const WCHAR *vxd_name = NULL;
1453 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1454 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1455 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1456 SECURITY_QUALITY_OF_SERVICE qos;
1458 static const UINT nt_disposition[5] =
1460 FILE_CREATE, /* CREATE_NEW */
1461 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1462 FILE_OPEN, /* OPEN_EXISTING */
1463 FILE_OPEN_IF, /* OPEN_ALWAYS */
1464 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1468 /* sanity checks */
1470 if (!filename || !filename[0])
1472 SetLastError( ERROR_PATH_NOT_FOUND );
1473 return INVALID_HANDLE_VALUE;
1476 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1477 (access & GENERIC_READ)?"GENERIC_READ ":"",
1478 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1479 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1480 (!access)?"QUERY_ACCESS ":"",
1481 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1482 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1483 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1484 creation, attributes);
1486 /* Open a console for CONIN$ or CONOUT$ */
1488 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1490 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1491 creation ? OPEN_EXISTING : 0);
1492 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1493 goto done;
1496 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1498 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1499 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1501 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1502 !strncmpiW( filename + 4, pipeW, 5 ) ||
1503 !strncmpiW( filename + 4, mailslotW, 9 ))
1505 dosdev = 0;
1507 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1509 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1511 else if (GetVersion() & 0x80000000)
1513 vxd_name = filename + 4;
1514 if (!creation) creation = OPEN_EXISTING;
1517 else dosdev = RtlIsDosDeviceName_U( filename );
1519 if (dosdev)
1521 static const WCHAR conW[] = {'C','O','N'};
1523 if (LOWORD(dosdev) == sizeof(conW) &&
1524 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, ARRAY_SIZE( conW )))
1526 switch (access & (GENERIC_READ|GENERIC_WRITE))
1528 case GENERIC_READ:
1529 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1530 goto done;
1531 case GENERIC_WRITE:
1532 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1533 goto done;
1534 default:
1535 SetLastError( ERROR_FILE_NOT_FOUND );
1536 return INVALID_HANDLE_VALUE;
1541 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1543 SetLastError( ERROR_INVALID_PARAMETER );
1544 return INVALID_HANDLE_VALUE;
1547 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1549 SetLastError( ERROR_PATH_NOT_FOUND );
1550 return INVALID_HANDLE_VALUE;
1553 /* now call NtCreateFile */
1555 options = 0;
1556 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1557 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1558 else
1559 options |= FILE_NON_DIRECTORY_FILE;
1560 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1562 options |= FILE_DELETE_ON_CLOSE;
1563 access |= DELETE;
1565 if (attributes & FILE_FLAG_NO_BUFFERING)
1566 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1567 if (!(attributes & FILE_FLAG_OVERLAPPED))
1568 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1569 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1570 options |= FILE_RANDOM_ACCESS;
1571 if (attributes & FILE_FLAG_WRITE_THROUGH)
1572 options |= FILE_WRITE_THROUGH;
1573 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1575 attr.Length = sizeof(attr);
1576 attr.RootDirectory = 0;
1577 attr.Attributes = OBJ_CASE_INSENSITIVE;
1578 attr.ObjectName = &nameW;
1579 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1580 if (attributes & SECURITY_SQOS_PRESENT)
1582 qos.Length = sizeof(qos);
1583 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1584 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1585 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1586 attr.SecurityQualityOfService = &qos;
1588 else
1589 attr.SecurityQualityOfService = NULL;
1591 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1593 status = NtCreateFile( &ret, access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attr, &io,
1594 NULL, attributes, sharing, nt_disposition[creation - CREATE_NEW],
1595 options, NULL, 0 );
1596 if (status)
1598 if (vxd_name && vxd_name[0])
1600 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1601 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleW(krnl386W),
1602 "__wine_vxd_open" );
1603 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1606 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1607 ret = INVALID_HANDLE_VALUE;
1609 /* In the case file creation was rejected due to CREATE_NEW flag
1610 * was specified and file with that name already exists, correct
1611 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1612 * Note: RtlNtStatusToDosError is not the subject to blame here.
1614 if (status == STATUS_OBJECT_NAME_COLLISION)
1615 SetLastError( ERROR_FILE_EXISTS );
1616 else
1617 SetLastError( RtlNtStatusToDosError(status) );
1619 else
1621 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1622 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1623 SetLastError( ERROR_ALREADY_EXISTS );
1624 else
1625 SetLastError( 0 );
1627 RtlFreeUnicodeString( &nameW );
1629 done:
1630 if (!ret) ret = INVALID_HANDLE_VALUE;
1631 TRACE("returning %p\n", ret);
1632 return ret;
1637 /*************************************************************************
1638 * CreateFileA (KERNEL32.@)
1640 * See CreateFileW.
1642 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1643 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1644 DWORD attributes, HANDLE template)
1646 WCHAR *nameW;
1648 if ((GetVersion() & 0x80000000) && IsBadStringPtrA(filename, -1)) return INVALID_HANDLE_VALUE;
1649 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1650 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1653 /*************************************************************************
1654 * CreateFile2 (KERNEL32.@)
1656 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1657 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1659 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1660 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1661 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1663 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1665 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1668 /***********************************************************************
1669 * DeleteFileW (KERNEL32.@)
1671 * Delete a file.
1673 * PARAMS
1674 * path [I] Path to the file to delete.
1676 * RETURNS
1677 * Success: TRUE.
1678 * Failure: FALSE, check GetLastError().
1680 BOOL WINAPI DeleteFileW( LPCWSTR path )
1682 UNICODE_STRING nameW;
1683 OBJECT_ATTRIBUTES attr;
1684 NTSTATUS status;
1685 HANDLE hFile;
1686 IO_STATUS_BLOCK io;
1688 TRACE("%s\n", debugstr_w(path) );
1690 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1692 SetLastError( ERROR_PATH_NOT_FOUND );
1693 return FALSE;
1696 attr.Length = sizeof(attr);
1697 attr.RootDirectory = 0;
1698 attr.Attributes = OBJ_CASE_INSENSITIVE;
1699 attr.ObjectName = &nameW;
1700 attr.SecurityDescriptor = NULL;
1701 attr.SecurityQualityOfService = NULL;
1703 status = NtCreateFile(&hFile, SYNCHRONIZE | DELETE, &attr, &io, NULL, 0,
1704 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1705 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1706 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1708 RtlFreeUnicodeString( &nameW );
1709 if (status)
1711 SetLastError( RtlNtStatusToDosError(status) );
1712 return FALSE;
1714 return TRUE;
1718 /***********************************************************************
1719 * DeleteFileA (KERNEL32.@)
1721 * See DeleteFileW.
1723 BOOL WINAPI DeleteFileA( LPCSTR path )
1725 WCHAR *pathW;
1727 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1728 return DeleteFileW( pathW );
1732 /**************************************************************************
1733 * ReplaceFileW (KERNEL32.@)
1734 * ReplaceFile (KERNEL32.@)
1736 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1737 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1738 LPVOID lpExclude, LPVOID lpReserved)
1740 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1741 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1742 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1743 DWORD error = ERROR_SUCCESS;
1744 UINT replaced_flags;
1745 BOOL ret = FALSE;
1746 NTSTATUS status;
1747 IO_STATUS_BLOCK io;
1748 OBJECT_ATTRIBUTES attr;
1750 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1751 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1752 dwReplaceFlags, lpExclude, lpReserved);
1754 if (dwReplaceFlags)
1755 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1757 /* First two arguments are mandatory */
1758 if (!lpReplacedFileName || !lpReplacementFileName)
1760 SetLastError(ERROR_INVALID_PARAMETER);
1761 return FALSE;
1764 unix_replaced_name.Buffer = NULL;
1765 unix_replacement_name.Buffer = NULL;
1766 unix_backup_name.Buffer = NULL;
1768 attr.Length = sizeof(attr);
1769 attr.RootDirectory = 0;
1770 attr.Attributes = OBJ_CASE_INSENSITIVE;
1771 attr.ObjectName = NULL;
1772 attr.SecurityDescriptor = NULL;
1773 attr.SecurityQualityOfService = NULL;
1775 /* Open the "replaced" file for reading and writing */
1776 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1778 error = ERROR_PATH_NOT_FOUND;
1779 goto fail;
1781 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1782 attr.ObjectName = &nt_replaced_name;
1783 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1784 &attr, &io,
1785 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1786 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1787 if (status == STATUS_SUCCESS)
1788 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1789 RtlFreeUnicodeString(&nt_replaced_name);
1790 if (status != STATUS_SUCCESS)
1792 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1793 error = ERROR_FILE_NOT_FOUND;
1794 else
1795 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1796 goto fail;
1800 * Open the replacement file for reading, writing, and deleting
1801 * (writing and deleting are needed when finished)
1803 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1805 error = ERROR_PATH_NOT_FOUND;
1806 goto fail;
1808 attr.ObjectName = &nt_replacement_name;
1809 status = NtOpenFile(&hReplacement,
1810 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1811 &attr, &io, 0,
1812 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1813 if (status == STATUS_SUCCESS)
1814 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1815 RtlFreeUnicodeString(&nt_replacement_name);
1816 if (status != STATUS_SUCCESS)
1818 error = RtlNtStatusToDosError(status);
1819 goto fail;
1822 /* If the user wants a backup then that needs to be performed first */
1823 if (lpBackupFileName)
1825 UNICODE_STRING nt_backup_name;
1826 FILE_BASIC_INFORMATION replaced_info;
1828 /* Obtain the file attributes from the "replaced" file */
1829 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1830 sizeof(replaced_info),
1831 FileBasicInformation);
1832 if (status != STATUS_SUCCESS)
1834 error = RtlNtStatusToDosError(status);
1835 goto fail;
1838 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1840 error = ERROR_PATH_NOT_FOUND;
1841 goto fail;
1843 attr.ObjectName = &nt_backup_name;
1844 /* Open the backup with permissions to write over it */
1845 status = NtCreateFile(&hBackup, GENERIC_WRITE | SYNCHRONIZE,
1846 &attr, &io, NULL, replaced_info.FileAttributes,
1847 FILE_SHARE_WRITE, FILE_OPEN_IF,
1848 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1849 NULL, 0);
1850 if (status == STATUS_SUCCESS)
1851 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1852 RtlFreeUnicodeString(&nt_backup_name);
1853 if (status != STATUS_SUCCESS)
1855 error = RtlNtStatusToDosError(status);
1856 goto fail;
1859 /* If an existing backup exists then copy over it */
1860 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1862 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1863 goto fail;
1868 * Now that the backup has been performed (if requested), copy the replacement
1869 * into place
1871 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1873 if (errno == EACCES)
1875 /* Inappropriate permissions on "replaced", rename will fail */
1876 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1877 goto fail;
1879 /* on failure we need to indicate whether a backup was made */
1880 if (!lpBackupFileName)
1881 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1882 else
1883 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1884 goto fail;
1886 /* Success! */
1887 ret = TRUE;
1889 /* Perform resource cleanup */
1890 fail:
1891 if (hBackup) CloseHandle(hBackup);
1892 if (hReplaced) CloseHandle(hReplaced);
1893 if (hReplacement) CloseHandle(hReplacement);
1894 RtlFreeAnsiString(&unix_backup_name);
1895 RtlFreeAnsiString(&unix_replacement_name);
1896 RtlFreeAnsiString(&unix_replaced_name);
1898 /* If there was an error, set the error code */
1899 if(!ret)
1900 SetLastError(error);
1901 return ret;
1905 /**************************************************************************
1906 * ReplaceFileA (KERNEL32.@)
1908 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1909 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1910 LPVOID lpExclude, LPVOID lpReserved)
1912 WCHAR *replacedW, *replacementW, *backupW = NULL;
1913 BOOL ret;
1915 /* This function only makes sense when the first two parameters are defined */
1916 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1918 SetLastError(ERROR_INVALID_PARAMETER);
1919 return FALSE;
1921 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1923 HeapFree( GetProcessHeap(), 0, replacedW );
1924 SetLastError(ERROR_INVALID_PARAMETER);
1925 return FALSE;
1927 /* The backup parameter, however, is optional */
1928 if (lpBackupFileName)
1930 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1932 HeapFree( GetProcessHeap(), 0, replacedW );
1933 HeapFree( GetProcessHeap(), 0, replacementW );
1934 SetLastError(ERROR_INVALID_PARAMETER);
1935 return FALSE;
1938 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1939 HeapFree( GetProcessHeap(), 0, replacedW );
1940 HeapFree( GetProcessHeap(), 0, replacementW );
1941 HeapFree( GetProcessHeap(), 0, backupW );
1942 return ret;
1946 /*************************************************************************
1947 * FindFirstFileExW (KERNEL32.@)
1949 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1950 * results as FindExSearchNameMatch
1952 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1953 LPVOID data, FINDEX_SEARCH_OPS search_op,
1954 LPVOID filter, DWORD flags)
1956 WCHAR *mask;
1957 BOOL has_wildcard = FALSE;
1958 FIND_FIRST_INFO *info = NULL;
1959 UNICODE_STRING nt_name;
1960 OBJECT_ATTRIBUTES attr;
1961 IO_STATUS_BLOCK io;
1962 NTSTATUS status;
1963 DWORD size, device = 0;
1965 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1967 if (flags != 0)
1969 FIXME("flags not implemented 0x%08x\n", flags );
1971 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1973 FIXME("search_op not implemented 0x%08x\n", search_op);
1974 SetLastError( ERROR_INVALID_PARAMETER );
1975 return INVALID_HANDLE_VALUE;
1977 if (level != FindExInfoStandard && level != FindExInfoBasic)
1979 FIXME("info level %d not implemented\n", level );
1980 SetLastError( ERROR_INVALID_PARAMETER );
1981 return INVALID_HANDLE_VALUE;
1984 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1986 SetLastError( ERROR_PATH_NOT_FOUND );
1987 return INVALID_HANDLE_VALUE;
1990 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1992 static const WCHAR dotW[] = {'.',0};
1993 WCHAR *dir = NULL;
1995 /* we still need to check that the directory can be opened */
1997 if (HIWORD(device))
1999 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
2001 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2002 goto error;
2004 memcpy( dir, filename, HIWORD(device) );
2005 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
2007 RtlFreeUnicodeString( &nt_name );
2008 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
2010 HeapFree( GetProcessHeap(), 0, dir );
2011 SetLastError( ERROR_PATH_NOT_FOUND );
2012 goto error;
2014 HeapFree( GetProcessHeap(), 0, dir );
2015 size = 0;
2017 else if (!mask || !*mask)
2019 SetLastError( ERROR_FILE_NOT_FOUND );
2020 goto error;
2022 else
2024 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
2025 has_wildcard = strpbrkW( mask, wildcardsW ) != NULL;
2026 size = has_wildcard ? 8192 : max_entry_size;
2029 if (!(info = HeapAlloc( GetProcessHeap(), 0, offsetof( FIND_FIRST_INFO, data[size] ))))
2031 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2032 goto error;
2035 /* check if path is the root of the drive, skipping the \??\ prefix */
2036 info->is_root = FALSE;
2037 if (nt_name.Length >= 6 * sizeof(WCHAR) && nt_name.Buffer[5] == ':')
2039 DWORD pos = 6;
2040 while (pos * sizeof(WCHAR) < nt_name.Length && nt_name.Buffer[pos] == '\\') pos++;
2041 info->is_root = (pos * sizeof(WCHAR) >= nt_name.Length);
2044 attr.Length = sizeof(attr);
2045 attr.RootDirectory = 0;
2046 attr.Attributes = OBJ_CASE_INSENSITIVE;
2047 attr.ObjectName = &nt_name;
2048 attr.SecurityDescriptor = NULL;
2049 attr.SecurityQualityOfService = NULL;
2051 status = NtOpenFile( &info->handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2052 FILE_SHARE_READ | FILE_SHARE_WRITE,
2053 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2055 if (status != STATUS_SUCCESS)
2057 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
2058 SetLastError( ERROR_PATH_NOT_FOUND );
2059 else
2060 SetLastError( RtlNtStatusToDosError(status) );
2061 goto error;
2064 RtlInitializeCriticalSection( &info->cs );
2065 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
2066 info->path = nt_name;
2067 info->magic = FIND_FIRST_MAGIC;
2068 info->wildcard = has_wildcard;
2069 info->data_pos = 0;
2070 info->data_len = 0;
2071 info->data_size = size;
2072 info->search_op = search_op;
2073 info->level = level;
2075 if (device)
2077 WIN32_FIND_DATAW *wfd = data;
2079 memset( wfd, 0, sizeof(*wfd) );
2080 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
2081 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
2082 CloseHandle( info->handle );
2083 info->handle = 0;
2085 else
2087 UNICODE_STRING mask_str;
2089 RtlInitUnicodeString( &mask_str, mask );
2090 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2091 FileBothDirectoryInformation, FALSE, &mask_str, TRUE );
2092 if (status)
2094 FindClose( info );
2095 SetLastError( RtlNtStatusToDosError( status ) );
2096 return INVALID_HANDLE_VALUE;
2099 info->data_len = io.Information;
2100 if (!has_wildcard || info->data_len < info->data_size - max_entry_size)
2102 if (has_wildcard) /* release unused buffer space */
2103 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY,
2104 info, offsetof( FIND_FIRST_INFO, data[info->data_len] ));
2105 info->data_size = 0; /* we read everything */
2108 if (!FindNextFileW( info, data ))
2110 TRACE( "%s not found\n", debugstr_w(filename) );
2111 FindClose( info );
2112 SetLastError( ERROR_FILE_NOT_FOUND );
2113 return INVALID_HANDLE_VALUE;
2115 if (!has_wildcard) /* we can't find two files with the same name */
2117 CloseHandle( info->handle );
2118 info->handle = 0;
2121 return info;
2123 error:
2124 HeapFree( GetProcessHeap(), 0, info );
2125 RtlFreeUnicodeString( &nt_name );
2126 return INVALID_HANDLE_VALUE;
2130 /*************************************************************************
2131 * FindNextFileW (KERNEL32.@)
2133 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2135 FIND_FIRST_INFO *info;
2136 FILE_BOTH_DIR_INFORMATION *dir_info;
2137 BOOL ret = FALSE;
2138 NTSTATUS status;
2140 TRACE("%p %p\n", handle, data);
2142 if (!handle || handle == INVALID_HANDLE_VALUE)
2144 SetLastError( ERROR_INVALID_HANDLE );
2145 return ret;
2147 info = handle;
2148 if (info->magic != FIND_FIRST_MAGIC)
2150 SetLastError( ERROR_INVALID_HANDLE );
2151 return ret;
2154 RtlEnterCriticalSection( &info->cs );
2156 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2157 else for (;;)
2159 if (info->data_pos >= info->data_len) /* need to read some more data */
2161 IO_STATUS_BLOCK io;
2163 if (info->data_size)
2164 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2165 FileBothDirectoryInformation, FALSE, NULL, FALSE );
2166 else
2167 status = STATUS_NO_MORE_FILES;
2169 if (status)
2171 SetLastError( RtlNtStatusToDosError( status ) );
2172 if (status == STATUS_NO_MORE_FILES)
2174 CloseHandle( info->handle );
2175 info->handle = 0;
2177 break;
2179 info->data_len = io.Information;
2180 info->data_pos = 0;
2183 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2185 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2186 else info->data_pos = info->data_len;
2188 /* don't return '.' and '..' in the root of the drive */
2189 if (info->is_root)
2191 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2192 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2193 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2196 /* check for dir symlink */
2197 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2198 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2199 info->wildcard)
2201 if (!check_dir_symlink( info, dir_info )) continue;
2204 data->dwFileAttributes = dir_info->FileAttributes;
2205 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2206 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2207 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2208 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2209 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2210 data->dwReserved0 = 0;
2211 data->dwReserved1 = 0;
2213 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2214 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2216 if (info->level != FindExInfoBasic)
2218 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2219 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2221 else
2222 data->cAlternateFileName[0] = 0;
2224 TRACE("returning %s (%s)\n",
2225 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2227 ret = TRUE;
2228 break;
2231 RtlLeaveCriticalSection( &info->cs );
2232 return ret;
2236 /*************************************************************************
2237 * FindClose (KERNEL32.@)
2239 BOOL WINAPI FindClose( HANDLE handle )
2241 FIND_FIRST_INFO *info = handle;
2243 if (!handle || handle == INVALID_HANDLE_VALUE)
2245 SetLastError( ERROR_INVALID_HANDLE );
2246 return FALSE;
2249 __TRY
2251 if (info->magic == FIND_FIRST_MAGIC)
2253 RtlEnterCriticalSection( &info->cs );
2254 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2256 info->magic = 0;
2257 if (info->handle) CloseHandle( info->handle );
2258 info->handle = 0;
2259 RtlFreeUnicodeString( &info->path );
2260 info->data_pos = 0;
2261 info->data_len = 0;
2262 RtlLeaveCriticalSection( &info->cs );
2263 info->cs.DebugInfo->Spare[0] = 0;
2264 RtlDeleteCriticalSection( &info->cs );
2265 HeapFree( GetProcessHeap(), 0, info );
2269 __EXCEPT_PAGE_FAULT
2271 WARN("Illegal handle %p\n", handle);
2272 SetLastError( ERROR_INVALID_HANDLE );
2273 return FALSE;
2275 __ENDTRY
2277 return TRUE;
2281 /*************************************************************************
2282 * FindFirstFileA (KERNEL32.@)
2284 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2286 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2287 FindExSearchNameMatch, NULL, 0);
2290 /*************************************************************************
2291 * FindFirstFileExA (KERNEL32.@)
2293 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2294 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2295 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2297 HANDLE handle;
2298 WIN32_FIND_DATAA *dataA;
2299 WIN32_FIND_DATAW dataW;
2300 WCHAR *nameW;
2302 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2304 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2305 if (handle == INVALID_HANDLE_VALUE) return handle;
2307 dataA = lpFindFileData;
2308 dataA->dwFileAttributes = dataW.dwFileAttributes;
2309 dataA->ftCreationTime = dataW.ftCreationTime;
2310 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2311 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2312 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2313 dataA->nFileSizeLow = dataW.nFileSizeLow;
2314 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2315 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2316 sizeof(dataA->cAlternateFileName) );
2317 return handle;
2321 /*************************************************************************
2322 * FindFirstFileW (KERNEL32.@)
2324 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2326 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2327 FindExSearchNameMatch, NULL, 0);
2331 /*************************************************************************
2332 * FindNextFileA (KERNEL32.@)
2334 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2336 WIN32_FIND_DATAW dataW;
2338 if (!FindNextFileW( handle, &dataW )) return FALSE;
2339 data->dwFileAttributes = dataW.dwFileAttributes;
2340 data->ftCreationTime = dataW.ftCreationTime;
2341 data->ftLastAccessTime = dataW.ftLastAccessTime;
2342 data->ftLastWriteTime = dataW.ftLastWriteTime;
2343 data->nFileSizeHigh = dataW.nFileSizeHigh;
2344 data->nFileSizeLow = dataW.nFileSizeLow;
2345 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2346 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2347 sizeof(data->cAlternateFileName) );
2348 return TRUE;
2352 /**************************************************************************
2353 * GetFileAttributesW (KERNEL32.@)
2355 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2357 FILE_BASIC_INFORMATION info;
2358 UNICODE_STRING nt_name;
2359 OBJECT_ATTRIBUTES attr;
2360 NTSTATUS status;
2362 TRACE("%s\n", debugstr_w(name));
2364 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2366 SetLastError( ERROR_PATH_NOT_FOUND );
2367 return INVALID_FILE_ATTRIBUTES;
2370 attr.Length = sizeof(attr);
2371 attr.RootDirectory = 0;
2372 attr.Attributes = OBJ_CASE_INSENSITIVE;
2373 attr.ObjectName = &nt_name;
2374 attr.SecurityDescriptor = NULL;
2375 attr.SecurityQualityOfService = NULL;
2377 status = NtQueryAttributesFile( &attr, &info );
2378 RtlFreeUnicodeString( &nt_name );
2380 if (status == STATUS_SUCCESS) return info.FileAttributes;
2382 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2383 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2385 SetLastError( RtlNtStatusToDosError(status) );
2386 return INVALID_FILE_ATTRIBUTES;
2390 /**************************************************************************
2391 * GetFileAttributesA (KERNEL32.@)
2393 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2395 WCHAR *nameW;
2397 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2398 return GetFileAttributesW( nameW );
2402 /**************************************************************************
2403 * SetFileAttributesW (KERNEL32.@)
2405 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2407 UNICODE_STRING nt_name;
2408 OBJECT_ATTRIBUTES attr;
2409 IO_STATUS_BLOCK io;
2410 NTSTATUS status;
2411 HANDLE handle;
2413 TRACE("%s %x\n", debugstr_w(name), attributes);
2415 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2417 SetLastError( ERROR_PATH_NOT_FOUND );
2418 return FALSE;
2421 attr.Length = sizeof(attr);
2422 attr.RootDirectory = 0;
2423 attr.Attributes = OBJ_CASE_INSENSITIVE;
2424 attr.ObjectName = &nt_name;
2425 attr.SecurityDescriptor = NULL;
2426 attr.SecurityQualityOfService = NULL;
2428 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2429 RtlFreeUnicodeString( &nt_name );
2431 if (status == STATUS_SUCCESS)
2433 FILE_BASIC_INFORMATION info;
2435 memset( &info, 0, sizeof(info) );
2436 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2437 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2438 NtClose( handle );
2441 if (status == STATUS_SUCCESS) return TRUE;
2442 SetLastError( RtlNtStatusToDosError(status) );
2443 return FALSE;
2447 /**************************************************************************
2448 * SetFileAttributesA (KERNEL32.@)
2450 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2452 WCHAR *nameW;
2454 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2455 return SetFileAttributesW( nameW, attributes );
2459 /**************************************************************************
2460 * GetFileAttributesExW (KERNEL32.@)
2462 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2464 FILE_NETWORK_OPEN_INFORMATION info;
2465 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2466 UNICODE_STRING nt_name;
2467 OBJECT_ATTRIBUTES attr;
2468 NTSTATUS status;
2470 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2472 if (level != GetFileExInfoStandard)
2474 SetLastError( ERROR_INVALID_PARAMETER );
2475 return FALSE;
2478 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2480 SetLastError( ERROR_PATH_NOT_FOUND );
2481 return FALSE;
2484 attr.Length = sizeof(attr);
2485 attr.RootDirectory = 0;
2486 attr.Attributes = OBJ_CASE_INSENSITIVE;
2487 attr.ObjectName = &nt_name;
2488 attr.SecurityDescriptor = NULL;
2489 attr.SecurityQualityOfService = NULL;
2491 status = NtQueryFullAttributesFile( &attr, &info );
2492 RtlFreeUnicodeString( &nt_name );
2494 if (status != STATUS_SUCCESS)
2496 SetLastError( RtlNtStatusToDosError(status) );
2497 return FALSE;
2500 data->dwFileAttributes = info.FileAttributes;
2501 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2502 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2503 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2504 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2505 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2506 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2507 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2508 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2509 return TRUE;
2513 /**************************************************************************
2514 * GetFileAttributesExA (KERNEL32.@)
2516 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2518 WCHAR *nameW;
2520 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2521 return GetFileAttributesExW( nameW, level, ptr );
2525 /******************************************************************************
2526 * GetCompressedFileSizeW (KERNEL32.@)
2528 * Get the actual number of bytes used on disk.
2530 * RETURNS
2531 * Success: Low-order doubleword of number of bytes
2532 * Failure: INVALID_FILE_SIZE
2534 DWORD WINAPI GetCompressedFileSizeW(
2535 LPCWSTR name, /* [in] Pointer to name of file */
2536 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2538 UNICODE_STRING nt_name;
2539 OBJECT_ATTRIBUTES attr;
2540 IO_STATUS_BLOCK io;
2541 NTSTATUS status;
2542 HANDLE handle;
2543 DWORD ret = INVALID_FILE_SIZE;
2545 TRACE("%s %p\n", debugstr_w(name), size_high);
2547 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2549 SetLastError( ERROR_PATH_NOT_FOUND );
2550 return INVALID_FILE_SIZE;
2553 attr.Length = sizeof(attr);
2554 attr.RootDirectory = 0;
2555 attr.Attributes = OBJ_CASE_INSENSITIVE;
2556 attr.ObjectName = &nt_name;
2557 attr.SecurityDescriptor = NULL;
2558 attr.SecurityQualityOfService = NULL;
2560 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2561 RtlFreeUnicodeString( &nt_name );
2563 if (status == STATUS_SUCCESS)
2565 /* we don't support compressed files, simply return the file size */
2566 ret = GetFileSize( handle, size_high );
2567 NtClose( handle );
2569 else SetLastError( RtlNtStatusToDosError(status) );
2571 return ret;
2575 /******************************************************************************
2576 * GetCompressedFileSizeA (KERNEL32.@)
2578 * See GetCompressedFileSizeW.
2580 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2582 WCHAR *nameW;
2584 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2585 return GetCompressedFileSizeW( nameW, size_high );
2589 /***********************************************************************
2590 * OpenVxDHandle (KERNEL32.@)
2592 * This function is supposed to return the corresponding Ring 0
2593 * ("kernel") handle for a Ring 3 handle in Win9x.
2594 * Evidently, Wine will have problems with this. But we try anyway,
2595 * maybe it helps...
2597 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2599 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2600 return hHandleRing3;
2604 /****************************************************************************
2605 * DeviceIoControl (KERNEL32.@)
2607 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2608 LPVOID lpvInBuffer, DWORD cbInBuffer,
2609 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2610 LPDWORD lpcbBytesReturned,
2611 LPOVERLAPPED lpOverlapped)
2613 NTSTATUS status;
2615 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2616 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2617 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2619 /* Check if this is a user defined control code for a VxD */
2621 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2623 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2624 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2625 DeviceIoProc proc = NULL;
2627 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleW(krnl386W),
2628 "__wine_vxd_get_proc" );
2629 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2630 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2631 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2634 /* Not a VxD, let ntdll handle it */
2636 if (lpOverlapped)
2638 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2639 lpOverlapped->Internal = STATUS_PENDING;
2640 lpOverlapped->InternalHigh = 0;
2641 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2642 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2643 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2644 dwIoControlCode, lpvInBuffer, cbInBuffer,
2645 lpvOutBuffer, cbOutBuffer);
2646 else
2647 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2648 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2649 dwIoControlCode, lpvInBuffer, cbInBuffer,
2650 lpvOutBuffer, cbOutBuffer);
2651 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2653 else
2655 IO_STATUS_BLOCK iosb;
2657 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2658 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2659 dwIoControlCode, lpvInBuffer, cbInBuffer,
2660 lpvOutBuffer, cbOutBuffer);
2661 else
2662 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2663 dwIoControlCode, lpvInBuffer, cbInBuffer,
2664 lpvOutBuffer, cbOutBuffer);
2665 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2667 if (status) SetLastError( RtlNtStatusToDosError(status) );
2668 return !status;
2672 /***********************************************************************
2673 * OpenFile (KERNEL32.@)
2675 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2677 HANDLE handle;
2678 FILETIME filetime;
2679 WORD filedatetime[2];
2681 if (!ofs) return HFILE_ERROR;
2683 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2684 ((mode & 0x3 )==OF_READ)?"OF_READ":
2685 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2686 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2687 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2688 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2689 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2690 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2691 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2692 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2693 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2694 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2695 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2696 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2697 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2698 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2699 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2700 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2704 ofs->cBytes = sizeof(OFSTRUCT);
2705 ofs->nErrCode = 0;
2706 if (mode & OF_REOPEN) name = ofs->szPathName;
2708 if (!name) return HFILE_ERROR;
2710 TRACE("%s %04x\n", name, mode );
2712 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2713 Are there any cases where getting the path here is wrong?
2714 Uwe Bonnes 1997 Apr 2 */
2715 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2717 /* OF_PARSE simply fills the structure */
2719 if (mode & OF_PARSE)
2721 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2722 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2723 return 0;
2726 /* OF_CREATE is completely different from all other options, so
2727 handle it first */
2729 if (mode & OF_CREATE)
2731 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2732 goto error;
2734 else
2736 /* Now look for the file */
2738 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2739 goto error;
2741 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2743 if (mode & OF_DELETE)
2745 if (!DeleteFileA( ofs->szPathName )) goto error;
2746 TRACE("(%s): OF_DELETE return = OK\n", name);
2747 return TRUE;
2750 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2751 if (handle == INVALID_HANDLE_VALUE) goto error;
2753 GetFileTime( handle, NULL, NULL, &filetime );
2754 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2755 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2757 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2759 CloseHandle( handle );
2760 WARN("(%s): OF_VERIFY failed\n", name );
2761 /* FIXME: what error here? */
2762 SetLastError( ERROR_FILE_NOT_FOUND );
2763 goto error;
2766 ofs->Reserved1 = filedatetime[0];
2767 ofs->Reserved2 = filedatetime[1];
2769 TRACE("(%s): OK, return = %p\n", name, handle );
2770 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2772 CloseHandle( handle );
2773 return TRUE;
2775 return HandleToLong(handle);
2777 error: /* We get here if there was an error opening the file */
2778 ofs->nErrCode = GetLastError();
2779 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2780 return HFILE_ERROR;
2784 /***********************************************************************
2785 * OpenFileById (KERNEL32.@)
2787 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2788 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2790 UINT options;
2791 HANDLE result;
2792 OBJECT_ATTRIBUTES attr;
2793 NTSTATUS status;
2794 IO_STATUS_BLOCK io;
2795 UNICODE_STRING objectName;
2797 if (!id)
2799 SetLastError( ERROR_INVALID_PARAMETER );
2800 return INVALID_HANDLE_VALUE;
2803 options = FILE_OPEN_BY_FILE_ID;
2804 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2805 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2806 else
2807 options |= FILE_NON_DIRECTORY_FILE;
2808 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2809 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2810 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2811 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2813 objectName.Length = sizeof(ULONGLONG);
2814 objectName.Buffer = (WCHAR *)&id->u.FileId;
2815 attr.Length = sizeof(attr);
2816 attr.RootDirectory = handle;
2817 attr.Attributes = 0;
2818 attr.ObjectName = &objectName;
2819 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2820 attr.SecurityQualityOfService = NULL;
2821 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2823 status = NtCreateFile( &result, access | SYNCHRONIZE, &attr, &io, NULL, flags,
2824 share, OPEN_EXISTING, options, NULL, 0 );
2825 if (status != STATUS_SUCCESS)
2827 SetLastError( RtlNtStatusToDosError( status ) );
2828 return INVALID_HANDLE_VALUE;
2830 return result;
2833 /***********************************************************************
2834 * ReOpenFile (KERNEL32.@)
2836 HANDLE WINAPI ReOpenFile(HANDLE handle_original, DWORD access, DWORD sharing, DWORD flags)
2838 FIXME("(%p, %d, %d, %d): stub\n", handle_original, access, sharing, flags);
2840 return INVALID_HANDLE_VALUE;
2844 /***********************************************************************
2845 * K32EnumDeviceDrivers (KERNEL32.@)
2847 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2849 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2851 if (needed)
2852 *needed = 0;
2854 return TRUE;
2857 /***********************************************************************
2858 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2860 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2862 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2864 if (base_name && size)
2865 base_name[0] = '\0';
2867 return 0;
2870 /***********************************************************************
2871 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2873 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2875 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2877 if (base_name && size)
2878 base_name[0] = '\0';
2880 return 0;
2883 /***********************************************************************
2884 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2886 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2888 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2890 if (file_name && size)
2891 file_name[0] = '\0';
2893 return 0;
2896 /***********************************************************************
2897 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2899 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2901 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2903 if (file_name && size)
2904 file_name[0] = '\0';
2906 return 0;
2909 /***********************************************************************
2910 * GetFinalPathNameByHandleW (KERNEL32.@)
2912 DWORD WINAPI GetFinalPathNameByHandleW(HANDLE file, LPWSTR path, DWORD charcount, DWORD flags)
2914 WCHAR buffer[sizeof(OBJECT_NAME_INFORMATION) + MAX_PATH + 1];
2915 OBJECT_NAME_INFORMATION *info = (OBJECT_NAME_INFORMATION*)&buffer;
2916 WCHAR drive_part[MAX_PATH];
2917 DWORD drive_part_len = 0;
2918 NTSTATUS status;
2919 DWORD result = 0;
2920 ULONG dummy;
2921 WCHAR *ptr;
2923 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags );
2925 if (flags & ~(FILE_NAME_OPENED | VOLUME_NAME_GUID | VOLUME_NAME_NONE | VOLUME_NAME_NT))
2927 WARN("Unknown flags: %x\n", flags);
2928 SetLastError( ERROR_INVALID_PARAMETER );
2929 return 0;
2932 /* get object name */
2933 status = NtQueryObject( file, ObjectNameInformation, &buffer, sizeof(buffer) - sizeof(WCHAR), &dummy );
2934 if (status != STATUS_SUCCESS)
2936 SetLastError( RtlNtStatusToDosError( status ) );
2937 return 0;
2939 if (!info->Name.Buffer)
2941 SetLastError( ERROR_INVALID_HANDLE );
2942 return 0;
2944 if (info->Name.Length < 4 * sizeof(WCHAR) || info->Name.Buffer[0] != '\\' ||
2945 info->Name.Buffer[1] != '?' || info->Name.Buffer[2] != '?' || info->Name.Buffer[3] != '\\' )
2947 FIXME("Unexpected object name: %s\n", debugstr_wn(info->Name.Buffer, info->Name.Length / sizeof(WCHAR)));
2948 SetLastError( ERROR_GEN_FAILURE );
2949 return 0;
2952 /* add terminating null character, remove "\\??\\" */
2953 info->Name.Buffer[info->Name.Length / sizeof(WCHAR)] = 0;
2954 info->Name.Length -= 4 * sizeof(WCHAR);
2955 info->Name.Buffer += 4;
2957 /* FILE_NAME_OPENED is not supported yet, and would require Wineserver changes */
2958 if (flags & FILE_NAME_OPENED)
2960 FIXME("FILE_NAME_OPENED not supported\n");
2961 flags &= ~FILE_NAME_OPENED;
2964 /* Get information required for VOLUME_NAME_NONE, VOLUME_NAME_GUID and VOLUME_NAME_NT */
2965 if (flags == VOLUME_NAME_NONE || flags == VOLUME_NAME_GUID || flags == VOLUME_NAME_NT)
2967 if (!GetVolumePathNameW( info->Name.Buffer, drive_part, MAX_PATH ))
2968 return 0;
2970 drive_part_len = strlenW(drive_part);
2971 if (!drive_part_len || drive_part_len > strlenW(info->Name.Buffer) ||
2972 drive_part[drive_part_len-1] != '\\' ||
2973 strncmpiW( info->Name.Buffer, drive_part, drive_part_len ))
2975 FIXME("Path %s returned by GetVolumePathNameW does not match file path %s\n",
2976 debugstr_w(drive_part), debugstr_w(info->Name.Buffer));
2977 SetLastError( ERROR_GEN_FAILURE );
2978 return 0;
2982 if (flags == VOLUME_NAME_NONE)
2984 ptr = info->Name.Buffer + drive_part_len - 1;
2985 result = strlenW(ptr);
2986 if (result < charcount)
2987 memcpy(path, ptr, (result + 1) * sizeof(WCHAR));
2988 else result++;
2990 else if (flags == VOLUME_NAME_GUID)
2992 WCHAR volume_prefix[51];
2994 /* GetVolumeNameForVolumeMountPointW sets error code on failure */
2995 if (!GetVolumeNameForVolumeMountPointW( drive_part, volume_prefix, 50 ))
2996 return 0;
2998 ptr = info->Name.Buffer + drive_part_len;
2999 result = strlenW(volume_prefix) + strlenW(ptr);
3000 if (result < charcount)
3002 path[0] = 0;
3003 strcatW(path, volume_prefix);
3004 strcatW(path, ptr);
3006 else
3008 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3009 result++;
3012 else if (flags == VOLUME_NAME_NT)
3014 WCHAR nt_prefix[MAX_PATH];
3016 /* QueryDosDeviceW sets error code on failure */
3017 drive_part[drive_part_len - 1] = 0;
3018 if (!QueryDosDeviceW( drive_part, nt_prefix, MAX_PATH ))
3019 return 0;
3021 ptr = info->Name.Buffer + drive_part_len - 1;
3022 result = strlenW(nt_prefix) + strlenW(ptr);
3023 if (result < charcount)
3025 path[0] = 0;
3026 strcatW(path, nt_prefix);
3027 strcatW(path, ptr);
3029 else
3031 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3032 result++;
3035 else if (flags == VOLUME_NAME_DOS)
3037 static const WCHAR dos_prefix[] = {'\\','\\','?','\\', '\0'};
3039 result = strlenW(dos_prefix) + strlenW(info->Name.Buffer);
3040 if (result < charcount)
3042 path[0] = 0;
3043 strcatW(path, dos_prefix);
3044 strcatW(path, info->Name.Buffer);
3046 else
3048 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3049 result++;
3052 else
3054 /* Windows crashes here, but we prefer returning ERROR_INVALID_PARAMETER */
3055 WARN("Invalid combination of flags: %x\n", flags);
3056 SetLastError( ERROR_INVALID_PARAMETER );
3059 return result;
3062 /***********************************************************************
3063 * GetFinalPathNameByHandleA (KERNEL32.@)
3065 DWORD WINAPI GetFinalPathNameByHandleA(HANDLE file, LPSTR path, DWORD charcount, DWORD flags)
3067 WCHAR *str;
3068 DWORD result, len, cp;
3070 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags);
3072 len = GetFinalPathNameByHandleW(file, NULL, 0, flags);
3073 if (len == 0)
3074 return 0;
3076 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3077 if (!str)
3079 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3080 return 0;
3083 result = GetFinalPathNameByHandleW(file, str, len, flags);
3084 if (result != len - 1)
3086 HeapFree(GetProcessHeap(), 0, str);
3087 WARN("GetFinalPathNameByHandleW failed unexpectedly: %u\n", result);
3088 return 0;
3091 cp = oem_file_apis ? CP_OEMCP : CP_ACP;
3093 len = WideCharToMultiByte(cp, 0, str, -1, NULL, 0, NULL, NULL);
3094 if (!len)
3096 HeapFree(GetProcessHeap(), 0, str);
3097 WARN("Failed to get multibyte length\n");
3098 return 0;
3101 if (charcount < len)
3103 HeapFree(GetProcessHeap(), 0, str);
3104 return len - 1;
3107 len = WideCharToMultiByte(cp, 0, str, -1, path, charcount, NULL, NULL);
3108 if (!len)
3110 HeapFree(GetProcessHeap(), 0, str);
3111 WARN("WideCharToMultiByte failed\n");
3112 return 0;
3115 HeapFree(GetProcessHeap(), 0, str);
3117 return len - 1;