kernel32/tests: Fix module tests compilation with __WINESRC__ defined.
[wine.git] / dlls / kernel32 / file.c
blob92c776d26b94332414a06c931712c2e6106698ff
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996, 2004 Alexandre Julliard
6 * Copyright 2008 Jeff Zaroyko
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #ifdef HAVE_SYS_STAT_H
30 # include <sys/stat.h>
31 #endif
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "winerror.h"
36 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #include "windef.h"
39 #include "winbase.h"
40 #include "winternl.h"
41 #include "winioctl.h"
42 #include "wincon.h"
43 #include "ddk/ntddk.h"
44 #include "kernel_private.h"
45 #include "fileapi.h"
47 #include "wine/exception.h"
48 #include "wine/unicode.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(file);
53 /* info structure for FindFirstFile handle */
54 typedef struct
56 DWORD magic; /* magic number */
57 HANDLE handle; /* handle to directory */
58 CRITICAL_SECTION cs; /* crit section protecting this structure */
59 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
60 UNICODE_STRING mask; /* file mask */
61 UNICODE_STRING path; /* NT path used to open the directory */
62 BOOL is_root; /* is directory the root of the drive? */
63 UINT data_pos; /* current position in dir data */
64 UINT data_len; /* length of dir data */
65 UINT data_size; /* size of data buffer, or 0 when everything has been read */
66 BYTE *data; /* directory data */
67 } FIND_FIRST_INFO;
69 #define FIND_FIRST_MAGIC 0xc0ffee11
71 static const UINT max_entry_size = offsetof( FILE_BOTH_DIRECTORY_INFORMATION, FileName[256] );
73 static BOOL oem_file_apis;
75 static const WCHAR wildcardsW[] = { '*','?',0 };
77 /***********************************************************************
78 * create_file_OF
80 * Wrapper for CreateFile that takes OF_* mode flags.
82 static HANDLE create_file_OF( LPCSTR path, INT mode )
84 DWORD access, sharing, creation;
86 if (mode & OF_CREATE)
88 creation = CREATE_ALWAYS;
89 access = GENERIC_READ | GENERIC_WRITE;
91 else
93 creation = OPEN_EXISTING;
94 switch(mode & 0x03)
96 case OF_READ: access = GENERIC_READ; break;
97 case OF_WRITE: access = GENERIC_WRITE; break;
98 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
99 default: access = 0; break;
103 switch(mode & 0x70)
105 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
106 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
107 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
108 case OF_SHARE_DENY_NONE:
109 case OF_SHARE_COMPAT:
110 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
112 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
116 /***********************************************************************
117 * check_dir_symlink
119 * Check if a dir symlink should be returned by FindNextFile.
121 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
123 UNICODE_STRING str;
124 ANSI_STRING unix_name;
125 struct stat st, parent_st;
126 BOOL ret = TRUE;
127 DWORD len;
129 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
130 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
131 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
132 len = info->path.Length / sizeof(WCHAR);
133 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
134 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
135 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
137 unix_name.Buffer = NULL;
138 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
139 !stat( unix_name.Buffer, &st ))
141 char *p = unix_name.Buffer + unix_name.Length - 1;
143 /* skip trailing slashes */
144 while (p > unix_name.Buffer && *p == '/') p--;
146 while (ret && p > unix_name.Buffer)
148 while (p > unix_name.Buffer && *p != '/') p--;
149 while (p > unix_name.Buffer && *p == '/') p--;
150 p[1] = 0;
151 if (!stat( unix_name.Buffer, &parent_st ) &&
152 parent_st.st_dev == st.st_dev &&
153 parent_st.st_ino == st.st_ino)
155 WARN( "suppressing dir symlink %s pointing to parent %s\n",
156 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
157 debugstr_a( unix_name.Buffer ));
158 ret = FALSE;
162 RtlFreeAnsiString( &unix_name );
163 RtlFreeUnicodeString( &str );
164 return ret;
168 /***********************************************************************
169 * FILE_SetDosError
171 * Set the DOS error code from errno.
173 void FILE_SetDosError(void)
175 int save_errno = errno; /* errno gets overwritten by printf */
177 TRACE("errno = %d %s\n", errno, strerror(errno));
178 switch (save_errno)
180 case EAGAIN:
181 SetLastError( ERROR_SHARING_VIOLATION );
182 break;
183 case EBADF:
184 SetLastError( ERROR_INVALID_HANDLE );
185 break;
186 case ENOSPC:
187 SetLastError( ERROR_HANDLE_DISK_FULL );
188 break;
189 case EACCES:
190 case EPERM:
191 case EROFS:
192 SetLastError( ERROR_ACCESS_DENIED );
193 break;
194 case EBUSY:
195 SetLastError( ERROR_LOCK_VIOLATION );
196 break;
197 case ENOENT:
198 SetLastError( ERROR_FILE_NOT_FOUND );
199 break;
200 case EISDIR:
201 SetLastError( ERROR_CANNOT_MAKE );
202 break;
203 case ENFILE:
204 case EMFILE:
205 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
206 break;
207 case EEXIST:
208 SetLastError( ERROR_FILE_EXISTS );
209 break;
210 case EINVAL:
211 case ESPIPE:
212 SetLastError( ERROR_SEEK );
213 break;
214 case ENOTEMPTY:
215 SetLastError( ERROR_DIR_NOT_EMPTY );
216 break;
217 case ENOEXEC:
218 SetLastError( ERROR_BAD_FORMAT );
219 break;
220 case ENOTDIR:
221 SetLastError( ERROR_PATH_NOT_FOUND );
222 break;
223 case EXDEV:
224 SetLastError( ERROR_NOT_SAME_DEVICE );
225 break;
226 default:
227 WARN("unknown file error: %s\n", strerror(save_errno) );
228 SetLastError( ERROR_GEN_FAILURE );
229 break;
231 errno = save_errno;
235 /***********************************************************************
236 * FILE_name_AtoW
238 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
240 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
241 * there is no possibility for the function to do that twice, taking into
242 * account any called function.
244 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
246 ANSI_STRING str;
247 UNICODE_STRING strW, *pstrW;
248 NTSTATUS status;
250 RtlInitAnsiString( &str, name );
251 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
252 if (oem_file_apis)
253 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
254 else
255 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
256 if (status == STATUS_SUCCESS) return pstrW->Buffer;
258 if (status == STATUS_BUFFER_OVERFLOW)
259 SetLastError( ERROR_FILENAME_EXCED_RANGE );
260 else
261 SetLastError( RtlNtStatusToDosError(status) );
262 return NULL;
266 /***********************************************************************
267 * FILE_name_WtoA
269 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
271 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
273 DWORD ret;
275 if (srclen < 0) srclen = strlenW( src ) + 1;
276 if (oem_file_apis)
277 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
278 else
279 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
280 return ret;
284 /**************************************************************************
285 * SetFileApisToOEM (KERNEL32.@)
287 VOID WINAPI SetFileApisToOEM(void)
289 oem_file_apis = TRUE;
293 /**************************************************************************
294 * SetFileApisToANSI (KERNEL32.@)
296 VOID WINAPI SetFileApisToANSI(void)
298 oem_file_apis = FALSE;
302 /******************************************************************************
303 * AreFileApisANSI (KERNEL32.@)
305 * Determines if file functions are using ANSI
307 * RETURNS
308 * TRUE: Set of file functions is using ANSI code page
309 * FALSE: Set of file functions is using OEM code page
311 BOOL WINAPI AreFileApisANSI(void)
313 return !oem_file_apis;
317 /**************************************************************************
318 * Operations on file handles *
319 **************************************************************************/
321 /******************************************************************
322 * FILE_ReadWriteApc (internal)
324 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
326 LPOVERLAPPED_COMPLETION_ROUTINE cr = apc_user;
328 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
332 /***********************************************************************
333 * ReadFileEx (KERNEL32.@)
335 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
336 LPOVERLAPPED overlapped,
337 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
339 LARGE_INTEGER offset;
340 NTSTATUS status;
341 PIO_STATUS_BLOCK io_status;
343 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
345 if (!overlapped)
347 SetLastError(ERROR_INVALID_PARAMETER);
348 return FALSE;
351 offset.u.LowPart = overlapped->u.s.Offset;
352 offset.u.HighPart = overlapped->u.s.OffsetHigh;
353 io_status = (PIO_STATUS_BLOCK)overlapped;
354 io_status->u.Status = STATUS_PENDING;
355 io_status->Information = 0;
357 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
358 io_status, buffer, bytesToRead, &offset, NULL);
360 if (status && status != STATUS_PENDING)
362 SetLastError( RtlNtStatusToDosError(status) );
363 return FALSE;
365 return TRUE;
369 /***********************************************************************
370 * ReadFileScatter (KERNEL32.@)
372 BOOL WINAPI ReadFileScatter( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
373 LPDWORD reserved, LPOVERLAPPED overlapped )
375 PIO_STATUS_BLOCK io_status;
376 LARGE_INTEGER offset;
377 NTSTATUS status;
379 TRACE( "(%p %p %u %p)\n", file, segments, count, overlapped );
381 offset.u.LowPart = overlapped->u.s.Offset;
382 offset.u.HighPart = overlapped->u.s.OffsetHigh;
383 io_status = (PIO_STATUS_BLOCK)overlapped;
384 io_status->u.Status = STATUS_PENDING;
385 io_status->Information = 0;
387 status = NtReadFileScatter( file, NULL, NULL, NULL, io_status, segments, count, &offset, NULL );
388 if (status) SetLastError( RtlNtStatusToDosError(status) );
389 return !status;
393 /***********************************************************************
394 * ReadFile (KERNEL32.@)
396 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
397 LPDWORD bytesRead, LPOVERLAPPED overlapped )
399 LARGE_INTEGER offset;
400 PLARGE_INTEGER poffset = NULL;
401 IO_STATUS_BLOCK iosb;
402 PIO_STATUS_BLOCK io_status = &iosb;
403 HANDLE hEvent = 0;
404 NTSTATUS status;
405 LPVOID cvalue = NULL;
407 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
408 bytesRead, overlapped );
410 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
412 if (is_console_handle(hFile))
414 DWORD conread, mode;
415 if (!ReadConsoleA(hFile, buffer, bytesToRead, &conread, NULL) ||
416 !GetConsoleMode(hFile, &mode))
417 return FALSE;
418 /* ctrl-Z (26) means end of file on window (if at beginning of buffer)
419 * but Unix uses ctrl-D (4), and ctrl-Z is a bad idea on Unix :-/
420 * So map both ctrl-D ctrl-Z to EOF.
422 if ((mode & ENABLE_PROCESSED_INPUT) && conread > 0 &&
423 (((char*)buffer)[0] == 26 || ((char*)buffer)[0] == 4))
425 conread = 0;
427 if (bytesRead) *bytesRead = conread;
428 return TRUE;
431 if (overlapped != NULL)
433 offset.u.LowPart = overlapped->u.s.Offset;
434 offset.u.HighPart = overlapped->u.s.OffsetHigh;
435 poffset = &offset;
436 hEvent = overlapped->hEvent;
437 io_status = (PIO_STATUS_BLOCK)overlapped;
438 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
440 io_status->u.Status = STATUS_PENDING;
441 io_status->Information = 0;
443 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
445 if (status == STATUS_PENDING && !overlapped)
447 WaitForSingleObject( hFile, INFINITE );
448 status = io_status->u.Status;
451 if (status != STATUS_PENDING && bytesRead)
452 *bytesRead = io_status->Information;
454 if (status == STATUS_END_OF_FILE)
456 if (overlapped != NULL)
458 SetLastError( RtlNtStatusToDosError(status) );
459 return FALSE;
462 else if (status && status != STATUS_TIMEOUT)
464 SetLastError( RtlNtStatusToDosError(status) );
465 return FALSE;
467 return TRUE;
471 /***********************************************************************
472 * WriteFileEx (KERNEL32.@)
474 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
475 LPOVERLAPPED overlapped,
476 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
478 LARGE_INTEGER offset;
479 NTSTATUS status;
480 PIO_STATUS_BLOCK io_status;
482 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
484 if (overlapped == NULL)
486 SetLastError(ERROR_INVALID_PARAMETER);
487 return FALSE;
489 offset.u.LowPart = overlapped->u.s.Offset;
490 offset.u.HighPart = overlapped->u.s.OffsetHigh;
492 io_status = (PIO_STATUS_BLOCK)overlapped;
493 io_status->u.Status = STATUS_PENDING;
494 io_status->Information = 0;
496 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
497 io_status, buffer, bytesToWrite, &offset, NULL);
499 if (status && status != STATUS_PENDING)
501 SetLastError( RtlNtStatusToDosError(status) );
502 return FALSE;
504 return TRUE;
508 /***********************************************************************
509 * WriteFileGather (KERNEL32.@)
511 BOOL WINAPI WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
512 LPDWORD reserved, LPOVERLAPPED overlapped )
514 PIO_STATUS_BLOCK io_status;
515 LARGE_INTEGER offset;
516 NTSTATUS status;
518 TRACE( "%p %p %u %p\n", file, segments, count, overlapped );
520 offset.u.LowPart = overlapped->u.s.Offset;
521 offset.u.HighPart = overlapped->u.s.OffsetHigh;
522 io_status = (PIO_STATUS_BLOCK)overlapped;
523 io_status->u.Status = STATUS_PENDING;
524 io_status->Information = 0;
526 status = NtWriteFileGather( file, NULL, NULL, NULL, io_status, segments, count, &offset, NULL );
527 if (status) SetLastError( RtlNtStatusToDosError(status) );
528 return !status;
532 /***********************************************************************
533 * WriteFile (KERNEL32.@)
535 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
536 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
538 HANDLE hEvent = NULL;
539 LARGE_INTEGER offset;
540 PLARGE_INTEGER poffset = NULL;
541 NTSTATUS status;
542 IO_STATUS_BLOCK iosb;
543 PIO_STATUS_BLOCK piosb = &iosb;
544 LPVOID cvalue = NULL;
546 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
548 if (is_console_handle(hFile))
549 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
551 if (overlapped)
553 offset.u.LowPart = overlapped->u.s.Offset;
554 offset.u.HighPart = overlapped->u.s.OffsetHigh;
555 poffset = &offset;
556 hEvent = overlapped->hEvent;
557 piosb = (PIO_STATUS_BLOCK)overlapped;
558 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
560 piosb->u.Status = STATUS_PENDING;
561 piosb->Information = 0;
563 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
564 buffer, bytesToWrite, poffset, NULL);
566 if (status == STATUS_PENDING && !overlapped)
568 WaitForSingleObject( hFile, INFINITE );
569 status = piosb->u.Status;
572 if (status != STATUS_PENDING && bytesWritten)
573 *bytesWritten = piosb->Information;
575 if (status && status != STATUS_TIMEOUT)
577 SetLastError( RtlNtStatusToDosError(status) );
578 return FALSE;
580 return TRUE;
584 /***********************************************************************
585 * GetOverlappedResult (KERNEL32.@)
587 * Check the result of an Asynchronous data transfer from a file.
589 * Parameters
590 * HANDLE hFile [in] handle of file to check on
591 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
592 * LPDWORD lpTransferred [in/out] number of bytes transferred
593 * BOOL bWait [in] wait for the transfer to complete ?
595 * RETURNS
596 * TRUE on success
597 * FALSE on failure
599 * If successful (and relevant) lpTransferred will hold the number of
600 * bytes transferred during the async operation.
602 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
603 LPDWORD lpTransferred, BOOL bWait)
605 NTSTATUS status;
607 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
609 status = lpOverlapped->Internal;
610 if (status == STATUS_PENDING)
612 if (!bWait)
614 SetLastError( ERROR_IO_INCOMPLETE );
615 return FALSE;
618 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
619 INFINITE ) == WAIT_FAILED)
620 return FALSE;
621 status = lpOverlapped->Internal;
624 *lpTransferred = lpOverlapped->InternalHigh;
626 if (status) SetLastError( RtlNtStatusToDosError(status) );
627 return !status;
630 /***********************************************************************
631 * CancelIoEx (KERNEL32.@)
633 * Cancels pending I/O operations on a file given the overlapped used.
635 * PARAMS
636 * handle [I] File handle.
637 * lpOverlapped [I,OPT] pointer to overlapped (if null, cancel all)
639 * RETURNS
640 * Success: TRUE.
641 * Failure: FALSE, check GetLastError().
643 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
645 IO_STATUS_BLOCK io_status;
647 NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
648 if (io_status.u.Status)
650 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
651 return FALSE;
653 return TRUE;
656 /***********************************************************************
657 * CancelIo (KERNEL32.@)
659 * Cancels pending I/O operations initiated by the current thread on a file.
661 * PARAMS
662 * handle [I] File handle.
664 * RETURNS
665 * Success: TRUE.
666 * Failure: FALSE, check GetLastError().
668 BOOL WINAPI CancelIo(HANDLE handle)
670 IO_STATUS_BLOCK io_status;
672 NtCancelIoFile(handle, &io_status);
673 if (io_status.u.Status)
675 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
676 return FALSE;
678 return TRUE;
681 /***********************************************************************
682 * _hread (KERNEL32.@)
684 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
686 return _lread( hFile, buffer, count );
690 /***********************************************************************
691 * _hwrite (KERNEL32.@)
693 * experimentation yields that _lwrite:
694 * o truncates the file at the current position with
695 * a 0 len write
696 * o returns 0 on a 0 length write
697 * o works with console handles
700 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
702 DWORD result;
704 TRACE("%d %p %d\n", handle, buffer, count );
706 if (!count)
708 /* Expand or truncate at current position */
709 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
710 return 0;
712 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
713 return HFILE_ERROR;
714 return result;
718 /***********************************************************************
719 * _lclose (KERNEL32.@)
721 HFILE WINAPI _lclose( HFILE hFile )
723 TRACE("handle %d\n", hFile );
724 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
728 /***********************************************************************
729 * _lcreat (KERNEL32.@)
731 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
733 HANDLE hfile;
735 /* Mask off all flags not explicitly allowed by the doc */
736 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
737 TRACE("%s %02x\n", path, attr );
738 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
739 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
740 CREATE_ALWAYS, attr, 0 );
741 return HandleToLong(hfile);
745 /***********************************************************************
746 * _lopen (KERNEL32.@)
748 HFILE WINAPI _lopen( LPCSTR path, INT mode )
750 HANDLE hfile;
752 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
753 hfile = create_file_OF( path, mode & ~OF_CREATE );
754 return HandleToLong(hfile);
757 /***********************************************************************
758 * _lread (KERNEL32.@)
760 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
762 DWORD result;
763 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
764 return HFILE_ERROR;
765 return result;
769 /***********************************************************************
770 * _llseek (KERNEL32.@)
772 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
774 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
778 /***********************************************************************
779 * _lwrite (KERNEL32.@)
781 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
783 return (UINT)_hwrite( hFile, buffer, (LONG)count );
787 /***********************************************************************
788 * FlushFileBuffers (KERNEL32.@)
790 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
792 NTSTATUS nts;
793 IO_STATUS_BLOCK ioblk;
795 if (is_console_handle( hFile ))
797 /* this will fail (as expected) for an output handle */
798 return FlushConsoleInputBuffer( hFile );
800 nts = NtFlushBuffersFile( hFile, &ioblk );
801 if (nts != STATUS_SUCCESS)
803 SetLastError( RtlNtStatusToDosError( nts ) );
804 return FALSE;
807 return TRUE;
811 /***********************************************************************
812 * GetFileType (KERNEL32.@)
814 DWORD WINAPI GetFileType( HANDLE hFile )
816 FILE_FS_DEVICE_INFORMATION info;
817 IO_STATUS_BLOCK io;
818 NTSTATUS status;
820 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
822 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
823 if (status != STATUS_SUCCESS)
825 SetLastError( RtlNtStatusToDosError(status) );
826 return FILE_TYPE_UNKNOWN;
829 switch(info.DeviceType)
831 case FILE_DEVICE_NULL:
832 case FILE_DEVICE_SERIAL_PORT:
833 case FILE_DEVICE_PARALLEL_PORT:
834 case FILE_DEVICE_TAPE:
835 case FILE_DEVICE_UNKNOWN:
836 return FILE_TYPE_CHAR;
837 case FILE_DEVICE_NAMED_PIPE:
838 return FILE_TYPE_PIPE;
839 default:
840 return FILE_TYPE_DISK;
845 /***********************************************************************
846 * GetFileInformationByHandle (KERNEL32.@)
848 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
850 FILE_ALL_INFORMATION all_info;
851 IO_STATUS_BLOCK io;
852 NTSTATUS status;
854 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
855 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
856 if (status == STATUS_SUCCESS)
858 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
859 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
860 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
861 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
862 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
863 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
864 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
865 info->dwVolumeSerialNumber = 0; /* FIXME */
866 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
867 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
868 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
869 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
870 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
871 return TRUE;
873 SetLastError( RtlNtStatusToDosError(status) );
874 return FALSE;
878 /***********************************************************************
879 * GetFileInformationByHandleEx (KERNEL32.@)
881 BOOL WINAPI GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
882 LPVOID info, DWORD size )
884 NTSTATUS status;
885 IO_STATUS_BLOCK io;
887 switch (class)
889 case FileBasicInfo:
890 case FileStandardInfo:
891 case FileRenameInfo:
892 case FileDispositionInfo:
893 case FileAllocationInfo:
894 case FileEndOfFileInfo:
895 case FileStreamInfo:
896 case FileCompressionInfo:
897 case FileAttributeTagInfo:
898 case FileIoPriorityHintInfo:
899 case FileRemoteProtocolInfo:
900 case FileFullDirectoryInfo:
901 case FileFullDirectoryRestartInfo:
902 case FileStorageInfo:
903 case FileAlignmentInfo:
904 case FileIdInfo:
905 case FileIdExtdDirectoryInfo:
906 case FileIdExtdDirectoryRestartInfo:
907 FIXME( "%p, %u, %p, %u\n", handle, class, info, size );
908 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
909 return FALSE;
911 case FileNameInfo:
912 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
913 if (status != STATUS_SUCCESS)
915 SetLastError( RtlNtStatusToDosError( status ) );
916 return FALSE;
918 return TRUE;
920 case FileIdBothDirectoryRestartInfo:
921 case FileIdBothDirectoryInfo:
922 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
923 FileIdBothDirectoryInformation, FALSE, NULL,
924 (class == FileIdBothDirectoryRestartInfo) );
925 if (status != STATUS_SUCCESS)
927 SetLastError( RtlNtStatusToDosError( status ) );
928 return FALSE;
930 return TRUE;
932 default:
933 SetLastError( ERROR_INVALID_PARAMETER );
934 return FALSE;
939 /***********************************************************************
940 * GetFileSize (KERNEL32.@)
942 * Retrieve the size of a file.
944 * PARAMS
945 * hFile [I] File to retrieve size of.
946 * filesizehigh [O] On return, the high bits of the file size.
948 * RETURNS
949 * Success: The low bits of the file size.
950 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
951 * check GetLastError() for values other than ERROR_SUCCESS.
953 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
955 LARGE_INTEGER size;
956 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
957 if (filesizehigh) *filesizehigh = size.u.HighPart;
958 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
959 return size.u.LowPart;
963 /***********************************************************************
964 * GetFileSizeEx (KERNEL32.@)
966 * Retrieve the size of a file.
968 * PARAMS
969 * hFile [I] File to retrieve size of.
970 * lpFileSIze [O] On return, the size of the file.
972 * RETURNS
973 * Success: TRUE.
974 * Failure: FALSE, check GetLastError().
976 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
978 FILE_STANDARD_INFORMATION info;
979 IO_STATUS_BLOCK io;
980 NTSTATUS status;
982 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
983 if (status == STATUS_SUCCESS)
985 *lpFileSize = info.EndOfFile;
986 return TRUE;
988 SetLastError( RtlNtStatusToDosError(status) );
989 return FALSE;
993 /**************************************************************************
994 * SetEndOfFile (KERNEL32.@)
996 * Sets the current position as the end of the file.
998 * PARAMS
999 * hFile [I] File handle.
1001 * RETURNS
1002 * Success: TRUE.
1003 * Failure: FALSE, check GetLastError().
1005 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1007 FILE_POSITION_INFORMATION pos;
1008 FILE_END_OF_FILE_INFORMATION eof;
1009 IO_STATUS_BLOCK io;
1010 NTSTATUS status;
1012 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
1013 if (status == STATUS_SUCCESS)
1015 eof.EndOfFile = pos.CurrentByteOffset;
1016 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
1018 if (status == STATUS_SUCCESS) return TRUE;
1019 SetLastError( RtlNtStatusToDosError(status) );
1020 return FALSE;
1023 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1025 FIXME("%p %u %p %u - stub\n", file, class, info, size);
1026 return FALSE;
1029 /***********************************************************************
1030 * SetFilePointer (KERNEL32.@)
1032 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1034 LARGE_INTEGER dist, newpos;
1036 if (highword)
1038 dist.u.LowPart = distance;
1039 dist.u.HighPart = *highword;
1041 else dist.QuadPart = distance;
1043 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1045 if (highword) *highword = newpos.u.HighPart;
1046 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1047 return newpos.u.LowPart;
1051 /***********************************************************************
1052 * SetFilePointerEx (KERNEL32.@)
1054 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1055 LARGE_INTEGER *newpos, DWORD method )
1057 LONGLONG pos;
1058 IO_STATUS_BLOCK io;
1059 FILE_POSITION_INFORMATION info;
1061 switch(method)
1063 case FILE_BEGIN:
1064 pos = distance.QuadPart;
1065 break;
1066 case FILE_CURRENT:
1067 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1068 goto error;
1069 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1070 break;
1071 case FILE_END:
1073 FILE_END_OF_FILE_INFORMATION eof;
1074 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1075 goto error;
1076 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1078 break;
1079 default:
1080 SetLastError( ERROR_INVALID_PARAMETER );
1081 return FALSE;
1084 if (pos < 0)
1086 SetLastError( ERROR_NEGATIVE_SEEK );
1087 return FALSE;
1090 info.CurrentByteOffset.QuadPart = pos;
1091 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1092 goto error;
1093 if (newpos) newpos->QuadPart = pos;
1094 return TRUE;
1096 error:
1097 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1098 return FALSE;
1101 /***********************************************************************
1102 * SetFileValidData (KERNEL32.@)
1104 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1106 FILE_VALID_DATA_LENGTH_INFORMATION info;
1107 IO_STATUS_BLOCK io;
1108 NTSTATUS status;
1110 info.ValidDataLength.QuadPart = ValidDataLength;
1111 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1113 if (status == STATUS_SUCCESS) return TRUE;
1114 SetLastError( RtlNtStatusToDosError(status) );
1115 return FALSE;
1118 /***********************************************************************
1119 * GetFileTime (KERNEL32.@)
1121 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1122 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1124 FILE_BASIC_INFORMATION info;
1125 IO_STATUS_BLOCK io;
1126 NTSTATUS status;
1128 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1129 if (status == STATUS_SUCCESS)
1131 if (lpCreationTime)
1133 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1134 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1136 if (lpLastAccessTime)
1138 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1139 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1141 if (lpLastWriteTime)
1143 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1144 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1146 return TRUE;
1148 SetLastError( RtlNtStatusToDosError(status) );
1149 return FALSE;
1153 /***********************************************************************
1154 * SetFileTime (KERNEL32.@)
1156 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1157 const FILETIME *atime, const FILETIME *mtime )
1159 FILE_BASIC_INFORMATION info;
1160 IO_STATUS_BLOCK io;
1161 NTSTATUS status;
1163 memset( &info, 0, sizeof(info) );
1164 if (ctime)
1166 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1167 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1169 if (atime)
1171 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1172 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1174 if (mtime)
1176 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1177 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1180 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1181 if (status == STATUS_SUCCESS) return TRUE;
1182 SetLastError( RtlNtStatusToDosError(status) );
1183 return FALSE;
1187 /**************************************************************************
1188 * LockFile (KERNEL32.@)
1190 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1191 DWORD count_low, DWORD count_high )
1193 NTSTATUS status;
1194 LARGE_INTEGER count, offset;
1196 TRACE( "%p %x%08x %x%08x\n",
1197 hFile, offset_high, offset_low, count_high, count_low );
1199 count.u.LowPart = count_low;
1200 count.u.HighPart = count_high;
1201 offset.u.LowPart = offset_low;
1202 offset.u.HighPart = offset_high;
1204 status = NtLockFile( hFile, 0, NULL, NULL,
1205 NULL, &offset, &count, NULL, TRUE, TRUE );
1207 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1208 return !status;
1212 /**************************************************************************
1213 * LockFileEx [KERNEL32.@]
1215 * Locks a byte range within an open file for shared or exclusive access.
1217 * RETURNS
1218 * success: TRUE
1219 * failure: FALSE
1221 * NOTES
1222 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1224 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1225 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1227 NTSTATUS status;
1228 LARGE_INTEGER count, offset;
1229 LPVOID cvalue = NULL;
1231 if (reserved)
1233 SetLastError( ERROR_INVALID_PARAMETER );
1234 return FALSE;
1237 TRACE( "%p %x%08x %x%08x flags %x\n",
1238 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1239 count_high, count_low, flags );
1241 count.u.LowPart = count_low;
1242 count.u.HighPart = count_high;
1243 offset.u.LowPart = overlapped->u.s.Offset;
1244 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1246 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1248 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1249 NULL, &offset, &count, NULL,
1250 flags & LOCKFILE_FAIL_IMMEDIATELY,
1251 flags & LOCKFILE_EXCLUSIVE_LOCK );
1253 if (status) SetLastError( RtlNtStatusToDosError(status) );
1254 return !status;
1258 /**************************************************************************
1259 * UnlockFile (KERNEL32.@)
1261 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1262 DWORD count_low, DWORD count_high )
1264 NTSTATUS status;
1265 LARGE_INTEGER count, offset;
1267 count.u.LowPart = count_low;
1268 count.u.HighPart = count_high;
1269 offset.u.LowPart = offset_low;
1270 offset.u.HighPart = offset_high;
1272 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1273 if (status) SetLastError( RtlNtStatusToDosError(status) );
1274 return !status;
1278 /**************************************************************************
1279 * UnlockFileEx (KERNEL32.@)
1281 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1282 LPOVERLAPPED overlapped )
1284 if (reserved)
1286 SetLastError( ERROR_INVALID_PARAMETER );
1287 return FALSE;
1289 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1291 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1295 /*************************************************************************
1296 * SetHandleCount (KERNEL32.@)
1298 UINT WINAPI SetHandleCount( UINT count )
1300 return count;
1304 /**************************************************************************
1305 * Operations on file names *
1306 **************************************************************************/
1309 /*************************************************************************
1310 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1312 * Creates or opens an object, and returns a handle that can be used to
1313 * access that object.
1315 * PARAMS
1317 * filename [in] pointer to filename to be accessed
1318 * access [in] access mode requested
1319 * sharing [in] share mode
1320 * sa [in] pointer to security attributes
1321 * creation [in] how to create the file
1322 * attributes [in] attributes for newly created file
1323 * template [in] handle to file with extended attributes to copy
1325 * RETURNS
1326 * Success: Open handle to specified file
1327 * Failure: INVALID_HANDLE_VALUE
1329 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1330 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1331 DWORD attributes, HANDLE template )
1333 NTSTATUS status;
1334 UINT options;
1335 OBJECT_ATTRIBUTES attr;
1336 UNICODE_STRING nameW;
1337 IO_STATUS_BLOCK io;
1338 HANDLE ret;
1339 DWORD dosdev;
1340 const WCHAR *vxd_name = NULL;
1341 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1342 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1343 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1344 SECURITY_QUALITY_OF_SERVICE qos;
1346 static const UINT nt_disposition[5] =
1348 FILE_CREATE, /* CREATE_NEW */
1349 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1350 FILE_OPEN, /* OPEN_EXISTING */
1351 FILE_OPEN_IF, /* OPEN_ALWAYS */
1352 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1356 /* sanity checks */
1358 if (!filename || !filename[0])
1360 SetLastError( ERROR_PATH_NOT_FOUND );
1361 return INVALID_HANDLE_VALUE;
1364 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1365 (access & GENERIC_READ)?"GENERIC_READ ":"",
1366 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1367 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1368 (!access)?"QUERY_ACCESS ":"",
1369 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1370 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1371 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1372 creation, attributes);
1374 /* Open a console for CONIN$ or CONOUT$ */
1376 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1378 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1379 creation ? OPEN_EXISTING : 0);
1380 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1381 goto done;
1384 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1386 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1387 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1389 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1390 !strncmpiW( filename + 4, pipeW, 5 ) ||
1391 !strncmpiW( filename + 4, mailslotW, 9 ))
1393 dosdev = 0;
1395 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1397 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1399 else if (GetVersion() & 0x80000000)
1401 vxd_name = filename + 4;
1402 if (!creation) creation = OPEN_EXISTING;
1405 else dosdev = RtlIsDosDeviceName_U( filename );
1407 if (dosdev)
1409 static const WCHAR conW[] = {'C','O','N'};
1411 if (LOWORD(dosdev) == sizeof(conW) &&
1412 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1414 switch (access & (GENERIC_READ|GENERIC_WRITE))
1416 case GENERIC_READ:
1417 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1418 goto done;
1419 case GENERIC_WRITE:
1420 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1421 goto done;
1422 default:
1423 SetLastError( ERROR_FILE_NOT_FOUND );
1424 return INVALID_HANDLE_VALUE;
1429 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1431 SetLastError( ERROR_INVALID_PARAMETER );
1432 return INVALID_HANDLE_VALUE;
1435 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1437 SetLastError( ERROR_PATH_NOT_FOUND );
1438 return INVALID_HANDLE_VALUE;
1441 /* now call NtCreateFile */
1443 options = 0;
1444 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1445 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1446 else
1447 options |= FILE_NON_DIRECTORY_FILE;
1448 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1450 options |= FILE_DELETE_ON_CLOSE;
1451 access |= DELETE;
1453 if (attributes & FILE_FLAG_NO_BUFFERING)
1454 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1455 if (!(attributes & FILE_FLAG_OVERLAPPED))
1456 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1457 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1458 options |= FILE_RANDOM_ACCESS;
1459 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1461 attr.Length = sizeof(attr);
1462 attr.RootDirectory = 0;
1463 attr.Attributes = OBJ_CASE_INSENSITIVE;
1464 attr.ObjectName = &nameW;
1465 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1466 if (attributes & SECURITY_SQOS_PRESENT)
1468 qos.Length = sizeof(qos);
1469 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1470 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1471 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1472 attr.SecurityQualityOfService = &qos;
1474 else
1475 attr.SecurityQualityOfService = NULL;
1477 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1479 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1480 sharing, nt_disposition[creation - CREATE_NEW],
1481 options, NULL, 0 );
1482 if (status)
1484 if (vxd_name && vxd_name[0])
1486 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1487 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1488 "__wine_vxd_open" );
1489 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1492 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1493 ret = INVALID_HANDLE_VALUE;
1495 /* In the case file creation was rejected due to CREATE_NEW flag
1496 * was specified and file with that name already exists, correct
1497 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1498 * Note: RtlNtStatusToDosError is not the subject to blame here.
1500 if (status == STATUS_OBJECT_NAME_COLLISION)
1501 SetLastError( ERROR_FILE_EXISTS );
1502 else
1503 SetLastError( RtlNtStatusToDosError(status) );
1505 else
1507 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1508 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1509 SetLastError( ERROR_ALREADY_EXISTS );
1510 else
1511 SetLastError( 0 );
1513 RtlFreeUnicodeString( &nameW );
1515 done:
1516 if (!ret) ret = INVALID_HANDLE_VALUE;
1517 TRACE("returning %p\n", ret);
1518 return ret;
1523 /*************************************************************************
1524 * CreateFileA (KERNEL32.@)
1526 * See CreateFileW.
1528 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1529 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1530 DWORD attributes, HANDLE template)
1532 WCHAR *nameW;
1534 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1535 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1538 /*************************************************************************
1539 * CreateFile2 (KERNEL32.@)
1541 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1542 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1544 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1545 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1546 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1548 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1550 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1553 /***********************************************************************
1554 * DeleteFileW (KERNEL32.@)
1556 * Delete a file.
1558 * PARAMS
1559 * path [I] Path to the file to delete.
1561 * RETURNS
1562 * Success: TRUE.
1563 * Failure: FALSE, check GetLastError().
1565 BOOL WINAPI DeleteFileW( LPCWSTR path )
1567 UNICODE_STRING nameW;
1568 OBJECT_ATTRIBUTES attr;
1569 NTSTATUS status;
1570 HANDLE hFile;
1571 IO_STATUS_BLOCK io;
1573 TRACE("%s\n", debugstr_w(path) );
1575 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1577 SetLastError( ERROR_PATH_NOT_FOUND );
1578 return FALSE;
1581 attr.Length = sizeof(attr);
1582 attr.RootDirectory = 0;
1583 attr.Attributes = OBJ_CASE_INSENSITIVE;
1584 attr.ObjectName = &nameW;
1585 attr.SecurityDescriptor = NULL;
1586 attr.SecurityQualityOfService = NULL;
1588 status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1589 &attr, &io, NULL, 0,
1590 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1591 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1592 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1594 RtlFreeUnicodeString( &nameW );
1595 if (status)
1597 SetLastError( RtlNtStatusToDosError(status) );
1598 return FALSE;
1600 return TRUE;
1604 /***********************************************************************
1605 * DeleteFileA (KERNEL32.@)
1607 * See DeleteFileW.
1609 BOOL WINAPI DeleteFileA( LPCSTR path )
1611 WCHAR *pathW;
1613 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1614 return DeleteFileW( pathW );
1618 /**************************************************************************
1619 * ReplaceFileW (KERNEL32.@)
1620 * ReplaceFile (KERNEL32.@)
1622 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1623 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1624 LPVOID lpExclude, LPVOID lpReserved)
1626 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1627 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1628 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1629 DWORD error = ERROR_SUCCESS;
1630 UINT replaced_flags;
1631 BOOL ret = FALSE;
1632 NTSTATUS status;
1633 IO_STATUS_BLOCK io;
1634 OBJECT_ATTRIBUTES attr;
1636 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1637 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1638 dwReplaceFlags, lpExclude, lpReserved);
1640 if (dwReplaceFlags)
1641 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1643 /* First two arguments are mandatory */
1644 if (!lpReplacedFileName || !lpReplacementFileName)
1646 SetLastError(ERROR_INVALID_PARAMETER);
1647 return FALSE;
1650 unix_replaced_name.Buffer = NULL;
1651 unix_replacement_name.Buffer = NULL;
1652 unix_backup_name.Buffer = NULL;
1654 attr.Length = sizeof(attr);
1655 attr.RootDirectory = 0;
1656 attr.Attributes = OBJ_CASE_INSENSITIVE;
1657 attr.ObjectName = NULL;
1658 attr.SecurityDescriptor = NULL;
1659 attr.SecurityQualityOfService = NULL;
1661 /* Open the "replaced" file for reading and writing */
1662 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1664 error = ERROR_PATH_NOT_FOUND;
1665 goto fail;
1667 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1668 attr.ObjectName = &nt_replaced_name;
1669 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1670 &attr, &io,
1671 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1672 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1673 if (status == STATUS_SUCCESS)
1674 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1675 RtlFreeUnicodeString(&nt_replaced_name);
1676 if (status != STATUS_SUCCESS)
1678 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1679 error = ERROR_FILE_NOT_FOUND;
1680 else
1681 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1682 goto fail;
1686 * Open the replacement file for reading, writing, and deleting
1687 * (writing and deleting are needed when finished)
1689 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1691 error = ERROR_PATH_NOT_FOUND;
1692 goto fail;
1694 attr.ObjectName = &nt_replacement_name;
1695 status = NtOpenFile(&hReplacement,
1696 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1697 &attr, &io, 0,
1698 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1699 if (status == STATUS_SUCCESS)
1700 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1701 RtlFreeUnicodeString(&nt_replacement_name);
1702 if (status != STATUS_SUCCESS)
1704 error = RtlNtStatusToDosError(status);
1705 goto fail;
1708 /* If the user wants a backup then that needs to be performed first */
1709 if (lpBackupFileName)
1711 UNICODE_STRING nt_backup_name;
1712 FILE_BASIC_INFORMATION replaced_info;
1714 /* Obtain the file attributes from the "replaced" file */
1715 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1716 sizeof(replaced_info),
1717 FileBasicInformation);
1718 if (status != STATUS_SUCCESS)
1720 error = RtlNtStatusToDosError(status);
1721 goto fail;
1724 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1726 error = ERROR_PATH_NOT_FOUND;
1727 goto fail;
1729 attr.ObjectName = &nt_backup_name;
1730 /* Open the backup with permissions to write over it */
1731 status = NtCreateFile(&hBackup, GENERIC_WRITE,
1732 &attr, &io, NULL, replaced_info.FileAttributes,
1733 FILE_SHARE_WRITE, FILE_OPEN_IF,
1734 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1735 NULL, 0);
1736 if (status == STATUS_SUCCESS)
1737 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1738 RtlFreeUnicodeString(&nt_backup_name);
1739 if (status != STATUS_SUCCESS)
1741 error = RtlNtStatusToDosError(status);
1742 goto fail;
1745 /* If an existing backup exists then copy over it */
1746 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1748 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1749 goto fail;
1754 * Now that the backup has been performed (if requested), copy the replacement
1755 * into place
1757 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1759 if (errno == EACCES)
1761 /* Inappropriate permissions on "replaced", rename will fail */
1762 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1763 goto fail;
1765 /* on failure we need to indicate whether a backup was made */
1766 if (!lpBackupFileName)
1767 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1768 else
1769 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1770 goto fail;
1772 /* Success! */
1773 ret = TRUE;
1775 /* Perform resource cleanup */
1776 fail:
1777 if (hBackup) CloseHandle(hBackup);
1778 if (hReplaced) CloseHandle(hReplaced);
1779 if (hReplacement) CloseHandle(hReplacement);
1780 RtlFreeAnsiString(&unix_backup_name);
1781 RtlFreeAnsiString(&unix_replacement_name);
1782 RtlFreeAnsiString(&unix_replaced_name);
1784 /* If there was an error, set the error code */
1785 if(!ret)
1786 SetLastError(error);
1787 return ret;
1791 /**************************************************************************
1792 * ReplaceFileA (KERNEL32.@)
1794 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1795 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1796 LPVOID lpExclude, LPVOID lpReserved)
1798 WCHAR *replacedW, *replacementW, *backupW = NULL;
1799 BOOL ret;
1801 /* This function only makes sense when the first two parameters are defined */
1802 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1804 SetLastError(ERROR_INVALID_PARAMETER);
1805 return FALSE;
1807 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1809 HeapFree( GetProcessHeap(), 0, replacedW );
1810 SetLastError(ERROR_INVALID_PARAMETER);
1811 return FALSE;
1813 /* The backup parameter, however, is optional */
1814 if (lpBackupFileName)
1816 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1818 HeapFree( GetProcessHeap(), 0, replacedW );
1819 HeapFree( GetProcessHeap(), 0, replacementW );
1820 SetLastError(ERROR_INVALID_PARAMETER);
1821 return FALSE;
1824 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1825 HeapFree( GetProcessHeap(), 0, replacedW );
1826 HeapFree( GetProcessHeap(), 0, replacementW );
1827 HeapFree( GetProcessHeap(), 0, backupW );
1828 return ret;
1832 /*************************************************************************
1833 * FindFirstFileExW (KERNEL32.@)
1835 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1836 * results as FindExSearchNameMatch
1838 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1839 LPVOID data, FINDEX_SEARCH_OPS search_op,
1840 LPVOID filter, DWORD flags)
1842 WCHAR *mask, *p;
1843 FIND_FIRST_INFO *info = NULL;
1844 UNICODE_STRING nt_name;
1845 OBJECT_ATTRIBUTES attr;
1846 IO_STATUS_BLOCK io;
1847 NTSTATUS status;
1848 DWORD device = 0;
1850 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1852 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1853 || flags != 0)
1855 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1856 return INVALID_HANDLE_VALUE;
1858 if (level != FindExInfoStandard)
1860 FIXME("info level %d not implemented\n", level );
1861 return INVALID_HANDLE_VALUE;
1864 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1866 SetLastError( ERROR_PATH_NOT_FOUND );
1867 return INVALID_HANDLE_VALUE;
1870 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1872 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1873 goto error;
1876 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1878 static const WCHAR dotW[] = {'.',0};
1879 WCHAR *dir = NULL;
1881 /* we still need to check that the directory can be opened */
1883 if (HIWORD(device))
1885 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1887 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1888 goto error;
1890 memcpy( dir, filename, HIWORD(device) );
1891 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1893 RtlFreeUnicodeString( &nt_name );
1894 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1896 HeapFree( GetProcessHeap(), 0, dir );
1897 SetLastError( ERROR_PATH_NOT_FOUND );
1898 goto error;
1900 HeapFree( GetProcessHeap(), 0, dir );
1901 RtlInitUnicodeString( &info->mask, NULL );
1903 else if (!mask || !*mask)
1905 SetLastError( ERROR_FILE_NOT_FOUND );
1906 goto error;
1908 else
1910 if (!RtlCreateUnicodeString( &info->mask, mask ))
1912 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1913 goto error;
1916 /* truncate dir name before mask */
1917 *mask = 0;
1918 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1921 /* check if path is the root of the drive */
1922 info->is_root = FALSE;
1923 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1924 if (p[0] && p[1] == ':')
1926 p += 2;
1927 while (*p == '\\') p++;
1928 info->is_root = (*p == 0);
1931 attr.Length = sizeof(attr);
1932 attr.RootDirectory = 0;
1933 attr.Attributes = OBJ_CASE_INSENSITIVE;
1934 attr.ObjectName = &nt_name;
1935 attr.SecurityDescriptor = NULL;
1936 attr.SecurityQualityOfService = NULL;
1938 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1939 FILE_SHARE_READ | FILE_SHARE_WRITE,
1940 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1942 if (status != STATUS_SUCCESS)
1944 RtlFreeUnicodeString( &info->mask );
1945 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1946 SetLastError( ERROR_PATH_NOT_FOUND );
1947 else
1948 SetLastError( RtlNtStatusToDosError(status) );
1949 goto error;
1952 RtlInitializeCriticalSection( &info->cs );
1953 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1954 info->path = nt_name;
1955 info->magic = FIND_FIRST_MAGIC;
1956 info->data_pos = 0;
1957 info->data_len = 0;
1958 info->data_size = 0;
1959 info->data = NULL;
1960 info->search_op = search_op;
1962 if (device)
1964 WIN32_FIND_DATAW *wfd = data;
1966 memset( wfd, 0, sizeof(*wfd) );
1967 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1968 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1969 CloseHandle( info->handle );
1970 info->handle = 0;
1972 else
1974 IO_STATUS_BLOCK io;
1975 BOOL has_wildcard = strpbrkW( info->mask.Buffer, wildcardsW ) != NULL;
1977 info->data_size = has_wildcard ? 8192 : max_entry_size;
1979 while (info->data_size)
1981 if (!(info->data = HeapAlloc( GetProcessHeap(), 0, info->data_size )))
1983 FindClose( info );
1984 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1985 return INVALID_HANDLE_VALUE;
1988 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
1989 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
1990 if (io.u.Status)
1992 FindClose( info );
1993 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
1994 return INVALID_HANDLE_VALUE;
1997 if (io.Information < info->data_size - max_entry_size)
1999 info->data_size = 0; /* we read everything */
2001 else if (info->data_size < 1024 * 1024)
2003 HeapFree( GetProcessHeap(), 0, info->data );
2004 info->data_size *= 2;
2006 else break;
2009 info->data_len = io.Information;
2010 if (!info->data_size && has_wildcard) /* release unused buffer space */
2011 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, info->data, info->data_len );
2013 if (!FindNextFileW( info, data ))
2015 TRACE( "%s not found\n", debugstr_w(filename) );
2016 FindClose( info );
2017 SetLastError( ERROR_FILE_NOT_FOUND );
2018 return INVALID_HANDLE_VALUE;
2020 if (!has_wildcard) /* we can't find two files with the same name */
2022 CloseHandle( info->handle );
2023 HeapFree( GetProcessHeap(), 0, info->data );
2024 info->handle = 0;
2025 info->data = NULL;
2028 return info;
2030 error:
2031 HeapFree( GetProcessHeap(), 0, info );
2032 RtlFreeUnicodeString( &nt_name );
2033 return INVALID_HANDLE_VALUE;
2037 /*************************************************************************
2038 * FindNextFileW (KERNEL32.@)
2040 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2042 FIND_FIRST_INFO *info;
2043 FILE_BOTH_DIR_INFORMATION *dir_info;
2044 BOOL ret = FALSE;
2046 TRACE("%p %p\n", handle, data);
2048 if (!handle || handle == INVALID_HANDLE_VALUE)
2050 SetLastError( ERROR_INVALID_HANDLE );
2051 return ret;
2053 info = handle;
2054 if (info->magic != FIND_FIRST_MAGIC)
2056 SetLastError( ERROR_INVALID_HANDLE );
2057 return ret;
2060 RtlEnterCriticalSection( &info->cs );
2062 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2063 else for (;;)
2065 if (info->data_pos >= info->data_len) /* need to read some more data */
2067 IO_STATUS_BLOCK io;
2069 if (info->data_size)
2070 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2071 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
2072 else
2073 io.u.Status = STATUS_NO_MORE_FILES;
2075 if (io.u.Status)
2077 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2078 if (io.u.Status == STATUS_NO_MORE_FILES)
2080 CloseHandle( info->handle );
2081 HeapFree( GetProcessHeap(), 0, info->data );
2082 info->handle = 0;
2083 info->data = NULL;
2085 break;
2087 info->data_len = io.Information;
2088 info->data_pos = 0;
2091 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2093 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2094 else info->data_pos = info->data_len;
2096 /* don't return '.' and '..' in the root of the drive */
2097 if (info->is_root)
2099 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2100 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2101 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2104 /* check for dir symlink */
2105 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2106 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2107 strpbrkW( info->mask.Buffer, wildcardsW ))
2109 if (!check_dir_symlink( info, dir_info )) continue;
2112 data->dwFileAttributes = dir_info->FileAttributes;
2113 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2114 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2115 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2116 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2117 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2118 data->dwReserved0 = 0;
2119 data->dwReserved1 = 0;
2121 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2122 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2123 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2124 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2126 TRACE("returning %s (%s)\n",
2127 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2129 ret = TRUE;
2130 break;
2133 RtlLeaveCriticalSection( &info->cs );
2134 return ret;
2138 /*************************************************************************
2139 * FindClose (KERNEL32.@)
2141 BOOL WINAPI FindClose( HANDLE handle )
2143 FIND_FIRST_INFO *info = handle;
2145 if (!handle || handle == INVALID_HANDLE_VALUE)
2147 SetLastError( ERROR_INVALID_HANDLE );
2148 return FALSE;
2151 __TRY
2153 if (info->magic == FIND_FIRST_MAGIC)
2155 RtlEnterCriticalSection( &info->cs );
2156 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2158 info->magic = 0;
2159 if (info->handle) CloseHandle( info->handle );
2160 info->handle = 0;
2161 RtlFreeUnicodeString( &info->mask );
2162 info->mask.Buffer = NULL;
2163 RtlFreeUnicodeString( &info->path );
2164 info->data_pos = 0;
2165 info->data_len = 0;
2166 HeapFree( GetProcessHeap(), 0, info->data );
2167 RtlLeaveCriticalSection( &info->cs );
2168 info->cs.DebugInfo->Spare[0] = 0;
2169 RtlDeleteCriticalSection( &info->cs );
2170 HeapFree( GetProcessHeap(), 0, info );
2174 __EXCEPT_PAGE_FAULT
2176 WARN("Illegal handle %p\n", handle);
2177 SetLastError( ERROR_INVALID_HANDLE );
2178 return FALSE;
2180 __ENDTRY
2182 return TRUE;
2186 /*************************************************************************
2187 * FindFirstFileA (KERNEL32.@)
2189 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2191 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2192 FindExSearchNameMatch, NULL, 0);
2195 /*************************************************************************
2196 * FindFirstFileExA (KERNEL32.@)
2198 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2199 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2200 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2202 HANDLE handle;
2203 WIN32_FIND_DATAA *dataA;
2204 WIN32_FIND_DATAW dataW;
2205 WCHAR *nameW;
2207 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2209 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2210 if (handle == INVALID_HANDLE_VALUE) return handle;
2212 dataA = lpFindFileData;
2213 dataA->dwFileAttributes = dataW.dwFileAttributes;
2214 dataA->ftCreationTime = dataW.ftCreationTime;
2215 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2216 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2217 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2218 dataA->nFileSizeLow = dataW.nFileSizeLow;
2219 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2220 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2221 sizeof(dataA->cAlternateFileName) );
2222 return handle;
2226 /*************************************************************************
2227 * FindFirstFileW (KERNEL32.@)
2229 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2231 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2232 FindExSearchNameMatch, NULL, 0);
2236 /*************************************************************************
2237 * FindNextFileA (KERNEL32.@)
2239 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2241 WIN32_FIND_DATAW dataW;
2243 if (!FindNextFileW( handle, &dataW )) return FALSE;
2244 data->dwFileAttributes = dataW.dwFileAttributes;
2245 data->ftCreationTime = dataW.ftCreationTime;
2246 data->ftLastAccessTime = dataW.ftLastAccessTime;
2247 data->ftLastWriteTime = dataW.ftLastWriteTime;
2248 data->nFileSizeHigh = dataW.nFileSizeHigh;
2249 data->nFileSizeLow = dataW.nFileSizeLow;
2250 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2251 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2252 sizeof(data->cAlternateFileName) );
2253 return TRUE;
2257 /**************************************************************************
2258 * GetFileAttributesW (KERNEL32.@)
2260 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2262 FILE_BASIC_INFORMATION info;
2263 UNICODE_STRING nt_name;
2264 OBJECT_ATTRIBUTES attr;
2265 NTSTATUS status;
2267 TRACE("%s\n", debugstr_w(name));
2269 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2271 SetLastError( ERROR_PATH_NOT_FOUND );
2272 return INVALID_FILE_ATTRIBUTES;
2275 attr.Length = sizeof(attr);
2276 attr.RootDirectory = 0;
2277 attr.Attributes = OBJ_CASE_INSENSITIVE;
2278 attr.ObjectName = &nt_name;
2279 attr.SecurityDescriptor = NULL;
2280 attr.SecurityQualityOfService = NULL;
2282 status = NtQueryAttributesFile( &attr, &info );
2283 RtlFreeUnicodeString( &nt_name );
2285 if (status == STATUS_SUCCESS) return info.FileAttributes;
2287 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2288 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2290 SetLastError( RtlNtStatusToDosError(status) );
2291 return INVALID_FILE_ATTRIBUTES;
2295 /**************************************************************************
2296 * GetFileAttributesA (KERNEL32.@)
2298 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2300 WCHAR *nameW;
2302 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2303 return GetFileAttributesW( nameW );
2307 /**************************************************************************
2308 * SetFileAttributesW (KERNEL32.@)
2310 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2312 UNICODE_STRING nt_name;
2313 OBJECT_ATTRIBUTES attr;
2314 IO_STATUS_BLOCK io;
2315 NTSTATUS status;
2316 HANDLE handle;
2318 TRACE("%s %x\n", debugstr_w(name), attributes);
2320 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2322 SetLastError( ERROR_PATH_NOT_FOUND );
2323 return FALSE;
2326 attr.Length = sizeof(attr);
2327 attr.RootDirectory = 0;
2328 attr.Attributes = OBJ_CASE_INSENSITIVE;
2329 attr.ObjectName = &nt_name;
2330 attr.SecurityDescriptor = NULL;
2331 attr.SecurityQualityOfService = NULL;
2333 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2334 RtlFreeUnicodeString( &nt_name );
2336 if (status == STATUS_SUCCESS)
2338 FILE_BASIC_INFORMATION info;
2340 memset( &info, 0, sizeof(info) );
2341 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2342 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2343 NtClose( handle );
2346 if (status == STATUS_SUCCESS) return TRUE;
2347 SetLastError( RtlNtStatusToDosError(status) );
2348 return FALSE;
2352 /**************************************************************************
2353 * SetFileAttributesA (KERNEL32.@)
2355 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2357 WCHAR *nameW;
2359 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2360 return SetFileAttributesW( nameW, attributes );
2364 /**************************************************************************
2365 * GetFileAttributesExW (KERNEL32.@)
2367 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2369 FILE_NETWORK_OPEN_INFORMATION info;
2370 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2371 UNICODE_STRING nt_name;
2372 OBJECT_ATTRIBUTES attr;
2373 NTSTATUS status;
2375 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2377 if (level != GetFileExInfoStandard)
2379 SetLastError( ERROR_INVALID_PARAMETER );
2380 return FALSE;
2383 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2385 SetLastError( ERROR_PATH_NOT_FOUND );
2386 return FALSE;
2389 attr.Length = sizeof(attr);
2390 attr.RootDirectory = 0;
2391 attr.Attributes = OBJ_CASE_INSENSITIVE;
2392 attr.ObjectName = &nt_name;
2393 attr.SecurityDescriptor = NULL;
2394 attr.SecurityQualityOfService = NULL;
2396 status = NtQueryFullAttributesFile( &attr, &info );
2397 RtlFreeUnicodeString( &nt_name );
2399 if (status != STATUS_SUCCESS)
2401 SetLastError( RtlNtStatusToDosError(status) );
2402 return FALSE;
2405 data->dwFileAttributes = info.FileAttributes;
2406 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2407 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2408 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2409 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2410 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2411 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2412 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2413 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2414 return TRUE;
2418 /**************************************************************************
2419 * GetFileAttributesExA (KERNEL32.@)
2421 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2423 WCHAR *nameW;
2425 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2426 return GetFileAttributesExW( nameW, level, ptr );
2430 /******************************************************************************
2431 * GetCompressedFileSizeW (KERNEL32.@)
2433 * Get the actual number of bytes used on disk.
2435 * RETURNS
2436 * Success: Low-order doubleword of number of bytes
2437 * Failure: INVALID_FILE_SIZE
2439 DWORD WINAPI GetCompressedFileSizeW(
2440 LPCWSTR name, /* [in] Pointer to name of file */
2441 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2443 UNICODE_STRING nt_name;
2444 OBJECT_ATTRIBUTES attr;
2445 IO_STATUS_BLOCK io;
2446 NTSTATUS status;
2447 HANDLE handle;
2448 DWORD ret = INVALID_FILE_SIZE;
2450 TRACE("%s %p\n", debugstr_w(name), size_high);
2452 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2454 SetLastError( ERROR_PATH_NOT_FOUND );
2455 return INVALID_FILE_SIZE;
2458 attr.Length = sizeof(attr);
2459 attr.RootDirectory = 0;
2460 attr.Attributes = OBJ_CASE_INSENSITIVE;
2461 attr.ObjectName = &nt_name;
2462 attr.SecurityDescriptor = NULL;
2463 attr.SecurityQualityOfService = NULL;
2465 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2466 RtlFreeUnicodeString( &nt_name );
2468 if (status == STATUS_SUCCESS)
2470 /* we don't support compressed files, simply return the file size */
2471 ret = GetFileSize( handle, size_high );
2472 NtClose( handle );
2474 else SetLastError( RtlNtStatusToDosError(status) );
2476 return ret;
2480 /******************************************************************************
2481 * GetCompressedFileSizeA (KERNEL32.@)
2483 * See GetCompressedFileSizeW.
2485 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2487 WCHAR *nameW;
2489 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2490 return GetCompressedFileSizeW( nameW, size_high );
2494 /***********************************************************************
2495 * OpenVxDHandle (KERNEL32.@)
2497 * This function is supposed to return the corresponding Ring 0
2498 * ("kernel") handle for a Ring 3 handle in Win9x.
2499 * Evidently, Wine will have problems with this. But we try anyway,
2500 * maybe it helps...
2502 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2504 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2505 return hHandleRing3;
2509 /****************************************************************************
2510 * DeviceIoControl (KERNEL32.@)
2512 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2513 LPVOID lpvInBuffer, DWORD cbInBuffer,
2514 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2515 LPDWORD lpcbBytesReturned,
2516 LPOVERLAPPED lpOverlapped)
2518 NTSTATUS status;
2520 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2521 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2522 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2524 /* Check if this is a user defined control code for a VxD */
2526 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2528 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2529 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2530 DeviceIoProc proc = NULL;
2532 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2533 "__wine_vxd_get_proc" );
2534 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2535 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2536 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2539 /* Not a VxD, let ntdll handle it */
2541 if (lpOverlapped)
2543 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2544 lpOverlapped->Internal = STATUS_PENDING;
2545 lpOverlapped->InternalHigh = 0;
2546 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2547 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2548 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2549 dwIoControlCode, lpvInBuffer, cbInBuffer,
2550 lpvOutBuffer, cbOutBuffer);
2551 else
2552 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2553 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2554 dwIoControlCode, lpvInBuffer, cbInBuffer,
2555 lpvOutBuffer, cbOutBuffer);
2556 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2558 else
2560 IO_STATUS_BLOCK iosb;
2562 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2563 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2564 dwIoControlCode, lpvInBuffer, cbInBuffer,
2565 lpvOutBuffer, cbOutBuffer);
2566 else
2567 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2568 dwIoControlCode, lpvInBuffer, cbInBuffer,
2569 lpvOutBuffer, cbOutBuffer);
2570 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2572 if (status) SetLastError( RtlNtStatusToDosError(status) );
2573 return !status;
2577 /***********************************************************************
2578 * OpenFile (KERNEL32.@)
2580 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2582 HANDLE handle;
2583 FILETIME filetime;
2584 WORD filedatetime[2];
2586 if (!ofs) return HFILE_ERROR;
2588 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2589 ((mode & 0x3 )==OF_READ)?"OF_READ":
2590 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2591 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2592 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2593 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2594 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2595 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2596 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2597 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2598 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2599 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2600 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2601 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2602 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2603 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2604 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2605 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2609 ofs->cBytes = sizeof(OFSTRUCT);
2610 ofs->nErrCode = 0;
2611 if (mode & OF_REOPEN) name = ofs->szPathName;
2613 if (!name) return HFILE_ERROR;
2615 TRACE("%s %04x\n", name, mode );
2617 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2618 Are there any cases where getting the path here is wrong?
2619 Uwe Bonnes 1997 Apr 2 */
2620 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2622 /* OF_PARSE simply fills the structure */
2624 if (mode & OF_PARSE)
2626 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2627 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2628 return 0;
2631 /* OF_CREATE is completely different from all other options, so
2632 handle it first */
2634 if (mode & OF_CREATE)
2636 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2637 goto error;
2639 else
2641 /* Now look for the file */
2643 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2644 goto error;
2646 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2648 if (mode & OF_DELETE)
2650 if (!DeleteFileA( ofs->szPathName )) goto error;
2651 TRACE("(%s): OF_DELETE return = OK\n", name);
2652 return TRUE;
2655 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2656 if (handle == INVALID_HANDLE_VALUE) goto error;
2658 GetFileTime( handle, NULL, NULL, &filetime );
2659 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2660 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2662 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2664 CloseHandle( handle );
2665 WARN("(%s): OF_VERIFY failed\n", name );
2666 /* FIXME: what error here? */
2667 SetLastError( ERROR_FILE_NOT_FOUND );
2668 goto error;
2671 ofs->Reserved1 = filedatetime[0];
2672 ofs->Reserved2 = filedatetime[1];
2674 TRACE("(%s): OK, return = %p\n", name, handle );
2675 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2677 CloseHandle( handle );
2678 return TRUE;
2680 return HandleToLong(handle);
2682 error: /* We get here if there was an error opening the file */
2683 ofs->nErrCode = GetLastError();
2684 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2685 return HFILE_ERROR;
2689 /***********************************************************************
2690 * OpenFileById (KERNEL32.@)
2692 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2693 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2695 UINT options;
2696 HANDLE result;
2697 OBJECT_ATTRIBUTES attr;
2698 NTSTATUS status;
2699 IO_STATUS_BLOCK io;
2700 UNICODE_STRING objectName;
2702 if (!id)
2704 SetLastError( ERROR_INVALID_PARAMETER );
2705 return INVALID_HANDLE_VALUE;
2708 options = FILE_OPEN_BY_FILE_ID;
2709 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2710 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2711 else
2712 options |= FILE_NON_DIRECTORY_FILE;
2713 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2714 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2715 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2716 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2718 objectName.Length = sizeof(ULONGLONG);
2719 objectName.Buffer = (WCHAR *)&id->u.FileId;
2720 attr.Length = sizeof(attr);
2721 attr.RootDirectory = handle;
2722 attr.Attributes = 0;
2723 attr.ObjectName = &objectName;
2724 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2725 attr.SecurityQualityOfService = NULL;
2726 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2728 status = NtCreateFile( &result, access, &attr, &io, NULL, flags,
2729 share, OPEN_EXISTING, options, NULL, 0 );
2730 if (status != STATUS_SUCCESS)
2732 SetLastError( RtlNtStatusToDosError( status ) );
2733 return INVALID_HANDLE_VALUE;
2735 return result;
2739 /***********************************************************************
2740 * K32EnumDeviceDrivers (KERNEL32.@)
2742 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2744 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2746 if (needed)
2747 *needed = 0;
2749 return TRUE;
2752 /***********************************************************************
2753 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2755 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2757 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2759 if (base_name && size)
2760 base_name[0] = '\0';
2762 return 0;
2765 /***********************************************************************
2766 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2768 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2770 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2772 if (base_name && size)
2773 base_name[0] = '\0';
2775 return 0;
2778 /***********************************************************************
2779 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2781 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2783 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2785 if (file_name && size)
2786 file_name[0] = '\0';
2788 return 0;
2791 /***********************************************************************
2792 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2794 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2796 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2798 if (file_name && size)
2799 file_name[0] = '\0';
2801 return 0;