2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996, 2004 Alexandre Julliard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "wine/port.h"
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
36 #define WIN32_NO_STATUS
42 #include "wine/winbase16.h"
43 #include "kernel_private.h"
45 #include "wine/exception.h"
47 #include "wine/unicode.h"
48 #include "wine/debug.h"
50 #include "wine/server.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(file);
54 HANDLE dos_handles[DOS_TABLE_SIZE];
56 /* info structure for FindFirstFile handle */
59 DWORD magic; /* magic number */
60 HANDLE handle; /* handle to directory */
61 CRITICAL_SECTION cs; /* crit section protecting this structure */
62 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
63 UNICODE_STRING mask; /* file mask */
64 UNICODE_STRING path; /* NT path used to open the directory */
65 BOOL is_root; /* is directory the root of the drive? */
66 UINT data_pos; /* current position in dir data */
67 UINT data_len; /* length of dir data */
68 BYTE data[8192]; /* directory data */
71 #define FIND_FIRST_MAGIC 0xc0ffee11
73 static BOOL oem_file_apis;
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 * Check if a dir symlink should be returned by FindNextFile.
120 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
123 ANSI_STRING unix_name;
124 struct stat st, parent_st;
128 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
129 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
130 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
131 len = info->path.Length / sizeof(WCHAR);
132 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
133 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
134 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
136 unix_name.Buffer = NULL;
137 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
138 !stat( unix_name.Buffer, &st ))
140 char *p = unix_name.Buffer + unix_name.Length - 1;
142 /* skip trailing slashes */
143 while (p > unix_name.Buffer && *p == '/') p--;
145 while (ret && p > unix_name.Buffer)
147 while (p > unix_name.Buffer && *p != '/') p--;
148 while (p > unix_name.Buffer && *p == '/') p--;
150 if (!stat( unix_name.Buffer, &parent_st ) &&
151 parent_st.st_dev == st.st_dev &&
152 parent_st.st_ino == st.st_ino)
154 WARN( "suppressing dir symlink %s pointing to parent %s\n",
155 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
156 debugstr_a( unix_name.Buffer ));
161 RtlFreeAnsiString( &unix_name );
162 RtlFreeUnicodeString( &str );
167 /***********************************************************************
170 * Set the DOS error code from errno.
172 void FILE_SetDosError(void)
174 int save_errno = errno; /* errno gets overwritten by printf */
176 TRACE("errno = %d %s\n", errno, strerror(errno));
180 SetLastError( ERROR_SHARING_VIOLATION );
183 SetLastError( ERROR_INVALID_HANDLE );
186 SetLastError( ERROR_HANDLE_DISK_FULL );
191 SetLastError( ERROR_ACCESS_DENIED );
194 SetLastError( ERROR_LOCK_VIOLATION );
197 SetLastError( ERROR_FILE_NOT_FOUND );
200 SetLastError( ERROR_CANNOT_MAKE );
204 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
207 SetLastError( ERROR_FILE_EXISTS );
211 SetLastError( ERROR_SEEK );
214 SetLastError( ERROR_DIR_NOT_EMPTY );
217 SetLastError( ERROR_BAD_FORMAT );
220 SetLastError( ERROR_PATH_NOT_FOUND );
223 SetLastError( ERROR_NOT_SAME_DEVICE );
226 WARN("unknown file error: %s\n", strerror(save_errno) );
227 SetLastError( ERROR_GEN_FAILURE );
234 /***********************************************************************
237 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
239 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
240 * there is no possibility for the function to do that twice, taking into
241 * account any called function.
243 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
246 UNICODE_STRING strW, *pstrW;
249 RtlInitAnsiString( &str, name );
250 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
252 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
254 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
255 if (status == STATUS_SUCCESS) return pstrW->Buffer;
257 if (status == STATUS_BUFFER_OVERFLOW)
258 SetLastError( ERROR_FILENAME_EXCED_RANGE );
260 SetLastError( RtlNtStatusToDosError(status) );
265 /***********************************************************************
268 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
270 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
274 if (srclen < 0) srclen = strlenW( src ) + 1;
276 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
278 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
283 /**************************************************************************
284 * SetFileApisToOEM (KERNEL32.@)
286 VOID WINAPI SetFileApisToOEM(void)
288 oem_file_apis = TRUE;
292 /**************************************************************************
293 * SetFileApisToANSI (KERNEL32.@)
295 VOID WINAPI SetFileApisToANSI(void)
297 oem_file_apis = FALSE;
301 /******************************************************************************
302 * AreFileApisANSI (KERNEL32.@)
304 * Determines if file functions are using ANSI
307 * TRUE: Set of file functions is using ANSI code page
308 * FALSE: Set of file functions is using OEM code page
310 BOOL WINAPI AreFileApisANSI(void)
312 return !oem_file_apis;
316 /**************************************************************************
317 * Operations on file handles *
318 **************************************************************************/
320 /***********************************************************************
321 * FILE_InitProcessDosHandles
323 * Allocates the default DOS handles for a process. Called either by
324 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
326 static void FILE_InitProcessDosHandles( void )
328 static BOOL init_done /* = FALSE */;
329 HANDLE cp = GetCurrentProcess();
331 if (init_done) return;
333 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
334 0, TRUE, DUPLICATE_SAME_ACCESS);
335 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
336 0, TRUE, DUPLICATE_SAME_ACCESS);
337 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
338 0, TRUE, DUPLICATE_SAME_ACCESS);
339 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
340 0, TRUE, DUPLICATE_SAME_ACCESS);
341 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
342 0, TRUE, DUPLICATE_SAME_ACCESS);
346 /******************************************************************
347 * FILE_ReadWriteApc (internal)
349 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
351 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
353 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
357 /***********************************************************************
358 * ReadFileEx (KERNEL32.@)
360 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
361 LPOVERLAPPED overlapped,
362 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
364 LARGE_INTEGER offset;
366 PIO_STATUS_BLOCK io_status;
368 TRACE("(hFile=%p, buffer=%p, bytes=%lu, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
372 SetLastError(ERROR_INVALID_PARAMETER);
376 offset.u.LowPart = overlapped->u.s.Offset;
377 offset.u.HighPart = overlapped->u.s.OffsetHigh;
378 io_status = (PIO_STATUS_BLOCK)overlapped;
379 io_status->u.Status = STATUS_PENDING;
381 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
382 io_status, buffer, bytesToRead, &offset, NULL);
386 SetLastError( RtlNtStatusToDosError(status) );
393 /***********************************************************************
394 * ReadFile (KERNEL32.@)
396 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
397 LPDWORD bytesRead, LPOVERLAPPED overlapped )
399 LARGE_INTEGER offset;
400 PLARGE_INTEGER poffset = NULL;
401 IO_STATUS_BLOCK iosb;
402 PIO_STATUS_BLOCK io_status = &iosb;
406 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
407 bytesRead, overlapped );
409 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
410 if (!bytesToRead) return TRUE;
412 if (is_console_handle(hFile))
413 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
415 if (overlapped != NULL)
417 offset.u.LowPart = overlapped->u.s.Offset;
418 offset.u.HighPart = overlapped->u.s.OffsetHigh;
420 hEvent = overlapped->hEvent;
421 io_status = (PIO_STATUS_BLOCK)overlapped;
423 io_status->u.Status = STATUS_PENDING;
424 io_status->Information = 0;
426 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
428 if (status != STATUS_PENDING && bytesRead)
429 *bytesRead = io_status->Information;
431 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
433 SetLastError( RtlNtStatusToDosError(status) );
440 /***********************************************************************
441 * WriteFileEx (KERNEL32.@)
443 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
444 LPOVERLAPPED overlapped,
445 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
447 LARGE_INTEGER offset;
449 PIO_STATUS_BLOCK io_status;
451 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
453 if (overlapped == NULL)
455 SetLastError(ERROR_INVALID_PARAMETER);
458 offset.u.LowPart = overlapped->u.s.Offset;
459 offset.u.HighPart = overlapped->u.s.OffsetHigh;
461 io_status = (PIO_STATUS_BLOCK)overlapped;
462 io_status->u.Status = STATUS_PENDING;
464 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
465 io_status, buffer, bytesToWrite, &offset, NULL);
467 if (status) SetLastError( RtlNtStatusToDosError(status) );
472 /***********************************************************************
473 * WriteFile (KERNEL32.@)
475 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
476 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
478 HANDLE hEvent = NULL;
479 LARGE_INTEGER offset;
480 PLARGE_INTEGER poffset = NULL;
482 IO_STATUS_BLOCK iosb;
483 PIO_STATUS_BLOCK piosb = &iosb;
485 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
487 if (is_console_handle(hFile))
488 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
492 offset.u.LowPart = overlapped->u.s.Offset;
493 offset.u.HighPart = overlapped->u.s.OffsetHigh;
495 hEvent = overlapped->hEvent;
496 piosb = (PIO_STATUS_BLOCK)overlapped;
498 piosb->u.Status = STATUS_PENDING;
499 piosb->Information = 0;
501 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
502 buffer, bytesToWrite, poffset, NULL);
504 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
505 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
507 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
508 buffer, bytesToWrite, poffset, NULL);
509 if (status != STATUS_INVALID_USER_BUFFER)
510 FIXME("Could not access memory (%p,%ld) at first, now OK. Protected by DIBSection code?\n",
511 buffer, bytesToWrite);
514 if (status != STATUS_PENDING && bytesWritten)
515 *bytesWritten = piosb->Information;
517 if (status && status != STATUS_TIMEOUT)
519 SetLastError( RtlNtStatusToDosError(status) );
526 /***********************************************************************
527 * GetOverlappedResult (KERNEL32.@)
529 * Check the result of an Asynchronous data transfer from a file.
532 * HANDLE hFile [in] handle of file to check on
533 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
534 * LPDWORD lpTransferred [in/out] number of bytes transferred
535 * BOOL bWait [in] wait for the transfer to complete ?
541 * If successful (and relevant) lpTransferred will hold the number of
542 * bytes transferred during the async operation.
546 * Currently only works for WaitCommEvent, ReadFile, WriteFile
547 * with communications ports.
550 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
551 LPDWORD lpTransferred, BOOL bWait)
553 DWORD r = WAIT_OBJECT_0;
555 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
557 if ( lpOverlapped == NULL )
559 ERR("lpOverlapped was null\n");
564 if ( lpOverlapped->hEvent )
568 TRACE( "waiting on %p\n", lpOverlapped );
569 r = WaitForSingleObjectEx( lpOverlapped->hEvent, INFINITE, TRUE );
570 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
571 } while ( r == WAIT_IO_COMPLETION );
576 while ( ((volatile OVERLAPPED*)lpOverlapped)->Internal == STATUS_PENDING )
580 else if ( lpOverlapped->Internal == STATUS_PENDING )
582 /* Wait in order to give APCs a chance to run. */
583 /* This is cheating, so we must set the event again in case of success -
584 it may be a non-manual reset event. */
587 TRACE( "waiting on %p\n", lpOverlapped );
588 r = WaitForSingleObjectEx( lpOverlapped->hEvent, 0, TRUE );
589 TRACE( "wait on %p returned %ld\n", lpOverlapped, r );
590 } while ( r == WAIT_IO_COMPLETION );
591 if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
592 NtSetEvent( lpOverlapped->hEvent, NULL );
594 if ( r == WAIT_FAILED )
596 WARN("wait operation failed\n");
599 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
601 switch ( lpOverlapped->Internal )
606 SetLastError( ERROR_IO_INCOMPLETE );
607 if ( bWait ) ERR("PENDING status after waiting!\n");
610 SetLastError( RtlNtStatusToDosError( lpOverlapped->Internal ) );
615 /***********************************************************************
616 * CancelIo (KERNEL32.@)
618 BOOL WINAPI CancelIo(HANDLE handle)
620 IO_STATUS_BLOCK io_status;
622 NtCancelIoFile(handle, &io_status);
623 if (io_status.u.Status)
625 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
631 /***********************************************************************
632 * _hread (KERNEL32.@)
634 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
636 return _lread( hFile, buffer, count );
640 /***********************************************************************
641 * _hwrite (KERNEL32.@)
643 * experimentation yields that _lwrite:
644 * o truncates the file at the current position with
646 * o returns 0 on a 0 length write
647 * o works with console handles
650 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
654 TRACE("%d %p %ld\n", handle, buffer, count );
658 /* Expand or truncate at current position */
659 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
662 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
668 /***********************************************************************
669 * _lclose (KERNEL32.@)
671 HFILE WINAPI _lclose( HFILE hFile )
673 TRACE("handle %d\n", hFile );
674 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
678 /***********************************************************************
679 * _lcreat (KERNEL32.@)
681 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
683 /* Mask off all flags not explicitly allowed by the doc */
684 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
685 TRACE("%s %02x\n", path, attr );
686 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
687 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
688 CREATE_ALWAYS, attr, 0 );
692 /***********************************************************************
693 * _lopen (KERNEL32.@)
695 HFILE WINAPI _lopen( LPCSTR path, INT mode )
697 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
698 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
701 /***********************************************************************
702 * _lread (KERNEL32.@)
704 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
707 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
713 /***********************************************************************
714 * _llseek (KERNEL32.@)
716 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
718 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
722 /***********************************************************************
723 * _lwrite (KERNEL32.@)
725 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
727 return (UINT)_hwrite( hFile, buffer, (LONG)count );
731 /***********************************************************************
732 * FlushFileBuffers (KERNEL32.@)
734 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
737 IO_STATUS_BLOCK ioblk;
739 if (is_console_handle( hFile ))
741 /* this will fail (as expected) for an output handle */
742 return FlushConsoleInputBuffer( hFile );
744 nts = NtFlushBuffersFile( hFile, &ioblk );
745 if (nts != STATUS_SUCCESS)
747 SetLastError( RtlNtStatusToDosError( nts ) );
755 /***********************************************************************
756 * GetFileType (KERNEL32.@)
758 DWORD WINAPI GetFileType( HANDLE hFile )
760 FILE_FS_DEVICE_INFORMATION info;
764 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
766 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
767 if (status != STATUS_SUCCESS)
769 SetLastError( RtlNtStatusToDosError(status) );
770 return FILE_TYPE_UNKNOWN;
773 switch(info.DeviceType)
775 case FILE_DEVICE_NULL:
776 case FILE_DEVICE_SERIAL_PORT:
777 case FILE_DEVICE_PARALLEL_PORT:
778 case FILE_DEVICE_UNKNOWN:
779 return FILE_TYPE_CHAR;
780 case FILE_DEVICE_NAMED_PIPE:
781 return FILE_TYPE_PIPE;
783 return FILE_TYPE_DISK;
788 /***********************************************************************
789 * GetFileInformationByHandle (KERNEL32.@)
791 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
793 FILE_ALL_INFORMATION all_info;
797 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
798 if (status == STATUS_SUCCESS)
800 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
801 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
802 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
803 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
804 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
805 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
806 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
807 info->dwVolumeSerialNumber = 0; /* FIXME */
808 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
809 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
810 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
811 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
812 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
815 SetLastError( RtlNtStatusToDosError(status) );
820 /***********************************************************************
821 * GetFileSize (KERNEL32.@)
823 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
826 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
827 if (filesizehigh) *filesizehigh = size.u.HighPart;
828 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
829 return size.u.LowPart;
833 /***********************************************************************
834 * GetFileSizeEx (KERNEL32.@)
836 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
838 FILE_END_OF_FILE_INFORMATION info;
842 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
843 if (status == STATUS_SUCCESS)
845 *lpFileSize = info.EndOfFile;
848 SetLastError( RtlNtStatusToDosError(status) );
853 /**************************************************************************
854 * SetEndOfFile (KERNEL32.@)
856 BOOL WINAPI SetEndOfFile( HANDLE hFile )
858 FILE_POSITION_INFORMATION pos;
859 FILE_END_OF_FILE_INFORMATION eof;
863 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
864 if (status == STATUS_SUCCESS)
866 eof.EndOfFile = pos.CurrentByteOffset;
867 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
869 if (status == STATUS_SUCCESS) return TRUE;
870 SetLastError( RtlNtStatusToDosError(status) );
875 /***********************************************************************
876 * SetFilePointer (KERNEL32.@)
878 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
880 LARGE_INTEGER dist, newpos;
884 dist.u.LowPart = distance;
885 dist.u.HighPart = *highword;
887 else dist.QuadPart = distance;
889 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
891 if (highword) *highword = newpos.u.HighPart;
892 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
893 return newpos.u.LowPart;
897 /***********************************************************************
898 * SetFilePointerEx (KERNEL32.@)
900 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
901 LARGE_INTEGER *newpos, DWORD method )
903 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
908 TRACE("handle %p offset %s newpos %p origin %ld\n",
909 hFile, wine_dbgstr_longlong(distance.QuadPart), newpos, method );
911 if (method > FILE_END)
913 SetLastError( ERROR_INVALID_PARAMETER );
917 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL )))
921 pos = distance.QuadPart;
922 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
924 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
925 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
926 SetLastError( ERROR_NEGATIVE_SEEK );
934 newpos->QuadPart = res;
936 wine_server_release_fd( hFile, fd );
938 else SetLastError( RtlNtStatusToDosError(status) );
943 /***********************************************************************
944 * GetFileTime (KERNEL32.@)
946 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
947 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
949 FILE_BASIC_INFORMATION info;
953 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
954 if (status == STATUS_SUCCESS)
958 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
959 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
961 if (lpLastAccessTime)
963 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
964 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
968 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
969 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
973 SetLastError( RtlNtStatusToDosError(status) );
978 /***********************************************************************
979 * SetFileTime (KERNEL32.@)
981 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
982 const FILETIME *atime, const FILETIME *mtime )
984 FILE_BASIC_INFORMATION info;
988 memset( &info, 0, sizeof(info) );
991 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
992 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
996 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
997 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1001 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1002 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1005 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1006 if (status == STATUS_SUCCESS) return TRUE;
1007 SetLastError( RtlNtStatusToDosError(status) );
1012 /**************************************************************************
1013 * LockFile (KERNEL32.@)
1015 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1016 DWORD count_low, DWORD count_high )
1019 LARGE_INTEGER count, offset;
1021 TRACE( "%p %lx%08lx %lx%08lx\n",
1022 hFile, offset_high, offset_low, count_high, count_low );
1024 count.u.LowPart = count_low;
1025 count.u.HighPart = count_high;
1026 offset.u.LowPart = offset_low;
1027 offset.u.HighPart = offset_high;
1029 status = NtLockFile( hFile, 0, NULL, NULL,
1030 NULL, &offset, &count, NULL, TRUE, TRUE );
1032 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1037 /**************************************************************************
1038 * LockFileEx [KERNEL32.@]
1040 * Locks a byte range within an open file for shared or exclusive access.
1047 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1049 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1050 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1053 LARGE_INTEGER count, offset;
1057 SetLastError( ERROR_INVALID_PARAMETER );
1061 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
1062 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1063 count_high, count_low, flags );
1065 count.u.LowPart = count_low;
1066 count.u.HighPart = count_high;
1067 offset.u.LowPart = overlapped->u.s.Offset;
1068 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1070 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1071 NULL, &offset, &count, NULL,
1072 flags & LOCKFILE_FAIL_IMMEDIATELY,
1073 flags & LOCKFILE_EXCLUSIVE_LOCK );
1075 if (status) SetLastError( RtlNtStatusToDosError(status) );
1080 /**************************************************************************
1081 * UnlockFile (KERNEL32.@)
1083 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1084 DWORD count_low, DWORD count_high )
1087 LARGE_INTEGER count, offset;
1089 count.u.LowPart = count_low;
1090 count.u.HighPart = count_high;
1091 offset.u.LowPart = offset_low;
1092 offset.u.HighPart = offset_high;
1094 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1095 if (status) SetLastError( RtlNtStatusToDosError(status) );
1100 /**************************************************************************
1101 * UnlockFileEx (KERNEL32.@)
1103 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1104 LPOVERLAPPED overlapped )
1108 SetLastError( ERROR_INVALID_PARAMETER );
1111 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1113 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1117 /***********************************************************************
1118 * Win32HandleToDosFileHandle (KERNEL32.21)
1120 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1121 * longer valid after this function (even on failure).
1123 * Note: this is not exactly right, since on Win95 the Win32 handles
1124 * are on top of DOS handles and we do it the other way
1125 * around. Should be good enough though.
1127 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1131 if (!handle || (handle == INVALID_HANDLE_VALUE))
1134 FILE_InitProcessDosHandles();
1135 for (i = 0; i < DOS_TABLE_SIZE; i++)
1136 if (!dos_handles[i])
1138 dos_handles[i] = handle;
1139 TRACE("Got %d for h32 %p\n", i, handle );
1142 CloseHandle( handle );
1143 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1148 /***********************************************************************
1149 * DosFileHandleToWin32Handle (KERNEL32.20)
1151 * Return the Win32 handle for a DOS handle.
1153 * Note: this is not exactly right, since on Win95 the Win32 handles
1154 * are on top of DOS handles and we do it the other way
1155 * around. Should be good enough though.
1157 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1159 HFILE16 hfile = (HFILE16)handle;
1160 if (hfile < 5) FILE_InitProcessDosHandles();
1161 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1163 SetLastError( ERROR_INVALID_HANDLE );
1164 return INVALID_HANDLE_VALUE;
1166 return dos_handles[hfile];
1170 /*************************************************************************
1171 * SetHandleCount (KERNEL32.@)
1173 UINT WINAPI SetHandleCount( UINT count )
1175 return min( 256, count );
1179 /***********************************************************************
1180 * DisposeLZ32Handle (KERNEL32.22)
1182 * Note: this is not entirely correct, we should only close the
1183 * 32-bit handle and not the 16-bit one, but we cannot do
1184 * this because of the way our DOS handles are implemented.
1185 * It shouldn't break anything though.
1187 void WINAPI DisposeLZ32Handle( HANDLE handle )
1191 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1193 for (i = 5; i < DOS_TABLE_SIZE; i++)
1194 if (dos_handles[i] == handle)
1197 CloseHandle( handle );
1202 /**************************************************************************
1203 * Operations on file names *
1204 **************************************************************************/
1207 /*************************************************************************
1208 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1210 * Creates or opens an object, and returns a handle that can be used to
1211 * access that object.
1215 * filename [in] pointer to filename to be accessed
1216 * access [in] access mode requested
1217 * sharing [in] share mode
1218 * sa [in] pointer to security attributes
1219 * creation [in] how to create the file
1220 * attributes [in] attributes for newly created file
1221 * template [in] handle to file with extended attributes to copy
1224 * Success: Open handle to specified file
1225 * Failure: INVALID_HANDLE_VALUE
1227 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1228 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1229 DWORD attributes, HANDLE template )
1233 OBJECT_ATTRIBUTES attr;
1234 UNICODE_STRING nameW;
1238 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1239 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1240 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1242 static const UINT nt_disposition[5] =
1244 FILE_CREATE, /* CREATE_NEW */
1245 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1246 FILE_OPEN, /* OPEN_EXISTING */
1247 FILE_OPEN_IF, /* OPEN_ALWAYS */
1248 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1254 if (!filename || !filename[0])
1256 SetLastError( ERROR_PATH_NOT_FOUND );
1257 return INVALID_HANDLE_VALUE;
1260 TRACE("%s %s%s%s%s%s%s creation %ld attributes 0x%lx\n", debugstr_w(filename),
1261 (access & GENERIC_READ)?"GENERIC_READ ":"",
1262 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1263 (!access)?"QUERY_ACCESS ":"",
1264 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1265 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1266 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1267 creation, attributes);
1269 /* Open a console for CONIN$ or CONOUT$ */
1271 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1273 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1277 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1279 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1280 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1282 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1283 !strncmpiW( filename + 4, pipeW, 5 ) ||
1284 !strncmpiW( filename + 4, mailslotW, 9 ))
1288 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1290 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1292 else if (!(GetVersion() & 0x80000000))
1296 else if (filename[4])
1298 ret = VXD_Open( filename+4, access, sa );
1303 SetLastError( ERROR_INVALID_NAME );
1304 return INVALID_HANDLE_VALUE;
1307 else dosdev = RtlIsDosDeviceName_U( filename );
1311 static const WCHAR conW[] = {'C','O','N'};
1313 if (LOWORD(dosdev) == sizeof(conW) &&
1314 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1316 switch (access & (GENERIC_READ|GENERIC_WRITE))
1319 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1322 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1325 SetLastError( ERROR_FILE_NOT_FOUND );
1326 return INVALID_HANDLE_VALUE;
1331 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1333 SetLastError( ERROR_INVALID_PARAMETER );
1334 return INVALID_HANDLE_VALUE;
1337 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1339 SetLastError( ERROR_PATH_NOT_FOUND );
1340 return INVALID_HANDLE_VALUE;
1343 /* now call NtCreateFile */
1346 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1347 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1349 options |= FILE_NON_DIRECTORY_FILE;
1350 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1351 options |= FILE_DELETE_ON_CLOSE;
1352 if (!(attributes & FILE_FLAG_OVERLAPPED))
1353 options |= FILE_SYNCHRONOUS_IO_ALERT;
1354 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1355 options |= FILE_RANDOM_ACCESS;
1356 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1358 attr.Length = sizeof(attr);
1359 attr.RootDirectory = 0;
1360 attr.Attributes = OBJ_CASE_INSENSITIVE;
1361 attr.ObjectName = &nameW;
1362 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1363 attr.SecurityQualityOfService = NULL;
1365 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1367 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1368 sharing, nt_disposition[creation - CREATE_NEW],
1372 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
1373 ret = INVALID_HANDLE_VALUE;
1375 /* In the case file creation was rejected due to CREATE_NEW flag
1376 * was specified and file with that name already exists, correct
1377 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1378 * Note: RtlNtStatusToDosError is not the subject to blame here.
1380 if (status == STATUS_OBJECT_NAME_COLLISION)
1381 SetLastError( ERROR_FILE_EXISTS );
1383 SetLastError( RtlNtStatusToDosError(status) );
1385 else SetLastError(0);
1386 RtlFreeUnicodeString( &nameW );
1389 if (!ret) ret = INVALID_HANDLE_VALUE;
1390 TRACE("returning %p\n", ret);
1396 /*************************************************************************
1397 * CreateFileA (KERNEL32.@)
1401 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1402 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1403 DWORD attributes, HANDLE template)
1407 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1408 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1412 /***********************************************************************
1413 * DeleteFileW (KERNEL32.@)
1415 BOOL WINAPI DeleteFileW( LPCWSTR path )
1417 UNICODE_STRING nameW;
1418 OBJECT_ATTRIBUTES attr;
1421 TRACE("%s\n", debugstr_w(path) );
1423 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1425 SetLastError( ERROR_PATH_NOT_FOUND );
1429 attr.Length = sizeof(attr);
1430 attr.RootDirectory = 0;
1431 attr.Attributes = OBJ_CASE_INSENSITIVE;
1432 attr.ObjectName = &nameW;
1433 attr.SecurityDescriptor = NULL;
1434 attr.SecurityQualityOfService = NULL;
1436 status = NtDeleteFile(&attr);
1437 RtlFreeUnicodeString( &nameW );
1440 SetLastError( RtlNtStatusToDosError(status) );
1447 /***********************************************************************
1448 * DeleteFileA (KERNEL32.@)
1450 BOOL WINAPI DeleteFileA( LPCSTR path )
1454 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1455 return DeleteFileW( pathW );
1459 /**************************************************************************
1460 * ReplaceFileW (KERNEL32.@)
1461 * ReplaceFile (KERNEL32.@)
1463 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1464 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1465 LPVOID lpExclude, LPVOID lpReserved)
1467 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1468 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1469 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1474 /**************************************************************************
1475 * ReplaceFileA (KERNEL32.@)
1477 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1478 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1479 LPVOID lpExclude, LPVOID lpReserved)
1481 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1482 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1483 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1488 /*************************************************************************
1489 * FindFirstFileExW (KERNEL32.@)
1491 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1492 LPVOID data, FINDEX_SEARCH_OPS search_op,
1493 LPVOID filter, DWORD flags)
1496 FIND_FIRST_INFO *info = NULL;
1497 UNICODE_STRING nt_name;
1498 OBJECT_ATTRIBUTES attr;
1502 TRACE("%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags);
1504 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1507 FIXME("options not implemented 0x%08x 0x%08lx\n", search_op, flags );
1508 return INVALID_HANDLE_VALUE;
1510 if (level != FindExInfoStandard)
1512 FIXME("info level %d not implemented\n", level );
1513 return INVALID_HANDLE_VALUE;
1516 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1518 SetLastError( ERROR_PATH_NOT_FOUND );
1519 return INVALID_HANDLE_VALUE;
1522 if (!mask || !*mask)
1524 SetLastError( ERROR_FILE_NOT_FOUND );
1528 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1530 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1534 if (!RtlCreateUnicodeString( &info->mask, mask ))
1536 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1540 /* truncate dir name before mask */
1542 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1544 /* check if path is the root of the drive */
1545 info->is_root = FALSE;
1546 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1547 if (p[0] && p[1] == ':')
1550 while (*p == '\\') p++;
1551 info->is_root = (*p == 0);
1554 attr.Length = sizeof(attr);
1555 attr.RootDirectory = 0;
1556 attr.Attributes = OBJ_CASE_INSENSITIVE;
1557 attr.ObjectName = &nt_name;
1558 attr.SecurityDescriptor = NULL;
1559 attr.SecurityQualityOfService = NULL;
1561 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1562 FILE_SHARE_READ | FILE_SHARE_WRITE,
1563 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1565 if (status != STATUS_SUCCESS)
1567 RtlFreeUnicodeString( &info->mask );
1568 SetLastError( RtlNtStatusToDosError(status) );
1572 RtlInitializeCriticalSection( &info->cs );
1573 info->path = nt_name;
1574 info->magic = FIND_FIRST_MAGIC;
1577 info->search_op = search_op;
1579 if (!FindNextFileW( (HANDLE)info, data ))
1581 TRACE( "%s not found\n", debugstr_w(filename) );
1582 FindClose( (HANDLE)info );
1583 SetLastError( ERROR_FILE_NOT_FOUND );
1584 return INVALID_HANDLE_VALUE;
1586 return (HANDLE)info;
1589 HeapFree( GetProcessHeap(), 0, info );
1590 RtlFreeUnicodeString( &nt_name );
1591 return INVALID_HANDLE_VALUE;
1595 /*************************************************************************
1596 * FindNextFileW (KERNEL32.@)
1598 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1600 FIND_FIRST_INFO *info;
1601 FILE_BOTH_DIR_INFORMATION *dir_info;
1604 TRACE("%p %p\n", handle, data);
1606 if (!handle || handle == INVALID_HANDLE_VALUE)
1608 SetLastError( ERROR_INVALID_HANDLE );
1611 info = (FIND_FIRST_INFO *)handle;
1612 if (info->magic != FIND_FIRST_MAGIC)
1614 SetLastError( ERROR_INVALID_HANDLE );
1618 RtlEnterCriticalSection( &info->cs );
1622 if (info->data_pos >= info->data_len) /* need to read some more data */
1626 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1627 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1630 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1633 info->data_len = io.Information;
1637 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1639 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1640 else info->data_pos = info->data_len;
1642 /* don't return '.' and '..' in the root of the drive */
1645 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1646 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1647 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1650 /* check for dir symlink */
1651 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1652 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
1654 if (!check_dir_symlink( info, dir_info )) continue;
1656 if (info->search_op == FindExSearchLimitToDirectories &&
1657 (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1660 data->dwFileAttributes = dir_info->FileAttributes;
1661 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1662 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1663 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1664 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1665 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1666 data->dwReserved0 = 0;
1667 data->dwReserved1 = 0;
1669 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1670 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1671 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1672 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1674 TRACE("returning %s (%s)\n",
1675 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1681 RtlLeaveCriticalSection( &info->cs );
1686 /*************************************************************************
1687 * FindClose (KERNEL32.@)
1689 BOOL WINAPI FindClose( HANDLE handle )
1691 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1693 if (!handle || handle == INVALID_HANDLE_VALUE)
1695 SetLastError( ERROR_INVALID_HANDLE );
1701 if (info->magic == FIND_FIRST_MAGIC)
1703 RtlEnterCriticalSection( &info->cs );
1704 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1707 if (info->handle) CloseHandle( info->handle );
1709 RtlFreeUnicodeString( &info->mask );
1710 info->mask.Buffer = NULL;
1711 RtlFreeUnicodeString( &info->path );
1714 RtlLeaveCriticalSection( &info->cs );
1715 RtlDeleteCriticalSection( &info->cs );
1716 HeapFree( GetProcessHeap(), 0, info );
1722 WARN("Illegal handle %p\n", handle);
1723 SetLastError( ERROR_INVALID_HANDLE );
1732 /*************************************************************************
1733 * FindFirstFileA (KERNEL32.@)
1735 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1737 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1738 FindExSearchNameMatch, NULL, 0);
1741 /*************************************************************************
1742 * FindFirstFileExA (KERNEL32.@)
1744 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1745 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1746 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1749 WIN32_FIND_DATAA *dataA;
1750 WIN32_FIND_DATAW dataW;
1753 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1755 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1756 if (handle == INVALID_HANDLE_VALUE) return handle;
1758 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1759 dataA->dwFileAttributes = dataW.dwFileAttributes;
1760 dataA->ftCreationTime = dataW.ftCreationTime;
1761 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1762 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1763 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1764 dataA->nFileSizeLow = dataW.nFileSizeLow;
1765 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1766 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1767 sizeof(dataA->cAlternateFileName) );
1772 /*************************************************************************
1773 * FindFirstFileW (KERNEL32.@)
1775 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1777 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1778 FindExSearchNameMatch, NULL, 0);
1782 /*************************************************************************
1783 * FindNextFileA (KERNEL32.@)
1785 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1787 WIN32_FIND_DATAW dataW;
1789 if (!FindNextFileW( handle, &dataW )) return FALSE;
1790 data->dwFileAttributes = dataW.dwFileAttributes;
1791 data->ftCreationTime = dataW.ftCreationTime;
1792 data->ftLastAccessTime = dataW.ftLastAccessTime;
1793 data->ftLastWriteTime = dataW.ftLastWriteTime;
1794 data->nFileSizeHigh = dataW.nFileSizeHigh;
1795 data->nFileSizeLow = dataW.nFileSizeLow;
1796 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1797 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1798 sizeof(data->cAlternateFileName) );
1803 /**************************************************************************
1804 * GetFileAttributesW (KERNEL32.@)
1806 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1808 FILE_BASIC_INFORMATION info;
1809 UNICODE_STRING nt_name;
1810 OBJECT_ATTRIBUTES attr;
1813 TRACE("%s\n", debugstr_w(name));
1815 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1817 SetLastError( ERROR_PATH_NOT_FOUND );
1818 return INVALID_FILE_ATTRIBUTES;
1821 attr.Length = sizeof(attr);
1822 attr.RootDirectory = 0;
1823 attr.Attributes = OBJ_CASE_INSENSITIVE;
1824 attr.ObjectName = &nt_name;
1825 attr.SecurityDescriptor = NULL;
1826 attr.SecurityQualityOfService = NULL;
1828 status = NtQueryAttributesFile( &attr, &info );
1829 RtlFreeUnicodeString( &nt_name );
1831 if (status == STATUS_SUCCESS) return info.FileAttributes;
1833 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1834 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1836 SetLastError( RtlNtStatusToDosError(status) );
1837 return INVALID_FILE_ATTRIBUTES;
1841 /**************************************************************************
1842 * GetFileAttributesA (KERNEL32.@)
1844 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1848 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1849 return GetFileAttributesW( nameW );
1853 /**************************************************************************
1854 * SetFileAttributesW (KERNEL32.@)
1856 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1858 UNICODE_STRING nt_name;
1859 OBJECT_ATTRIBUTES attr;
1864 TRACE("%s %lx\n", debugstr_w(name), attributes);
1866 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1868 SetLastError( ERROR_PATH_NOT_FOUND );
1872 attr.Length = sizeof(attr);
1873 attr.RootDirectory = 0;
1874 attr.Attributes = OBJ_CASE_INSENSITIVE;
1875 attr.ObjectName = &nt_name;
1876 attr.SecurityDescriptor = NULL;
1877 attr.SecurityQualityOfService = NULL;
1879 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1880 RtlFreeUnicodeString( &nt_name );
1882 if (status == STATUS_SUCCESS)
1884 FILE_BASIC_INFORMATION info;
1886 memset( &info, 0, sizeof(info) );
1887 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
1888 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
1892 if (status == STATUS_SUCCESS) return TRUE;
1893 SetLastError( RtlNtStatusToDosError(status) );
1898 /**************************************************************************
1899 * SetFileAttributesA (KERNEL32.@)
1901 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
1905 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1906 return SetFileAttributesW( nameW, attributes );
1910 /**************************************************************************
1911 * GetFileAttributesExW (KERNEL32.@)
1913 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1915 FILE_NETWORK_OPEN_INFORMATION info;
1916 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1917 UNICODE_STRING nt_name;
1918 OBJECT_ATTRIBUTES attr;
1921 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1923 if (level != GetFileExInfoStandard)
1925 SetLastError( ERROR_INVALID_PARAMETER );
1929 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1931 SetLastError( ERROR_PATH_NOT_FOUND );
1935 attr.Length = sizeof(attr);
1936 attr.RootDirectory = 0;
1937 attr.Attributes = OBJ_CASE_INSENSITIVE;
1938 attr.ObjectName = &nt_name;
1939 attr.SecurityDescriptor = NULL;
1940 attr.SecurityQualityOfService = NULL;
1942 status = NtQueryFullAttributesFile( &attr, &info );
1943 RtlFreeUnicodeString( &nt_name );
1945 if (status != STATUS_SUCCESS)
1947 SetLastError( RtlNtStatusToDosError(status) );
1951 data->dwFileAttributes = info.FileAttributes;
1952 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1953 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1954 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1955 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1956 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1957 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1958 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1959 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1964 /**************************************************************************
1965 * GetFileAttributesExA (KERNEL32.@)
1967 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
1971 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
1972 return GetFileAttributesExW( nameW, level, ptr );
1976 /******************************************************************************
1977 * GetCompressedFileSizeW (KERNEL32.@)
1979 * Get the actual number of bytes used on disk.
1982 * Success: Low-order doubleword of number of bytes
1983 * Failure: INVALID_FILE_SIZE
1985 DWORD WINAPI GetCompressedFileSizeW(
1986 LPCWSTR name, /* [in] Pointer to name of file */
1987 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
1989 UNICODE_STRING nt_name;
1990 OBJECT_ATTRIBUTES attr;
1994 DWORD ret = INVALID_FILE_SIZE;
1996 TRACE("%s %p\n", debugstr_w(name), size_high);
1998 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2000 SetLastError( ERROR_PATH_NOT_FOUND );
2001 return INVALID_FILE_SIZE;
2004 attr.Length = sizeof(attr);
2005 attr.RootDirectory = 0;
2006 attr.Attributes = OBJ_CASE_INSENSITIVE;
2007 attr.ObjectName = &nt_name;
2008 attr.SecurityDescriptor = NULL;
2009 attr.SecurityQualityOfService = NULL;
2011 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2012 RtlFreeUnicodeString( &nt_name );
2014 if (status == STATUS_SUCCESS)
2016 /* we don't support compressed files, simply return the file size */
2017 ret = GetFileSize( handle, size_high );
2020 else SetLastError( RtlNtStatusToDosError(status) );
2026 /******************************************************************************
2027 * GetCompressedFileSizeA (KERNEL32.@)
2029 * See GetCompressedFileSizeW.
2031 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2035 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2036 return GetCompressedFileSizeW( nameW, size_high );
2040 /***********************************************************************
2041 * OpenFile (KERNEL32.@)
2043 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2047 WORD filedatetime[2];
2049 if (!ofs) return HFILE_ERROR;
2051 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2052 ((mode & 0x3 )==OF_READ)?"OF_READ":
2053 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2054 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2055 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2056 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2057 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2058 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2059 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2060 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2061 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2062 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2063 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2064 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2065 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2066 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2067 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2068 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2072 ofs->cBytes = sizeof(OFSTRUCT);
2074 if (mode & OF_REOPEN) name = ofs->szPathName;
2076 if (!name) return HFILE_ERROR;
2078 TRACE("%s %04x\n", name, mode );
2080 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2081 Are there any cases where getting the path here is wrong?
2082 Uwe Bonnes 1997 Apr 2 */
2083 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2085 /* OF_PARSE simply fills the structure */
2087 if (mode & OF_PARSE)
2089 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2090 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2094 /* OF_CREATE is completely different from all other options, so
2097 if (mode & OF_CREATE)
2099 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2104 /* Now look for the file */
2106 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2109 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2111 if (mode & OF_DELETE)
2113 if (!DeleteFileA( ofs->szPathName )) goto error;
2114 TRACE("(%s): OF_DELETE return = OK\n", name);
2118 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2119 if (handle == INVALID_HANDLE_VALUE) goto error;
2121 GetFileTime( handle, NULL, NULL, &filetime );
2122 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2123 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2125 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2127 CloseHandle( handle );
2128 WARN("(%s): OF_VERIFY failed\n", name );
2129 /* FIXME: what error here? */
2130 SetLastError( ERROR_FILE_NOT_FOUND );
2134 ofs->Reserved1 = filedatetime[0];
2135 ofs->Reserved2 = filedatetime[1];
2137 TRACE("(%s): OK, return = %p\n", name, handle );
2138 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2140 CloseHandle( handle );
2143 else return (HFILE)handle;
2145 error: /* We get here if there was an error opening the file */
2146 ofs->nErrCode = GetLastError();
2147 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );