push a116a683330fd450d855d812b32928cd0eff60f8
[wine/hacks.git] / dlls / kernel32 / file.c
blob8c6f40492e04a9aec8a833e832e0c929dfa8c367
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996, 2004 Alexandre Julliard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
30 #endif
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34 #include "winerror.h"
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winternl.h"
40 #include "winioctl.h"
41 #include "wincon.h"
42 #include "wine/winbase16.h"
43 #include "kernel_private.h"
45 #include "wine/exception.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(file);
51 HANDLE dos_handles[DOS_TABLE_SIZE];
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 UNICODE_STRING mask; /* file mask */
61 UNICODE_STRING path; /* NT path used to open the directory */
62 BOOL is_root; /* is directory the root of the drive? */
63 UINT data_pos; /* current position in dir data */
64 UINT data_len; /* length of dir data */
65 BYTE data[8192]; /* directory data */
66 } FIND_FIRST_INFO;
68 #define FIND_FIRST_MAGIC 0xc0ffee11
70 static BOOL oem_file_apis;
72 static const WCHAR wildcardsW[] = { '*','?',0 };
74 /***********************************************************************
75 * create_file_OF
77 * Wrapper for CreateFile that takes OF_* mode flags.
79 static HANDLE create_file_OF( LPCSTR path, INT mode )
81 DWORD access, sharing, creation;
83 if (mode & OF_CREATE)
85 creation = CREATE_ALWAYS;
86 access = GENERIC_READ | GENERIC_WRITE;
88 else
90 creation = OPEN_EXISTING;
91 switch(mode & 0x03)
93 case OF_READ: access = GENERIC_READ; break;
94 case OF_WRITE: access = GENERIC_WRITE; break;
95 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
96 default: access = 0; break;
100 switch(mode & 0x70)
102 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
103 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
104 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
105 case OF_SHARE_DENY_NONE:
106 case OF_SHARE_COMPAT:
107 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
109 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
113 /***********************************************************************
114 * check_dir_symlink
116 * Check if a dir symlink should be returned by FindNextFile.
118 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
120 UNICODE_STRING str;
121 ANSI_STRING unix_name;
122 struct stat st, parent_st;
123 BOOL ret = TRUE;
124 DWORD len;
126 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
127 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
128 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
129 len = info->path.Length / sizeof(WCHAR);
130 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
131 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
132 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
134 unix_name.Buffer = NULL;
135 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
136 !stat( unix_name.Buffer, &st ))
138 char *p = unix_name.Buffer + unix_name.Length - 1;
140 /* skip trailing slashes */
141 while (p > unix_name.Buffer && *p == '/') p--;
143 while (ret && p > unix_name.Buffer)
145 while (p > unix_name.Buffer && *p != '/') p--;
146 while (p > unix_name.Buffer && *p == '/') p--;
147 p[1] = 0;
148 if (!stat( unix_name.Buffer, &parent_st ) &&
149 parent_st.st_dev == st.st_dev &&
150 parent_st.st_ino == st.st_ino)
152 WARN( "suppressing dir symlink %s pointing to parent %s\n",
153 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
154 debugstr_a( unix_name.Buffer ));
155 ret = FALSE;
159 RtlFreeAnsiString( &unix_name );
160 RtlFreeUnicodeString( &str );
161 return ret;
165 /***********************************************************************
166 * FILE_SetDosError
168 * Set the DOS error code from errno.
170 void FILE_SetDosError(void)
172 int save_errno = errno; /* errno gets overwritten by printf */
174 TRACE("errno = %d %s\n", errno, strerror(errno));
175 switch (save_errno)
177 case EAGAIN:
178 SetLastError( ERROR_SHARING_VIOLATION );
179 break;
180 case EBADF:
181 SetLastError( ERROR_INVALID_HANDLE );
182 break;
183 case ENOSPC:
184 SetLastError( ERROR_HANDLE_DISK_FULL );
185 break;
186 case EACCES:
187 case EPERM:
188 case EROFS:
189 SetLastError( ERROR_ACCESS_DENIED );
190 break;
191 case EBUSY:
192 SetLastError( ERROR_LOCK_VIOLATION );
193 break;
194 case ENOENT:
195 SetLastError( ERROR_FILE_NOT_FOUND );
196 break;
197 case EISDIR:
198 SetLastError( ERROR_CANNOT_MAKE );
199 break;
200 case ENFILE:
201 case EMFILE:
202 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
203 break;
204 case EEXIST:
205 SetLastError( ERROR_FILE_EXISTS );
206 break;
207 case EINVAL:
208 case ESPIPE:
209 SetLastError( ERROR_SEEK );
210 break;
211 case ENOTEMPTY:
212 SetLastError( ERROR_DIR_NOT_EMPTY );
213 break;
214 case ENOEXEC:
215 SetLastError( ERROR_BAD_FORMAT );
216 break;
217 case ENOTDIR:
218 SetLastError( ERROR_PATH_NOT_FOUND );
219 break;
220 case EXDEV:
221 SetLastError( ERROR_NOT_SAME_DEVICE );
222 break;
223 default:
224 WARN("unknown file error: %s\n", strerror(save_errno) );
225 SetLastError( ERROR_GEN_FAILURE );
226 break;
228 errno = save_errno;
232 /***********************************************************************
233 * FILE_name_AtoW
235 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
237 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
238 * there is no possibility for the function to do that twice, taking into
239 * account any called function.
241 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
243 ANSI_STRING str;
244 UNICODE_STRING strW, *pstrW;
245 NTSTATUS status;
247 RtlInitAnsiString( &str, name );
248 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
249 if (oem_file_apis)
250 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
251 else
252 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
253 if (status == STATUS_SUCCESS) return pstrW->Buffer;
255 if (status == STATUS_BUFFER_OVERFLOW)
256 SetLastError( ERROR_FILENAME_EXCED_RANGE );
257 else
258 SetLastError( RtlNtStatusToDosError(status) );
259 return NULL;
263 /***********************************************************************
264 * FILE_name_WtoA
266 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
268 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
270 DWORD ret;
272 if (srclen < 0) srclen = strlenW( src ) + 1;
273 if (oem_file_apis)
274 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
275 else
276 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
277 return ret;
281 /**************************************************************************
282 * SetFileApisToOEM (KERNEL32.@)
284 VOID WINAPI SetFileApisToOEM(void)
286 oem_file_apis = TRUE;
290 /**************************************************************************
291 * SetFileApisToANSI (KERNEL32.@)
293 VOID WINAPI SetFileApisToANSI(void)
295 oem_file_apis = FALSE;
299 /******************************************************************************
300 * AreFileApisANSI (KERNEL32.@)
302 * Determines if file functions are using ANSI
304 * RETURNS
305 * TRUE: Set of file functions is using ANSI code page
306 * FALSE: Set of file functions is using OEM code page
308 BOOL WINAPI AreFileApisANSI(void)
310 return !oem_file_apis;
314 /**************************************************************************
315 * Operations on file handles *
316 **************************************************************************/
318 /***********************************************************************
319 * FILE_InitProcessDosHandles
321 * Allocates the default DOS handles for a process. Called either by
322 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
324 static void FILE_InitProcessDosHandles( void )
326 static BOOL init_done /* = FALSE */;
327 HANDLE cp = GetCurrentProcess();
329 if (init_done) return;
330 init_done = TRUE;
331 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
332 0, TRUE, DUPLICATE_SAME_ACCESS);
333 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
334 0, TRUE, DUPLICATE_SAME_ACCESS);
335 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
336 0, TRUE, DUPLICATE_SAME_ACCESS);
337 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
338 0, TRUE, DUPLICATE_SAME_ACCESS);
339 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
340 0, TRUE, DUPLICATE_SAME_ACCESS);
344 /******************************************************************
345 * FILE_ReadWriteApc (internal)
347 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
349 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
351 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
355 /***********************************************************************
356 * ReadFileEx (KERNEL32.@)
358 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
359 LPOVERLAPPED overlapped,
360 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
362 LARGE_INTEGER offset;
363 NTSTATUS status;
364 PIO_STATUS_BLOCK io_status;
366 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
368 if (!overlapped)
370 SetLastError(ERROR_INVALID_PARAMETER);
371 return FALSE;
374 offset.u.LowPart = overlapped->u.s.Offset;
375 offset.u.HighPart = overlapped->u.s.OffsetHigh;
376 io_status = (PIO_STATUS_BLOCK)overlapped;
377 io_status->u.Status = STATUS_PENDING;
378 io_status->Information = 0;
380 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
381 io_status, buffer, bytesToRead, &offset, NULL);
383 if (status)
385 SetLastError( RtlNtStatusToDosError(status) );
386 return FALSE;
388 return TRUE;
392 /***********************************************************************
393 * ReadFile (KERNEL32.@)
395 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
396 LPDWORD bytesRead, LPOVERLAPPED overlapped )
398 LARGE_INTEGER offset;
399 PLARGE_INTEGER poffset = NULL;
400 IO_STATUS_BLOCK iosb;
401 PIO_STATUS_BLOCK io_status = &iosb;
402 HANDLE hEvent = 0;
403 NTSTATUS status;
404 LPVOID cvalue = NULL;
406 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
407 bytesRead, overlapped );
409 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
410 if (!bytesToRead) return TRUE;
412 if (is_console_handle(hFile))
413 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
415 if (overlapped != NULL)
417 offset.u.LowPart = overlapped->u.s.Offset;
418 offset.u.HighPart = overlapped->u.s.OffsetHigh;
419 poffset = &offset;
420 hEvent = overlapped->hEvent;
421 io_status = (PIO_STATUS_BLOCK)overlapped;
422 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
424 io_status->u.Status = STATUS_PENDING;
425 io_status->Information = 0;
427 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
429 if (status == STATUS_PENDING && !overlapped)
431 WaitForSingleObject( hFile, INFINITE );
432 status = io_status->u.Status;
435 if (status != STATUS_PENDING && bytesRead)
436 *bytesRead = io_status->Information;
438 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
440 SetLastError( RtlNtStatusToDosError(status) );
441 return FALSE;
443 return TRUE;
447 /***********************************************************************
448 * WriteFileEx (KERNEL32.@)
450 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
451 LPOVERLAPPED overlapped,
452 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
454 LARGE_INTEGER offset;
455 NTSTATUS status;
456 PIO_STATUS_BLOCK io_status;
458 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
460 if (overlapped == NULL)
462 SetLastError(ERROR_INVALID_PARAMETER);
463 return FALSE;
465 offset.u.LowPart = overlapped->u.s.Offset;
466 offset.u.HighPart = overlapped->u.s.OffsetHigh;
468 io_status = (PIO_STATUS_BLOCK)overlapped;
469 io_status->u.Status = STATUS_PENDING;
470 io_status->Information = 0;
472 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
473 io_status, buffer, bytesToWrite, &offset, NULL);
475 if (status) SetLastError( RtlNtStatusToDosError(status) );
476 return !status;
480 /***********************************************************************
481 * WriteFile (KERNEL32.@)
483 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
484 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
486 HANDLE hEvent = NULL;
487 LARGE_INTEGER offset;
488 PLARGE_INTEGER poffset = NULL;
489 NTSTATUS status;
490 IO_STATUS_BLOCK iosb;
491 PIO_STATUS_BLOCK piosb = &iosb;
492 LPVOID cvalue = NULL;
494 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
496 if (is_console_handle(hFile))
497 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
499 if (overlapped)
501 offset.u.LowPart = overlapped->u.s.Offset;
502 offset.u.HighPart = overlapped->u.s.OffsetHigh;
503 poffset = &offset;
504 hEvent = overlapped->hEvent;
505 piosb = (PIO_STATUS_BLOCK)overlapped;
506 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
508 piosb->u.Status = STATUS_PENDING;
509 piosb->Information = 0;
511 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
512 buffer, bytesToWrite, poffset, NULL);
514 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
515 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
517 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
518 buffer, bytesToWrite, poffset, NULL);
519 if (status != STATUS_INVALID_USER_BUFFER)
520 FIXME("Could not access memory (%p,%d) at first, now OK. Protected by DIBSection code?\n",
521 buffer, bytesToWrite);
524 if (status == STATUS_PENDING && !overlapped)
526 WaitForSingleObject( hFile, INFINITE );
527 status = piosb->u.Status;
530 if (status != STATUS_PENDING && bytesWritten)
531 *bytesWritten = piosb->Information;
533 if (status && status != STATUS_TIMEOUT)
535 SetLastError( RtlNtStatusToDosError(status) );
536 return FALSE;
538 return TRUE;
542 /***********************************************************************
543 * GetOverlappedResult (KERNEL32.@)
545 * Check the result of an Asynchronous data transfer from a file.
547 * Parameters
548 * HANDLE hFile [in] handle of file to check on
549 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
550 * LPDWORD lpTransferred [in/out] number of bytes transferred
551 * BOOL bWait [in] wait for the transfer to complete ?
553 * RETURNS
554 * TRUE on success
555 * FALSE on failure
557 * If successful (and relevant) lpTransferred will hold the number of
558 * bytes transferred during the async operation.
560 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
561 LPDWORD lpTransferred, BOOL bWait)
563 NTSTATUS status;
565 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
567 if ( lpOverlapped == NULL )
569 ERR("lpOverlapped was null\n");
570 return FALSE;
573 status = lpOverlapped->Internal;
574 if (status == STATUS_PENDING)
576 if (!bWait)
578 SetLastError( ERROR_IO_INCOMPLETE );
579 return FALSE;
582 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
583 INFINITE ) == WAIT_FAILED)
584 return FALSE;
585 status = lpOverlapped->Internal;
588 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
590 if (status) SetLastError( RtlNtStatusToDosError(status) );
591 return !status;
594 /***********************************************************************
595 * CancelIo (KERNEL32.@)
597 * Cancels pending I/O operations initiated by the current thread on a file.
599 * PARAMS
600 * handle [I] File handle.
602 * RETURNS
603 * Success: TRUE.
604 * Failure: FALSE, check GetLastError().
606 BOOL WINAPI CancelIo(HANDLE handle)
608 IO_STATUS_BLOCK io_status;
610 NtCancelIoFile(handle, &io_status);
611 if (io_status.u.Status)
613 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
614 return FALSE;
616 return TRUE;
619 /***********************************************************************
620 * _hread (KERNEL32.@)
622 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
624 return _lread( hFile, buffer, count );
628 /***********************************************************************
629 * _hwrite (KERNEL32.@)
631 * experimentation yields that _lwrite:
632 * o truncates the file at the current position with
633 * a 0 len write
634 * o returns 0 on a 0 length write
635 * o works with console handles
638 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
640 DWORD result;
642 TRACE("%d %p %d\n", handle, buffer, count );
644 if (!count)
646 /* Expand or truncate at current position */
647 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
648 return 0;
650 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
651 return HFILE_ERROR;
652 return result;
656 /***********************************************************************
657 * _lclose (KERNEL32.@)
659 HFILE WINAPI _lclose( HFILE hFile )
661 TRACE("handle %d\n", hFile );
662 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
666 /***********************************************************************
667 * _lcreat (KERNEL32.@)
669 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
671 HANDLE hfile;
673 /* Mask off all flags not explicitly allowed by the doc */
674 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
675 TRACE("%s %02x\n", path, attr );
676 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
677 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
678 CREATE_ALWAYS, attr, 0 );
679 return HandleToLong(hfile);
683 /***********************************************************************
684 * _lopen (KERNEL32.@)
686 HFILE WINAPI _lopen( LPCSTR path, INT mode )
688 HANDLE hfile;
690 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
691 hfile = create_file_OF( path, mode & ~OF_CREATE );
692 return HandleToLong(hfile);
695 /***********************************************************************
696 * _lread (KERNEL32.@)
698 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
700 DWORD result;
701 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
702 return HFILE_ERROR;
703 return result;
707 /***********************************************************************
708 * _llseek (KERNEL32.@)
710 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
712 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
716 /***********************************************************************
717 * _lwrite (KERNEL32.@)
719 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
721 return (UINT)_hwrite( hFile, buffer, (LONG)count );
725 /***********************************************************************
726 * FlushFileBuffers (KERNEL32.@)
728 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
730 NTSTATUS nts;
731 IO_STATUS_BLOCK ioblk;
733 if (is_console_handle( hFile ))
735 /* this will fail (as expected) for an output handle */
736 return FlushConsoleInputBuffer( hFile );
738 nts = NtFlushBuffersFile( hFile, &ioblk );
739 if (nts != STATUS_SUCCESS)
741 SetLastError( RtlNtStatusToDosError( nts ) );
742 return FALSE;
745 return TRUE;
749 /***********************************************************************
750 * GetFileType (KERNEL32.@)
752 DWORD WINAPI GetFileType( HANDLE hFile )
754 FILE_FS_DEVICE_INFORMATION info;
755 IO_STATUS_BLOCK io;
756 NTSTATUS status;
758 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
760 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
761 if (status != STATUS_SUCCESS)
763 SetLastError( RtlNtStatusToDosError(status) );
764 return FILE_TYPE_UNKNOWN;
767 switch(info.DeviceType)
769 case FILE_DEVICE_NULL:
770 case FILE_DEVICE_SERIAL_PORT:
771 case FILE_DEVICE_PARALLEL_PORT:
772 case FILE_DEVICE_TAPE:
773 case FILE_DEVICE_UNKNOWN:
774 return FILE_TYPE_CHAR;
775 case FILE_DEVICE_NAMED_PIPE:
776 return FILE_TYPE_PIPE;
777 default:
778 return FILE_TYPE_DISK;
783 /***********************************************************************
784 * GetFileInformationByHandle (KERNEL32.@)
786 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
788 FILE_ALL_INFORMATION all_info;
789 IO_STATUS_BLOCK io;
790 NTSTATUS status;
792 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
793 if (status == STATUS_SUCCESS)
795 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
796 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
797 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
798 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
799 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
800 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
801 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
802 info->dwVolumeSerialNumber = 0; /* FIXME */
803 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
804 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
805 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
806 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
807 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
808 return TRUE;
810 SetLastError( RtlNtStatusToDosError(status) );
811 return FALSE;
815 /***********************************************************************
816 * GetFileSize (KERNEL32.@)
818 * Retrieve the size of a file.
820 * PARAMS
821 * hFile [I] File to retrieve size of.
822 * filesizehigh [O] On return, the high bits of the file size.
824 * RETURNS
825 * Success: The low bits of the file size.
826 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
827 * check GetLastError() for values other than ERROR_SUCCESS.
829 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
831 LARGE_INTEGER size;
832 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
833 if (filesizehigh) *filesizehigh = size.u.HighPart;
834 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
835 return size.u.LowPart;
839 /***********************************************************************
840 * GetFileSizeEx (KERNEL32.@)
842 * Retrieve the size of a file.
844 * PARAMS
845 * hFile [I] File to retrieve size of.
846 * lpFileSIze [O] On return, the size of the file.
848 * RETURNS
849 * Success: TRUE.
850 * Failure: FALSE, check GetLastError().
852 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
854 FILE_END_OF_FILE_INFORMATION info;
855 IO_STATUS_BLOCK io;
856 NTSTATUS status;
858 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
859 if (status == STATUS_SUCCESS)
861 *lpFileSize = info.EndOfFile;
862 return TRUE;
864 SetLastError( RtlNtStatusToDosError(status) );
865 return FALSE;
869 /**************************************************************************
870 * SetEndOfFile (KERNEL32.@)
872 * Sets the current position as the end of the file.
874 * PARAMS
875 * hFile [I] File handle.
877 * RETURNS
878 * Success: TRUE.
879 * Failure: FALSE, check GetLastError().
881 BOOL WINAPI SetEndOfFile( HANDLE hFile )
883 FILE_POSITION_INFORMATION pos;
884 FILE_END_OF_FILE_INFORMATION eof;
885 IO_STATUS_BLOCK io;
886 NTSTATUS status;
888 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
889 if (status == STATUS_SUCCESS)
891 eof.EndOfFile = pos.CurrentByteOffset;
892 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
894 if (status == STATUS_SUCCESS) return TRUE;
895 SetLastError( RtlNtStatusToDosError(status) );
896 return FALSE;
900 /***********************************************************************
901 * SetFilePointer (KERNEL32.@)
903 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
905 LARGE_INTEGER dist, newpos;
907 if (highword)
909 dist.u.LowPart = distance;
910 dist.u.HighPart = *highword;
912 else dist.QuadPart = distance;
914 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
916 if (highword) *highword = newpos.u.HighPart;
917 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
918 return newpos.u.LowPart;
922 /***********************************************************************
923 * SetFilePointerEx (KERNEL32.@)
925 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
926 LARGE_INTEGER *newpos, DWORD method )
928 LONGLONG pos;
929 IO_STATUS_BLOCK io;
930 FILE_POSITION_INFORMATION info;
932 switch(method)
934 case FILE_BEGIN:
935 pos = distance.QuadPart;
936 break;
937 case FILE_CURRENT:
938 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
939 goto error;
940 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
941 break;
942 case FILE_END:
944 FILE_END_OF_FILE_INFORMATION eof;
945 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
946 goto error;
947 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
949 break;
950 default:
951 SetLastError( ERROR_INVALID_PARAMETER );
952 return FALSE;
955 if (pos < 0)
957 SetLastError( ERROR_NEGATIVE_SEEK );
958 return FALSE;
961 info.CurrentByteOffset.QuadPart = pos;
962 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
963 goto error;
964 if (newpos) newpos->QuadPart = pos;
965 return TRUE;
967 error:
968 SetLastError( RtlNtStatusToDosError(io.u.Status) );
969 return FALSE;
972 /***********************************************************************
973 * GetFileTime (KERNEL32.@)
975 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
976 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
978 FILE_BASIC_INFORMATION info;
979 IO_STATUS_BLOCK io;
980 NTSTATUS status;
982 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
983 if (status == STATUS_SUCCESS)
985 if (lpCreationTime)
987 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
988 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
990 if (lpLastAccessTime)
992 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
993 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
995 if (lpLastWriteTime)
997 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
998 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1000 return TRUE;
1002 SetLastError( RtlNtStatusToDosError(status) );
1003 return FALSE;
1007 /***********************************************************************
1008 * SetFileTime (KERNEL32.@)
1010 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1011 const FILETIME *atime, const FILETIME *mtime )
1013 FILE_BASIC_INFORMATION info;
1014 IO_STATUS_BLOCK io;
1015 NTSTATUS status;
1017 memset( &info, 0, sizeof(info) );
1018 if (ctime)
1020 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1021 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1023 if (atime)
1025 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1026 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1028 if (mtime)
1030 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1031 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1034 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1035 if (status == STATUS_SUCCESS) return TRUE;
1036 SetLastError( RtlNtStatusToDosError(status) );
1037 return FALSE;
1041 /**************************************************************************
1042 * LockFile (KERNEL32.@)
1044 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1045 DWORD count_low, DWORD count_high )
1047 NTSTATUS status;
1048 LARGE_INTEGER count, offset;
1050 TRACE( "%p %x%08x %x%08x\n",
1051 hFile, offset_high, offset_low, count_high, count_low );
1053 count.u.LowPart = count_low;
1054 count.u.HighPart = count_high;
1055 offset.u.LowPart = offset_low;
1056 offset.u.HighPart = offset_high;
1058 status = NtLockFile( hFile, 0, NULL, NULL,
1059 NULL, &offset, &count, NULL, TRUE, TRUE );
1061 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1062 return !status;
1066 /**************************************************************************
1067 * LockFileEx [KERNEL32.@]
1069 * Locks a byte range within an open file for shared or exclusive access.
1071 * RETURNS
1072 * success: TRUE
1073 * failure: FALSE
1075 * NOTES
1076 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1078 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1079 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1081 NTSTATUS status;
1082 LARGE_INTEGER count, offset;
1083 LPVOID cvalue = NULL;
1085 if (reserved)
1087 SetLastError( ERROR_INVALID_PARAMETER );
1088 return FALSE;
1091 TRACE( "%p %x%08x %x%08x flags %x\n",
1092 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1093 count_high, count_low, flags );
1095 count.u.LowPart = count_low;
1096 count.u.HighPart = count_high;
1097 offset.u.LowPart = overlapped->u.s.Offset;
1098 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1100 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1102 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1103 NULL, &offset, &count, NULL,
1104 flags & LOCKFILE_FAIL_IMMEDIATELY,
1105 flags & LOCKFILE_EXCLUSIVE_LOCK );
1107 if (status) SetLastError( RtlNtStatusToDosError(status) );
1108 return !status;
1112 /**************************************************************************
1113 * UnlockFile (KERNEL32.@)
1115 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1116 DWORD count_low, DWORD count_high )
1118 NTSTATUS status;
1119 LARGE_INTEGER count, offset;
1121 count.u.LowPart = count_low;
1122 count.u.HighPart = count_high;
1123 offset.u.LowPart = offset_low;
1124 offset.u.HighPart = offset_high;
1126 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1127 if (status) SetLastError( RtlNtStatusToDosError(status) );
1128 return !status;
1132 /**************************************************************************
1133 * UnlockFileEx (KERNEL32.@)
1135 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1136 LPOVERLAPPED overlapped )
1138 if (reserved)
1140 SetLastError( ERROR_INVALID_PARAMETER );
1141 return FALSE;
1143 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1145 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1149 /***********************************************************************
1150 * Win32HandleToDosFileHandle (KERNEL32.21)
1152 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1153 * longer valid after this function (even on failure).
1155 * Note: this is not exactly right, since on Win95 the Win32 handles
1156 * are on top of DOS handles and we do it the other way
1157 * around. Should be good enough though.
1159 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1161 int i;
1163 if (!handle || (handle == INVALID_HANDLE_VALUE))
1164 return HFILE_ERROR;
1166 FILE_InitProcessDosHandles();
1167 for (i = 0; i < DOS_TABLE_SIZE; i++)
1168 if (!dos_handles[i])
1170 dos_handles[i] = handle;
1171 TRACE("Got %d for h32 %p\n", i, handle );
1172 return (HFILE)i;
1174 CloseHandle( handle );
1175 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1176 return HFILE_ERROR;
1180 /***********************************************************************
1181 * DosFileHandleToWin32Handle (KERNEL32.20)
1183 * Return the Win32 handle for a DOS handle.
1185 * Note: this is not exactly right, since on Win95 the Win32 handles
1186 * are on top of DOS handles and we do it the other way
1187 * around. Should be good enough though.
1189 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1191 HFILE16 hfile = (HFILE16)handle;
1192 if (hfile < 5) FILE_InitProcessDosHandles();
1193 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1195 SetLastError( ERROR_INVALID_HANDLE );
1196 return INVALID_HANDLE_VALUE;
1198 return dos_handles[hfile];
1202 /*************************************************************************
1203 * SetHandleCount (KERNEL32.@)
1205 UINT WINAPI SetHandleCount( UINT count )
1207 return min( 256, count );
1211 /***********************************************************************
1212 * DisposeLZ32Handle (KERNEL32.22)
1214 * Note: this is not entirely correct, we should only close the
1215 * 32-bit handle and not the 16-bit one, but we cannot do
1216 * this because of the way our DOS handles are implemented.
1217 * It shouldn't break anything though.
1219 void WINAPI DisposeLZ32Handle( HANDLE handle )
1221 int i;
1223 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1225 for (i = 5; i < DOS_TABLE_SIZE; i++)
1226 if (dos_handles[i] == handle)
1228 dos_handles[i] = 0;
1229 CloseHandle( handle );
1230 break;
1234 /**************************************************************************
1235 * Operations on file names *
1236 **************************************************************************/
1239 /*************************************************************************
1240 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1242 * Creates or opens an object, and returns a handle that can be used to
1243 * access that object.
1245 * PARAMS
1247 * filename [in] pointer to filename to be accessed
1248 * access [in] access mode requested
1249 * sharing [in] share mode
1250 * sa [in] pointer to security attributes
1251 * creation [in] how to create the file
1252 * attributes [in] attributes for newly created file
1253 * template [in] handle to file with extended attributes to copy
1255 * RETURNS
1256 * Success: Open handle to specified file
1257 * Failure: INVALID_HANDLE_VALUE
1259 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1260 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1261 DWORD attributes, HANDLE template )
1263 NTSTATUS status;
1264 UINT options;
1265 OBJECT_ATTRIBUTES attr;
1266 UNICODE_STRING nameW;
1267 IO_STATUS_BLOCK io;
1268 HANDLE ret;
1269 DWORD dosdev;
1270 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1271 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1272 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1273 SECURITY_QUALITY_OF_SERVICE qos;
1275 static const UINT nt_disposition[5] =
1277 FILE_CREATE, /* CREATE_NEW */
1278 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1279 FILE_OPEN, /* OPEN_EXISTING */
1280 FILE_OPEN_IF, /* OPEN_ALWAYS */
1281 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1285 /* sanity checks */
1287 if (!filename || !filename[0])
1289 SetLastError( ERROR_PATH_NOT_FOUND );
1290 return INVALID_HANDLE_VALUE;
1293 TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1294 (access & GENERIC_READ)?"GENERIC_READ ":"",
1295 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1296 (!access)?"QUERY_ACCESS ":"",
1297 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1298 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1299 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1300 creation, attributes);
1302 /* Open a console for CONIN$ or CONOUT$ */
1304 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1306 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1307 goto done;
1310 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1312 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1313 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1315 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1316 !strncmpiW( filename + 4, pipeW, 5 ) ||
1317 !strncmpiW( filename + 4, mailslotW, 9 ))
1319 dosdev = 0;
1321 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1323 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1325 else if (!(GetVersion() & 0x80000000))
1327 dosdev = 0;
1329 else if (filename[4])
1331 ret = VXD_Open( filename+4, access, sa );
1332 goto done;
1334 else
1336 SetLastError( ERROR_INVALID_NAME );
1337 return INVALID_HANDLE_VALUE;
1340 else dosdev = RtlIsDosDeviceName_U( filename );
1342 if (dosdev)
1344 static const WCHAR conW[] = {'C','O','N'};
1346 if (LOWORD(dosdev) == sizeof(conW) &&
1347 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1349 switch (access & (GENERIC_READ|GENERIC_WRITE))
1351 case GENERIC_READ:
1352 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1353 goto done;
1354 case GENERIC_WRITE:
1355 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1356 goto done;
1357 default:
1358 SetLastError( ERROR_FILE_NOT_FOUND );
1359 return INVALID_HANDLE_VALUE;
1364 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1366 SetLastError( ERROR_INVALID_PARAMETER );
1367 return INVALID_HANDLE_VALUE;
1370 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1372 SetLastError( ERROR_PATH_NOT_FOUND );
1373 return INVALID_HANDLE_VALUE;
1376 /* now call NtCreateFile */
1378 options = 0;
1379 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1380 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1381 else
1382 options |= FILE_NON_DIRECTORY_FILE;
1383 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1385 options |= FILE_DELETE_ON_CLOSE;
1386 access |= DELETE;
1388 if (!(attributes & FILE_FLAG_OVERLAPPED))
1389 options |= FILE_SYNCHRONOUS_IO_ALERT;
1390 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1391 options |= FILE_RANDOM_ACCESS;
1392 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1394 attr.Length = sizeof(attr);
1395 attr.RootDirectory = 0;
1396 attr.Attributes = OBJ_CASE_INSENSITIVE;
1397 attr.ObjectName = &nameW;
1398 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1399 if (attributes & SECURITY_SQOS_PRESENT)
1401 qos.Length = sizeof(qos);
1402 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1403 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1404 qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1405 attr.SecurityQualityOfService = &qos;
1407 else
1408 attr.SecurityQualityOfService = NULL;
1410 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1412 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1413 sharing, nt_disposition[creation - CREATE_NEW],
1414 options, NULL, 0 );
1415 if (status)
1417 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1418 ret = INVALID_HANDLE_VALUE;
1420 /* In the case file creation was rejected due to CREATE_NEW flag
1421 * was specified and file with that name already exists, correct
1422 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1423 * Note: RtlNtStatusToDosError is not the subject to blame here.
1425 if (status == STATUS_OBJECT_NAME_COLLISION)
1426 SetLastError( ERROR_FILE_EXISTS );
1427 else
1428 SetLastError( RtlNtStatusToDosError(status) );
1430 else
1432 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1433 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1434 SetLastError( ERROR_ALREADY_EXISTS );
1435 else
1436 SetLastError( 0 );
1438 RtlFreeUnicodeString( &nameW );
1440 done:
1441 if (!ret) ret = INVALID_HANDLE_VALUE;
1442 TRACE("returning %p\n", ret);
1443 return ret;
1448 /*************************************************************************
1449 * CreateFileA (KERNEL32.@)
1451 * See CreateFileW.
1453 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1454 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1455 DWORD attributes, HANDLE template)
1457 WCHAR *nameW;
1459 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1460 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1464 /***********************************************************************
1465 * DeleteFileW (KERNEL32.@)
1467 * Delete a file.
1469 * PARAMS
1470 * path [I] Path to the file to delete.
1472 * RETURNS
1473 * Success: TRUE.
1474 * Failure: FALSE, check GetLastError().
1476 BOOL WINAPI DeleteFileW( LPCWSTR path )
1478 UNICODE_STRING nameW;
1479 OBJECT_ATTRIBUTES attr;
1480 NTSTATUS status;
1482 TRACE("%s\n", debugstr_w(path) );
1484 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1486 SetLastError( ERROR_PATH_NOT_FOUND );
1487 return FALSE;
1490 attr.Length = sizeof(attr);
1491 attr.RootDirectory = 0;
1492 attr.Attributes = OBJ_CASE_INSENSITIVE;
1493 attr.ObjectName = &nameW;
1494 attr.SecurityDescriptor = NULL;
1495 attr.SecurityQualityOfService = NULL;
1497 status = NtDeleteFile(&attr);
1498 RtlFreeUnicodeString( &nameW );
1499 if (status)
1501 SetLastError( RtlNtStatusToDosError(status) );
1502 return FALSE;
1504 return TRUE;
1508 /***********************************************************************
1509 * DeleteFileA (KERNEL32.@)
1511 * See DeleteFileW.
1513 BOOL WINAPI DeleteFileA( LPCSTR path )
1515 WCHAR *pathW;
1517 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1518 return DeleteFileW( pathW );
1522 /**************************************************************************
1523 * ReplaceFileW (KERNEL32.@)
1524 * ReplaceFile (KERNEL32.@)
1526 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1527 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1528 LPVOID lpExclude, LPVOID lpReserved)
1530 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1531 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1532 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1533 DWORD error = ERROR_SUCCESS;
1534 UINT replaced_flags;
1535 BOOL ret = FALSE;
1536 NTSTATUS status;
1537 IO_STATUS_BLOCK io;
1538 OBJECT_ATTRIBUTES attr;
1540 if (dwReplaceFlags)
1541 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1543 /* First two arguments are mandatory */
1544 if (!lpReplacedFileName || !lpReplacementFileName)
1546 SetLastError(ERROR_INVALID_PARAMETER);
1547 return FALSE;
1550 unix_replaced_name.Buffer = NULL;
1551 unix_replacement_name.Buffer = NULL;
1552 unix_backup_name.Buffer = NULL;
1554 attr.Length = sizeof(attr);
1555 attr.RootDirectory = 0;
1556 attr.Attributes = OBJ_CASE_INSENSITIVE;
1557 attr.ObjectName = NULL;
1558 attr.SecurityDescriptor = NULL;
1559 attr.SecurityQualityOfService = NULL;
1561 /* Open the "replaced" file for reading and writing */
1562 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1564 error = ERROR_PATH_NOT_FOUND;
1565 goto fail;
1567 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1568 attr.ObjectName = &nt_replaced_name;
1569 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1570 &attr, &io,
1571 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1572 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1573 if (status == STATUS_SUCCESS)
1574 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1575 RtlFreeUnicodeString(&nt_replaced_name);
1576 if (status != STATUS_SUCCESS)
1578 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1579 error = ERROR_FILE_NOT_FOUND;
1580 else
1581 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1582 goto fail;
1586 * Open the replacement file for reading, writing, and deleting
1587 * (writing and deleting are needed when finished)
1589 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1591 error = ERROR_PATH_NOT_FOUND;
1592 goto fail;
1594 attr.ObjectName = &nt_replacement_name;
1595 status = NtOpenFile(&hReplacement,
1596 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1597 &attr, &io, 0,
1598 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1599 if (status == STATUS_SUCCESS)
1600 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1601 RtlFreeUnicodeString(&nt_replacement_name);
1602 if (status != STATUS_SUCCESS)
1604 error = RtlNtStatusToDosError(status);
1605 goto fail;
1608 /* If the user wants a backup then that needs to be performed first */
1609 if (lpBackupFileName)
1611 UNICODE_STRING nt_backup_name;
1612 FILE_BASIC_INFORMATION replaced_info;
1614 /* Obtain the file attributes from the "replaced" file */
1615 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1616 sizeof(replaced_info),
1617 FileBasicInformation);
1618 if (status != STATUS_SUCCESS)
1620 error = RtlNtStatusToDosError(status);
1621 goto fail;
1624 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1626 error = ERROR_PATH_NOT_FOUND;
1627 goto fail;
1629 attr.ObjectName = &nt_backup_name;
1630 /* Open the backup with permissions to write over it */
1631 status = NtCreateFile(&hBackup, GENERIC_WRITE,
1632 &attr, &io, NULL, replaced_info.FileAttributes,
1633 FILE_SHARE_WRITE, FILE_OPEN_IF,
1634 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1635 NULL, 0);
1636 if (status == STATUS_SUCCESS)
1637 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1638 if (status != STATUS_SUCCESS)
1640 error = RtlNtStatusToDosError(status);
1641 goto fail;
1644 /* If an existing backup exists then copy over it */
1645 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1647 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1648 goto fail;
1653 * Now that the backup has been performed (if requested), copy the replacement
1654 * into place
1656 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1658 if (errno == EACCES)
1660 /* Inappropriate permissions on "replaced", rename will fail */
1661 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1662 goto fail;
1664 /* on failure we need to indicate whether a backup was made */
1665 if (!lpBackupFileName)
1666 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1667 else
1668 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1669 goto fail;
1671 /* Success! */
1672 ret = TRUE;
1674 /* Perform resource cleanup */
1675 fail:
1676 if (hBackup) CloseHandle(hBackup);
1677 if (hReplaced) CloseHandle(hReplaced);
1678 if (hReplacement) CloseHandle(hReplacement);
1679 RtlFreeAnsiString(&unix_backup_name);
1680 RtlFreeAnsiString(&unix_replacement_name);
1681 RtlFreeAnsiString(&unix_replaced_name);
1683 /* If there was an error, set the error code */
1684 if(!ret)
1685 SetLastError(error);
1686 return ret;
1690 /**************************************************************************
1691 * ReplaceFileA (KERNEL32.@)
1693 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1694 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1695 LPVOID lpExclude, LPVOID lpReserved)
1697 WCHAR *replacedW, *replacementW, *backupW = NULL;
1698 BOOL ret;
1700 /* This function only makes sense when the first two parameters are defined */
1701 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1703 SetLastError(ERROR_INVALID_PARAMETER);
1704 return FALSE;
1706 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1708 HeapFree( GetProcessHeap(), 0, replacedW );
1709 SetLastError(ERROR_INVALID_PARAMETER);
1710 return FALSE;
1712 /* The backup parameter, however, is optional */
1713 if (lpBackupFileName)
1715 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1717 HeapFree( GetProcessHeap(), 0, replacedW );
1718 HeapFree( GetProcessHeap(), 0, replacementW );
1719 SetLastError(ERROR_INVALID_PARAMETER);
1720 return FALSE;
1723 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1724 HeapFree( GetProcessHeap(), 0, replacedW );
1725 HeapFree( GetProcessHeap(), 0, replacementW );
1726 HeapFree( GetProcessHeap(), 0, backupW );
1727 return ret;
1731 /*************************************************************************
1732 * FindFirstFileExW (KERNEL32.@)
1734 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1735 * results as FindExSearchNameMatch
1737 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1738 LPVOID data, FINDEX_SEARCH_OPS search_op,
1739 LPVOID filter, DWORD flags)
1741 WCHAR *mask, *p;
1742 FIND_FIRST_INFO *info = NULL;
1743 UNICODE_STRING nt_name;
1744 OBJECT_ATTRIBUTES attr;
1745 IO_STATUS_BLOCK io;
1746 NTSTATUS status;
1747 DWORD device = 0;
1749 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1751 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1752 || flags != 0)
1754 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1755 return INVALID_HANDLE_VALUE;
1757 if (level != FindExInfoStandard)
1759 FIXME("info level %d not implemented\n", level );
1760 return INVALID_HANDLE_VALUE;
1763 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1765 SetLastError( ERROR_PATH_NOT_FOUND );
1766 return INVALID_HANDLE_VALUE;
1769 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1771 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1772 goto error;
1775 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1777 static const WCHAR dotW[] = {'.',0};
1778 WCHAR *dir = NULL;
1780 /* we still need to check that the directory can be opened */
1782 if (HIWORD(device))
1784 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1786 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1787 goto error;
1789 memcpy( dir, filename, HIWORD(device) );
1790 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1792 RtlFreeUnicodeString( &nt_name );
1793 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1795 HeapFree( GetProcessHeap(), 0, dir );
1796 SetLastError( ERROR_PATH_NOT_FOUND );
1797 goto error;
1799 HeapFree( GetProcessHeap(), 0, dir );
1800 RtlInitUnicodeString( &info->mask, NULL );
1802 else if (!mask || !*mask)
1804 SetLastError( ERROR_FILE_NOT_FOUND );
1805 goto error;
1807 else
1809 if (!RtlCreateUnicodeString( &info->mask, mask ))
1811 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1812 goto error;
1815 /* truncate dir name before mask */
1816 *mask = 0;
1817 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1820 /* check if path is the root of the drive */
1821 info->is_root = FALSE;
1822 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1823 if (p[0] && p[1] == ':')
1825 p += 2;
1826 while (*p == '\\') p++;
1827 info->is_root = (*p == 0);
1830 attr.Length = sizeof(attr);
1831 attr.RootDirectory = 0;
1832 attr.Attributes = OBJ_CASE_INSENSITIVE;
1833 attr.ObjectName = &nt_name;
1834 attr.SecurityDescriptor = NULL;
1835 attr.SecurityQualityOfService = NULL;
1837 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1838 FILE_SHARE_READ | FILE_SHARE_WRITE,
1839 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1841 if (status != STATUS_SUCCESS)
1843 RtlFreeUnicodeString( &info->mask );
1844 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1845 SetLastError( ERROR_PATH_NOT_FOUND );
1846 else
1847 SetLastError( RtlNtStatusToDosError(status) );
1848 goto error;
1851 RtlInitializeCriticalSection( &info->cs );
1852 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1853 info->path = nt_name;
1854 info->magic = FIND_FIRST_MAGIC;
1855 info->data_pos = 0;
1856 info->data_len = 0;
1857 info->search_op = search_op;
1859 if (device)
1861 WIN32_FIND_DATAW *wfd = data;
1863 memset( wfd, 0, sizeof(*wfd) );
1864 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1865 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1866 CloseHandle( info->handle );
1867 info->handle = 0;
1869 else
1871 IO_STATUS_BLOCK io;
1873 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1874 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1875 if (io.u.Status)
1877 FindClose( info );
1878 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1879 return INVALID_HANDLE_VALUE;
1881 info->data_len = io.Information;
1882 if (!FindNextFileW( info, data ))
1884 TRACE( "%s not found\n", debugstr_w(filename) );
1885 FindClose( info );
1886 SetLastError( ERROR_FILE_NOT_FOUND );
1887 return INVALID_HANDLE_VALUE;
1889 if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1891 /* we can't find two files with the same name */
1892 CloseHandle( info->handle );
1893 info->handle = 0;
1896 return info;
1898 error:
1899 HeapFree( GetProcessHeap(), 0, info );
1900 RtlFreeUnicodeString( &nt_name );
1901 return INVALID_HANDLE_VALUE;
1905 /*************************************************************************
1906 * FindNextFileW (KERNEL32.@)
1908 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1910 FIND_FIRST_INFO *info;
1911 FILE_BOTH_DIR_INFORMATION *dir_info;
1912 BOOL ret = FALSE;
1914 TRACE("%p %p\n", handle, data);
1916 if (!handle || handle == INVALID_HANDLE_VALUE)
1918 SetLastError( ERROR_INVALID_HANDLE );
1919 return ret;
1921 info = (FIND_FIRST_INFO *)handle;
1922 if (info->magic != FIND_FIRST_MAGIC)
1924 SetLastError( ERROR_INVALID_HANDLE );
1925 return ret;
1928 RtlEnterCriticalSection( &info->cs );
1930 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1931 else for (;;)
1933 if (info->data_pos >= info->data_len) /* need to read some more data */
1935 IO_STATUS_BLOCK io;
1937 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1938 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1939 if (io.u.Status)
1941 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1942 if (io.u.Status == STATUS_NO_MORE_FILES)
1944 CloseHandle( info->handle );
1945 info->handle = 0;
1947 break;
1949 info->data_len = io.Information;
1950 info->data_pos = 0;
1953 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1955 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1956 else info->data_pos = info->data_len;
1958 /* don't return '.' and '..' in the root of the drive */
1959 if (info->is_root)
1961 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1962 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1963 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1966 /* check for dir symlink */
1967 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1968 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1969 strpbrkW( info->mask.Buffer, wildcardsW ))
1971 if (!check_dir_symlink( info, dir_info )) continue;
1974 data->dwFileAttributes = dir_info->FileAttributes;
1975 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1976 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1977 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1978 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1979 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1980 data->dwReserved0 = 0;
1981 data->dwReserved1 = 0;
1983 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1984 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1985 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1986 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1988 TRACE("returning %s (%s)\n",
1989 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1991 ret = TRUE;
1992 break;
1995 RtlLeaveCriticalSection( &info->cs );
1996 return ret;
2000 /*************************************************************************
2001 * FindClose (KERNEL32.@)
2003 BOOL WINAPI FindClose( HANDLE handle )
2005 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
2007 if (!handle || handle == INVALID_HANDLE_VALUE)
2009 SetLastError( ERROR_INVALID_HANDLE );
2010 return FALSE;
2013 __TRY
2015 if (info->magic == FIND_FIRST_MAGIC)
2017 RtlEnterCriticalSection( &info->cs );
2018 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2020 info->magic = 0;
2021 if (info->handle) CloseHandle( info->handle );
2022 info->handle = 0;
2023 RtlFreeUnicodeString( &info->mask );
2024 info->mask.Buffer = NULL;
2025 RtlFreeUnicodeString( &info->path );
2026 info->data_pos = 0;
2027 info->data_len = 0;
2028 RtlLeaveCriticalSection( &info->cs );
2029 info->cs.DebugInfo->Spare[0] = 0;
2030 RtlDeleteCriticalSection( &info->cs );
2031 HeapFree( GetProcessHeap(), 0, info );
2035 __EXCEPT_PAGE_FAULT
2037 WARN("Illegal handle %p\n", handle);
2038 SetLastError( ERROR_INVALID_HANDLE );
2039 return FALSE;
2041 __ENDTRY
2043 return TRUE;
2047 /*************************************************************************
2048 * FindFirstFileA (KERNEL32.@)
2050 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2052 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2053 FindExSearchNameMatch, NULL, 0);
2056 /*************************************************************************
2057 * FindFirstFileExA (KERNEL32.@)
2059 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2060 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2061 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2063 HANDLE handle;
2064 WIN32_FIND_DATAA *dataA;
2065 WIN32_FIND_DATAW dataW;
2066 WCHAR *nameW;
2068 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2070 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2071 if (handle == INVALID_HANDLE_VALUE) return handle;
2073 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
2074 dataA->dwFileAttributes = dataW.dwFileAttributes;
2075 dataA->ftCreationTime = dataW.ftCreationTime;
2076 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2077 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2078 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2079 dataA->nFileSizeLow = dataW.nFileSizeLow;
2080 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2081 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2082 sizeof(dataA->cAlternateFileName) );
2083 return handle;
2087 /*************************************************************************
2088 * FindFirstFileW (KERNEL32.@)
2090 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2092 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2093 FindExSearchNameMatch, NULL, 0);
2097 /*************************************************************************
2098 * FindNextFileA (KERNEL32.@)
2100 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2102 WIN32_FIND_DATAW dataW;
2104 if (!FindNextFileW( handle, &dataW )) return FALSE;
2105 data->dwFileAttributes = dataW.dwFileAttributes;
2106 data->ftCreationTime = dataW.ftCreationTime;
2107 data->ftLastAccessTime = dataW.ftLastAccessTime;
2108 data->ftLastWriteTime = dataW.ftLastWriteTime;
2109 data->nFileSizeHigh = dataW.nFileSizeHigh;
2110 data->nFileSizeLow = dataW.nFileSizeLow;
2111 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2112 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2113 sizeof(data->cAlternateFileName) );
2114 return TRUE;
2118 /**************************************************************************
2119 * GetFileAttributesW (KERNEL32.@)
2121 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2123 FILE_BASIC_INFORMATION info;
2124 UNICODE_STRING nt_name;
2125 OBJECT_ATTRIBUTES attr;
2126 NTSTATUS status;
2128 TRACE("%s\n", debugstr_w(name));
2130 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2132 SetLastError( ERROR_PATH_NOT_FOUND );
2133 return INVALID_FILE_ATTRIBUTES;
2136 attr.Length = sizeof(attr);
2137 attr.RootDirectory = 0;
2138 attr.Attributes = OBJ_CASE_INSENSITIVE;
2139 attr.ObjectName = &nt_name;
2140 attr.SecurityDescriptor = NULL;
2141 attr.SecurityQualityOfService = NULL;
2143 status = NtQueryAttributesFile( &attr, &info );
2144 RtlFreeUnicodeString( &nt_name );
2146 if (status == STATUS_SUCCESS) return info.FileAttributes;
2148 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2149 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2151 SetLastError( RtlNtStatusToDosError(status) );
2152 return INVALID_FILE_ATTRIBUTES;
2156 /**************************************************************************
2157 * GetFileAttributesA (KERNEL32.@)
2159 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2161 WCHAR *nameW;
2163 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2164 return GetFileAttributesW( nameW );
2168 /**************************************************************************
2169 * SetFileAttributesW (KERNEL32.@)
2171 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2173 UNICODE_STRING nt_name;
2174 OBJECT_ATTRIBUTES attr;
2175 IO_STATUS_BLOCK io;
2176 NTSTATUS status;
2177 HANDLE handle;
2179 TRACE("%s %x\n", debugstr_w(name), attributes);
2181 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2183 SetLastError( ERROR_PATH_NOT_FOUND );
2184 return FALSE;
2187 attr.Length = sizeof(attr);
2188 attr.RootDirectory = 0;
2189 attr.Attributes = OBJ_CASE_INSENSITIVE;
2190 attr.ObjectName = &nt_name;
2191 attr.SecurityDescriptor = NULL;
2192 attr.SecurityQualityOfService = NULL;
2194 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2195 RtlFreeUnicodeString( &nt_name );
2197 if (status == STATUS_SUCCESS)
2199 FILE_BASIC_INFORMATION info;
2201 memset( &info, 0, sizeof(info) );
2202 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2203 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2204 NtClose( handle );
2207 if (status == STATUS_SUCCESS) return TRUE;
2208 SetLastError( RtlNtStatusToDosError(status) );
2209 return FALSE;
2213 /**************************************************************************
2214 * SetFileAttributesA (KERNEL32.@)
2216 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2218 WCHAR *nameW;
2220 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2221 return SetFileAttributesW( nameW, attributes );
2225 /**************************************************************************
2226 * GetFileAttributesExW (KERNEL32.@)
2228 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2230 FILE_NETWORK_OPEN_INFORMATION info;
2231 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2232 UNICODE_STRING nt_name;
2233 OBJECT_ATTRIBUTES attr;
2234 NTSTATUS status;
2236 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2238 if (level != GetFileExInfoStandard)
2240 SetLastError( ERROR_INVALID_PARAMETER );
2241 return FALSE;
2244 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2246 SetLastError( ERROR_PATH_NOT_FOUND );
2247 return FALSE;
2250 attr.Length = sizeof(attr);
2251 attr.RootDirectory = 0;
2252 attr.Attributes = OBJ_CASE_INSENSITIVE;
2253 attr.ObjectName = &nt_name;
2254 attr.SecurityDescriptor = NULL;
2255 attr.SecurityQualityOfService = NULL;
2257 status = NtQueryFullAttributesFile( &attr, &info );
2258 RtlFreeUnicodeString( &nt_name );
2260 if (status != STATUS_SUCCESS)
2262 SetLastError( RtlNtStatusToDosError(status) );
2263 return FALSE;
2266 data->dwFileAttributes = info.FileAttributes;
2267 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2268 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2269 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2270 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2271 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2272 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2273 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2274 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2275 return TRUE;
2279 /**************************************************************************
2280 * GetFileAttributesExA (KERNEL32.@)
2282 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2284 WCHAR *nameW;
2286 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2287 return GetFileAttributesExW( nameW, level, ptr );
2291 /******************************************************************************
2292 * GetCompressedFileSizeW (KERNEL32.@)
2294 * Get the actual number of bytes used on disk.
2296 * RETURNS
2297 * Success: Low-order doubleword of number of bytes
2298 * Failure: INVALID_FILE_SIZE
2300 DWORD WINAPI GetCompressedFileSizeW(
2301 LPCWSTR name, /* [in] Pointer to name of file */
2302 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2304 UNICODE_STRING nt_name;
2305 OBJECT_ATTRIBUTES attr;
2306 IO_STATUS_BLOCK io;
2307 NTSTATUS status;
2308 HANDLE handle;
2309 DWORD ret = INVALID_FILE_SIZE;
2311 TRACE("%s %p\n", debugstr_w(name), size_high);
2313 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2315 SetLastError( ERROR_PATH_NOT_FOUND );
2316 return INVALID_FILE_SIZE;
2319 attr.Length = sizeof(attr);
2320 attr.RootDirectory = 0;
2321 attr.Attributes = OBJ_CASE_INSENSITIVE;
2322 attr.ObjectName = &nt_name;
2323 attr.SecurityDescriptor = NULL;
2324 attr.SecurityQualityOfService = NULL;
2326 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2327 RtlFreeUnicodeString( &nt_name );
2329 if (status == STATUS_SUCCESS)
2331 /* we don't support compressed files, simply return the file size */
2332 ret = GetFileSize( handle, size_high );
2333 NtClose( handle );
2335 else SetLastError( RtlNtStatusToDosError(status) );
2337 return ret;
2341 /******************************************************************************
2342 * GetCompressedFileSizeA (KERNEL32.@)
2344 * See GetCompressedFileSizeW.
2346 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2348 WCHAR *nameW;
2350 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2351 return GetCompressedFileSizeW( nameW, size_high );
2355 /***********************************************************************
2356 * OpenFile (KERNEL32.@)
2358 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2360 HANDLE handle;
2361 FILETIME filetime;
2362 WORD filedatetime[2];
2364 if (!ofs) return HFILE_ERROR;
2366 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2367 ((mode & 0x3 )==OF_READ)?"OF_READ":
2368 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2369 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2370 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2371 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2372 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2373 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2374 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2375 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2376 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2377 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2378 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2379 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2380 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2381 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2382 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2383 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2387 ofs->cBytes = sizeof(OFSTRUCT);
2388 ofs->nErrCode = 0;
2389 if (mode & OF_REOPEN) name = ofs->szPathName;
2391 if (!name) return HFILE_ERROR;
2393 TRACE("%s %04x\n", name, mode );
2395 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2396 Are there any cases where getting the path here is wrong?
2397 Uwe Bonnes 1997 Apr 2 */
2398 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2400 /* OF_PARSE simply fills the structure */
2402 if (mode & OF_PARSE)
2404 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2405 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2406 return 0;
2409 /* OF_CREATE is completely different from all other options, so
2410 handle it first */
2412 if (mode & OF_CREATE)
2414 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2415 goto error;
2417 else
2419 /* Now look for the file */
2421 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2422 goto error;
2424 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2426 if (mode & OF_DELETE)
2428 if (!DeleteFileA( ofs->szPathName )) goto error;
2429 TRACE("(%s): OF_DELETE return = OK\n", name);
2430 return TRUE;
2433 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2434 if (handle == INVALID_HANDLE_VALUE) goto error;
2436 GetFileTime( handle, NULL, NULL, &filetime );
2437 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2438 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2440 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2442 CloseHandle( handle );
2443 WARN("(%s): OF_VERIFY failed\n", name );
2444 /* FIXME: what error here? */
2445 SetLastError( ERROR_FILE_NOT_FOUND );
2446 goto error;
2449 ofs->Reserved1 = filedatetime[0];
2450 ofs->Reserved2 = filedatetime[1];
2452 TRACE("(%s): OK, return = %p\n", name, handle );
2453 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2455 CloseHandle( handle );
2456 return TRUE;
2458 return HandleToLong(handle);
2460 error: /* We get here if there was an error opening the file */
2461 ofs->nErrCode = GetLastError();
2462 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2463 return HFILE_ERROR;