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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "wine/port.h"
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
36 #define WIN32_NO_STATUS
42 #include "wine/winbase16.h"
43 #include "kernel_private.h"
45 #include "wine/exception.h"
47 #include "wine/unicode.h"
48 #include "wine/debug.h"
50 #include "wine/server.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(file);
54 HANDLE dos_handles[DOS_TABLE_SIZE];
56 /* info structure for FindFirstFile handle */
59 DWORD magic; /* magic number */
60 HANDLE handle; /* handle to directory */
61 CRITICAL_SECTION cs; /* crit section protecting this structure */
62 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
63 UNICODE_STRING mask; /* file mask */
64 UNICODE_STRING path; /* NT path used to open the directory */
65 BOOL is_root; /* is directory the root of the drive? */
66 UINT data_pos; /* current position in dir data */
67 UINT data_len; /* length of dir data */
68 BYTE data[8192]; /* directory data */
71 #define FIND_FIRST_MAGIC 0xc0ffee11
73 static BOOL oem_file_apis;
75 static WINE_EXCEPTION_FILTER(page_fault)
77 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
78 return EXCEPTION_EXECUTE_HANDLER;
79 return EXCEPTION_CONTINUE_SEARCH;
83 /***********************************************************************
86 * Wrapper for CreateFile that takes OF_* mode flags.
88 static HANDLE create_file_OF( LPCSTR path, INT mode )
90 DWORD access, sharing, creation;
94 creation = CREATE_ALWAYS;
95 access = GENERIC_READ | GENERIC_WRITE;
99 creation = OPEN_EXISTING;
102 case OF_READ: access = GENERIC_READ; break;
103 case OF_WRITE: access = GENERIC_WRITE; break;
104 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
105 default: access = 0; break;
111 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
112 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
113 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
114 case OF_SHARE_DENY_NONE:
115 case OF_SHARE_COMPAT:
116 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
118 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
122 /***********************************************************************
125 * Check if a dir symlink should be returned by FindNextFile.
127 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
130 ANSI_STRING unix_name;
131 struct stat st, parent_st;
135 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
136 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
137 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
138 len = info->path.Length / sizeof(WCHAR);
139 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
140 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
141 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
143 unix_name.Buffer = NULL;
144 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
145 !stat( unix_name.Buffer, &st ))
147 char *p = unix_name.Buffer + unix_name.Length - 1;
149 /* skip trailing slashes */
150 while (p > unix_name.Buffer && *p == '/') p--;
152 while (ret && p > unix_name.Buffer)
154 while (p > unix_name.Buffer && *p != '/') p--;
155 while (p > unix_name.Buffer && *p == '/') p--;
157 if (!stat( unix_name.Buffer, &parent_st ) &&
158 parent_st.st_dev == st.st_dev &&
159 parent_st.st_ino == st.st_ino)
161 WARN( "suppressing dir symlink %s pointing to parent %s\n",
162 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
163 debugstr_a( unix_name.Buffer ));
168 RtlFreeAnsiString( &unix_name );
169 RtlFreeUnicodeString( &str );
174 /***********************************************************************
177 * Set the DOS error code from errno.
179 void FILE_SetDosError(void)
181 int save_errno = errno; /* errno gets overwritten by printf */
183 TRACE("errno = %d %s\n", errno, strerror(errno));
187 SetLastError( ERROR_SHARING_VIOLATION );
190 SetLastError( ERROR_INVALID_HANDLE );
193 SetLastError( ERROR_HANDLE_DISK_FULL );
198 SetLastError( ERROR_ACCESS_DENIED );
201 SetLastError( ERROR_LOCK_VIOLATION );
204 SetLastError( ERROR_FILE_NOT_FOUND );
207 SetLastError( ERROR_CANNOT_MAKE );
211 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
214 SetLastError( ERROR_FILE_EXISTS );
218 SetLastError( ERROR_SEEK );
221 SetLastError( ERROR_DIR_NOT_EMPTY );
224 SetLastError( ERROR_BAD_FORMAT );
227 SetLastError( ERROR_PATH_NOT_FOUND );
230 SetLastError( ERROR_NOT_SAME_DEVICE );
233 WARN("unknown file error: %s\n", strerror(save_errno) );
234 SetLastError( ERROR_GEN_FAILURE );
241 /***********************************************************************
244 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
246 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
247 * there is no possibility for the function to do that twice, taking into
248 * account any called function.
250 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
253 UNICODE_STRING strW, *pstrW;
256 RtlInitAnsiString( &str, name );
257 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
259 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
261 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
262 if (status == STATUS_SUCCESS) return pstrW->Buffer;
264 if (status == STATUS_BUFFER_OVERFLOW)
265 SetLastError( ERROR_FILENAME_EXCED_RANGE );
267 SetLastError( RtlNtStatusToDosError(status) );
272 /***********************************************************************
275 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
277 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
281 if (srclen < 0) srclen = strlenW( src ) + 1;
283 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
285 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
290 /**************************************************************************
291 * SetFileApisToOEM (KERNEL32.@)
293 VOID WINAPI SetFileApisToOEM(void)
295 oem_file_apis = TRUE;
299 /**************************************************************************
300 * SetFileApisToANSI (KERNEL32.@)
302 VOID WINAPI SetFileApisToANSI(void)
304 oem_file_apis = FALSE;
308 /******************************************************************************
309 * AreFileApisANSI (KERNEL32.@)
311 * Determines if file functions are using ANSI
314 * TRUE: Set of file functions is using ANSI code page
315 * FALSE: Set of file functions is using OEM code page
317 BOOL WINAPI AreFileApisANSI(void)
319 return !oem_file_apis;
323 /**************************************************************************
324 * Operations on file handles *
325 **************************************************************************/
327 /***********************************************************************
328 * FILE_InitProcessDosHandles
330 * Allocates the default DOS handles for a process. Called either by
331 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
333 static void FILE_InitProcessDosHandles( void )
335 static BOOL init_done /* = FALSE */;
336 HANDLE cp = GetCurrentProcess();
338 if (init_done) return;
340 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
341 0, TRUE, DUPLICATE_SAME_ACCESS);
342 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
343 0, TRUE, DUPLICATE_SAME_ACCESS);
344 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
345 0, TRUE, DUPLICATE_SAME_ACCESS);
346 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
347 0, TRUE, DUPLICATE_SAME_ACCESS);
348 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
349 0, TRUE, DUPLICATE_SAME_ACCESS);
353 /******************************************************************
354 * FILE_ReadWriteApc (internal)
356 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
358 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
360 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
364 /***********************************************************************
365 * ReadFileEx (KERNEL32.@)
367 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
368 LPOVERLAPPED overlapped,
369 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
371 LARGE_INTEGER offset;
373 PIO_STATUS_BLOCK io_status;
375 TRACE("(hFile=%p, buffer=%p, bytes=%lu, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
379 SetLastError(ERROR_INVALID_PARAMETER);
383 offset.u.LowPart = overlapped->u.s.Offset;
384 offset.u.HighPart = overlapped->u.s.OffsetHigh;
385 io_status = (PIO_STATUS_BLOCK)overlapped;
386 io_status->u.Status = STATUS_PENDING;
388 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
389 io_status, buffer, bytesToRead, &offset, NULL);
393 SetLastError( RtlNtStatusToDosError(status) );
400 /***********************************************************************
401 * ReadFile (KERNEL32.@)
403 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
404 LPDWORD bytesRead, LPOVERLAPPED overlapped )
406 LARGE_INTEGER offset;
407 PLARGE_INTEGER poffset = NULL;
408 IO_STATUS_BLOCK iosb;
409 PIO_STATUS_BLOCK io_status = &iosb;
413 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
414 bytesRead, overlapped );
416 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
417 if (!bytesToRead) return TRUE;
419 if (is_console_handle(hFile))
420 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
422 if (overlapped != NULL)
424 offset.u.LowPart = overlapped->u.s.Offset;
425 offset.u.HighPart = overlapped->u.s.OffsetHigh;
427 hEvent = overlapped->hEvent;
428 io_status = (PIO_STATUS_BLOCK)overlapped;
430 io_status->u.Status = STATUS_PENDING;
431 io_status->Information = 0;
433 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
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) );
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;
456 PIO_STATUS_BLOCK io_status;
458 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
460 if (overlapped == NULL)
462 SetLastError(ERROR_INVALID_PARAMETER);
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;
471 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
472 io_status, buffer, bytesToWrite, &offset, NULL);
474 if (status) SetLastError( RtlNtStatusToDosError(status) );
479 /***********************************************************************
480 * WriteFile (KERNEL32.@)
482 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
483 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
485 HANDLE hEvent = NULL;
486 LARGE_INTEGER offset;
487 PLARGE_INTEGER poffset = NULL;
489 IO_STATUS_BLOCK iosb;
490 PIO_STATUS_BLOCK piosb = &iosb;
492 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
494 if (is_console_handle(hFile))
495 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
499 offset.u.LowPart = overlapped->u.s.Offset;
500 offset.u.HighPart = overlapped->u.s.OffsetHigh;
502 hEvent = overlapped->hEvent;
503 piosb = (PIO_STATUS_BLOCK)overlapped;
505 piosb->u.Status = STATUS_PENDING;
506 piosb->Information = 0;
508 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
509 buffer, bytesToWrite, poffset, NULL);
511 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
512 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
514 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
515 buffer, bytesToWrite, poffset, NULL);
516 if (status != STATUS_INVALID_USER_BUFFER)
517 FIXME("Could not access memory (%p,%ld) at first, now OK. Protected by DIBSection code?\n",
518 buffer, bytesToWrite);
521 if (status != STATUS_PENDING && bytesWritten)
522 *bytesWritten = piosb->Information;
524 if (status && status != STATUS_TIMEOUT)
526 SetLastError( RtlNtStatusToDosError(status) );
533 /***********************************************************************
534 * GetOverlappedResult (KERNEL32.@)
536 * Check the result of an Asynchronous data transfer from a file.
539 * HANDLE hFile [in] handle of file to check on
540 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
541 * LPDWORD lpTransferred [in/out] number of bytes transferred
542 * BOOL bWait [in] wait for the transfer to complete ?
548 * If successful (and relevant) lpTransferred will hold the number of
549 * bytes transferred during the async operation.
553 * Currently only works for WaitCommEvent, ReadFile, WriteFile
554 * with communications ports.
557 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
558 LPDWORD lpTransferred, BOOL bWait)
560 DWORD r = WAIT_OBJECT_0;
562 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
564 if ( lpOverlapped == NULL )
566 ERR("lpOverlapped was null\n");
571 if ( lpOverlapped->hEvent )
575 TRACE( "waiting on %p\n", lpOverlapped );
576 r = WaitForSingleObjectEx( lpOverlapped->hEvent, INFINITE, TRUE );
577 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
578 } while ( r == WAIT_IO_COMPLETION );
583 while ( ((volatile OVERLAPPED*)lpOverlapped)->Internal == STATUS_PENDING )
587 else if ( lpOverlapped->Internal == STATUS_PENDING )
589 /* Wait in order to give APCs a chance to run. */
590 /* This is cheating, so we must set the event again in case of success -
591 it may be a non-manual reset event. */
594 TRACE( "waiting on %p\n", lpOverlapped );
595 r = WaitForSingleObjectEx( lpOverlapped->hEvent, 0, TRUE );
596 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
597 } while ( r == WAIT_IO_COMPLETION );
598 if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
599 NtSetEvent( lpOverlapped->hEvent, NULL );
601 if ( r == WAIT_FAILED )
603 WARN("wait operation failed\n");
606 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
608 switch ( lpOverlapped->Internal )
613 SetLastError( ERROR_IO_INCOMPLETE );
614 if ( bWait ) ERR("PENDING status after waiting!\n");
617 SetLastError( RtlNtStatusToDosError( lpOverlapped->Internal ) );
622 /***********************************************************************
623 * CancelIo (KERNEL32.@)
625 BOOL WINAPI CancelIo(HANDLE handle)
627 IO_STATUS_BLOCK io_status;
629 NtCancelIoFile(handle, &io_status);
630 if (io_status.u.Status)
632 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
638 /***********************************************************************
639 * _hread (KERNEL32.@)
641 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
643 return _lread( hFile, buffer, count );
647 /***********************************************************************
648 * _hwrite (KERNEL32.@)
650 * experimentation yields that _lwrite:
651 * o truncates the file at the current position with
653 * o returns 0 on a 0 length write
654 * o works with console handles
657 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
661 TRACE("%d %p %ld\n", handle, buffer, count );
665 /* Expand or truncate at current position */
666 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
669 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
675 /***********************************************************************
676 * _lclose (KERNEL32.@)
678 HFILE WINAPI _lclose( HFILE hFile )
680 TRACE("handle %d\n", hFile );
681 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
685 /***********************************************************************
686 * _lcreat (KERNEL32.@)
688 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
690 /* Mask off all flags not explicitly allowed by the doc */
691 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
692 TRACE("%s %02x\n", path, attr );
693 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
694 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
695 CREATE_ALWAYS, attr, 0 );
699 /***********************************************************************
700 * _lopen (KERNEL32.@)
702 HFILE WINAPI _lopen( LPCSTR path, INT mode )
704 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
705 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
708 /***********************************************************************
709 * _lread (KERNEL32.@)
711 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
714 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
720 /***********************************************************************
721 * _llseek (KERNEL32.@)
723 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
725 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
729 /***********************************************************************
730 * _lwrite (KERNEL32.@)
732 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
734 return (UINT)_hwrite( hFile, buffer, (LONG)count );
738 /***********************************************************************
739 * FlushFileBuffers (KERNEL32.@)
741 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
744 IO_STATUS_BLOCK ioblk;
746 if (is_console_handle( hFile ))
748 /* this will fail (as expected) for an output handle */
749 return FlushConsoleInputBuffer( hFile );
751 nts = NtFlushBuffersFile( hFile, &ioblk );
752 if (nts != STATUS_SUCCESS)
754 SetLastError( RtlNtStatusToDosError( nts ) );
762 /***********************************************************************
763 * GetFileType (KERNEL32.@)
765 DWORD WINAPI GetFileType( HANDLE hFile )
767 FILE_FS_DEVICE_INFORMATION info;
771 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
773 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
774 if (status != STATUS_SUCCESS)
776 SetLastError( RtlNtStatusToDosError(status) );
777 return FILE_TYPE_UNKNOWN;
780 switch(info.DeviceType)
782 case FILE_DEVICE_NULL:
783 case FILE_DEVICE_SERIAL_PORT:
784 case FILE_DEVICE_PARALLEL_PORT:
785 case FILE_DEVICE_UNKNOWN:
786 return FILE_TYPE_CHAR;
787 case FILE_DEVICE_NAMED_PIPE:
788 return FILE_TYPE_PIPE;
790 return FILE_TYPE_DISK;
795 /***********************************************************************
796 * GetFileInformationByHandle (KERNEL32.@)
798 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
800 FILE_ALL_INFORMATION all_info;
804 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
805 if (status == STATUS_SUCCESS)
807 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
808 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
809 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
810 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
811 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
812 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
813 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
814 info->dwVolumeSerialNumber = 0; /* FIXME */
815 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
816 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
817 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
818 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
819 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
822 SetLastError( RtlNtStatusToDosError(status) );
827 /***********************************************************************
828 * GetFileSize (KERNEL32.@)
830 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
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 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
845 FILE_END_OF_FILE_INFORMATION info;
849 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
850 if (status == STATUS_SUCCESS)
852 *lpFileSize = info.EndOfFile;
855 SetLastError( RtlNtStatusToDosError(status) );
860 /**************************************************************************
861 * SetEndOfFile (KERNEL32.@)
863 BOOL WINAPI SetEndOfFile( HANDLE hFile )
865 FILE_POSITION_INFORMATION pos;
866 FILE_END_OF_FILE_INFORMATION eof;
870 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
871 if (status == STATUS_SUCCESS)
873 eof.EndOfFile = pos.CurrentByteOffset;
874 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
876 if (status == STATUS_SUCCESS) return TRUE;
877 SetLastError( RtlNtStatusToDosError(status) );
882 /***********************************************************************
883 * SetFilePointer (KERNEL32.@)
885 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
887 LARGE_INTEGER dist, newpos;
891 dist.u.LowPart = distance;
892 dist.u.HighPart = *highword;
894 else dist.QuadPart = distance;
896 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
898 if (highword) *highword = newpos.u.HighPart;
899 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
900 return newpos.u.LowPart;
904 /***********************************************************************
905 * SetFilePointerEx (KERNEL32.@)
907 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
908 LARGE_INTEGER *newpos, DWORD method )
910 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
915 TRACE("handle %p offset %s newpos %p origin %ld\n",
916 hFile, wine_dbgstr_longlong(distance.QuadPart), newpos, method );
918 if (method > FILE_END)
920 SetLastError( ERROR_INVALID_PARAMETER );
924 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL )))
928 pos = distance.QuadPart;
929 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
931 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
932 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
933 SetLastError( ERROR_NEGATIVE_SEEK );
941 newpos->QuadPart = res;
943 wine_server_release_fd( hFile, fd );
945 else SetLastError( RtlNtStatusToDosError(status) );
950 /***********************************************************************
951 * GetFileTime (KERNEL32.@)
953 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
954 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
956 FILE_BASIC_INFORMATION info;
960 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
961 if (status == STATUS_SUCCESS)
965 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
966 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
968 if (lpLastAccessTime)
970 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
971 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
975 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
976 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
980 SetLastError( RtlNtStatusToDosError(status) );
985 /***********************************************************************
986 * SetFileTime (KERNEL32.@)
988 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
989 const FILETIME *atime, const FILETIME *mtime )
991 FILE_BASIC_INFORMATION info;
995 memset( &info, 0, sizeof(info) );
998 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
999 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1003 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1004 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1008 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1009 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1012 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1013 if (status == STATUS_SUCCESS) return TRUE;
1014 SetLastError( RtlNtStatusToDosError(status) );
1019 /**************************************************************************
1020 * LockFile (KERNEL32.@)
1022 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1023 DWORD count_low, DWORD count_high )
1026 LARGE_INTEGER count, offset;
1028 TRACE( "%p %lx%08lx %lx%08lx\n",
1029 hFile, offset_high, offset_low, count_high, count_low );
1031 count.u.LowPart = count_low;
1032 count.u.HighPart = count_high;
1033 offset.u.LowPart = offset_low;
1034 offset.u.HighPart = offset_high;
1036 status = NtLockFile( hFile, 0, NULL, NULL,
1037 NULL, &offset, &count, NULL, TRUE, TRUE );
1039 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1044 /**************************************************************************
1045 * LockFileEx [KERNEL32.@]
1047 * Locks a byte range within an open file for shared or exclusive access.
1054 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1056 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1057 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1060 LARGE_INTEGER count, offset;
1064 SetLastError( ERROR_INVALID_PARAMETER );
1068 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
1069 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1070 count_high, count_low, flags );
1072 count.u.LowPart = count_low;
1073 count.u.HighPart = count_high;
1074 offset.u.LowPart = overlapped->u.s.Offset;
1075 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1077 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1078 NULL, &offset, &count, NULL,
1079 flags & LOCKFILE_FAIL_IMMEDIATELY,
1080 flags & LOCKFILE_EXCLUSIVE_LOCK );
1082 if (status) SetLastError( RtlNtStatusToDosError(status) );
1087 /**************************************************************************
1088 * UnlockFile (KERNEL32.@)
1090 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1091 DWORD count_low, DWORD count_high )
1094 LARGE_INTEGER count, offset;
1096 count.u.LowPart = count_low;
1097 count.u.HighPart = count_high;
1098 offset.u.LowPart = offset_low;
1099 offset.u.HighPart = offset_high;
1101 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1102 if (status) SetLastError( RtlNtStatusToDosError(status) );
1107 /**************************************************************************
1108 * UnlockFileEx (KERNEL32.@)
1110 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1111 LPOVERLAPPED overlapped )
1115 SetLastError( ERROR_INVALID_PARAMETER );
1118 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1120 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1124 /***********************************************************************
1125 * Win32HandleToDosFileHandle (KERNEL32.21)
1127 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1128 * longer valid after this function (even on failure).
1130 * Note: this is not exactly right, since on Win95 the Win32 handles
1131 * are on top of DOS handles and we do it the other way
1132 * around. Should be good enough though.
1134 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1138 if (!handle || (handle == INVALID_HANDLE_VALUE))
1141 FILE_InitProcessDosHandles();
1142 for (i = 0; i < DOS_TABLE_SIZE; i++)
1143 if (!dos_handles[i])
1145 dos_handles[i] = handle;
1146 TRACE("Got %d for h32 %p\n", i, handle );
1149 CloseHandle( handle );
1150 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1155 /***********************************************************************
1156 * DosFileHandleToWin32Handle (KERNEL32.20)
1158 * Return the Win32 handle for a DOS handle.
1160 * Note: this is not exactly right, since on Win95 the Win32 handles
1161 * are on top of DOS handles and we do it the other way
1162 * around. Should be good enough though.
1164 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1166 HFILE16 hfile = (HFILE16)handle;
1167 if (hfile < 5) FILE_InitProcessDosHandles();
1168 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1170 SetLastError( ERROR_INVALID_HANDLE );
1171 return INVALID_HANDLE_VALUE;
1173 return dos_handles[hfile];
1177 /*************************************************************************
1178 * SetHandleCount (KERNEL32.@)
1180 UINT WINAPI SetHandleCount( UINT count )
1182 return min( 256, count );
1186 /***********************************************************************
1187 * DisposeLZ32Handle (KERNEL32.22)
1189 * Note: this is not entirely correct, we should only close the
1190 * 32-bit handle and not the 16-bit one, but we cannot do
1191 * this because of the way our DOS handles are implemented.
1192 * It shouldn't break anything though.
1194 void WINAPI DisposeLZ32Handle( HANDLE handle )
1198 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1200 for (i = 5; i < DOS_TABLE_SIZE; i++)
1201 if (dos_handles[i] == handle)
1204 CloseHandle( handle );
1209 /**************************************************************************
1210 * Operations on file names *
1211 **************************************************************************/
1214 /*************************************************************************
1215 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1217 * Creates or opens an object, and returns a handle that can be used to
1218 * access that object.
1222 * filename [in] pointer to filename to be accessed
1223 * access [in] access mode requested
1224 * sharing [in] share mode
1225 * sa [in] pointer to security attributes
1226 * creation [in] how to create the file
1227 * attributes [in] attributes for newly created file
1228 * template [in] handle to file with extended attributes to copy
1231 * Success: Open handle to specified file
1232 * Failure: INVALID_HANDLE_VALUE
1234 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1235 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1236 DWORD attributes, HANDLE template )
1240 OBJECT_ATTRIBUTES attr;
1241 UNICODE_STRING nameW;
1245 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1246 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1247 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1249 static const UINT nt_disposition[5] =
1251 FILE_CREATE, /* CREATE_NEW */
1252 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1253 FILE_OPEN, /* OPEN_EXISTING */
1254 FILE_OPEN_IF, /* OPEN_ALWAYS */
1255 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1261 if (!filename || !filename[0])
1263 SetLastError( ERROR_PATH_NOT_FOUND );
1264 return INVALID_HANDLE_VALUE;
1267 TRACE("%s %s%s%s%s%s%s creation %ld attributes 0x%lx\n", debugstr_w(filename),
1268 (access & GENERIC_READ)?"GENERIC_READ ":"",
1269 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1270 (!access)?"QUERY_ACCESS ":"",
1271 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1272 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1273 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1274 creation, attributes);
1276 /* Open a console for CONIN$ or CONOUT$ */
1278 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1280 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1284 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1286 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1287 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1289 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1290 !strncmpiW( filename + 4, pipeW, 5 ) ||
1291 !strncmpiW( filename + 4, mailslotW, 9 ))
1295 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1297 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1299 else if (filename[4])
1301 ret = VXD_Open( filename+4, access, sa );
1306 SetLastError( ERROR_INVALID_NAME );
1307 return INVALID_HANDLE_VALUE;
1310 else dosdev = RtlIsDosDeviceName_U( filename );
1314 static const WCHAR conW[] = {'C','O','N'};
1316 if (LOWORD(dosdev) == sizeof(conW) &&
1317 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1319 switch (access & (GENERIC_READ|GENERIC_WRITE))
1322 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1325 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1328 SetLastError( ERROR_FILE_NOT_FOUND );
1329 return INVALID_HANDLE_VALUE;
1334 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1336 SetLastError( ERROR_INVALID_PARAMETER );
1337 return INVALID_HANDLE_VALUE;
1340 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1342 SetLastError( ERROR_PATH_NOT_FOUND );
1343 return INVALID_HANDLE_VALUE;
1346 /* now call NtCreateFile */
1349 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1350 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1352 options |= FILE_NON_DIRECTORY_FILE;
1353 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1354 options |= FILE_DELETE_ON_CLOSE;
1355 if (!(attributes & FILE_FLAG_OVERLAPPED))
1356 options |= FILE_SYNCHRONOUS_IO_ALERT;
1357 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1358 options |= FILE_RANDOM_ACCESS;
1359 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1361 attr.Length = sizeof(attr);
1362 attr.RootDirectory = 0;
1363 attr.Attributes = OBJ_CASE_INSENSITIVE;
1364 attr.ObjectName = &nameW;
1365 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1366 attr.SecurityQualityOfService = NULL;
1368 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1370 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1371 sharing, nt_disposition[creation - CREATE_NEW],
1375 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1376 ret = INVALID_HANDLE_VALUE;
1378 /* In the case file creation was rejected due to CREATE_NEW flag
1379 * was specified and file with that name already exists, correct
1380 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1381 * Note: RtlNtStatusToDosError is not the subject to blame here.
1383 if (status == STATUS_OBJECT_NAME_COLLISION)
1384 SetLastError( ERROR_FILE_EXISTS );
1386 SetLastError( RtlNtStatusToDosError(status) );
1388 else SetLastError(0);
1389 RtlFreeUnicodeString( &nameW );
1392 if (!ret) ret = INVALID_HANDLE_VALUE;
1393 TRACE("returning %p\n", ret);
1399 /*************************************************************************
1400 * CreateFileA (KERNEL32.@)
1404 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1405 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1406 DWORD attributes, HANDLE template)
1410 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1411 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1415 /***********************************************************************
1416 * DeleteFileW (KERNEL32.@)
1418 BOOL WINAPI DeleteFileW( LPCWSTR path )
1420 UNICODE_STRING nameW;
1421 OBJECT_ATTRIBUTES attr;
1424 TRACE("%s\n", debugstr_w(path) );
1426 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1428 SetLastError( ERROR_PATH_NOT_FOUND );
1432 attr.Length = sizeof(attr);
1433 attr.RootDirectory = 0;
1434 attr.Attributes = OBJ_CASE_INSENSITIVE;
1435 attr.ObjectName = &nameW;
1436 attr.SecurityDescriptor = NULL;
1437 attr.SecurityQualityOfService = NULL;
1439 status = NtDeleteFile(&attr);
1440 RtlFreeUnicodeString( &nameW );
1443 SetLastError( RtlNtStatusToDosError(status) );
1450 /***********************************************************************
1451 * DeleteFileA (KERNEL32.@)
1453 BOOL WINAPI DeleteFileA( LPCSTR path )
1457 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1458 return DeleteFileW( pathW );
1462 /**************************************************************************
1463 * ReplaceFileW (KERNEL32.@)
1464 * ReplaceFile (KERNEL32.@)
1466 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1467 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1468 LPVOID lpExclude, LPVOID lpReserved)
1470 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1471 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1472 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1477 /**************************************************************************
1478 * ReplaceFileA (KERNEL32.@)
1480 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1481 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1482 LPVOID lpExclude, LPVOID lpReserved)
1484 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1485 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1486 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1491 /*************************************************************************
1492 * FindFirstFileExW (KERNEL32.@)
1494 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1495 LPVOID data, FINDEX_SEARCH_OPS search_op,
1496 LPVOID filter, DWORD flags)
1499 FIND_FIRST_INFO *info = NULL;
1500 UNICODE_STRING nt_name;
1501 OBJECT_ATTRIBUTES attr;
1505 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1507 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1510 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1511 return INVALID_HANDLE_VALUE;
1513 if (level != FindExInfoStandard)
1515 FIXME("info level %d not implemented\n", level );
1516 return INVALID_HANDLE_VALUE;
1519 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1521 SetLastError( ERROR_PATH_NOT_FOUND );
1522 return INVALID_HANDLE_VALUE;
1525 if (!mask || !*mask)
1527 SetLastError( ERROR_FILE_NOT_FOUND );
1531 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1533 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1537 if (!RtlCreateUnicodeString( &info->mask, mask ))
1539 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1543 /* truncate dir name before mask */
1545 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1547 /* check if path is the root of the drive */
1548 info->is_root = FALSE;
1549 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1550 if (p[0] && p[1] == ':')
1553 while (*p == '\\') p++;
1554 info->is_root = (*p == 0);
1557 attr.Length = sizeof(attr);
1558 attr.RootDirectory = 0;
1559 attr.Attributes = OBJ_CASE_INSENSITIVE;
1560 attr.ObjectName = &nt_name;
1561 attr.SecurityDescriptor = NULL;
1562 attr.SecurityQualityOfService = NULL;
1564 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1565 FILE_SHARE_READ | FILE_SHARE_WRITE,
1566 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1568 if (status != STATUS_SUCCESS)
1570 RtlFreeUnicodeString( &info->mask );
1571 SetLastError( RtlNtStatusToDosError(status) );
1575 RtlInitializeCriticalSection( &info->cs );
1576 info->path = nt_name;
1577 info->magic = FIND_FIRST_MAGIC;
1580 info->search_op = search_op;
1582 if (!FindNextFileW( (HANDLE)info, data ))
1584 TRACE( "%s not found\n", debugstr_w(filename) );
1585 FindClose( (HANDLE)info );
1586 SetLastError( ERROR_FILE_NOT_FOUND );
1587 return INVALID_HANDLE_VALUE;
1589 return (HANDLE)info;
1592 HeapFree( GetProcessHeap(), 0, info );
1593 RtlFreeUnicodeString( &nt_name );
1594 return INVALID_HANDLE_VALUE;
1598 /*************************************************************************
1599 * FindNextFileW (KERNEL32.@)
1601 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1603 FIND_FIRST_INFO *info;
1604 FILE_BOTH_DIR_INFORMATION *dir_info;
1607 TRACE("%p %p\n", handle, data);
1609 if (!handle || handle == INVALID_HANDLE_VALUE)
1611 SetLastError( ERROR_INVALID_HANDLE );
1614 info = (FIND_FIRST_INFO *)handle;
1615 if (info->magic != FIND_FIRST_MAGIC)
1617 SetLastError( ERROR_INVALID_HANDLE );
1621 RtlEnterCriticalSection( &info->cs );
1625 if (info->data_pos >= info->data_len) /* need to read some more data */
1629 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1630 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1633 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1636 info->data_len = io.Information;
1640 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1642 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1643 else info->data_pos = info->data_len;
1645 /* don't return '.' and '..' in the root of the drive */
1648 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1649 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1650 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1653 /* check for dir symlink */
1654 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1655 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
1657 if (!check_dir_symlink( info, dir_info )) continue;
1659 if (info->search_op == FindExSearchLimitToDirectories &&
1660 (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1663 data->dwFileAttributes = dir_info->FileAttributes;
1664 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1665 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1666 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1667 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1668 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1669 data->dwReserved0 = 0;
1670 data->dwReserved1 = 0;
1672 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1673 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1674 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1675 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1677 TRACE("returning %s (%s)\n",
1678 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1684 RtlLeaveCriticalSection( &info->cs );
1689 /*************************************************************************
1690 * FindClose (KERNEL32.@)
1692 BOOL WINAPI FindClose( HANDLE handle )
1694 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1696 if (!handle || handle == INVALID_HANDLE_VALUE)
1698 SetLastError( ERROR_INVALID_HANDLE );
1704 if (info->magic == FIND_FIRST_MAGIC)
1706 RtlEnterCriticalSection( &info->cs );
1707 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1710 if (info->handle) CloseHandle( info->handle );
1712 RtlFreeUnicodeString( &info->mask );
1713 info->mask.Buffer = NULL;
1714 RtlFreeUnicodeString( &info->path );
1717 RtlLeaveCriticalSection( &info->cs );
1718 RtlDeleteCriticalSection( &info->cs );
1719 HeapFree( GetProcessHeap(), 0, info );
1723 __EXCEPT(page_fault)
1725 WARN("Illegal handle %p\n", handle);
1726 SetLastError( ERROR_INVALID_HANDLE );
1735 /*************************************************************************
1736 * FindFirstFileA (KERNEL32.@)
1738 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1740 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1741 FindExSearchNameMatch, NULL, 0);
1744 /*************************************************************************
1745 * FindFirstFileExA (KERNEL32.@)
1747 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1748 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1749 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1752 WIN32_FIND_DATAA *dataA;
1753 WIN32_FIND_DATAW dataW;
1756 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1758 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1759 if (handle == INVALID_HANDLE_VALUE) return handle;
1761 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1762 dataA->dwFileAttributes = dataW.dwFileAttributes;
1763 dataA->ftCreationTime = dataW.ftCreationTime;
1764 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1765 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1766 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1767 dataA->nFileSizeLow = dataW.nFileSizeLow;
1768 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1769 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1770 sizeof(dataA->cAlternateFileName) );
1775 /*************************************************************************
1776 * FindFirstFileW (KERNEL32.@)
1778 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1780 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1781 FindExSearchNameMatch, NULL, 0);
1785 /*************************************************************************
1786 * FindNextFileA (KERNEL32.@)
1788 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1790 WIN32_FIND_DATAW dataW;
1792 if (!FindNextFileW( handle, &dataW )) return FALSE;
1793 data->dwFileAttributes = dataW.dwFileAttributes;
1794 data->ftCreationTime = dataW.ftCreationTime;
1795 data->ftLastAccessTime = dataW.ftLastAccessTime;
1796 data->ftLastWriteTime = dataW.ftLastWriteTime;
1797 data->nFileSizeHigh = dataW.nFileSizeHigh;
1798 data->nFileSizeLow = dataW.nFileSizeLow;
1799 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1800 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1801 sizeof(data->cAlternateFileName) );
1806 /**************************************************************************
1807 * GetFileAttributesW (KERNEL32.@)
1809 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1811 FILE_BASIC_INFORMATION info;
1812 UNICODE_STRING nt_name;
1813 OBJECT_ATTRIBUTES attr;
1816 TRACE("%s\n", debugstr_w(name));
1818 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1820 SetLastError( ERROR_PATH_NOT_FOUND );
1821 return INVALID_FILE_ATTRIBUTES;
1824 attr.Length = sizeof(attr);
1825 attr.RootDirectory = 0;
1826 attr.Attributes = OBJ_CASE_INSENSITIVE;
1827 attr.ObjectName = &nt_name;
1828 attr.SecurityDescriptor = NULL;
1829 attr.SecurityQualityOfService = NULL;
1831 status = NtQueryAttributesFile( &attr, &info );
1832 RtlFreeUnicodeString( &nt_name );
1834 if (status == STATUS_SUCCESS) return info.FileAttributes;
1836 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1837 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1839 SetLastError( RtlNtStatusToDosError(status) );
1840 return INVALID_FILE_ATTRIBUTES;
1844 /**************************************************************************
1845 * GetFileAttributesA (KERNEL32.@)
1847 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1851 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1852 return GetFileAttributesW( nameW );
1856 /**************************************************************************
1857 * SetFileAttributesW (KERNEL32.@)
1859 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1861 UNICODE_STRING nt_name;
1862 OBJECT_ATTRIBUTES attr;
1867 TRACE("%s %lx\n", debugstr_w(name), attributes);
1869 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1871 SetLastError( ERROR_PATH_NOT_FOUND );
1875 attr.Length = sizeof(attr);
1876 attr.RootDirectory = 0;
1877 attr.Attributes = OBJ_CASE_INSENSITIVE;
1878 attr.ObjectName = &nt_name;
1879 attr.SecurityDescriptor = NULL;
1880 attr.SecurityQualityOfService = NULL;
1882 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1883 RtlFreeUnicodeString( &nt_name );
1885 if (status == STATUS_SUCCESS)
1887 FILE_BASIC_INFORMATION info;
1889 memset( &info, 0, sizeof(info) );
1890 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1891 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1895 if (status == STATUS_SUCCESS) return TRUE;
1896 SetLastError( RtlNtStatusToDosError(status) );
1901 /**************************************************************************
1902 * SetFileAttributesA (KERNEL32.@)
1904 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1908 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1909 return SetFileAttributesW( nameW, attributes );
1913 /**************************************************************************
1914 * GetFileAttributesExW (KERNEL32.@)
1916 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1918 FILE_NETWORK_OPEN_INFORMATION info;
1919 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1920 UNICODE_STRING nt_name;
1921 OBJECT_ATTRIBUTES attr;
1924 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1926 if (level != GetFileExInfoStandard)
1928 SetLastError( ERROR_INVALID_PARAMETER );
1932 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1934 SetLastError( ERROR_PATH_NOT_FOUND );
1938 attr.Length = sizeof(attr);
1939 attr.RootDirectory = 0;
1940 attr.Attributes = OBJ_CASE_INSENSITIVE;
1941 attr.ObjectName = &nt_name;
1942 attr.SecurityDescriptor = NULL;
1943 attr.SecurityQualityOfService = NULL;
1945 status = NtQueryFullAttributesFile( &attr, &info );
1946 RtlFreeUnicodeString( &nt_name );
1948 if (status != STATUS_SUCCESS)
1950 SetLastError( RtlNtStatusToDosError(status) );
1954 data->dwFileAttributes = info.FileAttributes;
1955 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1956 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1957 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1958 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1959 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1960 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1961 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1962 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1967 /**************************************************************************
1968 * GetFileAttributesExA (KERNEL32.@)
1970 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1974 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1975 return GetFileAttributesExW( nameW, level, ptr );
1979 /******************************************************************************
1980 * GetCompressedFileSizeW (KERNEL32.@)
1982 * Get the actual number of bytes used on disk.
1985 * Success: Low-order doubleword of number of bytes
1986 * Failure: INVALID_FILE_SIZE
1988 DWORD WINAPI GetCompressedFileSizeW(
1989 LPCWSTR name, /* [in] Pointer to name of file */
1990 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1992 UNICODE_STRING nt_name;
1993 OBJECT_ATTRIBUTES attr;
1997 DWORD ret = INVALID_FILE_SIZE;
1999 TRACE("%s %p\n", debugstr_w(name), size_high);
2001 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2003 SetLastError( ERROR_PATH_NOT_FOUND );
2004 return INVALID_FILE_SIZE;
2007 attr.Length = sizeof(attr);
2008 attr.RootDirectory = 0;
2009 attr.Attributes = OBJ_CASE_INSENSITIVE;
2010 attr.ObjectName = &nt_name;
2011 attr.SecurityDescriptor = NULL;
2012 attr.SecurityQualityOfService = NULL;
2014 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2015 RtlFreeUnicodeString( &nt_name );
2017 if (status == STATUS_SUCCESS)
2019 /* we don't support compressed files, simply return the file size */
2020 ret = GetFileSize( handle, size_high );
2023 else SetLastError( RtlNtStatusToDosError(status) );
2029 /******************************************************************************
2030 * GetCompressedFileSizeA (KERNEL32.@)
2032 * See GetCompressedFileSizeW.
2034 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2038 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2039 return GetCompressedFileSizeW( nameW, size_high );
2043 /***********************************************************************
2044 * OpenFile (KERNEL32.@)
2046 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2050 WORD filedatetime[2];
2052 if (!ofs) return HFILE_ERROR;
2054 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2055 ((mode & 0x3 )==OF_READ)?"OF_READ":
2056 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2057 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2058 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2059 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2060 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2061 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2062 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2063 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2064 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2065 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2066 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2067 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2068 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2069 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2070 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2071 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2075 ofs->cBytes = sizeof(OFSTRUCT);
2077 if (mode & OF_REOPEN) name = ofs->szPathName;
2079 if (!name) return HFILE_ERROR;
2081 TRACE("%s %04x\n", name, mode );
2083 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2084 Are there any cases where getting the path here is wrong?
2085 Uwe Bonnes 1997 Apr 2 */
2086 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2088 /* OF_PARSE simply fills the structure */
2090 if (mode & OF_PARSE)
2092 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2093 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2097 /* OF_CREATE is completely different from all other options, so
2100 if (mode & OF_CREATE)
2102 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2107 /* Now look for the file */
2109 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2112 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2114 if (mode & OF_DELETE)
2116 if (!DeleteFileA( ofs->szPathName )) goto error;
2117 TRACE("(%s): OF_DELETE return = OK\n", name);
2121 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2122 if (handle == INVALID_HANDLE_VALUE) goto error;
2124 GetFileTime( handle, NULL, NULL, &filetime );
2125 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2126 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2128 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2130 CloseHandle( handle );
2131 WARN("(%s): OF_VERIFY failed\n", name );
2132 /* FIXME: what error here? */
2133 SetLastError( ERROR_FILE_NOT_FOUND );
2137 ofs->Reserved1 = filedatetime[0];
2138 ofs->Reserved2 = filedatetime[1];
2140 TRACE("(%s): OK, return = %p\n", name, handle );
2141 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2143 CloseHandle( handle );
2146 else return (HFILE)handle;
2148 error: /* We get here if there was an error opening the file */
2149 ofs->nErrCode = GetLastError();
2150 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );