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;
318 SetLastError(ERROR_INVALID_PARAMETER);
322 offset.u.LowPart = overlapped->Offset;
323 offset.u.HighPart = overlapped->OffsetHigh;
324 io_status = (PIO_STATUS_BLOCK)overlapped;
325 io_status->u.Status = STATUS_PENDING;
327 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
328 io_status, buffer, bytesToRead, &offset, NULL);
332 SetLastError( RtlNtStatusToDosError(status) );
339 /***********************************************************************
340 * ReadFile (KERNEL32.@)
342 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
343 LPDWORD bytesRead, LPOVERLAPPED overlapped )
345 LARGE_INTEGER offset;
346 PLARGE_INTEGER poffset = NULL;
347 IO_STATUS_BLOCK iosb;
348 PIO_STATUS_BLOCK io_status = &iosb;
352 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
353 bytesRead, overlapped );
355 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
356 if (!bytesToRead) return TRUE;
358 if (IsBadReadPtr(buffer, bytesToRead))
360 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
363 if (is_console_handle(hFile))
364 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
366 if (overlapped != NULL)
368 offset.u.LowPart = overlapped->Offset;
369 offset.u.HighPart = overlapped->OffsetHigh;
371 hEvent = overlapped->hEvent;
372 io_status = (PIO_STATUS_BLOCK)overlapped;
374 io_status->u.Status = STATUS_PENDING;
375 io_status->Information = 0;
377 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
379 if (status != STATUS_PENDING && bytesRead)
380 *bytesRead = io_status->Information;
382 if (status && status != STATUS_END_OF_FILE)
384 SetLastError( RtlNtStatusToDosError(status) );
391 /***********************************************************************
392 * WriteFileEx (KERNEL32.@)
394 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
395 LPOVERLAPPED overlapped,
396 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
398 LARGE_INTEGER offset;
400 PIO_STATUS_BLOCK io_status;
402 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
404 if (overlapped == NULL)
406 SetLastError(ERROR_INVALID_PARAMETER);
409 offset.u.LowPart = overlapped->Offset;
410 offset.u.HighPart = overlapped->OffsetHigh;
412 io_status = (PIO_STATUS_BLOCK)overlapped;
413 io_status->u.Status = STATUS_PENDING;
415 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
416 io_status, buffer, bytesToWrite, &offset, NULL);
418 if (status) SetLastError( RtlNtStatusToDosError(status) );
423 /***********************************************************************
424 * WriteFile (KERNEL32.@)
426 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
427 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
429 HANDLE hEvent = NULL;
430 LARGE_INTEGER offset;
431 PLARGE_INTEGER poffset = NULL;
433 IO_STATUS_BLOCK iosb;
434 PIO_STATUS_BLOCK piosb = &iosb;
436 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
438 if (is_console_handle(hFile))
439 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
441 if (IsBadReadPtr(buffer, bytesToWrite))
443 SetLastError(ERROR_READ_FAULT); /* FIXME */
449 offset.u.LowPart = overlapped->Offset;
450 offset.u.HighPart = overlapped->OffsetHigh;
452 hEvent = overlapped->hEvent;
453 piosb = (PIO_STATUS_BLOCK)overlapped;
455 piosb->u.Status = STATUS_PENDING;
456 piosb->Information = 0;
458 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
459 buffer, bytesToWrite, poffset, NULL);
462 SetLastError( RtlNtStatusToDosError(status) );
465 if (bytesWritten) *bytesWritten = piosb->Information;
471 /***********************************************************************
472 * GetOverlappedResult (KERNEL32.@)
474 * Check the result of an Asynchronous data transfer from a file.
477 * HANDLE hFile [in] handle of file to check on
478 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
479 * LPDWORD lpTransferred [in/out] number of bytes transferred
480 * BOOL bWait [in] wait for the transfer to complete ?
486 * If successful (and relevant) lpTransferred will hold the number of
487 * bytes transferred during the async operation.
491 * Currently only works for WaitCommEvent, ReadFile, WriteFile
492 * with communications ports.
495 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
496 LPDWORD lpTransferred, BOOL bWait)
500 TRACE("(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
502 if (lpOverlapped==NULL)
504 ERR("lpOverlapped was null\n");
507 if (!lpOverlapped->hEvent)
509 ERR("lpOverlapped->hEvent was null\n");
516 TRACE("waiting on %p\n",lpOverlapped);
517 r = WaitForSingleObjectEx(lpOverlapped->hEvent, INFINITE, TRUE);
518 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
519 } while (r==STATUS_USER_APC);
521 else if ( lpOverlapped->Internal == STATUS_PENDING )
523 /* Wait in order to give APCs a chance to run. */
524 /* This is cheating, so we must set the event again in case of success -
525 it may be a non-manual reset event. */
527 TRACE("waiting on %p\n",lpOverlapped);
528 r = WaitForSingleObjectEx(lpOverlapped->hEvent, 0, TRUE);
529 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
530 } while (r==STATUS_USER_APC);
531 if ( r == WAIT_OBJECT_0 )
532 NtSetEvent ( lpOverlapped->hEvent, NULL );
536 *lpTransferred = lpOverlapped->InternalHigh;
538 switch ( lpOverlapped->Internal )
543 SetLastError ( ERROR_IO_INCOMPLETE );
544 if ( bWait ) ERR ("PENDING status after waiting!\n");
547 SetLastError ( RtlNtStatusToDosError ( lpOverlapped->Internal ) );
552 /***********************************************************************
553 * CancelIo (KERNEL32.@)
555 BOOL WINAPI CancelIo(HANDLE handle)
557 async_private *ovp,*t;
559 TRACE("handle = %p\n",handle);
561 for (ovp = NtCurrentTeb()->pending_list; ovp; ovp = t)
564 if ( ovp->handle == handle )
565 cancel_async ( ovp );
571 /***********************************************************************
572 * _hread (KERNEL32.@)
574 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
576 return _lread( hFile, buffer, count );
580 /***********************************************************************
581 * _hwrite (KERNEL32.@)
583 * experimentation yields that _lwrite:
584 * o truncates the file at the current position with
586 * o returns 0 on a 0 length write
587 * o works with console handles
590 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
594 TRACE("%d %p %ld\n", handle, buffer, count );
598 /* Expand or truncate at current position */
599 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
602 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
608 /***********************************************************************
609 * _lclose (KERNEL32.@)
611 HFILE WINAPI _lclose( HFILE hFile )
613 TRACE("handle %d\n", hFile );
614 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
618 /***********************************************************************
619 * _lcreat (KERNEL32.@)
621 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
623 /* Mask off all flags not explicitly allowed by the doc */
624 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
625 TRACE("%s %02x\n", path, attr );
626 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
627 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
628 CREATE_ALWAYS, attr, 0 );
632 /***********************************************************************
633 * _lopen (KERNEL32.@)
635 HFILE WINAPI _lopen( LPCSTR path, INT mode )
637 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
638 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
642 /***********************************************************************
643 * _lread (KERNEL32.@)
645 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
648 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
654 /***********************************************************************
655 * _llseek (KERNEL32.@)
657 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
659 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
663 /***********************************************************************
664 * _lwrite (KERNEL32.@)
666 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
668 return (UINT)_hwrite( hFile, buffer, (LONG)count );
672 /***********************************************************************
673 * FlushFileBuffers (KERNEL32.@)
675 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
678 IO_STATUS_BLOCK ioblk;
680 if (is_console_handle( hFile ))
682 /* this will fail (as expected) for an output handle */
683 /* FIXME: wait until FlushFileBuffers is moved to dll/kernel */
684 /* return FlushConsoleInputBuffer( hFile ); */
687 nts = NtFlushBuffersFile( hFile, &ioblk );
688 if (nts != STATUS_SUCCESS)
690 SetLastError( RtlNtStatusToDosError( nts ) );
698 /***********************************************************************
699 * GetFileType (KERNEL32.@)
701 DWORD WINAPI GetFileType( HANDLE hFile )
703 FILE_FS_DEVICE_INFORMATION info;
707 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
709 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
710 if (status != STATUS_SUCCESS)
712 SetLastError( RtlNtStatusToDosError(status) );
713 return FILE_TYPE_UNKNOWN;
716 switch(info.DeviceType)
718 case FILE_DEVICE_NULL:
719 case FILE_DEVICE_SERIAL_PORT:
720 case FILE_DEVICE_PARALLEL_PORT:
721 case FILE_DEVICE_UNKNOWN:
722 return FILE_TYPE_CHAR;
723 case FILE_DEVICE_NAMED_PIPE:
724 return FILE_TYPE_PIPE;
726 return FILE_TYPE_DISK;
731 /***********************************************************************
732 * GetFileInformationByHandle (KERNEL32.@)
734 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
736 FILE_ALL_INFORMATION all_info;
740 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
741 if (status == STATUS_SUCCESS)
743 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
744 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
745 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
746 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
747 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
748 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
749 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
750 info->dwVolumeSerialNumber = 0; /* FIXME */
751 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
752 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
753 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
754 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
755 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
758 SetLastError( RtlNtStatusToDosError(status) );
763 /***********************************************************************
764 * GetFileSize (KERNEL32.@)
766 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
769 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
770 if (filesizehigh) *filesizehigh = size.u.HighPart;
771 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
772 return size.u.LowPart;
776 /***********************************************************************
777 * GetFileSizeEx (KERNEL32.@)
779 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
781 FILE_END_OF_FILE_INFORMATION info;
785 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
786 if (status == STATUS_SUCCESS)
788 *lpFileSize = info.EndOfFile;
791 SetLastError( RtlNtStatusToDosError(status) );
796 /**************************************************************************
797 * SetEndOfFile (KERNEL32.@)
799 BOOL WINAPI SetEndOfFile( HANDLE hFile )
801 FILE_POSITION_INFORMATION pos;
802 FILE_END_OF_FILE_INFORMATION eof;
806 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
807 if (status == STATUS_SUCCESS)
809 eof.EndOfFile = pos.CurrentByteOffset;
810 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
812 if (status == STATUS_SUCCESS) return TRUE;
813 SetLastError( RtlNtStatusToDosError(status) );
818 /***********************************************************************
819 * SetFilePointer (KERNEL32.@)
821 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
823 LARGE_INTEGER dist, newpos;
827 dist.u.LowPart = distance;
828 dist.u.HighPart = *highword;
830 else dist.QuadPart = distance;
832 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
834 if (highword) *highword = newpos.u.HighPart;
835 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
836 return newpos.u.LowPart;
840 /***********************************************************************
841 * SetFilePointerEx (KERNEL32.@)
843 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
844 LARGE_INTEGER *newpos, DWORD method )
846 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
851 TRACE("handle %p offset %s newpos %p origin %ld\n",
852 hFile, wine_dbgstr_longlong(distance.QuadPart), newpos, method );
854 if (method > FILE_END)
856 SetLastError( ERROR_INVALID_PARAMETER );
860 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
864 pos = distance.QuadPart;
865 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
867 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
868 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
869 SetLastError( ERROR_NEGATIVE_SEEK );
877 newpos->QuadPart = res;
879 wine_server_release_fd( hFile, fd );
881 else SetLastError( RtlNtStatusToDosError(status) );
886 /***********************************************************************
887 * GetFileTime (KERNEL32.@)
889 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
890 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
892 FILE_BASIC_INFORMATION info;
896 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
897 if (status == STATUS_SUCCESS)
901 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
902 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
904 if (lpLastAccessTime)
906 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
907 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
911 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
912 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
916 SetLastError( RtlNtStatusToDosError(status) );
921 /***********************************************************************
922 * SetFileTime (KERNEL32.@)
924 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
925 const FILETIME *atime, const FILETIME *mtime )
927 FILE_BASIC_INFORMATION info;
931 memset( &info, 0, sizeof(info) );
934 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
935 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
939 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
940 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
944 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
945 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
948 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
949 if (status == STATUS_SUCCESS) return TRUE;
950 SetLastError( RtlNtStatusToDosError(status) );
955 /**************************************************************************
956 * LockFile (KERNEL32.@)
958 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
959 DWORD count_low, DWORD count_high )
962 LARGE_INTEGER count, offset;
964 TRACE( "%p %lx%08lx %lx%08lx\n",
965 hFile, offset_high, offset_low, count_high, count_low );
967 count.u.LowPart = count_low;
968 count.u.HighPart = count_high;
969 offset.u.LowPart = offset_low;
970 offset.u.HighPart = offset_high;
972 status = NtLockFile( hFile, 0, NULL, NULL,
973 NULL, &offset, &count, NULL, TRUE, TRUE );
975 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
980 /**************************************************************************
981 * LockFileEx [KERNEL32.@]
983 * Locks a byte range within an open file for shared or exclusive access.
990 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
992 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
993 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
996 LARGE_INTEGER count, offset;
1000 SetLastError( ERROR_INVALID_PARAMETER );
1004 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
1005 hFile, overlapped->OffsetHigh, overlapped->Offset,
1006 count_high, count_low, flags );
1008 count.u.LowPart = count_low;
1009 count.u.HighPart = count_high;
1010 offset.u.LowPart = overlapped->Offset;
1011 offset.u.HighPart = overlapped->OffsetHigh;
1013 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1014 NULL, &offset, &count, NULL,
1015 flags & LOCKFILE_FAIL_IMMEDIATELY,
1016 flags & LOCKFILE_EXCLUSIVE_LOCK );
1018 if (status) SetLastError( RtlNtStatusToDosError(status) );
1023 /**************************************************************************
1024 * UnlockFile (KERNEL32.@)
1026 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1027 DWORD count_low, DWORD count_high )
1030 LARGE_INTEGER count, offset;
1032 count.u.LowPart = count_low;
1033 count.u.HighPart = count_high;
1034 offset.u.LowPart = offset_low;
1035 offset.u.HighPart = offset_high;
1037 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1038 if (status) SetLastError( RtlNtStatusToDosError(status) );
1043 /**************************************************************************
1044 * UnlockFileEx (KERNEL32.@)
1046 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1047 LPOVERLAPPED overlapped )
1051 SetLastError( ERROR_INVALID_PARAMETER );
1054 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1056 return UnlockFile( hFile, overlapped->Offset, overlapped->OffsetHigh, count_low, count_high );
1060 /***********************************************************************
1061 * Win32HandleToDosFileHandle (KERNEL32.21)
1063 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1064 * longer valid after this function (even on failure).
1066 * Note: this is not exactly right, since on Win95 the Win32 handles
1067 * are on top of DOS handles and we do it the other way
1068 * around. Should be good enough though.
1070 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1074 if (!handle || (handle == INVALID_HANDLE_VALUE))
1077 FILE_InitProcessDosHandles();
1078 for (i = 0; i < DOS_TABLE_SIZE; i++)
1079 if (!dos_handles[i])
1081 dos_handles[i] = handle;
1082 TRACE("Got %d for h32 %p\n", i, handle );
1085 CloseHandle( handle );
1086 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1091 /***********************************************************************
1092 * DosFileHandleToWin32Handle (KERNEL32.20)
1094 * Return the Win32 handle for a DOS handle.
1096 * Note: this is not exactly right, since on Win95 the Win32 handles
1097 * are on top of DOS handles and we do it the other way
1098 * around. Should be good enough though.
1100 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1102 HFILE16 hfile = (HFILE16)handle;
1103 if (hfile < 5) FILE_InitProcessDosHandles();
1104 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1106 SetLastError( ERROR_INVALID_HANDLE );
1107 return INVALID_HANDLE_VALUE;
1109 return dos_handles[hfile];
1113 /*************************************************************************
1114 * SetHandleCount (KERNEL32.@)
1116 UINT WINAPI SetHandleCount( UINT count )
1118 return min( 256, count );
1122 /***********************************************************************
1123 * DisposeLZ32Handle (KERNEL32.22)
1125 * Note: this is not entirely correct, we should only close the
1126 * 32-bit handle and not the 16-bit one, but we cannot do
1127 * this because of the way our DOS handles are implemented.
1128 * It shouldn't break anything though.
1130 void WINAPI DisposeLZ32Handle( HANDLE handle )
1134 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1136 for (i = 5; i < DOS_TABLE_SIZE; i++)
1137 if (dos_handles[i] == handle)
1140 CloseHandle( handle );
1145 /**************************************************************************
1146 * Operations on file names *
1147 **************************************************************************/
1150 /*************************************************************************
1151 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1153 * Creates or opens an object, and returns a handle that can be used to
1154 * access that object.
1158 * filename [in] pointer to filename to be accessed
1159 * access [in] access mode requested
1160 * sharing [in] share mode
1161 * sa [in] pointer to security attributes
1162 * creation [in] how to create the file
1163 * attributes [in] attributes for newly created file
1164 * template [in] handle to file with extended attributes to copy
1167 * Success: Open handle to specified file
1168 * Failure: INVALID_HANDLE_VALUE
1170 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1171 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1172 DWORD attributes, HANDLE template )
1176 OBJECT_ATTRIBUTES attr;
1177 UNICODE_STRING nameW;
1181 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1182 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1183 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1185 static const char * const creation_name[5] =
1186 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
1188 static const UINT nt_disposition[5] =
1190 FILE_CREATE, /* CREATE_NEW */
1191 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1192 FILE_OPEN, /* OPEN_EXISTING */
1193 FILE_OPEN_IF, /* OPEN_ALWAYS */
1194 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1200 if (!filename || !filename[0])
1202 SetLastError( ERROR_PATH_NOT_FOUND );
1203 return INVALID_HANDLE_VALUE;
1206 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1208 SetLastError( ERROR_INVALID_PARAMETER );
1209 return INVALID_HANDLE_VALUE;
1212 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
1213 (access & GENERIC_READ)?"GENERIC_READ ":"",
1214 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1215 (!access)?"QUERY_ACCESS ":"",
1216 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1217 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1218 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1219 creation_name[creation - CREATE_NEW], attributes);
1221 /* Open a console for CONIN$ or CONOUT$ */
1223 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1225 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1229 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1231 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1233 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1234 !strncmpiW( filename + 4, pipeW, 5 ))
1238 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1240 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1242 else if (filename[4])
1244 ret = VXD_Open( filename+4, access, sa );
1249 SetLastError( ERROR_INVALID_NAME );
1250 return INVALID_HANDLE_VALUE;
1253 else dosdev = RtlIsDosDeviceName_U( filename );
1257 static const WCHAR conW[] = {'C','O','N'};
1259 if (LOWORD(dosdev) == sizeof(conW) &&
1260 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)))
1262 switch (access & (GENERIC_READ|GENERIC_WRITE))
1265 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1268 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1271 SetLastError( ERROR_FILE_NOT_FOUND );
1272 return INVALID_HANDLE_VALUE;
1277 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1279 SetLastError( ERROR_PATH_NOT_FOUND );
1280 return INVALID_HANDLE_VALUE;
1283 /* now call NtCreateFile */
1286 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1287 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1289 options |= FILE_NON_DIRECTORY_FILE;
1290 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1291 options |= FILE_DELETE_ON_CLOSE;
1292 if (!(attributes & FILE_FLAG_OVERLAPPED))
1293 options |= FILE_SYNCHRONOUS_IO_ALERT;
1294 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1295 options |= FILE_RANDOM_ACCESS;
1296 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1298 attr.Length = sizeof(attr);
1299 attr.RootDirectory = 0;
1300 attr.Attributes = OBJ_CASE_INSENSITIVE;
1301 attr.ObjectName = &nameW;
1302 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1303 attr.SecurityQualityOfService = NULL;
1305 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1307 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1308 sharing, nt_disposition[creation - CREATE_NEW],
1312 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1313 ret = INVALID_HANDLE_VALUE;
1315 /* In the case file creation was rejected due to CREATE_NEW flag
1316 * was specified and file with that name already exists, correct
1317 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1318 * Note: RtlNtStatusToDosError is not the subject to blame here.
1320 if (status == STATUS_OBJECT_NAME_COLLISION)
1321 SetLastError( ERROR_FILE_EXISTS );
1323 SetLastError( RtlNtStatusToDosError(status) );
1325 else SetLastError(0);
1326 RtlFreeUnicodeString( &nameW );
1329 if (!ret) ret = INVALID_HANDLE_VALUE;
1330 TRACE("returning %p\n", ret);
1336 /*************************************************************************
1337 * CreateFileA (KERNEL32.@)
1339 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1340 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1341 DWORD attributes, HANDLE template)
1345 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1346 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1350 /***********************************************************************
1351 * DeleteFileW (KERNEL32.@)
1353 BOOL WINAPI DeleteFileW( LPCWSTR path )
1357 TRACE("%s\n", debugstr_w(path) );
1359 hFile = CreateFileW( path, GENERIC_READ | GENERIC_WRITE,
1360 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1361 NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 );
1362 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1364 CloseHandle(hFile); /* last close will delete the file */
1369 /***********************************************************************
1370 * DeleteFileA (KERNEL32.@)
1372 BOOL WINAPI DeleteFileA( LPCSTR path )
1376 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1377 return DeleteFileW( pathW );
1381 /**************************************************************************
1382 * ReplaceFileW (KERNEL32.@)
1383 * ReplaceFile (KERNEL32.@)
1385 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1386 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1387 LPVOID lpExclude, LPVOID lpReserved)
1389 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1390 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1391 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1396 /**************************************************************************
1397 * ReplaceFileA (KERNEL32.@)
1399 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1400 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1401 LPVOID lpExclude, LPVOID lpReserved)
1403 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1404 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1405 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1410 /*************************************************************************
1411 * FindFirstFileExW (KERNEL32.@)
1413 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1414 LPVOID data, FINDEX_SEARCH_OPS search_op,
1415 LPVOID filter, DWORD flags)
1418 FIND_FIRST_INFO *info = NULL;
1419 UNICODE_STRING nt_name;
1420 OBJECT_ATTRIBUTES attr;
1424 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1426 if ((search_op != FindExSearchNameMatch) || (flags != 0))
1428 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1429 return INVALID_HANDLE_VALUE;
1431 if (level != FindExInfoStandard)
1433 FIXME("info level %d not implemented\n", level );
1434 return INVALID_HANDLE_VALUE;
1437 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1439 SetLastError( ERROR_PATH_NOT_FOUND );
1440 return INVALID_HANDLE_VALUE;
1443 if (!mask || !*mask)
1445 SetLastError( ERROR_FILE_NOT_FOUND );
1449 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1451 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1455 if (!RtlCreateUnicodeString( &info->mask, mask ))
1457 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1461 /* truncate dir name before mask */
1463 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1465 /* check if path is the root of the drive */
1466 info->is_root = FALSE;
1467 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1468 if (p[0] && p[1] == ':')
1471 while (*p == '\\') p++;
1472 info->is_root = (*p == 0);
1475 attr.Length = sizeof(attr);
1476 attr.RootDirectory = 0;
1477 attr.Attributes = OBJ_CASE_INSENSITIVE;
1478 attr.ObjectName = &nt_name;
1479 attr.SecurityDescriptor = NULL;
1480 attr.SecurityQualityOfService = NULL;
1482 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1483 FILE_SHARE_READ | FILE_SHARE_WRITE,
1484 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1486 if (status != STATUS_SUCCESS)
1488 RtlFreeUnicodeString( &info->mask );
1489 SetLastError( RtlNtStatusToDosError(status) );
1492 RtlFreeUnicodeString( &nt_name );
1494 RtlInitializeCriticalSection( &info->cs );
1495 info->magic = FIND_FIRST_MAGIC;
1499 if (!FindNextFileW( (HANDLE)info, data ))
1501 TRACE( "%s not found\n", debugstr_w(filename) );
1502 FindClose( (HANDLE)info );
1503 SetLastError( ERROR_FILE_NOT_FOUND );
1504 return INVALID_HANDLE_VALUE;
1506 return (HANDLE)info;
1509 if (info) HeapFree( GetProcessHeap(), 0, info );
1510 RtlFreeUnicodeString( &nt_name );
1511 return INVALID_HANDLE_VALUE;
1515 /*************************************************************************
1516 * FindNextFileW (KERNEL32.@)
1518 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1520 FIND_FIRST_INFO *info;
1521 FILE_BOTH_DIR_INFORMATION *dir_info;
1524 TRACE("%p %p\n", handle, data);
1526 if (!handle || handle == INVALID_HANDLE_VALUE)
1528 SetLastError( ERROR_INVALID_HANDLE );
1531 info = (FIND_FIRST_INFO *)handle;
1532 if (info->magic != FIND_FIRST_MAGIC)
1534 SetLastError( ERROR_INVALID_HANDLE );
1538 RtlEnterCriticalSection( &info->cs );
1542 if (info->data_pos >= info->data_len) /* need to read some more data */
1546 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1547 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1550 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1553 info->data_len = io.Information;
1557 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1559 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1560 else info->data_pos = info->data_len;
1562 /* don't return '.' and '..' in the root of the drive */
1565 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1566 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1567 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1570 data->dwFileAttributes = dir_info->FileAttributes;
1571 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1572 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1573 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1574 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1575 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1576 data->dwReserved0 = 0;
1577 data->dwReserved1 = 0;
1579 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1580 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1581 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1582 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1584 TRACE("returning %s (%s)\n",
1585 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1591 RtlLeaveCriticalSection( &info->cs );
1596 /*************************************************************************
1597 * FindClose (KERNEL32.@)
1599 BOOL WINAPI FindClose( HANDLE handle )
1601 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1603 if (!handle || handle == INVALID_HANDLE_VALUE)
1605 SetLastError( ERROR_INVALID_HANDLE );
1611 if (info->magic == FIND_FIRST_MAGIC)
1613 RtlEnterCriticalSection( &info->cs );
1614 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1617 if (info->handle) CloseHandle( info->handle );
1619 RtlFreeUnicodeString( &info->mask );
1620 info->mask.Buffer = NULL;
1623 RtlLeaveCriticalSection( &info->cs );
1624 RtlDeleteCriticalSection( &info->cs );
1625 HeapFree( GetProcessHeap(), 0, info );
1629 __EXCEPT(page_fault)
1631 WARN("Illegal handle %p\n", handle);
1632 SetLastError( ERROR_INVALID_HANDLE );
1641 /*************************************************************************
1642 * FindFirstFileA (KERNEL32.@)
1644 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1646 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1647 FindExSearchNameMatch, NULL, 0);
1650 /*************************************************************************
1651 * FindFirstFileExA (KERNEL32.@)
1653 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1654 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1655 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1658 WIN32_FIND_DATAA *dataA;
1659 WIN32_FIND_DATAW dataW;
1662 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1664 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1665 if (handle == INVALID_HANDLE_VALUE) return handle;
1667 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1668 dataA->dwFileAttributes = dataW.dwFileAttributes;
1669 dataA->ftCreationTime = dataW.ftCreationTime;
1670 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1671 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1672 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1673 dataA->nFileSizeLow = dataW.nFileSizeLow;
1674 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1675 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1676 sizeof(dataA->cAlternateFileName) );
1681 /*************************************************************************
1682 * FindFirstFileW (KERNEL32.@)
1684 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1686 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1687 FindExSearchNameMatch, NULL, 0);
1691 /*************************************************************************
1692 * FindNextFileA (KERNEL32.@)
1694 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1696 WIN32_FIND_DATAW dataW;
1698 if (!FindNextFileW( handle, &dataW )) return FALSE;
1699 data->dwFileAttributes = dataW.dwFileAttributes;
1700 data->ftCreationTime = dataW.ftCreationTime;
1701 data->ftLastAccessTime = dataW.ftLastAccessTime;
1702 data->ftLastWriteTime = dataW.ftLastWriteTime;
1703 data->nFileSizeHigh = dataW.nFileSizeHigh;
1704 data->nFileSizeLow = dataW.nFileSizeLow;
1705 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1706 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1707 sizeof(data->cAlternateFileName) );
1712 /**************************************************************************
1713 * GetFileAttributesW (KERNEL32.@)
1715 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1717 FILE_BASIC_INFORMATION info;
1718 UNICODE_STRING nt_name;
1719 OBJECT_ATTRIBUTES attr;
1722 TRACE("%s\n", debugstr_w(name));
1724 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1726 SetLastError( ERROR_PATH_NOT_FOUND );
1727 return INVALID_FILE_ATTRIBUTES;
1730 attr.Length = sizeof(attr);
1731 attr.RootDirectory = 0;
1732 attr.Attributes = OBJ_CASE_INSENSITIVE;
1733 attr.ObjectName = &nt_name;
1734 attr.SecurityDescriptor = NULL;
1735 attr.SecurityQualityOfService = NULL;
1737 status = NtQueryAttributesFile( &attr, &info );
1738 RtlFreeUnicodeString( &nt_name );
1740 if (status == STATUS_SUCCESS) return info.FileAttributes;
1742 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1743 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1745 SetLastError( RtlNtStatusToDosError(status) );
1746 return INVALID_FILE_ATTRIBUTES;
1750 /**************************************************************************
1751 * GetFileAttributesA (KERNEL32.@)
1753 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1757 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1758 return GetFileAttributesW( nameW );
1762 /**************************************************************************
1763 * SetFileAttributesW (KERNEL32.@)
1765 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1767 UNICODE_STRING nt_name;
1768 OBJECT_ATTRIBUTES attr;
1773 TRACE("%s %lx\n", debugstr_w(name), attributes);
1775 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1777 SetLastError( ERROR_PATH_NOT_FOUND );
1781 attr.Length = sizeof(attr);
1782 attr.RootDirectory = 0;
1783 attr.Attributes = OBJ_CASE_INSENSITIVE;
1784 attr.ObjectName = &nt_name;
1785 attr.SecurityDescriptor = NULL;
1786 attr.SecurityQualityOfService = NULL;
1788 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1789 RtlFreeUnicodeString( &nt_name );
1791 if (status == STATUS_SUCCESS)
1793 FILE_BASIC_INFORMATION info;
1795 memset( &info, 0, sizeof(info) );
1796 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1797 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1801 if (status == STATUS_SUCCESS) return TRUE;
1802 SetLastError( RtlNtStatusToDosError(status) );
1807 /**************************************************************************
1808 * SetFileAttributesA (KERNEL32.@)
1810 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1814 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1815 return SetFileAttributesW( nameW, attributes );
1819 /**************************************************************************
1820 * GetFileAttributesExW (KERNEL32.@)
1822 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1824 FILE_NETWORK_OPEN_INFORMATION info;
1825 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1826 UNICODE_STRING nt_name;
1827 OBJECT_ATTRIBUTES attr;
1830 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1832 if (level != GetFileExInfoStandard)
1834 SetLastError( ERROR_INVALID_PARAMETER );
1838 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1840 SetLastError( ERROR_PATH_NOT_FOUND );
1844 attr.Length = sizeof(attr);
1845 attr.RootDirectory = 0;
1846 attr.Attributes = OBJ_CASE_INSENSITIVE;
1847 attr.ObjectName = &nt_name;
1848 attr.SecurityDescriptor = NULL;
1849 attr.SecurityQualityOfService = NULL;
1851 status = NtQueryFullAttributesFile( &attr, &info );
1852 RtlFreeUnicodeString( &nt_name );
1854 if (status != STATUS_SUCCESS)
1856 SetLastError( RtlNtStatusToDosError(status) );
1860 data->dwFileAttributes = info.FileAttributes;
1861 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1862 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1863 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1864 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1865 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1866 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1867 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1868 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1873 /**************************************************************************
1874 * GetFileAttributesExA (KERNEL32.@)
1876 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1880 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1881 return GetFileAttributesExW( nameW, level, ptr );
1885 /******************************************************************************
1886 * GetCompressedFileSizeW (KERNEL32.@)
1889 * Success: Low-order doubleword of number of bytes
1890 * Failure: INVALID_FILE_SIZE
1892 DWORD WINAPI GetCompressedFileSizeW(
1893 LPCWSTR name, /* [in] Pointer to name of file */
1894 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1896 UNICODE_STRING nt_name;
1897 OBJECT_ATTRIBUTES attr;
1901 DWORD ret = INVALID_FILE_SIZE;
1903 TRACE("%s %p\n", debugstr_w(name), size_high);
1905 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1907 SetLastError( ERROR_PATH_NOT_FOUND );
1908 return INVALID_FILE_SIZE;
1911 attr.Length = sizeof(attr);
1912 attr.RootDirectory = 0;
1913 attr.Attributes = OBJ_CASE_INSENSITIVE;
1914 attr.ObjectName = &nt_name;
1915 attr.SecurityDescriptor = NULL;
1916 attr.SecurityQualityOfService = NULL;
1918 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1919 RtlFreeUnicodeString( &nt_name );
1921 if (status == STATUS_SUCCESS)
1923 /* we don't support compressed files, simply return the file size */
1924 ret = GetFileSize( handle, size_high );
1927 else SetLastError( RtlNtStatusToDosError(status) );
1933 /******************************************************************************
1934 * GetCompressedFileSizeA (KERNEL32.@)
1936 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
1940 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
1941 return GetCompressedFileSizeW( nameW, size_high );
1945 /***********************************************************************
1946 * OpenFile (KERNEL32.@)
1948 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1952 WORD filedatetime[2];
1954 if (!ofs) return HFILE_ERROR;
1956 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
1957 ((mode & 0x3 )==OF_READ)?"OF_READ":
1958 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
1959 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
1960 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
1961 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
1962 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
1963 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
1964 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
1965 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
1966 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
1967 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
1968 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
1969 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
1970 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
1971 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
1972 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
1973 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
1977 ofs->cBytes = sizeof(OFSTRUCT);
1979 if (mode & OF_REOPEN) name = ofs->szPathName;
1981 if (!name) return HFILE_ERROR;
1983 TRACE("%s %04x\n", name, mode );
1985 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
1986 Are there any cases where getting the path here is wrong?
1987 Uwe Bonnes 1997 Apr 2 */
1988 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
1990 /* OF_PARSE simply fills the structure */
1992 if (mode & OF_PARSE)
1994 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
1995 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
1999 /* OF_CREATE is completely different from all other options, so
2002 if (mode & OF_CREATE)
2004 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2009 /* Now look for the file */
2011 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2014 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2016 if (mode & OF_DELETE)
2018 if (!DeleteFileA( ofs->szPathName )) goto error;
2019 TRACE("(%s): OF_DELETE return = OK\n", name);
2023 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2024 if (handle == INVALID_HANDLE_VALUE) goto error;
2026 GetFileTime( handle, NULL, NULL, &filetime );
2027 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2028 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2030 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2032 CloseHandle( handle );
2033 WARN("(%s): OF_VERIFY failed\n", name );
2034 /* FIXME: what error here? */
2035 SetLastError( ERROR_FILE_NOT_FOUND );
2039 ofs->Reserved1 = filedatetime[0];
2040 ofs->Reserved2 = filedatetime[1];
2042 TRACE("(%s): OK, return = %p\n", name, handle );
2043 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2045 CloseHandle( handle );
2048 else return (HFILE)handle;
2050 error: /* We get here if there was an error opening the file */
2051 ofs->nErrCode = GetLastError();
2052 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );