msi: Read the disk prompt source list property from the user-unmanaged context.
[wine.git] / dlls / kernel32 / file.c
bloba5da6c66efa4fc7e22010f28401dd6c6bf991d31
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"
48 #include "thread.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(file);
52 HANDLE dos_handles[DOS_TABLE_SIZE];
54 /* info structure for FindFirstFile handle */
55 typedef struct
57 DWORD magic; /* magic number */
58 HANDLE handle; /* handle to directory */
59 CRITICAL_SECTION cs; /* crit section protecting this structure */
60 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
61 UNICODE_STRING mask; /* file mask */
62 UNICODE_STRING path; /* NT path used to open the directory */
63 BOOL is_root; /* is directory the root of the drive? */
64 UINT data_pos; /* current position in dir data */
65 UINT data_len; /* length of dir data */
66 BYTE data[8192]; /* directory data */
67 } FIND_FIRST_INFO;
69 #define FIND_FIRST_MAGIC 0xc0ffee11
71 static BOOL oem_file_apis;
73 static const WCHAR wildcardsW[] = { '*','?',0 };
75 /***********************************************************************
76 * create_file_OF
78 * Wrapper for CreateFile that takes OF_* mode flags.
80 static HANDLE create_file_OF( LPCSTR path, INT mode )
82 DWORD access, sharing, creation;
84 if (mode & OF_CREATE)
86 creation = CREATE_ALWAYS;
87 access = GENERIC_READ | GENERIC_WRITE;
89 else
91 creation = OPEN_EXISTING;
92 switch(mode & 0x03)
94 case OF_READ: access = GENERIC_READ; break;
95 case OF_WRITE: access = GENERIC_WRITE; break;
96 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
97 default: access = 0; break;
101 switch(mode & 0x70)
103 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
104 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
105 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
106 case OF_SHARE_DENY_NONE:
107 case OF_SHARE_COMPAT:
108 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
110 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
114 /***********************************************************************
115 * check_dir_symlink
117 * Check if a dir symlink should be returned by FindNextFile.
119 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
121 UNICODE_STRING str;
122 ANSI_STRING unix_name;
123 struct stat st, parent_st;
124 BOOL ret = TRUE;
125 DWORD len;
127 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
128 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
129 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
130 len = info->path.Length / sizeof(WCHAR);
131 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
132 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
133 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
135 unix_name.Buffer = NULL;
136 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
137 !stat( unix_name.Buffer, &st ))
139 char *p = unix_name.Buffer + unix_name.Length - 1;
141 /* skip trailing slashes */
142 while (p > unix_name.Buffer && *p == '/') p--;
144 while (ret && p > unix_name.Buffer)
146 while (p > unix_name.Buffer && *p != '/') p--;
147 while (p > unix_name.Buffer && *p == '/') p--;
148 p[1] = 0;
149 if (!stat( unix_name.Buffer, &parent_st ) &&
150 parent_st.st_dev == st.st_dev &&
151 parent_st.st_ino == st.st_ino)
153 WARN( "suppressing dir symlink %s pointing to parent %s\n",
154 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
155 debugstr_a( unix_name.Buffer ));
156 ret = FALSE;
160 RtlFreeAnsiString( &unix_name );
161 RtlFreeUnicodeString( &str );
162 return ret;
166 /***********************************************************************
167 * FILE_SetDosError
169 * Set the DOS error code from errno.
171 void FILE_SetDosError(void)
173 int save_errno = errno; /* errno gets overwritten by printf */
175 TRACE("errno = %d %s\n", errno, strerror(errno));
176 switch (save_errno)
178 case EAGAIN:
179 SetLastError( ERROR_SHARING_VIOLATION );
180 break;
181 case EBADF:
182 SetLastError( ERROR_INVALID_HANDLE );
183 break;
184 case ENOSPC:
185 SetLastError( ERROR_HANDLE_DISK_FULL );
186 break;
187 case EACCES:
188 case EPERM:
189 case EROFS:
190 SetLastError( ERROR_ACCESS_DENIED );
191 break;
192 case EBUSY:
193 SetLastError( ERROR_LOCK_VIOLATION );
194 break;
195 case ENOENT:
196 SetLastError( ERROR_FILE_NOT_FOUND );
197 break;
198 case EISDIR:
199 SetLastError( ERROR_CANNOT_MAKE );
200 break;
201 case ENFILE:
202 case EMFILE:
203 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
204 break;
205 case EEXIST:
206 SetLastError( ERROR_FILE_EXISTS );
207 break;
208 case EINVAL:
209 case ESPIPE:
210 SetLastError( ERROR_SEEK );
211 break;
212 case ENOTEMPTY:
213 SetLastError( ERROR_DIR_NOT_EMPTY );
214 break;
215 case ENOEXEC:
216 SetLastError( ERROR_BAD_FORMAT );
217 break;
218 case ENOTDIR:
219 SetLastError( ERROR_PATH_NOT_FOUND );
220 break;
221 case EXDEV:
222 SetLastError( ERROR_NOT_SAME_DEVICE );
223 break;
224 default:
225 WARN("unknown file error: %s\n", strerror(save_errno) );
226 SetLastError( ERROR_GEN_FAILURE );
227 break;
229 errno = save_errno;
233 /***********************************************************************
234 * FILE_name_AtoW
236 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
238 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
239 * there is no possibility for the function to do that twice, taking into
240 * account any called function.
242 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
244 ANSI_STRING str;
245 UNICODE_STRING strW, *pstrW;
246 NTSTATUS status;
248 RtlInitAnsiString( &str, name );
249 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
250 if (oem_file_apis)
251 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
252 else
253 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
254 if (status == STATUS_SUCCESS) return pstrW->Buffer;
256 if (status == STATUS_BUFFER_OVERFLOW)
257 SetLastError( ERROR_FILENAME_EXCED_RANGE );
258 else
259 SetLastError( RtlNtStatusToDosError(status) );
260 return NULL;
264 /***********************************************************************
265 * FILE_name_WtoA
267 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
269 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
271 DWORD ret;
273 if (srclen < 0) srclen = strlenW( src ) + 1;
274 if (oem_file_apis)
275 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
276 else
277 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
278 return ret;
282 /**************************************************************************
283 * SetFileApisToOEM (KERNEL32.@)
285 VOID WINAPI SetFileApisToOEM(void)
287 oem_file_apis = TRUE;
291 /**************************************************************************
292 * SetFileApisToANSI (KERNEL32.@)
294 VOID WINAPI SetFileApisToANSI(void)
296 oem_file_apis = FALSE;
300 /******************************************************************************
301 * AreFileApisANSI (KERNEL32.@)
303 * Determines if file functions are using ANSI
305 * RETURNS
306 * TRUE: Set of file functions is using ANSI code page
307 * FALSE: Set of file functions is using OEM code page
309 BOOL WINAPI AreFileApisANSI(void)
311 return !oem_file_apis;
315 /**************************************************************************
316 * Operations on file handles *
317 **************************************************************************/
319 /***********************************************************************
320 * FILE_InitProcessDosHandles
322 * Allocates the default DOS handles for a process. Called either by
323 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
325 static void FILE_InitProcessDosHandles( void )
327 static BOOL init_done /* = FALSE */;
328 HANDLE cp = GetCurrentProcess();
330 if (init_done) return;
331 init_done = TRUE;
332 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
333 0, TRUE, DUPLICATE_SAME_ACCESS);
334 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
335 0, TRUE, DUPLICATE_SAME_ACCESS);
336 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
337 0, TRUE, DUPLICATE_SAME_ACCESS);
338 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
339 0, TRUE, DUPLICATE_SAME_ACCESS);
340 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
341 0, TRUE, DUPLICATE_SAME_ACCESS);
345 /******************************************************************
346 * FILE_ReadWriteApc (internal)
348 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
350 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
352 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
356 /***********************************************************************
357 * ReadFileEx (KERNEL32.@)
359 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
360 LPOVERLAPPED overlapped,
361 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
363 LARGE_INTEGER offset;
364 NTSTATUS status;
365 PIO_STATUS_BLOCK io_status;
367 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
369 if (!overlapped)
371 SetLastError(ERROR_INVALID_PARAMETER);
372 return FALSE;
375 offset.u.LowPart = overlapped->u.s.Offset;
376 offset.u.HighPart = overlapped->u.s.OffsetHigh;
377 io_status = (PIO_STATUS_BLOCK)overlapped;
378 io_status->u.Status = STATUS_PENDING;
379 io_status->Information = 0;
381 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
382 io_status, buffer, bytesToRead, &offset, NULL);
384 if (status)
386 SetLastError( RtlNtStatusToDosError(status) );
387 return FALSE;
389 return TRUE;
393 /***********************************************************************
394 * ReadFile (KERNEL32.@)
396 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
397 LPDWORD bytesRead, LPOVERLAPPED overlapped )
399 LARGE_INTEGER offset;
400 PLARGE_INTEGER poffset = NULL;
401 IO_STATUS_BLOCK iosb;
402 PIO_STATUS_BLOCK io_status = &iosb;
403 HANDLE hEvent = 0;
404 NTSTATUS status;
405 LPVOID cvalue = NULL;
407 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
408 bytesRead, overlapped );
410 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
411 if (!bytesToRead) return TRUE;
413 if (is_console_handle(hFile))
414 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
416 if (overlapped != NULL)
418 offset.u.LowPart = overlapped->u.s.Offset;
419 offset.u.HighPart = overlapped->u.s.OffsetHigh;
420 poffset = &offset;
421 hEvent = overlapped->hEvent;
422 io_status = (PIO_STATUS_BLOCK)overlapped;
423 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
425 io_status->u.Status = STATUS_PENDING;
426 io_status->Information = 0;
428 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
430 if (status == STATUS_PENDING && !overlapped)
432 WaitForSingleObject( hFile, INFINITE );
433 status = io_status->u.Status;
436 if (status != STATUS_PENDING && bytesRead)
437 *bytesRead = io_status->Information;
439 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
441 SetLastError( RtlNtStatusToDosError(status) );
442 return FALSE;
444 return TRUE;
448 /***********************************************************************
449 * WriteFileEx (KERNEL32.@)
451 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
452 LPOVERLAPPED overlapped,
453 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
455 LARGE_INTEGER offset;
456 NTSTATUS status;
457 PIO_STATUS_BLOCK io_status;
459 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
461 if (overlapped == NULL)
463 SetLastError(ERROR_INVALID_PARAMETER);
464 return FALSE;
466 offset.u.LowPart = overlapped->u.s.Offset;
467 offset.u.HighPart = overlapped->u.s.OffsetHigh;
469 io_status = (PIO_STATUS_BLOCK)overlapped;
470 io_status->u.Status = STATUS_PENDING;
471 io_status->Information = 0;
473 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
474 io_status, buffer, bytesToWrite, &offset, NULL);
476 if (status) SetLastError( RtlNtStatusToDosError(status) );
477 return !status;
481 /***********************************************************************
482 * WriteFile (KERNEL32.@)
484 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
485 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
487 HANDLE hEvent = NULL;
488 LARGE_INTEGER offset;
489 PLARGE_INTEGER poffset = NULL;
490 NTSTATUS status;
491 IO_STATUS_BLOCK iosb;
492 PIO_STATUS_BLOCK piosb = &iosb;
493 LPVOID cvalue = NULL;
495 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
497 if (is_console_handle(hFile))
498 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
500 if (overlapped)
502 offset.u.LowPart = overlapped->u.s.Offset;
503 offset.u.HighPart = overlapped->u.s.OffsetHigh;
504 poffset = &offset;
505 hEvent = overlapped->hEvent;
506 piosb = (PIO_STATUS_BLOCK)overlapped;
507 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
509 piosb->u.Status = STATUS_PENDING;
510 piosb->Information = 0;
512 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
513 buffer, bytesToWrite, poffset, NULL);
515 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
516 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
518 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
519 buffer, bytesToWrite, poffset, NULL);
520 if (status != STATUS_INVALID_USER_BUFFER)
521 FIXME("Could not access memory (%p,%d) at first, now OK. Protected by DIBSection code?\n",
522 buffer, bytesToWrite);
525 if (status == STATUS_PENDING && !overlapped)
527 WaitForSingleObject( hFile, INFINITE );
528 status = piosb->u.Status;
531 if (status != STATUS_PENDING && bytesWritten)
532 *bytesWritten = piosb->Information;
534 if (status && status != STATUS_TIMEOUT)
536 SetLastError( RtlNtStatusToDosError(status) );
537 return FALSE;
539 return TRUE;
543 /***********************************************************************
544 * GetOverlappedResult (KERNEL32.@)
546 * Check the result of an Asynchronous data transfer from a file.
548 * Parameters
549 * HANDLE hFile [in] handle of file to check on
550 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
551 * LPDWORD lpTransferred [in/out] number of bytes transferred
552 * BOOL bWait [in] wait for the transfer to complete ?
554 * RETURNS
555 * TRUE on success
556 * FALSE on failure
558 * If successful (and relevant) lpTransferred will hold the number of
559 * bytes transferred during the async operation.
561 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
562 LPDWORD lpTransferred, BOOL bWait)
564 NTSTATUS status;
566 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
568 if ( lpOverlapped == NULL )
570 ERR("lpOverlapped was null\n");
571 return FALSE;
574 status = lpOverlapped->Internal;
575 if (status == STATUS_PENDING)
577 if (!bWait)
579 SetLastError( ERROR_IO_INCOMPLETE );
580 return FALSE;
583 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
584 INFINITE ) == WAIT_FAILED)
585 return FALSE;
586 status = lpOverlapped->Internal;
589 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
591 if (status) SetLastError( RtlNtStatusToDosError(status) );
592 return !status;
595 /***********************************************************************
596 * CancelIo (KERNEL32.@)
598 * Cancels pending I/O operations initiated by the current thread on a file.
600 * PARAMS
601 * handle [I] File handle.
603 * RETURNS
604 * Success: TRUE.
605 * Failure: FALSE, check GetLastError().
607 BOOL WINAPI CancelIo(HANDLE handle)
609 IO_STATUS_BLOCK io_status;
611 NtCancelIoFile(handle, &io_status);
612 if (io_status.u.Status)
614 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
615 return FALSE;
617 return TRUE;
620 /***********************************************************************
621 * _hread (KERNEL32.@)
623 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
625 return _lread( hFile, buffer, count );
629 /***********************************************************************
630 * _hwrite (KERNEL32.@)
632 * experimentation yields that _lwrite:
633 * o truncates the file at the current position with
634 * a 0 len write
635 * o returns 0 on a 0 length write
636 * o works with console handles
639 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
641 DWORD result;
643 TRACE("%d %p %d\n", handle, buffer, count );
645 if (!count)
647 /* Expand or truncate at current position */
648 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
649 return 0;
651 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
652 return HFILE_ERROR;
653 return result;
657 /***********************************************************************
658 * _lclose (KERNEL32.@)
660 HFILE WINAPI _lclose( HFILE hFile )
662 TRACE("handle %d\n", hFile );
663 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
667 /***********************************************************************
668 * _lcreat (KERNEL32.@)
670 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
672 HANDLE hfile;
674 /* Mask off all flags not explicitly allowed by the doc */
675 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
676 TRACE("%s %02x\n", path, attr );
677 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
678 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
679 CREATE_ALWAYS, attr, 0 );
680 return HandleToLong(hfile);
684 /***********************************************************************
685 * _lopen (KERNEL32.@)
687 HFILE WINAPI _lopen( LPCSTR path, INT mode )
689 HANDLE hfile;
691 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
692 hfile = create_file_OF( path, mode & ~OF_CREATE );
693 return HandleToLong(hfile);
696 /***********************************************************************
697 * _lread (KERNEL32.@)
699 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
701 DWORD result;
702 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
703 return HFILE_ERROR;
704 return result;
708 /***********************************************************************
709 * _llseek (KERNEL32.@)
711 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
713 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
717 /***********************************************************************
718 * _lwrite (KERNEL32.@)
720 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
722 return (UINT)_hwrite( hFile, buffer, (LONG)count );
726 /***********************************************************************
727 * FlushFileBuffers (KERNEL32.@)
729 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
731 NTSTATUS nts;
732 IO_STATUS_BLOCK ioblk;
734 if (is_console_handle( hFile ))
736 /* this will fail (as expected) for an output handle */
737 return FlushConsoleInputBuffer( hFile );
739 nts = NtFlushBuffersFile( hFile, &ioblk );
740 if (nts != STATUS_SUCCESS)
742 SetLastError( RtlNtStatusToDosError( nts ) );
743 return FALSE;
746 return TRUE;
750 /***********************************************************************
751 * GetFileType (KERNEL32.@)
753 DWORD WINAPI GetFileType( HANDLE hFile )
755 FILE_FS_DEVICE_INFORMATION info;
756 IO_STATUS_BLOCK io;
757 NTSTATUS status;
759 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
761 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
762 if (status != STATUS_SUCCESS)
764 SetLastError( RtlNtStatusToDosError(status) );
765 return FILE_TYPE_UNKNOWN;
768 switch(info.DeviceType)
770 case FILE_DEVICE_NULL:
771 case FILE_DEVICE_SERIAL_PORT:
772 case FILE_DEVICE_PARALLEL_PORT:
773 case FILE_DEVICE_TAPE:
774 case FILE_DEVICE_UNKNOWN:
775 return FILE_TYPE_CHAR;
776 case FILE_DEVICE_NAMED_PIPE:
777 return FILE_TYPE_PIPE;
778 default:
779 return FILE_TYPE_DISK;
784 /***********************************************************************
785 * GetFileInformationByHandle (KERNEL32.@)
787 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
789 FILE_ALL_INFORMATION all_info;
790 IO_STATUS_BLOCK io;
791 NTSTATUS status;
793 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
794 if (status == STATUS_SUCCESS)
796 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
797 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
798 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
799 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
800 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
801 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
802 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
803 info->dwVolumeSerialNumber = 0; /* FIXME */
804 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
805 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
806 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
807 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
808 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
809 return TRUE;
811 SetLastError( RtlNtStatusToDosError(status) );
812 return FALSE;
816 /***********************************************************************
817 * GetFileSize (KERNEL32.@)
819 * Retrieve the size of a file.
821 * PARAMS
822 * hFile [I] File to retrieve size of.
823 * filesizehigh [O] On return, the high bits of the file size.
825 * RETURNS
826 * Success: The low bits of the file size.
827 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
828 * check GetLastError() for values other than ERROR_SUCCESS.
830 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
832 LARGE_INTEGER size;
833 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
834 if (filesizehigh) *filesizehigh = size.u.HighPart;
835 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
836 return size.u.LowPart;
840 /***********************************************************************
841 * GetFileSizeEx (KERNEL32.@)
843 * Retrieve the size of a file.
845 * PARAMS
846 * hFile [I] File to retrieve size of.
847 * lpFileSIze [O] On return, the size of the file.
849 * RETURNS
850 * Success: TRUE.
851 * Failure: FALSE, check GetLastError().
853 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
855 FILE_END_OF_FILE_INFORMATION info;
856 IO_STATUS_BLOCK io;
857 NTSTATUS status;
859 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
860 if (status == STATUS_SUCCESS)
862 *lpFileSize = info.EndOfFile;
863 return TRUE;
865 SetLastError( RtlNtStatusToDosError(status) );
866 return FALSE;
870 /**************************************************************************
871 * SetEndOfFile (KERNEL32.@)
873 * Sets the current position as the end of the file.
875 * PARAMS
876 * hFile [I] File handle.
878 * RETURNS
879 * Success: TRUE.
880 * Failure: FALSE, check GetLastError().
882 BOOL WINAPI SetEndOfFile( HANDLE hFile )
884 FILE_POSITION_INFORMATION pos;
885 FILE_END_OF_FILE_INFORMATION eof;
886 IO_STATUS_BLOCK io;
887 NTSTATUS status;
889 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
890 if (status == STATUS_SUCCESS)
892 eof.EndOfFile = pos.CurrentByteOffset;
893 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
895 if (status == STATUS_SUCCESS) return TRUE;
896 SetLastError( RtlNtStatusToDosError(status) );
897 return FALSE;
901 /***********************************************************************
902 * SetFilePointer (KERNEL32.@)
904 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
906 LARGE_INTEGER dist, newpos;
908 if (highword)
910 dist.u.LowPart = distance;
911 dist.u.HighPart = *highword;
913 else dist.QuadPart = distance;
915 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
917 if (highword) *highword = newpos.u.HighPart;
918 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
919 return newpos.u.LowPart;
923 /***********************************************************************
924 * SetFilePointerEx (KERNEL32.@)
926 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
927 LARGE_INTEGER *newpos, DWORD method )
929 LONGLONG pos;
930 IO_STATUS_BLOCK io;
931 FILE_POSITION_INFORMATION info;
933 switch(method)
935 case FILE_BEGIN:
936 pos = distance.QuadPart;
937 break;
938 case FILE_CURRENT:
939 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
940 goto error;
941 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
942 break;
943 case FILE_END:
945 FILE_END_OF_FILE_INFORMATION eof;
946 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
947 goto error;
948 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
950 break;
951 default:
952 SetLastError( ERROR_INVALID_PARAMETER );
953 return FALSE;
956 if (pos < 0)
958 SetLastError( ERROR_NEGATIVE_SEEK );
959 return FALSE;
962 info.CurrentByteOffset.QuadPart = pos;
963 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
964 goto error;
965 if (newpos) newpos->QuadPart = pos;
966 return TRUE;
968 error:
969 SetLastError( RtlNtStatusToDosError(io.u.Status) );
970 return FALSE;
973 /***********************************************************************
974 * GetFileTime (KERNEL32.@)
976 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
977 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
979 FILE_BASIC_INFORMATION info;
980 IO_STATUS_BLOCK io;
981 NTSTATUS status;
983 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
984 if (status == STATUS_SUCCESS)
986 if (lpCreationTime)
988 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
989 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
991 if (lpLastAccessTime)
993 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
994 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
996 if (lpLastWriteTime)
998 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
999 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1001 return TRUE;
1003 SetLastError( RtlNtStatusToDosError(status) );
1004 return FALSE;
1008 /***********************************************************************
1009 * SetFileTime (KERNEL32.@)
1011 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1012 const FILETIME *atime, const FILETIME *mtime )
1014 FILE_BASIC_INFORMATION info;
1015 IO_STATUS_BLOCK io;
1016 NTSTATUS status;
1018 memset( &info, 0, sizeof(info) );
1019 if (ctime)
1021 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1022 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1024 if (atime)
1026 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1027 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1029 if (mtime)
1031 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1032 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1035 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1036 if (status == STATUS_SUCCESS) return TRUE;
1037 SetLastError( RtlNtStatusToDosError(status) );
1038 return FALSE;
1042 /**************************************************************************
1043 * LockFile (KERNEL32.@)
1045 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1046 DWORD count_low, DWORD count_high )
1048 NTSTATUS status;
1049 LARGE_INTEGER count, offset;
1051 TRACE( "%p %x%08x %x%08x\n",
1052 hFile, offset_high, offset_low, count_high, count_low );
1054 count.u.LowPart = count_low;
1055 count.u.HighPart = count_high;
1056 offset.u.LowPart = offset_low;
1057 offset.u.HighPart = offset_high;
1059 status = NtLockFile( hFile, 0, NULL, NULL,
1060 NULL, &offset, &count, NULL, TRUE, TRUE );
1062 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1063 return !status;
1067 /**************************************************************************
1068 * LockFileEx [KERNEL32.@]
1070 * Locks a byte range within an open file for shared or exclusive access.
1072 * RETURNS
1073 * success: TRUE
1074 * failure: FALSE
1076 * NOTES
1077 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1079 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1080 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1082 NTSTATUS status;
1083 LARGE_INTEGER count, offset;
1084 LPVOID cvalue = NULL;
1086 if (reserved)
1088 SetLastError( ERROR_INVALID_PARAMETER );
1089 return FALSE;
1092 TRACE( "%p %x%08x %x%08x flags %x\n",
1093 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1094 count_high, count_low, flags );
1096 count.u.LowPart = count_low;
1097 count.u.HighPart = count_high;
1098 offset.u.LowPart = overlapped->u.s.Offset;
1099 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1101 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1103 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1104 NULL, &offset, &count, NULL,
1105 flags & LOCKFILE_FAIL_IMMEDIATELY,
1106 flags & LOCKFILE_EXCLUSIVE_LOCK );
1108 if (status) SetLastError( RtlNtStatusToDosError(status) );
1109 return !status;
1113 /**************************************************************************
1114 * UnlockFile (KERNEL32.@)
1116 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1117 DWORD count_low, DWORD count_high )
1119 NTSTATUS status;
1120 LARGE_INTEGER count, offset;
1122 count.u.LowPart = count_low;
1123 count.u.HighPart = count_high;
1124 offset.u.LowPart = offset_low;
1125 offset.u.HighPart = offset_high;
1127 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1128 if (status) SetLastError( RtlNtStatusToDosError(status) );
1129 return !status;
1133 /**************************************************************************
1134 * UnlockFileEx (KERNEL32.@)
1136 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1137 LPOVERLAPPED overlapped )
1139 if (reserved)
1141 SetLastError( ERROR_INVALID_PARAMETER );
1142 return FALSE;
1144 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1146 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1150 /***********************************************************************
1151 * Win32HandleToDosFileHandle (KERNEL32.21)
1153 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1154 * longer valid after this function (even on failure).
1156 * Note: this is not exactly right, since on Win95 the Win32 handles
1157 * are on top of DOS handles and we do it the other way
1158 * around. Should be good enough though.
1160 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1162 int i;
1164 if (!handle || (handle == INVALID_HANDLE_VALUE))
1165 return HFILE_ERROR;
1167 FILE_InitProcessDosHandles();
1168 for (i = 0; i < DOS_TABLE_SIZE; i++)
1169 if (!dos_handles[i])
1171 dos_handles[i] = handle;
1172 TRACE("Got %d for h32 %p\n", i, handle );
1173 return (HFILE)i;
1175 CloseHandle( handle );
1176 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1177 return HFILE_ERROR;
1181 /***********************************************************************
1182 * DosFileHandleToWin32Handle (KERNEL32.20)
1184 * Return the Win32 handle for a DOS handle.
1186 * Note: this is not exactly right, since on Win95 the Win32 handles
1187 * are on top of DOS handles and we do it the other way
1188 * around. Should be good enough though.
1190 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1192 HFILE16 hfile = (HFILE16)handle;
1193 if (hfile < 5) FILE_InitProcessDosHandles();
1194 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1196 SetLastError( ERROR_INVALID_HANDLE );
1197 return INVALID_HANDLE_VALUE;
1199 return dos_handles[hfile];
1203 /*************************************************************************
1204 * SetHandleCount (KERNEL32.@)
1206 UINT WINAPI SetHandleCount( UINT count )
1208 return min( 256, count );
1212 /***********************************************************************
1213 * DisposeLZ32Handle (KERNEL32.22)
1215 * Note: this is not entirely correct, we should only close the
1216 * 32-bit handle and not the 16-bit one, but we cannot do
1217 * this because of the way our DOS handles are implemented.
1218 * It shouldn't break anything though.
1220 void WINAPI DisposeLZ32Handle( HANDLE handle )
1222 int i;
1224 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1226 for (i = 5; i < DOS_TABLE_SIZE; i++)
1227 if (dos_handles[i] == handle)
1229 dos_handles[i] = 0;
1230 CloseHandle( handle );
1231 break;
1235 /**************************************************************************
1236 * Operations on file names *
1237 **************************************************************************/
1240 /*************************************************************************
1241 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1243 * Creates or opens an object, and returns a handle that can be used to
1244 * access that object.
1246 * PARAMS
1248 * filename [in] pointer to filename to be accessed
1249 * access [in] access mode requested
1250 * sharing [in] share mode
1251 * sa [in] pointer to security attributes
1252 * creation [in] how to create the file
1253 * attributes [in] attributes for newly created file
1254 * template [in] handle to file with extended attributes to copy
1256 * RETURNS
1257 * Success: Open handle to specified file
1258 * Failure: INVALID_HANDLE_VALUE
1260 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1261 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1262 DWORD attributes, HANDLE template )
1264 NTSTATUS status;
1265 UINT options;
1266 OBJECT_ATTRIBUTES attr;
1267 UNICODE_STRING nameW;
1268 IO_STATUS_BLOCK io;
1269 HANDLE ret;
1270 DWORD dosdev;
1271 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1272 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1273 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1274 SECURITY_QUALITY_OF_SERVICE qos;
1276 static const UINT nt_disposition[5] =
1278 FILE_CREATE, /* CREATE_NEW */
1279 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1280 FILE_OPEN, /* OPEN_EXISTING */
1281 FILE_OPEN_IF, /* OPEN_ALWAYS */
1282 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1286 /* sanity checks */
1288 if (!filename || !filename[0])
1290 SetLastError( ERROR_PATH_NOT_FOUND );
1291 return INVALID_HANDLE_VALUE;
1294 TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1295 (access & GENERIC_READ)?"GENERIC_READ ":"",
1296 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1297 (!access)?"QUERY_ACCESS ":"",
1298 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1299 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1300 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1301 creation, attributes);
1303 /* Open a console for CONIN$ or CONOUT$ */
1305 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1307 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1308 goto done;
1311 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1313 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1314 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1316 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1317 !strncmpiW( filename + 4, pipeW, 5 ) ||
1318 !strncmpiW( filename + 4, mailslotW, 9 ))
1320 dosdev = 0;
1322 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1324 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1326 else if (!(GetVersion() & 0x80000000))
1328 dosdev = 0;
1330 else if (filename[4])
1332 ret = VXD_Open( filename+4, access, sa );
1333 goto done;
1335 else
1337 SetLastError( ERROR_INVALID_NAME );
1338 return INVALID_HANDLE_VALUE;
1341 else dosdev = RtlIsDosDeviceName_U( filename );
1343 if (dosdev)
1345 static const WCHAR conW[] = {'C','O','N'};
1347 if (LOWORD(dosdev) == sizeof(conW) &&
1348 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1350 switch (access & (GENERIC_READ|GENERIC_WRITE))
1352 case GENERIC_READ:
1353 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1354 goto done;
1355 case GENERIC_WRITE:
1356 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1357 goto done;
1358 default:
1359 SetLastError( ERROR_FILE_NOT_FOUND );
1360 return INVALID_HANDLE_VALUE;
1365 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1367 SetLastError( ERROR_INVALID_PARAMETER );
1368 return INVALID_HANDLE_VALUE;
1371 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1373 SetLastError( ERROR_PATH_NOT_FOUND );
1374 return INVALID_HANDLE_VALUE;
1377 /* now call NtCreateFile */
1379 options = 0;
1380 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1381 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1382 else
1383 options |= FILE_NON_DIRECTORY_FILE;
1384 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1386 options |= FILE_DELETE_ON_CLOSE;
1387 access |= DELETE;
1389 if (!(attributes & FILE_FLAG_OVERLAPPED))
1390 options |= FILE_SYNCHRONOUS_IO_ALERT;
1391 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1392 options |= FILE_RANDOM_ACCESS;
1393 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1395 attr.Length = sizeof(attr);
1396 attr.RootDirectory = 0;
1397 attr.Attributes = OBJ_CASE_INSENSITIVE;
1398 attr.ObjectName = &nameW;
1399 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1400 if (attributes & SECURITY_SQOS_PRESENT)
1402 qos.Length = sizeof(qos);
1403 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1404 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1405 qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1406 attr.SecurityQualityOfService = &qos;
1408 else
1409 attr.SecurityQualityOfService = NULL;
1411 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1413 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1414 sharing, nt_disposition[creation - CREATE_NEW],
1415 options, NULL, 0 );
1416 if (status)
1418 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1419 ret = INVALID_HANDLE_VALUE;
1421 /* In the case file creation was rejected due to CREATE_NEW flag
1422 * was specified and file with that name already exists, correct
1423 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1424 * Note: RtlNtStatusToDosError is not the subject to blame here.
1426 if (status == STATUS_OBJECT_NAME_COLLISION)
1427 SetLastError( ERROR_FILE_EXISTS );
1428 else
1429 SetLastError( RtlNtStatusToDosError(status) );
1431 else
1433 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1434 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1435 SetLastError( ERROR_ALREADY_EXISTS );
1436 else
1437 SetLastError( 0 );
1439 RtlFreeUnicodeString( &nameW );
1441 done:
1442 if (!ret) ret = INVALID_HANDLE_VALUE;
1443 TRACE("returning %p\n", ret);
1444 return ret;
1449 /*************************************************************************
1450 * CreateFileA (KERNEL32.@)
1452 * See CreateFileW.
1454 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1455 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1456 DWORD attributes, HANDLE template)
1458 WCHAR *nameW;
1460 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1461 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1465 /***********************************************************************
1466 * DeleteFileW (KERNEL32.@)
1468 * Delete a file.
1470 * PARAMS
1471 * path [I] Path to the file to delete.
1473 * RETURNS
1474 * Success: TRUE.
1475 * Failure: FALSE, check GetLastError().
1477 BOOL WINAPI DeleteFileW( LPCWSTR path )
1479 UNICODE_STRING nameW;
1480 OBJECT_ATTRIBUTES attr;
1481 NTSTATUS status;
1483 TRACE("%s\n", debugstr_w(path) );
1485 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1487 SetLastError( ERROR_PATH_NOT_FOUND );
1488 return FALSE;
1491 attr.Length = sizeof(attr);
1492 attr.RootDirectory = 0;
1493 attr.Attributes = OBJ_CASE_INSENSITIVE;
1494 attr.ObjectName = &nameW;
1495 attr.SecurityDescriptor = NULL;
1496 attr.SecurityQualityOfService = NULL;
1498 status = NtDeleteFile(&attr);
1499 RtlFreeUnicodeString( &nameW );
1500 if (status)
1502 SetLastError( RtlNtStatusToDosError(status) );
1503 return FALSE;
1505 return TRUE;
1509 /***********************************************************************
1510 * DeleteFileA (KERNEL32.@)
1512 * See DeleteFileW.
1514 BOOL WINAPI DeleteFileA( LPCSTR path )
1516 WCHAR *pathW;
1518 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1519 return DeleteFileW( pathW );
1523 /**************************************************************************
1524 * ReplaceFileW (KERNEL32.@)
1525 * ReplaceFile (KERNEL32.@)
1527 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1528 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1529 LPVOID lpExclude, LPVOID lpReserved)
1531 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1532 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1533 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1534 DWORD error = ERROR_SUCCESS;
1535 UINT replaced_flags;
1536 BOOL ret = FALSE;
1537 NTSTATUS status;
1538 IO_STATUS_BLOCK io;
1539 OBJECT_ATTRIBUTES attr;
1541 if (dwReplaceFlags)
1542 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1544 /* First two arguments are mandatory */
1545 if (!lpReplacedFileName || !lpReplacementFileName)
1547 SetLastError(ERROR_INVALID_PARAMETER);
1548 return FALSE;
1551 unix_replaced_name.Buffer = NULL;
1552 unix_replacement_name.Buffer = NULL;
1553 unix_backup_name.Buffer = NULL;
1555 attr.Length = sizeof(attr);
1556 attr.RootDirectory = 0;
1557 attr.Attributes = OBJ_CASE_INSENSITIVE;
1558 attr.ObjectName = NULL;
1559 attr.SecurityDescriptor = NULL;
1560 attr.SecurityQualityOfService = NULL;
1562 /* Open the "replaced" file for reading and writing */
1563 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1565 error = ERROR_PATH_NOT_FOUND;
1566 goto fail;
1568 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1569 attr.ObjectName = &nt_replaced_name;
1570 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1571 &attr, &io,
1572 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1573 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1574 if (status == STATUS_SUCCESS)
1575 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1576 RtlFreeUnicodeString(&nt_replaced_name);
1577 if (status != STATUS_SUCCESS)
1579 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1580 error = ERROR_FILE_NOT_FOUND;
1581 else
1582 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1583 goto fail;
1587 * Open the replacement file for reading, writing, and deleting
1588 * (writing and deleting are needed when finished)
1590 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1592 error = ERROR_PATH_NOT_FOUND;
1593 goto fail;
1595 attr.ObjectName = &nt_replacement_name;
1596 status = NtOpenFile(&hReplacement,
1597 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1598 &attr, &io, 0,
1599 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1600 if (status == STATUS_SUCCESS)
1601 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1602 RtlFreeUnicodeString(&nt_replacement_name);
1603 if (status != STATUS_SUCCESS)
1605 error = RtlNtStatusToDosError(status);
1606 goto fail;
1609 /* If the user wants a backup then that needs to be performed first */
1610 if (lpBackupFileName)
1612 UNICODE_STRING nt_backup_name;
1613 FILE_BASIC_INFORMATION replaced_info;
1615 /* Obtain the file attributes from the "replaced" file */
1616 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1617 sizeof(replaced_info),
1618 FileBasicInformation);
1619 if (status != STATUS_SUCCESS)
1621 error = RtlNtStatusToDosError(status);
1622 goto fail;
1625 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1627 error = ERROR_PATH_NOT_FOUND;
1628 goto fail;
1630 attr.ObjectName = &nt_backup_name;
1631 /* Open the backup with permissions to write over it */
1632 status = NtCreateFile(&hBackup, GENERIC_WRITE,
1633 &attr, &io, NULL, replaced_info.FileAttributes,
1634 FILE_SHARE_WRITE, FILE_OPEN_IF,
1635 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1636 NULL, 0);
1637 if (status == STATUS_SUCCESS)
1638 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1639 if (status != STATUS_SUCCESS)
1641 error = RtlNtStatusToDosError(status);
1642 goto fail;
1645 /* If an existing backup exists then copy over it */
1646 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1648 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1649 goto fail;
1654 * Now that the backup has been performed (if requested), copy the replacement
1655 * into place
1657 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1659 if (errno == EACCES)
1661 /* Inappropriate permissions on "replaced", rename will fail */
1662 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1663 goto fail;
1665 /* on failure we need to indicate whether a backup was made */
1666 if (!lpBackupFileName)
1667 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1668 else
1669 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1670 goto fail;
1672 /* Success! */
1673 ret = TRUE;
1675 /* Perform resource cleanup */
1676 fail:
1677 if (hBackup) CloseHandle(hBackup);
1678 if (hReplaced) CloseHandle(hReplaced);
1679 if (hReplacement) CloseHandle(hReplacement);
1680 RtlFreeAnsiString(&unix_backup_name);
1681 RtlFreeAnsiString(&unix_replacement_name);
1682 RtlFreeAnsiString(&unix_replaced_name);
1684 /* If there was an error, set the error code */
1685 if(!ret)
1686 SetLastError(error);
1687 return ret;
1691 /**************************************************************************
1692 * ReplaceFileA (KERNEL32.@)
1694 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1695 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1696 LPVOID lpExclude, LPVOID lpReserved)
1698 WCHAR *replacedW, *replacementW, *backupW = NULL;
1699 BOOL ret;
1701 /* This function only makes sense when the first two parameters are defined */
1702 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1704 SetLastError(ERROR_INVALID_PARAMETER);
1705 return FALSE;
1707 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1709 HeapFree( GetProcessHeap(), 0, replacedW );
1710 SetLastError(ERROR_INVALID_PARAMETER);
1711 return FALSE;
1713 /* The backup parameter, however, is optional */
1714 if (lpBackupFileName)
1716 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1718 HeapFree( GetProcessHeap(), 0, replacedW );
1719 HeapFree( GetProcessHeap(), 0, replacementW );
1720 SetLastError(ERROR_INVALID_PARAMETER);
1721 return FALSE;
1724 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1725 HeapFree( GetProcessHeap(), 0, replacedW );
1726 HeapFree( GetProcessHeap(), 0, replacementW );
1727 HeapFree( GetProcessHeap(), 0, backupW );
1728 return ret;
1732 /*************************************************************************
1733 * FindFirstFileExW (KERNEL32.@)
1735 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1736 * results as FindExSearchNameMatch
1738 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1739 LPVOID data, FINDEX_SEARCH_OPS search_op,
1740 LPVOID filter, DWORD flags)
1742 WCHAR *mask, *p;
1743 FIND_FIRST_INFO *info = NULL;
1744 UNICODE_STRING nt_name;
1745 OBJECT_ATTRIBUTES attr;
1746 IO_STATUS_BLOCK io;
1747 NTSTATUS status;
1748 DWORD device = 0;
1750 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1752 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1753 || flags != 0)
1755 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1756 return INVALID_HANDLE_VALUE;
1758 if (level != FindExInfoStandard)
1760 FIXME("info level %d not implemented\n", level );
1761 return INVALID_HANDLE_VALUE;
1764 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1766 SetLastError( ERROR_PATH_NOT_FOUND );
1767 return INVALID_HANDLE_VALUE;
1770 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1772 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1773 goto error;
1776 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1778 static const WCHAR dotW[] = {'.',0};
1779 WCHAR *dir = NULL;
1781 /* we still need to check that the directory can be opened */
1783 if (HIWORD(device))
1785 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1787 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1788 goto error;
1790 memcpy( dir, filename, HIWORD(device) );
1791 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1793 RtlFreeUnicodeString( &nt_name );
1794 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1796 HeapFree( GetProcessHeap(), 0, dir );
1797 SetLastError( ERROR_PATH_NOT_FOUND );
1798 goto error;
1800 HeapFree( GetProcessHeap(), 0, dir );
1801 RtlInitUnicodeString( &info->mask, NULL );
1803 else if (!mask || !*mask)
1805 SetLastError( ERROR_FILE_NOT_FOUND );
1806 goto error;
1808 else
1810 if (!RtlCreateUnicodeString( &info->mask, mask ))
1812 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1813 goto error;
1816 /* truncate dir name before mask */
1817 *mask = 0;
1818 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1821 /* check if path is the root of the drive */
1822 info->is_root = FALSE;
1823 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1824 if (p[0] && p[1] == ':')
1826 p += 2;
1827 while (*p == '\\') p++;
1828 info->is_root = (*p == 0);
1831 attr.Length = sizeof(attr);
1832 attr.RootDirectory = 0;
1833 attr.Attributes = OBJ_CASE_INSENSITIVE;
1834 attr.ObjectName = &nt_name;
1835 attr.SecurityDescriptor = NULL;
1836 attr.SecurityQualityOfService = NULL;
1838 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1839 FILE_SHARE_READ | FILE_SHARE_WRITE,
1840 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1842 if (status != STATUS_SUCCESS)
1844 RtlFreeUnicodeString( &info->mask );
1845 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1846 SetLastError( ERROR_PATH_NOT_FOUND );
1847 else
1848 SetLastError( RtlNtStatusToDosError(status) );
1849 goto error;
1852 RtlInitializeCriticalSection( &info->cs );
1853 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1854 info->path = nt_name;
1855 info->magic = FIND_FIRST_MAGIC;
1856 info->data_pos = 0;
1857 info->data_len = 0;
1858 info->search_op = search_op;
1860 if (device)
1862 WIN32_FIND_DATAW *wfd = data;
1864 memset( wfd, 0, sizeof(*wfd) );
1865 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1866 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1867 CloseHandle( info->handle );
1868 info->handle = 0;
1870 else
1872 IO_STATUS_BLOCK io;
1874 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1875 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1876 if (io.u.Status)
1878 FindClose( info );
1879 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1880 return INVALID_HANDLE_VALUE;
1882 info->data_len = io.Information;
1883 if (!FindNextFileW( info, data ))
1885 TRACE( "%s not found\n", debugstr_w(filename) );
1886 FindClose( info );
1887 SetLastError( ERROR_FILE_NOT_FOUND );
1888 return INVALID_HANDLE_VALUE;
1890 if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1892 /* we can't find two files with the same name */
1893 CloseHandle( info->handle );
1894 info->handle = 0;
1897 return info;
1899 error:
1900 HeapFree( GetProcessHeap(), 0, info );
1901 RtlFreeUnicodeString( &nt_name );
1902 return INVALID_HANDLE_VALUE;
1906 /*************************************************************************
1907 * FindNextFileW (KERNEL32.@)
1909 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1911 FIND_FIRST_INFO *info;
1912 FILE_BOTH_DIR_INFORMATION *dir_info;
1913 BOOL ret = FALSE;
1915 TRACE("%p %p\n", handle, data);
1917 if (!handle || handle == INVALID_HANDLE_VALUE)
1919 SetLastError( ERROR_INVALID_HANDLE );
1920 return ret;
1922 info = (FIND_FIRST_INFO *)handle;
1923 if (info->magic != FIND_FIRST_MAGIC)
1925 SetLastError( ERROR_INVALID_HANDLE );
1926 return ret;
1929 RtlEnterCriticalSection( &info->cs );
1931 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1932 else for (;;)
1934 if (info->data_pos >= info->data_len) /* need to read some more data */
1936 IO_STATUS_BLOCK io;
1938 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1939 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1940 if (io.u.Status)
1942 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1943 if (io.u.Status == STATUS_NO_MORE_FILES)
1945 CloseHandle( info->handle );
1946 info->handle = 0;
1948 break;
1950 info->data_len = io.Information;
1951 info->data_pos = 0;
1954 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1956 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1957 else info->data_pos = info->data_len;
1959 /* don't return '.' and '..' in the root of the drive */
1960 if (info->is_root)
1962 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1963 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1964 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1967 /* check for dir symlink */
1968 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1969 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1970 strpbrkW( info->mask.Buffer, wildcardsW ))
1972 if (!check_dir_symlink( info, dir_info )) continue;
1975 data->dwFileAttributes = dir_info->FileAttributes;
1976 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1977 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1978 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1979 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1980 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1981 data->dwReserved0 = 0;
1982 data->dwReserved1 = 0;
1984 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1985 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1986 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1987 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1989 TRACE("returning %s (%s)\n",
1990 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1992 ret = TRUE;
1993 break;
1996 RtlLeaveCriticalSection( &info->cs );
1997 return ret;
2001 /*************************************************************************
2002 * FindClose (KERNEL32.@)
2004 BOOL WINAPI FindClose( HANDLE handle )
2006 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
2008 if (!handle || handle == INVALID_HANDLE_VALUE)
2010 SetLastError( ERROR_INVALID_HANDLE );
2011 return FALSE;
2014 __TRY
2016 if (info->magic == FIND_FIRST_MAGIC)
2018 RtlEnterCriticalSection( &info->cs );
2019 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2021 info->magic = 0;
2022 if (info->handle) CloseHandle( info->handle );
2023 info->handle = 0;
2024 RtlFreeUnicodeString( &info->mask );
2025 info->mask.Buffer = NULL;
2026 RtlFreeUnicodeString( &info->path );
2027 info->data_pos = 0;
2028 info->data_len = 0;
2029 RtlLeaveCriticalSection( &info->cs );
2030 info->cs.DebugInfo->Spare[0] = 0;
2031 RtlDeleteCriticalSection( &info->cs );
2032 HeapFree( GetProcessHeap(), 0, info );
2036 __EXCEPT_PAGE_FAULT
2038 WARN("Illegal handle %p\n", handle);
2039 SetLastError( ERROR_INVALID_HANDLE );
2040 return FALSE;
2042 __ENDTRY
2044 return TRUE;
2048 /*************************************************************************
2049 * FindFirstFileA (KERNEL32.@)
2051 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2053 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2054 FindExSearchNameMatch, NULL, 0);
2057 /*************************************************************************
2058 * FindFirstFileExA (KERNEL32.@)
2060 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2061 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2062 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2064 HANDLE handle;
2065 WIN32_FIND_DATAA *dataA;
2066 WIN32_FIND_DATAW dataW;
2067 WCHAR *nameW;
2069 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2071 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2072 if (handle == INVALID_HANDLE_VALUE) return handle;
2074 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
2075 dataA->dwFileAttributes = dataW.dwFileAttributes;
2076 dataA->ftCreationTime = dataW.ftCreationTime;
2077 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2078 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2079 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2080 dataA->nFileSizeLow = dataW.nFileSizeLow;
2081 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2082 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2083 sizeof(dataA->cAlternateFileName) );
2084 return handle;
2088 /*************************************************************************
2089 * FindFirstFileW (KERNEL32.@)
2091 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2093 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2094 FindExSearchNameMatch, NULL, 0);
2098 /*************************************************************************
2099 * FindNextFileA (KERNEL32.@)
2101 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2103 WIN32_FIND_DATAW dataW;
2105 if (!FindNextFileW( handle, &dataW )) return FALSE;
2106 data->dwFileAttributes = dataW.dwFileAttributes;
2107 data->ftCreationTime = dataW.ftCreationTime;
2108 data->ftLastAccessTime = dataW.ftLastAccessTime;
2109 data->ftLastWriteTime = dataW.ftLastWriteTime;
2110 data->nFileSizeHigh = dataW.nFileSizeHigh;
2111 data->nFileSizeLow = dataW.nFileSizeLow;
2112 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2113 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2114 sizeof(data->cAlternateFileName) );
2115 return TRUE;
2119 /**************************************************************************
2120 * GetFileAttributesW (KERNEL32.@)
2122 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2124 FILE_BASIC_INFORMATION info;
2125 UNICODE_STRING nt_name;
2126 OBJECT_ATTRIBUTES attr;
2127 NTSTATUS status;
2129 TRACE("%s\n", debugstr_w(name));
2131 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2133 SetLastError( ERROR_PATH_NOT_FOUND );
2134 return INVALID_FILE_ATTRIBUTES;
2137 attr.Length = sizeof(attr);
2138 attr.RootDirectory = 0;
2139 attr.Attributes = OBJ_CASE_INSENSITIVE;
2140 attr.ObjectName = &nt_name;
2141 attr.SecurityDescriptor = NULL;
2142 attr.SecurityQualityOfService = NULL;
2144 status = NtQueryAttributesFile( &attr, &info );
2145 RtlFreeUnicodeString( &nt_name );
2147 if (status == STATUS_SUCCESS) return info.FileAttributes;
2149 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2150 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2152 SetLastError( RtlNtStatusToDosError(status) );
2153 return INVALID_FILE_ATTRIBUTES;
2157 /**************************************************************************
2158 * GetFileAttributesA (KERNEL32.@)
2160 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2162 WCHAR *nameW;
2164 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2165 return GetFileAttributesW( nameW );
2169 /**************************************************************************
2170 * SetFileAttributesW (KERNEL32.@)
2172 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2174 UNICODE_STRING nt_name;
2175 OBJECT_ATTRIBUTES attr;
2176 IO_STATUS_BLOCK io;
2177 NTSTATUS status;
2178 HANDLE handle;
2180 TRACE("%s %x\n", debugstr_w(name), attributes);
2182 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2184 SetLastError( ERROR_PATH_NOT_FOUND );
2185 return FALSE;
2188 attr.Length = sizeof(attr);
2189 attr.RootDirectory = 0;
2190 attr.Attributes = OBJ_CASE_INSENSITIVE;
2191 attr.ObjectName = &nt_name;
2192 attr.SecurityDescriptor = NULL;
2193 attr.SecurityQualityOfService = NULL;
2195 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2196 RtlFreeUnicodeString( &nt_name );
2198 if (status == STATUS_SUCCESS)
2200 FILE_BASIC_INFORMATION info;
2202 memset( &info, 0, sizeof(info) );
2203 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2204 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2205 NtClose( handle );
2208 if (status == STATUS_SUCCESS) return TRUE;
2209 SetLastError( RtlNtStatusToDosError(status) );
2210 return FALSE;
2214 /**************************************************************************
2215 * SetFileAttributesA (KERNEL32.@)
2217 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2219 WCHAR *nameW;
2221 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2222 return SetFileAttributesW( nameW, attributes );
2226 /**************************************************************************
2227 * GetFileAttributesExW (KERNEL32.@)
2229 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2231 FILE_NETWORK_OPEN_INFORMATION info;
2232 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2233 UNICODE_STRING nt_name;
2234 OBJECT_ATTRIBUTES attr;
2235 NTSTATUS status;
2237 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2239 if (level != GetFileExInfoStandard)
2241 SetLastError( ERROR_INVALID_PARAMETER );
2242 return FALSE;
2245 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2247 SetLastError( ERROR_PATH_NOT_FOUND );
2248 return FALSE;
2251 attr.Length = sizeof(attr);
2252 attr.RootDirectory = 0;
2253 attr.Attributes = OBJ_CASE_INSENSITIVE;
2254 attr.ObjectName = &nt_name;
2255 attr.SecurityDescriptor = NULL;
2256 attr.SecurityQualityOfService = NULL;
2258 status = NtQueryFullAttributesFile( &attr, &info );
2259 RtlFreeUnicodeString( &nt_name );
2261 if (status != STATUS_SUCCESS)
2263 SetLastError( RtlNtStatusToDosError(status) );
2264 return FALSE;
2267 data->dwFileAttributes = info.FileAttributes;
2268 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2269 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2270 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2271 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2272 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2273 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2274 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2275 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2276 return TRUE;
2280 /**************************************************************************
2281 * GetFileAttributesExA (KERNEL32.@)
2283 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2285 WCHAR *nameW;
2287 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2288 return GetFileAttributesExW( nameW, level, ptr );
2292 /******************************************************************************
2293 * GetCompressedFileSizeW (KERNEL32.@)
2295 * Get the actual number of bytes used on disk.
2297 * RETURNS
2298 * Success: Low-order doubleword of number of bytes
2299 * Failure: INVALID_FILE_SIZE
2301 DWORD WINAPI GetCompressedFileSizeW(
2302 LPCWSTR name, /* [in] Pointer to name of file */
2303 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2305 UNICODE_STRING nt_name;
2306 OBJECT_ATTRIBUTES attr;
2307 IO_STATUS_BLOCK io;
2308 NTSTATUS status;
2309 HANDLE handle;
2310 DWORD ret = INVALID_FILE_SIZE;
2312 TRACE("%s %p\n", debugstr_w(name), size_high);
2314 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2316 SetLastError( ERROR_PATH_NOT_FOUND );
2317 return INVALID_FILE_SIZE;
2320 attr.Length = sizeof(attr);
2321 attr.RootDirectory = 0;
2322 attr.Attributes = OBJ_CASE_INSENSITIVE;
2323 attr.ObjectName = &nt_name;
2324 attr.SecurityDescriptor = NULL;
2325 attr.SecurityQualityOfService = NULL;
2327 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2328 RtlFreeUnicodeString( &nt_name );
2330 if (status == STATUS_SUCCESS)
2332 /* we don't support compressed files, simply return the file size */
2333 ret = GetFileSize( handle, size_high );
2334 NtClose( handle );
2336 else SetLastError( RtlNtStatusToDosError(status) );
2338 return ret;
2342 /******************************************************************************
2343 * GetCompressedFileSizeA (KERNEL32.@)
2345 * See GetCompressedFileSizeW.
2347 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2349 WCHAR *nameW;
2351 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2352 return GetCompressedFileSizeW( nameW, size_high );
2356 /***********************************************************************
2357 * OpenFile (KERNEL32.@)
2359 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2361 HANDLE handle;
2362 FILETIME filetime;
2363 WORD filedatetime[2];
2365 if (!ofs) return HFILE_ERROR;
2367 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2368 ((mode & 0x3 )==OF_READ)?"OF_READ":
2369 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2370 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2371 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2372 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2373 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2374 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2375 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2376 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2377 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2378 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2379 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2380 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2381 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2382 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2383 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2384 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2388 ofs->cBytes = sizeof(OFSTRUCT);
2389 ofs->nErrCode = 0;
2390 if (mode & OF_REOPEN) name = ofs->szPathName;
2392 if (!name) return HFILE_ERROR;
2394 TRACE("%s %04x\n", name, mode );
2396 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2397 Are there any cases where getting the path here is wrong?
2398 Uwe Bonnes 1997 Apr 2 */
2399 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2401 /* OF_PARSE simply fills the structure */
2403 if (mode & OF_PARSE)
2405 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2406 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2407 return 0;
2410 /* OF_CREATE is completely different from all other options, so
2411 handle it first */
2413 if (mode & OF_CREATE)
2415 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2416 goto error;
2418 else
2420 /* Now look for the file */
2422 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2423 goto error;
2425 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2427 if (mode & OF_DELETE)
2429 if (!DeleteFileA( ofs->szPathName )) goto error;
2430 TRACE("(%s): OF_DELETE return = OK\n", name);
2431 return TRUE;
2434 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2435 if (handle == INVALID_HANDLE_VALUE) goto error;
2437 GetFileTime( handle, NULL, NULL, &filetime );
2438 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2439 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2441 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2443 CloseHandle( handle );
2444 WARN("(%s): OF_VERIFY failed\n", name );
2445 /* FIXME: what error here? */
2446 SetLastError( ERROR_FILE_NOT_FOUND );
2447 goto error;
2450 ofs->Reserved1 = filedatetime[0];
2451 ofs->Reserved2 = filedatetime[1];
2453 TRACE("(%s): OK, return = %p\n", name, handle );
2454 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2456 CloseHandle( handle );
2457 return TRUE;
2459 return HandleToLong(handle);
2461 error: /* We get here if there was an error opening the file */
2462 ofs->nErrCode = GetLastError();
2463 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2464 return HFILE_ERROR;