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"
29 #define NONAMELESSUNION
30 #define NONAMELESSSTRUCT
39 #include "wine/winbase16.h"
40 #include "kernel_private.h"
42 #include "wine/exception.h"
44 #include "wine/unicode.h"
45 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(file);
50 HANDLE dos_handles[DOS_TABLE_SIZE];
52 /* info structure for FindFirstFile handle */
55 DWORD magic; /* magic number */
56 HANDLE handle; /* handle to directory */
57 CRITICAL_SECTION cs; /* crit section protecting this structure */
58 UNICODE_STRING mask; /* file mask */
59 BOOL is_root; /* is directory the root of the drive? */
60 UINT data_pos; /* current position in dir data */
61 UINT data_len; /* length of dir data */
62 BYTE data[8192]; /* directory data */
65 #define FIND_FIRST_MAGIC 0xc0ffee11
67 static BOOL oem_file_apis;
69 static WINE_EXCEPTION_FILTER(page_fault)
71 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
72 return EXCEPTION_EXECUTE_HANDLER;
73 return EXCEPTION_CONTINUE_SEARCH;
77 /***********************************************************************
80 * Wrapper for CreateFile that takes OF_* mode flags.
82 static HANDLE create_file_OF( LPCSTR path, INT mode )
84 DWORD access, sharing, creation;
88 creation = CREATE_ALWAYS;
89 access = GENERIC_READ | GENERIC_WRITE;
93 creation = OPEN_EXISTING;
96 case OF_READ: access = GENERIC_READ; break;
97 case OF_WRITE: access = GENERIC_WRITE; break;
98 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
99 default: access = 0; break;
105 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
106 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
107 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
108 case OF_SHARE_DENY_NONE:
109 case OF_SHARE_COMPAT:
110 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
112 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
116 /***********************************************************************
119 * Set the DOS error code from errno.
121 void FILE_SetDosError(void)
123 int save_errno = errno; /* errno gets overwritten by printf */
125 TRACE("errno = %d %s\n", errno, strerror(errno));
129 SetLastError( ERROR_SHARING_VIOLATION );
132 SetLastError( ERROR_INVALID_HANDLE );
135 SetLastError( ERROR_HANDLE_DISK_FULL );
140 SetLastError( ERROR_ACCESS_DENIED );
143 SetLastError( ERROR_LOCK_VIOLATION );
146 SetLastError( ERROR_FILE_NOT_FOUND );
149 SetLastError( ERROR_CANNOT_MAKE );
153 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
156 SetLastError( ERROR_FILE_EXISTS );
160 SetLastError( ERROR_SEEK );
163 SetLastError( ERROR_DIR_NOT_EMPTY );
166 SetLastError( ERROR_BAD_FORMAT );
169 SetLastError( ERROR_PATH_NOT_FOUND );
172 SetLastError( ERROR_NOT_SAME_DEVICE );
175 WARN("unknown file error: %s\n", strerror(save_errno) );
176 SetLastError( ERROR_GEN_FAILURE );
183 /***********************************************************************
186 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
188 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
189 * there is no possibility for the function to do that twice, taking into
190 * account any called function.
192 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
195 UNICODE_STRING strW, *pstrW;
198 RtlInitAnsiString( &str, name );
199 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
201 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
203 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
204 if (status == STATUS_SUCCESS) return pstrW->Buffer;
206 if (status == STATUS_BUFFER_OVERFLOW)
207 SetLastError( ERROR_FILENAME_EXCED_RANGE );
209 SetLastError( RtlNtStatusToDosError(status) );
214 /***********************************************************************
217 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
219 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
223 if (srclen < 0) srclen = strlenW( src ) + 1;
225 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
227 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
232 /**************************************************************************
233 * SetFileApisToOEM (KERNEL32.@)
235 VOID WINAPI SetFileApisToOEM(void)
237 oem_file_apis = TRUE;
241 /**************************************************************************
242 * SetFileApisToANSI (KERNEL32.@)
244 VOID WINAPI SetFileApisToANSI(void)
246 oem_file_apis = FALSE;
250 /******************************************************************************
251 * AreFileApisANSI (KERNEL32.@)
253 * Determines if file functions are using ANSI
256 * TRUE: Set of file functions is using ANSI code page
257 * FALSE: Set of file functions is using OEM code page
259 BOOL WINAPI AreFileApisANSI(void)
261 return !oem_file_apis;
265 /**************************************************************************
266 * Operations on file handles *
267 **************************************************************************/
269 /***********************************************************************
270 * FILE_InitProcessDosHandles
272 * Allocates the default DOS handles for a process. Called either by
273 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
275 static void FILE_InitProcessDosHandles( void )
277 static BOOL init_done /* = FALSE */;
278 HANDLE cp = GetCurrentProcess();
280 if (init_done) return;
282 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
283 0, TRUE, DUPLICATE_SAME_ACCESS);
284 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
285 0, TRUE, DUPLICATE_SAME_ACCESS);
286 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
287 0, TRUE, DUPLICATE_SAME_ACCESS);
288 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
289 0, TRUE, DUPLICATE_SAME_ACCESS);
290 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
291 0, TRUE, DUPLICATE_SAME_ACCESS);
295 /******************************************************************
296 * FILE_ReadWriteApc (internal)
298 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
300 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
302 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
306 /***********************************************************************
307 * ReadFileEx (KERNEL32.@)
309 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
310 LPOVERLAPPED overlapped,
311 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
313 LARGE_INTEGER offset;
315 PIO_STATUS_BLOCK io_status;
317 TRACE("(hFile=%p, buffer=%p, bytes=%lu, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
321 SetLastError(ERROR_INVALID_PARAMETER);
325 offset.u.LowPart = overlapped->Offset;
326 offset.u.HighPart = overlapped->OffsetHigh;
327 io_status = (PIO_STATUS_BLOCK)overlapped;
328 io_status->u.Status = STATUS_PENDING;
330 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
331 io_status, buffer, bytesToRead, &offset, NULL);
335 SetLastError( RtlNtStatusToDosError(status) );
342 /***********************************************************************
343 * ReadFile (KERNEL32.@)
345 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
346 LPDWORD bytesRead, LPOVERLAPPED overlapped )
348 LARGE_INTEGER offset;
349 PLARGE_INTEGER poffset = NULL;
350 IO_STATUS_BLOCK iosb;
351 PIO_STATUS_BLOCK io_status = &iosb;
355 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
356 bytesRead, overlapped );
358 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
359 if (!bytesToRead) return TRUE;
361 if (is_console_handle(hFile))
362 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
364 if (overlapped != NULL)
366 offset.u.LowPart = overlapped->Offset;
367 offset.u.HighPart = overlapped->OffsetHigh;
369 hEvent = overlapped->hEvent;
370 io_status = (PIO_STATUS_BLOCK)overlapped;
372 io_status->u.Status = STATUS_PENDING;
373 io_status->Information = 0;
375 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
377 if (status != STATUS_PENDING && bytesRead)
378 *bytesRead = io_status->Information;
380 if (status && status != STATUS_END_OF_FILE)
382 SetLastError( RtlNtStatusToDosError(status) );
389 /***********************************************************************
390 * WriteFileEx (KERNEL32.@)
392 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
393 LPOVERLAPPED overlapped,
394 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
396 LARGE_INTEGER offset;
398 PIO_STATUS_BLOCK io_status;
400 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
402 if (overlapped == NULL)
404 SetLastError(ERROR_INVALID_PARAMETER);
407 offset.u.LowPart = overlapped->Offset;
408 offset.u.HighPart = overlapped->OffsetHigh;
410 io_status = (PIO_STATUS_BLOCK)overlapped;
411 io_status->u.Status = STATUS_PENDING;
413 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
414 io_status, buffer, bytesToWrite, &offset, NULL);
416 if (status) SetLastError( RtlNtStatusToDosError(status) );
421 /***********************************************************************
422 * WriteFile (KERNEL32.@)
424 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
425 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
427 HANDLE hEvent = NULL;
428 LARGE_INTEGER offset;
429 PLARGE_INTEGER poffset = NULL;
431 IO_STATUS_BLOCK iosb;
432 PIO_STATUS_BLOCK piosb = &iosb;
434 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
436 if (is_console_handle(hFile))
437 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
441 offset.u.LowPart = overlapped->Offset;
442 offset.u.HighPart = overlapped->OffsetHigh;
444 hEvent = overlapped->hEvent;
445 piosb = (PIO_STATUS_BLOCK)overlapped;
447 piosb->u.Status = STATUS_PENDING;
448 piosb->Information = 0;
450 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
451 buffer, bytesToWrite, poffset, NULL);
453 if (status != STATUS_PENDING && bytesWritten)
454 *bytesWritten = piosb->Information;
458 SetLastError( RtlNtStatusToDosError(status) );
465 /***********************************************************************
466 * GetOverlappedResult (KERNEL32.@)
468 * Check the result of an Asynchronous data transfer from a file.
471 * HANDLE hFile [in] handle of file to check on
472 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
473 * LPDWORD lpTransferred [in/out] number of bytes transferred
474 * BOOL bWait [in] wait for the transfer to complete ?
480 * If successful (and relevant) lpTransferred will hold the number of
481 * bytes transferred during the async operation.
485 * Currently only works for WaitCommEvent, ReadFile, WriteFile
486 * with communications ports.
489 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
490 LPDWORD lpTransferred, BOOL bWait)
492 DWORD r = WAIT_OBJECT_0;
494 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
496 if ( lpOverlapped == NULL )
498 ERR("lpOverlapped was null\n");
503 if ( lpOverlapped->hEvent )
507 TRACE( "waiting on %p\n", lpOverlapped );
508 r = WaitForSingleObjectEx( lpOverlapped->hEvent, INFINITE, TRUE );
509 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
510 } while ( r == WAIT_IO_COMPLETION );
515 while ( (volatile DWORD)lpOverlapped->Internal == STATUS_PENDING )
519 else if ( lpOverlapped->Internal == STATUS_PENDING )
521 /* Wait in order to give APCs a chance to run. */
522 /* This is cheating, so we must set the event again in case of success -
523 it may be a non-manual reset event. */
526 TRACE( "waiting on %p\n", lpOverlapped );
527 r = WaitForSingleObjectEx( lpOverlapped->hEvent, 0, TRUE );
528 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
529 } while ( r == WAIT_IO_COMPLETION );
530 if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
531 NtSetEvent( lpOverlapped->hEvent, NULL );
533 if ( r == WAIT_FAILED )
535 ERR("wait operation failed\n");
538 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
540 switch ( lpOverlapped->Internal )
545 SetLastError( ERROR_IO_INCOMPLETE );
546 if ( bWait ) ERR("PENDING status after waiting!\n");
549 SetLastError( RtlNtStatusToDosError( lpOverlapped->Internal ) );
554 /***********************************************************************
555 * CancelIo (KERNEL32.@)
557 BOOL WINAPI CancelIo(HANDLE handle)
559 async_private *ovp,*t;
561 TRACE("handle = %p\n",handle);
563 for (ovp = NtCurrentTeb()->pending_list; ovp; ovp = t)
566 if ( ovp->handle == handle )
567 cancel_async ( ovp );
573 /***********************************************************************
574 * _hread (KERNEL32.@)
576 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
578 return _lread( hFile, buffer, count );
582 /***********************************************************************
583 * _hwrite (KERNEL32.@)
585 * experimentation yields that _lwrite:
586 * o truncates the file at the current position with
588 * o returns 0 on a 0 length write
589 * o works with console handles
592 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
596 TRACE("%d %p %ld\n", handle, buffer, count );
600 /* Expand or truncate at current position */
601 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
604 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
610 /***********************************************************************
611 * _lclose (KERNEL32.@)
613 HFILE WINAPI _lclose( HFILE hFile )
615 TRACE("handle %d\n", hFile );
616 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
620 /***********************************************************************
621 * _lcreat (KERNEL32.@)
623 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
625 /* Mask off all flags not explicitly allowed by the doc */
626 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
627 TRACE("%s %02x\n", path, attr );
628 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
629 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
630 CREATE_ALWAYS, attr, 0 );
634 /***********************************************************************
635 * _lopen (KERNEL32.@)
637 HFILE WINAPI _lopen( LPCSTR path, INT mode )
639 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
640 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
643 /***********************************************************************
644 * _lread (KERNEL32.@)
646 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
649 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
655 /***********************************************************************
656 * _llseek (KERNEL32.@)
658 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
660 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
664 /***********************************************************************
665 * _lwrite (KERNEL32.@)
667 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
669 return (UINT)_hwrite( hFile, buffer, (LONG)count );
673 /***********************************************************************
674 * FlushFileBuffers (KERNEL32.@)
676 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
679 IO_STATUS_BLOCK ioblk;
681 if (is_console_handle( hFile ))
683 /* this will fail (as expected) for an output handle */
684 /* FIXME: wait until FlushFileBuffers is moved to dll/kernel */
685 /* return FlushConsoleInputBuffer( hFile ); */
688 nts = NtFlushBuffersFile( hFile, &ioblk );
689 if (nts != STATUS_SUCCESS)
691 SetLastError( RtlNtStatusToDosError( nts ) );
699 /***********************************************************************
700 * GetFileType (KERNEL32.@)
702 DWORD WINAPI GetFileType( HANDLE hFile )
704 FILE_FS_DEVICE_INFORMATION info;
708 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
710 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
711 if (status != STATUS_SUCCESS)
713 SetLastError( RtlNtStatusToDosError(status) );
714 return FILE_TYPE_UNKNOWN;
717 switch(info.DeviceType)
719 case FILE_DEVICE_NULL:
720 case FILE_DEVICE_SERIAL_PORT:
721 case FILE_DEVICE_PARALLEL_PORT:
722 case FILE_DEVICE_UNKNOWN:
723 return FILE_TYPE_CHAR;
724 case FILE_DEVICE_NAMED_PIPE:
725 return FILE_TYPE_PIPE;
727 return FILE_TYPE_DISK;
732 /***********************************************************************
733 * GetFileInformationByHandle (KERNEL32.@)
735 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
737 FILE_ALL_INFORMATION all_info;
741 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
742 if (status == STATUS_SUCCESS)
744 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
745 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
746 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
747 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
748 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
749 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
750 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
751 info->dwVolumeSerialNumber = 0; /* FIXME */
752 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
753 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
754 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
755 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
756 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
759 SetLastError( RtlNtStatusToDosError(status) );
764 /***********************************************************************
765 * GetFileSize (KERNEL32.@)
767 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
770 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
771 if (filesizehigh) *filesizehigh = size.u.HighPart;
772 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
773 return size.u.LowPart;
777 /***********************************************************************
778 * GetFileSizeEx (KERNEL32.@)
780 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
782 FILE_END_OF_FILE_INFORMATION info;
786 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
787 if (status == STATUS_SUCCESS)
789 *lpFileSize = info.EndOfFile;
792 SetLastError( RtlNtStatusToDosError(status) );
797 /**************************************************************************
798 * SetEndOfFile (KERNEL32.@)
800 BOOL WINAPI SetEndOfFile( HANDLE hFile )
802 FILE_POSITION_INFORMATION pos;
803 FILE_END_OF_FILE_INFORMATION eof;
807 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
808 if (status == STATUS_SUCCESS)
810 eof.EndOfFile = pos.CurrentByteOffset;
811 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
813 if (status == STATUS_SUCCESS) return TRUE;
814 SetLastError( RtlNtStatusToDosError(status) );
819 /***********************************************************************
820 * SetFilePointer (KERNEL32.@)
822 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
824 LARGE_INTEGER dist, newpos;
828 dist.u.LowPart = distance;
829 dist.u.HighPart = *highword;
831 else dist.QuadPart = distance;
833 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
835 if (highword) *highword = newpos.u.HighPart;
836 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
837 return newpos.u.LowPart;
841 /***********************************************************************
842 * SetFilePointerEx (KERNEL32.@)
844 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
845 LARGE_INTEGER *newpos, DWORD method )
847 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
852 TRACE("handle %p offset %s newpos %p origin %ld\n",
853 hFile, wine_dbgstr_longlong(distance.QuadPart), newpos, method );
855 if (method > FILE_END)
857 SetLastError( ERROR_INVALID_PARAMETER );
861 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL )))
865 pos = distance.QuadPart;
866 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
868 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
869 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
870 SetLastError( ERROR_NEGATIVE_SEEK );
878 newpos->QuadPart = res;
880 wine_server_release_fd( hFile, fd );
882 else SetLastError( RtlNtStatusToDosError(status) );
887 /***********************************************************************
888 * GetFileTime (KERNEL32.@)
890 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
891 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
893 FILE_BASIC_INFORMATION info;
897 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
898 if (status == STATUS_SUCCESS)
902 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
903 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
905 if (lpLastAccessTime)
907 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
908 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
912 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
913 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
917 SetLastError( RtlNtStatusToDosError(status) );
922 /***********************************************************************
923 * SetFileTime (KERNEL32.@)
925 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
926 const FILETIME *atime, const FILETIME *mtime )
928 FILE_BASIC_INFORMATION info;
932 memset( &info, 0, sizeof(info) );
935 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
936 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
940 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
941 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
945 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
946 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
949 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
950 if (status == STATUS_SUCCESS) return TRUE;
951 SetLastError( RtlNtStatusToDosError(status) );
956 /**************************************************************************
957 * LockFile (KERNEL32.@)
959 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
960 DWORD count_low, DWORD count_high )
963 LARGE_INTEGER count, offset;
965 TRACE( "%p %lx%08lx %lx%08lx\n",
966 hFile, offset_high, offset_low, count_high, count_low );
968 count.u.LowPart = count_low;
969 count.u.HighPart = count_high;
970 offset.u.LowPart = offset_low;
971 offset.u.HighPart = offset_high;
973 status = NtLockFile( hFile, 0, NULL, NULL,
974 NULL, &offset, &count, NULL, TRUE, TRUE );
976 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
981 /**************************************************************************
982 * LockFileEx [KERNEL32.@]
984 * Locks a byte range within an open file for shared or exclusive access.
991 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
993 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
994 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
997 LARGE_INTEGER count, offset;
1001 SetLastError( ERROR_INVALID_PARAMETER );
1005 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
1006 hFile, overlapped->OffsetHigh, overlapped->Offset,
1007 count_high, count_low, flags );
1009 count.u.LowPart = count_low;
1010 count.u.HighPart = count_high;
1011 offset.u.LowPart = overlapped->Offset;
1012 offset.u.HighPart = overlapped->OffsetHigh;
1014 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1015 NULL, &offset, &count, NULL,
1016 flags & LOCKFILE_FAIL_IMMEDIATELY,
1017 flags & LOCKFILE_EXCLUSIVE_LOCK );
1019 if (status) SetLastError( RtlNtStatusToDosError(status) );
1024 /**************************************************************************
1025 * UnlockFile (KERNEL32.@)
1027 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1028 DWORD count_low, DWORD count_high )
1031 LARGE_INTEGER count, offset;
1033 count.u.LowPart = count_low;
1034 count.u.HighPart = count_high;
1035 offset.u.LowPart = offset_low;
1036 offset.u.HighPart = offset_high;
1038 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1039 if (status) SetLastError( RtlNtStatusToDosError(status) );
1044 /**************************************************************************
1045 * UnlockFileEx (KERNEL32.@)
1047 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1048 LPOVERLAPPED overlapped )
1052 SetLastError( ERROR_INVALID_PARAMETER );
1055 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1057 return UnlockFile( hFile, overlapped->Offset, overlapped->OffsetHigh, count_low, count_high );
1061 /***********************************************************************
1062 * Win32HandleToDosFileHandle (KERNEL32.21)
1064 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1065 * longer valid after this function (even on failure).
1067 * Note: this is not exactly right, since on Win95 the Win32 handles
1068 * are on top of DOS handles and we do it the other way
1069 * around. Should be good enough though.
1071 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1075 if (!handle || (handle == INVALID_HANDLE_VALUE))
1078 FILE_InitProcessDosHandles();
1079 for (i = 0; i < DOS_TABLE_SIZE; i++)
1080 if (!dos_handles[i])
1082 dos_handles[i] = handle;
1083 TRACE("Got %d for h32 %p\n", i, handle );
1086 CloseHandle( handle );
1087 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1092 /***********************************************************************
1093 * DosFileHandleToWin32Handle (KERNEL32.20)
1095 * Return the Win32 handle for a DOS handle.
1097 * Note: this is not exactly right, since on Win95 the Win32 handles
1098 * are on top of DOS handles and we do it the other way
1099 * around. Should be good enough though.
1101 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1103 HFILE16 hfile = (HFILE16)handle;
1104 if (hfile < 5) FILE_InitProcessDosHandles();
1105 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1107 SetLastError( ERROR_INVALID_HANDLE );
1108 return INVALID_HANDLE_VALUE;
1110 return dos_handles[hfile];
1114 /*************************************************************************
1115 * SetHandleCount (KERNEL32.@)
1117 UINT WINAPI SetHandleCount( UINT count )
1119 return min( 256, count );
1123 /***********************************************************************
1124 * DisposeLZ32Handle (KERNEL32.22)
1126 * Note: this is not entirely correct, we should only close the
1127 * 32-bit handle and not the 16-bit one, but we cannot do
1128 * this because of the way our DOS handles are implemented.
1129 * It shouldn't break anything though.
1131 void WINAPI DisposeLZ32Handle( HANDLE handle )
1135 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1137 for (i = 5; i < DOS_TABLE_SIZE; i++)
1138 if (dos_handles[i] == handle)
1141 CloseHandle( handle );
1146 /**************************************************************************
1147 * Operations on file names *
1148 **************************************************************************/
1151 /*************************************************************************
1152 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1154 * Creates or opens an object, and returns a handle that can be used to
1155 * access that object.
1159 * filename [in] pointer to filename to be accessed
1160 * access [in] access mode requested
1161 * sharing [in] share mode
1162 * sa [in] pointer to security attributes
1163 * creation [in] how to create the file
1164 * attributes [in] attributes for newly created file
1165 * template [in] handle to file with extended attributes to copy
1168 * Success: Open handle to specified file
1169 * Failure: INVALID_HANDLE_VALUE
1171 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1172 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1173 DWORD attributes, HANDLE template )
1177 OBJECT_ATTRIBUTES attr;
1178 UNICODE_STRING nameW;
1182 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1183 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1184 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1186 static const char * const creation_name[5] =
1187 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
1189 static const UINT nt_disposition[5] =
1191 FILE_CREATE, /* CREATE_NEW */
1192 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1193 FILE_OPEN, /* OPEN_EXISTING */
1194 FILE_OPEN_IF, /* OPEN_ALWAYS */
1195 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1201 if (!filename || !filename[0])
1203 SetLastError( ERROR_PATH_NOT_FOUND );
1204 return INVALID_HANDLE_VALUE;
1207 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1209 SetLastError( ERROR_INVALID_PARAMETER );
1210 return INVALID_HANDLE_VALUE;
1213 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
1214 (access & GENERIC_READ)?"GENERIC_READ ":"",
1215 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1216 (!access)?"QUERY_ACCESS ":"",
1217 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1218 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1219 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1220 creation_name[creation - CREATE_NEW], attributes);
1222 /* Open a console for CONIN$ or CONOUT$ */
1224 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1226 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1230 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1232 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1234 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1235 !strncmpiW( filename + 4, pipeW, 5 ))
1239 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1241 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1243 else if (filename[4])
1245 ret = VXD_Open( filename+4, access, sa );
1250 SetLastError( ERROR_INVALID_NAME );
1251 return INVALID_HANDLE_VALUE;
1254 else dosdev = RtlIsDosDeviceName_U( filename );
1258 static const WCHAR conW[] = {'C','O','N'};
1260 if (LOWORD(dosdev) == sizeof(conW) &&
1261 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)))
1263 switch (access & (GENERIC_READ|GENERIC_WRITE))
1266 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1269 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1272 SetLastError( ERROR_FILE_NOT_FOUND );
1273 return INVALID_HANDLE_VALUE;
1278 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1280 SetLastError( ERROR_PATH_NOT_FOUND );
1281 return INVALID_HANDLE_VALUE;
1284 /* now call NtCreateFile */
1287 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1288 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1290 options |= FILE_NON_DIRECTORY_FILE;
1291 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1292 options |= FILE_DELETE_ON_CLOSE;
1293 if (!(attributes & FILE_FLAG_OVERLAPPED))
1294 options |= FILE_SYNCHRONOUS_IO_ALERT;
1295 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1296 options |= FILE_RANDOM_ACCESS;
1297 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1299 attr.Length = sizeof(attr);
1300 attr.RootDirectory = 0;
1301 attr.Attributes = OBJ_CASE_INSENSITIVE;
1302 attr.ObjectName = &nameW;
1303 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1304 attr.SecurityQualityOfService = NULL;
1306 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1308 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1309 sharing, nt_disposition[creation - CREATE_NEW],
1313 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1314 ret = INVALID_HANDLE_VALUE;
1316 /* In the case file creation was rejected due to CREATE_NEW flag
1317 * was specified and file with that name already exists, correct
1318 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1319 * Note: RtlNtStatusToDosError is not the subject to blame here.
1321 if (status == STATUS_OBJECT_NAME_COLLISION)
1322 SetLastError( ERROR_FILE_EXISTS );
1324 SetLastError( RtlNtStatusToDosError(status) );
1326 else SetLastError(0);
1327 RtlFreeUnicodeString( &nameW );
1330 if (!ret) ret = INVALID_HANDLE_VALUE;
1331 TRACE("returning %p\n", ret);
1337 /*************************************************************************
1338 * CreateFileA (KERNEL32.@)
1340 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1341 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1342 DWORD attributes, HANDLE template)
1346 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1347 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1351 /***********************************************************************
1352 * DeleteFileW (KERNEL32.@)
1354 BOOL WINAPI DeleteFileW( LPCWSTR path )
1356 UNICODE_STRING nameW;
1357 OBJECT_ATTRIBUTES attr;
1360 TRACE("%s\n", debugstr_w(path) );
1362 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1364 SetLastError( ERROR_PATH_NOT_FOUND );
1368 attr.Length = sizeof(attr);
1369 attr.RootDirectory = 0;
1370 attr.Attributes = OBJ_CASE_INSENSITIVE;
1371 attr.ObjectName = &nameW;
1372 attr.SecurityDescriptor = NULL;
1373 attr.SecurityQualityOfService = NULL;
1375 status = NtDeleteFile(&attr);
1376 RtlFreeUnicodeString( &nameW );
1379 SetLastError( RtlNtStatusToDosError(status) );
1386 /***********************************************************************
1387 * DeleteFileA (KERNEL32.@)
1389 BOOL WINAPI DeleteFileA( LPCSTR path )
1393 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1394 return DeleteFileW( pathW );
1398 /**************************************************************************
1399 * ReplaceFileW (KERNEL32.@)
1400 * ReplaceFile (KERNEL32.@)
1402 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1403 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1404 LPVOID lpExclude, LPVOID lpReserved)
1406 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1407 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1408 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1413 /**************************************************************************
1414 * ReplaceFileA (KERNEL32.@)
1416 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1417 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1418 LPVOID lpExclude, LPVOID lpReserved)
1420 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1421 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1422 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1427 /*************************************************************************
1428 * FindFirstFileExW (KERNEL32.@)
1430 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1431 LPVOID data, FINDEX_SEARCH_OPS search_op,
1432 LPVOID filter, DWORD flags)
1435 FIND_FIRST_INFO *info = NULL;
1436 UNICODE_STRING nt_name;
1437 OBJECT_ATTRIBUTES attr;
1441 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1443 if ((search_op != FindExSearchNameMatch) || (flags != 0))
1445 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1446 return INVALID_HANDLE_VALUE;
1448 if (level != FindExInfoStandard)
1450 FIXME("info level %d not implemented\n", level );
1451 return INVALID_HANDLE_VALUE;
1454 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1456 SetLastError( ERROR_PATH_NOT_FOUND );
1457 return INVALID_HANDLE_VALUE;
1460 if (!mask || !*mask)
1462 SetLastError( ERROR_FILE_NOT_FOUND );
1466 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1468 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1472 if (!RtlCreateUnicodeString( &info->mask, mask ))
1474 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1478 /* truncate dir name before mask */
1480 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1482 /* check if path is the root of the drive */
1483 info->is_root = FALSE;
1484 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1485 if (p[0] && p[1] == ':')
1488 while (*p == '\\') p++;
1489 info->is_root = (*p == 0);
1492 attr.Length = sizeof(attr);
1493 attr.RootDirectory = 0;
1494 attr.Attributes = OBJ_CASE_INSENSITIVE;
1495 attr.ObjectName = &nt_name;
1496 attr.SecurityDescriptor = NULL;
1497 attr.SecurityQualityOfService = NULL;
1499 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1500 FILE_SHARE_READ | FILE_SHARE_WRITE,
1501 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1503 if (status != STATUS_SUCCESS)
1505 RtlFreeUnicodeString( &info->mask );
1506 SetLastError( RtlNtStatusToDosError(status) );
1509 RtlFreeUnicodeString( &nt_name );
1511 RtlInitializeCriticalSection( &info->cs );
1512 info->magic = FIND_FIRST_MAGIC;
1516 if (!FindNextFileW( (HANDLE)info, data ))
1518 TRACE( "%s not found\n", debugstr_w(filename) );
1519 FindClose( (HANDLE)info );
1520 SetLastError( ERROR_FILE_NOT_FOUND );
1521 return INVALID_HANDLE_VALUE;
1523 return (HANDLE)info;
1526 if (info) HeapFree( GetProcessHeap(), 0, info );
1527 RtlFreeUnicodeString( &nt_name );
1528 return INVALID_HANDLE_VALUE;
1532 /*************************************************************************
1533 * FindNextFileW (KERNEL32.@)
1535 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1537 FIND_FIRST_INFO *info;
1538 FILE_BOTH_DIR_INFORMATION *dir_info;
1541 TRACE("%p %p\n", handle, data);
1543 if (!handle || handle == INVALID_HANDLE_VALUE)
1545 SetLastError( ERROR_INVALID_HANDLE );
1548 info = (FIND_FIRST_INFO *)handle;
1549 if (info->magic != FIND_FIRST_MAGIC)
1551 SetLastError( ERROR_INVALID_HANDLE );
1555 RtlEnterCriticalSection( &info->cs );
1559 if (info->data_pos >= info->data_len) /* need to read some more data */
1563 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1564 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1567 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1570 info->data_len = io.Information;
1574 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1576 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1577 else info->data_pos = info->data_len;
1579 /* don't return '.' and '..' in the root of the drive */
1582 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1583 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1584 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1587 data->dwFileAttributes = dir_info->FileAttributes;
1588 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1589 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1590 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1591 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1592 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1593 data->dwReserved0 = 0;
1594 data->dwReserved1 = 0;
1596 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1597 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1598 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1599 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1601 TRACE("returning %s (%s)\n",
1602 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1608 RtlLeaveCriticalSection( &info->cs );
1613 /*************************************************************************
1614 * FindClose (KERNEL32.@)
1616 BOOL WINAPI FindClose( HANDLE handle )
1618 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1620 if (!handle || handle == INVALID_HANDLE_VALUE)
1622 SetLastError( ERROR_INVALID_HANDLE );
1628 if (info->magic == FIND_FIRST_MAGIC)
1630 RtlEnterCriticalSection( &info->cs );
1631 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1634 if (info->handle) CloseHandle( info->handle );
1636 RtlFreeUnicodeString( &info->mask );
1637 info->mask.Buffer = NULL;
1640 RtlLeaveCriticalSection( &info->cs );
1641 RtlDeleteCriticalSection( &info->cs );
1642 HeapFree( GetProcessHeap(), 0, info );
1646 __EXCEPT(page_fault)
1648 WARN("Illegal handle %p\n", handle);
1649 SetLastError( ERROR_INVALID_HANDLE );
1658 /*************************************************************************
1659 * FindFirstFileA (KERNEL32.@)
1661 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1663 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1664 FindExSearchNameMatch, NULL, 0);
1667 /*************************************************************************
1668 * FindFirstFileExA (KERNEL32.@)
1670 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1671 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1672 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1675 WIN32_FIND_DATAA *dataA;
1676 WIN32_FIND_DATAW dataW;
1679 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1681 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1682 if (handle == INVALID_HANDLE_VALUE) return handle;
1684 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1685 dataA->dwFileAttributes = dataW.dwFileAttributes;
1686 dataA->ftCreationTime = dataW.ftCreationTime;
1687 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1688 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1689 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1690 dataA->nFileSizeLow = dataW.nFileSizeLow;
1691 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1692 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1693 sizeof(dataA->cAlternateFileName) );
1698 /*************************************************************************
1699 * FindFirstFileW (KERNEL32.@)
1701 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1703 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1704 FindExSearchNameMatch, NULL, 0);
1708 /*************************************************************************
1709 * FindNextFileA (KERNEL32.@)
1711 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1713 WIN32_FIND_DATAW dataW;
1715 if (!FindNextFileW( handle, &dataW )) return FALSE;
1716 data->dwFileAttributes = dataW.dwFileAttributes;
1717 data->ftCreationTime = dataW.ftCreationTime;
1718 data->ftLastAccessTime = dataW.ftLastAccessTime;
1719 data->ftLastWriteTime = dataW.ftLastWriteTime;
1720 data->nFileSizeHigh = dataW.nFileSizeHigh;
1721 data->nFileSizeLow = dataW.nFileSizeLow;
1722 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1723 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1724 sizeof(data->cAlternateFileName) );
1729 /**************************************************************************
1730 * GetFileAttributesW (KERNEL32.@)
1732 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1734 FILE_BASIC_INFORMATION info;
1735 UNICODE_STRING nt_name;
1736 OBJECT_ATTRIBUTES attr;
1739 TRACE("%s\n", debugstr_w(name));
1741 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1743 SetLastError( ERROR_PATH_NOT_FOUND );
1744 return INVALID_FILE_ATTRIBUTES;
1747 attr.Length = sizeof(attr);
1748 attr.RootDirectory = 0;
1749 attr.Attributes = OBJ_CASE_INSENSITIVE;
1750 attr.ObjectName = &nt_name;
1751 attr.SecurityDescriptor = NULL;
1752 attr.SecurityQualityOfService = NULL;
1754 status = NtQueryAttributesFile( &attr, &info );
1755 RtlFreeUnicodeString( &nt_name );
1757 if (status == STATUS_SUCCESS) return info.FileAttributes;
1759 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1760 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1762 SetLastError( RtlNtStatusToDosError(status) );
1763 return INVALID_FILE_ATTRIBUTES;
1767 /**************************************************************************
1768 * GetFileAttributesA (KERNEL32.@)
1770 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1774 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1775 return GetFileAttributesW( nameW );
1779 /**************************************************************************
1780 * SetFileAttributesW (KERNEL32.@)
1782 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1784 UNICODE_STRING nt_name;
1785 OBJECT_ATTRIBUTES attr;
1790 TRACE("%s %lx\n", debugstr_w(name), attributes);
1792 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1794 SetLastError( ERROR_PATH_NOT_FOUND );
1798 attr.Length = sizeof(attr);
1799 attr.RootDirectory = 0;
1800 attr.Attributes = OBJ_CASE_INSENSITIVE;
1801 attr.ObjectName = &nt_name;
1802 attr.SecurityDescriptor = NULL;
1803 attr.SecurityQualityOfService = NULL;
1805 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1806 RtlFreeUnicodeString( &nt_name );
1808 if (status == STATUS_SUCCESS)
1810 FILE_BASIC_INFORMATION info;
1812 memset( &info, 0, sizeof(info) );
1813 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1814 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1818 if (status == STATUS_SUCCESS) return TRUE;
1819 SetLastError( RtlNtStatusToDosError(status) );
1824 /**************************************************************************
1825 * SetFileAttributesA (KERNEL32.@)
1827 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1831 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1832 return SetFileAttributesW( nameW, attributes );
1836 /**************************************************************************
1837 * GetFileAttributesExW (KERNEL32.@)
1839 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1841 FILE_NETWORK_OPEN_INFORMATION info;
1842 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1843 UNICODE_STRING nt_name;
1844 OBJECT_ATTRIBUTES attr;
1847 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1849 if (level != GetFileExInfoStandard)
1851 SetLastError( ERROR_INVALID_PARAMETER );
1855 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1857 SetLastError( ERROR_PATH_NOT_FOUND );
1861 attr.Length = sizeof(attr);
1862 attr.RootDirectory = 0;
1863 attr.Attributes = OBJ_CASE_INSENSITIVE;
1864 attr.ObjectName = &nt_name;
1865 attr.SecurityDescriptor = NULL;
1866 attr.SecurityQualityOfService = NULL;
1868 status = NtQueryFullAttributesFile( &attr, &info );
1869 RtlFreeUnicodeString( &nt_name );
1871 if (status != STATUS_SUCCESS)
1873 SetLastError( RtlNtStatusToDosError(status) );
1877 data->dwFileAttributes = info.FileAttributes;
1878 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1879 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1880 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1881 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1882 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1883 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1884 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1885 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1890 /**************************************************************************
1891 * GetFileAttributesExA (KERNEL32.@)
1893 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1897 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1898 return GetFileAttributesExW( nameW, level, ptr );
1902 /******************************************************************************
1903 * GetCompressedFileSizeW (KERNEL32.@)
1906 * Success: Low-order doubleword of number of bytes
1907 * Failure: INVALID_FILE_SIZE
1909 DWORD WINAPI GetCompressedFileSizeW(
1910 LPCWSTR name, /* [in] Pointer to name of file */
1911 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1913 UNICODE_STRING nt_name;
1914 OBJECT_ATTRIBUTES attr;
1918 DWORD ret = INVALID_FILE_SIZE;
1920 TRACE("%s %p\n", debugstr_w(name), size_high);
1922 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1924 SetLastError( ERROR_PATH_NOT_FOUND );
1925 return INVALID_FILE_SIZE;
1928 attr.Length = sizeof(attr);
1929 attr.RootDirectory = 0;
1930 attr.Attributes = OBJ_CASE_INSENSITIVE;
1931 attr.ObjectName = &nt_name;
1932 attr.SecurityDescriptor = NULL;
1933 attr.SecurityQualityOfService = NULL;
1935 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1936 RtlFreeUnicodeString( &nt_name );
1938 if (status == STATUS_SUCCESS)
1940 /* we don't support compressed files, simply return the file size */
1941 ret = GetFileSize( handle, size_high );
1944 else SetLastError( RtlNtStatusToDosError(status) );
1950 /******************************************************************************
1951 * GetCompressedFileSizeA (KERNEL32.@)
1953 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
1957 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
1958 return GetCompressedFileSizeW( nameW, size_high );
1962 /***********************************************************************
1963 * OpenFile (KERNEL32.@)
1965 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1969 WORD filedatetime[2];
1971 if (!ofs) return HFILE_ERROR;
1973 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
1974 ((mode & 0x3 )==OF_READ)?"OF_READ":
1975 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
1976 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
1977 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
1978 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
1979 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
1980 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
1981 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
1982 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
1983 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
1984 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
1985 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
1986 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
1987 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
1988 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
1989 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
1990 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
1994 ofs->cBytes = sizeof(OFSTRUCT);
1996 if (mode & OF_REOPEN) name = ofs->szPathName;
1998 if (!name) return HFILE_ERROR;
2000 TRACE("%s %04x\n", name, mode );
2002 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2003 Are there any cases where getting the path here is wrong?
2004 Uwe Bonnes 1997 Apr 2 */
2005 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2007 /* OF_PARSE simply fills the structure */
2009 if (mode & OF_PARSE)
2011 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2012 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2016 /* OF_CREATE is completely different from all other options, so
2019 if (mode & OF_CREATE)
2021 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2026 /* Now look for the file */
2028 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2031 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2033 if (mode & OF_DELETE)
2035 if (!DeleteFileA( ofs->szPathName )) goto error;
2036 TRACE("(%s): OF_DELETE return = OK\n", name);
2040 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2041 if (handle == INVALID_HANDLE_VALUE) goto error;
2043 GetFileTime( handle, NULL, NULL, &filetime );
2044 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2045 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2047 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2049 CloseHandle( handle );
2050 WARN("(%s): OF_VERIFY failed\n", name );
2051 /* FIXME: what error here? */
2052 SetLastError( ERROR_FILE_NOT_FOUND );
2056 ofs->Reserved1 = filedatetime[0];
2057 ofs->Reserved2 = filedatetime[1];
2059 TRACE("(%s): OK, return = %p\n", name, handle );
2060 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2062 CloseHandle( handle );
2065 else return (HFILE)handle;
2067 error: /* We get here if there was an error opening the file */
2068 ofs->nErrCode = GetLastError();
2069 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );