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 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
38 #include "wine/winbase16.h"
39 #include "kernel_private.h"
41 #include "wine/exception.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(file);
49 HANDLE dos_handles[DOS_TABLE_SIZE];
51 /* info structure for FindFirstFile handle */
54 HANDLE handle; /* handle to directory */
55 CRITICAL_SECTION cs; /* crit section protecting this structure */
56 UNICODE_STRING mask; /* file mask */
57 BOOL is_root; /* is directory the root of the drive? */
58 UINT data_pos; /* current position in dir data */
59 UINT data_len; /* length of dir data */
60 BYTE data[8192]; /* directory data */
63 static BOOL oem_file_apis;
65 static WINE_EXCEPTION_FILTER(page_fault)
67 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
68 return EXCEPTION_EXECUTE_HANDLER;
69 return EXCEPTION_CONTINUE_SEARCH;
73 /***********************************************************************
76 * Wrapper for CreateFile that takes OF_* mode flags.
78 static HANDLE create_file_OF( LPCSTR path, INT mode )
80 DWORD access, sharing, creation;
84 creation = CREATE_ALWAYS;
85 access = GENERIC_READ | GENERIC_WRITE;
89 creation = OPEN_EXISTING;
92 case OF_READ: access = GENERIC_READ; break;
93 case OF_WRITE: access = GENERIC_WRITE; break;
94 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
95 default: access = 0; break;
101 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
102 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
103 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
104 case OF_SHARE_DENY_NONE:
105 case OF_SHARE_COMPAT:
106 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
108 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
112 /***********************************************************************
115 * Set the DOS error code from errno.
117 void FILE_SetDosError(void)
119 int save_errno = errno; /* errno gets overwritten by printf */
121 TRACE("errno = %d %s\n", errno, strerror(errno));
125 SetLastError( ERROR_SHARING_VIOLATION );
128 SetLastError( ERROR_INVALID_HANDLE );
131 SetLastError( ERROR_HANDLE_DISK_FULL );
136 SetLastError( ERROR_ACCESS_DENIED );
139 SetLastError( ERROR_LOCK_VIOLATION );
142 SetLastError( ERROR_FILE_NOT_FOUND );
145 SetLastError( ERROR_CANNOT_MAKE );
149 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
152 SetLastError( ERROR_FILE_EXISTS );
156 SetLastError( ERROR_SEEK );
159 SetLastError( ERROR_DIR_NOT_EMPTY );
162 SetLastError( ERROR_BAD_FORMAT );
165 SetLastError( ERROR_PATH_NOT_FOUND );
168 SetLastError( ERROR_NOT_SAME_DEVICE );
171 WARN("unknown file error: %s\n", strerror(save_errno) );
172 SetLastError( ERROR_GEN_FAILURE );
179 /***********************************************************************
182 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
184 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
185 * there is no possibility for the function to do that twice, taking into
186 * account any called function.
188 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
191 UNICODE_STRING strW, *pstrW;
194 RtlInitAnsiString( &str, name );
195 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
197 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
199 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
200 if (status == STATUS_SUCCESS) return pstrW->Buffer;
202 if (status == STATUS_BUFFER_OVERFLOW)
203 SetLastError( ERROR_FILENAME_EXCED_RANGE );
205 SetLastError( RtlNtStatusToDosError(status) );
210 /***********************************************************************
213 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
215 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
219 if (srclen < 0) srclen = strlenW( src ) + 1;
221 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
223 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
228 /**************************************************************************
229 * SetFileApisToOEM (KERNEL32.@)
231 VOID WINAPI SetFileApisToOEM(void)
233 oem_file_apis = TRUE;
237 /**************************************************************************
238 * SetFileApisToANSI (KERNEL32.@)
240 VOID WINAPI SetFileApisToANSI(void)
242 oem_file_apis = FALSE;
246 /******************************************************************************
247 * AreFileApisANSI (KERNEL32.@)
249 * Determines if file functions are using ANSI
252 * TRUE: Set of file functions is using ANSI code page
253 * FALSE: Set of file functions is using OEM code page
255 BOOL WINAPI AreFileApisANSI(void)
257 return !oem_file_apis;
261 /**************************************************************************
262 * Operations on file handles *
263 **************************************************************************/
265 /***********************************************************************
266 * FILE_InitProcessDosHandles
268 * Allocates the default DOS handles for a process. Called either by
269 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
271 static void FILE_InitProcessDosHandles( void )
273 static BOOL init_done /* = FALSE */;
274 HANDLE cp = GetCurrentProcess();
276 if (init_done) return;
278 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
279 0, TRUE, DUPLICATE_SAME_ACCESS);
280 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
281 0, TRUE, DUPLICATE_SAME_ACCESS);
282 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
283 0, TRUE, DUPLICATE_SAME_ACCESS);
284 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
285 0, TRUE, DUPLICATE_SAME_ACCESS);
286 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
287 0, TRUE, DUPLICATE_SAME_ACCESS);
291 /******************************************************************
292 * FILE_ReadWriteApc (internal)
294 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
296 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
298 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
302 /***********************************************************************
303 * ReadFileEx (KERNEL32.@)
305 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
306 LPOVERLAPPED overlapped,
307 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
309 LARGE_INTEGER offset;
311 PIO_STATUS_BLOCK io_status;
315 SetLastError(ERROR_INVALID_PARAMETER);
319 offset.u.LowPart = overlapped->Offset;
320 offset.u.HighPart = overlapped->OffsetHigh;
321 io_status = (PIO_STATUS_BLOCK)overlapped;
322 io_status->u.Status = STATUS_PENDING;
324 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
325 io_status, buffer, bytesToRead, &offset, NULL);
329 SetLastError( RtlNtStatusToDosError(status) );
336 /***********************************************************************
337 * ReadFile (KERNEL32.@)
339 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
340 LPDWORD bytesRead, LPOVERLAPPED overlapped )
342 LARGE_INTEGER offset;
343 PLARGE_INTEGER poffset = NULL;
344 IO_STATUS_BLOCK iosb;
345 PIO_STATUS_BLOCK io_status = &iosb;
349 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
350 bytesRead, overlapped );
352 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
353 if (!bytesToRead) return TRUE;
355 if (IsBadReadPtr(buffer, bytesToRead))
357 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
360 if (is_console_handle(hFile))
361 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
363 if (overlapped != NULL)
365 offset.u.LowPart = overlapped->Offset;
366 offset.u.HighPart = overlapped->OffsetHigh;
368 hEvent = overlapped->hEvent;
369 io_status = (PIO_STATUS_BLOCK)overlapped;
371 io_status->u.Status = STATUS_PENDING;
372 io_status->Information = 0;
374 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
376 if (status != STATUS_PENDING && bytesRead)
377 *bytesRead = io_status->Information;
379 if (status && status != STATUS_END_OF_FILE)
381 SetLastError( RtlNtStatusToDosError(status) );
388 /***********************************************************************
389 * WriteFileEx (KERNEL32.@)
391 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
392 LPOVERLAPPED overlapped,
393 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
395 LARGE_INTEGER offset;
397 PIO_STATUS_BLOCK io_status;
399 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
401 if (overlapped == NULL)
403 SetLastError(ERROR_INVALID_PARAMETER);
406 offset.u.LowPart = overlapped->Offset;
407 offset.u.HighPart = overlapped->OffsetHigh;
409 io_status = (PIO_STATUS_BLOCK)overlapped;
410 io_status->u.Status = STATUS_PENDING;
412 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
413 io_status, buffer, bytesToWrite, &offset, NULL);
415 if (status) SetLastError( RtlNtStatusToDosError(status) );
420 /***********************************************************************
421 * WriteFile (KERNEL32.@)
423 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
424 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
426 HANDLE hEvent = NULL;
427 LARGE_INTEGER offset;
428 PLARGE_INTEGER poffset = NULL;
430 IO_STATUS_BLOCK iosb;
431 PIO_STATUS_BLOCK piosb = &iosb;
433 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
435 if (is_console_handle(hFile))
436 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
438 if (IsBadReadPtr(buffer, bytesToWrite))
440 SetLastError(ERROR_READ_FAULT); /* FIXME */
446 offset.u.LowPart = overlapped->Offset;
447 offset.u.HighPart = overlapped->OffsetHigh;
449 hEvent = overlapped->hEvent;
450 piosb = (PIO_STATUS_BLOCK)overlapped;
452 piosb->u.Status = STATUS_PENDING;
453 piosb->Information = 0;
455 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
456 buffer, bytesToWrite, poffset, NULL);
459 SetLastError( RtlNtStatusToDosError(status) );
462 if (bytesWritten) *bytesWritten = piosb->Information;
468 /***********************************************************************
469 * GetOverlappedResult (KERNEL32.@)
471 * Check the result of an Asynchronous data transfer from a file.
474 * HANDLE hFile [in] handle of file to check on
475 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
476 * LPDWORD lpTransferred [in/out] number of bytes transferred
477 * BOOL bWait [in] wait for the transfer to complete ?
483 * If successful (and relevant) lpTransferred will hold the number of
484 * bytes transferred during the async operation.
488 * Currently only works for WaitCommEvent, ReadFile, WriteFile
489 * with communications ports.
492 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
493 LPDWORD lpTransferred, BOOL bWait)
497 TRACE("(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
499 if (lpOverlapped==NULL)
501 ERR("lpOverlapped was null\n");
504 if (!lpOverlapped->hEvent)
506 ERR("lpOverlapped->hEvent was null\n");
513 TRACE("waiting on %p\n",lpOverlapped);
514 r = WaitForSingleObjectEx(lpOverlapped->hEvent, INFINITE, TRUE);
515 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
516 } while (r==STATUS_USER_APC);
518 else if ( lpOverlapped->Internal == STATUS_PENDING )
520 /* Wait in order to give APCs a chance to run. */
521 /* This is cheating, so we must set the event again in case of success -
522 it may be a non-manual reset event. */
524 TRACE("waiting on %p\n",lpOverlapped);
525 r = WaitForSingleObjectEx(lpOverlapped->hEvent, 0, TRUE);
526 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
527 } while (r==STATUS_USER_APC);
528 if ( r == WAIT_OBJECT_0 )
529 NtSetEvent ( lpOverlapped->hEvent, NULL );
533 *lpTransferred = lpOverlapped->InternalHigh;
535 switch ( lpOverlapped->Internal )
540 SetLastError ( ERROR_IO_INCOMPLETE );
541 if ( bWait ) ERR ("PENDING status after waiting!\n");
544 SetLastError ( RtlNtStatusToDosError ( lpOverlapped->Internal ) );
549 /***********************************************************************
550 * CancelIo (KERNEL32.@)
552 BOOL WINAPI CancelIo(HANDLE handle)
554 async_private *ovp,*t;
556 TRACE("handle = %p\n",handle);
558 for (ovp = NtCurrentTeb()->pending_list; ovp; ovp = t)
561 if ( ovp->handle == handle )
562 cancel_async ( ovp );
568 /***********************************************************************
569 * _hread (KERNEL32.@)
571 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
573 return _lread( hFile, buffer, count );
577 /***********************************************************************
578 * _hwrite (KERNEL32.@)
580 * experimentation yields that _lwrite:
581 * o truncates the file at the current position with
583 * o returns 0 on a 0 length write
584 * o works with console handles
587 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
591 TRACE("%d %p %ld\n", handle, buffer, count );
595 /* Expand or truncate at current position */
596 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
599 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
605 /***********************************************************************
606 * _lclose (KERNEL32.@)
608 HFILE WINAPI _lclose( HFILE hFile )
610 TRACE("handle %d\n", hFile );
611 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
615 /***********************************************************************
616 * _lcreat (KERNEL32.@)
618 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
620 /* Mask off all flags not explicitly allowed by the doc */
621 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
622 TRACE("%s %02x\n", path, attr );
623 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
624 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
625 CREATE_ALWAYS, attr, 0 );
629 /***********************************************************************
630 * _lopen (KERNEL32.@)
632 HFILE WINAPI _lopen( LPCSTR path, INT mode )
634 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
635 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
639 /***********************************************************************
640 * _lread (KERNEL32.@)
642 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
645 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
651 /***********************************************************************
652 * _llseek (KERNEL32.@)
654 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
656 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
660 /***********************************************************************
661 * _lwrite (KERNEL32.@)
663 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
665 return (UINT)_hwrite( hFile, buffer, (LONG)count );
669 /***********************************************************************
670 * FlushFileBuffers (KERNEL32.@)
672 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
675 IO_STATUS_BLOCK ioblk;
677 if (is_console_handle( hFile ))
679 /* this will fail (as expected) for an output handle */
680 /* FIXME: wait until FlushFileBuffers is moved to dll/kernel */
681 /* return FlushConsoleInputBuffer( hFile ); */
684 nts = NtFlushBuffersFile( hFile, &ioblk );
685 if (nts != STATUS_SUCCESS)
687 SetLastError( RtlNtStatusToDosError( nts ) );
695 /***********************************************************************
696 * GetFileType (KERNEL32.@)
698 DWORD WINAPI GetFileType( HANDLE hFile )
700 FILE_FS_DEVICE_INFORMATION info;
704 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
706 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
707 if (status != STATUS_SUCCESS)
709 SetLastError( RtlNtStatusToDosError(status) );
710 return FILE_TYPE_UNKNOWN;
713 switch(info.DeviceType)
715 case FILE_DEVICE_NULL:
716 case FILE_DEVICE_SERIAL_PORT:
717 case FILE_DEVICE_PARALLEL_PORT:
718 case FILE_DEVICE_UNKNOWN:
719 return FILE_TYPE_CHAR;
720 case FILE_DEVICE_NAMED_PIPE:
721 return FILE_TYPE_PIPE;
723 return FILE_TYPE_DISK;
728 /***********************************************************************
729 * GetFileInformationByHandle (KERNEL32.@)
731 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
733 FILE_ALL_INFORMATION all_info;
737 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
738 if (status == STATUS_SUCCESS)
740 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
741 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
742 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
743 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
744 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
745 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
746 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
747 info->dwVolumeSerialNumber = 0; /* FIXME */
748 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
749 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
750 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
751 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
752 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
755 SetLastError( RtlNtStatusToDosError(status) );
760 /***********************************************************************
761 * GetFileSize (KERNEL32.@)
763 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
766 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
767 if (filesizehigh) *filesizehigh = size.u.HighPart;
768 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
769 return size.u.LowPart;
773 /***********************************************************************
774 * GetFileSizeEx (KERNEL32.@)
776 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
778 FILE_END_OF_FILE_INFORMATION info;
782 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
783 if (status == STATUS_SUCCESS)
785 *lpFileSize = info.EndOfFile;
788 SetLastError( RtlNtStatusToDosError(status) );
793 /**************************************************************************
794 * SetEndOfFile (KERNEL32.@)
796 BOOL WINAPI SetEndOfFile( HANDLE hFile )
798 FILE_POSITION_INFORMATION pos;
799 FILE_END_OF_FILE_INFORMATION eof;
803 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
804 if (status == STATUS_SUCCESS)
806 eof.EndOfFile = pos.CurrentByteOffset;
807 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
809 if (status == STATUS_SUCCESS) return TRUE;
810 SetLastError( RtlNtStatusToDosError(status) );
815 /***********************************************************************
816 * SetFilePointer (KERNEL32.@)
818 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
821 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
822 DWORD ret = INVALID_SET_FILE_POINTER;
826 TRACE("handle %p offset %ld high %ld origin %ld\n",
827 hFile, distance, highword?*highword:0, method );
829 if (method > FILE_END)
831 SetLastError( ERROR_INVALID_PARAMETER );
835 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
839 if (highword) pos = ((off_t)*highword << 32) | (ULONG)distance;
840 else pos = (off_t)distance;
841 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
843 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
844 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
845 SetLastError( ERROR_NEGATIVE_SEEK );
852 if (highword) *highword = (res >> 32);
853 if (ret == INVALID_SET_FILE_POINTER) SetLastError( 0 );
855 wine_server_release_fd( hFile, fd );
857 else SetLastError( RtlNtStatusToDosError(status) );
863 /***********************************************************************
864 * GetFileTime (KERNEL32.@)
866 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
867 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
869 FILE_BASIC_INFORMATION info;
873 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
874 if (status == STATUS_SUCCESS)
878 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
879 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
881 if (lpLastAccessTime)
883 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
884 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
888 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
889 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
893 SetLastError( RtlNtStatusToDosError(status) );
898 /***********************************************************************
899 * SetFileTime (KERNEL32.@)
901 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
902 const FILETIME *atime, const FILETIME *mtime )
904 FILE_BASIC_INFORMATION info;
908 memset( &info, 0, sizeof(info) );
911 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
912 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
916 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
917 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
921 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
922 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
925 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
926 if (status == STATUS_SUCCESS) return TRUE;
927 SetLastError( RtlNtStatusToDosError(status) );
932 /**************************************************************************
933 * LockFile (KERNEL32.@)
935 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
936 DWORD count_low, DWORD count_high )
939 LARGE_INTEGER count, offset;
941 TRACE( "%p %lx%08lx %lx%08lx\n",
942 hFile, offset_high, offset_low, count_high, count_low );
944 count.u.LowPart = count_low;
945 count.u.HighPart = count_high;
946 offset.u.LowPart = offset_low;
947 offset.u.HighPart = offset_high;
949 status = NtLockFile( hFile, 0, NULL, NULL,
950 NULL, &offset, &count, NULL, TRUE, TRUE );
952 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
957 /**************************************************************************
958 * LockFileEx [KERNEL32.@]
960 * Locks a byte range within an open file for shared or exclusive access.
967 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
969 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
970 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
973 LARGE_INTEGER count, offset;
977 SetLastError( ERROR_INVALID_PARAMETER );
981 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
982 hFile, overlapped->OffsetHigh, overlapped->Offset,
983 count_high, count_low, flags );
985 count.u.LowPart = count_low;
986 count.u.HighPart = count_high;
987 offset.u.LowPart = overlapped->Offset;
988 offset.u.HighPart = overlapped->OffsetHigh;
990 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
991 NULL, &offset, &count, NULL,
992 flags & LOCKFILE_FAIL_IMMEDIATELY,
993 flags & LOCKFILE_EXCLUSIVE_LOCK );
995 if (status) SetLastError( RtlNtStatusToDosError(status) );
1000 /**************************************************************************
1001 * UnlockFile (KERNEL32.@)
1003 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1004 DWORD count_low, DWORD count_high )
1007 LARGE_INTEGER count, offset;
1009 count.u.LowPart = count_low;
1010 count.u.HighPart = count_high;
1011 offset.u.LowPart = offset_low;
1012 offset.u.HighPart = offset_high;
1014 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1015 if (status) SetLastError( RtlNtStatusToDosError(status) );
1020 /**************************************************************************
1021 * UnlockFileEx (KERNEL32.@)
1023 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1024 LPOVERLAPPED overlapped )
1028 SetLastError( ERROR_INVALID_PARAMETER );
1031 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1033 return UnlockFile( hFile, overlapped->Offset, overlapped->OffsetHigh, count_low, count_high );
1037 /***********************************************************************
1038 * Win32HandleToDosFileHandle (KERNEL32.21)
1040 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1041 * longer valid after this function (even on failure).
1043 * Note: this is not exactly right, since on Win95 the Win32 handles
1044 * are on top of DOS handles and we do it the other way
1045 * around. Should be good enough though.
1047 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1051 if (!handle || (handle == INVALID_HANDLE_VALUE))
1054 FILE_InitProcessDosHandles();
1055 for (i = 0; i < DOS_TABLE_SIZE; i++)
1056 if (!dos_handles[i])
1058 dos_handles[i] = handle;
1059 TRACE("Got %d for h32 %p\n", i, handle );
1062 CloseHandle( handle );
1063 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1068 /***********************************************************************
1069 * DosFileHandleToWin32Handle (KERNEL32.20)
1071 * Return the Win32 handle for a DOS handle.
1073 * Note: this is not exactly right, since on Win95 the Win32 handles
1074 * are on top of DOS handles and we do it the other way
1075 * around. Should be good enough though.
1077 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1079 HFILE16 hfile = (HFILE16)handle;
1080 if (hfile < 5) FILE_InitProcessDosHandles();
1081 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1083 SetLastError( ERROR_INVALID_HANDLE );
1084 return INVALID_HANDLE_VALUE;
1086 return dos_handles[hfile];
1090 /*************************************************************************
1091 * SetHandleCount (KERNEL32.@)
1093 UINT WINAPI SetHandleCount( UINT count )
1095 return min( 256, count );
1099 /***********************************************************************
1100 * DisposeLZ32Handle (KERNEL32.22)
1102 * Note: this is not entirely correct, we should only close the
1103 * 32-bit handle and not the 16-bit one, but we cannot do
1104 * this because of the way our DOS handles are implemented.
1105 * It shouldn't break anything though.
1107 void WINAPI DisposeLZ32Handle( HANDLE handle )
1111 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1113 for (i = 5; i < DOS_TABLE_SIZE; i++)
1114 if (dos_handles[i] == handle)
1117 CloseHandle( handle );
1122 /**************************************************************************
1123 * Operations on file names *
1124 **************************************************************************/
1127 /*************************************************************************
1128 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1130 * Creates or opens an object, and returns a handle that can be used to
1131 * access that object.
1135 * filename [in] pointer to filename to be accessed
1136 * access [in] access mode requested
1137 * sharing [in] share mode
1138 * sa [in] pointer to security attributes
1139 * creation [in] how to create the file
1140 * attributes [in] attributes for newly created file
1141 * template [in] handle to file with extended attributes to copy
1144 * Success: Open handle to specified file
1145 * Failure: INVALID_HANDLE_VALUE
1147 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1148 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1149 DWORD attributes, HANDLE template )
1153 OBJECT_ATTRIBUTES attr;
1154 UNICODE_STRING nameW;
1158 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1159 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1160 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1162 static const char * const creation_name[5] =
1163 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
1165 static const UINT nt_disposition[5] =
1167 FILE_CREATE, /* CREATE_NEW */
1168 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1169 FILE_OPEN, /* OPEN_EXISTING */
1170 FILE_OPEN_IF, /* OPEN_ALWAYS */
1171 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1177 if (!filename || !filename[0])
1179 SetLastError( ERROR_PATH_NOT_FOUND );
1180 return INVALID_HANDLE_VALUE;
1183 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1185 SetLastError( ERROR_INVALID_PARAMETER );
1186 return INVALID_HANDLE_VALUE;
1189 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
1190 (access & GENERIC_READ)?"GENERIC_READ ":"",
1191 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1192 (!access)?"QUERY_ACCESS ":"",
1193 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1194 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1195 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1196 creation_name[creation - CREATE_NEW], attributes);
1198 /* Open a console for CONIN$ or CONOUT$ */
1200 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1202 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1206 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1208 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1210 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1211 !strncmpiW( filename + 4, pipeW, 5 ))
1215 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1217 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1219 else if (filename[4])
1221 ret = VXD_Open( filename+4, access, sa );
1226 SetLastError( ERROR_INVALID_NAME );
1227 return INVALID_HANDLE_VALUE;
1230 else dosdev = RtlIsDosDeviceName_U( filename );
1234 static const WCHAR conW[] = {'C','O','N'};
1236 if (LOWORD(dosdev) == sizeof(conW) &&
1237 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)))
1239 switch (access & (GENERIC_READ|GENERIC_WRITE))
1242 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1245 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1248 SetLastError( ERROR_FILE_NOT_FOUND );
1249 return INVALID_HANDLE_VALUE;
1254 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1256 SetLastError( ERROR_PATH_NOT_FOUND );
1257 return INVALID_HANDLE_VALUE;
1260 /* now call NtCreateFile */
1263 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1264 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1266 options |= FILE_NON_DIRECTORY_FILE;
1267 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1268 options |= FILE_DELETE_ON_CLOSE;
1269 if (!(attributes & FILE_FLAG_OVERLAPPED))
1270 options |= FILE_SYNCHRONOUS_IO_ALERT;
1271 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1272 options |= FILE_RANDOM_ACCESS;
1273 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1275 attr.Length = sizeof(attr);
1276 attr.RootDirectory = 0;
1277 attr.Attributes = OBJ_CASE_INSENSITIVE;
1278 attr.ObjectName = &nameW;
1279 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1280 attr.SecurityQualityOfService = NULL;
1282 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1284 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1285 sharing, nt_disposition[creation - CREATE_NEW],
1289 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1290 ret = INVALID_HANDLE_VALUE;
1292 /* In the case file creation was rejected due to CREATE_NEW flag
1293 * was specified and file with that name already exists, correct
1294 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1295 * Note: RtlNtStatusToDosError is not the subject to blame here.
1297 if (status == STATUS_OBJECT_NAME_COLLISION)
1298 SetLastError( ERROR_FILE_EXISTS );
1300 SetLastError( RtlNtStatusToDosError(status) );
1302 else SetLastError(0);
1303 RtlFreeUnicodeString( &nameW );
1306 if (!ret) ret = INVALID_HANDLE_VALUE;
1307 TRACE("returning %p\n", ret);
1313 /*************************************************************************
1314 * CreateFileA (KERNEL32.@)
1316 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1317 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1318 DWORD attributes, HANDLE template)
1322 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1323 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1327 /***********************************************************************
1328 * DeleteFileW (KERNEL32.@)
1330 BOOL WINAPI DeleteFileW( LPCWSTR path )
1334 TRACE("%s\n", debugstr_w(path) );
1336 hFile = CreateFileW( path, GENERIC_READ | GENERIC_WRITE,
1337 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1338 NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 );
1339 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1341 CloseHandle(hFile); /* last close will delete the file */
1346 /***********************************************************************
1347 * DeleteFileA (KERNEL32.@)
1349 BOOL WINAPI DeleteFileA( LPCSTR path )
1353 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1354 return DeleteFileW( pathW );
1358 /**************************************************************************
1359 * ReplaceFileW (KERNEL32.@)
1360 * ReplaceFile (KERNEL32.@)
1362 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1363 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1364 LPVOID lpExclude, LPVOID lpReserved)
1366 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1367 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1368 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1373 /**************************************************************************
1374 * ReplaceFileA (KERNEL32.@)
1376 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1377 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1378 LPVOID lpExclude, LPVOID lpReserved)
1380 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1381 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1382 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1387 /*************************************************************************
1388 * FindFirstFileExW (KERNEL32.@)
1390 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1391 LPVOID data, FINDEX_SEARCH_OPS search_op,
1392 LPVOID filter, DWORD flags)
1395 FIND_FIRST_INFO *info = NULL;
1396 UNICODE_STRING nt_name;
1397 OBJECT_ATTRIBUTES attr;
1401 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1403 if ((search_op != FindExSearchNameMatch) || (flags != 0))
1405 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1406 return INVALID_HANDLE_VALUE;
1408 if (level != FindExInfoStandard)
1410 FIXME("info level %d not implemented\n", level );
1411 return INVALID_HANDLE_VALUE;
1414 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1416 SetLastError( ERROR_PATH_NOT_FOUND );
1417 return INVALID_HANDLE_VALUE;
1420 if (!mask || !*mask)
1422 SetLastError( ERROR_FILE_NOT_FOUND );
1426 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1428 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1432 if (!RtlCreateUnicodeString( &info->mask, mask ))
1434 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1438 /* truncate dir name before mask */
1440 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1442 /* check if path is the root of the drive */
1443 info->is_root = FALSE;
1444 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1445 if (p[0] && p[1] == ':')
1448 while (*p == '\\') p++;
1449 info->is_root = (*p == 0);
1452 attr.Length = sizeof(attr);
1453 attr.RootDirectory = 0;
1454 attr.Attributes = OBJ_CASE_INSENSITIVE;
1455 attr.ObjectName = &nt_name;
1456 attr.SecurityDescriptor = NULL;
1457 attr.SecurityQualityOfService = NULL;
1459 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1460 FILE_SHARE_READ | FILE_SHARE_WRITE,
1461 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1463 if (status != STATUS_SUCCESS)
1465 RtlFreeUnicodeString( &info->mask );
1466 SetLastError( RtlNtStatusToDosError(status) );
1469 RtlFreeUnicodeString( &nt_name );
1471 RtlInitializeCriticalSection( &info->cs );
1475 if (!FindNextFileW( (HANDLE)info, data ))
1477 TRACE( "%s not found\n", debugstr_w(filename) );
1478 FindClose( (HANDLE)info );
1479 SetLastError( ERROR_FILE_NOT_FOUND );
1480 return INVALID_HANDLE_VALUE;
1482 return (HANDLE)info;
1485 if (info) HeapFree( GetProcessHeap(), 0, info );
1486 RtlFreeUnicodeString( &nt_name );
1487 return INVALID_HANDLE_VALUE;
1491 /*************************************************************************
1492 * FindNextFileW (KERNEL32.@)
1494 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1496 FIND_FIRST_INFO *info;
1497 FILE_BOTH_DIR_INFORMATION *dir_info;
1500 TRACE("%p %p\n", handle, data);
1502 if (handle == INVALID_HANDLE_VALUE)
1504 SetLastError( ERROR_INVALID_HANDLE );
1507 info = (FIND_FIRST_INFO *)handle;
1509 RtlEnterCriticalSection( &info->cs );
1513 if (info->data_pos >= info->data_len) /* need to read some more data */
1517 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1518 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1521 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1524 info->data_len = io.Information;
1528 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1530 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1531 else info->data_pos = info->data_len;
1533 /* don't return '.' and '..' in the root of the drive */
1536 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1537 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1538 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1541 data->dwFileAttributes = dir_info->FileAttributes;
1542 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1543 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1544 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1545 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1546 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1547 data->dwReserved0 = 0;
1548 data->dwReserved1 = 0;
1550 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1551 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1552 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1553 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1555 TRACE("returning %s (%s)\n",
1556 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1562 RtlLeaveCriticalSection( &info->cs );
1567 /*************************************************************************
1568 * FindClose (KERNEL32.@)
1570 BOOL WINAPI FindClose( HANDLE handle )
1572 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1574 if (!handle || handle == INVALID_HANDLE_VALUE) goto error;
1578 RtlEnterCriticalSection( &info->cs );
1579 if (info->handle) CloseHandle( info->handle );
1581 RtlFreeUnicodeString( &info->mask );
1582 info->mask.Buffer = NULL;
1586 __EXCEPT(page_fault)
1588 WARN("Illegal handle %p\n", handle);
1589 SetLastError( ERROR_INVALID_HANDLE );
1594 RtlLeaveCriticalSection( &info->cs );
1595 RtlDeleteCriticalSection( &info->cs );
1596 HeapFree(GetProcessHeap(), 0, info);
1600 SetLastError( ERROR_INVALID_HANDLE );
1605 /*************************************************************************
1606 * FindFirstFileA (KERNEL32.@)
1608 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1610 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1611 FindExSearchNameMatch, NULL, 0);
1614 /*************************************************************************
1615 * FindFirstFileExA (KERNEL32.@)
1617 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1618 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1619 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1622 WIN32_FIND_DATAA *dataA;
1623 WIN32_FIND_DATAW dataW;
1626 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1628 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1629 if (handle == INVALID_HANDLE_VALUE) return handle;
1631 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1632 dataA->dwFileAttributes = dataW.dwFileAttributes;
1633 dataA->ftCreationTime = dataW.ftCreationTime;
1634 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1635 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1636 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1637 dataA->nFileSizeLow = dataW.nFileSizeLow;
1638 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1639 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1640 sizeof(dataA->cAlternateFileName) );
1645 /*************************************************************************
1646 * FindFirstFileW (KERNEL32.@)
1648 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1650 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1651 FindExSearchNameMatch, NULL, 0);
1655 /*************************************************************************
1656 * FindNextFileA (KERNEL32.@)
1658 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1660 WIN32_FIND_DATAW dataW;
1662 if (!FindNextFileW( handle, &dataW )) return FALSE;
1663 data->dwFileAttributes = dataW.dwFileAttributes;
1664 data->ftCreationTime = dataW.ftCreationTime;
1665 data->ftLastAccessTime = dataW.ftLastAccessTime;
1666 data->ftLastWriteTime = dataW.ftLastWriteTime;
1667 data->nFileSizeHigh = dataW.nFileSizeHigh;
1668 data->nFileSizeLow = dataW.nFileSizeLow;
1669 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1670 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1671 sizeof(data->cAlternateFileName) );
1676 /**************************************************************************
1677 * GetFileAttributesW (KERNEL32.@)
1679 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1681 FILE_BASIC_INFORMATION info;
1682 UNICODE_STRING nt_name;
1683 OBJECT_ATTRIBUTES attr;
1686 TRACE("%s\n", debugstr_w(name));
1688 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1690 SetLastError( ERROR_PATH_NOT_FOUND );
1691 return INVALID_FILE_ATTRIBUTES;
1694 attr.Length = sizeof(attr);
1695 attr.RootDirectory = 0;
1696 attr.Attributes = OBJ_CASE_INSENSITIVE;
1697 attr.ObjectName = &nt_name;
1698 attr.SecurityDescriptor = NULL;
1699 attr.SecurityQualityOfService = NULL;
1701 status = NtQueryAttributesFile( &attr, &info );
1702 RtlFreeUnicodeString( &nt_name );
1704 if (status == STATUS_SUCCESS) return info.FileAttributes;
1706 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1707 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1709 SetLastError( RtlNtStatusToDosError(status) );
1710 return INVALID_FILE_ATTRIBUTES;
1714 /**************************************************************************
1715 * GetFileAttributesA (KERNEL32.@)
1717 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1721 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1722 return GetFileAttributesW( nameW );
1726 /**************************************************************************
1727 * SetFileAttributesW (KERNEL32.@)
1729 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1731 UNICODE_STRING nt_name;
1732 OBJECT_ATTRIBUTES attr;
1737 TRACE("%s %lx\n", debugstr_w(name), attributes);
1739 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1741 SetLastError( ERROR_PATH_NOT_FOUND );
1745 attr.Length = sizeof(attr);
1746 attr.RootDirectory = 0;
1747 attr.Attributes = OBJ_CASE_INSENSITIVE;
1748 attr.ObjectName = &nt_name;
1749 attr.SecurityDescriptor = NULL;
1750 attr.SecurityQualityOfService = NULL;
1752 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1753 RtlFreeUnicodeString( &nt_name );
1755 if (status == STATUS_SUCCESS)
1757 FILE_BASIC_INFORMATION info;
1759 memset( &info, 0, sizeof(info) );
1760 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1761 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1765 if (status == STATUS_SUCCESS) return TRUE;
1766 SetLastError( RtlNtStatusToDosError(status) );
1771 /**************************************************************************
1772 * SetFileAttributesA (KERNEL32.@)
1774 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1778 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1779 return SetFileAttributesW( nameW, attributes );
1783 /**************************************************************************
1784 * GetFileAttributesExW (KERNEL32.@)
1786 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1788 FILE_NETWORK_OPEN_INFORMATION info;
1789 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1790 UNICODE_STRING nt_name;
1791 OBJECT_ATTRIBUTES attr;
1794 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1796 if (level != GetFileExInfoStandard)
1798 SetLastError( ERROR_INVALID_PARAMETER );
1802 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1804 SetLastError( ERROR_PATH_NOT_FOUND );
1808 attr.Length = sizeof(attr);
1809 attr.RootDirectory = 0;
1810 attr.Attributes = OBJ_CASE_INSENSITIVE;
1811 attr.ObjectName = &nt_name;
1812 attr.SecurityDescriptor = NULL;
1813 attr.SecurityQualityOfService = NULL;
1815 status = NtQueryFullAttributesFile( &attr, &info );
1816 RtlFreeUnicodeString( &nt_name );
1818 if (status != STATUS_SUCCESS)
1820 SetLastError( RtlNtStatusToDosError(status) );
1824 data->dwFileAttributes = info.FileAttributes;
1825 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1826 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1827 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1828 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1829 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1830 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1831 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1832 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1837 /**************************************************************************
1838 * GetFileAttributesExA (KERNEL32.@)
1840 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1844 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1845 return GetFileAttributesExW( nameW, level, ptr );
1849 /******************************************************************************
1850 * GetCompressedFileSizeW (KERNEL32.@)
1853 * Success: Low-order doubleword of number of bytes
1854 * Failure: INVALID_FILE_SIZE
1856 DWORD WINAPI GetCompressedFileSizeW(
1857 LPCWSTR name, /* [in] Pointer to name of file */
1858 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1860 UNICODE_STRING nt_name;
1861 OBJECT_ATTRIBUTES attr;
1865 DWORD ret = INVALID_FILE_SIZE;
1867 TRACE("%s %p\n", debugstr_w(name), size_high);
1869 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1871 SetLastError( ERROR_PATH_NOT_FOUND );
1872 return INVALID_FILE_SIZE;
1875 attr.Length = sizeof(attr);
1876 attr.RootDirectory = 0;
1877 attr.Attributes = OBJ_CASE_INSENSITIVE;
1878 attr.ObjectName = &nt_name;
1879 attr.SecurityDescriptor = NULL;
1880 attr.SecurityQualityOfService = NULL;
1882 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1883 RtlFreeUnicodeString( &nt_name );
1885 if (status == STATUS_SUCCESS)
1887 /* we don't support compressed files, simply return the file size */
1888 ret = GetFileSize( handle, size_high );
1891 else SetLastError( RtlNtStatusToDosError(status) );
1897 /******************************************************************************
1898 * GetCompressedFileSizeA (KERNEL32.@)
1900 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
1904 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
1905 return GetCompressedFileSizeW( nameW, size_high );
1909 /***********************************************************************
1910 * OpenFile (KERNEL32.@)
1912 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1916 WORD filedatetime[2];
1918 if (!ofs) return HFILE_ERROR;
1920 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
1921 ((mode & 0x3 )==OF_READ)?"OF_READ":
1922 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
1923 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
1924 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
1925 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
1926 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
1927 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
1928 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
1929 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
1930 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
1931 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
1932 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
1933 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
1934 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
1935 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
1936 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
1937 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
1941 ofs->cBytes = sizeof(OFSTRUCT);
1943 if (mode & OF_REOPEN) name = ofs->szPathName;
1945 if (!name) return HFILE_ERROR;
1947 TRACE("%s %04x\n", name, mode );
1949 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
1950 Are there any cases where getting the path here is wrong?
1951 Uwe Bonnes 1997 Apr 2 */
1952 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
1954 /* OF_PARSE simply fills the structure */
1956 if (mode & OF_PARSE)
1958 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
1959 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
1963 /* OF_CREATE is completely different from all other options, so
1966 if (mode & OF_CREATE)
1968 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
1973 /* Now look for the file */
1975 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
1978 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
1980 if (mode & OF_DELETE)
1982 if (!DeleteFileA( ofs->szPathName )) goto error;
1983 TRACE("(%s): OF_DELETE return = OK\n", name);
1987 handle = (HANDLE)_lopen( ofs->szPathName, mode );
1988 if (handle == INVALID_HANDLE_VALUE) goto error;
1990 GetFileTime( handle, NULL, NULL, &filetime );
1991 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
1992 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
1994 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
1996 CloseHandle( handle );
1997 WARN("(%s): OF_VERIFY failed\n", name );
1998 /* FIXME: what error here? */
1999 SetLastError( ERROR_FILE_NOT_FOUND );
2003 ofs->Reserved1 = filedatetime[0];
2004 ofs->Reserved2 = filedatetime[1];
2006 TRACE("(%s): OK, return = %p\n", name, handle );
2007 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2009 CloseHandle( handle );
2012 else return (HFILE)handle;
2014 error: /* We get here if there was an error opening the file */
2015 ofs->nErrCode = GetLastError();
2016 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );