wined3d: Add AMD NT6x drivers.
[wine.git] / dlls / kernel32 / file.c
blobe32d75dab83bd99d6cd0b5fec3968de83ef40612
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 "kernel_private.h"
45 #include "wine/exception.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(file);
51 /* info structure for FindFirstFile handle */
52 typedef struct
54 DWORD magic; /* magic number */
55 HANDLE handle; /* handle to directory */
56 CRITICAL_SECTION cs; /* crit section protecting this structure */
57 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
58 UNICODE_STRING mask; /* file mask */
59 UNICODE_STRING path; /* NT path used to open the directory */
60 BOOL is_root; /* is directory the root of the drive? */
61 UINT data_pos; /* current position in dir data */
62 UINT data_len; /* length of dir data */
63 BYTE data[8192]; /* directory data */
64 } FIND_FIRST_INFO;
66 #define FIND_FIRST_MAGIC 0xc0ffee11
68 static BOOL oem_file_apis;
70 static const WCHAR wildcardsW[] = { '*','?',0 };
72 /***********************************************************************
73 * create_file_OF
75 * Wrapper for CreateFile that takes OF_* mode flags.
77 static HANDLE create_file_OF( LPCSTR path, INT mode )
79 DWORD access, sharing, creation;
81 if (mode & OF_CREATE)
83 creation = CREATE_ALWAYS;
84 access = GENERIC_READ | GENERIC_WRITE;
86 else
88 creation = OPEN_EXISTING;
89 switch(mode & 0x03)
91 case OF_READ: access = GENERIC_READ; break;
92 case OF_WRITE: access = GENERIC_WRITE; break;
93 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
94 default: access = 0; break;
98 switch(mode & 0x70)
100 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
101 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
102 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
103 case OF_SHARE_DENY_NONE:
104 case OF_SHARE_COMPAT:
105 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
107 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
111 /***********************************************************************
112 * check_dir_symlink
114 * Check if a dir symlink should be returned by FindNextFile.
116 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
118 UNICODE_STRING str;
119 ANSI_STRING unix_name;
120 struct stat st, parent_st;
121 BOOL ret = TRUE;
122 DWORD len;
124 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
125 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
126 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
127 len = info->path.Length / sizeof(WCHAR);
128 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
129 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
130 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
132 unix_name.Buffer = NULL;
133 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
134 !stat( unix_name.Buffer, &st ))
136 char *p = unix_name.Buffer + unix_name.Length - 1;
138 /* skip trailing slashes */
139 while (p > unix_name.Buffer && *p == '/') p--;
141 while (ret && p > unix_name.Buffer)
143 while (p > unix_name.Buffer && *p != '/') p--;
144 while (p > unix_name.Buffer && *p == '/') p--;
145 p[1] = 0;
146 if (!stat( unix_name.Buffer, &parent_st ) &&
147 parent_st.st_dev == st.st_dev &&
148 parent_st.st_ino == st.st_ino)
150 WARN( "suppressing dir symlink %s pointing to parent %s\n",
151 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
152 debugstr_a( unix_name.Buffer ));
153 ret = FALSE;
157 RtlFreeAnsiString( &unix_name );
158 RtlFreeUnicodeString( &str );
159 return ret;
163 /***********************************************************************
164 * FILE_SetDosError
166 * Set the DOS error code from errno.
168 void FILE_SetDosError(void)
170 int save_errno = errno; /* errno gets overwritten by printf */
172 TRACE("errno = %d %s\n", errno, strerror(errno));
173 switch (save_errno)
175 case EAGAIN:
176 SetLastError( ERROR_SHARING_VIOLATION );
177 break;
178 case EBADF:
179 SetLastError( ERROR_INVALID_HANDLE );
180 break;
181 case ENOSPC:
182 SetLastError( ERROR_HANDLE_DISK_FULL );
183 break;
184 case EACCES:
185 case EPERM:
186 case EROFS:
187 SetLastError( ERROR_ACCESS_DENIED );
188 break;
189 case EBUSY:
190 SetLastError( ERROR_LOCK_VIOLATION );
191 break;
192 case ENOENT:
193 SetLastError( ERROR_FILE_NOT_FOUND );
194 break;
195 case EISDIR:
196 SetLastError( ERROR_CANNOT_MAKE );
197 break;
198 case ENFILE:
199 case EMFILE:
200 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
201 break;
202 case EEXIST:
203 SetLastError( ERROR_FILE_EXISTS );
204 break;
205 case EINVAL:
206 case ESPIPE:
207 SetLastError( ERROR_SEEK );
208 break;
209 case ENOTEMPTY:
210 SetLastError( ERROR_DIR_NOT_EMPTY );
211 break;
212 case ENOEXEC:
213 SetLastError( ERROR_BAD_FORMAT );
214 break;
215 case ENOTDIR:
216 SetLastError( ERROR_PATH_NOT_FOUND );
217 break;
218 case EXDEV:
219 SetLastError( ERROR_NOT_SAME_DEVICE );
220 break;
221 default:
222 WARN("unknown file error: %s\n", strerror(save_errno) );
223 SetLastError( ERROR_GEN_FAILURE );
224 break;
226 errno = save_errno;
230 /***********************************************************************
231 * FILE_name_AtoW
233 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
235 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
236 * there is no possibility for the function to do that twice, taking into
237 * account any called function.
239 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
241 ANSI_STRING str;
242 UNICODE_STRING strW, *pstrW;
243 NTSTATUS status;
245 RtlInitAnsiString( &str, name );
246 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
247 if (oem_file_apis)
248 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
249 else
250 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
251 if (status == STATUS_SUCCESS) return pstrW->Buffer;
253 if (status == STATUS_BUFFER_OVERFLOW)
254 SetLastError( ERROR_FILENAME_EXCED_RANGE );
255 else
256 SetLastError( RtlNtStatusToDosError(status) );
257 return NULL;
261 /***********************************************************************
262 * FILE_name_WtoA
264 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
266 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
268 DWORD ret;
270 if (srclen < 0) srclen = strlenW( src ) + 1;
271 if (oem_file_apis)
272 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
273 else
274 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
275 return ret;
279 /**************************************************************************
280 * SetFileApisToOEM (KERNEL32.@)
282 VOID WINAPI SetFileApisToOEM(void)
284 oem_file_apis = TRUE;
288 /**************************************************************************
289 * SetFileApisToANSI (KERNEL32.@)
291 VOID WINAPI SetFileApisToANSI(void)
293 oem_file_apis = FALSE;
297 /******************************************************************************
298 * AreFileApisANSI (KERNEL32.@)
300 * Determines if file functions are using ANSI
302 * RETURNS
303 * TRUE: Set of file functions is using ANSI code page
304 * FALSE: Set of file functions is using OEM code page
306 BOOL WINAPI AreFileApisANSI(void)
308 return !oem_file_apis;
312 /**************************************************************************
313 * Operations on file handles *
314 **************************************************************************/
316 /******************************************************************
317 * FILE_ReadWriteApc (internal)
319 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
321 LPOVERLAPPED_COMPLETION_ROUTINE cr = apc_user;
323 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
327 /***********************************************************************
328 * ReadFileEx (KERNEL32.@)
330 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
331 LPOVERLAPPED overlapped,
332 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
334 LARGE_INTEGER offset;
335 NTSTATUS status;
336 PIO_STATUS_BLOCK io_status;
338 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
340 if (!overlapped)
342 SetLastError(ERROR_INVALID_PARAMETER);
343 return FALSE;
346 offset.u.LowPart = overlapped->u.s.Offset;
347 offset.u.HighPart = overlapped->u.s.OffsetHigh;
348 io_status = (PIO_STATUS_BLOCK)overlapped;
349 io_status->u.Status = STATUS_PENDING;
350 io_status->Information = 0;
352 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
353 io_status, buffer, bytesToRead, &offset, NULL);
355 if (status)
357 SetLastError( RtlNtStatusToDosError(status) );
358 return FALSE;
360 return TRUE;
364 /***********************************************************************
365 * ReadFileScatter (KERNEL32.@)
367 BOOL WINAPI ReadFileScatter( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
368 LPDWORD reserved, LPOVERLAPPED overlapped )
370 PIO_STATUS_BLOCK io_status;
371 LARGE_INTEGER offset;
372 NTSTATUS status;
374 TRACE( "(%p %p %u %p)\n", file, segments, count, overlapped );
376 offset.u.LowPart = overlapped->u.s.Offset;
377 offset.u.HighPart = overlapped->u.s.OffsetHigh;
378 io_status = (PIO_STATUS_BLOCK)overlapped;
379 io_status->u.Status = STATUS_PENDING;
380 io_status->Information = 0;
382 status = NtReadFileScatter( file, NULL, NULL, NULL, io_status, segments, count, &offset, NULL );
383 if (status) SetLastError( RtlNtStatusToDosError(status) );
384 return !status;
388 /***********************************************************************
389 * ReadFile (KERNEL32.@)
391 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
392 LPDWORD bytesRead, LPOVERLAPPED overlapped )
394 LARGE_INTEGER offset;
395 PLARGE_INTEGER poffset = NULL;
396 IO_STATUS_BLOCK iosb;
397 PIO_STATUS_BLOCK io_status = &iosb;
398 HANDLE hEvent = 0;
399 NTSTATUS status;
400 LPVOID cvalue = NULL;
402 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
403 bytesRead, overlapped );
405 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
406 if (!bytesToRead) return TRUE;
408 if (is_console_handle(hFile))
409 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
411 if (overlapped != NULL)
413 offset.u.LowPart = overlapped->u.s.Offset;
414 offset.u.HighPart = overlapped->u.s.OffsetHigh;
415 poffset = &offset;
416 hEvent = overlapped->hEvent;
417 io_status = (PIO_STATUS_BLOCK)overlapped;
418 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
420 io_status->u.Status = STATUS_PENDING;
421 io_status->Information = 0;
423 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
425 if (status == STATUS_PENDING && !overlapped)
427 WaitForSingleObject( hFile, INFINITE );
428 status = io_status->u.Status;
431 if (status != STATUS_PENDING && bytesRead)
432 *bytesRead = io_status->Information;
434 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
436 SetLastError( RtlNtStatusToDosError(status) );
437 return FALSE;
439 return TRUE;
443 /***********************************************************************
444 * WriteFileEx (KERNEL32.@)
446 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
447 LPOVERLAPPED overlapped,
448 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
450 LARGE_INTEGER offset;
451 NTSTATUS status;
452 PIO_STATUS_BLOCK io_status;
454 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
456 if (overlapped == NULL)
458 SetLastError(ERROR_INVALID_PARAMETER);
459 return FALSE;
461 offset.u.LowPart = overlapped->u.s.Offset;
462 offset.u.HighPart = overlapped->u.s.OffsetHigh;
464 io_status = (PIO_STATUS_BLOCK)overlapped;
465 io_status->u.Status = STATUS_PENDING;
466 io_status->Information = 0;
468 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
469 io_status, buffer, bytesToWrite, &offset, NULL);
471 if (status) SetLastError( RtlNtStatusToDosError(status) );
472 return !status;
476 /***********************************************************************
477 * WriteFileGather (KERNEL32.@)
479 BOOL WINAPI WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
480 LPDWORD reserved, LPOVERLAPPED overlapped )
482 PIO_STATUS_BLOCK io_status;
483 LARGE_INTEGER offset;
484 NTSTATUS status;
486 TRACE( "%p %p %u %p\n", file, segments, count, overlapped );
488 offset.u.LowPart = overlapped->u.s.Offset;
489 offset.u.HighPart = overlapped->u.s.OffsetHigh;
490 io_status = (PIO_STATUS_BLOCK)overlapped;
491 io_status->u.Status = STATUS_PENDING;
492 io_status->Information = 0;
494 status = NtWriteFileGather( file, NULL, NULL, NULL, io_status, segments, count, &offset, NULL );
495 if (status) SetLastError( RtlNtStatusToDosError(status) );
496 return !status;
500 /***********************************************************************
501 * WriteFile (KERNEL32.@)
503 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
504 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
506 HANDLE hEvent = NULL;
507 LARGE_INTEGER offset;
508 PLARGE_INTEGER poffset = NULL;
509 NTSTATUS status;
510 IO_STATUS_BLOCK iosb;
511 PIO_STATUS_BLOCK piosb = &iosb;
512 LPVOID cvalue = NULL;
514 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
516 if (is_console_handle(hFile))
517 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
519 if (overlapped)
521 offset.u.LowPart = overlapped->u.s.Offset;
522 offset.u.HighPart = overlapped->u.s.OffsetHigh;
523 poffset = &offset;
524 hEvent = overlapped->hEvent;
525 piosb = (PIO_STATUS_BLOCK)overlapped;
526 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
528 piosb->u.Status = STATUS_PENDING;
529 piosb->Information = 0;
531 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
532 buffer, bytesToWrite, poffset, NULL);
534 if (status == STATUS_PENDING && !overlapped)
536 WaitForSingleObject( hFile, INFINITE );
537 status = piosb->u.Status;
540 if (status != STATUS_PENDING && bytesWritten)
541 *bytesWritten = piosb->Information;
543 if (status && status != STATUS_TIMEOUT)
545 SetLastError( RtlNtStatusToDosError(status) );
546 return FALSE;
548 return TRUE;
552 /***********************************************************************
553 * GetOverlappedResult (KERNEL32.@)
555 * Check the result of an Asynchronous data transfer from a file.
557 * Parameters
558 * HANDLE hFile [in] handle of file to check on
559 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
560 * LPDWORD lpTransferred [in/out] number of bytes transferred
561 * BOOL bWait [in] wait for the transfer to complete ?
563 * RETURNS
564 * TRUE on success
565 * FALSE on failure
567 * If successful (and relevant) lpTransferred will hold the number of
568 * bytes transferred during the async operation.
570 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
571 LPDWORD lpTransferred, BOOL bWait)
573 NTSTATUS status;
575 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
577 status = lpOverlapped->Internal;
578 if (status == STATUS_PENDING)
580 if (!bWait)
582 SetLastError( ERROR_IO_INCOMPLETE );
583 return FALSE;
586 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
587 INFINITE ) == WAIT_FAILED)
588 return FALSE;
589 status = lpOverlapped->Internal;
592 *lpTransferred = lpOverlapped->InternalHigh;
594 if (status) SetLastError( RtlNtStatusToDosError(status) );
595 return !status;
598 /***********************************************************************
599 * CancelIoEx (KERNEL32.@)
601 * Cancels pending I/O operations on a file given the overlapped used.
603 * PARAMS
604 * handle [I] File handle.
605 * lpOverlapped [I,OPT] pointer to overlapped (if null, cancel all)
607 * RETURNS
608 * Success: TRUE.
609 * Failure: FALSE, check GetLastError().
611 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
613 IO_STATUS_BLOCK io_status;
615 NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
616 if (io_status.u.Status)
618 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
619 return FALSE;
621 return TRUE;
624 /***********************************************************************
625 * CancelIo (KERNEL32.@)
627 * Cancels pending I/O operations initiated by the current thread on a file.
629 * PARAMS
630 * handle [I] File handle.
632 * RETURNS
633 * Success: TRUE.
634 * Failure: FALSE, check GetLastError().
636 BOOL WINAPI CancelIo(HANDLE handle)
638 IO_STATUS_BLOCK io_status;
640 NtCancelIoFile(handle, &io_status);
641 if (io_status.u.Status)
643 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
644 return FALSE;
646 return TRUE;
649 /***********************************************************************
650 * _hread (KERNEL32.@)
652 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
654 return _lread( hFile, buffer, count );
658 /***********************************************************************
659 * _hwrite (KERNEL32.@)
661 * experimentation yields that _lwrite:
662 * o truncates the file at the current position with
663 * a 0 len write
664 * o returns 0 on a 0 length write
665 * o works with console handles
668 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
670 DWORD result;
672 TRACE("%d %p %d\n", handle, buffer, count );
674 if (!count)
676 /* Expand or truncate at current position */
677 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
678 return 0;
680 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
681 return HFILE_ERROR;
682 return result;
686 /***********************************************************************
687 * _lclose (KERNEL32.@)
689 HFILE WINAPI _lclose( HFILE hFile )
691 TRACE("handle %d\n", hFile );
692 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
696 /***********************************************************************
697 * _lcreat (KERNEL32.@)
699 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
701 HANDLE hfile;
703 /* Mask off all flags not explicitly allowed by the doc */
704 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
705 TRACE("%s %02x\n", path, attr );
706 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
707 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
708 CREATE_ALWAYS, attr, 0 );
709 return HandleToLong(hfile);
713 /***********************************************************************
714 * _lopen (KERNEL32.@)
716 HFILE WINAPI _lopen( LPCSTR path, INT mode )
718 HANDLE hfile;
720 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
721 hfile = create_file_OF( path, mode & ~OF_CREATE );
722 return HandleToLong(hfile);
725 /***********************************************************************
726 * _lread (KERNEL32.@)
728 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
730 DWORD result;
731 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
732 return HFILE_ERROR;
733 return result;
737 /***********************************************************************
738 * _llseek (KERNEL32.@)
740 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
742 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
746 /***********************************************************************
747 * _lwrite (KERNEL32.@)
749 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
751 return (UINT)_hwrite( hFile, buffer, (LONG)count );
755 /***********************************************************************
756 * FlushFileBuffers (KERNEL32.@)
758 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
760 NTSTATUS nts;
761 IO_STATUS_BLOCK ioblk;
763 if (is_console_handle( hFile ))
765 /* this will fail (as expected) for an output handle */
766 return FlushConsoleInputBuffer( hFile );
768 nts = NtFlushBuffersFile( hFile, &ioblk );
769 if (nts != STATUS_SUCCESS)
771 SetLastError( RtlNtStatusToDosError( nts ) );
772 return FALSE;
775 return TRUE;
779 /***********************************************************************
780 * GetFileType (KERNEL32.@)
782 DWORD WINAPI GetFileType( HANDLE hFile )
784 FILE_FS_DEVICE_INFORMATION info;
785 IO_STATUS_BLOCK io;
786 NTSTATUS status;
788 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
790 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
791 if (status != STATUS_SUCCESS)
793 SetLastError( RtlNtStatusToDosError(status) );
794 return FILE_TYPE_UNKNOWN;
797 switch(info.DeviceType)
799 case FILE_DEVICE_NULL:
800 case FILE_DEVICE_SERIAL_PORT:
801 case FILE_DEVICE_PARALLEL_PORT:
802 case FILE_DEVICE_TAPE:
803 case FILE_DEVICE_UNKNOWN:
804 return FILE_TYPE_CHAR;
805 case FILE_DEVICE_NAMED_PIPE:
806 return FILE_TYPE_PIPE;
807 default:
808 return FILE_TYPE_DISK;
813 /***********************************************************************
814 * GetFileInformationByHandle (KERNEL32.@)
816 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
818 FILE_ALL_INFORMATION all_info;
819 IO_STATUS_BLOCK io;
820 NTSTATUS status;
822 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
823 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
824 if (status == STATUS_SUCCESS)
826 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
827 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
828 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
829 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
830 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
831 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
832 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
833 info->dwVolumeSerialNumber = 0; /* FIXME */
834 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
835 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
836 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
837 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
838 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
839 return TRUE;
841 SetLastError( RtlNtStatusToDosError(status) );
842 return FALSE;
846 /***********************************************************************
847 * GetFileSize (KERNEL32.@)
849 * Retrieve the size of a file.
851 * PARAMS
852 * hFile [I] File to retrieve size of.
853 * filesizehigh [O] On return, the high bits of the file size.
855 * RETURNS
856 * Success: The low bits of the file size.
857 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
858 * check GetLastError() for values other than ERROR_SUCCESS.
860 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
862 LARGE_INTEGER size;
863 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
864 if (filesizehigh) *filesizehigh = size.u.HighPart;
865 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
866 return size.u.LowPart;
870 /***********************************************************************
871 * GetFileSizeEx (KERNEL32.@)
873 * Retrieve the size of a file.
875 * PARAMS
876 * hFile [I] File to retrieve size of.
877 * lpFileSIze [O] On return, the size of the file.
879 * RETURNS
880 * Success: TRUE.
881 * Failure: FALSE, check GetLastError().
883 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
885 FILE_STANDARD_INFORMATION info;
886 IO_STATUS_BLOCK io;
887 NTSTATUS status;
889 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
890 if (status == STATUS_SUCCESS)
892 *lpFileSize = info.EndOfFile;
893 return TRUE;
895 SetLastError( RtlNtStatusToDosError(status) );
896 return FALSE;
900 /**************************************************************************
901 * SetEndOfFile (KERNEL32.@)
903 * Sets the current position as the end of the file.
905 * PARAMS
906 * hFile [I] File handle.
908 * RETURNS
909 * Success: TRUE.
910 * Failure: FALSE, check GetLastError().
912 BOOL WINAPI SetEndOfFile( HANDLE hFile )
914 FILE_POSITION_INFORMATION pos;
915 FILE_END_OF_FILE_INFORMATION eof;
916 IO_STATUS_BLOCK io;
917 NTSTATUS status;
919 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
920 if (status == STATUS_SUCCESS)
922 eof.EndOfFile = pos.CurrentByteOffset;
923 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
925 if (status == STATUS_SUCCESS) return TRUE;
926 SetLastError( RtlNtStatusToDosError(status) );
927 return FALSE;
931 /***********************************************************************
932 * SetFilePointer (KERNEL32.@)
934 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
936 LARGE_INTEGER dist, newpos;
938 if (highword)
940 dist.u.LowPart = distance;
941 dist.u.HighPart = *highword;
943 else dist.QuadPart = distance;
945 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
947 if (highword) *highword = newpos.u.HighPart;
948 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
949 return newpos.u.LowPart;
953 /***********************************************************************
954 * SetFilePointerEx (KERNEL32.@)
956 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
957 LARGE_INTEGER *newpos, DWORD method )
959 LONGLONG pos;
960 IO_STATUS_BLOCK io;
961 FILE_POSITION_INFORMATION info;
963 switch(method)
965 case FILE_BEGIN:
966 pos = distance.QuadPart;
967 break;
968 case FILE_CURRENT:
969 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
970 goto error;
971 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
972 break;
973 case FILE_END:
975 FILE_END_OF_FILE_INFORMATION eof;
976 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
977 goto error;
978 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
980 break;
981 default:
982 SetLastError( ERROR_INVALID_PARAMETER );
983 return FALSE;
986 if (pos < 0)
988 SetLastError( ERROR_NEGATIVE_SEEK );
989 return FALSE;
992 info.CurrentByteOffset.QuadPart = pos;
993 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
994 goto error;
995 if (newpos) newpos->QuadPart = pos;
996 return TRUE;
998 error:
999 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1000 return FALSE;
1003 /***********************************************************************
1004 * SetFileValidData (KERNEL32.@)
1006 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1008 FIXME("stub: %p, %s\n", hFile, wine_dbgstr_longlong(ValidDataLength));
1009 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1010 return FALSE;
1013 /***********************************************************************
1014 * GetFileTime (KERNEL32.@)
1016 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1017 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1019 FILE_BASIC_INFORMATION info;
1020 IO_STATUS_BLOCK io;
1021 NTSTATUS status;
1023 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1024 if (status == STATUS_SUCCESS)
1026 if (lpCreationTime)
1028 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1029 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1031 if (lpLastAccessTime)
1033 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1034 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1036 if (lpLastWriteTime)
1038 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1039 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1041 return TRUE;
1043 SetLastError( RtlNtStatusToDosError(status) );
1044 return FALSE;
1048 /***********************************************************************
1049 * SetFileTime (KERNEL32.@)
1051 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1052 const FILETIME *atime, const FILETIME *mtime )
1054 FILE_BASIC_INFORMATION info;
1055 IO_STATUS_BLOCK io;
1056 NTSTATUS status;
1058 memset( &info, 0, sizeof(info) );
1059 if (ctime)
1061 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1062 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1064 if (atime)
1066 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1067 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1069 if (mtime)
1071 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1072 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1075 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1076 if (status == STATUS_SUCCESS) return TRUE;
1077 SetLastError( RtlNtStatusToDosError(status) );
1078 return FALSE;
1082 /**************************************************************************
1083 * LockFile (KERNEL32.@)
1085 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1086 DWORD count_low, DWORD count_high )
1088 NTSTATUS status;
1089 LARGE_INTEGER count, offset;
1091 TRACE( "%p %x%08x %x%08x\n",
1092 hFile, offset_high, offset_low, count_high, count_low );
1094 count.u.LowPart = count_low;
1095 count.u.HighPart = count_high;
1096 offset.u.LowPart = offset_low;
1097 offset.u.HighPart = offset_high;
1099 status = NtLockFile( hFile, 0, NULL, NULL,
1100 NULL, &offset, &count, NULL, TRUE, TRUE );
1102 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1103 return !status;
1107 /**************************************************************************
1108 * LockFileEx [KERNEL32.@]
1110 * Locks a byte range within an open file for shared or exclusive access.
1112 * RETURNS
1113 * success: TRUE
1114 * failure: FALSE
1116 * NOTES
1117 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1119 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1120 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1122 NTSTATUS status;
1123 LARGE_INTEGER count, offset;
1124 LPVOID cvalue = NULL;
1126 if (reserved)
1128 SetLastError( ERROR_INVALID_PARAMETER );
1129 return FALSE;
1132 TRACE( "%p %x%08x %x%08x flags %x\n",
1133 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1134 count_high, count_low, flags );
1136 count.u.LowPart = count_low;
1137 count.u.HighPart = count_high;
1138 offset.u.LowPart = overlapped->u.s.Offset;
1139 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1141 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1143 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1144 NULL, &offset, &count, NULL,
1145 flags & LOCKFILE_FAIL_IMMEDIATELY,
1146 flags & LOCKFILE_EXCLUSIVE_LOCK );
1148 if (status) SetLastError( RtlNtStatusToDosError(status) );
1149 return !status;
1153 /**************************************************************************
1154 * UnlockFile (KERNEL32.@)
1156 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1157 DWORD count_low, DWORD count_high )
1159 NTSTATUS status;
1160 LARGE_INTEGER count, offset;
1162 count.u.LowPart = count_low;
1163 count.u.HighPart = count_high;
1164 offset.u.LowPart = offset_low;
1165 offset.u.HighPart = offset_high;
1167 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1168 if (status) SetLastError( RtlNtStatusToDosError(status) );
1169 return !status;
1173 /**************************************************************************
1174 * UnlockFileEx (KERNEL32.@)
1176 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1177 LPOVERLAPPED overlapped )
1179 if (reserved)
1181 SetLastError( ERROR_INVALID_PARAMETER );
1182 return FALSE;
1184 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1186 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1190 /*************************************************************************
1191 * SetHandleCount (KERNEL32.@)
1193 UINT WINAPI SetHandleCount( UINT count )
1195 return count;
1199 /**************************************************************************
1200 * Operations on file names *
1201 **************************************************************************/
1204 /*************************************************************************
1205 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1207 * Creates or opens an object, and returns a handle that can be used to
1208 * access that object.
1210 * PARAMS
1212 * filename [in] pointer to filename to be accessed
1213 * access [in] access mode requested
1214 * sharing [in] share mode
1215 * sa [in] pointer to security attributes
1216 * creation [in] how to create the file
1217 * attributes [in] attributes for newly created file
1218 * template [in] handle to file with extended attributes to copy
1220 * RETURNS
1221 * Success: Open handle to specified file
1222 * Failure: INVALID_HANDLE_VALUE
1224 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1225 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1226 DWORD attributes, HANDLE template )
1228 NTSTATUS status;
1229 UINT options;
1230 OBJECT_ATTRIBUTES attr;
1231 UNICODE_STRING nameW;
1232 IO_STATUS_BLOCK io;
1233 HANDLE ret;
1234 DWORD dosdev;
1235 const WCHAR *vxd_name = NULL;
1236 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1237 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1238 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1239 SECURITY_QUALITY_OF_SERVICE qos;
1241 static const UINT nt_disposition[5] =
1243 FILE_CREATE, /* CREATE_NEW */
1244 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1245 FILE_OPEN, /* OPEN_EXISTING */
1246 FILE_OPEN_IF, /* OPEN_ALWAYS */
1247 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1251 /* sanity checks */
1253 if (!filename || !filename[0])
1255 SetLastError( ERROR_PATH_NOT_FOUND );
1256 return INVALID_HANDLE_VALUE;
1259 TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1260 (access & GENERIC_READ)?"GENERIC_READ ":"",
1261 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1262 (!access)?"QUERY_ACCESS ":"",
1263 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1264 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1265 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1266 creation, attributes);
1268 /* Open a console for CONIN$ or CONOUT$ */
1270 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1272 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1273 goto done;
1276 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1278 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1279 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1281 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1282 !strncmpiW( filename + 4, pipeW, 5 ) ||
1283 !strncmpiW( filename + 4, mailslotW, 9 ))
1285 dosdev = 0;
1287 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1289 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1291 else if (GetVersion() & 0x80000000)
1293 vxd_name = filename + 4;
1296 else dosdev = RtlIsDosDeviceName_U( filename );
1298 if (dosdev)
1300 static const WCHAR conW[] = {'C','O','N'};
1302 if (LOWORD(dosdev) == sizeof(conW) &&
1303 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1305 switch (access & (GENERIC_READ|GENERIC_WRITE))
1307 case GENERIC_READ:
1308 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1309 goto done;
1310 case GENERIC_WRITE:
1311 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1312 goto done;
1313 default:
1314 SetLastError( ERROR_FILE_NOT_FOUND );
1315 return INVALID_HANDLE_VALUE;
1320 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1322 SetLastError( ERROR_INVALID_PARAMETER );
1323 return INVALID_HANDLE_VALUE;
1326 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1328 SetLastError( ERROR_PATH_NOT_FOUND );
1329 return INVALID_HANDLE_VALUE;
1332 /* now call NtCreateFile */
1334 options = 0;
1335 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1336 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1337 else
1338 options |= FILE_NON_DIRECTORY_FILE;
1339 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1341 options |= FILE_DELETE_ON_CLOSE;
1342 access |= DELETE;
1344 if (attributes & FILE_FLAG_NO_BUFFERING)
1345 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1346 if (!(attributes & FILE_FLAG_OVERLAPPED))
1347 options |= FILE_SYNCHRONOUS_IO_ALERT;
1348 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1349 options |= FILE_RANDOM_ACCESS;
1350 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1352 attr.Length = sizeof(attr);
1353 attr.RootDirectory = 0;
1354 attr.Attributes = OBJ_CASE_INSENSITIVE;
1355 attr.ObjectName = &nameW;
1356 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1357 if (attributes & SECURITY_SQOS_PRESENT)
1359 qos.Length = sizeof(qos);
1360 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1361 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1362 qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1363 attr.SecurityQualityOfService = &qos;
1365 else
1366 attr.SecurityQualityOfService = NULL;
1368 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1370 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1371 sharing, nt_disposition[creation - CREATE_NEW],
1372 options, NULL, 0 );
1373 if (status)
1375 if (vxd_name && vxd_name[0])
1377 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1378 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1379 "__wine_vxd_open" );
1380 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1383 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1384 ret = INVALID_HANDLE_VALUE;
1386 /* In the case file creation was rejected due to CREATE_NEW flag
1387 * was specified and file with that name already exists, correct
1388 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1389 * Note: RtlNtStatusToDosError is not the subject to blame here.
1391 if (status == STATUS_OBJECT_NAME_COLLISION)
1392 SetLastError( ERROR_FILE_EXISTS );
1393 else
1394 SetLastError( RtlNtStatusToDosError(status) );
1396 else
1398 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1399 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1400 SetLastError( ERROR_ALREADY_EXISTS );
1401 else
1402 SetLastError( 0 );
1404 RtlFreeUnicodeString( &nameW );
1406 done:
1407 if (!ret) ret = INVALID_HANDLE_VALUE;
1408 TRACE("returning %p\n", ret);
1409 return ret;
1414 /*************************************************************************
1415 * CreateFileA (KERNEL32.@)
1417 * See CreateFileW.
1419 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1420 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1421 DWORD attributes, HANDLE template)
1423 WCHAR *nameW;
1425 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1426 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1430 /***********************************************************************
1431 * DeleteFileW (KERNEL32.@)
1433 * Delete a file.
1435 * PARAMS
1436 * path [I] Path to the file to delete.
1438 * RETURNS
1439 * Success: TRUE.
1440 * Failure: FALSE, check GetLastError().
1442 BOOL WINAPI DeleteFileW( LPCWSTR path )
1444 UNICODE_STRING nameW;
1445 OBJECT_ATTRIBUTES attr;
1446 NTSTATUS status;
1447 HANDLE hFile;
1448 IO_STATUS_BLOCK io;
1450 TRACE("%s\n", debugstr_w(path) );
1452 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1454 SetLastError( ERROR_PATH_NOT_FOUND );
1455 return FALSE;
1458 attr.Length = sizeof(attr);
1459 attr.RootDirectory = 0;
1460 attr.Attributes = OBJ_CASE_INSENSITIVE;
1461 attr.ObjectName = &nameW;
1462 attr.SecurityDescriptor = NULL;
1463 attr.SecurityQualityOfService = NULL;
1465 status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1466 &attr, &io, NULL, 0,
1467 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1468 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1469 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1471 RtlFreeUnicodeString( &nameW );
1472 if (status)
1474 SetLastError( RtlNtStatusToDosError(status) );
1475 return FALSE;
1477 return TRUE;
1481 /***********************************************************************
1482 * DeleteFileA (KERNEL32.@)
1484 * See DeleteFileW.
1486 BOOL WINAPI DeleteFileA( LPCSTR path )
1488 WCHAR *pathW;
1490 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1491 return DeleteFileW( pathW );
1495 /**************************************************************************
1496 * ReplaceFileW (KERNEL32.@)
1497 * ReplaceFile (KERNEL32.@)
1499 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1500 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1501 LPVOID lpExclude, LPVOID lpReserved)
1503 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1504 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1505 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1506 DWORD error = ERROR_SUCCESS;
1507 UINT replaced_flags;
1508 BOOL ret = FALSE;
1509 NTSTATUS status;
1510 IO_STATUS_BLOCK io;
1511 OBJECT_ATTRIBUTES attr;
1513 if (dwReplaceFlags)
1514 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1516 /* First two arguments are mandatory */
1517 if (!lpReplacedFileName || !lpReplacementFileName)
1519 SetLastError(ERROR_INVALID_PARAMETER);
1520 return FALSE;
1523 unix_replaced_name.Buffer = NULL;
1524 unix_replacement_name.Buffer = NULL;
1525 unix_backup_name.Buffer = NULL;
1527 attr.Length = sizeof(attr);
1528 attr.RootDirectory = 0;
1529 attr.Attributes = OBJ_CASE_INSENSITIVE;
1530 attr.ObjectName = NULL;
1531 attr.SecurityDescriptor = NULL;
1532 attr.SecurityQualityOfService = NULL;
1534 /* Open the "replaced" file for reading and writing */
1535 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1537 error = ERROR_PATH_NOT_FOUND;
1538 goto fail;
1540 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1541 attr.ObjectName = &nt_replaced_name;
1542 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1543 &attr, &io,
1544 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1545 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1546 if (status == STATUS_SUCCESS)
1547 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1548 RtlFreeUnicodeString(&nt_replaced_name);
1549 if (status != STATUS_SUCCESS)
1551 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1552 error = ERROR_FILE_NOT_FOUND;
1553 else
1554 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1555 goto fail;
1559 * Open the replacement file for reading, writing, and deleting
1560 * (writing and deleting are needed when finished)
1562 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1564 error = ERROR_PATH_NOT_FOUND;
1565 goto fail;
1567 attr.ObjectName = &nt_replacement_name;
1568 status = NtOpenFile(&hReplacement,
1569 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1570 &attr, &io, 0,
1571 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1572 if (status == STATUS_SUCCESS)
1573 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1574 RtlFreeUnicodeString(&nt_replacement_name);
1575 if (status != STATUS_SUCCESS)
1577 error = RtlNtStatusToDosError(status);
1578 goto fail;
1581 /* If the user wants a backup then that needs to be performed first */
1582 if (lpBackupFileName)
1584 UNICODE_STRING nt_backup_name;
1585 FILE_BASIC_INFORMATION replaced_info;
1587 /* Obtain the file attributes from the "replaced" file */
1588 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1589 sizeof(replaced_info),
1590 FileBasicInformation);
1591 if (status != STATUS_SUCCESS)
1593 error = RtlNtStatusToDosError(status);
1594 goto fail;
1597 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1599 error = ERROR_PATH_NOT_FOUND;
1600 goto fail;
1602 attr.ObjectName = &nt_backup_name;
1603 /* Open the backup with permissions to write over it */
1604 status = NtCreateFile(&hBackup, GENERIC_WRITE,
1605 &attr, &io, NULL, replaced_info.FileAttributes,
1606 FILE_SHARE_WRITE, FILE_OPEN_IF,
1607 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1608 NULL, 0);
1609 if (status == STATUS_SUCCESS)
1610 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1611 RtlFreeUnicodeString(&nt_backup_name);
1612 if (status != STATUS_SUCCESS)
1614 error = RtlNtStatusToDosError(status);
1615 goto fail;
1618 /* If an existing backup exists then copy over it */
1619 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1621 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1622 goto fail;
1627 * Now that the backup has been performed (if requested), copy the replacement
1628 * into place
1630 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1632 if (errno == EACCES)
1634 /* Inappropriate permissions on "replaced", rename will fail */
1635 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1636 goto fail;
1638 /* on failure we need to indicate whether a backup was made */
1639 if (!lpBackupFileName)
1640 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1641 else
1642 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1643 goto fail;
1645 /* Success! */
1646 ret = TRUE;
1648 /* Perform resource cleanup */
1649 fail:
1650 if (hBackup) CloseHandle(hBackup);
1651 if (hReplaced) CloseHandle(hReplaced);
1652 if (hReplacement) CloseHandle(hReplacement);
1653 RtlFreeAnsiString(&unix_backup_name);
1654 RtlFreeAnsiString(&unix_replacement_name);
1655 RtlFreeAnsiString(&unix_replaced_name);
1657 /* If there was an error, set the error code */
1658 if(!ret)
1659 SetLastError(error);
1660 return ret;
1664 /**************************************************************************
1665 * ReplaceFileA (KERNEL32.@)
1667 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1668 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1669 LPVOID lpExclude, LPVOID lpReserved)
1671 WCHAR *replacedW, *replacementW, *backupW = NULL;
1672 BOOL ret;
1674 /* This function only makes sense when the first two parameters are defined */
1675 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1677 SetLastError(ERROR_INVALID_PARAMETER);
1678 return FALSE;
1680 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1682 HeapFree( GetProcessHeap(), 0, replacedW );
1683 SetLastError(ERROR_INVALID_PARAMETER);
1684 return FALSE;
1686 /* The backup parameter, however, is optional */
1687 if (lpBackupFileName)
1689 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1691 HeapFree( GetProcessHeap(), 0, replacedW );
1692 HeapFree( GetProcessHeap(), 0, replacementW );
1693 SetLastError(ERROR_INVALID_PARAMETER);
1694 return FALSE;
1697 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1698 HeapFree( GetProcessHeap(), 0, replacedW );
1699 HeapFree( GetProcessHeap(), 0, replacementW );
1700 HeapFree( GetProcessHeap(), 0, backupW );
1701 return ret;
1705 /*************************************************************************
1706 * FindFirstFileExW (KERNEL32.@)
1708 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1709 * results as FindExSearchNameMatch
1711 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1712 LPVOID data, FINDEX_SEARCH_OPS search_op,
1713 LPVOID filter, DWORD flags)
1715 WCHAR *mask, *p;
1716 FIND_FIRST_INFO *info = NULL;
1717 UNICODE_STRING nt_name;
1718 OBJECT_ATTRIBUTES attr;
1719 IO_STATUS_BLOCK io;
1720 NTSTATUS status;
1721 DWORD device = 0;
1723 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1725 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1726 || flags != 0)
1728 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1729 return INVALID_HANDLE_VALUE;
1731 if (level != FindExInfoStandard)
1733 FIXME("info level %d not implemented\n", level );
1734 return INVALID_HANDLE_VALUE;
1737 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1739 SetLastError( ERROR_PATH_NOT_FOUND );
1740 return INVALID_HANDLE_VALUE;
1743 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1745 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1746 goto error;
1749 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1751 static const WCHAR dotW[] = {'.',0};
1752 WCHAR *dir = NULL;
1754 /* we still need to check that the directory can be opened */
1756 if (HIWORD(device))
1758 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1760 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1761 goto error;
1763 memcpy( dir, filename, HIWORD(device) );
1764 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1766 RtlFreeUnicodeString( &nt_name );
1767 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1769 HeapFree( GetProcessHeap(), 0, dir );
1770 SetLastError( ERROR_PATH_NOT_FOUND );
1771 goto error;
1773 HeapFree( GetProcessHeap(), 0, dir );
1774 RtlInitUnicodeString( &info->mask, NULL );
1776 else if (!mask || !*mask)
1778 SetLastError( ERROR_FILE_NOT_FOUND );
1779 goto error;
1781 else
1783 if (!RtlCreateUnicodeString( &info->mask, mask ))
1785 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1786 goto error;
1789 /* truncate dir name before mask */
1790 *mask = 0;
1791 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1794 /* check if path is the root of the drive */
1795 info->is_root = FALSE;
1796 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1797 if (p[0] && p[1] == ':')
1799 p += 2;
1800 while (*p == '\\') p++;
1801 info->is_root = (*p == 0);
1804 attr.Length = sizeof(attr);
1805 attr.RootDirectory = 0;
1806 attr.Attributes = OBJ_CASE_INSENSITIVE;
1807 attr.ObjectName = &nt_name;
1808 attr.SecurityDescriptor = NULL;
1809 attr.SecurityQualityOfService = NULL;
1811 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1812 FILE_SHARE_READ | FILE_SHARE_WRITE,
1813 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1815 if (status != STATUS_SUCCESS)
1817 RtlFreeUnicodeString( &info->mask );
1818 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1819 SetLastError( ERROR_PATH_NOT_FOUND );
1820 else
1821 SetLastError( RtlNtStatusToDosError(status) );
1822 goto error;
1825 RtlInitializeCriticalSection( &info->cs );
1826 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1827 info->path = nt_name;
1828 info->magic = FIND_FIRST_MAGIC;
1829 info->data_pos = 0;
1830 info->data_len = 0;
1831 info->search_op = search_op;
1833 if (device)
1835 WIN32_FIND_DATAW *wfd = data;
1837 memset( wfd, 0, sizeof(*wfd) );
1838 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1839 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1840 CloseHandle( info->handle );
1841 info->handle = 0;
1843 else
1845 IO_STATUS_BLOCK io;
1847 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1848 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1849 if (io.u.Status)
1851 FindClose( info );
1852 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1853 return INVALID_HANDLE_VALUE;
1855 info->data_len = io.Information;
1856 if (!FindNextFileW( info, data ))
1858 TRACE( "%s not found\n", debugstr_w(filename) );
1859 FindClose( info );
1860 SetLastError( ERROR_FILE_NOT_FOUND );
1861 return INVALID_HANDLE_VALUE;
1863 if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1865 /* we can't find two files with the same name */
1866 CloseHandle( info->handle );
1867 info->handle = 0;
1870 return info;
1872 error:
1873 HeapFree( GetProcessHeap(), 0, info );
1874 RtlFreeUnicodeString( &nt_name );
1875 return INVALID_HANDLE_VALUE;
1879 /*************************************************************************
1880 * FindNextFileW (KERNEL32.@)
1882 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1884 FIND_FIRST_INFO *info;
1885 FILE_BOTH_DIR_INFORMATION *dir_info;
1886 BOOL ret = FALSE;
1888 TRACE("%p %p\n", handle, data);
1890 if (!handle || handle == INVALID_HANDLE_VALUE)
1892 SetLastError( ERROR_INVALID_HANDLE );
1893 return ret;
1895 info = handle;
1896 if (info->magic != FIND_FIRST_MAGIC)
1898 SetLastError( ERROR_INVALID_HANDLE );
1899 return ret;
1902 RtlEnterCriticalSection( &info->cs );
1904 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1905 else for (;;)
1907 if (info->data_pos >= info->data_len) /* need to read some more data */
1909 IO_STATUS_BLOCK io;
1911 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1912 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1913 if (io.u.Status)
1915 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1916 if (io.u.Status == STATUS_NO_MORE_FILES)
1918 CloseHandle( info->handle );
1919 info->handle = 0;
1921 break;
1923 info->data_len = io.Information;
1924 info->data_pos = 0;
1927 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1929 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1930 else info->data_pos = info->data_len;
1932 /* don't return '.' and '..' in the root of the drive */
1933 if (info->is_root)
1935 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1936 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1937 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1940 /* check for dir symlink */
1941 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1942 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1943 strpbrkW( info->mask.Buffer, wildcardsW ))
1945 if (!check_dir_symlink( info, dir_info )) continue;
1948 data->dwFileAttributes = dir_info->FileAttributes;
1949 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1950 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1951 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1952 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1953 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1954 data->dwReserved0 = 0;
1955 data->dwReserved1 = 0;
1957 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1958 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1959 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1960 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1962 TRACE("returning %s (%s)\n",
1963 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1965 ret = TRUE;
1966 break;
1969 RtlLeaveCriticalSection( &info->cs );
1970 return ret;
1974 /*************************************************************************
1975 * FindClose (KERNEL32.@)
1977 BOOL WINAPI FindClose( HANDLE handle )
1979 FIND_FIRST_INFO *info = handle;
1981 if (!handle || handle == INVALID_HANDLE_VALUE)
1983 SetLastError( ERROR_INVALID_HANDLE );
1984 return FALSE;
1987 __TRY
1989 if (info->magic == FIND_FIRST_MAGIC)
1991 RtlEnterCriticalSection( &info->cs );
1992 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1994 info->magic = 0;
1995 if (info->handle) CloseHandle( info->handle );
1996 info->handle = 0;
1997 RtlFreeUnicodeString( &info->mask );
1998 info->mask.Buffer = NULL;
1999 RtlFreeUnicodeString( &info->path );
2000 info->data_pos = 0;
2001 info->data_len = 0;
2002 RtlLeaveCriticalSection( &info->cs );
2003 info->cs.DebugInfo->Spare[0] = 0;
2004 RtlDeleteCriticalSection( &info->cs );
2005 HeapFree( GetProcessHeap(), 0, info );
2009 __EXCEPT_PAGE_FAULT
2011 WARN("Illegal handle %p\n", handle);
2012 SetLastError( ERROR_INVALID_HANDLE );
2013 return FALSE;
2015 __ENDTRY
2017 return TRUE;
2021 /*************************************************************************
2022 * FindFirstFileA (KERNEL32.@)
2024 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2026 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2027 FindExSearchNameMatch, NULL, 0);
2030 /*************************************************************************
2031 * FindFirstFileExA (KERNEL32.@)
2033 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2034 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2035 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2037 HANDLE handle;
2038 WIN32_FIND_DATAA *dataA;
2039 WIN32_FIND_DATAW dataW;
2040 WCHAR *nameW;
2042 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2044 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2045 if (handle == INVALID_HANDLE_VALUE) return handle;
2047 dataA = lpFindFileData;
2048 dataA->dwFileAttributes = dataW.dwFileAttributes;
2049 dataA->ftCreationTime = dataW.ftCreationTime;
2050 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2051 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2052 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2053 dataA->nFileSizeLow = dataW.nFileSizeLow;
2054 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2055 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2056 sizeof(dataA->cAlternateFileName) );
2057 return handle;
2061 /*************************************************************************
2062 * FindFirstFileW (KERNEL32.@)
2064 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2066 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2067 FindExSearchNameMatch, NULL, 0);
2071 /*************************************************************************
2072 * FindNextFileA (KERNEL32.@)
2074 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2076 WIN32_FIND_DATAW dataW;
2078 if (!FindNextFileW( handle, &dataW )) return FALSE;
2079 data->dwFileAttributes = dataW.dwFileAttributes;
2080 data->ftCreationTime = dataW.ftCreationTime;
2081 data->ftLastAccessTime = dataW.ftLastAccessTime;
2082 data->ftLastWriteTime = dataW.ftLastWriteTime;
2083 data->nFileSizeHigh = dataW.nFileSizeHigh;
2084 data->nFileSizeLow = dataW.nFileSizeLow;
2085 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2086 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2087 sizeof(data->cAlternateFileName) );
2088 return TRUE;
2092 /**************************************************************************
2093 * GetFileAttributesW (KERNEL32.@)
2095 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2097 FILE_BASIC_INFORMATION info;
2098 UNICODE_STRING nt_name;
2099 OBJECT_ATTRIBUTES attr;
2100 NTSTATUS status;
2102 TRACE("%s\n", debugstr_w(name));
2104 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2106 SetLastError( ERROR_PATH_NOT_FOUND );
2107 return INVALID_FILE_ATTRIBUTES;
2110 attr.Length = sizeof(attr);
2111 attr.RootDirectory = 0;
2112 attr.Attributes = OBJ_CASE_INSENSITIVE;
2113 attr.ObjectName = &nt_name;
2114 attr.SecurityDescriptor = NULL;
2115 attr.SecurityQualityOfService = NULL;
2117 status = NtQueryAttributesFile( &attr, &info );
2118 RtlFreeUnicodeString( &nt_name );
2120 if (status == STATUS_SUCCESS) return info.FileAttributes;
2122 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2123 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2125 SetLastError( RtlNtStatusToDosError(status) );
2126 return INVALID_FILE_ATTRIBUTES;
2130 /**************************************************************************
2131 * GetFileAttributesA (KERNEL32.@)
2133 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2135 WCHAR *nameW;
2137 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2138 return GetFileAttributesW( nameW );
2142 /**************************************************************************
2143 * SetFileAttributesW (KERNEL32.@)
2145 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2147 UNICODE_STRING nt_name;
2148 OBJECT_ATTRIBUTES attr;
2149 IO_STATUS_BLOCK io;
2150 NTSTATUS status;
2151 HANDLE handle;
2153 TRACE("%s %x\n", debugstr_w(name), attributes);
2155 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2157 SetLastError( ERROR_PATH_NOT_FOUND );
2158 return FALSE;
2161 attr.Length = sizeof(attr);
2162 attr.RootDirectory = 0;
2163 attr.Attributes = OBJ_CASE_INSENSITIVE;
2164 attr.ObjectName = &nt_name;
2165 attr.SecurityDescriptor = NULL;
2166 attr.SecurityQualityOfService = NULL;
2168 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2169 RtlFreeUnicodeString( &nt_name );
2171 if (status == STATUS_SUCCESS)
2173 FILE_BASIC_INFORMATION info;
2175 memset( &info, 0, sizeof(info) );
2176 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2177 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2178 NtClose( handle );
2181 if (status == STATUS_SUCCESS) return TRUE;
2182 SetLastError( RtlNtStatusToDosError(status) );
2183 return FALSE;
2187 /**************************************************************************
2188 * SetFileAttributesA (KERNEL32.@)
2190 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2192 WCHAR *nameW;
2194 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2195 return SetFileAttributesW( nameW, attributes );
2199 /**************************************************************************
2200 * GetFileAttributesExW (KERNEL32.@)
2202 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2204 FILE_NETWORK_OPEN_INFORMATION info;
2205 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2206 UNICODE_STRING nt_name;
2207 OBJECT_ATTRIBUTES attr;
2208 NTSTATUS status;
2210 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2212 if (level != GetFileExInfoStandard)
2214 SetLastError( ERROR_INVALID_PARAMETER );
2215 return FALSE;
2218 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2220 SetLastError( ERROR_PATH_NOT_FOUND );
2221 return FALSE;
2224 attr.Length = sizeof(attr);
2225 attr.RootDirectory = 0;
2226 attr.Attributes = OBJ_CASE_INSENSITIVE;
2227 attr.ObjectName = &nt_name;
2228 attr.SecurityDescriptor = NULL;
2229 attr.SecurityQualityOfService = NULL;
2231 status = NtQueryFullAttributesFile( &attr, &info );
2232 RtlFreeUnicodeString( &nt_name );
2234 if (status != STATUS_SUCCESS)
2236 SetLastError( RtlNtStatusToDosError(status) );
2237 return FALSE;
2240 data->dwFileAttributes = info.FileAttributes;
2241 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2242 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2243 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2244 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2245 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2246 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2247 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2248 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2249 return TRUE;
2253 /**************************************************************************
2254 * GetFileAttributesExA (KERNEL32.@)
2256 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2258 WCHAR *nameW;
2260 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2261 return GetFileAttributesExW( nameW, level, ptr );
2265 /******************************************************************************
2266 * GetCompressedFileSizeW (KERNEL32.@)
2268 * Get the actual number of bytes used on disk.
2270 * RETURNS
2271 * Success: Low-order doubleword of number of bytes
2272 * Failure: INVALID_FILE_SIZE
2274 DWORD WINAPI GetCompressedFileSizeW(
2275 LPCWSTR name, /* [in] Pointer to name of file */
2276 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2278 UNICODE_STRING nt_name;
2279 OBJECT_ATTRIBUTES attr;
2280 IO_STATUS_BLOCK io;
2281 NTSTATUS status;
2282 HANDLE handle;
2283 DWORD ret = INVALID_FILE_SIZE;
2285 TRACE("%s %p\n", debugstr_w(name), size_high);
2287 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2289 SetLastError( ERROR_PATH_NOT_FOUND );
2290 return INVALID_FILE_SIZE;
2293 attr.Length = sizeof(attr);
2294 attr.RootDirectory = 0;
2295 attr.Attributes = OBJ_CASE_INSENSITIVE;
2296 attr.ObjectName = &nt_name;
2297 attr.SecurityDescriptor = NULL;
2298 attr.SecurityQualityOfService = NULL;
2300 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2301 RtlFreeUnicodeString( &nt_name );
2303 if (status == STATUS_SUCCESS)
2305 /* we don't support compressed files, simply return the file size */
2306 ret = GetFileSize( handle, size_high );
2307 NtClose( handle );
2309 else SetLastError( RtlNtStatusToDosError(status) );
2311 return ret;
2315 /******************************************************************************
2316 * GetCompressedFileSizeA (KERNEL32.@)
2318 * See GetCompressedFileSizeW.
2320 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2322 WCHAR *nameW;
2324 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2325 return GetCompressedFileSizeW( nameW, size_high );
2329 /***********************************************************************
2330 * OpenVxDHandle (KERNEL32.@)
2332 * This function is supposed to return the corresponding Ring 0
2333 * ("kernel") handle for a Ring 3 handle in Win9x.
2334 * Evidently, Wine will have problems with this. But we try anyway,
2335 * maybe it helps...
2337 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2339 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2340 return hHandleRing3;
2344 /****************************************************************************
2345 * DeviceIoControl (KERNEL32.@)
2347 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2348 LPVOID lpvInBuffer, DWORD cbInBuffer,
2349 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2350 LPDWORD lpcbBytesReturned,
2351 LPOVERLAPPED lpOverlapped)
2353 NTSTATUS status;
2355 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2356 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2357 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2359 /* Check if this is a user defined control code for a VxD */
2361 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2363 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2364 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2365 DeviceIoProc proc = NULL;
2367 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2368 "__wine_vxd_get_proc" );
2369 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2370 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2371 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2374 /* Not a VxD, let ntdll handle it */
2376 if (lpOverlapped)
2378 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2379 lpOverlapped->Internal = STATUS_PENDING;
2380 lpOverlapped->InternalHigh = 0;
2381 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2382 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2383 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2384 dwIoControlCode, lpvInBuffer, cbInBuffer,
2385 lpvOutBuffer, cbOutBuffer);
2386 else
2387 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2388 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2389 dwIoControlCode, lpvInBuffer, cbInBuffer,
2390 lpvOutBuffer, cbOutBuffer);
2391 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2393 else
2395 IO_STATUS_BLOCK iosb;
2397 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2398 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2399 dwIoControlCode, lpvInBuffer, cbInBuffer,
2400 lpvOutBuffer, cbOutBuffer);
2401 else
2402 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2403 dwIoControlCode, lpvInBuffer, cbInBuffer,
2404 lpvOutBuffer, cbOutBuffer);
2405 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2407 if (status) SetLastError( RtlNtStatusToDosError(status) );
2408 return !status;
2412 /***********************************************************************
2413 * OpenFile (KERNEL32.@)
2415 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2417 HANDLE handle;
2418 FILETIME filetime;
2419 WORD filedatetime[2];
2421 if (!ofs) return HFILE_ERROR;
2423 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2424 ((mode & 0x3 )==OF_READ)?"OF_READ":
2425 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2426 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2427 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2428 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2429 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2430 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2431 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2432 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2433 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2434 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2435 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2436 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2437 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2438 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2439 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2440 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2444 ofs->cBytes = sizeof(OFSTRUCT);
2445 ofs->nErrCode = 0;
2446 if (mode & OF_REOPEN) name = ofs->szPathName;
2448 if (!name) return HFILE_ERROR;
2450 TRACE("%s %04x\n", name, mode );
2452 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2453 Are there any cases where getting the path here is wrong?
2454 Uwe Bonnes 1997 Apr 2 */
2455 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2457 /* OF_PARSE simply fills the structure */
2459 if (mode & OF_PARSE)
2461 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2462 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2463 return 0;
2466 /* OF_CREATE is completely different from all other options, so
2467 handle it first */
2469 if (mode & OF_CREATE)
2471 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2472 goto error;
2474 else
2476 /* Now look for the file */
2478 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2479 goto error;
2481 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2483 if (mode & OF_DELETE)
2485 if (!DeleteFileA( ofs->szPathName )) goto error;
2486 TRACE("(%s): OF_DELETE return = OK\n", name);
2487 return TRUE;
2490 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2491 if (handle == INVALID_HANDLE_VALUE) goto error;
2493 GetFileTime( handle, NULL, NULL, &filetime );
2494 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2495 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2497 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2499 CloseHandle( handle );
2500 WARN("(%s): OF_VERIFY failed\n", name );
2501 /* FIXME: what error here? */
2502 SetLastError( ERROR_FILE_NOT_FOUND );
2503 goto error;
2506 ofs->Reserved1 = filedatetime[0];
2507 ofs->Reserved2 = filedatetime[1];
2509 TRACE("(%s): OK, return = %p\n", name, handle );
2510 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2512 CloseHandle( handle );
2513 return TRUE;
2515 return HandleToLong(handle);
2517 error: /* We get here if there was an error opening the file */
2518 ofs->nErrCode = GetLastError();
2519 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2520 return HFILE_ERROR;