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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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"
51 WINE_DEFAULT_DEBUG_CHANNEL(file);
53 HANDLE dos_handles[DOS_TABLE_SIZE];
55 /* info structure for FindFirstFile handle */
58 DWORD magic; /* magic number */
59 HANDLE handle; /* handle to directory */
60 CRITICAL_SECTION cs; /* crit section protecting this structure */
61 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
62 UNICODE_STRING mask; /* file mask */
63 UNICODE_STRING path; /* NT path used to open the directory */
64 BOOL is_root; /* is directory the root of the drive? */
65 UINT data_pos; /* current position in dir data */
66 UINT data_len; /* length of dir data */
67 BYTE data[8192]; /* directory data */
70 #define FIND_FIRST_MAGIC 0xc0ffee11
72 static BOOL oem_file_apis;
75 /***********************************************************************
78 * Wrapper for CreateFile that takes OF_* mode flags.
80 static HANDLE create_file_OF( LPCSTR path, INT mode )
82 DWORD access, sharing, creation;
86 creation = CREATE_ALWAYS;
87 access = GENERIC_READ | GENERIC_WRITE;
91 creation = OPEN_EXISTING;
94 case OF_READ: access = GENERIC_READ; break;
95 case OF_WRITE: access = GENERIC_WRITE; break;
96 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
97 default: access = 0; break;
103 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
104 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
105 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
106 case OF_SHARE_DENY_NONE:
107 case OF_SHARE_COMPAT:
108 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
110 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
114 /***********************************************************************
117 * Check if a dir symlink should be returned by FindNextFile.
119 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
122 ANSI_STRING unix_name;
123 struct stat st, parent_st;
127 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
128 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
129 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
130 len = info->path.Length / sizeof(WCHAR);
131 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
132 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
133 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
135 unix_name.Buffer = NULL;
136 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
137 !stat( unix_name.Buffer, &st ))
139 char *p = unix_name.Buffer + unix_name.Length - 1;
141 /* skip trailing slashes */
142 while (p > unix_name.Buffer && *p == '/') p--;
144 while (ret && p > unix_name.Buffer)
146 while (p > unix_name.Buffer && *p != '/') p--;
147 while (p > unix_name.Buffer && *p == '/') p--;
149 if (!stat( unix_name.Buffer, &parent_st ) &&
150 parent_st.st_dev == st.st_dev &&
151 parent_st.st_ino == st.st_ino)
153 WARN( "suppressing dir symlink %s pointing to parent %s\n",
154 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
155 debugstr_a( unix_name.Buffer ));
160 RtlFreeAnsiString( &unix_name );
161 RtlFreeUnicodeString( &str );
166 /***********************************************************************
169 * Set the DOS error code from errno.
171 void FILE_SetDosError(void)
173 int save_errno = errno; /* errno gets overwritten by printf */
175 TRACE("errno = %d %s\n", errno, strerror(errno));
179 SetLastError( ERROR_SHARING_VIOLATION );
182 SetLastError( ERROR_INVALID_HANDLE );
185 SetLastError( ERROR_HANDLE_DISK_FULL );
190 SetLastError( ERROR_ACCESS_DENIED );
193 SetLastError( ERROR_LOCK_VIOLATION );
196 SetLastError( ERROR_FILE_NOT_FOUND );
199 SetLastError( ERROR_CANNOT_MAKE );
203 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
206 SetLastError( ERROR_FILE_EXISTS );
210 SetLastError( ERROR_SEEK );
213 SetLastError( ERROR_DIR_NOT_EMPTY );
216 SetLastError( ERROR_BAD_FORMAT );
219 SetLastError( ERROR_PATH_NOT_FOUND );
222 SetLastError( ERROR_NOT_SAME_DEVICE );
225 WARN("unknown file error: %s\n", strerror(save_errno) );
226 SetLastError( ERROR_GEN_FAILURE );
233 /***********************************************************************
236 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
238 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
239 * there is no possibility for the function to do that twice, taking into
240 * account any called function.
242 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
245 UNICODE_STRING strW, *pstrW;
248 RtlInitAnsiString( &str, name );
249 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
251 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
253 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
254 if (status == STATUS_SUCCESS) return pstrW->Buffer;
256 if (status == STATUS_BUFFER_OVERFLOW)
257 SetLastError( ERROR_FILENAME_EXCED_RANGE );
259 SetLastError( RtlNtStatusToDosError(status) );
264 /***********************************************************************
267 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
269 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
273 if (srclen < 0) srclen = strlenW( src ) + 1;
275 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
277 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
282 /**************************************************************************
283 * SetFileApisToOEM (KERNEL32.@)
285 VOID WINAPI SetFileApisToOEM(void)
287 oem_file_apis = TRUE;
291 /**************************************************************************
292 * SetFileApisToANSI (KERNEL32.@)
294 VOID WINAPI SetFileApisToANSI(void)
296 oem_file_apis = FALSE;
300 /******************************************************************************
301 * AreFileApisANSI (KERNEL32.@)
303 * Determines if file functions are using ANSI
306 * TRUE: Set of file functions is using ANSI code page
307 * FALSE: Set of file functions is using OEM code page
309 BOOL WINAPI AreFileApisANSI(void)
311 return !oem_file_apis;
315 /**************************************************************************
316 * Operations on file handles *
317 **************************************************************************/
319 /***********************************************************************
320 * FILE_InitProcessDosHandles
322 * Allocates the default DOS handles for a process. Called either by
323 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
325 static void FILE_InitProcessDosHandles( void )
327 static BOOL init_done /* = FALSE */;
328 HANDLE cp = GetCurrentProcess();
330 if (init_done) return;
332 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
333 0, TRUE, DUPLICATE_SAME_ACCESS);
334 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
335 0, TRUE, DUPLICATE_SAME_ACCESS);
336 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
337 0, TRUE, DUPLICATE_SAME_ACCESS);
338 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
339 0, TRUE, DUPLICATE_SAME_ACCESS);
340 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
341 0, TRUE, DUPLICATE_SAME_ACCESS);
345 /******************************************************************
346 * FILE_ReadWriteApc (internal)
348 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
350 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
352 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
356 /***********************************************************************
357 * ReadFileEx (KERNEL32.@)
359 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
360 LPOVERLAPPED overlapped,
361 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
363 LARGE_INTEGER offset;
365 PIO_STATUS_BLOCK io_status;
367 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
371 SetLastError(ERROR_INVALID_PARAMETER);
375 offset.u.LowPart = overlapped->u.s.Offset;
376 offset.u.HighPart = overlapped->u.s.OffsetHigh;
377 io_status = (PIO_STATUS_BLOCK)overlapped;
378 io_status->u.Status = STATUS_PENDING;
380 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
381 io_status, buffer, bytesToRead, &offset, NULL);
385 SetLastError( RtlNtStatusToDosError(status) );
392 /***********************************************************************
393 * ReadFile (KERNEL32.@)
395 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
396 LPDWORD bytesRead, LPOVERLAPPED overlapped )
398 LARGE_INTEGER offset;
399 PLARGE_INTEGER poffset = NULL;
400 IO_STATUS_BLOCK iosb;
401 PIO_STATUS_BLOCK io_status = &iosb;
405 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
406 bytesRead, overlapped );
408 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
409 if (!bytesToRead) return TRUE;
411 if (is_console_handle(hFile))
412 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
414 if (overlapped != NULL)
416 offset.u.LowPart = overlapped->u.s.Offset;
417 offset.u.HighPart = overlapped->u.s.OffsetHigh;
419 hEvent = overlapped->hEvent;
420 io_status = (PIO_STATUS_BLOCK)overlapped;
422 io_status->u.Status = STATUS_PENDING;
423 io_status->Information = 0;
425 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
427 if (status != STATUS_PENDING && bytesRead)
428 *bytesRead = io_status->Information;
430 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
432 SetLastError( RtlNtStatusToDosError(status) );
439 /***********************************************************************
440 * WriteFileEx (KERNEL32.@)
442 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
443 LPOVERLAPPED overlapped,
444 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
446 LARGE_INTEGER offset;
448 PIO_STATUS_BLOCK io_status;
450 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
452 if (overlapped == NULL)
454 SetLastError(ERROR_INVALID_PARAMETER);
457 offset.u.LowPart = overlapped->u.s.Offset;
458 offset.u.HighPart = overlapped->u.s.OffsetHigh;
460 io_status = (PIO_STATUS_BLOCK)overlapped;
461 io_status->u.Status = STATUS_PENDING;
463 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
464 io_status, buffer, bytesToWrite, &offset, NULL);
466 if (status) SetLastError( RtlNtStatusToDosError(status) );
471 /***********************************************************************
472 * WriteFile (KERNEL32.@)
474 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
475 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
477 HANDLE hEvent = NULL;
478 LARGE_INTEGER offset;
479 PLARGE_INTEGER poffset = NULL;
481 IO_STATUS_BLOCK iosb;
482 PIO_STATUS_BLOCK piosb = &iosb;
484 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
486 if (is_console_handle(hFile))
487 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
491 offset.u.LowPart = overlapped->u.s.Offset;
492 offset.u.HighPart = overlapped->u.s.OffsetHigh;
494 hEvent = overlapped->hEvent;
495 piosb = (PIO_STATUS_BLOCK)overlapped;
497 piosb->u.Status = STATUS_PENDING;
498 piosb->Information = 0;
500 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
501 buffer, bytesToWrite, poffset, NULL);
503 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
504 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
506 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
507 buffer, bytesToWrite, poffset, NULL);
508 if (status != STATUS_INVALID_USER_BUFFER)
509 FIXME("Could not access memory (%p,%d) at first, now OK. Protected by DIBSection code?\n",
510 buffer, bytesToWrite);
513 if (status != STATUS_PENDING && bytesWritten)
514 *bytesWritten = piosb->Information;
516 if (status && status != STATUS_TIMEOUT)
518 SetLastError( RtlNtStatusToDosError(status) );
525 /***********************************************************************
526 * GetOverlappedResult (KERNEL32.@)
528 * Check the result of an Asynchronous data transfer from a file.
531 * HANDLE hFile [in] handle of file to check on
532 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
533 * LPDWORD lpTransferred [in/out] number of bytes transferred
534 * BOOL bWait [in] wait for the transfer to complete ?
540 * If successful (and relevant) lpTransferred will hold the number of
541 * bytes transferred during the async operation.
545 * Currently only works for WaitCommEvent, ReadFile, WriteFile
546 * with communications ports.
549 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
550 LPDWORD lpTransferred, BOOL bWait)
552 DWORD r = WAIT_OBJECT_0;
554 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
556 if ( lpOverlapped == NULL )
558 ERR("lpOverlapped was null\n");
563 if ( lpOverlapped->hEvent )
567 TRACE( "waiting on %p\n", lpOverlapped );
568 r = WaitForSingleObjectEx( lpOverlapped->hEvent, INFINITE, TRUE );
569 TRACE( "wait on %p returned %d\n", lpOverlapped, r );
570 } while ( r == WAIT_IO_COMPLETION );
575 while ( ((volatile OVERLAPPED*)lpOverlapped)->Internal == STATUS_PENDING )
579 else if ( lpOverlapped->Internal == STATUS_PENDING )
581 /* Wait in order to give APCs a chance to run. */
582 /* This is cheating, so we must set the event again in case of success -
583 it may be a non-manual reset event. */
586 TRACE( "waiting on %p\n", lpOverlapped );
587 r = WaitForSingleObjectEx( lpOverlapped->hEvent, 0, TRUE );
588 TRACE( "wait on %p returned %d\n", lpOverlapped, r );
589 } while ( r == WAIT_IO_COMPLETION );
590 if ( r == WAIT_OBJECT_0 && lpOverlapped->hEvent )
591 NtSetEvent( lpOverlapped->hEvent, NULL );
593 if ( r == WAIT_FAILED )
595 WARN("wait operation failed\n");
598 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
600 switch ( lpOverlapped->Internal )
605 SetLastError( ERROR_IO_INCOMPLETE );
606 if ( bWait ) ERR("PENDING status after waiting!\n");
609 SetLastError( RtlNtStatusToDosError( lpOverlapped->Internal ) );
614 /***********************************************************************
615 * CancelIo (KERNEL32.@)
617 * Cancels pending I/O operations initiated by the current thread on a file.
620 * handle [I] File handle.
624 * Failure: FALSE, check GetLastError().
626 BOOL WINAPI CancelIo(HANDLE handle)
628 IO_STATUS_BLOCK io_status;
630 NtCancelIoFile(handle, &io_status);
631 if (io_status.u.Status)
633 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
639 /***********************************************************************
640 * _hread (KERNEL32.@)
642 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
644 return _lread( hFile, buffer, count );
648 /***********************************************************************
649 * _hwrite (KERNEL32.@)
651 * experimentation yields that _lwrite:
652 * o truncates the file at the current position with
654 * o returns 0 on a 0 length write
655 * o works with console handles
658 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
662 TRACE("%d %p %d\n", handle, buffer, count );
666 /* Expand or truncate at current position */
667 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
670 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
676 /***********************************************************************
677 * _lclose (KERNEL32.@)
679 HFILE WINAPI _lclose( HFILE hFile )
681 TRACE("handle %d\n", hFile );
682 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
686 /***********************************************************************
687 * _lcreat (KERNEL32.@)
689 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
691 /* Mask off all flags not explicitly allowed by the doc */
692 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
693 TRACE("%s %02x\n", path, attr );
694 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
695 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
696 CREATE_ALWAYS, attr, 0 );
700 /***********************************************************************
701 * _lopen (KERNEL32.@)
703 HFILE WINAPI _lopen( LPCSTR path, INT mode )
705 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
706 return (HFILE)create_file_OF( path, mode & ~OF_CREATE );
709 /***********************************************************************
710 * _lread (KERNEL32.@)
712 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
715 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL ))
721 /***********************************************************************
722 * _llseek (KERNEL32.@)
724 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
726 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
730 /***********************************************************************
731 * _lwrite (KERNEL32.@)
733 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
735 return (UINT)_hwrite( hFile, buffer, (LONG)count );
739 /***********************************************************************
740 * FlushFileBuffers (KERNEL32.@)
742 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
745 IO_STATUS_BLOCK ioblk;
747 if (is_console_handle( hFile ))
749 /* this will fail (as expected) for an output handle */
750 return FlushConsoleInputBuffer( hFile );
752 nts = NtFlushBuffersFile( hFile, &ioblk );
753 if (nts != STATUS_SUCCESS)
755 SetLastError( RtlNtStatusToDosError( nts ) );
763 /***********************************************************************
764 * GetFileType (KERNEL32.@)
766 DWORD WINAPI GetFileType( HANDLE hFile )
768 FILE_FS_DEVICE_INFORMATION info;
772 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
774 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
775 if (status != STATUS_SUCCESS)
777 SetLastError( RtlNtStatusToDosError(status) );
778 return FILE_TYPE_UNKNOWN;
781 switch(info.DeviceType)
783 case FILE_DEVICE_NULL:
784 case FILE_DEVICE_SERIAL_PORT:
785 case FILE_DEVICE_PARALLEL_PORT:
786 case FILE_DEVICE_TAPE:
787 case FILE_DEVICE_UNKNOWN:
788 return FILE_TYPE_CHAR;
789 case FILE_DEVICE_NAMED_PIPE:
790 return FILE_TYPE_PIPE;
792 return FILE_TYPE_DISK;
797 /***********************************************************************
798 * GetFileInformationByHandle (KERNEL32.@)
800 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
802 FILE_ALL_INFORMATION all_info;
806 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
807 if (status == STATUS_SUCCESS)
809 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
810 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
811 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
812 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
813 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
814 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
815 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
816 info->dwVolumeSerialNumber = 0; /* FIXME */
817 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
818 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
819 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
820 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
821 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
824 SetLastError( RtlNtStatusToDosError(status) );
829 /***********************************************************************
830 * GetFileSize (KERNEL32.@)
832 * Retrieve the size of a file.
835 * hFile [I] File to retrieve size of.
836 * filesizehigh [O] On return, the high bits of the file size.
839 * Success: The low bits of the file size.
840 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
841 * check GetLastError() for values other than ERROR_SUCCESS.
843 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
846 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
847 if (filesizehigh) *filesizehigh = size.u.HighPart;
848 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
849 return size.u.LowPart;
853 /***********************************************************************
854 * GetFileSizeEx (KERNEL32.@)
856 * Retrieve the size of a file.
859 * hFile [I] File to retrieve size of.
860 * lpFileSIze [O] On return, the size of the file.
864 * Failure: FALSE, check GetLastError().
866 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
868 FILE_END_OF_FILE_INFORMATION info;
872 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
873 if (status == STATUS_SUCCESS)
875 *lpFileSize = info.EndOfFile;
878 SetLastError( RtlNtStatusToDosError(status) );
883 /**************************************************************************
884 * SetEndOfFile (KERNEL32.@)
886 * Sets the current position as the end of the file.
889 * hFile [I] File handle.
893 * Failure: FALSE, check GetLastError().
895 BOOL WINAPI SetEndOfFile( HANDLE hFile )
897 FILE_POSITION_INFORMATION pos;
898 FILE_END_OF_FILE_INFORMATION eof;
902 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
903 if (status == STATUS_SUCCESS)
905 eof.EndOfFile = pos.CurrentByteOffset;
906 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
908 if (status == STATUS_SUCCESS) return TRUE;
909 SetLastError( RtlNtStatusToDosError(status) );
914 /***********************************************************************
915 * SetFilePointer (KERNEL32.@)
917 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
919 LARGE_INTEGER dist, newpos;
923 dist.u.LowPart = distance;
924 dist.u.HighPart = *highword;
926 else dist.QuadPart = distance;
928 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
930 if (highword) *highword = newpos.u.HighPart;
931 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
932 return newpos.u.LowPart;
936 /***********************************************************************
937 * SetFilePointerEx (KERNEL32.@)
939 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
940 LARGE_INTEGER *newpos, DWORD method )
944 FILE_POSITION_INFORMATION info;
949 pos = distance.QuadPart;
952 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
954 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
958 FILE_END_OF_FILE_INFORMATION eof;
959 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
961 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
965 SetLastError( ERROR_INVALID_PARAMETER );
971 SetLastError( ERROR_NEGATIVE_SEEK );
975 info.CurrentByteOffset.QuadPart = pos;
976 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
978 if (newpos) newpos->QuadPart = pos;
982 SetLastError( RtlNtStatusToDosError(io.u.Status) );
986 /***********************************************************************
987 * GetFileTime (KERNEL32.@)
989 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
990 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
992 FILE_BASIC_INFORMATION info;
996 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
997 if (status == STATUS_SUCCESS)
1001 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1002 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1004 if (lpLastAccessTime)
1006 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1007 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1009 if (lpLastWriteTime)
1011 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1012 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1016 SetLastError( RtlNtStatusToDosError(status) );
1021 /***********************************************************************
1022 * SetFileTime (KERNEL32.@)
1024 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1025 const FILETIME *atime, const FILETIME *mtime )
1027 FILE_BASIC_INFORMATION info;
1031 memset( &info, 0, sizeof(info) );
1034 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1035 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1039 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1040 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1044 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1045 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1048 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1049 if (status == STATUS_SUCCESS) return TRUE;
1050 SetLastError( RtlNtStatusToDosError(status) );
1055 /**************************************************************************
1056 * LockFile (KERNEL32.@)
1058 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1059 DWORD count_low, DWORD count_high )
1062 LARGE_INTEGER count, offset;
1064 TRACE( "%p %x%08x %x%08x\n",
1065 hFile, offset_high, offset_low, count_high, count_low );
1067 count.u.LowPart = count_low;
1068 count.u.HighPart = count_high;
1069 offset.u.LowPart = offset_low;
1070 offset.u.HighPart = offset_high;
1072 status = NtLockFile( hFile, 0, NULL, NULL,
1073 NULL, &offset, &count, NULL, TRUE, TRUE );
1075 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1080 /**************************************************************************
1081 * LockFileEx [KERNEL32.@]
1083 * Locks a byte range within an open file for shared or exclusive access.
1090 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1092 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1093 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1096 LARGE_INTEGER count, offset;
1100 SetLastError( ERROR_INVALID_PARAMETER );
1104 TRACE( "%p %x%08x %x%08x flags %x\n",
1105 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1106 count_high, count_low, flags );
1108 count.u.LowPart = count_low;
1109 count.u.HighPart = count_high;
1110 offset.u.LowPart = overlapped->u.s.Offset;
1111 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1113 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1114 NULL, &offset, &count, NULL,
1115 flags & LOCKFILE_FAIL_IMMEDIATELY,
1116 flags & LOCKFILE_EXCLUSIVE_LOCK );
1118 if (status) SetLastError( RtlNtStatusToDosError(status) );
1123 /**************************************************************************
1124 * UnlockFile (KERNEL32.@)
1126 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1127 DWORD count_low, DWORD count_high )
1130 LARGE_INTEGER count, offset;
1132 count.u.LowPart = count_low;
1133 count.u.HighPart = count_high;
1134 offset.u.LowPart = offset_low;
1135 offset.u.HighPart = offset_high;
1137 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1138 if (status) SetLastError( RtlNtStatusToDosError(status) );
1143 /**************************************************************************
1144 * UnlockFileEx (KERNEL32.@)
1146 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1147 LPOVERLAPPED overlapped )
1151 SetLastError( ERROR_INVALID_PARAMETER );
1154 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1156 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1160 /***********************************************************************
1161 * Win32HandleToDosFileHandle (KERNEL32.21)
1163 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1164 * longer valid after this function (even on failure).
1166 * Note: this is not exactly right, since on Win95 the Win32 handles
1167 * are on top of DOS handles and we do it the other way
1168 * around. Should be good enough though.
1170 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1174 if (!handle || (handle == INVALID_HANDLE_VALUE))
1177 FILE_InitProcessDosHandles();
1178 for (i = 0; i < DOS_TABLE_SIZE; i++)
1179 if (!dos_handles[i])
1181 dos_handles[i] = handle;
1182 TRACE("Got %d for h32 %p\n", i, handle );
1185 CloseHandle( handle );
1186 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1191 /***********************************************************************
1192 * DosFileHandleToWin32Handle (KERNEL32.20)
1194 * Return the Win32 handle for a DOS handle.
1196 * Note: this is not exactly right, since on Win95 the Win32 handles
1197 * are on top of DOS handles and we do it the other way
1198 * around. Should be good enough though.
1200 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1202 HFILE16 hfile = (HFILE16)handle;
1203 if (hfile < 5) FILE_InitProcessDosHandles();
1204 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1206 SetLastError( ERROR_INVALID_HANDLE );
1207 return INVALID_HANDLE_VALUE;
1209 return dos_handles[hfile];
1213 /*************************************************************************
1214 * SetHandleCount (KERNEL32.@)
1216 UINT WINAPI SetHandleCount( UINT count )
1218 return min( 256, count );
1222 /***********************************************************************
1223 * DisposeLZ32Handle (KERNEL32.22)
1225 * Note: this is not entirely correct, we should only close the
1226 * 32-bit handle and not the 16-bit one, but we cannot do
1227 * this because of the way our DOS handles are implemented.
1228 * It shouldn't break anything though.
1230 void WINAPI DisposeLZ32Handle( HANDLE handle )
1234 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1236 for (i = 5; i < DOS_TABLE_SIZE; i++)
1237 if (dos_handles[i] == handle)
1240 CloseHandle( handle );
1245 /**************************************************************************
1246 * Operations on file names *
1247 **************************************************************************/
1250 /*************************************************************************
1251 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1253 * Creates or opens an object, and returns a handle that can be used to
1254 * access that object.
1258 * filename [in] pointer to filename to be accessed
1259 * access [in] access mode requested
1260 * sharing [in] share mode
1261 * sa [in] pointer to security attributes
1262 * creation [in] how to create the file
1263 * attributes [in] attributes for newly created file
1264 * template [in] handle to file with extended attributes to copy
1267 * Success: Open handle to specified file
1268 * Failure: INVALID_HANDLE_VALUE
1270 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1271 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1272 DWORD attributes, HANDLE template )
1276 OBJECT_ATTRIBUTES attr;
1277 UNICODE_STRING nameW;
1281 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1282 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1283 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1285 static const UINT nt_disposition[5] =
1287 FILE_CREATE, /* CREATE_NEW */
1288 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1289 FILE_OPEN, /* OPEN_EXISTING */
1290 FILE_OPEN_IF, /* OPEN_ALWAYS */
1291 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1297 if (!filename || !filename[0])
1299 SetLastError( ERROR_PATH_NOT_FOUND );
1300 return INVALID_HANDLE_VALUE;
1303 TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1304 (access & GENERIC_READ)?"GENERIC_READ ":"",
1305 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1306 (!access)?"QUERY_ACCESS ":"",
1307 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1308 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1309 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1310 creation, attributes);
1312 /* Open a console for CONIN$ or CONOUT$ */
1314 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1316 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1320 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1322 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1323 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1325 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1326 !strncmpiW( filename + 4, pipeW, 5 ) ||
1327 !strncmpiW( filename + 4, mailslotW, 9 ))
1331 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1333 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1335 else if (!(GetVersion() & 0x80000000))
1339 else if (filename[4])
1341 ret = VXD_Open( filename+4, access, sa );
1346 SetLastError( ERROR_INVALID_NAME );
1347 return INVALID_HANDLE_VALUE;
1350 else dosdev = RtlIsDosDeviceName_U( filename );
1354 static const WCHAR conW[] = {'C','O','N'};
1356 if (LOWORD(dosdev) == sizeof(conW) &&
1357 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1359 switch (access & (GENERIC_READ|GENERIC_WRITE))
1362 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1365 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1368 SetLastError( ERROR_FILE_NOT_FOUND );
1369 return INVALID_HANDLE_VALUE;
1374 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1376 SetLastError( ERROR_INVALID_PARAMETER );
1377 return INVALID_HANDLE_VALUE;
1380 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1382 SetLastError( ERROR_PATH_NOT_FOUND );
1383 return INVALID_HANDLE_VALUE;
1386 /* now call NtCreateFile */
1389 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1390 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1392 options |= FILE_NON_DIRECTORY_FILE;
1393 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1395 options |= FILE_DELETE_ON_CLOSE;
1398 if (!(attributes & FILE_FLAG_OVERLAPPED))
1399 options |= FILE_SYNCHRONOUS_IO_ALERT;
1400 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1401 options |= FILE_RANDOM_ACCESS;
1402 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1404 attr.Length = sizeof(attr);
1405 attr.RootDirectory = 0;
1406 attr.Attributes = OBJ_CASE_INSENSITIVE;
1407 attr.ObjectName = &nameW;
1408 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1409 attr.SecurityQualityOfService = NULL;
1411 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1413 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1414 sharing, nt_disposition[creation - CREATE_NEW],
1418 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1419 ret = INVALID_HANDLE_VALUE;
1421 /* In the case file creation was rejected due to CREATE_NEW flag
1422 * was specified and file with that name already exists, correct
1423 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1424 * Note: RtlNtStatusToDosError is not the subject to blame here.
1426 if (status == STATUS_OBJECT_NAME_COLLISION)
1427 SetLastError( ERROR_FILE_EXISTS );
1429 SetLastError( RtlNtStatusToDosError(status) );
1431 else SetLastError(0);
1432 RtlFreeUnicodeString( &nameW );
1435 if (!ret) ret = INVALID_HANDLE_VALUE;
1436 TRACE("returning %p\n", ret);
1442 /*************************************************************************
1443 * CreateFileA (KERNEL32.@)
1447 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1448 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1449 DWORD attributes, HANDLE template)
1453 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1454 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1458 /***********************************************************************
1459 * DeleteFileW (KERNEL32.@)
1464 * path [I] Path to the file to delete.
1468 * Failure: FALSE, check GetLastError().
1470 BOOL WINAPI DeleteFileW( LPCWSTR path )
1472 UNICODE_STRING nameW;
1473 OBJECT_ATTRIBUTES attr;
1476 TRACE("%s\n", debugstr_w(path) );
1478 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1480 SetLastError( ERROR_PATH_NOT_FOUND );
1484 attr.Length = sizeof(attr);
1485 attr.RootDirectory = 0;
1486 attr.Attributes = OBJ_CASE_INSENSITIVE;
1487 attr.ObjectName = &nameW;
1488 attr.SecurityDescriptor = NULL;
1489 attr.SecurityQualityOfService = NULL;
1491 status = NtDeleteFile(&attr);
1492 RtlFreeUnicodeString( &nameW );
1495 SetLastError( RtlNtStatusToDosError(status) );
1502 /***********************************************************************
1503 * DeleteFileA (KERNEL32.@)
1507 BOOL WINAPI DeleteFileA( LPCSTR path )
1511 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1512 return DeleteFileW( pathW );
1516 /**************************************************************************
1517 * ReplaceFileW (KERNEL32.@)
1518 * ReplaceFile (KERNEL32.@)
1520 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1521 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1522 LPVOID lpExclude, LPVOID lpReserved)
1524 FIXME("(%s,%s,%s,%08x,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1525 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1526 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1531 /**************************************************************************
1532 * ReplaceFileA (KERNEL32.@)
1534 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1535 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1536 LPVOID lpExclude, LPVOID lpReserved)
1538 FIXME("(%s,%s,%s,%08x,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1539 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1540 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1545 /*************************************************************************
1546 * FindFirstFileExW (KERNEL32.@)
1548 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1549 LPVOID data, FINDEX_SEARCH_OPS search_op,
1550 LPVOID filter, DWORD flags)
1552 static const WCHAR wildcardsW[] = { '*','?',0 };
1554 FIND_FIRST_INFO *info = NULL;
1555 UNICODE_STRING nt_name;
1556 OBJECT_ATTRIBUTES attr;
1561 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1563 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1566 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1567 return INVALID_HANDLE_VALUE;
1569 if (level != FindExInfoStandard)
1571 FIXME("info level %d not implemented\n", level );
1572 return INVALID_HANDLE_VALUE;
1575 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1577 SetLastError( ERROR_PATH_NOT_FOUND );
1578 return INVALID_HANDLE_VALUE;
1581 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1583 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1587 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1589 static const WCHAR dotW[] = {'.',0};
1592 /* we still need to check that the directory can be opened */
1596 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1598 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1601 memcpy( dir, filename, HIWORD(device) );
1602 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1604 RtlFreeUnicodeString( &nt_name );
1605 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1607 HeapFree( GetProcessHeap(), 0, dir );
1608 SetLastError( ERROR_PATH_NOT_FOUND );
1611 HeapFree( GetProcessHeap(), 0, dir );
1612 RtlInitUnicodeString( &info->mask, NULL );
1614 else if (!mask || !*mask)
1616 SetLastError( ERROR_FILE_NOT_FOUND );
1621 if (!RtlCreateUnicodeString( &info->mask, mask ))
1623 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1627 /* truncate dir name before mask */
1629 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1632 /* check if path is the root of the drive */
1633 info->is_root = FALSE;
1634 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1635 if (p[0] && p[1] == ':')
1638 while (*p == '\\') p++;
1639 info->is_root = (*p == 0);
1642 attr.Length = sizeof(attr);
1643 attr.RootDirectory = 0;
1644 attr.Attributes = OBJ_CASE_INSENSITIVE;
1645 attr.ObjectName = &nt_name;
1646 attr.SecurityDescriptor = NULL;
1647 attr.SecurityQualityOfService = NULL;
1649 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1650 FILE_SHARE_READ | FILE_SHARE_WRITE,
1651 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1653 if (status != STATUS_SUCCESS)
1655 RtlFreeUnicodeString( &info->mask );
1656 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1657 SetLastError( ERROR_PATH_NOT_FOUND );
1659 SetLastError( RtlNtStatusToDosError(status) );
1663 RtlInitializeCriticalSection( &info->cs );
1664 info->path = nt_name;
1665 info->magic = FIND_FIRST_MAGIC;
1668 info->search_op = search_op;
1672 WIN32_FIND_DATAW *wfd = data;
1674 memset( wfd, 0, sizeof(*wfd) );
1675 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1676 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1677 CloseHandle( info->handle );
1680 else if (!FindNextFileW( (HANDLE)info, data ))
1682 TRACE( "%s not found\n", debugstr_w(filename) );
1683 FindClose( (HANDLE)info );
1684 SetLastError( ERROR_FILE_NOT_FOUND );
1685 return INVALID_HANDLE_VALUE;
1687 else if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1689 /* we can't find two files with the same name */
1690 CloseHandle( info->handle );
1693 return (HANDLE)info;
1696 HeapFree( GetProcessHeap(), 0, info );
1697 RtlFreeUnicodeString( &nt_name );
1698 return INVALID_HANDLE_VALUE;
1702 /*************************************************************************
1703 * FindNextFileW (KERNEL32.@)
1705 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1707 FIND_FIRST_INFO *info;
1708 FILE_BOTH_DIR_INFORMATION *dir_info;
1711 TRACE("%p %p\n", handle, data);
1713 if (!handle || handle == INVALID_HANDLE_VALUE)
1715 SetLastError( ERROR_INVALID_HANDLE );
1718 info = (FIND_FIRST_INFO *)handle;
1719 if (info->magic != FIND_FIRST_MAGIC)
1721 SetLastError( ERROR_INVALID_HANDLE );
1725 RtlEnterCriticalSection( &info->cs );
1727 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1730 if (info->data_pos >= info->data_len) /* need to read some more data */
1734 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1735 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1738 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1739 if (io.u.Status == STATUS_NO_MORE_FILES)
1741 CloseHandle( info->handle );
1746 info->data_len = io.Information;
1750 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1752 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1753 else info->data_pos = info->data_len;
1755 /* don't return '.' and '..' in the root of the drive */
1758 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1759 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1760 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1763 /* check for dir symlink */
1764 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1765 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
1767 if (!check_dir_symlink( info, dir_info )) continue;
1769 if (info->search_op == FindExSearchLimitToDirectories &&
1770 (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1773 data->dwFileAttributes = dir_info->FileAttributes;
1774 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1775 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1776 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1777 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1778 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1779 data->dwReserved0 = 0;
1780 data->dwReserved1 = 0;
1782 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1783 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1784 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1785 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1787 TRACE("returning %s (%s)\n",
1788 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1794 RtlLeaveCriticalSection( &info->cs );
1799 /*************************************************************************
1800 * FindClose (KERNEL32.@)
1802 BOOL WINAPI FindClose( HANDLE handle )
1804 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1806 if (!handle || handle == INVALID_HANDLE_VALUE)
1808 SetLastError( ERROR_INVALID_HANDLE );
1814 if (info->magic == FIND_FIRST_MAGIC)
1816 RtlEnterCriticalSection( &info->cs );
1817 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1820 if (info->handle) CloseHandle( info->handle );
1822 RtlFreeUnicodeString( &info->mask );
1823 info->mask.Buffer = NULL;
1824 RtlFreeUnicodeString( &info->path );
1827 RtlLeaveCriticalSection( &info->cs );
1828 RtlDeleteCriticalSection( &info->cs );
1829 HeapFree( GetProcessHeap(), 0, info );
1835 WARN("Illegal handle %p\n", handle);
1836 SetLastError( ERROR_INVALID_HANDLE );
1845 /*************************************************************************
1846 * FindFirstFileA (KERNEL32.@)
1848 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1850 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1851 FindExSearchNameMatch, NULL, 0);
1854 /*************************************************************************
1855 * FindFirstFileExA (KERNEL32.@)
1857 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1858 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1859 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1862 WIN32_FIND_DATAA *dataA;
1863 WIN32_FIND_DATAW dataW;
1866 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1868 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1869 if (handle == INVALID_HANDLE_VALUE) return handle;
1871 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1872 dataA->dwFileAttributes = dataW.dwFileAttributes;
1873 dataA->ftCreationTime = dataW.ftCreationTime;
1874 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1875 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1876 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1877 dataA->nFileSizeLow = dataW.nFileSizeLow;
1878 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1879 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1880 sizeof(dataA->cAlternateFileName) );
1885 /*************************************************************************
1886 * FindFirstFileW (KERNEL32.@)
1888 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1890 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1891 FindExSearchNameMatch, NULL, 0);
1895 /*************************************************************************
1896 * FindNextFileA (KERNEL32.@)
1898 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1900 WIN32_FIND_DATAW dataW;
1902 if (!FindNextFileW( handle, &dataW )) return FALSE;
1903 data->dwFileAttributes = dataW.dwFileAttributes;
1904 data->ftCreationTime = dataW.ftCreationTime;
1905 data->ftLastAccessTime = dataW.ftLastAccessTime;
1906 data->ftLastWriteTime = dataW.ftLastWriteTime;
1907 data->nFileSizeHigh = dataW.nFileSizeHigh;
1908 data->nFileSizeLow = dataW.nFileSizeLow;
1909 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1910 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1911 sizeof(data->cAlternateFileName) );
1916 /**************************************************************************
1917 * GetFileAttributesW (KERNEL32.@)
1919 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1921 FILE_BASIC_INFORMATION info;
1922 UNICODE_STRING nt_name;
1923 OBJECT_ATTRIBUTES attr;
1926 TRACE("%s\n", debugstr_w(name));
1928 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1930 SetLastError( ERROR_PATH_NOT_FOUND );
1931 return INVALID_FILE_ATTRIBUTES;
1934 attr.Length = sizeof(attr);
1935 attr.RootDirectory = 0;
1936 attr.Attributes = OBJ_CASE_INSENSITIVE;
1937 attr.ObjectName = &nt_name;
1938 attr.SecurityDescriptor = NULL;
1939 attr.SecurityQualityOfService = NULL;
1941 status = NtQueryAttributesFile( &attr, &info );
1942 RtlFreeUnicodeString( &nt_name );
1944 if (status == STATUS_SUCCESS) return info.FileAttributes;
1946 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1947 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1949 SetLastError( RtlNtStatusToDosError(status) );
1950 return INVALID_FILE_ATTRIBUTES;
1954 /**************************************************************************
1955 * GetFileAttributesA (KERNEL32.@)
1957 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1961 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1962 return GetFileAttributesW( nameW );
1966 /**************************************************************************
1967 * SetFileAttributesW (KERNEL32.@)
1969 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1971 UNICODE_STRING nt_name;
1972 OBJECT_ATTRIBUTES attr;
1977 TRACE("%s %x\n", debugstr_w(name), attributes);
1979 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1981 SetLastError( ERROR_PATH_NOT_FOUND );
1985 attr.Length = sizeof(attr);
1986 attr.RootDirectory = 0;
1987 attr.Attributes = OBJ_CASE_INSENSITIVE;
1988 attr.ObjectName = &nt_name;
1989 attr.SecurityDescriptor = NULL;
1990 attr.SecurityQualityOfService = NULL;
1992 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1993 RtlFreeUnicodeString( &nt_name );
1995 if (status == STATUS_SUCCESS)
1997 FILE_BASIC_INFORMATION info;
1999 memset( &info, 0, sizeof(info) );
2000 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2001 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2005 if (status == STATUS_SUCCESS) return TRUE;
2006 SetLastError( RtlNtStatusToDosError(status) );
2011 /**************************************************************************
2012 * SetFileAttributesA (KERNEL32.@)
2014 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2018 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2019 return SetFileAttributesW( nameW, attributes );
2023 /**************************************************************************
2024 * GetFileAttributesExW (KERNEL32.@)
2026 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2028 FILE_NETWORK_OPEN_INFORMATION info;
2029 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2030 UNICODE_STRING nt_name;
2031 OBJECT_ATTRIBUTES attr;
2034 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2036 if (level != GetFileExInfoStandard)
2038 SetLastError( ERROR_INVALID_PARAMETER );
2042 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2044 SetLastError( ERROR_PATH_NOT_FOUND );
2048 attr.Length = sizeof(attr);
2049 attr.RootDirectory = 0;
2050 attr.Attributes = OBJ_CASE_INSENSITIVE;
2051 attr.ObjectName = &nt_name;
2052 attr.SecurityDescriptor = NULL;
2053 attr.SecurityQualityOfService = NULL;
2055 status = NtQueryFullAttributesFile( &attr, &info );
2056 RtlFreeUnicodeString( &nt_name );
2058 if (status != STATUS_SUCCESS)
2060 SetLastError( RtlNtStatusToDosError(status) );
2064 data->dwFileAttributes = info.FileAttributes;
2065 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2066 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2067 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2068 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2069 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2070 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2071 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2072 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2077 /**************************************************************************
2078 * GetFileAttributesExA (KERNEL32.@)
2080 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2084 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2085 return GetFileAttributesExW( nameW, level, ptr );
2089 /******************************************************************************
2090 * GetCompressedFileSizeW (KERNEL32.@)
2092 * Get the actual number of bytes used on disk.
2095 * Success: Low-order doubleword of number of bytes
2096 * Failure: INVALID_FILE_SIZE
2098 DWORD WINAPI GetCompressedFileSizeW(
2099 LPCWSTR name, /* [in] Pointer to name of file */
2100 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2102 UNICODE_STRING nt_name;
2103 OBJECT_ATTRIBUTES attr;
2107 DWORD ret = INVALID_FILE_SIZE;
2109 TRACE("%s %p\n", debugstr_w(name), size_high);
2111 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2113 SetLastError( ERROR_PATH_NOT_FOUND );
2114 return INVALID_FILE_SIZE;
2117 attr.Length = sizeof(attr);
2118 attr.RootDirectory = 0;
2119 attr.Attributes = OBJ_CASE_INSENSITIVE;
2120 attr.ObjectName = &nt_name;
2121 attr.SecurityDescriptor = NULL;
2122 attr.SecurityQualityOfService = NULL;
2124 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2125 RtlFreeUnicodeString( &nt_name );
2127 if (status == STATUS_SUCCESS)
2129 /* we don't support compressed files, simply return the file size */
2130 ret = GetFileSize( handle, size_high );
2133 else SetLastError( RtlNtStatusToDosError(status) );
2139 /******************************************************************************
2140 * GetCompressedFileSizeA (KERNEL32.@)
2142 * See GetCompressedFileSizeW.
2144 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2148 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2149 return GetCompressedFileSizeW( nameW, size_high );
2153 /***********************************************************************
2154 * OpenFile (KERNEL32.@)
2156 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2160 WORD filedatetime[2];
2162 if (!ofs) return HFILE_ERROR;
2164 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2165 ((mode & 0x3 )==OF_READ)?"OF_READ":
2166 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2167 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2168 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2169 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2170 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2171 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2172 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2173 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2174 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2175 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2176 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2177 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2178 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2179 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2180 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2181 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2185 ofs->cBytes = sizeof(OFSTRUCT);
2187 if (mode & OF_REOPEN) name = ofs->szPathName;
2189 if (!name) return HFILE_ERROR;
2191 TRACE("%s %04x\n", name, mode );
2193 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2194 Are there any cases where getting the path here is wrong?
2195 Uwe Bonnes 1997 Apr 2 */
2196 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2198 /* OF_PARSE simply fills the structure */
2200 if (mode & OF_PARSE)
2202 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2203 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2207 /* OF_CREATE is completely different from all other options, so
2210 if (mode & OF_CREATE)
2212 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2217 /* Now look for the file */
2219 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2222 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2224 if (mode & OF_DELETE)
2226 if (!DeleteFileA( ofs->szPathName )) goto error;
2227 TRACE("(%s): OF_DELETE return = OK\n", name);
2231 handle = (HANDLE)_lopen( ofs->szPathName, mode );
2232 if (handle == INVALID_HANDLE_VALUE) goto error;
2234 GetFileTime( handle, NULL, NULL, &filetime );
2235 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2236 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2238 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2240 CloseHandle( handle );
2241 WARN("(%s): OF_VERIFY failed\n", name );
2242 /* FIXME: what error here? */
2243 SetLastError( ERROR_FILE_NOT_FOUND );
2247 ofs->Reserved1 = filedatetime[0];
2248 ofs->Reserved2 = filedatetime[1];
2250 TRACE("(%s): OK, return = %p\n", name, handle );
2251 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2253 CloseHandle( handle );
2256 else return (HFILE)handle;
2258 error: /* We get here if there was an error opening the file */
2259 ofs->nErrCode = GetLastError();
2260 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );