d3d8: Get rid of the format switching code in d3d8_device_CopyRects().
[wine.git] / dlls / kernel32 / file.c
blobcf683df95c0c6f0431a80c6180ca4265685e1e73
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 void *cvalue = NULL;
378 NTSTATUS status;
380 TRACE( "(%p %p %u %p)\n", file, segments, count, overlapped );
382 offset.u.LowPart = overlapped->u.s.Offset;
383 offset.u.HighPart = overlapped->u.s.OffsetHigh;
384 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
385 io_status = (PIO_STATUS_BLOCK)overlapped;
386 io_status->u.Status = STATUS_PENDING;
387 io_status->Information = 0;
389 status = NtReadFileScatter( file, overlapped->hEvent, NULL, cvalue, io_status,
390 segments, count, &offset, NULL );
391 if (status) SetLastError( RtlNtStatusToDosError(status) );
392 return !status;
396 /***********************************************************************
397 * ReadFile (KERNEL32.@)
399 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
400 LPDWORD bytesRead, LPOVERLAPPED overlapped )
402 LARGE_INTEGER offset;
403 PLARGE_INTEGER poffset = NULL;
404 IO_STATUS_BLOCK iosb;
405 PIO_STATUS_BLOCK io_status = &iosb;
406 HANDLE hEvent = 0;
407 NTSTATUS status;
408 LPVOID cvalue = NULL;
410 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
411 bytesRead, overlapped );
413 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
415 if (is_console_handle(hFile))
417 DWORD conread, mode;
418 if (!ReadConsoleA(hFile, buffer, bytesToRead, &conread, NULL) ||
419 !GetConsoleMode(hFile, &mode))
420 return FALSE;
421 /* ctrl-Z (26) means end of file on window (if at beginning of buffer)
422 * but Unix uses ctrl-D (4), and ctrl-Z is a bad idea on Unix :-/
423 * So map both ctrl-D ctrl-Z to EOF.
425 if ((mode & ENABLE_PROCESSED_INPUT) && conread > 0 &&
426 (((char*)buffer)[0] == 26 || ((char*)buffer)[0] == 4))
428 conread = 0;
430 if (bytesRead) *bytesRead = conread;
431 return TRUE;
434 if (overlapped != NULL)
436 offset.u.LowPart = overlapped->u.s.Offset;
437 offset.u.HighPart = overlapped->u.s.OffsetHigh;
438 poffset = &offset;
439 hEvent = overlapped->hEvent;
440 io_status = (PIO_STATUS_BLOCK)overlapped;
441 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
443 io_status->u.Status = STATUS_PENDING;
444 io_status->Information = 0;
446 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
448 if (status == STATUS_PENDING && !overlapped)
450 WaitForSingleObject( hFile, INFINITE );
451 status = io_status->u.Status;
454 if (status != STATUS_PENDING && bytesRead)
455 *bytesRead = io_status->Information;
457 if (status == STATUS_END_OF_FILE)
459 if (overlapped != NULL)
461 SetLastError( RtlNtStatusToDosError(status) );
462 return FALSE;
465 else if (status && status != STATUS_TIMEOUT)
467 SetLastError( RtlNtStatusToDosError(status) );
468 return FALSE;
470 return TRUE;
474 /***********************************************************************
475 * WriteFileEx (KERNEL32.@)
477 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
478 LPOVERLAPPED overlapped,
479 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
481 LARGE_INTEGER offset;
482 NTSTATUS status;
483 PIO_STATUS_BLOCK io_status;
485 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
487 if (overlapped == NULL)
489 SetLastError(ERROR_INVALID_PARAMETER);
490 return FALSE;
492 offset.u.LowPart = overlapped->u.s.Offset;
493 offset.u.HighPart = overlapped->u.s.OffsetHigh;
495 io_status = (PIO_STATUS_BLOCK)overlapped;
496 io_status->u.Status = STATUS_PENDING;
497 io_status->Information = 0;
499 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
500 io_status, buffer, bytesToWrite, &offset, NULL);
502 if (status && status != STATUS_PENDING)
504 SetLastError( RtlNtStatusToDosError(status) );
505 return FALSE;
507 return TRUE;
511 /***********************************************************************
512 * WriteFileGather (KERNEL32.@)
514 BOOL WINAPI WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
515 LPDWORD reserved, LPOVERLAPPED overlapped )
517 PIO_STATUS_BLOCK io_status;
518 LARGE_INTEGER offset;
519 void *cvalue = NULL;
520 NTSTATUS status;
522 TRACE( "%p %p %u %p\n", file, segments, count, overlapped );
524 offset.u.LowPart = overlapped->u.s.Offset;
525 offset.u.HighPart = overlapped->u.s.OffsetHigh;
526 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
527 io_status = (PIO_STATUS_BLOCK)overlapped;
528 io_status->u.Status = STATUS_PENDING;
529 io_status->Information = 0;
531 status = NtWriteFileGather( file, overlapped->hEvent, NULL, cvalue, io_status,
532 segments, count, &offset, NULL );
533 if (status) SetLastError( RtlNtStatusToDosError(status) );
534 return !status;
538 /***********************************************************************
539 * WriteFile (KERNEL32.@)
541 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
542 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
544 HANDLE hEvent = NULL;
545 LARGE_INTEGER offset;
546 PLARGE_INTEGER poffset = NULL;
547 NTSTATUS status;
548 IO_STATUS_BLOCK iosb;
549 PIO_STATUS_BLOCK piosb = &iosb;
550 LPVOID cvalue = NULL;
552 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
554 if (is_console_handle(hFile))
555 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
557 if (overlapped)
559 offset.u.LowPart = overlapped->u.s.Offset;
560 offset.u.HighPart = overlapped->u.s.OffsetHigh;
561 poffset = &offset;
562 hEvent = overlapped->hEvent;
563 piosb = (PIO_STATUS_BLOCK)overlapped;
564 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
566 piosb->u.Status = STATUS_PENDING;
567 piosb->Information = 0;
569 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
570 buffer, bytesToWrite, poffset, NULL);
572 if (status == STATUS_PENDING && !overlapped)
574 WaitForSingleObject( hFile, INFINITE );
575 status = piosb->u.Status;
578 if (status != STATUS_PENDING && bytesWritten)
579 *bytesWritten = piosb->Information;
581 if (status && status != STATUS_TIMEOUT)
583 SetLastError( RtlNtStatusToDosError(status) );
584 return FALSE;
586 return TRUE;
590 /***********************************************************************
591 * GetOverlappedResult (KERNEL32.@)
593 * Check the result of an Asynchronous data transfer from a file.
595 * Parameters
596 * HANDLE hFile [in] handle of file to check on
597 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
598 * LPDWORD lpTransferred [in/out] number of bytes transferred
599 * BOOL bWait [in] wait for the transfer to complete ?
601 * RETURNS
602 * TRUE on success
603 * FALSE on failure
605 * If successful (and relevant) lpTransferred will hold the number of
606 * bytes transferred during the async operation.
608 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
609 LPDWORD lpTransferred, BOOL bWait)
611 NTSTATUS status;
613 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
615 status = lpOverlapped->Internal;
616 if (status == STATUS_PENDING)
618 if (!bWait)
620 SetLastError( ERROR_IO_INCOMPLETE );
621 return FALSE;
624 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
625 INFINITE ) == WAIT_FAILED)
626 return FALSE;
627 status = lpOverlapped->Internal;
630 *lpTransferred = lpOverlapped->InternalHigh;
632 if (status) SetLastError( RtlNtStatusToDosError(status) );
633 return !status;
636 /***********************************************************************
637 * CancelIoEx (KERNEL32.@)
639 * Cancels pending I/O operations on a file given the overlapped used.
641 * PARAMS
642 * handle [I] File handle.
643 * lpOverlapped [I,OPT] pointer to overlapped (if null, cancel all)
645 * RETURNS
646 * Success: TRUE.
647 * Failure: FALSE, check GetLastError().
649 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
651 IO_STATUS_BLOCK io_status;
653 NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
654 if (io_status.u.Status)
656 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
657 return FALSE;
659 return TRUE;
662 /***********************************************************************
663 * CancelIo (KERNEL32.@)
665 * Cancels pending I/O operations initiated by the current thread on a file.
667 * PARAMS
668 * handle [I] File handle.
670 * RETURNS
671 * Success: TRUE.
672 * Failure: FALSE, check GetLastError().
674 BOOL WINAPI CancelIo(HANDLE handle)
676 IO_STATUS_BLOCK io_status;
678 NtCancelIoFile(handle, &io_status);
679 if (io_status.u.Status)
681 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
682 return FALSE;
684 return TRUE;
687 /***********************************************************************
688 * _hread (KERNEL32.@)
690 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
692 return _lread( hFile, buffer, count );
696 /***********************************************************************
697 * _hwrite (KERNEL32.@)
699 * experimentation yields that _lwrite:
700 * o truncates the file at the current position with
701 * a 0 len write
702 * o returns 0 on a 0 length write
703 * o works with console handles
706 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
708 DWORD result;
710 TRACE("%d %p %d\n", handle, buffer, count );
712 if (!count)
714 /* Expand or truncate at current position */
715 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
716 return 0;
718 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
719 return HFILE_ERROR;
720 return result;
724 /***********************************************************************
725 * _lclose (KERNEL32.@)
727 HFILE WINAPI _lclose( HFILE hFile )
729 TRACE("handle %d\n", hFile );
730 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
734 /***********************************************************************
735 * _lcreat (KERNEL32.@)
737 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
739 HANDLE hfile;
741 /* Mask off all flags not explicitly allowed by the doc */
742 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
743 TRACE("%s %02x\n", path, attr );
744 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
745 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
746 CREATE_ALWAYS, attr, 0 );
747 return HandleToLong(hfile);
751 /***********************************************************************
752 * _lopen (KERNEL32.@)
754 HFILE WINAPI _lopen( LPCSTR path, INT mode )
756 HANDLE hfile;
758 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
759 hfile = create_file_OF( path, mode & ~OF_CREATE );
760 return HandleToLong(hfile);
763 /***********************************************************************
764 * _lread (KERNEL32.@)
766 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
768 DWORD result;
769 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
770 return HFILE_ERROR;
771 return result;
775 /***********************************************************************
776 * _llseek (KERNEL32.@)
778 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
780 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
784 /***********************************************************************
785 * _lwrite (KERNEL32.@)
787 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
789 return (UINT)_hwrite( hFile, buffer, (LONG)count );
793 /***********************************************************************
794 * FlushFileBuffers (KERNEL32.@)
796 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
798 NTSTATUS nts;
799 IO_STATUS_BLOCK ioblk;
801 if (is_console_handle( hFile ))
803 /* this will fail (as expected) for an output handle */
804 return FlushConsoleInputBuffer( hFile );
806 nts = NtFlushBuffersFile( hFile, &ioblk );
807 if (nts != STATUS_SUCCESS)
809 SetLastError( RtlNtStatusToDosError( nts ) );
810 return FALSE;
813 return TRUE;
817 /***********************************************************************
818 * GetFileType (KERNEL32.@)
820 DWORD WINAPI GetFileType( HANDLE hFile )
822 FILE_FS_DEVICE_INFORMATION info;
823 IO_STATUS_BLOCK io;
824 NTSTATUS status;
826 if (hFile == (HANDLE)STD_INPUT_HANDLE || hFile == (HANDLE)STD_OUTPUT_HANDLE
827 || hFile == (HANDLE)STD_ERROR_HANDLE)
828 hFile = GetStdHandle((DWORD_PTR)hFile);
830 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
832 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
833 if (status != STATUS_SUCCESS)
835 SetLastError( RtlNtStatusToDosError(status) );
836 return FILE_TYPE_UNKNOWN;
839 switch(info.DeviceType)
841 case FILE_DEVICE_NULL:
842 case FILE_DEVICE_SERIAL_PORT:
843 case FILE_DEVICE_PARALLEL_PORT:
844 case FILE_DEVICE_TAPE:
845 case FILE_DEVICE_UNKNOWN:
846 return FILE_TYPE_CHAR;
847 case FILE_DEVICE_NAMED_PIPE:
848 return FILE_TYPE_PIPE;
849 default:
850 return FILE_TYPE_DISK;
855 /***********************************************************************
856 * GetFileInformationByHandle (KERNEL32.@)
858 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
860 FILE_ALL_INFORMATION all_info;
861 IO_STATUS_BLOCK io;
862 NTSTATUS status;
864 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
865 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
866 if (status == STATUS_SUCCESS)
868 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
869 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
870 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
871 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
872 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
873 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
874 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
875 info->dwVolumeSerialNumber = 0; /* FIXME */
876 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
877 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
878 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
879 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
880 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
881 return TRUE;
883 SetLastError( RtlNtStatusToDosError(status) );
884 return FALSE;
888 /***********************************************************************
889 * GetFileInformationByHandleEx (KERNEL32.@)
891 BOOL WINAPI GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
892 LPVOID info, DWORD size )
894 NTSTATUS status;
895 IO_STATUS_BLOCK io;
897 switch (class)
899 case FileBasicInfo:
900 case FileStandardInfo:
901 case FileRenameInfo:
902 case FileDispositionInfo:
903 case FileAllocationInfo:
904 case FileEndOfFileInfo:
905 case FileStreamInfo:
906 case FileCompressionInfo:
907 case FileAttributeTagInfo:
908 case FileIoPriorityHintInfo:
909 case FileRemoteProtocolInfo:
910 case FileFullDirectoryInfo:
911 case FileFullDirectoryRestartInfo:
912 case FileStorageInfo:
913 case FileAlignmentInfo:
914 case FileIdInfo:
915 case FileIdExtdDirectoryInfo:
916 case FileIdExtdDirectoryRestartInfo:
917 FIXME( "%p, %u, %p, %u\n", handle, class, info, size );
918 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
919 return FALSE;
921 case FileNameInfo:
922 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
923 if (status != STATUS_SUCCESS)
925 SetLastError( RtlNtStatusToDosError( status ) );
926 return FALSE;
928 return TRUE;
930 case FileIdBothDirectoryRestartInfo:
931 case FileIdBothDirectoryInfo:
932 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
933 FileIdBothDirectoryInformation, FALSE, NULL,
934 (class == FileIdBothDirectoryRestartInfo) );
935 if (status != STATUS_SUCCESS)
937 SetLastError( RtlNtStatusToDosError( status ) );
938 return FALSE;
940 return TRUE;
942 default:
943 SetLastError( ERROR_INVALID_PARAMETER );
944 return FALSE;
949 /***********************************************************************
950 * GetFileSize (KERNEL32.@)
952 * Retrieve the size of a file.
954 * PARAMS
955 * hFile [I] File to retrieve size of.
956 * filesizehigh [O] On return, the high bits of the file size.
958 * RETURNS
959 * Success: The low bits of the file size.
960 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
961 * check GetLastError() for values other than ERROR_SUCCESS.
963 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
965 LARGE_INTEGER size;
966 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
967 if (filesizehigh) *filesizehigh = size.u.HighPart;
968 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
969 return size.u.LowPart;
973 /***********************************************************************
974 * GetFileSizeEx (KERNEL32.@)
976 * Retrieve the size of a file.
978 * PARAMS
979 * hFile [I] File to retrieve size of.
980 * lpFileSIze [O] On return, the size of the file.
982 * RETURNS
983 * Success: TRUE.
984 * Failure: FALSE, check GetLastError().
986 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
988 FILE_STANDARD_INFORMATION info;
989 IO_STATUS_BLOCK io;
990 NTSTATUS status;
992 if (is_console_handle( hFile ))
994 SetLastError( ERROR_INVALID_HANDLE );
995 return FALSE;
998 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
999 if (status == STATUS_SUCCESS)
1001 *lpFileSize = info.EndOfFile;
1002 return TRUE;
1004 SetLastError( RtlNtStatusToDosError(status) );
1005 return FALSE;
1009 /**************************************************************************
1010 * SetEndOfFile (KERNEL32.@)
1012 * Sets the current position as the end of the file.
1014 * PARAMS
1015 * hFile [I] File handle.
1017 * RETURNS
1018 * Success: TRUE.
1019 * Failure: FALSE, check GetLastError().
1021 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1023 FILE_POSITION_INFORMATION pos;
1024 FILE_END_OF_FILE_INFORMATION eof;
1025 IO_STATUS_BLOCK io;
1026 NTSTATUS status;
1028 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
1029 if (status == STATUS_SUCCESS)
1031 eof.EndOfFile = pos.CurrentByteOffset;
1032 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
1034 if (status == STATUS_SUCCESS) return TRUE;
1035 SetLastError( RtlNtStatusToDosError(status) );
1036 return FALSE;
1039 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1041 FIXME("%p %u %p %u - stub\n", file, class, info, size);
1042 return FALSE;
1045 /***********************************************************************
1046 * SetFilePointer (KERNEL32.@)
1048 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1050 LARGE_INTEGER dist, newpos;
1052 if (highword)
1054 dist.u.LowPart = distance;
1055 dist.u.HighPart = *highword;
1057 else dist.QuadPart = distance;
1059 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1061 if (highword) *highword = newpos.u.HighPart;
1062 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1063 return newpos.u.LowPart;
1067 /***********************************************************************
1068 * SetFilePointerEx (KERNEL32.@)
1070 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1071 LARGE_INTEGER *newpos, DWORD method )
1073 LONGLONG pos;
1074 IO_STATUS_BLOCK io;
1075 FILE_POSITION_INFORMATION info;
1077 switch(method)
1079 case FILE_BEGIN:
1080 pos = distance.QuadPart;
1081 break;
1082 case FILE_CURRENT:
1083 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1084 goto error;
1085 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1086 break;
1087 case FILE_END:
1089 FILE_END_OF_FILE_INFORMATION eof;
1090 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1091 goto error;
1092 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1094 break;
1095 default:
1096 SetLastError( ERROR_INVALID_PARAMETER );
1097 return FALSE;
1100 if (pos < 0)
1102 SetLastError( ERROR_NEGATIVE_SEEK );
1103 return FALSE;
1106 info.CurrentByteOffset.QuadPart = pos;
1107 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1108 goto error;
1109 if (newpos) newpos->QuadPart = pos;
1110 return TRUE;
1112 error:
1113 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1114 return FALSE;
1117 /***********************************************************************
1118 * SetFileValidData (KERNEL32.@)
1120 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1122 FILE_VALID_DATA_LENGTH_INFORMATION info;
1123 IO_STATUS_BLOCK io;
1124 NTSTATUS status;
1126 info.ValidDataLength.QuadPart = ValidDataLength;
1127 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1129 if (status == STATUS_SUCCESS) return TRUE;
1130 SetLastError( RtlNtStatusToDosError(status) );
1131 return FALSE;
1134 /***********************************************************************
1135 * GetFileTime (KERNEL32.@)
1137 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1138 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1140 FILE_BASIC_INFORMATION info;
1141 IO_STATUS_BLOCK io;
1142 NTSTATUS status;
1144 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1145 if (status == STATUS_SUCCESS)
1147 if (lpCreationTime)
1149 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1150 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1152 if (lpLastAccessTime)
1154 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1155 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1157 if (lpLastWriteTime)
1159 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1160 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1162 return TRUE;
1164 SetLastError( RtlNtStatusToDosError(status) );
1165 return FALSE;
1169 /***********************************************************************
1170 * SetFileTime (KERNEL32.@)
1172 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1173 const FILETIME *atime, const FILETIME *mtime )
1175 FILE_BASIC_INFORMATION info;
1176 IO_STATUS_BLOCK io;
1177 NTSTATUS status;
1179 memset( &info, 0, sizeof(info) );
1180 if (ctime)
1182 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1183 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1185 if (atime)
1187 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1188 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1190 if (mtime)
1192 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1193 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1196 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1197 if (status == STATUS_SUCCESS) return TRUE;
1198 SetLastError( RtlNtStatusToDosError(status) );
1199 return FALSE;
1203 /**************************************************************************
1204 * LockFile (KERNEL32.@)
1206 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1207 DWORD count_low, DWORD count_high )
1209 NTSTATUS status;
1210 LARGE_INTEGER count, offset;
1212 TRACE( "%p %x%08x %x%08x\n",
1213 hFile, offset_high, offset_low, count_high, count_low );
1215 count.u.LowPart = count_low;
1216 count.u.HighPart = count_high;
1217 offset.u.LowPart = offset_low;
1218 offset.u.HighPart = offset_high;
1220 status = NtLockFile( hFile, 0, NULL, NULL,
1221 NULL, &offset, &count, NULL, TRUE, TRUE );
1223 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1224 return !status;
1228 /**************************************************************************
1229 * LockFileEx [KERNEL32.@]
1231 * Locks a byte range within an open file for shared or exclusive access.
1233 * RETURNS
1234 * success: TRUE
1235 * failure: FALSE
1237 * NOTES
1238 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1240 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1241 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1243 NTSTATUS status;
1244 LARGE_INTEGER count, offset;
1245 LPVOID cvalue = NULL;
1247 if (reserved)
1249 SetLastError( ERROR_INVALID_PARAMETER );
1250 return FALSE;
1253 TRACE( "%p %x%08x %x%08x flags %x\n",
1254 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1255 count_high, count_low, flags );
1257 count.u.LowPart = count_low;
1258 count.u.HighPart = count_high;
1259 offset.u.LowPart = overlapped->u.s.Offset;
1260 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1262 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1264 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1265 NULL, &offset, &count, NULL,
1266 flags & LOCKFILE_FAIL_IMMEDIATELY,
1267 flags & LOCKFILE_EXCLUSIVE_LOCK );
1269 if (status) SetLastError( RtlNtStatusToDosError(status) );
1270 return !status;
1274 /**************************************************************************
1275 * UnlockFile (KERNEL32.@)
1277 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1278 DWORD count_low, DWORD count_high )
1280 NTSTATUS status;
1281 LARGE_INTEGER count, offset;
1283 count.u.LowPart = count_low;
1284 count.u.HighPart = count_high;
1285 offset.u.LowPart = offset_low;
1286 offset.u.HighPart = offset_high;
1288 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1289 if (status) SetLastError( RtlNtStatusToDosError(status) );
1290 return !status;
1294 /**************************************************************************
1295 * UnlockFileEx (KERNEL32.@)
1297 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1298 LPOVERLAPPED overlapped )
1300 if (reserved)
1302 SetLastError( ERROR_INVALID_PARAMETER );
1303 return FALSE;
1305 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1307 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1311 /*************************************************************************
1312 * SetHandleCount (KERNEL32.@)
1314 UINT WINAPI SetHandleCount( UINT count )
1316 return count;
1320 /**************************************************************************
1321 * Operations on file names *
1322 **************************************************************************/
1325 /*************************************************************************
1326 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1328 * Creates or opens an object, and returns a handle that can be used to
1329 * access that object.
1331 * PARAMS
1333 * filename [in] pointer to filename to be accessed
1334 * access [in] access mode requested
1335 * sharing [in] share mode
1336 * sa [in] pointer to security attributes
1337 * creation [in] how to create the file
1338 * attributes [in] attributes for newly created file
1339 * template [in] handle to file with extended attributes to copy
1341 * RETURNS
1342 * Success: Open handle to specified file
1343 * Failure: INVALID_HANDLE_VALUE
1345 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1346 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1347 DWORD attributes, HANDLE template )
1349 NTSTATUS status;
1350 UINT options;
1351 OBJECT_ATTRIBUTES attr;
1352 UNICODE_STRING nameW;
1353 IO_STATUS_BLOCK io;
1354 HANDLE ret;
1355 DWORD dosdev;
1356 const WCHAR *vxd_name = NULL;
1357 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1358 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1359 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1360 SECURITY_QUALITY_OF_SERVICE qos;
1362 static const UINT nt_disposition[5] =
1364 FILE_CREATE, /* CREATE_NEW */
1365 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1366 FILE_OPEN, /* OPEN_EXISTING */
1367 FILE_OPEN_IF, /* OPEN_ALWAYS */
1368 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1372 /* sanity checks */
1374 if (!filename || !filename[0])
1376 SetLastError( ERROR_PATH_NOT_FOUND );
1377 return INVALID_HANDLE_VALUE;
1380 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1381 (access & GENERIC_READ)?"GENERIC_READ ":"",
1382 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1383 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1384 (!access)?"QUERY_ACCESS ":"",
1385 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1386 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1387 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1388 creation, attributes);
1390 /* Open a console for CONIN$ or CONOUT$ */
1392 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1394 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1395 creation ? OPEN_EXISTING : 0);
1396 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1397 goto done;
1400 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1402 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1403 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1405 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1406 !strncmpiW( filename + 4, pipeW, 5 ) ||
1407 !strncmpiW( filename + 4, mailslotW, 9 ))
1409 dosdev = 0;
1411 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1413 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1415 else if (GetVersion() & 0x80000000)
1417 vxd_name = filename + 4;
1418 if (!creation) creation = OPEN_EXISTING;
1421 else dosdev = RtlIsDosDeviceName_U( filename );
1423 if (dosdev)
1425 static const WCHAR conW[] = {'C','O','N'};
1427 if (LOWORD(dosdev) == sizeof(conW) &&
1428 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1430 switch (access & (GENERIC_READ|GENERIC_WRITE))
1432 case GENERIC_READ:
1433 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1434 goto done;
1435 case GENERIC_WRITE:
1436 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1437 goto done;
1438 default:
1439 SetLastError( ERROR_FILE_NOT_FOUND );
1440 return INVALID_HANDLE_VALUE;
1445 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1447 SetLastError( ERROR_INVALID_PARAMETER );
1448 return INVALID_HANDLE_VALUE;
1451 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1453 SetLastError( ERROR_PATH_NOT_FOUND );
1454 return INVALID_HANDLE_VALUE;
1457 /* now call NtCreateFile */
1459 options = 0;
1460 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1461 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1462 else
1463 options |= FILE_NON_DIRECTORY_FILE;
1464 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1466 options |= FILE_DELETE_ON_CLOSE;
1467 access |= DELETE;
1469 if (attributes & FILE_FLAG_NO_BUFFERING)
1470 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1471 if (!(attributes & FILE_FLAG_OVERLAPPED))
1472 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1473 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1474 options |= FILE_RANDOM_ACCESS;
1475 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1477 attr.Length = sizeof(attr);
1478 attr.RootDirectory = 0;
1479 attr.Attributes = OBJ_CASE_INSENSITIVE;
1480 attr.ObjectName = &nameW;
1481 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1482 if (attributes & SECURITY_SQOS_PRESENT)
1484 qos.Length = sizeof(qos);
1485 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1486 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1487 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1488 attr.SecurityQualityOfService = &qos;
1490 else
1491 attr.SecurityQualityOfService = NULL;
1493 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1495 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1496 sharing, nt_disposition[creation - CREATE_NEW],
1497 options, NULL, 0 );
1498 if (status)
1500 if (vxd_name && vxd_name[0])
1502 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1503 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1504 "__wine_vxd_open" );
1505 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1508 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1509 ret = INVALID_HANDLE_VALUE;
1511 /* In the case file creation was rejected due to CREATE_NEW flag
1512 * was specified and file with that name already exists, correct
1513 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1514 * Note: RtlNtStatusToDosError is not the subject to blame here.
1516 if (status == STATUS_OBJECT_NAME_COLLISION)
1517 SetLastError( ERROR_FILE_EXISTS );
1518 else
1519 SetLastError( RtlNtStatusToDosError(status) );
1521 else
1523 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1524 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1525 SetLastError( ERROR_ALREADY_EXISTS );
1526 else
1527 SetLastError( 0 );
1529 RtlFreeUnicodeString( &nameW );
1531 done:
1532 if (!ret) ret = INVALID_HANDLE_VALUE;
1533 TRACE("returning %p\n", ret);
1534 return ret;
1539 /*************************************************************************
1540 * CreateFileA (KERNEL32.@)
1542 * See CreateFileW.
1544 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1545 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1546 DWORD attributes, HANDLE template)
1548 WCHAR *nameW;
1550 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1551 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1554 /*************************************************************************
1555 * CreateFile2 (KERNEL32.@)
1557 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1558 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1560 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1561 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1562 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1564 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1566 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1569 /***********************************************************************
1570 * DeleteFileW (KERNEL32.@)
1572 * Delete a file.
1574 * PARAMS
1575 * path [I] Path to the file to delete.
1577 * RETURNS
1578 * Success: TRUE.
1579 * Failure: FALSE, check GetLastError().
1581 BOOL WINAPI DeleteFileW( LPCWSTR path )
1583 UNICODE_STRING nameW;
1584 OBJECT_ATTRIBUTES attr;
1585 NTSTATUS status;
1586 HANDLE hFile;
1587 IO_STATUS_BLOCK io;
1589 TRACE("%s\n", debugstr_w(path) );
1591 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1593 SetLastError( ERROR_PATH_NOT_FOUND );
1594 return FALSE;
1597 attr.Length = sizeof(attr);
1598 attr.RootDirectory = 0;
1599 attr.Attributes = OBJ_CASE_INSENSITIVE;
1600 attr.ObjectName = &nameW;
1601 attr.SecurityDescriptor = NULL;
1602 attr.SecurityQualityOfService = NULL;
1604 status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1605 &attr, &io, NULL, 0,
1606 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1607 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1608 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1610 RtlFreeUnicodeString( &nameW );
1611 if (status)
1613 SetLastError( RtlNtStatusToDosError(status) );
1614 return FALSE;
1616 return TRUE;
1620 /***********************************************************************
1621 * DeleteFileA (KERNEL32.@)
1623 * See DeleteFileW.
1625 BOOL WINAPI DeleteFileA( LPCSTR path )
1627 WCHAR *pathW;
1629 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1630 return DeleteFileW( pathW );
1634 /**************************************************************************
1635 * ReplaceFileW (KERNEL32.@)
1636 * ReplaceFile (KERNEL32.@)
1638 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1639 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1640 LPVOID lpExclude, LPVOID lpReserved)
1642 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1643 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1644 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1645 DWORD error = ERROR_SUCCESS;
1646 UINT replaced_flags;
1647 BOOL ret = FALSE;
1648 NTSTATUS status;
1649 IO_STATUS_BLOCK io;
1650 OBJECT_ATTRIBUTES attr;
1652 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1653 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1654 dwReplaceFlags, lpExclude, lpReserved);
1656 if (dwReplaceFlags)
1657 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1659 /* First two arguments are mandatory */
1660 if (!lpReplacedFileName || !lpReplacementFileName)
1662 SetLastError(ERROR_INVALID_PARAMETER);
1663 return FALSE;
1666 unix_replaced_name.Buffer = NULL;
1667 unix_replacement_name.Buffer = NULL;
1668 unix_backup_name.Buffer = NULL;
1670 attr.Length = sizeof(attr);
1671 attr.RootDirectory = 0;
1672 attr.Attributes = OBJ_CASE_INSENSITIVE;
1673 attr.ObjectName = NULL;
1674 attr.SecurityDescriptor = NULL;
1675 attr.SecurityQualityOfService = NULL;
1677 /* Open the "replaced" file for reading and writing */
1678 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1680 error = ERROR_PATH_NOT_FOUND;
1681 goto fail;
1683 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1684 attr.ObjectName = &nt_replaced_name;
1685 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1686 &attr, &io,
1687 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1688 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1689 if (status == STATUS_SUCCESS)
1690 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1691 RtlFreeUnicodeString(&nt_replaced_name);
1692 if (status != STATUS_SUCCESS)
1694 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1695 error = ERROR_FILE_NOT_FOUND;
1696 else
1697 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1698 goto fail;
1702 * Open the replacement file for reading, writing, and deleting
1703 * (writing and deleting are needed when finished)
1705 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1707 error = ERROR_PATH_NOT_FOUND;
1708 goto fail;
1710 attr.ObjectName = &nt_replacement_name;
1711 status = NtOpenFile(&hReplacement,
1712 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1713 &attr, &io, 0,
1714 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1715 if (status == STATUS_SUCCESS)
1716 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1717 RtlFreeUnicodeString(&nt_replacement_name);
1718 if (status != STATUS_SUCCESS)
1720 error = RtlNtStatusToDosError(status);
1721 goto fail;
1724 /* If the user wants a backup then that needs to be performed first */
1725 if (lpBackupFileName)
1727 UNICODE_STRING nt_backup_name;
1728 FILE_BASIC_INFORMATION replaced_info;
1730 /* Obtain the file attributes from the "replaced" file */
1731 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1732 sizeof(replaced_info),
1733 FileBasicInformation);
1734 if (status != STATUS_SUCCESS)
1736 error = RtlNtStatusToDosError(status);
1737 goto fail;
1740 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1742 error = ERROR_PATH_NOT_FOUND;
1743 goto fail;
1745 attr.ObjectName = &nt_backup_name;
1746 /* Open the backup with permissions to write over it */
1747 status = NtCreateFile(&hBackup, GENERIC_WRITE,
1748 &attr, &io, NULL, replaced_info.FileAttributes,
1749 FILE_SHARE_WRITE, FILE_OPEN_IF,
1750 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1751 NULL, 0);
1752 if (status == STATUS_SUCCESS)
1753 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1754 RtlFreeUnicodeString(&nt_backup_name);
1755 if (status != STATUS_SUCCESS)
1757 error = RtlNtStatusToDosError(status);
1758 goto fail;
1761 /* If an existing backup exists then copy over it */
1762 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1764 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1765 goto fail;
1770 * Now that the backup has been performed (if requested), copy the replacement
1771 * into place
1773 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1775 if (errno == EACCES)
1777 /* Inappropriate permissions on "replaced", rename will fail */
1778 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1779 goto fail;
1781 /* on failure we need to indicate whether a backup was made */
1782 if (!lpBackupFileName)
1783 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1784 else
1785 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1786 goto fail;
1788 /* Success! */
1789 ret = TRUE;
1791 /* Perform resource cleanup */
1792 fail:
1793 if (hBackup) CloseHandle(hBackup);
1794 if (hReplaced) CloseHandle(hReplaced);
1795 if (hReplacement) CloseHandle(hReplacement);
1796 RtlFreeAnsiString(&unix_backup_name);
1797 RtlFreeAnsiString(&unix_replacement_name);
1798 RtlFreeAnsiString(&unix_replaced_name);
1800 /* If there was an error, set the error code */
1801 if(!ret)
1802 SetLastError(error);
1803 return ret;
1807 /**************************************************************************
1808 * ReplaceFileA (KERNEL32.@)
1810 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1811 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1812 LPVOID lpExclude, LPVOID lpReserved)
1814 WCHAR *replacedW, *replacementW, *backupW = NULL;
1815 BOOL ret;
1817 /* This function only makes sense when the first two parameters are defined */
1818 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1820 SetLastError(ERROR_INVALID_PARAMETER);
1821 return FALSE;
1823 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1825 HeapFree( GetProcessHeap(), 0, replacedW );
1826 SetLastError(ERROR_INVALID_PARAMETER);
1827 return FALSE;
1829 /* The backup parameter, however, is optional */
1830 if (lpBackupFileName)
1832 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1834 HeapFree( GetProcessHeap(), 0, replacedW );
1835 HeapFree( GetProcessHeap(), 0, replacementW );
1836 SetLastError(ERROR_INVALID_PARAMETER);
1837 return FALSE;
1840 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1841 HeapFree( GetProcessHeap(), 0, replacedW );
1842 HeapFree( GetProcessHeap(), 0, replacementW );
1843 HeapFree( GetProcessHeap(), 0, backupW );
1844 return ret;
1848 /*************************************************************************
1849 * FindFirstFileExW (KERNEL32.@)
1851 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1852 * results as FindExSearchNameMatch
1854 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1855 LPVOID data, FINDEX_SEARCH_OPS search_op,
1856 LPVOID filter, DWORD flags)
1858 WCHAR *mask, *p;
1859 FIND_FIRST_INFO *info = NULL;
1860 UNICODE_STRING nt_name;
1861 OBJECT_ATTRIBUTES attr;
1862 IO_STATUS_BLOCK io;
1863 NTSTATUS status;
1864 DWORD device = 0;
1866 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1868 if ((search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1869 || flags != 0)
1871 FIXME("options not implemented 0x%08x 0x%08x\n", search_op, flags );
1872 return INVALID_HANDLE_VALUE;
1874 if (level != FindExInfoStandard)
1876 FIXME("info level %d not implemented\n", level );
1877 return INVALID_HANDLE_VALUE;
1880 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1882 SetLastError( ERROR_PATH_NOT_FOUND );
1883 return INVALID_HANDLE_VALUE;
1886 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1888 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1889 goto error;
1892 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1894 static const WCHAR dotW[] = {'.',0};
1895 WCHAR *dir = NULL;
1897 /* we still need to check that the directory can be opened */
1899 if (HIWORD(device))
1901 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1903 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1904 goto error;
1906 memcpy( dir, filename, HIWORD(device) );
1907 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1909 RtlFreeUnicodeString( &nt_name );
1910 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1912 HeapFree( GetProcessHeap(), 0, dir );
1913 SetLastError( ERROR_PATH_NOT_FOUND );
1914 goto error;
1916 HeapFree( GetProcessHeap(), 0, dir );
1917 RtlInitUnicodeString( &info->mask, NULL );
1919 else if (!mask || !*mask)
1921 SetLastError( ERROR_FILE_NOT_FOUND );
1922 goto error;
1924 else
1926 if (!RtlCreateUnicodeString( &info->mask, mask ))
1928 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1929 goto error;
1932 /* truncate dir name before mask */
1933 *mask = 0;
1934 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1937 /* check if path is the root of the drive */
1938 info->is_root = FALSE;
1939 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1940 if (p[0] && p[1] == ':')
1942 p += 2;
1943 while (*p == '\\') p++;
1944 info->is_root = (*p == 0);
1947 attr.Length = sizeof(attr);
1948 attr.RootDirectory = 0;
1949 attr.Attributes = OBJ_CASE_INSENSITIVE;
1950 attr.ObjectName = &nt_name;
1951 attr.SecurityDescriptor = NULL;
1952 attr.SecurityQualityOfService = NULL;
1954 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1955 FILE_SHARE_READ | FILE_SHARE_WRITE,
1956 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1958 if (status != STATUS_SUCCESS)
1960 RtlFreeUnicodeString( &info->mask );
1961 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1962 SetLastError( ERROR_PATH_NOT_FOUND );
1963 else
1964 SetLastError( RtlNtStatusToDosError(status) );
1965 goto error;
1968 RtlInitializeCriticalSection( &info->cs );
1969 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1970 info->path = nt_name;
1971 info->magic = FIND_FIRST_MAGIC;
1972 info->data_pos = 0;
1973 info->data_len = 0;
1974 info->data_size = 0;
1975 info->data = NULL;
1976 info->search_op = search_op;
1978 if (device)
1980 WIN32_FIND_DATAW *wfd = data;
1982 memset( wfd, 0, sizeof(*wfd) );
1983 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1984 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1985 CloseHandle( info->handle );
1986 info->handle = 0;
1988 else
1990 IO_STATUS_BLOCK io;
1991 BOOL has_wildcard = strpbrkW( info->mask.Buffer, wildcardsW ) != NULL;
1993 info->data_size = has_wildcard ? 8192 : max_entry_size * 2;
1995 while (info->data_size)
1997 if (!(info->data = HeapAlloc( GetProcessHeap(), 0, info->data_size )))
1999 FindClose( info );
2000 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2001 return INVALID_HANDLE_VALUE;
2004 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2005 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
2006 if (io.u.Status)
2008 FindClose( info );
2009 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2010 return INVALID_HANDLE_VALUE;
2013 if (io.Information < info->data_size - max_entry_size)
2015 info->data_size = 0; /* we read everything */
2017 else if (info->data_size < 1024 * 1024)
2019 HeapFree( GetProcessHeap(), 0, info->data );
2020 info->data_size *= 2;
2022 else break;
2025 info->data_len = io.Information;
2026 if (!info->data_size && has_wildcard) /* release unused buffer space */
2027 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, info->data, info->data_len );
2029 if (!FindNextFileW( info, data ))
2031 TRACE( "%s not found\n", debugstr_w(filename) );
2032 FindClose( info );
2033 SetLastError( ERROR_FILE_NOT_FOUND );
2034 return INVALID_HANDLE_VALUE;
2036 if (!has_wildcard) /* we can't find two files with the same name */
2038 CloseHandle( info->handle );
2039 HeapFree( GetProcessHeap(), 0, info->data );
2040 info->handle = 0;
2041 info->data = NULL;
2044 return info;
2046 error:
2047 HeapFree( GetProcessHeap(), 0, info );
2048 RtlFreeUnicodeString( &nt_name );
2049 return INVALID_HANDLE_VALUE;
2053 /*************************************************************************
2054 * FindNextFileW (KERNEL32.@)
2056 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2058 FIND_FIRST_INFO *info;
2059 FILE_BOTH_DIR_INFORMATION *dir_info;
2060 BOOL ret = FALSE;
2062 TRACE("%p %p\n", handle, data);
2064 if (!handle || handle == INVALID_HANDLE_VALUE)
2066 SetLastError( ERROR_INVALID_HANDLE );
2067 return ret;
2069 info = handle;
2070 if (info->magic != FIND_FIRST_MAGIC)
2072 SetLastError( ERROR_INVALID_HANDLE );
2073 return ret;
2076 RtlEnterCriticalSection( &info->cs );
2078 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2079 else for (;;)
2081 if (info->data_pos >= info->data_len) /* need to read some more data */
2083 IO_STATUS_BLOCK io;
2085 if (info->data_size)
2086 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2087 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
2088 else
2089 io.u.Status = STATUS_NO_MORE_FILES;
2091 if (io.u.Status)
2093 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2094 if (io.u.Status == STATUS_NO_MORE_FILES)
2096 CloseHandle( info->handle );
2097 HeapFree( GetProcessHeap(), 0, info->data );
2098 info->handle = 0;
2099 info->data = NULL;
2101 break;
2103 info->data_len = io.Information;
2104 info->data_pos = 0;
2107 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2109 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2110 else info->data_pos = info->data_len;
2112 /* don't return '.' and '..' in the root of the drive */
2113 if (info->is_root)
2115 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2116 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2117 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2120 /* check for dir symlink */
2121 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2122 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2123 strpbrkW( info->mask.Buffer, wildcardsW ))
2125 if (!check_dir_symlink( info, dir_info )) continue;
2128 data->dwFileAttributes = dir_info->FileAttributes;
2129 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2130 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2131 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2132 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2133 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2134 data->dwReserved0 = 0;
2135 data->dwReserved1 = 0;
2137 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2138 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2139 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2140 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2142 TRACE("returning %s (%s)\n",
2143 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2145 ret = TRUE;
2146 break;
2149 RtlLeaveCriticalSection( &info->cs );
2150 return ret;
2154 /*************************************************************************
2155 * FindClose (KERNEL32.@)
2157 BOOL WINAPI FindClose( HANDLE handle )
2159 FIND_FIRST_INFO *info = handle;
2161 if (!handle || handle == INVALID_HANDLE_VALUE)
2163 SetLastError( ERROR_INVALID_HANDLE );
2164 return FALSE;
2167 __TRY
2169 if (info->magic == FIND_FIRST_MAGIC)
2171 RtlEnterCriticalSection( &info->cs );
2172 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2174 info->magic = 0;
2175 if (info->handle) CloseHandle( info->handle );
2176 info->handle = 0;
2177 RtlFreeUnicodeString( &info->mask );
2178 info->mask.Buffer = NULL;
2179 RtlFreeUnicodeString( &info->path );
2180 info->data_pos = 0;
2181 info->data_len = 0;
2182 HeapFree( GetProcessHeap(), 0, info->data );
2183 RtlLeaveCriticalSection( &info->cs );
2184 info->cs.DebugInfo->Spare[0] = 0;
2185 RtlDeleteCriticalSection( &info->cs );
2186 HeapFree( GetProcessHeap(), 0, info );
2190 __EXCEPT_PAGE_FAULT
2192 WARN("Illegal handle %p\n", handle);
2193 SetLastError( ERROR_INVALID_HANDLE );
2194 return FALSE;
2196 __ENDTRY
2198 return TRUE;
2202 /*************************************************************************
2203 * FindFirstFileA (KERNEL32.@)
2205 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2207 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2208 FindExSearchNameMatch, NULL, 0);
2211 /*************************************************************************
2212 * FindFirstFileExA (KERNEL32.@)
2214 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2215 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2216 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2218 HANDLE handle;
2219 WIN32_FIND_DATAA *dataA;
2220 WIN32_FIND_DATAW dataW;
2221 WCHAR *nameW;
2223 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2225 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2226 if (handle == INVALID_HANDLE_VALUE) return handle;
2228 dataA = lpFindFileData;
2229 dataA->dwFileAttributes = dataW.dwFileAttributes;
2230 dataA->ftCreationTime = dataW.ftCreationTime;
2231 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2232 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2233 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2234 dataA->nFileSizeLow = dataW.nFileSizeLow;
2235 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2236 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2237 sizeof(dataA->cAlternateFileName) );
2238 return handle;
2242 /*************************************************************************
2243 * FindFirstFileW (KERNEL32.@)
2245 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2247 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2248 FindExSearchNameMatch, NULL, 0);
2252 /*************************************************************************
2253 * FindNextFileA (KERNEL32.@)
2255 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2257 WIN32_FIND_DATAW dataW;
2259 if (!FindNextFileW( handle, &dataW )) return FALSE;
2260 data->dwFileAttributes = dataW.dwFileAttributes;
2261 data->ftCreationTime = dataW.ftCreationTime;
2262 data->ftLastAccessTime = dataW.ftLastAccessTime;
2263 data->ftLastWriteTime = dataW.ftLastWriteTime;
2264 data->nFileSizeHigh = dataW.nFileSizeHigh;
2265 data->nFileSizeLow = dataW.nFileSizeLow;
2266 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2267 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2268 sizeof(data->cAlternateFileName) );
2269 return TRUE;
2273 /**************************************************************************
2274 * GetFileAttributesW (KERNEL32.@)
2276 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2278 FILE_BASIC_INFORMATION info;
2279 UNICODE_STRING nt_name;
2280 OBJECT_ATTRIBUTES attr;
2281 NTSTATUS status;
2283 TRACE("%s\n", debugstr_w(name));
2285 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2287 SetLastError( ERROR_PATH_NOT_FOUND );
2288 return INVALID_FILE_ATTRIBUTES;
2291 attr.Length = sizeof(attr);
2292 attr.RootDirectory = 0;
2293 attr.Attributes = OBJ_CASE_INSENSITIVE;
2294 attr.ObjectName = &nt_name;
2295 attr.SecurityDescriptor = NULL;
2296 attr.SecurityQualityOfService = NULL;
2298 status = NtQueryAttributesFile( &attr, &info );
2299 RtlFreeUnicodeString( &nt_name );
2301 if (status == STATUS_SUCCESS) return info.FileAttributes;
2303 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2304 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2306 SetLastError( RtlNtStatusToDosError(status) );
2307 return INVALID_FILE_ATTRIBUTES;
2311 /**************************************************************************
2312 * GetFileAttributesA (KERNEL32.@)
2314 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2316 WCHAR *nameW;
2318 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2319 return GetFileAttributesW( nameW );
2323 /**************************************************************************
2324 * SetFileAttributesW (KERNEL32.@)
2326 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2328 UNICODE_STRING nt_name;
2329 OBJECT_ATTRIBUTES attr;
2330 IO_STATUS_BLOCK io;
2331 NTSTATUS status;
2332 HANDLE handle;
2334 TRACE("%s %x\n", debugstr_w(name), attributes);
2336 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2338 SetLastError( ERROR_PATH_NOT_FOUND );
2339 return FALSE;
2342 attr.Length = sizeof(attr);
2343 attr.RootDirectory = 0;
2344 attr.Attributes = OBJ_CASE_INSENSITIVE;
2345 attr.ObjectName = &nt_name;
2346 attr.SecurityDescriptor = NULL;
2347 attr.SecurityQualityOfService = NULL;
2349 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2350 RtlFreeUnicodeString( &nt_name );
2352 if (status == STATUS_SUCCESS)
2354 FILE_BASIC_INFORMATION info;
2356 memset( &info, 0, sizeof(info) );
2357 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2358 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2359 NtClose( handle );
2362 if (status == STATUS_SUCCESS) return TRUE;
2363 SetLastError( RtlNtStatusToDosError(status) );
2364 return FALSE;
2368 /**************************************************************************
2369 * SetFileAttributesA (KERNEL32.@)
2371 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2373 WCHAR *nameW;
2375 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2376 return SetFileAttributesW( nameW, attributes );
2380 /**************************************************************************
2381 * GetFileAttributesExW (KERNEL32.@)
2383 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2385 FILE_NETWORK_OPEN_INFORMATION info;
2386 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2387 UNICODE_STRING nt_name;
2388 OBJECT_ATTRIBUTES attr;
2389 NTSTATUS status;
2391 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2393 if (level != GetFileExInfoStandard)
2395 SetLastError( ERROR_INVALID_PARAMETER );
2396 return FALSE;
2399 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2401 SetLastError( ERROR_PATH_NOT_FOUND );
2402 return FALSE;
2405 attr.Length = sizeof(attr);
2406 attr.RootDirectory = 0;
2407 attr.Attributes = OBJ_CASE_INSENSITIVE;
2408 attr.ObjectName = &nt_name;
2409 attr.SecurityDescriptor = NULL;
2410 attr.SecurityQualityOfService = NULL;
2412 status = NtQueryFullAttributesFile( &attr, &info );
2413 RtlFreeUnicodeString( &nt_name );
2415 if (status != STATUS_SUCCESS)
2417 SetLastError( RtlNtStatusToDosError(status) );
2418 return FALSE;
2421 data->dwFileAttributes = info.FileAttributes;
2422 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2423 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2424 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2425 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2426 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2427 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2428 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2429 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2430 return TRUE;
2434 /**************************************************************************
2435 * GetFileAttributesExA (KERNEL32.@)
2437 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2439 WCHAR *nameW;
2441 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2442 return GetFileAttributesExW( nameW, level, ptr );
2446 /******************************************************************************
2447 * GetCompressedFileSizeW (KERNEL32.@)
2449 * Get the actual number of bytes used on disk.
2451 * RETURNS
2452 * Success: Low-order doubleword of number of bytes
2453 * Failure: INVALID_FILE_SIZE
2455 DWORD WINAPI GetCompressedFileSizeW(
2456 LPCWSTR name, /* [in] Pointer to name of file */
2457 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2459 UNICODE_STRING nt_name;
2460 OBJECT_ATTRIBUTES attr;
2461 IO_STATUS_BLOCK io;
2462 NTSTATUS status;
2463 HANDLE handle;
2464 DWORD ret = INVALID_FILE_SIZE;
2466 TRACE("%s %p\n", debugstr_w(name), size_high);
2468 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2470 SetLastError( ERROR_PATH_NOT_FOUND );
2471 return INVALID_FILE_SIZE;
2474 attr.Length = sizeof(attr);
2475 attr.RootDirectory = 0;
2476 attr.Attributes = OBJ_CASE_INSENSITIVE;
2477 attr.ObjectName = &nt_name;
2478 attr.SecurityDescriptor = NULL;
2479 attr.SecurityQualityOfService = NULL;
2481 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2482 RtlFreeUnicodeString( &nt_name );
2484 if (status == STATUS_SUCCESS)
2486 /* we don't support compressed files, simply return the file size */
2487 ret = GetFileSize( handle, size_high );
2488 NtClose( handle );
2490 else SetLastError( RtlNtStatusToDosError(status) );
2492 return ret;
2496 /******************************************************************************
2497 * GetCompressedFileSizeA (KERNEL32.@)
2499 * See GetCompressedFileSizeW.
2501 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2503 WCHAR *nameW;
2505 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2506 return GetCompressedFileSizeW( nameW, size_high );
2510 /***********************************************************************
2511 * OpenVxDHandle (KERNEL32.@)
2513 * This function is supposed to return the corresponding Ring 0
2514 * ("kernel") handle for a Ring 3 handle in Win9x.
2515 * Evidently, Wine will have problems with this. But we try anyway,
2516 * maybe it helps...
2518 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2520 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2521 return hHandleRing3;
2525 /****************************************************************************
2526 * DeviceIoControl (KERNEL32.@)
2528 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2529 LPVOID lpvInBuffer, DWORD cbInBuffer,
2530 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2531 LPDWORD lpcbBytesReturned,
2532 LPOVERLAPPED lpOverlapped)
2534 NTSTATUS status;
2536 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2537 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2538 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2540 /* Check if this is a user defined control code for a VxD */
2542 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2544 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2545 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2546 DeviceIoProc proc = NULL;
2548 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2549 "__wine_vxd_get_proc" );
2550 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2551 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2552 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2555 /* Not a VxD, let ntdll handle it */
2557 if (lpOverlapped)
2559 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2560 lpOverlapped->Internal = STATUS_PENDING;
2561 lpOverlapped->InternalHigh = 0;
2562 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2563 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2564 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2565 dwIoControlCode, lpvInBuffer, cbInBuffer,
2566 lpvOutBuffer, cbOutBuffer);
2567 else
2568 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2569 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2570 dwIoControlCode, lpvInBuffer, cbInBuffer,
2571 lpvOutBuffer, cbOutBuffer);
2572 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2574 else
2576 IO_STATUS_BLOCK iosb;
2578 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2579 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2580 dwIoControlCode, lpvInBuffer, cbInBuffer,
2581 lpvOutBuffer, cbOutBuffer);
2582 else
2583 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2584 dwIoControlCode, lpvInBuffer, cbInBuffer,
2585 lpvOutBuffer, cbOutBuffer);
2586 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2588 if (status) SetLastError( RtlNtStatusToDosError(status) );
2589 return !status;
2593 /***********************************************************************
2594 * OpenFile (KERNEL32.@)
2596 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2598 HANDLE handle;
2599 FILETIME filetime;
2600 WORD filedatetime[2];
2602 if (!ofs) return HFILE_ERROR;
2604 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2605 ((mode & 0x3 )==OF_READ)?"OF_READ":
2606 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2607 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2608 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2609 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2610 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2611 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2612 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2613 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2614 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2615 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2616 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2617 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2618 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2619 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2620 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2621 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2625 ofs->cBytes = sizeof(OFSTRUCT);
2626 ofs->nErrCode = 0;
2627 if (mode & OF_REOPEN) name = ofs->szPathName;
2629 if (!name) return HFILE_ERROR;
2631 TRACE("%s %04x\n", name, mode );
2633 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2634 Are there any cases where getting the path here is wrong?
2635 Uwe Bonnes 1997 Apr 2 */
2636 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2638 /* OF_PARSE simply fills the structure */
2640 if (mode & OF_PARSE)
2642 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2643 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2644 return 0;
2647 /* OF_CREATE is completely different from all other options, so
2648 handle it first */
2650 if (mode & OF_CREATE)
2652 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2653 goto error;
2655 else
2657 /* Now look for the file */
2659 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2660 goto error;
2662 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2664 if (mode & OF_DELETE)
2666 if (!DeleteFileA( ofs->szPathName )) goto error;
2667 TRACE("(%s): OF_DELETE return = OK\n", name);
2668 return TRUE;
2671 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2672 if (handle == INVALID_HANDLE_VALUE) goto error;
2674 GetFileTime( handle, NULL, NULL, &filetime );
2675 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2676 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2678 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2680 CloseHandle( handle );
2681 WARN("(%s): OF_VERIFY failed\n", name );
2682 /* FIXME: what error here? */
2683 SetLastError( ERROR_FILE_NOT_FOUND );
2684 goto error;
2687 ofs->Reserved1 = filedatetime[0];
2688 ofs->Reserved2 = filedatetime[1];
2690 TRACE("(%s): OK, return = %p\n", name, handle );
2691 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2693 CloseHandle( handle );
2694 return TRUE;
2696 return HandleToLong(handle);
2698 error: /* We get here if there was an error opening the file */
2699 ofs->nErrCode = GetLastError();
2700 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2701 return HFILE_ERROR;
2705 /***********************************************************************
2706 * OpenFileById (KERNEL32.@)
2708 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2709 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2711 UINT options;
2712 HANDLE result;
2713 OBJECT_ATTRIBUTES attr;
2714 NTSTATUS status;
2715 IO_STATUS_BLOCK io;
2716 UNICODE_STRING objectName;
2718 if (!id)
2720 SetLastError( ERROR_INVALID_PARAMETER );
2721 return INVALID_HANDLE_VALUE;
2724 options = FILE_OPEN_BY_FILE_ID;
2725 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2726 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2727 else
2728 options |= FILE_NON_DIRECTORY_FILE;
2729 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2730 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2731 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2732 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2734 objectName.Length = sizeof(ULONGLONG);
2735 objectName.Buffer = (WCHAR *)&id->u.FileId;
2736 attr.Length = sizeof(attr);
2737 attr.RootDirectory = handle;
2738 attr.Attributes = 0;
2739 attr.ObjectName = &objectName;
2740 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2741 attr.SecurityQualityOfService = NULL;
2742 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2744 status = NtCreateFile( &result, access, &attr, &io, NULL, flags,
2745 share, OPEN_EXISTING, options, NULL, 0 );
2746 if (status != STATUS_SUCCESS)
2748 SetLastError( RtlNtStatusToDosError( status ) );
2749 return INVALID_HANDLE_VALUE;
2751 return result;
2755 /***********************************************************************
2756 * K32EnumDeviceDrivers (KERNEL32.@)
2758 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2760 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2762 if (needed)
2763 *needed = 0;
2765 return TRUE;
2768 /***********************************************************************
2769 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2771 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2773 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2775 if (base_name && size)
2776 base_name[0] = '\0';
2778 return 0;
2781 /***********************************************************************
2782 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2784 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2786 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2788 if (base_name && size)
2789 base_name[0] = '\0';
2791 return 0;
2794 /***********************************************************************
2795 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2797 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2799 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2801 if (file_name && size)
2802 file_name[0] = '\0';
2804 return 0;
2807 /***********************************************************************
2808 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2810 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2812 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2814 if (file_name && size)
2815 file_name[0] = '\0';
2817 return 0;