kernel32: Always clear the I/O status block count before calling ntdll functions.
[wine/multimedia.git] / dlls / kernel32 / file.c
blob90280ad48c1354f2e785ea0e07ba130ce7b39b6e
1 /*
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
30 #endif
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34 #include "winerror.h"
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winternl.h"
40 #include "winioctl.h"
41 #include "wincon.h"
42 #include "wine/winbase16.h"
43 #include "kernel_private.h"
45 #include "wine/exception.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
48 #include "thread.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(file);
52 HANDLE dos_handles[DOS_TABLE_SIZE];
54 /* info structure for FindFirstFile handle */
55 typedef struct
57 DWORD magic; /* magic number */
58 HANDLE handle; /* handle to directory */
59 CRITICAL_SECTION cs; /* crit section protecting this structure */
60 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
61 UNICODE_STRING mask; /* file mask */
62 UNICODE_STRING path; /* NT path used to open the directory */
63 BOOL is_root; /* is directory the root of the drive? */
64 UINT data_pos; /* current position in dir data */
65 UINT data_len; /* length of dir data */
66 BYTE data[8192]; /* directory data */
67 } FIND_FIRST_INFO;
69 #define FIND_FIRST_MAGIC 0xc0ffee11
71 static BOOL oem_file_apis;
73 static const WCHAR wildcardsW[] = { '*','?',0 };
75 /***********************************************************************
76 * create_file_OF
78 * Wrapper for CreateFile that takes OF_* mode flags.
80 static HANDLE create_file_OF( LPCSTR path, INT mode )
82 DWORD access, sharing, creation;
84 if (mode & OF_CREATE)
86 creation = CREATE_ALWAYS;
87 access = GENERIC_READ | GENERIC_WRITE;
89 else
91 creation = OPEN_EXISTING;
92 switch(mode & 0x03)
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;
101 switch(mode & 0x70)
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 /***********************************************************************
115 * check_dir_symlink
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 )
121 UNICODE_STRING str;
122 ANSI_STRING unix_name;
123 struct stat st, parent_st;
124 BOOL ret = TRUE;
125 DWORD len;
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--;
148 p[1] = 0;
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 ));
156 ret = FALSE;
160 RtlFreeAnsiString( &unix_name );
161 RtlFreeUnicodeString( &str );
162 return ret;
166 /***********************************************************************
167 * FILE_SetDosError
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));
176 switch (save_errno)
178 case EAGAIN:
179 SetLastError( ERROR_SHARING_VIOLATION );
180 break;
181 case EBADF:
182 SetLastError( ERROR_INVALID_HANDLE );
183 break;
184 case ENOSPC:
185 SetLastError( ERROR_HANDLE_DISK_FULL );
186 break;
187 case EACCES:
188 case EPERM:
189 case EROFS:
190 SetLastError( ERROR_ACCESS_DENIED );
191 break;
192 case EBUSY:
193 SetLastError( ERROR_LOCK_VIOLATION );
194 break;
195 case ENOENT:
196 SetLastError( ERROR_FILE_NOT_FOUND );
197 break;
198 case EISDIR:
199 SetLastError( ERROR_CANNOT_MAKE );
200 break;
201 case ENFILE:
202 case EMFILE:
203 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
204 break;
205 case EEXIST:
206 SetLastError( ERROR_FILE_EXISTS );
207 break;
208 case EINVAL:
209 case ESPIPE:
210 SetLastError( ERROR_SEEK );
211 break;
212 case ENOTEMPTY:
213 SetLastError( ERROR_DIR_NOT_EMPTY );
214 break;
215 case ENOEXEC:
216 SetLastError( ERROR_BAD_FORMAT );
217 break;
218 case ENOTDIR:
219 SetLastError( ERROR_PATH_NOT_FOUND );
220 break;
221 case EXDEV:
222 SetLastError( ERROR_NOT_SAME_DEVICE );
223 break;
224 default:
225 WARN("unknown file error: %s\n", strerror(save_errno) );
226 SetLastError( ERROR_GEN_FAILURE );
227 break;
229 errno = save_errno;
233 /***********************************************************************
234 * FILE_name_AtoW
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 )
244 ANSI_STRING str;
245 UNICODE_STRING strW, *pstrW;
246 NTSTATUS status;
248 RtlInitAnsiString( &str, name );
249 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
250 if (oem_file_apis)
251 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
252 else
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 );
258 else
259 SetLastError( RtlNtStatusToDosError(status) );
260 return NULL;
264 /***********************************************************************
265 * FILE_name_WtoA
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 )
271 DWORD ret;
273 if (srclen < 0) srclen = strlenW( src ) + 1;
274 if (oem_file_apis)
275 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
276 else
277 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
278 return ret;
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
305 * RETURNS
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;
331 init_done = TRUE;
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 reserved)
350 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
352 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (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;
364 NTSTATUS status;
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);
369 if (!overlapped)
371 SetLastError(ERROR_INVALID_PARAMETER);
372 return FALSE;
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;
379 io_status->Information = 0;
381 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
382 io_status, buffer, bytesToRead, &offset, NULL);
384 if (status)
386 SetLastError( RtlNtStatusToDosError(status) );
387 return FALSE;
389 return TRUE;
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;
403 HANDLE hEvent = 0;
404 NTSTATUS status;
406 TRACE("%p %p %d %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;
419 poffset = &offset;
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 && !overlapped)
430 WaitForSingleObject( hFile, INFINITE );
431 status = io_status->u.Status;
434 if (status != STATUS_PENDING && bytesRead)
435 *bytesRead = io_status->Information;
437 if (status && status != STATUS_END_OF_FILE && status != STATUS_TIMEOUT)
439 SetLastError( RtlNtStatusToDosError(status) );
440 return FALSE;
442 return TRUE;
446 /***********************************************************************
447 * WriteFileEx (KERNEL32.@)
449 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
450 LPOVERLAPPED overlapped,
451 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
453 LARGE_INTEGER offset;
454 NTSTATUS status;
455 PIO_STATUS_BLOCK io_status;
457 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
459 if (overlapped == NULL)
461 SetLastError(ERROR_INVALID_PARAMETER);
462 return FALSE;
464 offset.u.LowPart = overlapped->u.s.Offset;
465 offset.u.HighPart = overlapped->u.s.OffsetHigh;
467 io_status = (PIO_STATUS_BLOCK)overlapped;
468 io_status->u.Status = STATUS_PENDING;
469 io_status->Information = 0;
471 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
472 io_status, buffer, bytesToWrite, &offset, NULL);
474 if (status) SetLastError( RtlNtStatusToDosError(status) );
475 return !status;
479 /***********************************************************************
480 * WriteFile (KERNEL32.@)
482 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
483 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
485 HANDLE hEvent = NULL;
486 LARGE_INTEGER offset;
487 PLARGE_INTEGER poffset = NULL;
488 NTSTATUS status;
489 IO_STATUS_BLOCK iosb;
490 PIO_STATUS_BLOCK piosb = &iosb;
492 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
494 if (is_console_handle(hFile))
495 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
497 if (overlapped)
499 offset.u.LowPart = overlapped->u.s.Offset;
500 offset.u.HighPart = overlapped->u.s.OffsetHigh;
501 poffset = &offset;
502 hEvent = overlapped->hEvent;
503 piosb = (PIO_STATUS_BLOCK)overlapped;
505 piosb->u.Status = STATUS_PENDING;
506 piosb->Information = 0;
508 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
509 buffer, bytesToWrite, poffset, NULL);
511 /* FIXME: NtWriteFile does not always cause page faults, generate them now */
512 if (status == STATUS_INVALID_USER_BUFFER && !IsBadReadPtr( buffer, bytesToWrite ))
514 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
515 buffer, bytesToWrite, poffset, NULL);
516 if (status != STATUS_INVALID_USER_BUFFER)
517 FIXME("Could not access memory (%p,%d) at first, now OK. Protected by DIBSection code?\n",
518 buffer, bytesToWrite);
521 if (status == STATUS_PENDING && !overlapped)
523 WaitForSingleObject( hFile, INFINITE );
524 status = piosb->u.Status;
527 if (status != STATUS_PENDING && bytesWritten)
528 *bytesWritten = piosb->Information;
530 if (status && status != STATUS_TIMEOUT)
532 SetLastError( RtlNtStatusToDosError(status) );
533 return FALSE;
535 return TRUE;
539 /***********************************************************************
540 * GetOverlappedResult (KERNEL32.@)
542 * Check the result of an Asynchronous data transfer from a file.
544 * Parameters
545 * HANDLE hFile [in] handle of file to check on
546 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
547 * LPDWORD lpTransferred [in/out] number of bytes transferred
548 * BOOL bWait [in] wait for the transfer to complete ?
550 * RETURNS
551 * TRUE on success
552 * FALSE on failure
554 * If successful (and relevant) lpTransferred will hold the number of
555 * bytes transferred during the async operation.
557 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
558 LPDWORD lpTransferred, BOOL bWait)
560 NTSTATUS status;
562 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
564 if ( lpOverlapped == NULL )
566 ERR("lpOverlapped was null\n");
567 return FALSE;
570 status = lpOverlapped->Internal;
571 if (status == STATUS_PENDING)
573 if (!bWait)
575 SetLastError( ERROR_IO_INCOMPLETE );
576 return FALSE;
579 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
580 INFINITE ) == WAIT_FAILED)
581 return FALSE;
582 status = lpOverlapped->Internal;
585 if (lpTransferred) *lpTransferred = lpOverlapped->InternalHigh;
587 if (status) SetLastError( RtlNtStatusToDosError(status) );
588 return !status;
591 /***********************************************************************
592 * CancelIo (KERNEL32.@)
594 * Cancels pending I/O operations initiated by the current thread on a file.
596 * PARAMS
597 * handle [I] File handle.
599 * RETURNS
600 * Success: TRUE.
601 * Failure: FALSE, check GetLastError().
603 BOOL WINAPI CancelIo(HANDLE handle)
605 IO_STATUS_BLOCK io_status;
607 NtCancelIoFile(handle, &io_status);
608 if (io_status.u.Status)
610 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
611 return FALSE;
613 return TRUE;
616 /***********************************************************************
617 * _hread (KERNEL32.@)
619 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
621 return _lread( hFile, buffer, count );
625 /***********************************************************************
626 * _hwrite (KERNEL32.@)
628 * experimentation yields that _lwrite:
629 * o truncates the file at the current position with
630 * a 0 len write
631 * o returns 0 on a 0 length write
632 * o works with console handles
635 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
637 DWORD result;
639 TRACE("%d %p %d\n", handle, buffer, count );
641 if (!count)
643 /* Expand or truncate at current position */
644 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
645 return 0;
647 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
648 return HFILE_ERROR;
649 return result;
653 /***********************************************************************
654 * _lclose (KERNEL32.@)
656 HFILE WINAPI _lclose( HFILE hFile )
658 TRACE("handle %d\n", hFile );
659 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
663 /***********************************************************************
664 * _lcreat (KERNEL32.@)
666 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
668 HANDLE hfile;
670 /* Mask off all flags not explicitly allowed by the doc */
671 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
672 TRACE("%s %02x\n", path, attr );
673 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
674 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
675 CREATE_ALWAYS, attr, 0 );
676 return HandleToLong(hfile);
680 /***********************************************************************
681 * _lopen (KERNEL32.@)
683 HFILE WINAPI _lopen( LPCSTR path, INT mode )
685 HANDLE hfile;
687 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
688 hfile = create_file_OF( path, mode & ~OF_CREATE );
689 return HandleToLong(hfile);
692 /***********************************************************************
693 * _lread (KERNEL32.@)
695 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
697 DWORD result;
698 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
699 return HFILE_ERROR;
700 return result;
704 /***********************************************************************
705 * _llseek (KERNEL32.@)
707 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
709 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
713 /***********************************************************************
714 * _lwrite (KERNEL32.@)
716 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
718 return (UINT)_hwrite( hFile, buffer, (LONG)count );
722 /***********************************************************************
723 * FlushFileBuffers (KERNEL32.@)
725 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
727 NTSTATUS nts;
728 IO_STATUS_BLOCK ioblk;
730 if (is_console_handle( hFile ))
732 /* this will fail (as expected) for an output handle */
733 return FlushConsoleInputBuffer( hFile );
735 nts = NtFlushBuffersFile( hFile, &ioblk );
736 if (nts != STATUS_SUCCESS)
738 SetLastError( RtlNtStatusToDosError( nts ) );
739 return FALSE;
742 return TRUE;
746 /***********************************************************************
747 * GetFileType (KERNEL32.@)
749 DWORD WINAPI GetFileType( HANDLE hFile )
751 FILE_FS_DEVICE_INFORMATION info;
752 IO_STATUS_BLOCK io;
753 NTSTATUS status;
755 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
757 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
758 if (status != STATUS_SUCCESS)
760 SetLastError( RtlNtStatusToDosError(status) );
761 return FILE_TYPE_UNKNOWN;
764 switch(info.DeviceType)
766 case FILE_DEVICE_NULL:
767 case FILE_DEVICE_SERIAL_PORT:
768 case FILE_DEVICE_PARALLEL_PORT:
769 case FILE_DEVICE_TAPE:
770 case FILE_DEVICE_UNKNOWN:
771 return FILE_TYPE_CHAR;
772 case FILE_DEVICE_NAMED_PIPE:
773 return FILE_TYPE_PIPE;
774 default:
775 return FILE_TYPE_DISK;
780 /***********************************************************************
781 * GetFileInformationByHandle (KERNEL32.@)
783 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
785 FILE_ALL_INFORMATION all_info;
786 IO_STATUS_BLOCK io;
787 NTSTATUS status;
789 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
790 if (status == STATUS_SUCCESS)
792 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
793 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
794 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
795 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
796 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
797 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
798 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
799 info->dwVolumeSerialNumber = 0; /* FIXME */
800 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
801 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
802 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
803 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
804 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
805 return TRUE;
807 SetLastError( RtlNtStatusToDosError(status) );
808 return FALSE;
812 /***********************************************************************
813 * GetFileSize (KERNEL32.@)
815 * Retrieve the size of a file.
817 * PARAMS
818 * hFile [I] File to retrieve size of.
819 * filesizehigh [O] On return, the high bits of the file size.
821 * RETURNS
822 * Success: The low bits of the file size.
823 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
824 * check GetLastError() for values other than ERROR_SUCCESS.
826 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
828 LARGE_INTEGER size;
829 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
830 if (filesizehigh) *filesizehigh = size.u.HighPart;
831 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
832 return size.u.LowPart;
836 /***********************************************************************
837 * GetFileSizeEx (KERNEL32.@)
839 * Retrieve the size of a file.
841 * PARAMS
842 * hFile [I] File to retrieve size of.
843 * lpFileSIze [O] On return, the size of the file.
845 * RETURNS
846 * Success: TRUE.
847 * Failure: FALSE, check GetLastError().
849 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
851 FILE_END_OF_FILE_INFORMATION info;
852 IO_STATUS_BLOCK io;
853 NTSTATUS status;
855 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileEndOfFileInformation );
856 if (status == STATUS_SUCCESS)
858 *lpFileSize = info.EndOfFile;
859 return TRUE;
861 SetLastError( RtlNtStatusToDosError(status) );
862 return FALSE;
866 /**************************************************************************
867 * SetEndOfFile (KERNEL32.@)
869 * Sets the current position as the end of the file.
871 * PARAMS
872 * hFile [I] File handle.
874 * RETURNS
875 * Success: TRUE.
876 * Failure: FALSE, check GetLastError().
878 BOOL WINAPI SetEndOfFile( HANDLE hFile )
880 FILE_POSITION_INFORMATION pos;
881 FILE_END_OF_FILE_INFORMATION eof;
882 IO_STATUS_BLOCK io;
883 NTSTATUS status;
885 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
886 if (status == STATUS_SUCCESS)
888 eof.EndOfFile = pos.CurrentByteOffset;
889 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
891 if (status == STATUS_SUCCESS) return TRUE;
892 SetLastError( RtlNtStatusToDosError(status) );
893 return FALSE;
897 /***********************************************************************
898 * SetFilePointer (KERNEL32.@)
900 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
902 LARGE_INTEGER dist, newpos;
904 if (highword)
906 dist.u.LowPart = distance;
907 dist.u.HighPart = *highword;
909 else dist.QuadPart = distance;
911 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
913 if (highword) *highword = newpos.u.HighPart;
914 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
915 return newpos.u.LowPart;
919 /***********************************************************************
920 * SetFilePointerEx (KERNEL32.@)
922 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
923 LARGE_INTEGER *newpos, DWORD method )
925 LONGLONG pos;
926 IO_STATUS_BLOCK io;
927 FILE_POSITION_INFORMATION info;
929 switch(method)
931 case FILE_BEGIN:
932 pos = distance.QuadPart;
933 break;
934 case FILE_CURRENT:
935 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
936 goto error;
937 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
938 break;
939 case FILE_END:
941 FILE_END_OF_FILE_INFORMATION eof;
942 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
943 goto error;
944 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
946 break;
947 default:
948 SetLastError( ERROR_INVALID_PARAMETER );
949 return FALSE;
952 if (pos < 0)
954 SetLastError( ERROR_NEGATIVE_SEEK );
955 return FALSE;
958 info.CurrentByteOffset.QuadPart = pos;
959 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
960 goto error;
961 if (newpos) newpos->QuadPart = pos;
962 return TRUE;
964 error:
965 SetLastError( RtlNtStatusToDosError(io.u.Status) );
966 return FALSE;
969 /***********************************************************************
970 * GetFileTime (KERNEL32.@)
972 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
973 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
975 FILE_BASIC_INFORMATION info;
976 IO_STATUS_BLOCK io;
977 NTSTATUS status;
979 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
980 if (status == STATUS_SUCCESS)
982 if (lpCreationTime)
984 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
985 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
987 if (lpLastAccessTime)
989 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
990 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
992 if (lpLastWriteTime)
994 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
995 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
997 return TRUE;
999 SetLastError( RtlNtStatusToDosError(status) );
1000 return FALSE;
1004 /***********************************************************************
1005 * SetFileTime (KERNEL32.@)
1007 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1008 const FILETIME *atime, const FILETIME *mtime )
1010 FILE_BASIC_INFORMATION info;
1011 IO_STATUS_BLOCK io;
1012 NTSTATUS status;
1014 memset( &info, 0, sizeof(info) );
1015 if (ctime)
1017 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1018 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1020 if (atime)
1022 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1023 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1025 if (mtime)
1027 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1028 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1031 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1032 if (status == STATUS_SUCCESS) return TRUE;
1033 SetLastError( RtlNtStatusToDosError(status) );
1034 return FALSE;
1038 /**************************************************************************
1039 * LockFile (KERNEL32.@)
1041 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1042 DWORD count_low, DWORD count_high )
1044 NTSTATUS status;
1045 LARGE_INTEGER count, offset;
1047 TRACE( "%p %x%08x %x%08x\n",
1048 hFile, offset_high, offset_low, count_high, count_low );
1050 count.u.LowPart = count_low;
1051 count.u.HighPart = count_high;
1052 offset.u.LowPart = offset_low;
1053 offset.u.HighPart = offset_high;
1055 status = NtLockFile( hFile, 0, NULL, NULL,
1056 NULL, &offset, &count, NULL, TRUE, TRUE );
1058 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1059 return !status;
1063 /**************************************************************************
1064 * LockFileEx [KERNEL32.@]
1066 * Locks a byte range within an open file for shared or exclusive access.
1068 * RETURNS
1069 * success: TRUE
1070 * failure: FALSE
1072 * NOTES
1073 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1075 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1076 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1078 NTSTATUS status;
1079 LARGE_INTEGER count, offset;
1081 if (reserved)
1083 SetLastError( ERROR_INVALID_PARAMETER );
1084 return FALSE;
1087 TRACE( "%p %x%08x %x%08x flags %x\n",
1088 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1089 count_high, count_low, flags );
1091 count.u.LowPart = count_low;
1092 count.u.HighPart = count_high;
1093 offset.u.LowPart = overlapped->u.s.Offset;
1094 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1096 status = NtLockFile( hFile, overlapped->hEvent, NULL, NULL,
1097 NULL, &offset, &count, NULL,
1098 flags & LOCKFILE_FAIL_IMMEDIATELY,
1099 flags & LOCKFILE_EXCLUSIVE_LOCK );
1101 if (status) SetLastError( RtlNtStatusToDosError(status) );
1102 return !status;
1106 /**************************************************************************
1107 * UnlockFile (KERNEL32.@)
1109 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1110 DWORD count_low, DWORD count_high )
1112 NTSTATUS status;
1113 LARGE_INTEGER count, offset;
1115 count.u.LowPart = count_low;
1116 count.u.HighPart = count_high;
1117 offset.u.LowPart = offset_low;
1118 offset.u.HighPart = offset_high;
1120 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1121 if (status) SetLastError( RtlNtStatusToDosError(status) );
1122 return !status;
1126 /**************************************************************************
1127 * UnlockFileEx (KERNEL32.@)
1129 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1130 LPOVERLAPPED overlapped )
1132 if (reserved)
1134 SetLastError( ERROR_INVALID_PARAMETER );
1135 return FALSE;
1137 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1139 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1143 /***********************************************************************
1144 * Win32HandleToDosFileHandle (KERNEL32.21)
1146 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1147 * longer valid after this function (even on failure).
1149 * Note: this is not exactly right, since on Win95 the Win32 handles
1150 * are on top of DOS handles and we do it the other way
1151 * around. Should be good enough though.
1153 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1155 int i;
1157 if (!handle || (handle == INVALID_HANDLE_VALUE))
1158 return HFILE_ERROR;
1160 FILE_InitProcessDosHandles();
1161 for (i = 0; i < DOS_TABLE_SIZE; i++)
1162 if (!dos_handles[i])
1164 dos_handles[i] = handle;
1165 TRACE("Got %d for h32 %p\n", i, handle );
1166 return (HFILE)i;
1168 CloseHandle( handle );
1169 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1170 return HFILE_ERROR;
1174 /***********************************************************************
1175 * DosFileHandleToWin32Handle (KERNEL32.20)
1177 * Return the Win32 handle for a DOS handle.
1179 * Note: this is not exactly right, since on Win95 the Win32 handles
1180 * are on top of DOS handles and we do it the other way
1181 * around. Should be good enough though.
1183 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1185 HFILE16 hfile = (HFILE16)handle;
1186 if (hfile < 5) FILE_InitProcessDosHandles();
1187 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1189 SetLastError( ERROR_INVALID_HANDLE );
1190 return INVALID_HANDLE_VALUE;
1192 return dos_handles[hfile];
1196 /*************************************************************************
1197 * SetHandleCount (KERNEL32.@)
1199 UINT WINAPI SetHandleCount( UINT count )
1201 return min( 256, count );
1205 /***********************************************************************
1206 * DisposeLZ32Handle (KERNEL32.22)
1208 * Note: this is not entirely correct, we should only close the
1209 * 32-bit handle and not the 16-bit one, but we cannot do
1210 * this because of the way our DOS handles are implemented.
1211 * It shouldn't break anything though.
1213 void WINAPI DisposeLZ32Handle( HANDLE handle )
1215 int i;
1217 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1219 for (i = 5; i < DOS_TABLE_SIZE; i++)
1220 if (dos_handles[i] == handle)
1222 dos_handles[i] = 0;
1223 CloseHandle( handle );
1224 break;
1228 /**************************************************************************
1229 * Operations on file names *
1230 **************************************************************************/
1233 /*************************************************************************
1234 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1236 * Creates or opens an object, and returns a handle that can be used to
1237 * access that object.
1239 * PARAMS
1241 * filename [in] pointer to filename to be accessed
1242 * access [in] access mode requested
1243 * sharing [in] share mode
1244 * sa [in] pointer to security attributes
1245 * creation [in] how to create the file
1246 * attributes [in] attributes for newly created file
1247 * template [in] handle to file with extended attributes to copy
1249 * RETURNS
1250 * Success: Open handle to specified file
1251 * Failure: INVALID_HANDLE_VALUE
1253 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1254 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1255 DWORD attributes, HANDLE template )
1257 NTSTATUS status;
1258 UINT options;
1259 OBJECT_ATTRIBUTES attr;
1260 UNICODE_STRING nameW;
1261 IO_STATUS_BLOCK io;
1262 HANDLE ret;
1263 DWORD dosdev;
1264 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1265 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1266 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1267 SECURITY_QUALITY_OF_SERVICE qos;
1269 static const UINT nt_disposition[5] =
1271 FILE_CREATE, /* CREATE_NEW */
1272 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1273 FILE_OPEN, /* OPEN_EXISTING */
1274 FILE_OPEN_IF, /* OPEN_ALWAYS */
1275 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1279 /* sanity checks */
1281 if (!filename || !filename[0])
1283 SetLastError( ERROR_PATH_NOT_FOUND );
1284 return INVALID_HANDLE_VALUE;
1287 TRACE("%s %s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1288 (access & GENERIC_READ)?"GENERIC_READ ":"",
1289 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1290 (!access)?"QUERY_ACCESS ":"",
1291 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1292 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1293 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1294 creation, attributes);
1296 /* Open a console for CONIN$ or CONOUT$ */
1298 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1300 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
1301 goto done;
1304 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1306 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1307 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1309 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1310 !strncmpiW( filename + 4, pipeW, 5 ) ||
1311 !strncmpiW( filename + 4, mailslotW, 9 ))
1313 dosdev = 0;
1315 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1317 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1319 else if (!(GetVersion() & 0x80000000))
1321 dosdev = 0;
1323 else if (filename[4])
1325 ret = VXD_Open( filename+4, access, sa );
1326 goto done;
1328 else
1330 SetLastError( ERROR_INVALID_NAME );
1331 return INVALID_HANDLE_VALUE;
1334 else dosdev = RtlIsDosDeviceName_U( filename );
1336 if (dosdev)
1338 static const WCHAR conW[] = {'C','O','N'};
1340 if (LOWORD(dosdev) == sizeof(conW) &&
1341 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1343 switch (access & (GENERIC_READ|GENERIC_WRITE))
1345 case GENERIC_READ:
1346 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
1347 goto done;
1348 case GENERIC_WRITE:
1349 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
1350 goto done;
1351 default:
1352 SetLastError( ERROR_FILE_NOT_FOUND );
1353 return INVALID_HANDLE_VALUE;
1358 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1360 SetLastError( ERROR_INVALID_PARAMETER );
1361 return INVALID_HANDLE_VALUE;
1364 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1366 SetLastError( ERROR_PATH_NOT_FOUND );
1367 return INVALID_HANDLE_VALUE;
1370 /* now call NtCreateFile */
1372 options = 0;
1373 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1374 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1375 else
1376 options |= FILE_NON_DIRECTORY_FILE;
1377 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1379 options |= FILE_DELETE_ON_CLOSE;
1380 access |= DELETE;
1382 if (!(attributes & FILE_FLAG_OVERLAPPED))
1383 options |= FILE_SYNCHRONOUS_IO_ALERT;
1384 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1385 options |= FILE_RANDOM_ACCESS;
1386 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1388 attr.Length = sizeof(attr);
1389 attr.RootDirectory = 0;
1390 attr.Attributes = OBJ_CASE_INSENSITIVE;
1391 attr.ObjectName = &nameW;
1392 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1393 if (attributes & SECURITY_SQOS_PRESENT)
1395 qos.Length = sizeof(qos);
1396 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1397 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1398 qos.EffectiveOnly = attributes & SECURITY_EFFECTIVE_ONLY ? TRUE : FALSE;
1399 attr.SecurityQualityOfService = &qos;
1401 else
1402 attr.SecurityQualityOfService = NULL;
1404 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1406 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1407 sharing, nt_disposition[creation - CREATE_NEW],
1408 options, NULL, 0 );
1409 if (status)
1411 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1412 ret = INVALID_HANDLE_VALUE;
1414 /* In the case file creation was rejected due to CREATE_NEW flag
1415 * was specified and file with that name already exists, correct
1416 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1417 * Note: RtlNtStatusToDosError is not the subject to blame here.
1419 if (status == STATUS_OBJECT_NAME_COLLISION)
1420 SetLastError( ERROR_FILE_EXISTS );
1421 else
1422 SetLastError( RtlNtStatusToDosError(status) );
1424 else SetLastError(0);
1425 RtlFreeUnicodeString( &nameW );
1427 done:
1428 if (!ret) ret = INVALID_HANDLE_VALUE;
1429 TRACE("returning %p\n", ret);
1430 return ret;
1435 /*************************************************************************
1436 * CreateFileA (KERNEL32.@)
1438 * See CreateFileW.
1440 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1441 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1442 DWORD attributes, HANDLE template)
1444 WCHAR *nameW;
1446 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1447 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1451 /***********************************************************************
1452 * DeleteFileW (KERNEL32.@)
1454 * Delete a file.
1456 * PARAMS
1457 * path [I] Path to the file to delete.
1459 * RETURNS
1460 * Success: TRUE.
1461 * Failure: FALSE, check GetLastError().
1463 BOOL WINAPI DeleteFileW( LPCWSTR path )
1465 UNICODE_STRING nameW;
1466 OBJECT_ATTRIBUTES attr;
1467 NTSTATUS status;
1469 TRACE("%s\n", debugstr_w(path) );
1471 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1473 SetLastError( ERROR_PATH_NOT_FOUND );
1474 return FALSE;
1477 attr.Length = sizeof(attr);
1478 attr.RootDirectory = 0;
1479 attr.Attributes = OBJ_CASE_INSENSITIVE;
1480 attr.ObjectName = &nameW;
1481 attr.SecurityDescriptor = NULL;
1482 attr.SecurityQualityOfService = NULL;
1484 status = NtDeleteFile(&attr);
1485 RtlFreeUnicodeString( &nameW );
1486 if (status)
1488 SetLastError( RtlNtStatusToDosError(status) );
1489 return FALSE;
1491 return TRUE;
1495 /***********************************************************************
1496 * DeleteFileA (KERNEL32.@)
1498 * See DeleteFileW.
1500 BOOL WINAPI DeleteFileA( LPCSTR path )
1502 WCHAR *pathW;
1504 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1505 return DeleteFileW( pathW );
1509 /**************************************************************************
1510 * ReplaceFileW (KERNEL32.@)
1511 * ReplaceFile (KERNEL32.@)
1513 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
1514 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1515 LPVOID lpExclude, LPVOID lpReserved)
1517 FIXME("(%s,%s,%s,%08x,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
1518 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
1519 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1520 return FALSE;
1524 /**************************************************************************
1525 * ReplaceFileA (KERNEL32.@)
1527 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1528 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1529 LPVOID lpExclude, LPVOID lpReserved)
1531 FIXME("(%s,%s,%s,%08x,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
1532 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
1533 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
1534 return FALSE;
1538 /*************************************************************************
1539 * FindFirstFileExW (KERNEL32.@)
1541 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1542 LPVOID data, FINDEX_SEARCH_OPS search_op,
1543 LPVOID filter, DWORD flags)
1545 WCHAR *mask, *p;
1546 FIND_FIRST_INFO *info = NULL;
1547 UNICODE_STRING nt_name;
1548 OBJECT_ATTRIBUTES attr;
1549 IO_STATUS_BLOCK io;
1550 NTSTATUS status;
1551 DWORD device = 0;
1553 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1555 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1556 || flags != 0)
1558 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1559 return INVALID_HANDLE_VALUE;
1561 if (level != FindExInfoStandard)
1563 FIXME("info level %d not implemented\n", level );
1564 return INVALID_HANDLE_VALUE;
1567 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1569 SetLastError( ERROR_PATH_NOT_FOUND );
1570 return INVALID_HANDLE_VALUE;
1573 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1575 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1576 goto error;
1579 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1581 static const WCHAR dotW[] = {'.',0};
1582 WCHAR *dir = NULL;
1584 /* we still need to check that the directory can be opened */
1586 if (HIWORD(device))
1588 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1590 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1591 goto error;
1593 memcpy( dir, filename, HIWORD(device) );
1594 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1596 RtlFreeUnicodeString( &nt_name );
1597 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1599 HeapFree( GetProcessHeap(), 0, dir );
1600 SetLastError( ERROR_PATH_NOT_FOUND );
1601 goto error;
1603 HeapFree( GetProcessHeap(), 0, dir );
1604 RtlInitUnicodeString( &info->mask, NULL );
1606 else if (!mask || !*mask)
1608 SetLastError( ERROR_FILE_NOT_FOUND );
1609 goto error;
1611 else
1613 if (!RtlCreateUnicodeString( &info->mask, mask ))
1615 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1616 goto error;
1619 /* truncate dir name before mask */
1620 *mask = 0;
1621 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1624 /* check if path is the root of the drive */
1625 info->is_root = FALSE;
1626 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1627 if (p[0] && p[1] == ':')
1629 p += 2;
1630 while (*p == '\\') p++;
1631 info->is_root = (*p == 0);
1634 attr.Length = sizeof(attr);
1635 attr.RootDirectory = 0;
1636 attr.Attributes = OBJ_CASE_INSENSITIVE;
1637 attr.ObjectName = &nt_name;
1638 attr.SecurityDescriptor = NULL;
1639 attr.SecurityQualityOfService = NULL;
1641 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1642 FILE_SHARE_READ | FILE_SHARE_WRITE,
1643 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1645 if (status != STATUS_SUCCESS)
1647 RtlFreeUnicodeString( &info->mask );
1648 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1649 SetLastError( ERROR_PATH_NOT_FOUND );
1650 else
1651 SetLastError( RtlNtStatusToDosError(status) );
1652 goto error;
1655 RtlInitializeCriticalSection( &info->cs );
1656 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1657 info->path = nt_name;
1658 info->magic = FIND_FIRST_MAGIC;
1659 info->data_pos = 0;
1660 info->data_len = 0;
1661 info->search_op = search_op;
1663 if (device)
1665 WIN32_FIND_DATAW *wfd = data;
1667 memset( wfd, 0, sizeof(*wfd) );
1668 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1669 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1670 CloseHandle( info->handle );
1671 info->handle = 0;
1673 else
1675 IO_STATUS_BLOCK io;
1677 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1678 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1679 if (io.u.Status)
1681 FindClose( info );
1682 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1683 return INVALID_HANDLE_VALUE;
1685 info->data_len = io.Information;
1686 if (!FindNextFileW( info, data ))
1688 TRACE( "%s not found\n", debugstr_w(filename) );
1689 FindClose( info );
1690 SetLastError( ERROR_FILE_NOT_FOUND );
1691 return INVALID_HANDLE_VALUE;
1693 if (!strpbrkW( info->mask.Buffer, wildcardsW ))
1695 /* we can't find two files with the same name */
1696 CloseHandle( info->handle );
1697 info->handle = 0;
1700 return info;
1702 error:
1703 HeapFree( GetProcessHeap(), 0, info );
1704 RtlFreeUnicodeString( &nt_name );
1705 return INVALID_HANDLE_VALUE;
1709 /*************************************************************************
1710 * FindNextFileW (KERNEL32.@)
1712 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1714 FIND_FIRST_INFO *info;
1715 FILE_BOTH_DIR_INFORMATION *dir_info;
1716 BOOL ret = FALSE;
1718 TRACE("%p %p\n", handle, data);
1720 if (!handle || handle == INVALID_HANDLE_VALUE)
1722 SetLastError( ERROR_INVALID_HANDLE );
1723 return ret;
1725 info = (FIND_FIRST_INFO *)handle;
1726 if (info->magic != FIND_FIRST_MAGIC)
1728 SetLastError( ERROR_INVALID_HANDLE );
1729 return ret;
1732 RtlEnterCriticalSection( &info->cs );
1734 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1735 else for (;;)
1737 if (info->data_pos >= info->data_len) /* need to read some more data */
1739 IO_STATUS_BLOCK io;
1741 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, sizeof(info->data),
1742 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
1743 if (io.u.Status)
1745 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1746 if (io.u.Status == STATUS_NO_MORE_FILES)
1748 CloseHandle( info->handle );
1749 info->handle = 0;
1751 break;
1753 info->data_len = io.Information;
1754 info->data_pos = 0;
1757 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1759 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1760 else info->data_pos = info->data_len;
1762 /* don't return '.' and '..' in the root of the drive */
1763 if (info->is_root)
1765 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1766 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1767 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1770 /* check for dir symlink */
1771 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
1772 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
1773 strpbrkW( info->mask.Buffer, wildcardsW ))
1775 if (!check_dir_symlink( info, dir_info )) continue;
1777 if (info->search_op == FindExSearchLimitToDirectories &&
1778 (dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
1779 continue;
1781 data->dwFileAttributes = dir_info->FileAttributes;
1782 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1783 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1784 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1785 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1786 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1787 data->dwReserved0 = 0;
1788 data->dwReserved1 = 0;
1790 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1791 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1792 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1793 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1795 TRACE("returning %s (%s)\n",
1796 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1798 ret = TRUE;
1799 break;
1802 RtlLeaveCriticalSection( &info->cs );
1803 return ret;
1807 /*************************************************************************
1808 * FindClose (KERNEL32.@)
1810 BOOL WINAPI FindClose( HANDLE handle )
1812 FIND_FIRST_INFO *info = (FIND_FIRST_INFO *)handle;
1814 if (!handle || handle == INVALID_HANDLE_VALUE)
1816 SetLastError( ERROR_INVALID_HANDLE );
1817 return FALSE;
1820 __TRY
1822 if (info->magic == FIND_FIRST_MAGIC)
1824 RtlEnterCriticalSection( &info->cs );
1825 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1827 info->magic = 0;
1828 if (info->handle) CloseHandle( info->handle );
1829 info->handle = 0;
1830 RtlFreeUnicodeString( &info->mask );
1831 info->mask.Buffer = NULL;
1832 RtlFreeUnicodeString( &info->path );
1833 info->data_pos = 0;
1834 info->data_len = 0;
1835 RtlLeaveCriticalSection( &info->cs );
1836 info->cs.DebugInfo->Spare[0] = 0;
1837 RtlDeleteCriticalSection( &info->cs );
1838 HeapFree( GetProcessHeap(), 0, info );
1842 __EXCEPT_PAGE_FAULT
1844 WARN("Illegal handle %p\n", handle);
1845 SetLastError( ERROR_INVALID_HANDLE );
1846 return FALSE;
1848 __ENDTRY
1850 return TRUE;
1854 /*************************************************************************
1855 * FindFirstFileA (KERNEL32.@)
1857 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
1859 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1860 FindExSearchNameMatch, NULL, 0);
1863 /*************************************************************************
1864 * FindFirstFileExA (KERNEL32.@)
1866 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
1867 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
1868 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
1870 HANDLE handle;
1871 WIN32_FIND_DATAA *dataA;
1872 WIN32_FIND_DATAW dataW;
1873 WCHAR *nameW;
1875 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
1877 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1878 if (handle == INVALID_HANDLE_VALUE) return handle;
1880 dataA = (WIN32_FIND_DATAA *) lpFindFileData;
1881 dataA->dwFileAttributes = dataW.dwFileAttributes;
1882 dataA->ftCreationTime = dataW.ftCreationTime;
1883 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1884 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1885 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1886 dataA->nFileSizeLow = dataW.nFileSizeLow;
1887 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1888 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1889 sizeof(dataA->cAlternateFileName) );
1890 return handle;
1894 /*************************************************************************
1895 * FindFirstFileW (KERNEL32.@)
1897 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1899 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1900 FindExSearchNameMatch, NULL, 0);
1904 /*************************************************************************
1905 * FindNextFileA (KERNEL32.@)
1907 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1909 WIN32_FIND_DATAW dataW;
1911 if (!FindNextFileW( handle, &dataW )) return FALSE;
1912 data->dwFileAttributes = dataW.dwFileAttributes;
1913 data->ftCreationTime = dataW.ftCreationTime;
1914 data->ftLastAccessTime = dataW.ftLastAccessTime;
1915 data->ftLastWriteTime = dataW.ftLastWriteTime;
1916 data->nFileSizeHigh = dataW.nFileSizeHigh;
1917 data->nFileSizeLow = dataW.nFileSizeLow;
1918 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1919 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1920 sizeof(data->cAlternateFileName) );
1921 return TRUE;
1925 /**************************************************************************
1926 * GetFileAttributesW (KERNEL32.@)
1928 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
1930 FILE_BASIC_INFORMATION info;
1931 UNICODE_STRING nt_name;
1932 OBJECT_ATTRIBUTES attr;
1933 NTSTATUS status;
1935 TRACE("%s\n", debugstr_w(name));
1937 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1939 SetLastError( ERROR_PATH_NOT_FOUND );
1940 return INVALID_FILE_ATTRIBUTES;
1943 attr.Length = sizeof(attr);
1944 attr.RootDirectory = 0;
1945 attr.Attributes = OBJ_CASE_INSENSITIVE;
1946 attr.ObjectName = &nt_name;
1947 attr.SecurityDescriptor = NULL;
1948 attr.SecurityQualityOfService = NULL;
1950 status = NtQueryAttributesFile( &attr, &info );
1951 RtlFreeUnicodeString( &nt_name );
1953 if (status == STATUS_SUCCESS) return info.FileAttributes;
1955 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1956 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1958 SetLastError( RtlNtStatusToDosError(status) );
1959 return INVALID_FILE_ATTRIBUTES;
1963 /**************************************************************************
1964 * GetFileAttributesA (KERNEL32.@)
1966 DWORD WINAPI GetFileAttributesA( LPCSTR name )
1968 WCHAR *nameW;
1970 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1971 return GetFileAttributesW( nameW );
1975 /**************************************************************************
1976 * SetFileAttributesW (KERNEL32.@)
1978 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
1980 UNICODE_STRING nt_name;
1981 OBJECT_ATTRIBUTES attr;
1982 IO_STATUS_BLOCK io;
1983 NTSTATUS status;
1984 HANDLE handle;
1986 TRACE("%s %x\n", debugstr_w(name), attributes);
1988 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1990 SetLastError( ERROR_PATH_NOT_FOUND );
1991 return FALSE;
1994 attr.Length = sizeof(attr);
1995 attr.RootDirectory = 0;
1996 attr.Attributes = OBJ_CASE_INSENSITIVE;
1997 attr.ObjectName = &nt_name;
1998 attr.SecurityDescriptor = NULL;
1999 attr.SecurityQualityOfService = NULL;
2001 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2002 RtlFreeUnicodeString( &nt_name );
2004 if (status == STATUS_SUCCESS)
2006 FILE_BASIC_INFORMATION info;
2008 memset( &info, 0, sizeof(info) );
2009 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2010 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2011 NtClose( handle );
2014 if (status == STATUS_SUCCESS) return TRUE;
2015 SetLastError( RtlNtStatusToDosError(status) );
2016 return FALSE;
2020 /**************************************************************************
2021 * SetFileAttributesA (KERNEL32.@)
2023 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2025 WCHAR *nameW;
2027 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2028 return SetFileAttributesW( nameW, attributes );
2032 /**************************************************************************
2033 * GetFileAttributesExW (KERNEL32.@)
2035 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2037 FILE_NETWORK_OPEN_INFORMATION info;
2038 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2039 UNICODE_STRING nt_name;
2040 OBJECT_ATTRIBUTES attr;
2041 NTSTATUS status;
2043 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2045 if (level != GetFileExInfoStandard)
2047 SetLastError( ERROR_INVALID_PARAMETER );
2048 return FALSE;
2051 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2053 SetLastError( ERROR_PATH_NOT_FOUND );
2054 return FALSE;
2057 attr.Length = sizeof(attr);
2058 attr.RootDirectory = 0;
2059 attr.Attributes = OBJ_CASE_INSENSITIVE;
2060 attr.ObjectName = &nt_name;
2061 attr.SecurityDescriptor = NULL;
2062 attr.SecurityQualityOfService = NULL;
2064 status = NtQueryFullAttributesFile( &attr, &info );
2065 RtlFreeUnicodeString( &nt_name );
2067 if (status != STATUS_SUCCESS)
2069 SetLastError( RtlNtStatusToDosError(status) );
2070 return FALSE;
2073 data->dwFileAttributes = info.FileAttributes;
2074 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2075 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2076 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2077 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2078 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2079 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2080 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2081 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2082 return TRUE;
2086 /**************************************************************************
2087 * GetFileAttributesExA (KERNEL32.@)
2089 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2091 WCHAR *nameW;
2093 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2094 return GetFileAttributesExW( nameW, level, ptr );
2098 /******************************************************************************
2099 * GetCompressedFileSizeW (KERNEL32.@)
2101 * Get the actual number of bytes used on disk.
2103 * RETURNS
2104 * Success: Low-order doubleword of number of bytes
2105 * Failure: INVALID_FILE_SIZE
2107 DWORD WINAPI GetCompressedFileSizeW(
2108 LPCWSTR name, /* [in] Pointer to name of file */
2109 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2111 UNICODE_STRING nt_name;
2112 OBJECT_ATTRIBUTES attr;
2113 IO_STATUS_BLOCK io;
2114 NTSTATUS status;
2115 HANDLE handle;
2116 DWORD ret = INVALID_FILE_SIZE;
2118 TRACE("%s %p\n", debugstr_w(name), size_high);
2120 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2122 SetLastError( ERROR_PATH_NOT_FOUND );
2123 return INVALID_FILE_SIZE;
2126 attr.Length = sizeof(attr);
2127 attr.RootDirectory = 0;
2128 attr.Attributes = OBJ_CASE_INSENSITIVE;
2129 attr.ObjectName = &nt_name;
2130 attr.SecurityDescriptor = NULL;
2131 attr.SecurityQualityOfService = NULL;
2133 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2134 RtlFreeUnicodeString( &nt_name );
2136 if (status == STATUS_SUCCESS)
2138 /* we don't support compressed files, simply return the file size */
2139 ret = GetFileSize( handle, size_high );
2140 NtClose( handle );
2142 else SetLastError( RtlNtStatusToDosError(status) );
2144 return ret;
2148 /******************************************************************************
2149 * GetCompressedFileSizeA (KERNEL32.@)
2151 * See GetCompressedFileSizeW.
2153 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2155 WCHAR *nameW;
2157 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2158 return GetCompressedFileSizeW( nameW, size_high );
2162 /***********************************************************************
2163 * OpenFile (KERNEL32.@)
2165 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2167 HANDLE handle;
2168 FILETIME filetime;
2169 WORD filedatetime[2];
2171 if (!ofs) return HFILE_ERROR;
2173 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2174 ((mode & 0x3 )==OF_READ)?"OF_READ":
2175 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2176 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2177 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2178 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2179 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2180 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2181 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2182 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2183 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2184 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2185 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2186 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2187 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2188 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2189 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2190 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2194 ofs->cBytes = sizeof(OFSTRUCT);
2195 ofs->nErrCode = 0;
2196 if (mode & OF_REOPEN) name = ofs->szPathName;
2198 if (!name) return HFILE_ERROR;
2200 TRACE("%s %04x\n", name, mode );
2202 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2203 Are there any cases where getting the path here is wrong?
2204 Uwe Bonnes 1997 Apr 2 */
2205 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2207 /* OF_PARSE simply fills the structure */
2209 if (mode & OF_PARSE)
2211 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2212 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2213 return 0;
2216 /* OF_CREATE is completely different from all other options, so
2217 handle it first */
2219 if (mode & OF_CREATE)
2221 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2222 goto error;
2224 else
2226 /* Now look for the file */
2228 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2229 goto error;
2231 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2233 if (mode & OF_DELETE)
2235 if (!DeleteFileA( ofs->szPathName )) goto error;
2236 TRACE("(%s): OF_DELETE return = OK\n", name);
2237 return TRUE;
2240 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2241 if (handle == INVALID_HANDLE_VALUE) goto error;
2243 GetFileTime( handle, NULL, NULL, &filetime );
2244 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2245 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2247 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2249 CloseHandle( handle );
2250 WARN("(%s): OF_VERIFY failed\n", name );
2251 /* FIXME: what error here? */
2252 SetLastError( ERROR_FILE_NOT_FOUND );
2253 goto error;
2256 ofs->Reserved1 = filedatetime[0];
2257 ofs->Reserved2 = filedatetime[1];
2259 TRACE("(%s): OK, return = %p\n", name, handle );
2260 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2262 CloseHandle( handle );
2263 return TRUE;
2265 return HandleToLong(handle);
2267 error: /* We get here if there was an error opening the file */
2268 ofs->nErrCode = GetLastError();
2269 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2270 return HFILE_ERROR;