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.@)
1401 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1402 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1403 DWORD attributes, HANDLE template)
1407 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1408 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1412 /***********************************************************************
1413 * DeleteFileW (KERNEL32.@)
1415 BOOL WINAPI DeleteFileW( LPCWSTR path )
1417 UNICODE_STRING nameW;
1418 OBJECT_ATTRIBUTES attr;
1421 TRACE("%s\n", debugstr_w(path) );
1423 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1425 SetLastError( ERROR_PATH_NOT_FOUND );
1429 attr.Length = sizeof(attr);
1430 attr.RootDirectory = 0;
1431 attr.Attributes = OBJ_CASE_INSENSITIVE;
1432 attr.ObjectName = &nameW;
1433 attr.SecurityDescriptor = NULL;
1434 attr.SecurityQualityOfService = NULL;
1436 status = NtDeleteFile(&attr);
1437 RtlFreeUnicodeString( &nameW );
1440 SetLastError( RtlNtStatusToDosError(status) );
1447 /***********************************************************************
1448 * DeleteFileA (KERNEL32.@)
1450 BOOL WINAPI DeleteFileA( LPCSTR path )
1454 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1455 return DeleteFileW( pathW );
1459 /**************************************************************************
1460 * ReplaceFileW (KERNEL32.@)
1461 * ReplaceFile (KERNEL32.@)
1463 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1464 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1465 LPVOID lpExclude, LPVOID lpReserved)
1467 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1468 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1469 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1474 /**************************************************************************
1475 * ReplaceFileA (KERNEL32.@)
1477 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1478 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1479 LPVOID lpExclude, LPVOID lpReserved)
1481 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1482 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1483 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1488 /*************************************************************************
1489 * FindFirstFileExW (KERNEL32.@)
1491 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1492 LPVOID data, FINDEX_SEARCH_OPS search_op,
1493 LPVOID filter, DWORD flags)
1496 FIND_FIRST_INFO *info = NULL;
1497 UNICODE_STRING nt_name;
1498 OBJECT_ATTRIBUTES attr;
1502 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1504 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1507 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1508 return INVALID_HANDLE_VALUE;
1510 if (level != FindExInfoStandard)
1512 FIXME("info level %d not implemented\n", level );
1513 return INVALID_HANDLE_VALUE;
1516 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1518 SetLastError( ERROR_PATH_NOT_FOUND );
1519 return INVALID_HANDLE_VALUE;
1522 if (!mask || !*mask)
1524 SetLastError( ERROR_FILE_NOT_FOUND );
1528 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1530 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1534 if (!RtlCreateUnicodeString( &info->mask, mask ))
1536 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1540 /* truncate dir name before mask */
1542 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1544 /* check if path is the root of the drive */
1545 info->is_root = FALSE;
1546 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1547 if (p[0] && p[1] == ':')
1550 while (*p == '\\') p++;
1551 info->is_root = (*p == 0);
1554 attr.Length = sizeof(attr);
1555 attr.RootDirectory = 0;
1556 attr.Attributes = OBJ_CASE_INSENSITIVE;
1557 attr.ObjectName = &nt_name;
1558 attr.SecurityDescriptor = NULL;
1559 attr.SecurityQualityOfService = NULL;
1561 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1562 FILE_SHARE_READ | FILE_SHARE_WRITE,
1563 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1565 if (status != STATUS_SUCCESS)
1567 RtlFreeUnicodeString( &info->mask );
1568 SetLastError( RtlNtStatusToDosError(status) );
1572 RtlInitializeCriticalSection( &info->cs );
1573 info->path = nt_name;
1574 info->magic = FIND_FIRST_MAGIC;
1577 info->search_op = search_op;
1579 if (!FindNextFileW( (HANDLE)info, data ))
1581 TRACE( "%s not found\n", debugstr_w(filename) );
1582 FindClose( (HANDLE)info );
1583 SetLastError( ERROR_FILE_NOT_FOUND );
1584 return INVALID_HANDLE_VALUE;
1586 return (HANDLE)info;
1589 HeapFree( GetProcessHeap(), 0, info );
1590 RtlFreeUnicodeString( &nt_name );
1591 return INVALID_HANDLE_VALUE;
1595 /*************************************************************************
1596 * FindNextFileW (KERNEL32.@)
1598 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1600 FIND_FIRST_INFO *info;
1601 FILE_BOTH_DIR_INFORMATION *dir_info;
1604 TRACE("%p %p\n", handle, data);
1606 if (!handle || handle == INVALID_HANDLE_VALUE)
1608 SetLastError( ERROR_INVALID_HANDLE );
1611 info = (FIND_FIRST_INFO *)handle;
1612 if (info->magic != FIND_FIRST_MAGIC)
1614 SetLastError( ERROR_INVALID_HANDLE );
1618 RtlEnterCriticalSection( &info->cs );
1622 if (info->data_pos >= info->data_len) /* need to read some more data */
1626 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1627 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1630 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1633 info->data_len = io.Information;
1637 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1639 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1640 else info->data_pos = info->data_len;
1642 /* don't return '.' and '..' in the root of the drive */
1645 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1646 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1647 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1650 /* check for dir symlink */
1651 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1652 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
1654 if (!check_dir_symlink( info, dir_info )) continue;
1656 if (info->search_op == FindExSearchLimitToDirectories &&
1657 (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1660 data->dwFileAttributes = dir_info->FileAttributes;
1661 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1662 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1663 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1664 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1665 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1666 data->dwReserved0 = 0;
1667 data->dwReserved1 = 0;
1669 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1670 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1671 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1672 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1674 TRACE("returning %s (%s)\n",
1675 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1681 RtlLeaveCriticalSection( &info->cs );
1686 /*************************************************************************
1687 * FindClose (KERNEL32.@)
1689 BOOL WINAPI FindClose( HANDLE handle )
1691 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1693 if (!handle || handle == INVALID_HANDLE_VALUE)
1695 SetLastError( ERROR_INVALID_HANDLE );
1701 if (info->magic == FIND_FIRST_MAGIC)
1703 RtlEnterCriticalSection( &info->cs );
1704 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1707 if (info->handle) CloseHandle( info->handle );
1709 RtlFreeUnicodeString( &info->mask );
1710 info->mask.Buffer = NULL;
1711 RtlFreeUnicodeString( &info->path );
1714 RtlLeaveCriticalSection( &info->cs );
1715 RtlDeleteCriticalSection( &info->cs );
1716 HeapFree( GetProcessHeap(), 0, info );
1720 __EXCEPT(page_fault)
1722 WARN("Illegal handle %p\n", handle);
1723 SetLastError( ERROR_INVALID_HANDLE );
1732 /*************************************************************************
1733 * FindFirstFileA (KERNEL32.@)
1735 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1737 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1738 FindExSearchNameMatch, NULL, 0);
1741 /*************************************************************************
1742 * FindFirstFileExA (KERNEL32.@)
1744 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1745 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1746 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1749 WIN32_FIND_DATAA *dataA;
1750 WIN32_FIND_DATAW dataW;
1753 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1755 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1756 if (handle == INVALID_HANDLE_VALUE) return handle;
1758 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1759 dataA->dwFileAttributes = dataW.dwFileAttributes;
1760 dataA->ftCreationTime = dataW.ftCreationTime;
1761 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1762 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1763 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1764 dataA->nFileSizeLow = dataW.nFileSizeLow;
1765 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1766 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1767 sizeof(dataA->cAlternateFileName) );
1772 /*************************************************************************
1773 * FindFirstFileW (KERNEL32.@)
1775 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1777 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1778 FindExSearchNameMatch, NULL, 0);
1782 /*************************************************************************
1783 * FindNextFileA (KERNEL32.@)
1785 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1787 WIN32_FIND_DATAW dataW;
1789 if (!FindNextFileW( handle, &dataW )) return FALSE;
1790 data->dwFileAttributes = dataW.dwFileAttributes;
1791 data->ftCreationTime = dataW.ftCreationTime;
1792 data->ftLastAccessTime = dataW.ftLastAccessTime;
1793 data->ftLastWriteTime = dataW.ftLastWriteTime;
1794 data->nFileSizeHigh = dataW.nFileSizeHigh;
1795 data->nFileSizeLow = dataW.nFileSizeLow;
1796 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1797 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1798 sizeof(data->cAlternateFileName) );
1803 /**************************************************************************
1804 * GetFileAttributesW (KERNEL32.@)
1806 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1808 FILE_BASIC_INFORMATION info;
1809 UNICODE_STRING nt_name;
1810 OBJECT_ATTRIBUTES attr;
1813 TRACE("%s\n", debugstr_w(name));
1815 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1817 SetLastError( ERROR_PATH_NOT_FOUND );
1818 return INVALID_FILE_ATTRIBUTES;
1821 attr.Length = sizeof(attr);
1822 attr.RootDirectory = 0;
1823 attr.Attributes = OBJ_CASE_INSENSITIVE;
1824 attr.ObjectName = &nt_name;
1825 attr.SecurityDescriptor = NULL;
1826 attr.SecurityQualityOfService = NULL;
1828 status = NtQueryAttributesFile( &attr, &info );
1829 RtlFreeUnicodeString( &nt_name );
1831 if (status == STATUS_SUCCESS) return info.FileAttributes;
1833 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1834 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1836 SetLastError( RtlNtStatusToDosError(status) );
1837 return INVALID_FILE_ATTRIBUTES;
1841 /**************************************************************************
1842 * GetFileAttributesA (KERNEL32.@)
1844 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1848 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1849 return GetFileAttributesW( nameW );
1853 /**************************************************************************
1854 * SetFileAttributesW (KERNEL32.@)
1856 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1858 UNICODE_STRING nt_name;
1859 OBJECT_ATTRIBUTES attr;
1864 TRACE("%s %lx\n", debugstr_w(name), attributes);
1866 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1868 SetLastError( ERROR_PATH_NOT_FOUND );
1872 attr.Length = sizeof(attr);
1873 attr.RootDirectory = 0;
1874 attr.Attributes = OBJ_CASE_INSENSITIVE;
1875 attr.ObjectName = &nt_name;
1876 attr.SecurityDescriptor = NULL;
1877 attr.SecurityQualityOfService = NULL;
1879 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1880 RtlFreeUnicodeString( &nt_name );
1882 if (status == STATUS_SUCCESS)
1884 FILE_BASIC_INFORMATION info;
1886 memset( &info, 0, sizeof(info) );
1887 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1888 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1892 if (status == STATUS_SUCCESS) return TRUE;
1893 SetLastError( RtlNtStatusToDosError(status) );
1898 /**************************************************************************
1899 * SetFileAttributesA (KERNEL32.@)
1901 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1905 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1906 return SetFileAttributesW( nameW, attributes );
1910 /**************************************************************************
1911 * GetFileAttributesExW (KERNEL32.@)
1913 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1915 FILE_NETWORK_OPEN_INFORMATION info;
1916 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1917 UNICODE_STRING nt_name;
1918 OBJECT_ATTRIBUTES attr;
1921 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1923 if (level != GetFileExInfoStandard)
1925 SetLastError( ERROR_INVALID_PARAMETER );
1929 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1931 SetLastError( ERROR_PATH_NOT_FOUND );
1935 attr.Length = sizeof(attr);
1936 attr.RootDirectory = 0;
1937 attr.Attributes = OBJ_CASE_INSENSITIVE;
1938 attr.ObjectName = &nt_name;
1939 attr.SecurityDescriptor = NULL;
1940 attr.SecurityQualityOfService = NULL;
1942 status = NtQueryFullAttributesFile( &attr, &info );
1943 RtlFreeUnicodeString( &nt_name );
1945 if (status != STATUS_SUCCESS)
1947 SetLastError( RtlNtStatusToDosError(status) );
1951 data->dwFileAttributes = info.FileAttributes;
1952 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1953 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1954 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1955 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1956 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1957 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1958 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1959 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1964 /**************************************************************************
1965 * GetFileAttributesExA (KERNEL32.@)
1967 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1971 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1972 return GetFileAttributesExW( nameW, level, ptr );
1976 /******************************************************************************
1977 * GetCompressedFileSizeW (KERNEL32.@)
1980 * Success: Low-order doubleword of number of bytes
1981 * Failure: INVALID_FILE_SIZE
1983 DWORD WINAPI GetCompressedFileSizeW(
1984 LPCWSTR name, /* [in] Pointer to name of file */
1985 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1987 UNICODE_STRING nt_name;
1988 OBJECT_ATTRIBUTES attr;
1992 DWORD ret = INVALID_FILE_SIZE;
1994 TRACE("%s %p\n", debugstr_w(name), size_high);
1996 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1998 SetLastError( ERROR_PATH_NOT_FOUND );
1999 return INVALID_FILE_SIZE;
2002 attr.Length = sizeof(attr);
2003 attr.RootDirectory = 0;
2004 attr.Attributes = OBJ_CASE_INSENSITIVE;
2005 attr.ObjectName = &nt_name;
2006 attr.SecurityDescriptor = NULL;
2007 attr.SecurityQualityOfService = NULL;
2009 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2010 RtlFreeUnicodeString( &nt_name );
2012 if (status == STATUS_SUCCESS)
2014 /* we don't support compressed files, simply return the file size */
2015 ret = GetFileSize( handle, size_high );
2018 else SetLastError( RtlNtStatusToDosError(status) );
2024 /******************************************************************************
2025 * GetCompressedFileSizeA (KERNEL32.@)
2027 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2031 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2032 return GetCompressedFileSizeW( nameW, size_high );
2036 /***********************************************************************
2037 * OpenFile (KERNEL32.@)
2039 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2043 WORD filedatetime[2];
2045 if (!ofs) return HFILE_ERROR;
2047 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2048 ((mode & 0x3 )==OF_READ)?"OF_READ":
2049 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2050 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2051 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2052 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2053 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2054 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2055 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2056 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2057 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2058 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2059 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2060 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2061 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2062 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2063 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2064 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2068 ofs->cBytes = sizeof(OFSTRUCT);
2070 if (mode & OF_REOPEN) name = ofs->szPathName;
2072 if (!name) return HFILE_ERROR;
2074 TRACE("%s %04x\n", name, mode );
2076 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2077 Are there any cases where getting the path here is wrong?
2078 Uwe Bonnes 1997 Apr 2 */
2079 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2081 /* OF_PARSE simply fills the structure */
2083 if (mode & OF_PARSE)
2085 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2086 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2090 /* OF_CREATE is completely different from all other options, so
2093 if (mode & OF_CREATE)
2095 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2100 /* Now look for the file */
2102 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2105 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2107 if (mode & OF_DELETE)
2109 if (!DeleteFileA( ofs->szPathName )) goto error;
2110 TRACE("(%s): OF_DELETE return = OK\n", name);
2114 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2115 if (handle == INVALID_HANDLE_VALUE) goto error;
2117 GetFileTime( handle, NULL, NULL, &filetime );
2118 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2119 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2121 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2123 CloseHandle( handle );
2124 WARN("(%s): OF_VERIFY failed\n", name );
2125 /* FIXME: what error here? */
2126 SetLastError( ERROR_FILE_NOT_FOUND );
2130 ofs->Reserved1 = filedatetime[0];
2131 ofs->Reserved2 = filedatetime[1];
2133 TRACE("(%s): OK, return = %p\n", name, handle );
2134 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2136 CloseHandle( handle );
2139 else return (HFILE)handle;
2141 error: /* We get here if there was an error opening the file */
2142 ofs->nErrCode = GetLastError();
2143 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );