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
41 #include "wine/winbase16.h"
42 #include "kernel_private.h"
44 #include "wine/exception.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
49 #include "wine/server.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(file);
53 HANDLE dos_handles[DOS_TABLE_SIZE];
55 /* info structure for FindFirstFile handle */
58 DWORD magic; /* magic number */
59 HANDLE handle; /* handle to directory */
60 CRITICAL_SECTION cs; /* crit section protecting this structure */
61 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
62 UNICODE_STRING mask; /* file mask */
63 UNICODE_STRING path; /* NT path used to open the directory */
64 BOOL is_root; /* is directory the root of the drive? */
65 UINT data_pos; /* current position in dir data */
66 UINT data_len; /* length of dir data */
67 BYTE data[8192]; /* directory data */
70 #define FIND_FIRST_MAGIC 0xc0ffee11
72 static BOOL oem_file_apis;
74 static WINE_EXCEPTION_FILTER(page_fault)
76 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
77 return EXCEPTION_EXECUTE_HANDLER;
78 return EXCEPTION_CONTINUE_SEARCH;
82 /***********************************************************************
85 * Wrapper for CreateFile that takes OF_* mode flags.
87 static HANDLE create_file_OF( LPCSTR path, INT mode )
89 DWORD access, sharing, creation;
93 creation = CREATE_ALWAYS;
94 access = GENERIC_READ | GENERIC_WRITE;
98 creation = OPEN_EXISTING;
101 case OF_READ: access = GENERIC_READ; break;
102 case OF_WRITE: access = GENERIC_WRITE; break;
103 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
104 default: access = 0; break;
110 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
111 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
112 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
113 case OF_SHARE_DENY_NONE:
114 case OF_SHARE_COMPAT:
115 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
117 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
121 /***********************************************************************
124 * Check if a dir symlink should be returned by FindNextFile.
126 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
129 ANSI_STRING unix_name;
130 struct stat st, parent_st;
134 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
135 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
136 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
137 len = info->path.Length / sizeof(WCHAR);
138 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
139 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
140 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
142 unix_name.Buffer = NULL;
143 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
144 !stat( unix_name.Buffer, &st ))
146 char *p = unix_name.Buffer + unix_name.Length - 1;
148 /* skip trailing slashes */
149 while (p > unix_name.Buffer && *p == '/') p--;
151 while (ret && p > unix_name.Buffer)
153 while (p > unix_name.Buffer && *p != '/') p--;
154 while (p > unix_name.Buffer && *p == '/') p--;
156 if (!stat( unix_name.Buffer, &parent_st ) &&
157 parent_st.st_dev == st.st_dev &&
158 parent_st.st_ino == st.st_ino)
160 WARN( "suppressing dir symlink %s pointing to parent %s\n",
161 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
162 debugstr_a( unix_name.Buffer ));
167 RtlFreeAnsiString( &unix_name );
168 RtlFreeUnicodeString( &str );
173 /***********************************************************************
176 * Set the DOS error code from errno.
178 void FILE_SetDosError(void)
180 int save_errno = errno; /* errno gets overwritten by printf */
182 TRACE("errno = %d %s\n", errno, strerror(errno));
186 SetLastError( ERROR_SHARING_VIOLATION );
189 SetLastError( ERROR_INVALID_HANDLE );
192 SetLastError( ERROR_HANDLE_DISK_FULL );
197 SetLastError( ERROR_ACCESS_DENIED );
200 SetLastError( ERROR_LOCK_VIOLATION );
203 SetLastError( ERROR_FILE_NOT_FOUND );
206 SetLastError( ERROR_CANNOT_MAKE );
210 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
213 SetLastError( ERROR_FILE_EXISTS );
217 SetLastError( ERROR_SEEK );
220 SetLastError( ERROR_DIR_NOT_EMPTY );
223 SetLastError( ERROR_BAD_FORMAT );
226 SetLastError( ERROR_PATH_NOT_FOUND );
229 SetLastError( ERROR_NOT_SAME_DEVICE );
232 WARN("unknown file error: %s\n", strerror(save_errno) );
233 SetLastError( ERROR_GEN_FAILURE );
240 /***********************************************************************
243 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
245 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
246 * there is no possibility for the function to do that twice, taking into
247 * account any called function.
249 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
252 UNICODE_STRING strW, *pstrW;
255 RtlInitAnsiString( &str, name );
256 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
258 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
260 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
261 if (status == STATUS_SUCCESS) return pstrW->Buffer;
263 if (status == STATUS_BUFFER_OVERFLOW)
264 SetLastError( ERROR_FILENAME_EXCED_RANGE );
266 SetLastError( RtlNtStatusToDosError(status) );
271 /***********************************************************************
274 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
276 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
280 if (srclen < 0) srclen = strlenW( src ) + 1;
282 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
284 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
289 /**************************************************************************
290 * SetFileApisToOEM (KERNEL32.@)
292 VOID WINAPI SetFileApisToOEM(void)
294 oem_file_apis = TRUE;
298 /**************************************************************************
299 * SetFileApisToANSI (KERNEL32.@)
301 VOID WINAPI SetFileApisToANSI(void)
303 oem_file_apis = FALSE;
307 /******************************************************************************
308 * AreFileApisANSI (KERNEL32.@)
310 * Determines if file functions are using ANSI
313 * TRUE: Set of file functions is using ANSI code page
314 * FALSE: Set of file functions is using OEM code page
316 BOOL WINAPI AreFileApisANSI(void)
318 return !oem_file_apis;
322 /**************************************************************************
323 * Operations on file handles *
324 **************************************************************************/
326 /***********************************************************************
327 * FILE_InitProcessDosHandles
329 * Allocates the default DOS handles for a process. Called either by
330 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
332 static void FILE_InitProcessDosHandles( void )
334 static BOOL init_done /* = FALSE */;
335 HANDLE cp = GetCurrentProcess();
337 if (init_done) return;
339 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
340 0, TRUE, DUPLICATE_SAME_ACCESS);
341 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
342 0, TRUE, DUPLICATE_SAME_ACCESS);
343 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
344 0, TRUE, DUPLICATE_SAME_ACCESS);
345 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
346 0, TRUE, DUPLICATE_SAME_ACCESS);
347 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
348 0, TRUE, DUPLICATE_SAME_ACCESS);
352 /******************************************************************
353 * FILE_ReadWriteApc (internal)
355 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
357 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
359 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
363 /***********************************************************************
364 * ReadFileEx (KERNEL32.@)
366 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
367 LPOVERLAPPED overlapped,
368 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
370 LARGE_INTEGER offset;
372 PIO_STATUS_BLOCK io_status;
374 TRACE("(hFile=%p, buffer=%p, bytes=%lu, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
378 SetLastError(ERROR_INVALID_PARAMETER);
382 offset.u.LowPart = overlapped->u.s.Offset;
383 offset.u.HighPart = overlapped->u.s.OffsetHigh;
384 io_status = (PIO_STATUS_BLOCK)overlapped;
385 io_status->u.Status = STATUS_PENDING;
387 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
388 io_status, buffer, bytesToRead, &offset, NULL);
392 SetLastError( RtlNtStatusToDosError(status) );
399 /***********************************************************************
400 * ReadFile (KERNEL32.@)
402 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
403 LPDWORD bytesRead, LPOVERLAPPED overlapped )
405 LARGE_INTEGER offset;
406 PLARGE_INTEGER poffset = NULL;
407 IO_STATUS_BLOCK iosb;
408 PIO_STATUS_BLOCK io_status = &iosb;
412 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
413 bytesRead, overlapped );
415 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
416 if (!bytesToRead) return TRUE;
418 if (is_console_handle(hFile))
419 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
421 if (overlapped != NULL)
423 offset.u.LowPart = overlapped->u.s.Offset;
424 offset.u.HighPart = overlapped->u.s.OffsetHigh;
426 hEvent = overlapped->hEvent;
427 io_status = (PIO_STATUS_BLOCK)overlapped;
429 io_status->u.Status = STATUS_PENDING;
430 io_status->Information = 0;
432 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
434 if (status != STATUS_PENDING && bytesRead)
435 *bytesRead = io_status->Information;
437 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
439 SetLastError( RtlNtStatusToDosError(status) );
446 /***********************************************************************
447 * WriteFileEx (KERNEL32.@)
449 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
450 LPOVERLAPPED overlapped,
451 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
453 LARGE_INTEGER offset;
455 PIO_STATUS_BLOCK io_status;
457 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
459 if (overlapped == NULL)
461 SetLastError(ERROR_INVALID_PARAMETER);
464 offset.u.LowPart = overlapped->u.s.Offset;
465 offset.u.HighPart = overlapped->u.s.OffsetHigh;
467 io_status = (PIO_STATUS_BLOCK)overlapped;
468 io_status->u.Status = STATUS_PENDING;
470 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
471 io_status, buffer, bytesToWrite, &offset, NULL);
473 if (status) SetLastError( RtlNtStatusToDosError(status) );
478 /***********************************************************************
479 * WriteFile (KERNEL32.@)
481 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
482 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
484 HANDLE hEvent = NULL;
485 LARGE_INTEGER offset;
486 PLARGE_INTEGER poffset = NULL;
488 IO_STATUS_BLOCK iosb;
489 PIO_STATUS_BLOCK piosb = &iosb;
491 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
493 if (is_console_handle(hFile))
494 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
498 offset.u.LowPart = overlapped->u.s.Offset;
499 offset.u.HighPart = overlapped->u.s.OffsetHigh;
501 hEvent = overlapped->hEvent;
502 piosb = (PIO_STATUS_BLOCK)overlapped;
504 piosb->u.Status = STATUS_PENDING;
505 piosb->Information = 0;
507 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
508 buffer, bytesToWrite, poffset, NULL);
510 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
511 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
513 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
514 buffer, bytesToWrite, poffset, NULL);
515 if (status != STATUS_INVALID_USER_BUFFER)
516 FIXME("Could not access memory (%p,%ld) at first, now OK. Protected by DIBSection code?\n",
517 buffer, bytesToWrite);
520 if (status != STATUS_PENDING && bytesWritten)
521 *bytesWritten = piosb->Information;
523 if (status && status != STATUS_TIMEOUT)
525 SetLastError( RtlNtStatusToDosError(status) );
532 /***********************************************************************
533 * GetOverlappedResult (KERNEL32.@)
535 * Check the result of an Asynchronous data transfer from a file.
538 * HANDLE hFile [in] handle of file to check on
539 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
540 * LPDWORD lpTransferred [in/out] number of bytes transferred
541 * BOOL bWait [in] wait for the transfer to complete ?
547 * If successful (and relevant) lpTransferred will hold the number of
548 * bytes transferred during the async operation.
552 * Currently only works for WaitCommEvent, ReadFile, WriteFile
553 * with communications ports.
556 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
557 LPDWORD lpTransferred, BOOL bWait)
559 DWORD r = WAIT_OBJECT_0;
561 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
563 if ( lpOverlapped == NULL )
565 ERR("lpOverlapped was null\n");
570 if ( lpOverlapped->hEvent )
574 TRACE( "waiting on %p\n", lpOverlapped );
575 r = WaitForSingleObjectEx( lpOverlapped->hEvent, INFINITE, TRUE );
576 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
577 } while ( r == WAIT_IO_COMPLETION );
582 while ( ((volatile OVERLAPPED*)lpOverlapped)->Internal == STATUS_PENDING )
586 else if ( lpOverlapped->Internal == STATUS_PENDING )
588 /* Wait in order to give APCs a chance to run. */
589 /* This is cheating, so we must set the event again in case of success -
590 it may be a non-manual reset event. */
593 TRACE( "waiting on %p\n", lpOverlapped );
594 r = WaitForSingleObjectEx( lpOverlapped->hEvent, 0, TRUE );
595 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
596 } while ( r == WAIT_IO_COMPLETION );
597 if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
598 NtSetEvent( lpOverlapped->hEvent, NULL );
600 if ( r == WAIT_FAILED )
602 WARN("wait operation failed\n");
605 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
607 switch ( lpOverlapped->Internal )
612 SetLastError( ERROR_IO_INCOMPLETE );
613 if ( bWait ) ERR("PENDING status after waiting!\n");
616 SetLastError( RtlNtStatusToDosError( lpOverlapped->Internal ) );
621 /***********************************************************************
622 * CancelIo (KERNEL32.@)
624 BOOL WINAPI CancelIo(HANDLE handle)
626 IO_STATUS_BLOCK io_status;
628 NtCancelIoFile(handle, &io_status);
629 if (io_status.u.Status)
631 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
637 /***********************************************************************
638 * _hread (KERNEL32.@)
640 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
642 return _lread( hFile, buffer, count );
646 /***********************************************************************
647 * _hwrite (KERNEL32.@)
649 * experimentation yields that _lwrite:
650 * o truncates the file at the current position with
652 * o returns 0 on a 0 length write
653 * o works with console handles
656 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
660 TRACE("%d %p %ld\n", handle, buffer, count );
664 /* Expand or truncate at current position */
665 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
668 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
674 /***********************************************************************
675 * _lclose (KERNEL32.@)
677 HFILE WINAPI _lclose( HFILE hFile )
679 TRACE("handle %d\n", hFile );
680 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
684 /***********************************************************************
685 * _lcreat (KERNEL32.@)
687 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
689 /* Mask off all flags not explicitly allowed by the doc */
690 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
691 TRACE("%s %02x\n", path, attr );
692 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
693 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
694 CREATE_ALWAYS, attr, 0 );
698 /***********************************************************************
699 * _lopen (KERNEL32.@)
701 HFILE WINAPI _lopen( LPCSTR path, INT mode )
703 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
704 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
707 /***********************************************************************
708 * _lread (KERNEL32.@)
710 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
713 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
719 /***********************************************************************
720 * _llseek (KERNEL32.@)
722 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
724 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
728 /***********************************************************************
729 * _lwrite (KERNEL32.@)
731 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
733 return (UINT)_hwrite( hFile, buffer, (LONG)count );
737 /***********************************************************************
738 * FlushFileBuffers (KERNEL32.@)
740 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
743 IO_STATUS_BLOCK ioblk;
745 if (is_console_handle( hFile ))
747 /* this will fail (as expected) for an output handle */
748 return FlushConsoleInputBuffer( hFile );
750 nts = NtFlushBuffersFile( hFile, &ioblk );
751 if (nts != STATUS_SUCCESS)
753 SetLastError( RtlNtStatusToDosError( nts ) );
761 /***********************************************************************
762 * GetFileType (KERNEL32.@)
764 DWORD WINAPI GetFileType( HANDLE hFile )
766 FILE_FS_DEVICE_INFORMATION info;
770 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
772 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
773 if (status != STATUS_SUCCESS)
775 SetLastError( RtlNtStatusToDosError(status) );
776 return FILE_TYPE_UNKNOWN;
779 switch(info.DeviceType)
781 case FILE_DEVICE_NULL:
782 case FILE_DEVICE_SERIAL_PORT:
783 case FILE_DEVICE_PARALLEL_PORT:
784 case FILE_DEVICE_UNKNOWN:
785 return FILE_TYPE_CHAR;
786 case FILE_DEVICE_NAMED_PIPE:
787 return FILE_TYPE_PIPE;
789 return FILE_TYPE_DISK;
794 /***********************************************************************
795 * GetFileInformationByHandle (KERNEL32.@)
797 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
799 FILE_ALL_INFORMATION all_info;
803 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
804 if (status == STATUS_SUCCESS)
806 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
807 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
808 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
809 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
810 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
811 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
812 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
813 info->dwVolumeSerialNumber = 0; /* FIXME */
814 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
815 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
816 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
817 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
818 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
821 SetLastError( RtlNtStatusToDosError(status) );
826 /***********************************************************************
827 * GetFileSize (KERNEL32.@)
829 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
832 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
833 if (filesizehigh) *filesizehigh = size.u.HighPart;
834 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
835 return size.u.LowPart;
839 /***********************************************************************
840 * GetFileSizeEx (KERNEL32.@)
842 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
844 FILE_END_OF_FILE_INFORMATION info;
848 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
849 if (status == STATUS_SUCCESS)
851 *lpFileSize = info.EndOfFile;
854 SetLastError( RtlNtStatusToDosError(status) );
859 /**************************************************************************
860 * SetEndOfFile (KERNEL32.@)
862 BOOL WINAPI SetEndOfFile( HANDLE hFile )
864 FILE_POSITION_INFORMATION pos;
865 FILE_END_OF_FILE_INFORMATION eof;
869 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
870 if (status == STATUS_SUCCESS)
872 eof.EndOfFile = pos.CurrentByteOffset;
873 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
875 if (status == STATUS_SUCCESS) return TRUE;
876 SetLastError( RtlNtStatusToDosError(status) );
881 /***********************************************************************
882 * SetFilePointer (KERNEL32.@)
884 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
886 LARGE_INTEGER dist, newpos;
890 dist.u.LowPart = distance;
891 dist.u.HighPart = *highword;
893 else dist.QuadPart = distance;
895 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
897 if (highword) *highword = newpos.u.HighPart;
898 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
899 return newpos.u.LowPart;
903 /***********************************************************************
904 * SetFilePointerEx (KERNEL32.@)
906 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
907 LARGE_INTEGER *newpos, DWORD method )
909 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
914 TRACE("handle %p offset %s newpos %p origin %ld\n",
915 hFile, wine_dbgstr_longlong(distance.QuadPart), newpos, method );
917 if (method > FILE_END)
919 SetLastError( ERROR_INVALID_PARAMETER );
923 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL )))
927 pos = distance.QuadPart;
928 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
930 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
931 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
932 SetLastError( ERROR_NEGATIVE_SEEK );
940 newpos->QuadPart = res;
942 wine_server_release_fd( hFile, fd );
944 else SetLastError( RtlNtStatusToDosError(status) );
949 /***********************************************************************
950 * GetFileTime (KERNEL32.@)
952 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
953 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
955 FILE_BASIC_INFORMATION info;
959 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
960 if (status == STATUS_SUCCESS)
964 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
965 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
967 if (lpLastAccessTime)
969 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
970 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
974 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
975 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
979 SetLastError( RtlNtStatusToDosError(status) );
984 /***********************************************************************
985 * SetFileTime (KERNEL32.@)
987 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
988 const FILETIME *atime, const FILETIME *mtime )
990 FILE_BASIC_INFORMATION info;
994 memset( &info, 0, sizeof(info) );
997 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
998 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1002 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1003 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1007 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1008 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1011 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1012 if (status == STATUS_SUCCESS) return TRUE;
1013 SetLastError( RtlNtStatusToDosError(status) );
1018 /**************************************************************************
1019 * LockFile (KERNEL32.@)
1021 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1022 DWORD count_low, DWORD count_high )
1025 LARGE_INTEGER count, offset;
1027 TRACE( "%p %lx%08lx %lx%08lx\n",
1028 hFile, offset_high, offset_low, count_high, count_low );
1030 count.u.LowPart = count_low;
1031 count.u.HighPart = count_high;
1032 offset.u.LowPart = offset_low;
1033 offset.u.HighPart = offset_high;
1035 status = NtLockFile( hFile, 0, NULL, NULL,
1036 NULL, &offset, &count, NULL, TRUE, TRUE );
1038 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1043 /**************************************************************************
1044 * LockFileEx [KERNEL32.@]
1046 * Locks a byte range within an open file for shared or exclusive access.
1053 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1055 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1056 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1059 LARGE_INTEGER count, offset;
1063 SetLastError( ERROR_INVALID_PARAMETER );
1067 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
1068 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1069 count_high, count_low, flags );
1071 count.u.LowPart = count_low;
1072 count.u.HighPart = count_high;
1073 offset.u.LowPart = overlapped->u.s.Offset;
1074 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1076 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1077 NULL, &offset, &count, NULL,
1078 flags & LOCKFILE_FAIL_IMMEDIATELY,
1079 flags & LOCKFILE_EXCLUSIVE_LOCK );
1081 if (status) SetLastError( RtlNtStatusToDosError(status) );
1086 /**************************************************************************
1087 * UnlockFile (KERNEL32.@)
1089 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1090 DWORD count_low, DWORD count_high )
1093 LARGE_INTEGER count, offset;
1095 count.u.LowPart = count_low;
1096 count.u.HighPart = count_high;
1097 offset.u.LowPart = offset_low;
1098 offset.u.HighPart = offset_high;
1100 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1101 if (status) SetLastError( RtlNtStatusToDosError(status) );
1106 /**************************************************************************
1107 * UnlockFileEx (KERNEL32.@)
1109 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1110 LPOVERLAPPED overlapped )
1114 SetLastError( ERROR_INVALID_PARAMETER );
1117 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1119 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1123 /***********************************************************************
1124 * Win32HandleToDosFileHandle (KERNEL32.21)
1126 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1127 * longer valid after this function (even on failure).
1129 * Note: this is not exactly right, since on Win95 the Win32 handles
1130 * are on top of DOS handles and we do it the other way
1131 * around. Should be good enough though.
1133 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1137 if (!handle || (handle == INVALID_HANDLE_VALUE))
1140 FILE_InitProcessDosHandles();
1141 for (i = 0; i < DOS_TABLE_SIZE; i++)
1142 if (!dos_handles[i])
1144 dos_handles[i] = handle;
1145 TRACE("Got %d for h32 %p\n", i, handle );
1148 CloseHandle( handle );
1149 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1154 /***********************************************************************
1155 * DosFileHandleToWin32Handle (KERNEL32.20)
1157 * Return the Win32 handle for a DOS handle.
1159 * Note: this is not exactly right, since on Win95 the Win32 handles
1160 * are on top of DOS handles and we do it the other way
1161 * around. Should be good enough though.
1163 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1165 HFILE16 hfile = (HFILE16)handle;
1166 if (hfile < 5) FILE_InitProcessDosHandles();
1167 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1169 SetLastError( ERROR_INVALID_HANDLE );
1170 return INVALID_HANDLE_VALUE;
1172 return dos_handles[hfile];
1176 /*************************************************************************
1177 * SetHandleCount (KERNEL32.@)
1179 UINT WINAPI SetHandleCount( UINT count )
1181 return min( 256, count );
1185 /***********************************************************************
1186 * DisposeLZ32Handle (KERNEL32.22)
1188 * Note: this is not entirely correct, we should only close the
1189 * 32-bit handle and not the 16-bit one, but we cannot do
1190 * this because of the way our DOS handles are implemented.
1191 * It shouldn't break anything though.
1193 void WINAPI DisposeLZ32Handle( HANDLE handle )
1197 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1199 for (i = 5; i < DOS_TABLE_SIZE; i++)
1200 if (dos_handles[i] == handle)
1203 CloseHandle( handle );
1208 /**************************************************************************
1209 * Operations on file names *
1210 **************************************************************************/
1213 /*************************************************************************
1214 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1216 * Creates or opens an object, and returns a handle that can be used to
1217 * access that object.
1221 * filename [in] pointer to filename to be accessed
1222 * access [in] access mode requested
1223 * sharing [in] share mode
1224 * sa [in] pointer to security attributes
1225 * creation [in] how to create the file
1226 * attributes [in] attributes for newly created file
1227 * template [in] handle to file with extended attributes to copy
1230 * Success: Open handle to specified file
1231 * Failure: INVALID_HANDLE_VALUE
1233 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1234 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1235 DWORD attributes, HANDLE template )
1239 OBJECT_ATTRIBUTES attr;
1240 UNICODE_STRING nameW;
1244 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1245 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1246 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1248 static const UINT nt_disposition[5] =
1250 FILE_CREATE, /* CREATE_NEW */
1251 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1252 FILE_OPEN, /* OPEN_EXISTING */
1253 FILE_OPEN_IF, /* OPEN_ALWAYS */
1254 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1260 if (!filename || !filename[0])
1262 SetLastError( ERROR_PATH_NOT_FOUND );
1263 return INVALID_HANDLE_VALUE;
1266 TRACE("%s %s%s%s%s%s%s creation %ld attributes 0x%lx\n", debugstr_w(filename),
1267 (access & GENERIC_READ)?"GENERIC_READ ":"",
1268 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1269 (!access)?"QUERY_ACCESS ":"",
1270 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1271 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1272 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1273 creation, attributes);
1275 /* Open a console for CONIN$ or CONOUT$ */
1277 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1279 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1283 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1285 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1286 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1288 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1289 !strncmpiW( filename + 4, pipeW, 5 ) ||
1290 !strncmpiW( filename + 4, mailslotW, 9 ))
1294 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1296 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1298 else if (filename[4])
1300 ret = VXD_Open( filename+4, access, sa );
1305 SetLastError( ERROR_INVALID_NAME );
1306 return INVALID_HANDLE_VALUE;
1309 else dosdev = RtlIsDosDeviceName_U( filename );
1313 static const WCHAR conW[] = {'C','O','N'};
1315 if (LOWORD(dosdev) == sizeof(conW) &&
1316 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1318 switch (access & (GENERIC_READ|GENERIC_WRITE))
1321 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1324 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1327 SetLastError( ERROR_FILE_NOT_FOUND );
1328 return INVALID_HANDLE_VALUE;
1333 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1335 SetLastError( ERROR_INVALID_PARAMETER );
1336 return INVALID_HANDLE_VALUE;
1339 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1341 SetLastError( ERROR_PATH_NOT_FOUND );
1342 return INVALID_HANDLE_VALUE;
1345 /* now call NtCreateFile */
1348 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1349 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1351 options |= FILE_NON_DIRECTORY_FILE;
1352 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1353 options |= FILE_DELETE_ON_CLOSE;
1354 if (!(attributes & FILE_FLAG_OVERLAPPED))
1355 options |= FILE_SYNCHRONOUS_IO_ALERT;
1356 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1357 options |= FILE_RANDOM_ACCESS;
1358 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1360 attr.Length = sizeof(attr);
1361 attr.RootDirectory = 0;
1362 attr.Attributes = OBJ_CASE_INSENSITIVE;
1363 attr.ObjectName = &nameW;
1364 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1365 attr.SecurityQualityOfService = NULL;
1367 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1369 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1370 sharing, nt_disposition[creation - CREATE_NEW],
1374 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1375 ret = INVALID_HANDLE_VALUE;
1377 /* In the case file creation was rejected due to CREATE_NEW flag
1378 * was specified and file with that name already exists, correct
1379 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1380 * Note: RtlNtStatusToDosError is not the subject to blame here.
1382 if (status == STATUS_OBJECT_NAME_COLLISION)
1383 SetLastError( ERROR_FILE_EXISTS );
1385 SetLastError( RtlNtStatusToDosError(status) );
1387 else SetLastError(0);
1388 RtlFreeUnicodeString( &nameW );
1391 if (!ret) ret = INVALID_HANDLE_VALUE;
1392 TRACE("returning %p\n", ret);
1398 /*************************************************************************
1399 * CreateFileA (KERNEL32.@)
1403 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1404 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1405 DWORD attributes, HANDLE template)
1409 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1410 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1414 /***********************************************************************
1415 * DeleteFileW (KERNEL32.@)
1417 BOOL WINAPI DeleteFileW( LPCWSTR path )
1419 UNICODE_STRING nameW;
1420 OBJECT_ATTRIBUTES attr;
1423 TRACE("%s\n", debugstr_w(path) );
1425 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1427 SetLastError( ERROR_PATH_NOT_FOUND );
1431 attr.Length = sizeof(attr);
1432 attr.RootDirectory = 0;
1433 attr.Attributes = OBJ_CASE_INSENSITIVE;
1434 attr.ObjectName = &nameW;
1435 attr.SecurityDescriptor = NULL;
1436 attr.SecurityQualityOfService = NULL;
1438 status = NtDeleteFile(&attr);
1439 RtlFreeUnicodeString( &nameW );
1442 SetLastError( RtlNtStatusToDosError(status) );
1449 /***********************************************************************
1450 * DeleteFileA (KERNEL32.@)
1452 BOOL WINAPI DeleteFileA( LPCSTR path )
1456 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1457 return DeleteFileW( pathW );
1461 /**************************************************************************
1462 * ReplaceFileW (KERNEL32.@)
1463 * ReplaceFile (KERNEL32.@)
1465 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1466 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1467 LPVOID lpExclude, LPVOID lpReserved)
1469 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1470 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1471 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1476 /**************************************************************************
1477 * ReplaceFileA (KERNEL32.@)
1479 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1480 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1481 LPVOID lpExclude, LPVOID lpReserved)
1483 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1484 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1485 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1490 /*************************************************************************
1491 * FindFirstFileExW (KERNEL32.@)
1493 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1494 LPVOID data, FINDEX_SEARCH_OPS search_op,
1495 LPVOID filter, DWORD flags)
1498 FIND_FIRST_INFO *info = NULL;
1499 UNICODE_STRING nt_name;
1500 OBJECT_ATTRIBUTES attr;
1504 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1506 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1509 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1510 return INVALID_HANDLE_VALUE;
1512 if (level != FindExInfoStandard)
1514 FIXME("info level %d not implemented\n", level );
1515 return INVALID_HANDLE_VALUE;
1518 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1520 SetLastError( ERROR_PATH_NOT_FOUND );
1521 return INVALID_HANDLE_VALUE;
1524 if (!mask || !*mask)
1526 SetLastError( ERROR_FILE_NOT_FOUND );
1530 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1532 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1536 if (!RtlCreateUnicodeString( &info->mask, mask ))
1538 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1542 /* truncate dir name before mask */
1544 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1546 /* check if path is the root of the drive */
1547 info->is_root = FALSE;
1548 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1549 if (p[0] && p[1] == ':')
1552 while (*p == '\\') p++;
1553 info->is_root = (*p == 0);
1556 attr.Length = sizeof(attr);
1557 attr.RootDirectory = 0;
1558 attr.Attributes = OBJ_CASE_INSENSITIVE;
1559 attr.ObjectName = &nt_name;
1560 attr.SecurityDescriptor = NULL;
1561 attr.SecurityQualityOfService = NULL;
1563 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1564 FILE_SHARE_READ | FILE_SHARE_WRITE,
1565 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1567 if (status != STATUS_SUCCESS)
1569 RtlFreeUnicodeString( &info->mask );
1570 SetLastError( RtlNtStatusToDosError(status) );
1574 RtlInitializeCriticalSection( &info->cs );
1575 info->path = nt_name;
1576 info->magic = FIND_FIRST_MAGIC;
1579 info->search_op = search_op;
1581 if (!FindNextFileW( (HANDLE)info, data ))
1583 TRACE( "%s not found\n", debugstr_w(filename) );
1584 FindClose( (HANDLE)info );
1585 SetLastError( ERROR_FILE_NOT_FOUND );
1586 return INVALID_HANDLE_VALUE;
1588 return (HANDLE)info;
1591 HeapFree( GetProcessHeap(), 0, info );
1592 RtlFreeUnicodeString( &nt_name );
1593 return INVALID_HANDLE_VALUE;
1597 /*************************************************************************
1598 * FindNextFileW (KERNEL32.@)
1600 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1602 FIND_FIRST_INFO *info;
1603 FILE_BOTH_DIR_INFORMATION *dir_info;
1606 TRACE("%p %p\n", handle, data);
1608 if (!handle || handle == INVALID_HANDLE_VALUE)
1610 SetLastError( ERROR_INVALID_HANDLE );
1613 info = (FIND_FIRST_INFO *)handle;
1614 if (info->magic != FIND_FIRST_MAGIC)
1616 SetLastError( ERROR_INVALID_HANDLE );
1620 RtlEnterCriticalSection( &info->cs );
1624 if (info->data_pos >= info->data_len) /* need to read some more data */
1628 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1629 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1632 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1635 info->data_len = io.Information;
1639 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1641 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1642 else info->data_pos = info->data_len;
1644 /* don't return '.' and '..' in the root of the drive */
1647 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1648 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1649 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1652 /* check for dir symlink */
1653 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1654 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
1656 if (!check_dir_symlink( info, dir_info )) continue;
1658 if (info->search_op == FindExSearchLimitToDirectories &&
1659 (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1662 data->dwFileAttributes = dir_info->FileAttributes;
1663 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1664 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1665 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1666 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1667 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1668 data->dwReserved0 = 0;
1669 data->dwReserved1 = 0;
1671 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1672 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1673 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1674 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1676 TRACE("returning %s (%s)\n",
1677 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1683 RtlLeaveCriticalSection( &info->cs );
1688 /*************************************************************************
1689 * FindClose (KERNEL32.@)
1691 BOOL WINAPI FindClose( HANDLE handle )
1693 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1695 if (!handle || handle == INVALID_HANDLE_VALUE)
1697 SetLastError( ERROR_INVALID_HANDLE );
1703 if (info->magic == FIND_FIRST_MAGIC)
1705 RtlEnterCriticalSection( &info->cs );
1706 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1709 if (info->handle) CloseHandle( info->handle );
1711 RtlFreeUnicodeString( &info->mask );
1712 info->mask.Buffer = NULL;
1713 RtlFreeUnicodeString( &info->path );
1716 RtlLeaveCriticalSection( &info->cs );
1717 RtlDeleteCriticalSection( &info->cs );
1718 HeapFree( GetProcessHeap(), 0, info );
1722 __EXCEPT(page_fault)
1724 WARN("Illegal handle %p\n", handle);
1725 SetLastError( ERROR_INVALID_HANDLE );
1734 /*************************************************************************
1735 * FindFirstFileA (KERNEL32.@)
1737 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1739 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1740 FindExSearchNameMatch, NULL, 0);
1743 /*************************************************************************
1744 * FindFirstFileExA (KERNEL32.@)
1746 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1747 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1748 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1751 WIN32_FIND_DATAA *dataA;
1752 WIN32_FIND_DATAW dataW;
1755 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1757 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1758 if (handle == INVALID_HANDLE_VALUE) return handle;
1760 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1761 dataA->dwFileAttributes = dataW.dwFileAttributes;
1762 dataA->ftCreationTime = dataW.ftCreationTime;
1763 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1764 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1765 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1766 dataA->nFileSizeLow = dataW.nFileSizeLow;
1767 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1768 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1769 sizeof(dataA->cAlternateFileName) );
1774 /*************************************************************************
1775 * FindFirstFileW (KERNEL32.@)
1777 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1779 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1780 FindExSearchNameMatch, NULL, 0);
1784 /*************************************************************************
1785 * FindNextFileA (KERNEL32.@)
1787 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1789 WIN32_FIND_DATAW dataW;
1791 if (!FindNextFileW( handle, &dataW )) return FALSE;
1792 data->dwFileAttributes = dataW.dwFileAttributes;
1793 data->ftCreationTime = dataW.ftCreationTime;
1794 data->ftLastAccessTime = dataW.ftLastAccessTime;
1795 data->ftLastWriteTime = dataW.ftLastWriteTime;
1796 data->nFileSizeHigh = dataW.nFileSizeHigh;
1797 data->nFileSizeLow = dataW.nFileSizeLow;
1798 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1799 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1800 sizeof(data->cAlternateFileName) );
1805 /**************************************************************************
1806 * GetFileAttributesW (KERNEL32.@)
1808 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1810 FILE_BASIC_INFORMATION info;
1811 UNICODE_STRING nt_name;
1812 OBJECT_ATTRIBUTES attr;
1815 TRACE("%s\n", debugstr_w(name));
1817 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1819 SetLastError( ERROR_PATH_NOT_FOUND );
1820 return INVALID_FILE_ATTRIBUTES;
1823 attr.Length = sizeof(attr);
1824 attr.RootDirectory = 0;
1825 attr.Attributes = OBJ_CASE_INSENSITIVE;
1826 attr.ObjectName = &nt_name;
1827 attr.SecurityDescriptor = NULL;
1828 attr.SecurityQualityOfService = NULL;
1830 status = NtQueryAttributesFile( &attr, &info );
1831 RtlFreeUnicodeString( &nt_name );
1833 if (status == STATUS_SUCCESS) return info.FileAttributes;
1835 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1836 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1838 SetLastError( RtlNtStatusToDosError(status) );
1839 return INVALID_FILE_ATTRIBUTES;
1843 /**************************************************************************
1844 * GetFileAttributesA (KERNEL32.@)
1846 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1850 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1851 return GetFileAttributesW( nameW );
1855 /**************************************************************************
1856 * SetFileAttributesW (KERNEL32.@)
1858 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1860 UNICODE_STRING nt_name;
1861 OBJECT_ATTRIBUTES attr;
1866 TRACE("%s %lx\n", debugstr_w(name), attributes);
1868 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1870 SetLastError( ERROR_PATH_NOT_FOUND );
1874 attr.Length = sizeof(attr);
1875 attr.RootDirectory = 0;
1876 attr.Attributes = OBJ_CASE_INSENSITIVE;
1877 attr.ObjectName = &nt_name;
1878 attr.SecurityDescriptor = NULL;
1879 attr.SecurityQualityOfService = NULL;
1881 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1882 RtlFreeUnicodeString( &nt_name );
1884 if (status == STATUS_SUCCESS)
1886 FILE_BASIC_INFORMATION info;
1888 memset( &info, 0, sizeof(info) );
1889 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1890 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1894 if (status == STATUS_SUCCESS) return TRUE;
1895 SetLastError( RtlNtStatusToDosError(status) );
1900 /**************************************************************************
1901 * SetFileAttributesA (KERNEL32.@)
1903 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1907 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1908 return SetFileAttributesW( nameW, attributes );
1912 /**************************************************************************
1913 * GetFileAttributesExW (KERNEL32.@)
1915 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1917 FILE_NETWORK_OPEN_INFORMATION info;
1918 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1919 UNICODE_STRING nt_name;
1920 OBJECT_ATTRIBUTES attr;
1923 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1925 if (level != GetFileExInfoStandard)
1927 SetLastError( ERROR_INVALID_PARAMETER );
1931 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1933 SetLastError( ERROR_PATH_NOT_FOUND );
1937 attr.Length = sizeof(attr);
1938 attr.RootDirectory = 0;
1939 attr.Attributes = OBJ_CASE_INSENSITIVE;
1940 attr.ObjectName = &nt_name;
1941 attr.SecurityDescriptor = NULL;
1942 attr.SecurityQualityOfService = NULL;
1944 status = NtQueryFullAttributesFile( &attr, &info );
1945 RtlFreeUnicodeString( &nt_name );
1947 if (status != STATUS_SUCCESS)
1949 SetLastError( RtlNtStatusToDosError(status) );
1953 data->dwFileAttributes = info.FileAttributes;
1954 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1955 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1956 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1957 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1958 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1959 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1960 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1961 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1966 /**************************************************************************
1967 * GetFileAttributesExA (KERNEL32.@)
1969 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1973 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1974 return GetFileAttributesExW( nameW, level, ptr );
1978 /******************************************************************************
1979 * GetCompressedFileSizeW (KERNEL32.@)
1981 * Get the actual number of bytes used on disk.
1984 * Success: Low-order doubleword of number of bytes
1985 * Failure: INVALID_FILE_SIZE
1987 DWORD WINAPI GetCompressedFileSizeW(
1988 LPCWSTR name, /* [in] Pointer to name of file */
1989 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1991 UNICODE_STRING nt_name;
1992 OBJECT_ATTRIBUTES attr;
1996 DWORD ret = INVALID_FILE_SIZE;
1998 TRACE("%s %p\n", debugstr_w(name), size_high);
2000 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2002 SetLastError( ERROR_PATH_NOT_FOUND );
2003 return INVALID_FILE_SIZE;
2006 attr.Length = sizeof(attr);
2007 attr.RootDirectory = 0;
2008 attr.Attributes = OBJ_CASE_INSENSITIVE;
2009 attr.ObjectName = &nt_name;
2010 attr.SecurityDescriptor = NULL;
2011 attr.SecurityQualityOfService = NULL;
2013 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2014 RtlFreeUnicodeString( &nt_name );
2016 if (status == STATUS_SUCCESS)
2018 /* we don't support compressed files, simply return the file size */
2019 ret = GetFileSize( handle, size_high );
2022 else SetLastError( RtlNtStatusToDosError(status) );
2028 /******************************************************************************
2029 * GetCompressedFileSizeA (KERNEL32.@)
2031 * See GetCompressedFileSizeW.
2033 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2037 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2038 return GetCompressedFileSizeW( nameW, size_high );
2042 /***********************************************************************
2043 * OpenFile (KERNEL32.@)
2045 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2049 WORD filedatetime[2];
2051 if (!ofs) return HFILE_ERROR;
2053 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2054 ((mode & 0x3 )==OF_READ)?"OF_READ":
2055 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2056 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2057 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2058 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2059 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2060 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2061 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2062 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2063 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2064 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2065 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2066 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2067 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2068 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2069 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2070 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2074 ofs->cBytes = sizeof(OFSTRUCT);
2076 if (mode & OF_REOPEN) name = ofs->szPathName;
2078 if (!name) return HFILE_ERROR;
2080 TRACE("%s %04x\n", name, mode );
2082 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2083 Are there any cases where getting the path here is wrong?
2084 Uwe Bonnes 1997 Apr 2 */
2085 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2087 /* OF_PARSE simply fills the structure */
2089 if (mode & OF_PARSE)
2091 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2092 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2096 /* OF_CREATE is completely different from all other options, so
2099 if (mode & OF_CREATE)
2101 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2106 /* Now look for the file */
2108 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2111 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2113 if (mode & OF_DELETE)
2115 if (!DeleteFileA( ofs->szPathName )) goto error;
2116 TRACE("(%s): OF_DELETE return = OK\n", name);
2120 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2121 if (handle == INVALID_HANDLE_VALUE) goto error;
2123 GetFileTime( handle, NULL, NULL, &filetime );
2124 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2125 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2127 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2129 CloseHandle( handle );
2130 WARN("(%s): OF_VERIFY failed\n", name );
2131 /* FIXME: what error here? */
2132 SetLastError( ERROR_FILE_NOT_FOUND );
2136 ofs->Reserved1 = filedatetime[0];
2137 ofs->Reserved2 = filedatetime[1];
2139 TRACE("(%s): OK, return = %p\n", name, handle );
2140 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2142 CloseHandle( handle );
2145 else return (HFILE)handle;
2147 error: /* We get here if there was an error opening the file */
2148 ofs->nErrCode = GetLastError();
2149 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );