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 DWORD magic; /* magic number */
55 HANDLE handle; /* handle to directory */
56 CRITICAL_SECTION cs; /* crit section protecting this structure */
57 UNICODE_STRING mask; /* file mask */
58 BOOL is_root; /* is directory the root of the drive? */
59 UINT data_pos; /* current position in dir data */
60 UINT data_len; /* length of dir data */
61 BYTE data[8192]; /* directory data */
64 #define FIND_FIRST_MAGIC 0xc0ffee11
66 static BOOL oem_file_apis;
68 static WINE_EXCEPTION_FILTER(page_fault)
70 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
71 return EXCEPTION_EXECUTE_HANDLER;
72 return EXCEPTION_CONTINUE_SEARCH;
76 /***********************************************************************
79 * Wrapper for CreateFile that takes OF_* mode flags.
81 static HANDLE create_file_OF( LPCSTR path, INT mode )
83 DWORD access, sharing, creation;
87 creation = CREATE_ALWAYS;
88 access = GENERIC_READ | GENERIC_WRITE;
92 creation = OPEN_EXISTING;
95 case OF_READ: access = GENERIC_READ; break;
96 case OF_WRITE: access = GENERIC_WRITE; break;
97 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
98 default: access = 0; break;
104 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
105 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
106 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
107 case OF_SHARE_DENY_NONE:
108 case OF_SHARE_COMPAT:
109 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
111 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
115 /***********************************************************************
118 * Set the DOS error code from errno.
120 void FILE_SetDosError(void)
122 int save_errno = errno; /* errno gets overwritten by printf */
124 TRACE("errno = %d %s\n", errno, strerror(errno));
128 SetLastError( ERROR_SHARING_VIOLATION );
131 SetLastError( ERROR_INVALID_HANDLE );
134 SetLastError( ERROR_HANDLE_DISK_FULL );
139 SetLastError( ERROR_ACCESS_DENIED );
142 SetLastError( ERROR_LOCK_VIOLATION );
145 SetLastError( ERROR_FILE_NOT_FOUND );
148 SetLastError( ERROR_CANNOT_MAKE );
152 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
155 SetLastError( ERROR_FILE_EXISTS );
159 SetLastError( ERROR_SEEK );
162 SetLastError( ERROR_DIR_NOT_EMPTY );
165 SetLastError( ERROR_BAD_FORMAT );
168 SetLastError( ERROR_PATH_NOT_FOUND );
171 SetLastError( ERROR_NOT_SAME_DEVICE );
174 WARN("unknown file error: %s\n", strerror(save_errno) );
175 SetLastError( ERROR_GEN_FAILURE );
182 /***********************************************************************
185 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
187 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
188 * there is no possibility for the function to do that twice, taking into
189 * account any called function.
191 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
194 UNICODE_STRING strW, *pstrW;
197 RtlInitAnsiString( &str, name );
198 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
200 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
202 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
203 if (status == STATUS_SUCCESS) return pstrW->Buffer;
205 if (status == STATUS_BUFFER_OVERFLOW)
206 SetLastError( ERROR_FILENAME_EXCED_RANGE );
208 SetLastError( RtlNtStatusToDosError(status) );
213 /***********************************************************************
216 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
218 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
222 if (srclen < 0) srclen = strlenW( src ) + 1;
224 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
226 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
231 /**************************************************************************
232 * SetFileApisToOEM (KERNEL32.@)
234 VOID WINAPI SetFileApisToOEM(void)
236 oem_file_apis = TRUE;
240 /**************************************************************************
241 * SetFileApisToANSI (KERNEL32.@)
243 VOID WINAPI SetFileApisToANSI(void)
245 oem_file_apis = FALSE;
249 /******************************************************************************
250 * AreFileApisANSI (KERNEL32.@)
252 * Determines if file functions are using ANSI
255 * TRUE: Set of file functions is using ANSI code page
256 * FALSE: Set of file functions is using OEM code page
258 BOOL WINAPI AreFileApisANSI(void)
260 return !oem_file_apis;
264 /**************************************************************************
265 * Operations on file handles *
266 **************************************************************************/
268 /***********************************************************************
269 * FILE_InitProcessDosHandles
271 * Allocates the default DOS handles for a process. Called either by
272 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
274 static void FILE_InitProcessDosHandles( void )
276 static BOOL init_done /* = FALSE */;
277 HANDLE cp = GetCurrentProcess();
279 if (init_done) return;
281 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
282 0, TRUE, DUPLICATE_SAME_ACCESS);
283 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
284 0, TRUE, DUPLICATE_SAME_ACCESS);
285 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
286 0, TRUE, DUPLICATE_SAME_ACCESS);
287 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
288 0, TRUE, DUPLICATE_SAME_ACCESS);
289 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
290 0, TRUE, DUPLICATE_SAME_ACCESS);
294 /******************************************************************
295 * FILE_ReadWriteApc (internal)
297 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
299 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
301 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
305 /***********************************************************************
306 * ReadFileEx (KERNEL32.@)
308 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
309 LPOVERLAPPED overlapped,
310 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
312 LARGE_INTEGER offset;
314 PIO_STATUS_BLOCK io_status;
316 TRACE("(hFile=%p, buffer=%p, bytes=%lu, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
320 SetLastError(ERROR_INVALID_PARAMETER);
324 offset.u.LowPart = overlapped->Offset;
325 offset.u.HighPart = overlapped->OffsetHigh;
326 io_status = (PIO_STATUS_BLOCK)overlapped;
327 io_status->u.Status = STATUS_PENDING;
329 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
330 io_status, buffer, bytesToRead, &offset, NULL);
334 SetLastError( RtlNtStatusToDosError(status) );
341 /***********************************************************************
342 * ReadFile (KERNEL32.@)
344 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
345 LPDWORD bytesRead, LPOVERLAPPED overlapped )
347 LARGE_INTEGER offset;
348 PLARGE_INTEGER poffset = NULL;
349 IO_STATUS_BLOCK iosb;
350 PIO_STATUS_BLOCK io_status = &iosb;
354 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
355 bytesRead, overlapped );
357 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
358 if (!bytesToRead) return TRUE;
360 if (IsBadReadPtr(buffer, bytesToRead))
362 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
365 if (is_console_handle(hFile))
366 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
368 if (overlapped != NULL)
370 offset.u.LowPart = overlapped->Offset;
371 offset.u.HighPart = overlapped->OffsetHigh;
373 hEvent = overlapped->hEvent;
374 io_status = (PIO_STATUS_BLOCK)overlapped;
376 io_status->u.Status = STATUS_PENDING;
377 io_status->Information = 0;
379 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
381 if (status != STATUS_PENDING && bytesRead)
382 *bytesRead = io_status->Information;
384 if (status && status != STATUS_END_OF_FILE)
386 SetLastError( RtlNtStatusToDosError(status) );
393 /***********************************************************************
394 * WriteFileEx (KERNEL32.@)
396 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
397 LPOVERLAPPED overlapped,
398 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
400 LARGE_INTEGER offset;
402 PIO_STATUS_BLOCK io_status;
404 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
406 if (overlapped == NULL)
408 SetLastError(ERROR_INVALID_PARAMETER);
411 offset.u.LowPart = overlapped->Offset;
412 offset.u.HighPart = overlapped->OffsetHigh;
414 io_status = (PIO_STATUS_BLOCK)overlapped;
415 io_status->u.Status = STATUS_PENDING;
417 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
418 io_status, buffer, bytesToWrite, &offset, NULL);
420 if (status) SetLastError( RtlNtStatusToDosError(status) );
425 /***********************************************************************
426 * WriteFile (KERNEL32.@)
428 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
429 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
431 HANDLE hEvent = NULL;
432 LARGE_INTEGER offset;
433 PLARGE_INTEGER poffset = NULL;
435 IO_STATUS_BLOCK iosb;
436 PIO_STATUS_BLOCK piosb = &iosb;
438 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
440 if (is_console_handle(hFile))
441 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
443 if (IsBadReadPtr(buffer, bytesToWrite))
445 SetLastError(ERROR_READ_FAULT); /* FIXME */
451 offset.u.LowPart = overlapped->Offset;
452 offset.u.HighPart = overlapped->OffsetHigh;
454 hEvent = overlapped->hEvent;
455 piosb = (PIO_STATUS_BLOCK)overlapped;
457 piosb->u.Status = STATUS_PENDING;
458 piosb->Information = 0;
460 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
461 buffer, bytesToWrite, poffset, NULL);
464 SetLastError( RtlNtStatusToDosError(status) );
467 if (bytesWritten) *bytesWritten = piosb->Information;
473 /***********************************************************************
474 * GetOverlappedResult (KERNEL32.@)
476 * Check the result of an Asynchronous data transfer from a file.
479 * HANDLE hFile [in] handle of file to check on
480 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
481 * LPDWORD lpTransferred [in/out] number of bytes transferred
482 * BOOL bWait [in] wait for the transfer to complete ?
488 * If successful (and relevant) lpTransferred will hold the number of
489 * bytes transferred during the async operation.
493 * Currently only works for WaitCommEvent, ReadFile, WriteFile
494 * with communications ports.
497 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
498 LPDWORD lpTransferred, BOOL bWait)
502 TRACE("(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
504 if (lpOverlapped==NULL)
506 ERR("lpOverlapped was null\n");
509 if (!lpOverlapped->hEvent)
511 ERR("lpOverlapped->hEvent was null\n");
518 TRACE("waiting on %p\n",lpOverlapped);
519 r = WaitForSingleObjectEx(lpOverlapped->hEvent, INFINITE, TRUE);
520 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
521 } while (r==STATUS_USER_APC);
523 else if ( lpOverlapped->Internal == STATUS_PENDING )
525 /* Wait in order to give APCs a chance to run. */
526 /* This is cheating, so we must set the event again in case of success -
527 it may be a non-manual reset event. */
529 TRACE("waiting on %p\n",lpOverlapped);
530 r = WaitForSingleObjectEx(lpOverlapped->hEvent, 0, TRUE);
531 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
532 } while (r==STATUS_USER_APC);
533 if ( r == WAIT_OBJECT_0 )
534 NtSetEvent ( lpOverlapped->hEvent, NULL );
538 *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 );
644 /***********************************************************************
645 * _lread (KERNEL32.@)
647 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
650 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
656 /***********************************************************************
657 * _llseek (KERNEL32.@)
659 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
661 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
665 /***********************************************************************
666 * _lwrite (KERNEL32.@)
668 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
670 return (UINT)_hwrite( hFile, buffer, (LONG)count );
674 /***********************************************************************
675 * FlushFileBuffers (KERNEL32.@)
677 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
680 IO_STATUS_BLOCK ioblk;
682 if (is_console_handle( hFile ))
684 /* this will fail (as expected) for an output handle */
685 /* FIXME: wait until FlushFileBuffers is moved to dll/kernel */
686 /* return FlushConsoleInputBuffer( hFile ); */
689 nts = NtFlushBuffersFile( hFile, &ioblk );
690 if (nts != STATUS_SUCCESS)
692 SetLastError( RtlNtStatusToDosError( nts ) );
700 /***********************************************************************
701 * GetFileType (KERNEL32.@)
703 DWORD WINAPI GetFileType( HANDLE hFile )
705 FILE_FS_DEVICE_INFORMATION info;
709 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
711 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
712 if (status != STATUS_SUCCESS)
714 SetLastError( RtlNtStatusToDosError(status) );
715 return FILE_TYPE_UNKNOWN;
718 switch(info.DeviceType)
720 case FILE_DEVICE_NULL:
721 case FILE_DEVICE_SERIAL_PORT:
722 case FILE_DEVICE_PARALLEL_PORT:
723 case FILE_DEVICE_UNKNOWN:
724 return FILE_TYPE_CHAR;
725 case FILE_DEVICE_NAMED_PIPE:
726 return FILE_TYPE_PIPE;
728 return FILE_TYPE_DISK;
733 /***********************************************************************
734 * GetFileInformationByHandle (KERNEL32.@)
736 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
738 FILE_ALL_INFORMATION all_info;
742 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
743 if (status == STATUS_SUCCESS)
745 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
746 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
747 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
748 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
749 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
750 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
751 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
752 info->dwVolumeSerialNumber = 0; /* FIXME */
753 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
754 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
755 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
756 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
757 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
760 SetLastError( RtlNtStatusToDosError(status) );
765 /***********************************************************************
766 * GetFileSize (KERNEL32.@)
768 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
771 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
772 if (filesizehigh) *filesizehigh = size.u.HighPart;
773 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
774 return size.u.LowPart;
778 /***********************************************************************
779 * GetFileSizeEx (KERNEL32.@)
781 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
783 FILE_END_OF_FILE_INFORMATION info;
787 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
788 if (status == STATUS_SUCCESS)
790 *lpFileSize = info.EndOfFile;
793 SetLastError( RtlNtStatusToDosError(status) );
798 /**************************************************************************
799 * SetEndOfFile (KERNEL32.@)
801 BOOL WINAPI SetEndOfFile( HANDLE hFile )
803 FILE_POSITION_INFORMATION pos;
804 FILE_END_OF_FILE_INFORMATION eof;
808 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
809 if (status == STATUS_SUCCESS)
811 eof.EndOfFile = pos.CurrentByteOffset;
812 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
814 if (status == STATUS_SUCCESS) return TRUE;
815 SetLastError( RtlNtStatusToDosError(status) );
820 /***********************************************************************
821 * SetFilePointer (KERNEL32.@)
823 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
825 LARGE_INTEGER dist, newpos;
829 dist.u.LowPart = distance;
830 dist.u.HighPart = *highword;
832 else dist.QuadPart = distance;
834 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
836 if (highword) *highword = newpos.u.HighPart;
837 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
838 return newpos.u.LowPart;
842 /***********************************************************************
843 * SetFilePointerEx (KERNEL32.@)
845 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
846 LARGE_INTEGER *newpos, DWORD method )
848 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
853 TRACE("handle %p offset %s newpos %p origin %ld\n",
854 hFile, wine_dbgstr_longlong(distance.QuadPart), newpos, method );
856 if (method > FILE_END)
858 SetLastError( ERROR_INVALID_PARAMETER );
862 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
866 pos = distance.QuadPart;
867 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
869 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
870 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
871 SetLastError( ERROR_NEGATIVE_SEEK );
879 newpos->QuadPart = res;
881 wine_server_release_fd( hFile, fd );
883 else SetLastError( RtlNtStatusToDosError(status) );
888 /***********************************************************************
889 * GetFileTime (KERNEL32.@)
891 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
892 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
894 FILE_BASIC_INFORMATION info;
898 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
899 if (status == STATUS_SUCCESS)
903 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
904 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
906 if (lpLastAccessTime)
908 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
909 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
913 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
914 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
918 SetLastError( RtlNtStatusToDosError(status) );
923 /***********************************************************************
924 * SetFileTime (KERNEL32.@)
926 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
927 const FILETIME *atime, const FILETIME *mtime )
929 FILE_BASIC_INFORMATION info;
933 memset( &info, 0, sizeof(info) );
936 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
937 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
941 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
942 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
946 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
947 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
950 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
951 if (status == STATUS_SUCCESS) return TRUE;
952 SetLastError( RtlNtStatusToDosError(status) );
957 /**************************************************************************
958 * LockFile (KERNEL32.@)
960 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
961 DWORD count_low, DWORD count_high )
964 LARGE_INTEGER count, offset;
966 TRACE( "%p %lx%08lx %lx%08lx\n",
967 hFile, offset_high, offset_low, count_high, count_low );
969 count.u.LowPart = count_low;
970 count.u.HighPart = count_high;
971 offset.u.LowPart = offset_low;
972 offset.u.HighPart = offset_high;
974 status = NtLockFile( hFile, 0, NULL, NULL,
975 NULL, &offset, &count, NULL, TRUE, TRUE );
977 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
982 /**************************************************************************
983 * LockFileEx [KERNEL32.@]
985 * Locks a byte range within an open file for shared or exclusive access.
992 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
994 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
995 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
998 LARGE_INTEGER count, offset;
1002 SetLastError( ERROR_INVALID_PARAMETER );
1006 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
1007 hFile, overlapped->OffsetHigh, overlapped->Offset,
1008 count_high, count_low, flags );
1010 count.u.LowPart = count_low;
1011 count.u.HighPart = count_high;
1012 offset.u.LowPart = overlapped->Offset;
1013 offset.u.HighPart = overlapped->OffsetHigh;
1015 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1016 NULL, &offset, &count, NULL,
1017 flags & LOCKFILE_FAIL_IMMEDIATELY,
1018 flags & LOCKFILE_EXCLUSIVE_LOCK );
1020 if (status) SetLastError( RtlNtStatusToDosError(status) );
1025 /**************************************************************************
1026 * UnlockFile (KERNEL32.@)
1028 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1029 DWORD count_low, DWORD count_high )
1032 LARGE_INTEGER count, offset;
1034 count.u.LowPart = count_low;
1035 count.u.HighPart = count_high;
1036 offset.u.LowPart = offset_low;
1037 offset.u.HighPart = offset_high;
1039 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1040 if (status) SetLastError( RtlNtStatusToDosError(status) );
1045 /**************************************************************************
1046 * UnlockFileEx (KERNEL32.@)
1048 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1049 LPOVERLAPPED overlapped )
1053 SetLastError( ERROR_INVALID_PARAMETER );
1056 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1058 return UnlockFile( hFile, overlapped->Offset, overlapped->OffsetHigh, count_low, count_high );
1062 /***********************************************************************
1063 * Win32HandleToDosFileHandle (KERNEL32.21)
1065 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1066 * longer valid after this function (even on failure).
1068 * Note: this is not exactly right, since on Win95 the Win32 handles
1069 * are on top of DOS handles and we do it the other way
1070 * around. Should be good enough though.
1072 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1076 if (!handle || (handle == INVALID_HANDLE_VALUE))
1079 FILE_InitProcessDosHandles();
1080 for (i = 0; i < DOS_TABLE_SIZE; i++)
1081 if (!dos_handles[i])
1083 dos_handles[i] = handle;
1084 TRACE("Got %d for h32 %p\n", i, handle );
1087 CloseHandle( handle );
1088 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1093 /***********************************************************************
1094 * DosFileHandleToWin32Handle (KERNEL32.20)
1096 * Return the Win32 handle for a DOS handle.
1098 * Note: this is not exactly right, since on Win95 the Win32 handles
1099 * are on top of DOS handles and we do it the other way
1100 * around. Should be good enough though.
1102 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1104 HFILE16 hfile = (HFILE16)handle;
1105 if (hfile < 5) FILE_InitProcessDosHandles();
1106 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1108 SetLastError( ERROR_INVALID_HANDLE );
1109 return INVALID_HANDLE_VALUE;
1111 return dos_handles[hfile];
1115 /*************************************************************************
1116 * SetHandleCount (KERNEL32.@)
1118 UINT WINAPI SetHandleCount( UINT count )
1120 return min( 256, count );
1124 /***********************************************************************
1125 * DisposeLZ32Handle (KERNEL32.22)
1127 * Note: this is not entirely correct, we should only close the
1128 * 32-bit handle and not the 16-bit one, but we cannot do
1129 * this because of the way our DOS handles are implemented.
1130 * It shouldn't break anything though.
1132 void WINAPI DisposeLZ32Handle( HANDLE handle )
1136 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1138 for (i = 5; i < DOS_TABLE_SIZE; i++)
1139 if (dos_handles[i] == handle)
1142 CloseHandle( handle );
1147 /**************************************************************************
1148 * Operations on file names *
1149 **************************************************************************/
1152 /*************************************************************************
1153 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1155 * Creates or opens an object, and returns a handle that can be used to
1156 * access that object.
1160 * filename [in] pointer to filename to be accessed
1161 * access [in] access mode requested
1162 * sharing [in] share mode
1163 * sa [in] pointer to security attributes
1164 * creation [in] how to create the file
1165 * attributes [in] attributes for newly created file
1166 * template [in] handle to file with extended attributes to copy
1169 * Success: Open handle to specified file
1170 * Failure: INVALID_HANDLE_VALUE
1172 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1173 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1174 DWORD attributes, HANDLE template )
1178 OBJECT_ATTRIBUTES attr;
1179 UNICODE_STRING nameW;
1183 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1184 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1185 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1187 static const char * const creation_name[5] =
1188 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
1190 static const UINT nt_disposition[5] =
1192 FILE_CREATE, /* CREATE_NEW */
1193 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1194 FILE_OPEN, /* OPEN_EXISTING */
1195 FILE_OPEN_IF, /* OPEN_ALWAYS */
1196 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1202 if (!filename || !filename[0])
1204 SetLastError( ERROR_PATH_NOT_FOUND );
1205 return INVALID_HANDLE_VALUE;
1208 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1210 SetLastError( ERROR_INVALID_PARAMETER );
1211 return INVALID_HANDLE_VALUE;
1214 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
1215 (access & GENERIC_READ)?"GENERIC_READ ":"",
1216 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1217 (!access)?"QUERY_ACCESS ":"",
1218 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1219 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1220 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1221 creation_name[creation - CREATE_NEW], attributes);
1223 /* Open a console for CONIN$ or CONOUT$ */
1225 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1227 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1231 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1233 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1235 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1236 !strncmpiW( filename + 4, pipeW, 5 ))
1240 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1242 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1244 else if (filename[4])
1246 ret = VXD_Open( filename+4, access, sa );
1251 SetLastError( ERROR_INVALID_NAME );
1252 return INVALID_HANDLE_VALUE;
1255 else dosdev = RtlIsDosDeviceName_U( filename );
1259 static const WCHAR conW[] = {'C','O','N'};
1261 if (LOWORD(dosdev) == sizeof(conW) &&
1262 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)))
1264 switch (access & (GENERIC_READ|GENERIC_WRITE))
1267 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1270 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1273 SetLastError( ERROR_FILE_NOT_FOUND );
1274 return INVALID_HANDLE_VALUE;
1279 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1281 SetLastError( ERROR_PATH_NOT_FOUND );
1282 return INVALID_HANDLE_VALUE;
1285 /* now call NtCreateFile */
1288 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1289 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1291 options |= FILE_NON_DIRECTORY_FILE;
1292 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1293 options |= FILE_DELETE_ON_CLOSE;
1294 if (!(attributes & FILE_FLAG_OVERLAPPED))
1295 options |= FILE_SYNCHRONOUS_IO_ALERT;
1296 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1297 options |= FILE_RANDOM_ACCESS;
1298 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1300 attr.Length = sizeof(attr);
1301 attr.RootDirectory = 0;
1302 attr.Attributes = OBJ_CASE_INSENSITIVE;
1303 attr.ObjectName = &nameW;
1304 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1305 attr.SecurityQualityOfService = NULL;
1307 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1309 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1310 sharing, nt_disposition[creation - CREATE_NEW],
1314 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1315 ret = INVALID_HANDLE_VALUE;
1317 /* In the case file creation was rejected due to CREATE_NEW flag
1318 * was specified and file with that name already exists, correct
1319 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1320 * Note: RtlNtStatusToDosError is not the subject to blame here.
1322 if (status == STATUS_OBJECT_NAME_COLLISION)
1323 SetLastError( ERROR_FILE_EXISTS );
1325 SetLastError( RtlNtStatusToDosError(status) );
1327 else SetLastError(0);
1328 RtlFreeUnicodeString( &nameW );
1331 if (!ret) ret = INVALID_HANDLE_VALUE;
1332 TRACE("returning %p\n", ret);
1338 /*************************************************************************
1339 * CreateFileA (KERNEL32.@)
1341 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1342 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1343 DWORD attributes, HANDLE template)
1347 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1348 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1352 /***********************************************************************
1353 * DeleteFileW (KERNEL32.@)
1355 BOOL WINAPI DeleteFileW( LPCWSTR path )
1359 TRACE("%s\n", debugstr_w(path) );
1361 hFile = CreateFileW( path, GENERIC_READ | GENERIC_WRITE,
1362 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1363 NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 );
1364 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1366 CloseHandle(hFile); /* last close will delete the file */
1371 /***********************************************************************
1372 * DeleteFileA (KERNEL32.@)
1374 BOOL WINAPI DeleteFileA( LPCSTR path )
1378 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1379 return DeleteFileW( pathW );
1383 /**************************************************************************
1384 * ReplaceFileW (KERNEL32.@)
1385 * ReplaceFile (KERNEL32.@)
1387 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1388 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1389 LPVOID lpExclude, LPVOID lpReserved)
1391 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1392 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1393 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1398 /**************************************************************************
1399 * ReplaceFileA (KERNEL32.@)
1401 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1402 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1403 LPVOID lpExclude, LPVOID lpReserved)
1405 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1406 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1407 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1412 /*************************************************************************
1413 * FindFirstFileExW (KERNEL32.@)
1415 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1416 LPVOID data, FINDEX_SEARCH_OPS search_op,
1417 LPVOID filter, DWORD flags)
1420 FIND_FIRST_INFO *info = NULL;
1421 UNICODE_STRING nt_name;
1422 OBJECT_ATTRIBUTES attr;
1426 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1428 if ((search_op != FindExSearchNameMatch) || (flags != 0))
1430 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1431 return INVALID_HANDLE_VALUE;
1433 if (level != FindExInfoStandard)
1435 FIXME("info level %d not implemented\n", level );
1436 return INVALID_HANDLE_VALUE;
1439 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1441 SetLastError( ERROR_PATH_NOT_FOUND );
1442 return INVALID_HANDLE_VALUE;
1445 if (!mask || !*mask)
1447 SetLastError( ERROR_FILE_NOT_FOUND );
1451 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1453 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1457 if (!RtlCreateUnicodeString( &info->mask, mask ))
1459 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1463 /* truncate dir name before mask */
1465 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1467 /* check if path is the root of the drive */
1468 info->is_root = FALSE;
1469 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1470 if (p[0] && p[1] == ':')
1473 while (*p == '\\') p++;
1474 info->is_root = (*p == 0);
1477 attr.Length = sizeof(attr);
1478 attr.RootDirectory = 0;
1479 attr.Attributes = OBJ_CASE_INSENSITIVE;
1480 attr.ObjectName = &nt_name;
1481 attr.SecurityDescriptor = NULL;
1482 attr.SecurityQualityOfService = NULL;
1484 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1485 FILE_SHARE_READ | FILE_SHARE_WRITE,
1486 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1488 if (status != STATUS_SUCCESS)
1490 RtlFreeUnicodeString( &info->mask );
1491 SetLastError( RtlNtStatusToDosError(status) );
1494 RtlFreeUnicodeString( &nt_name );
1496 RtlInitializeCriticalSection( &info->cs );
1497 info->magic = FIND_FIRST_MAGIC;
1501 if (!FindNextFileW( (HANDLE)info, data ))
1503 TRACE( "%s not found\n", debugstr_w(filename) );
1504 FindClose( (HANDLE)info );
1505 SetLastError( ERROR_FILE_NOT_FOUND );
1506 return INVALID_HANDLE_VALUE;
1508 return (HANDLE)info;
1511 if (info) HeapFree( GetProcessHeap(), 0, info );
1512 RtlFreeUnicodeString( &nt_name );
1513 return INVALID_HANDLE_VALUE;
1517 /*************************************************************************
1518 * FindNextFileW (KERNEL32.@)
1520 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1522 FIND_FIRST_INFO *info;
1523 FILE_BOTH_DIR_INFORMATION *dir_info;
1526 TRACE("%p %p\n", handle, data);
1528 if (!handle || handle == INVALID_HANDLE_VALUE)
1530 SetLastError( ERROR_INVALID_HANDLE );
1533 info = (FIND_FIRST_INFO *)handle;
1534 if (info->magic != FIND_FIRST_MAGIC)
1536 SetLastError( ERROR_INVALID_HANDLE );
1540 RtlEnterCriticalSection( &info->cs );
1544 if (info->data_pos >= info->data_len) /* need to read some more data */
1548 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1549 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1552 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1555 info->data_len = io.Information;
1559 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1561 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1562 else info->data_pos = info->data_len;
1564 /* don't return '.' and '..' in the root of the drive */
1567 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1568 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1569 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1572 data->dwFileAttributes = dir_info->FileAttributes;
1573 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1574 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1575 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1576 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1577 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1578 data->dwReserved0 = 0;
1579 data->dwReserved1 = 0;
1581 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1582 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1583 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1584 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1586 TRACE("returning %s (%s)\n",
1587 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1593 RtlLeaveCriticalSection( &info->cs );
1598 /*************************************************************************
1599 * FindClose (KERNEL32.@)
1601 BOOL WINAPI FindClose( HANDLE handle )
1603 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1605 if (!handle || handle == INVALID_HANDLE_VALUE)
1607 SetLastError( ERROR_INVALID_HANDLE );
1613 if (info->magic == FIND_FIRST_MAGIC)
1615 RtlEnterCriticalSection( &info->cs );
1616 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1619 if (info->handle) CloseHandle( info->handle );
1621 RtlFreeUnicodeString( &info->mask );
1622 info->mask.Buffer = NULL;
1625 RtlLeaveCriticalSection( &info->cs );
1626 RtlDeleteCriticalSection( &info->cs );
1627 HeapFree( GetProcessHeap(), 0, info );
1631 __EXCEPT(page_fault)
1633 WARN("Illegal handle %p\n", handle);
1634 SetLastError( ERROR_INVALID_HANDLE );
1643 /*************************************************************************
1644 * FindFirstFileA (KERNEL32.@)
1646 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1648 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1649 FindExSearchNameMatch, NULL, 0);
1652 /*************************************************************************
1653 * FindFirstFileExA (KERNEL32.@)
1655 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1656 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1657 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1660 WIN32_FIND_DATAA *dataA;
1661 WIN32_FIND_DATAW dataW;
1664 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1666 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1667 if (handle == INVALID_HANDLE_VALUE) return handle;
1669 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1670 dataA->dwFileAttributes = dataW.dwFileAttributes;
1671 dataA->ftCreationTime = dataW.ftCreationTime;
1672 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1673 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1674 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1675 dataA->nFileSizeLow = dataW.nFileSizeLow;
1676 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1677 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1678 sizeof(dataA->cAlternateFileName) );
1683 /*************************************************************************
1684 * FindFirstFileW (KERNEL32.@)
1686 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1688 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1689 FindExSearchNameMatch, NULL, 0);
1693 /*************************************************************************
1694 * FindNextFileA (KERNEL32.@)
1696 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1698 WIN32_FIND_DATAW dataW;
1700 if (!FindNextFileW( handle, &dataW )) return FALSE;
1701 data->dwFileAttributes = dataW.dwFileAttributes;
1702 data->ftCreationTime = dataW.ftCreationTime;
1703 data->ftLastAccessTime = dataW.ftLastAccessTime;
1704 data->ftLastWriteTime = dataW.ftLastWriteTime;
1705 data->nFileSizeHigh = dataW.nFileSizeHigh;
1706 data->nFileSizeLow = dataW.nFileSizeLow;
1707 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1708 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1709 sizeof(data->cAlternateFileName) );
1714 /**************************************************************************
1715 * GetFileAttributesW (KERNEL32.@)
1717 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1719 FILE_BASIC_INFORMATION info;
1720 UNICODE_STRING nt_name;
1721 OBJECT_ATTRIBUTES attr;
1724 TRACE("%s\n", debugstr_w(name));
1726 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1728 SetLastError( ERROR_PATH_NOT_FOUND );
1729 return INVALID_FILE_ATTRIBUTES;
1732 attr.Length = sizeof(attr);
1733 attr.RootDirectory = 0;
1734 attr.Attributes = OBJ_CASE_INSENSITIVE;
1735 attr.ObjectName = &nt_name;
1736 attr.SecurityDescriptor = NULL;
1737 attr.SecurityQualityOfService = NULL;
1739 status = NtQueryAttributesFile( &attr, &info );
1740 RtlFreeUnicodeString( &nt_name );
1742 if (status == STATUS_SUCCESS) return info.FileAttributes;
1744 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1745 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1747 SetLastError( RtlNtStatusToDosError(status) );
1748 return INVALID_FILE_ATTRIBUTES;
1752 /**************************************************************************
1753 * GetFileAttributesA (KERNEL32.@)
1755 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1759 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1760 return GetFileAttributesW( nameW );
1764 /**************************************************************************
1765 * SetFileAttributesW (KERNEL32.@)
1767 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1769 UNICODE_STRING nt_name;
1770 OBJECT_ATTRIBUTES attr;
1775 TRACE("%s %lx\n", debugstr_w(name), attributes);
1777 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1779 SetLastError( ERROR_PATH_NOT_FOUND );
1783 attr.Length = sizeof(attr);
1784 attr.RootDirectory = 0;
1785 attr.Attributes = OBJ_CASE_INSENSITIVE;
1786 attr.ObjectName = &nt_name;
1787 attr.SecurityDescriptor = NULL;
1788 attr.SecurityQualityOfService = NULL;
1790 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1791 RtlFreeUnicodeString( &nt_name );
1793 if (status == STATUS_SUCCESS)
1795 FILE_BASIC_INFORMATION info;
1797 memset( &info, 0, sizeof(info) );
1798 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1799 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1803 if (status == STATUS_SUCCESS) return TRUE;
1804 SetLastError( RtlNtStatusToDosError(status) );
1809 /**************************************************************************
1810 * SetFileAttributesA (KERNEL32.@)
1812 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1816 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1817 return SetFileAttributesW( nameW, attributes );
1821 /**************************************************************************
1822 * GetFileAttributesExW (KERNEL32.@)
1824 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1826 FILE_NETWORK_OPEN_INFORMATION info;
1827 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1828 UNICODE_STRING nt_name;
1829 OBJECT_ATTRIBUTES attr;
1832 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1834 if (level != GetFileExInfoStandard)
1836 SetLastError( ERROR_INVALID_PARAMETER );
1840 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1842 SetLastError( ERROR_PATH_NOT_FOUND );
1846 attr.Length = sizeof(attr);
1847 attr.RootDirectory = 0;
1848 attr.Attributes = OBJ_CASE_INSENSITIVE;
1849 attr.ObjectName = &nt_name;
1850 attr.SecurityDescriptor = NULL;
1851 attr.SecurityQualityOfService = NULL;
1853 status = NtQueryFullAttributesFile( &attr, &info );
1854 RtlFreeUnicodeString( &nt_name );
1856 if (status != STATUS_SUCCESS)
1858 SetLastError( RtlNtStatusToDosError(status) );
1862 data->dwFileAttributes = info.FileAttributes;
1863 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1864 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1865 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1866 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1867 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1868 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1869 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1870 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1875 /**************************************************************************
1876 * GetFileAttributesExA (KERNEL32.@)
1878 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1882 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1883 return GetFileAttributesExW( nameW, level, ptr );
1887 /******************************************************************************
1888 * GetCompressedFileSizeW (KERNEL32.@)
1891 * Success: Low-order doubleword of number of bytes
1892 * Failure: INVALID_FILE_SIZE
1894 DWORD WINAPI GetCompressedFileSizeW(
1895 LPCWSTR name, /* [in] Pointer to name of file */
1896 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1898 UNICODE_STRING nt_name;
1899 OBJECT_ATTRIBUTES attr;
1903 DWORD ret = INVALID_FILE_SIZE;
1905 TRACE("%s %p\n", debugstr_w(name), size_high);
1907 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1909 SetLastError( ERROR_PATH_NOT_FOUND );
1910 return INVALID_FILE_SIZE;
1913 attr.Length = sizeof(attr);
1914 attr.RootDirectory = 0;
1915 attr.Attributes = OBJ_CASE_INSENSITIVE;
1916 attr.ObjectName = &nt_name;
1917 attr.SecurityDescriptor = NULL;
1918 attr.SecurityQualityOfService = NULL;
1920 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1921 RtlFreeUnicodeString( &nt_name );
1923 if (status == STATUS_SUCCESS)
1925 /* we don't support compressed files, simply return the file size */
1926 ret = GetFileSize( handle, size_high );
1929 else SetLastError( RtlNtStatusToDosError(status) );
1935 /******************************************************************************
1936 * GetCompressedFileSizeA (KERNEL32.@)
1938 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
1942 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
1943 return GetCompressedFileSizeW( nameW, size_high );
1947 /***********************************************************************
1948 * OpenFile (KERNEL32.@)
1950 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1954 WORD filedatetime[2];
1956 if (!ofs) return HFILE_ERROR;
1958 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
1959 ((mode & 0x3 )==OF_READ)?"OF_READ":
1960 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
1961 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
1962 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
1963 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
1964 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
1965 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
1966 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
1967 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
1968 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
1969 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
1970 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
1971 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
1972 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
1973 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
1974 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
1975 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
1979 ofs->cBytes = sizeof(OFSTRUCT);
1981 if (mode & OF_REOPEN) name = ofs->szPathName;
1983 if (!name) return HFILE_ERROR;
1985 TRACE("%s %04x\n", name, mode );
1987 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
1988 Are there any cases where getting the path here is wrong?
1989 Uwe Bonnes 1997 Apr 2 */
1990 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
1992 /* OF_PARSE simply fills the structure */
1994 if (mode & OF_PARSE)
1996 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
1997 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2001 /* OF_CREATE is completely different from all other options, so
2004 if (mode & OF_CREATE)
2006 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2011 /* Now look for the file */
2013 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2016 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2018 if (mode & OF_DELETE)
2020 if (!DeleteFileA( ofs->szPathName )) goto error;
2021 TRACE("(%s): OF_DELETE return = OK\n", name);
2025 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2026 if (handle == INVALID_HANDLE_VALUE) goto error;
2028 GetFileTime( handle, NULL, NULL, &filetime );
2029 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2030 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2032 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2034 CloseHandle( handle );
2035 WARN("(%s): OF_VERIFY failed\n", name );
2036 /* FIXME: what error here? */
2037 SetLastError( ERROR_FILE_NOT_FOUND );
2041 ofs->Reserved1 = filedatetime[0];
2042 ofs->Reserved2 = filedatetime[1];
2044 TRACE("(%s): OK, return = %p\n", name, handle );
2045 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2047 CloseHandle( handle );
2050 else return (HFILE)handle;
2052 error: /* We get here if there was an error opening the file */
2053 ofs->nErrCode = GetLastError();
2054 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );