wined3d: Use a separate STATE_VDECL state handler in the GLSL pipeline.
[wine/multimedia.git] / dlls / kernel32 / file.c
blob006db1c207e1e205eb502369db934a6a0fcb0a7c
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 FINDEX_INFO_LEVELS level; /* Level passed to FindFirst */
61 UNICODE_STRING mask; /* file mask */
62 UNICODE_STRING path; /* NT path used to open the directory */
63 BOOL is_root; /* is directory the root of the drive? */
64 UINT data_pos; /* current position in dir data */
65 UINT data_len; /* length of dir data */
66 UINT data_size; /* size of data buffer, or 0 when everything has been read */
67 BYTE *data; /* directory data */
68 } FIND_FIRST_INFO;
70 #define FIND_FIRST_MAGIC 0xc0ffee11
72 static const UINT max_entry_size = offsetof( FILE_BOTH_DIRECTORY_INFORMATION, FileName[256] );
74 static BOOL oem_file_apis;
76 static const WCHAR wildcardsW[] = { '*','?',0 };
78 /***********************************************************************
79 * create_file_OF
81 * Wrapper for CreateFile that takes OF_* mode flags.
83 static HANDLE create_file_OF( LPCSTR path, INT mode )
85 DWORD access, sharing, creation;
87 if (mode & OF_CREATE)
89 creation = CREATE_ALWAYS;
90 access = GENERIC_READ | GENERIC_WRITE;
92 else
94 creation = OPEN_EXISTING;
95 switch(mode & 0x03)
97 case OF_READ: access = GENERIC_READ; break;
98 case OF_WRITE: access = GENERIC_WRITE; break;
99 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
100 default: access = 0; break;
104 switch(mode & 0x70)
106 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
107 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
108 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
109 case OF_SHARE_DENY_NONE:
110 case OF_SHARE_COMPAT:
111 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
113 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
117 /***********************************************************************
118 * check_dir_symlink
120 * Check if a dir symlink should be returned by FindNextFile.
122 static BOOL check_dir_symlink( FIND_FIRST_INFO *info, const FILE_BOTH_DIR_INFORMATION *file_info )
124 UNICODE_STRING str;
125 ANSI_STRING unix_name;
126 struct stat st, parent_st;
127 BOOL ret = TRUE;
128 DWORD len;
130 str.MaximumLength = info->path.Length + sizeof(WCHAR) + file_info->FileNameLength;
131 if (!(str.Buffer = HeapAlloc( GetProcessHeap(), 0, str.MaximumLength ))) return TRUE;
132 memcpy( str.Buffer, info->path.Buffer, info->path.Length );
133 len = info->path.Length / sizeof(WCHAR);
134 if (!len || str.Buffer[len-1] != '\\') str.Buffer[len++] = '\\';
135 memcpy( str.Buffer + len, file_info->FileName, file_info->FileNameLength );
136 str.Length = len * sizeof(WCHAR) + file_info->FileNameLength;
138 unix_name.Buffer = NULL;
139 if (!wine_nt_to_unix_file_name( &str, &unix_name, OPEN_EXISTING, FALSE ) &&
140 !stat( unix_name.Buffer, &st ))
142 char *p = unix_name.Buffer + unix_name.Length - 1;
144 /* skip trailing slashes */
145 while (p > unix_name.Buffer && *p == '/') p--;
147 while (ret && p > unix_name.Buffer)
149 while (p > unix_name.Buffer && *p != '/') p--;
150 while (p > unix_name.Buffer && *p == '/') p--;
151 p[1] = 0;
152 if (!stat( unix_name.Buffer, &parent_st ) &&
153 parent_st.st_dev == st.st_dev &&
154 parent_st.st_ino == st.st_ino)
156 WARN( "suppressing dir symlink %s pointing to parent %s\n",
157 debugstr_wn( str.Buffer, str.Length/sizeof(WCHAR) ),
158 debugstr_a( unix_name.Buffer ));
159 ret = FALSE;
163 RtlFreeAnsiString( &unix_name );
164 RtlFreeUnicodeString( &str );
165 return ret;
169 /***********************************************************************
170 * FILE_SetDosError
172 * Set the DOS error code from errno.
174 void FILE_SetDosError(void)
176 int save_errno = errno; /* errno gets overwritten by printf */
178 TRACE("errno = %d %s\n", errno, strerror(errno));
179 switch (save_errno)
181 case EAGAIN:
182 SetLastError( ERROR_SHARING_VIOLATION );
183 break;
184 case EBADF:
185 SetLastError( ERROR_INVALID_HANDLE );
186 break;
187 case ENOSPC:
188 SetLastError( ERROR_HANDLE_DISK_FULL );
189 break;
190 case EACCES:
191 case EPERM:
192 case EROFS:
193 SetLastError( ERROR_ACCESS_DENIED );
194 break;
195 case EBUSY:
196 SetLastError( ERROR_LOCK_VIOLATION );
197 break;
198 case ENOENT:
199 SetLastError( ERROR_FILE_NOT_FOUND );
200 break;
201 case EISDIR:
202 SetLastError( ERROR_CANNOT_MAKE );
203 break;
204 case ENFILE:
205 case EMFILE:
206 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
207 break;
208 case EEXIST:
209 SetLastError( ERROR_FILE_EXISTS );
210 break;
211 case EINVAL:
212 case ESPIPE:
213 SetLastError( ERROR_SEEK );
214 break;
215 case ENOTEMPTY:
216 SetLastError( ERROR_DIR_NOT_EMPTY );
217 break;
218 case ENOEXEC:
219 SetLastError( ERROR_BAD_FORMAT );
220 break;
221 case ENOTDIR:
222 SetLastError( ERROR_PATH_NOT_FOUND );
223 break;
224 case EXDEV:
225 SetLastError( ERROR_NOT_SAME_DEVICE );
226 break;
227 default:
228 WARN("unknown file error: %s\n", strerror(save_errno) );
229 SetLastError( ERROR_GEN_FAILURE );
230 break;
232 errno = save_errno;
236 /***********************************************************************
237 * FILE_name_AtoW
239 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
241 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
242 * there is no possibility for the function to do that twice, taking into
243 * account any called function.
245 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
247 ANSI_STRING str;
248 UNICODE_STRING strW, *pstrW;
249 NTSTATUS status;
251 RtlInitAnsiString( &str, name );
252 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
253 if (oem_file_apis)
254 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
255 else
256 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
257 if (status == STATUS_SUCCESS) return pstrW->Buffer;
259 if (status == STATUS_BUFFER_OVERFLOW)
260 SetLastError( ERROR_FILENAME_EXCED_RANGE );
261 else
262 SetLastError( RtlNtStatusToDosError(status) );
263 return NULL;
267 /***********************************************************************
268 * FILE_name_WtoA
270 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
272 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
274 DWORD ret;
276 if (srclen < 0) srclen = strlenW( src ) + 1;
277 if (oem_file_apis)
278 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
279 else
280 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
281 return ret;
285 /**************************************************************************
286 * SetFileApisToOEM (KERNEL32.@)
288 VOID WINAPI SetFileApisToOEM(void)
290 oem_file_apis = TRUE;
294 /**************************************************************************
295 * SetFileApisToANSI (KERNEL32.@)
297 VOID WINAPI SetFileApisToANSI(void)
299 oem_file_apis = FALSE;
303 /******************************************************************************
304 * AreFileApisANSI (KERNEL32.@)
306 * Determines if file functions are using ANSI
308 * RETURNS
309 * TRUE: Set of file functions is using ANSI code page
310 * FALSE: Set of file functions is using OEM code page
312 BOOL WINAPI AreFileApisANSI(void)
314 return !oem_file_apis;
318 /**************************************************************************
319 * Operations on file handles *
320 **************************************************************************/
322 /******************************************************************
323 * FILE_ReadWriteApc (internal)
325 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG reserved)
327 LPOVERLAPPED_COMPLETION_ROUTINE cr = apc_user;
329 cr(RtlNtStatusToDosError(io_status->u.Status), io_status->Information, (LPOVERLAPPED)io_status);
333 /***********************************************************************
334 * ReadFileEx (KERNEL32.@)
336 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
337 LPOVERLAPPED overlapped,
338 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
340 LARGE_INTEGER offset;
341 NTSTATUS status;
342 PIO_STATUS_BLOCK io_status;
344 TRACE("(hFile=%p, buffer=%p, bytes=%u, ovl=%p, ovl_fn=%p)\n", hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
346 if (!overlapped)
348 SetLastError(ERROR_INVALID_PARAMETER);
349 return FALSE;
352 offset.u.LowPart = overlapped->u.s.Offset;
353 offset.u.HighPart = overlapped->u.s.OffsetHigh;
354 io_status = (PIO_STATUS_BLOCK)overlapped;
355 io_status->u.Status = STATUS_PENDING;
356 io_status->Information = 0;
358 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
359 io_status, buffer, bytesToRead, &offset, NULL);
361 if (status && status != STATUS_PENDING)
363 SetLastError( RtlNtStatusToDosError(status) );
364 return FALSE;
366 return TRUE;
370 /***********************************************************************
371 * ReadFileScatter (KERNEL32.@)
373 BOOL WINAPI ReadFileScatter( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
374 LPDWORD reserved, LPOVERLAPPED overlapped )
376 PIO_STATUS_BLOCK io_status;
377 LARGE_INTEGER offset;
378 void *cvalue = NULL;
379 NTSTATUS status;
381 TRACE( "(%p %p %u %p)\n", file, segments, count, overlapped );
383 offset.u.LowPart = overlapped->u.s.Offset;
384 offset.u.HighPart = overlapped->u.s.OffsetHigh;
385 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
386 io_status = (PIO_STATUS_BLOCK)overlapped;
387 io_status->u.Status = STATUS_PENDING;
388 io_status->Information = 0;
390 status = NtReadFileScatter( file, overlapped->hEvent, NULL, cvalue, io_status,
391 segments, count, &offset, NULL );
392 if (status) SetLastError( RtlNtStatusToDosError(status) );
393 return !status;
397 /***********************************************************************
398 * ReadFile (KERNEL32.@)
400 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
401 LPDWORD bytesRead, LPOVERLAPPED overlapped )
403 LARGE_INTEGER offset;
404 PLARGE_INTEGER poffset = NULL;
405 IO_STATUS_BLOCK iosb;
406 PIO_STATUS_BLOCK io_status = &iosb;
407 HANDLE hEvent = 0;
408 NTSTATUS status;
409 LPVOID cvalue = NULL;
411 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToRead,
412 bytesRead, overlapped );
414 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
416 if (is_console_handle(hFile))
418 DWORD conread, mode;
419 if (!ReadConsoleA(hFile, buffer, bytesToRead, &conread, NULL) ||
420 !GetConsoleMode(hFile, &mode))
421 return FALSE;
422 /* ctrl-Z (26) means end of file on window (if at beginning of buffer)
423 * but Unix uses ctrl-D (4), and ctrl-Z is a bad idea on Unix :-/
424 * So map both ctrl-D ctrl-Z to EOF.
426 if ((mode & ENABLE_PROCESSED_INPUT) && conread > 0 &&
427 (((char*)buffer)[0] == 26 || ((char*)buffer)[0] == 4))
429 conread = 0;
431 if (bytesRead) *bytesRead = conread;
432 return TRUE;
435 if (overlapped != NULL)
437 offset.u.LowPart = overlapped->u.s.Offset;
438 offset.u.HighPart = overlapped->u.s.OffsetHigh;
439 poffset = &offset;
440 hEvent = overlapped->hEvent;
441 io_status = (PIO_STATUS_BLOCK)overlapped;
442 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
444 io_status->u.Status = STATUS_PENDING;
445 io_status->Information = 0;
447 status = NtReadFile(hFile, hEvent, NULL, cvalue, io_status, buffer, bytesToRead, poffset, NULL);
449 if (status == STATUS_PENDING && !overlapped)
451 WaitForSingleObject( hFile, INFINITE );
452 status = io_status->u.Status;
455 if (status != STATUS_PENDING && bytesRead)
456 *bytesRead = io_status->Information;
458 if (status == STATUS_END_OF_FILE)
460 if (overlapped != NULL)
462 SetLastError( RtlNtStatusToDosError(status) );
463 return FALSE;
466 else if (status && status != STATUS_TIMEOUT)
468 SetLastError( RtlNtStatusToDosError(status) );
469 return FALSE;
471 return TRUE;
475 /***********************************************************************
476 * WriteFileEx (KERNEL32.@)
478 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
479 LPOVERLAPPED overlapped,
480 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
482 LARGE_INTEGER offset;
483 NTSTATUS status;
484 PIO_STATUS_BLOCK io_status;
486 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
488 if (overlapped == NULL)
490 SetLastError(ERROR_INVALID_PARAMETER);
491 return FALSE;
493 offset.u.LowPart = overlapped->u.s.Offset;
494 offset.u.HighPart = overlapped->u.s.OffsetHigh;
496 io_status = (PIO_STATUS_BLOCK)overlapped;
497 io_status->u.Status = STATUS_PENDING;
498 io_status->Information = 0;
500 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
501 io_status, buffer, bytesToWrite, &offset, NULL);
503 if (status && status != STATUS_PENDING)
505 SetLastError( RtlNtStatusToDosError(status) );
506 return FALSE;
508 return TRUE;
512 /***********************************************************************
513 * WriteFileGather (KERNEL32.@)
515 BOOL WINAPI WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
516 LPDWORD reserved, LPOVERLAPPED overlapped )
518 PIO_STATUS_BLOCK io_status;
519 LARGE_INTEGER offset;
520 void *cvalue = NULL;
521 NTSTATUS status;
523 TRACE( "%p %p %u %p\n", file, segments, count, overlapped );
525 offset.u.LowPart = overlapped->u.s.Offset;
526 offset.u.HighPart = overlapped->u.s.OffsetHigh;
527 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
528 io_status = (PIO_STATUS_BLOCK)overlapped;
529 io_status->u.Status = STATUS_PENDING;
530 io_status->Information = 0;
532 status = NtWriteFileGather( file, overlapped->hEvent, NULL, cvalue, io_status,
533 segments, count, &offset, NULL );
534 if (status) SetLastError( RtlNtStatusToDosError(status) );
535 return !status;
539 /***********************************************************************
540 * WriteFile (KERNEL32.@)
542 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
543 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
545 HANDLE hEvent = NULL;
546 LARGE_INTEGER offset;
547 PLARGE_INTEGER poffset = NULL;
548 NTSTATUS status;
549 IO_STATUS_BLOCK iosb;
550 PIO_STATUS_BLOCK piosb = &iosb;
551 LPVOID cvalue = NULL;
553 TRACE("%p %p %d %p %p\n", hFile, buffer, bytesToWrite, bytesWritten, overlapped );
555 if (is_console_handle(hFile))
556 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
558 if (overlapped)
560 offset.u.LowPart = overlapped->u.s.Offset;
561 offset.u.HighPart = overlapped->u.s.OffsetHigh;
562 poffset = &offset;
563 hEvent = overlapped->hEvent;
564 piosb = (PIO_STATUS_BLOCK)overlapped;
565 if (((ULONG_PTR)hEvent & 1) == 0) cvalue = overlapped;
567 piosb->u.Status = STATUS_PENDING;
568 piosb->Information = 0;
570 status = NtWriteFile(hFile, hEvent, NULL, cvalue, piosb,
571 buffer, bytesToWrite, poffset, NULL);
573 if (status == STATUS_PENDING && !overlapped)
575 WaitForSingleObject( hFile, INFINITE );
576 status = piosb->u.Status;
579 if (status != STATUS_PENDING && bytesWritten)
580 *bytesWritten = piosb->Information;
582 if (status && status != STATUS_TIMEOUT)
584 SetLastError( RtlNtStatusToDosError(status) );
585 return FALSE;
587 return TRUE;
591 /***********************************************************************
592 * GetOverlappedResult (KERNEL32.@)
594 * Check the result of an Asynchronous data transfer from a file.
596 * Parameters
597 * HANDLE hFile [in] handle of file to check on
598 * LPOVERLAPPED lpOverlapped [in/out] pointer to overlapped
599 * LPDWORD lpTransferred [in/out] number of bytes transferred
600 * BOOL bWait [in] wait for the transfer to complete ?
602 * RETURNS
603 * TRUE on success
604 * FALSE on failure
606 * If successful (and relevant) lpTransferred will hold the number of
607 * bytes transferred during the async operation.
609 BOOL WINAPI GetOverlappedResult(HANDLE hFile, LPOVERLAPPED lpOverlapped,
610 LPDWORD lpTransferred, BOOL bWait)
612 NTSTATUS status;
614 TRACE( "(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait );
616 status = lpOverlapped->Internal;
617 if (status == STATUS_PENDING)
619 if (!bWait)
621 SetLastError( ERROR_IO_INCOMPLETE );
622 return FALSE;
625 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : hFile,
626 INFINITE ) == WAIT_FAILED)
627 return FALSE;
628 status = lpOverlapped->Internal;
631 *lpTransferred = lpOverlapped->InternalHigh;
633 if (status) SetLastError( RtlNtStatusToDosError(status) );
634 return !status;
637 /***********************************************************************
638 * CancelIoEx (KERNEL32.@)
640 * Cancels pending I/O operations on a file given the overlapped used.
642 * PARAMS
643 * handle [I] File handle.
644 * lpOverlapped [I,OPT] pointer to overlapped (if null, cancel all)
646 * RETURNS
647 * Success: TRUE.
648 * Failure: FALSE, check GetLastError().
650 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
652 IO_STATUS_BLOCK io_status;
654 NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
655 if (io_status.u.Status)
657 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
658 return FALSE;
660 return TRUE;
663 /***********************************************************************
664 * CancelIo (KERNEL32.@)
666 * Cancels pending I/O operations initiated by the current thread on a file.
668 * PARAMS
669 * handle [I] File handle.
671 * RETURNS
672 * Success: TRUE.
673 * Failure: FALSE, check GetLastError().
675 BOOL WINAPI CancelIo(HANDLE handle)
677 IO_STATUS_BLOCK io_status;
679 NtCancelIoFile(handle, &io_status);
680 if (io_status.u.Status)
682 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
683 return FALSE;
685 return TRUE;
688 /***********************************************************************
689 * _hread (KERNEL32.@)
691 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
693 return _lread( hFile, buffer, count );
697 /***********************************************************************
698 * _hwrite (KERNEL32.@)
700 * experimentation yields that _lwrite:
701 * o truncates the file at the current position with
702 * a 0 len write
703 * o returns 0 on a 0 length write
704 * o works with console handles
707 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
709 DWORD result;
711 TRACE("%d %p %d\n", handle, buffer, count );
713 if (!count)
715 /* Expand or truncate at current position */
716 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
717 return 0;
719 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
720 return HFILE_ERROR;
721 return result;
725 /***********************************************************************
726 * _lclose (KERNEL32.@)
728 HFILE WINAPI _lclose( HFILE hFile )
730 TRACE("handle %d\n", hFile );
731 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
735 /***********************************************************************
736 * _lcreat (KERNEL32.@)
738 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
740 HANDLE hfile;
742 /* Mask off all flags not explicitly allowed by the doc */
743 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
744 TRACE("%s %02x\n", path, attr );
745 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
746 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
747 CREATE_ALWAYS, attr, 0 );
748 return HandleToLong(hfile);
752 /***********************************************************************
753 * _lopen (KERNEL32.@)
755 HFILE WINAPI _lopen( LPCSTR path, INT mode )
757 HANDLE hfile;
759 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
760 hfile = create_file_OF( path, mode & ~OF_CREATE );
761 return HandleToLong(hfile);
764 /***********************************************************************
765 * _lread (KERNEL32.@)
767 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
769 DWORD result;
770 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
771 return HFILE_ERROR;
772 return result;
776 /***********************************************************************
777 * _llseek (KERNEL32.@)
779 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
781 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
785 /***********************************************************************
786 * _lwrite (KERNEL32.@)
788 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
790 return (UINT)_hwrite( hFile, buffer, (LONG)count );
794 /***********************************************************************
795 * FlushFileBuffers (KERNEL32.@)
797 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
799 NTSTATUS nts;
800 IO_STATUS_BLOCK ioblk;
802 if (is_console_handle( hFile ))
804 /* this will fail (as expected) for an output handle */
805 return FlushConsoleInputBuffer( hFile );
807 nts = NtFlushBuffersFile( hFile, &ioblk );
808 if (nts != STATUS_SUCCESS)
810 SetLastError( RtlNtStatusToDosError( nts ) );
811 return FALSE;
814 return TRUE;
818 /***********************************************************************
819 * GetFileType (KERNEL32.@)
821 DWORD WINAPI GetFileType( HANDLE hFile )
823 FILE_FS_DEVICE_INFORMATION info;
824 IO_STATUS_BLOCK io;
825 NTSTATUS status;
827 if (hFile == (HANDLE)STD_INPUT_HANDLE || hFile == (HANDLE)STD_OUTPUT_HANDLE
828 || hFile == (HANDLE)STD_ERROR_HANDLE)
829 hFile = GetStdHandle((DWORD_PTR)hFile);
831 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
833 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
834 if (status != STATUS_SUCCESS)
836 SetLastError( RtlNtStatusToDosError(status) );
837 return FILE_TYPE_UNKNOWN;
840 switch(info.DeviceType)
842 case FILE_DEVICE_NULL:
843 case FILE_DEVICE_SERIAL_PORT:
844 case FILE_DEVICE_PARALLEL_PORT:
845 case FILE_DEVICE_TAPE:
846 case FILE_DEVICE_UNKNOWN:
847 return FILE_TYPE_CHAR;
848 case FILE_DEVICE_NAMED_PIPE:
849 return FILE_TYPE_PIPE;
850 default:
851 return FILE_TYPE_DISK;
856 /***********************************************************************
857 * GetFileInformationByHandle (KERNEL32.@)
859 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
861 FILE_ALL_INFORMATION all_info;
862 IO_STATUS_BLOCK io;
863 NTSTATUS status;
865 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
866 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
867 if (status == STATUS_SUCCESS)
869 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
870 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
871 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
872 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
873 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
874 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
875 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
876 info->dwVolumeSerialNumber = 0; /* FIXME */
877 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
878 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
879 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
880 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
881 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
882 return TRUE;
884 SetLastError( RtlNtStatusToDosError(status) );
885 return FALSE;
889 /***********************************************************************
890 * GetFileInformationByHandleEx (KERNEL32.@)
892 BOOL WINAPI GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
893 LPVOID info, DWORD size )
895 NTSTATUS status;
896 IO_STATUS_BLOCK io;
898 switch (class)
900 case FileBasicInfo:
901 case FileStandardInfo:
902 case FileRenameInfo:
903 case FileDispositionInfo:
904 case FileAllocationInfo:
905 case FileEndOfFileInfo:
906 case FileStreamInfo:
907 case FileCompressionInfo:
908 case FileAttributeTagInfo:
909 case FileIoPriorityHintInfo:
910 case FileRemoteProtocolInfo:
911 case FileFullDirectoryInfo:
912 case FileFullDirectoryRestartInfo:
913 case FileStorageInfo:
914 case FileAlignmentInfo:
915 case FileIdInfo:
916 case FileIdExtdDirectoryInfo:
917 case FileIdExtdDirectoryRestartInfo:
918 FIXME( "%p, %u, %p, %u\n", handle, class, info, size );
919 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
920 return FALSE;
922 case FileNameInfo:
923 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
924 if (status != STATUS_SUCCESS)
926 SetLastError( RtlNtStatusToDosError( status ) );
927 return FALSE;
929 return TRUE;
931 case FileIdBothDirectoryRestartInfo:
932 case FileIdBothDirectoryInfo:
933 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
934 FileIdBothDirectoryInformation, FALSE, NULL,
935 (class == FileIdBothDirectoryRestartInfo) );
936 if (status != STATUS_SUCCESS)
938 SetLastError( RtlNtStatusToDosError( status ) );
939 return FALSE;
941 return TRUE;
943 default:
944 SetLastError( ERROR_INVALID_PARAMETER );
945 return FALSE;
950 /***********************************************************************
951 * GetFileSize (KERNEL32.@)
953 * Retrieve the size of a file.
955 * PARAMS
956 * hFile [I] File to retrieve size of.
957 * filesizehigh [O] On return, the high bits of the file size.
959 * RETURNS
960 * Success: The low bits of the file size.
961 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
962 * check GetLastError() for values other than ERROR_SUCCESS.
964 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
966 LARGE_INTEGER size;
967 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
968 if (filesizehigh) *filesizehigh = size.u.HighPart;
969 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
970 return size.u.LowPart;
974 /***********************************************************************
975 * GetFileSizeEx (KERNEL32.@)
977 * Retrieve the size of a file.
979 * PARAMS
980 * hFile [I] File to retrieve size of.
981 * lpFileSIze [O] On return, the size of the file.
983 * RETURNS
984 * Success: TRUE.
985 * Failure: FALSE, check GetLastError().
987 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
989 FILE_STANDARD_INFORMATION info;
990 IO_STATUS_BLOCK io;
991 NTSTATUS status;
993 if (is_console_handle( hFile ))
995 SetLastError( ERROR_INVALID_HANDLE );
996 return FALSE;
999 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
1000 if (status == STATUS_SUCCESS)
1002 *lpFileSize = info.EndOfFile;
1003 return TRUE;
1005 SetLastError( RtlNtStatusToDosError(status) );
1006 return FALSE;
1010 /**************************************************************************
1011 * SetEndOfFile (KERNEL32.@)
1013 * Sets the current position as the end of the file.
1015 * PARAMS
1016 * hFile [I] File handle.
1018 * RETURNS
1019 * Success: TRUE.
1020 * Failure: FALSE, check GetLastError().
1022 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1024 FILE_POSITION_INFORMATION pos;
1025 FILE_END_OF_FILE_INFORMATION eof;
1026 IO_STATUS_BLOCK io;
1027 NTSTATUS status;
1029 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
1030 if (status == STATUS_SUCCESS)
1032 eof.EndOfFile = pos.CurrentByteOffset;
1033 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
1035 if (status == STATUS_SUCCESS) return TRUE;
1036 SetLastError( RtlNtStatusToDosError(status) );
1037 return FALSE;
1040 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1042 FIXME("%p %u %p %u - stub\n", file, class, info, size);
1043 return FALSE;
1046 /***********************************************************************
1047 * SetFilePointer (KERNEL32.@)
1049 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1051 LARGE_INTEGER dist, newpos;
1053 if (highword)
1055 dist.u.LowPart = distance;
1056 dist.u.HighPart = *highword;
1058 else dist.QuadPart = distance;
1060 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1062 if (highword) *highword = newpos.u.HighPart;
1063 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1064 return newpos.u.LowPart;
1068 /***********************************************************************
1069 * SetFilePointerEx (KERNEL32.@)
1071 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1072 LARGE_INTEGER *newpos, DWORD method )
1074 LONGLONG pos;
1075 IO_STATUS_BLOCK io;
1076 FILE_POSITION_INFORMATION info;
1078 switch(method)
1080 case FILE_BEGIN:
1081 pos = distance.QuadPart;
1082 break;
1083 case FILE_CURRENT:
1084 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1085 goto error;
1086 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1087 break;
1088 case FILE_END:
1090 FILE_END_OF_FILE_INFORMATION eof;
1091 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1092 goto error;
1093 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1095 break;
1096 default:
1097 SetLastError( ERROR_INVALID_PARAMETER );
1098 return FALSE;
1101 if (pos < 0)
1103 SetLastError( ERROR_NEGATIVE_SEEK );
1104 return FALSE;
1107 info.CurrentByteOffset.QuadPart = pos;
1108 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1109 goto error;
1110 if (newpos) newpos->QuadPart = pos;
1111 return TRUE;
1113 error:
1114 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1115 return FALSE;
1118 /***********************************************************************
1119 * SetFileValidData (KERNEL32.@)
1121 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1123 FILE_VALID_DATA_LENGTH_INFORMATION info;
1124 IO_STATUS_BLOCK io;
1125 NTSTATUS status;
1127 info.ValidDataLength.QuadPart = ValidDataLength;
1128 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1130 if (status == STATUS_SUCCESS) return TRUE;
1131 SetLastError( RtlNtStatusToDosError(status) );
1132 return FALSE;
1135 /***********************************************************************
1136 * GetFileTime (KERNEL32.@)
1138 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1139 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1141 FILE_BASIC_INFORMATION info;
1142 IO_STATUS_BLOCK io;
1143 NTSTATUS status;
1145 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1146 if (status == STATUS_SUCCESS)
1148 if (lpCreationTime)
1150 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1151 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1153 if (lpLastAccessTime)
1155 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1156 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1158 if (lpLastWriteTime)
1160 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1161 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1163 return TRUE;
1165 SetLastError( RtlNtStatusToDosError(status) );
1166 return FALSE;
1170 /***********************************************************************
1171 * SetFileTime (KERNEL32.@)
1173 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1174 const FILETIME *atime, const FILETIME *mtime )
1176 FILE_BASIC_INFORMATION info;
1177 IO_STATUS_BLOCK io;
1178 NTSTATUS status;
1180 memset( &info, 0, sizeof(info) );
1181 if (ctime)
1183 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1184 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1186 if (atime)
1188 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1189 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1191 if (mtime)
1193 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1194 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1197 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1198 if (status == STATUS_SUCCESS) return TRUE;
1199 SetLastError( RtlNtStatusToDosError(status) );
1200 return FALSE;
1204 /**************************************************************************
1205 * LockFile (KERNEL32.@)
1207 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1208 DWORD count_low, DWORD count_high )
1210 NTSTATUS status;
1211 LARGE_INTEGER count, offset;
1213 TRACE( "%p %x%08x %x%08x\n",
1214 hFile, offset_high, offset_low, count_high, count_low );
1216 count.u.LowPart = count_low;
1217 count.u.HighPart = count_high;
1218 offset.u.LowPart = offset_low;
1219 offset.u.HighPart = offset_high;
1221 status = NtLockFile( hFile, 0, NULL, NULL,
1222 NULL, &offset, &count, NULL, TRUE, TRUE );
1224 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1225 return !status;
1229 /**************************************************************************
1230 * LockFileEx [KERNEL32.@]
1232 * Locks a byte range within an open file for shared or exclusive access.
1234 * RETURNS
1235 * success: TRUE
1236 * failure: FALSE
1238 * NOTES
1239 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1241 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1242 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1244 NTSTATUS status;
1245 LARGE_INTEGER count, offset;
1246 LPVOID cvalue = NULL;
1248 if (reserved)
1250 SetLastError( ERROR_INVALID_PARAMETER );
1251 return FALSE;
1254 TRACE( "%p %x%08x %x%08x flags %x\n",
1255 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1256 count_high, count_low, flags );
1258 count.u.LowPart = count_low;
1259 count.u.HighPart = count_high;
1260 offset.u.LowPart = overlapped->u.s.Offset;
1261 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1263 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1265 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1266 NULL, &offset, &count, NULL,
1267 flags & LOCKFILE_FAIL_IMMEDIATELY,
1268 flags & LOCKFILE_EXCLUSIVE_LOCK );
1270 if (status) SetLastError( RtlNtStatusToDosError(status) );
1271 return !status;
1275 /**************************************************************************
1276 * UnlockFile (KERNEL32.@)
1278 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1279 DWORD count_low, DWORD count_high )
1281 NTSTATUS status;
1282 LARGE_INTEGER count, offset;
1284 count.u.LowPart = count_low;
1285 count.u.HighPart = count_high;
1286 offset.u.LowPart = offset_low;
1287 offset.u.HighPart = offset_high;
1289 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1290 if (status) SetLastError( RtlNtStatusToDosError(status) );
1291 return !status;
1295 /**************************************************************************
1296 * UnlockFileEx (KERNEL32.@)
1298 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1299 LPOVERLAPPED overlapped )
1301 if (reserved)
1303 SetLastError( ERROR_INVALID_PARAMETER );
1304 return FALSE;
1306 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1308 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1312 /*************************************************************************
1313 * SetHandleCount (KERNEL32.@)
1315 UINT WINAPI SetHandleCount( UINT count )
1317 return count;
1321 /**************************************************************************
1322 * Operations on file names *
1323 **************************************************************************/
1326 /*************************************************************************
1327 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1329 * Creates or opens an object, and returns a handle that can be used to
1330 * access that object.
1332 * PARAMS
1334 * filename [in] pointer to filename to be accessed
1335 * access [in] access mode requested
1336 * sharing [in] share mode
1337 * sa [in] pointer to security attributes
1338 * creation [in] how to create the file
1339 * attributes [in] attributes for newly created file
1340 * template [in] handle to file with extended attributes to copy
1342 * RETURNS
1343 * Success: Open handle to specified file
1344 * Failure: INVALID_HANDLE_VALUE
1346 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1347 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1348 DWORD attributes, HANDLE template )
1350 NTSTATUS status;
1351 UINT options;
1352 OBJECT_ATTRIBUTES attr;
1353 UNICODE_STRING nameW;
1354 IO_STATUS_BLOCK io;
1355 HANDLE ret;
1356 DWORD dosdev;
1357 const WCHAR *vxd_name = NULL;
1358 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1359 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1360 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1361 SECURITY_QUALITY_OF_SERVICE qos;
1363 static const UINT nt_disposition[5] =
1365 FILE_CREATE, /* CREATE_NEW */
1366 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1367 FILE_OPEN, /* OPEN_EXISTING */
1368 FILE_OPEN_IF, /* OPEN_ALWAYS */
1369 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1373 /* sanity checks */
1375 if (!filename || !filename[0])
1377 SetLastError( ERROR_PATH_NOT_FOUND );
1378 return INVALID_HANDLE_VALUE;
1381 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1382 (access & GENERIC_READ)?"GENERIC_READ ":"",
1383 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1384 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1385 (!access)?"QUERY_ACCESS ":"",
1386 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1387 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1388 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1389 creation, attributes);
1391 /* Open a console for CONIN$ or CONOUT$ */
1393 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1395 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1396 creation ? OPEN_EXISTING : 0);
1397 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1398 goto done;
1401 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1403 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1404 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1406 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1407 !strncmpiW( filename + 4, pipeW, 5 ) ||
1408 !strncmpiW( filename + 4, mailslotW, 9 ))
1410 dosdev = 0;
1412 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1414 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1416 else if (GetVersion() & 0x80000000)
1418 vxd_name = filename + 4;
1419 if (!creation) creation = OPEN_EXISTING;
1422 else dosdev = RtlIsDosDeviceName_U( filename );
1424 if (dosdev)
1426 static const WCHAR conW[] = {'C','O','N'};
1428 if (LOWORD(dosdev) == sizeof(conW) &&
1429 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1431 switch (access & (GENERIC_READ|GENERIC_WRITE))
1433 case GENERIC_READ:
1434 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1435 goto done;
1436 case GENERIC_WRITE:
1437 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1438 goto done;
1439 default:
1440 SetLastError( ERROR_FILE_NOT_FOUND );
1441 return INVALID_HANDLE_VALUE;
1446 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1448 SetLastError( ERROR_INVALID_PARAMETER );
1449 return INVALID_HANDLE_VALUE;
1452 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1454 SetLastError( ERROR_PATH_NOT_FOUND );
1455 return INVALID_HANDLE_VALUE;
1458 /* now call NtCreateFile */
1460 options = 0;
1461 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1462 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1463 else
1464 options |= FILE_NON_DIRECTORY_FILE;
1465 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1467 options |= FILE_DELETE_ON_CLOSE;
1468 access |= DELETE;
1470 if (attributes & FILE_FLAG_NO_BUFFERING)
1471 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1472 if (!(attributes & FILE_FLAG_OVERLAPPED))
1473 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1474 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1475 options |= FILE_RANDOM_ACCESS;
1476 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1478 attr.Length = sizeof(attr);
1479 attr.RootDirectory = 0;
1480 attr.Attributes = OBJ_CASE_INSENSITIVE;
1481 attr.ObjectName = &nameW;
1482 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1483 if (attributes & SECURITY_SQOS_PRESENT)
1485 qos.Length = sizeof(qos);
1486 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1487 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1488 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1489 attr.SecurityQualityOfService = &qos;
1491 else
1492 attr.SecurityQualityOfService = NULL;
1494 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1496 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
1497 sharing, nt_disposition[creation - CREATE_NEW],
1498 options, NULL, 0 );
1499 if (status)
1501 if (vxd_name && vxd_name[0])
1503 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1504 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1505 "__wine_vxd_open" );
1506 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1509 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1510 ret = INVALID_HANDLE_VALUE;
1512 /* In the case file creation was rejected due to CREATE_NEW flag
1513 * was specified and file with that name already exists, correct
1514 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1515 * Note: RtlNtStatusToDosError is not the subject to blame here.
1517 if (status == STATUS_OBJECT_NAME_COLLISION)
1518 SetLastError( ERROR_FILE_EXISTS );
1519 else
1520 SetLastError( RtlNtStatusToDosError(status) );
1522 else
1524 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1525 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1526 SetLastError( ERROR_ALREADY_EXISTS );
1527 else
1528 SetLastError( 0 );
1530 RtlFreeUnicodeString( &nameW );
1532 done:
1533 if (!ret) ret = INVALID_HANDLE_VALUE;
1534 TRACE("returning %p\n", ret);
1535 return ret;
1540 /*************************************************************************
1541 * CreateFileA (KERNEL32.@)
1543 * See CreateFileW.
1545 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1546 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1547 DWORD attributes, HANDLE template)
1549 WCHAR *nameW;
1551 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1552 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1555 /*************************************************************************
1556 * CreateFile2 (KERNEL32.@)
1558 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1559 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1561 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1562 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1563 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1565 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1567 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1570 /***********************************************************************
1571 * DeleteFileW (KERNEL32.@)
1573 * Delete a file.
1575 * PARAMS
1576 * path [I] Path to the file to delete.
1578 * RETURNS
1579 * Success: TRUE.
1580 * Failure: FALSE, check GetLastError().
1582 BOOL WINAPI DeleteFileW( LPCWSTR path )
1584 UNICODE_STRING nameW;
1585 OBJECT_ATTRIBUTES attr;
1586 NTSTATUS status;
1587 HANDLE hFile;
1588 IO_STATUS_BLOCK io;
1590 TRACE("%s\n", debugstr_w(path) );
1592 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1594 SetLastError( ERROR_PATH_NOT_FOUND );
1595 return FALSE;
1598 attr.Length = sizeof(attr);
1599 attr.RootDirectory = 0;
1600 attr.Attributes = OBJ_CASE_INSENSITIVE;
1601 attr.ObjectName = &nameW;
1602 attr.SecurityDescriptor = NULL;
1603 attr.SecurityQualityOfService = NULL;
1605 status = NtCreateFile(&hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
1606 &attr, &io, NULL, 0,
1607 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1608 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1609 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1611 RtlFreeUnicodeString( &nameW );
1612 if (status)
1614 SetLastError( RtlNtStatusToDosError(status) );
1615 return FALSE;
1617 return TRUE;
1621 /***********************************************************************
1622 * DeleteFileA (KERNEL32.@)
1624 * See DeleteFileW.
1626 BOOL WINAPI DeleteFileA( LPCSTR path )
1628 WCHAR *pathW;
1630 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1631 return DeleteFileW( pathW );
1635 /**************************************************************************
1636 * ReplaceFileW (KERNEL32.@)
1637 * ReplaceFile (KERNEL32.@)
1639 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1640 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1641 LPVOID lpExclude, LPVOID lpReserved)
1643 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1644 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1645 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1646 DWORD error = ERROR_SUCCESS;
1647 UINT replaced_flags;
1648 BOOL ret = FALSE;
1649 NTSTATUS status;
1650 IO_STATUS_BLOCK io;
1651 OBJECT_ATTRIBUTES attr;
1653 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1654 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1655 dwReplaceFlags, lpExclude, lpReserved);
1657 if (dwReplaceFlags)
1658 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1660 /* First two arguments are mandatory */
1661 if (!lpReplacedFileName || !lpReplacementFileName)
1663 SetLastError(ERROR_INVALID_PARAMETER);
1664 return FALSE;
1667 unix_replaced_name.Buffer = NULL;
1668 unix_replacement_name.Buffer = NULL;
1669 unix_backup_name.Buffer = NULL;
1671 attr.Length = sizeof(attr);
1672 attr.RootDirectory = 0;
1673 attr.Attributes = OBJ_CASE_INSENSITIVE;
1674 attr.ObjectName = NULL;
1675 attr.SecurityDescriptor = NULL;
1676 attr.SecurityQualityOfService = NULL;
1678 /* Open the "replaced" file for reading and writing */
1679 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1681 error = ERROR_PATH_NOT_FOUND;
1682 goto fail;
1684 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1685 attr.ObjectName = &nt_replaced_name;
1686 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1687 &attr, &io,
1688 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1689 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1690 if (status == STATUS_SUCCESS)
1691 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1692 RtlFreeUnicodeString(&nt_replaced_name);
1693 if (status != STATUS_SUCCESS)
1695 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1696 error = ERROR_FILE_NOT_FOUND;
1697 else
1698 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1699 goto fail;
1703 * Open the replacement file for reading, writing, and deleting
1704 * (writing and deleting are needed when finished)
1706 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1708 error = ERROR_PATH_NOT_FOUND;
1709 goto fail;
1711 attr.ObjectName = &nt_replacement_name;
1712 status = NtOpenFile(&hReplacement,
1713 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1714 &attr, &io, 0,
1715 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1716 if (status == STATUS_SUCCESS)
1717 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1718 RtlFreeUnicodeString(&nt_replacement_name);
1719 if (status != STATUS_SUCCESS)
1721 error = RtlNtStatusToDosError(status);
1722 goto fail;
1725 /* If the user wants a backup then that needs to be performed first */
1726 if (lpBackupFileName)
1728 UNICODE_STRING nt_backup_name;
1729 FILE_BASIC_INFORMATION replaced_info;
1731 /* Obtain the file attributes from the "replaced" file */
1732 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1733 sizeof(replaced_info),
1734 FileBasicInformation);
1735 if (status != STATUS_SUCCESS)
1737 error = RtlNtStatusToDosError(status);
1738 goto fail;
1741 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1743 error = ERROR_PATH_NOT_FOUND;
1744 goto fail;
1746 attr.ObjectName = &nt_backup_name;
1747 /* Open the backup with permissions to write over it */
1748 status = NtCreateFile(&hBackup, GENERIC_WRITE,
1749 &attr, &io, NULL, replaced_info.FileAttributes,
1750 FILE_SHARE_WRITE, FILE_OPEN_IF,
1751 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1752 NULL, 0);
1753 if (status == STATUS_SUCCESS)
1754 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1755 RtlFreeUnicodeString(&nt_backup_name);
1756 if (status != STATUS_SUCCESS)
1758 error = RtlNtStatusToDosError(status);
1759 goto fail;
1762 /* If an existing backup exists then copy over it */
1763 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1765 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1766 goto fail;
1771 * Now that the backup has been performed (if requested), copy the replacement
1772 * into place
1774 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1776 if (errno == EACCES)
1778 /* Inappropriate permissions on "replaced", rename will fail */
1779 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1780 goto fail;
1782 /* on failure we need to indicate whether a backup was made */
1783 if (!lpBackupFileName)
1784 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1785 else
1786 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1787 goto fail;
1789 /* Success! */
1790 ret = TRUE;
1792 /* Perform resource cleanup */
1793 fail:
1794 if (hBackup) CloseHandle(hBackup);
1795 if (hReplaced) CloseHandle(hReplaced);
1796 if (hReplacement) CloseHandle(hReplacement);
1797 RtlFreeAnsiString(&unix_backup_name);
1798 RtlFreeAnsiString(&unix_replacement_name);
1799 RtlFreeAnsiString(&unix_replaced_name);
1801 /* If there was an error, set the error code */
1802 if(!ret)
1803 SetLastError(error);
1804 return ret;
1808 /**************************************************************************
1809 * ReplaceFileA (KERNEL32.@)
1811 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1812 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1813 LPVOID lpExclude, LPVOID lpReserved)
1815 WCHAR *replacedW, *replacementW, *backupW = NULL;
1816 BOOL ret;
1818 /* This function only makes sense when the first two parameters are defined */
1819 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1821 SetLastError(ERROR_INVALID_PARAMETER);
1822 return FALSE;
1824 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1826 HeapFree( GetProcessHeap(), 0, replacedW );
1827 SetLastError(ERROR_INVALID_PARAMETER);
1828 return FALSE;
1830 /* The backup parameter, however, is optional */
1831 if (lpBackupFileName)
1833 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1835 HeapFree( GetProcessHeap(), 0, replacedW );
1836 HeapFree( GetProcessHeap(), 0, replacementW );
1837 SetLastError(ERROR_INVALID_PARAMETER);
1838 return FALSE;
1841 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1842 HeapFree( GetProcessHeap(), 0, replacedW );
1843 HeapFree( GetProcessHeap(), 0, replacementW );
1844 HeapFree( GetProcessHeap(), 0, backupW );
1845 return ret;
1849 /*************************************************************************
1850 * FindFirstFileExW (KERNEL32.@)
1852 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1853 * results as FindExSearchNameMatch
1855 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1856 LPVOID data, FINDEX_SEARCH_OPS search_op,
1857 LPVOID filter, DWORD flags)
1859 WCHAR *mask, *p;
1860 FIND_FIRST_INFO *info = NULL;
1861 UNICODE_STRING nt_name;
1862 OBJECT_ATTRIBUTES attr;
1863 IO_STATUS_BLOCK io;
1864 NTSTATUS status;
1865 DWORD device = 0;
1867 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1869 if (flags != 0)
1871 FIXME("flags not implemented 0x%08x\n", flags );
1873 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1875 FIXME("search_op not implemented 0x%08x\n", search_op);
1876 SetLastError( ERROR_INVALID_PARAMETER );
1877 return INVALID_HANDLE_VALUE;
1879 if (level != FindExInfoStandard && level != FindExInfoBasic)
1881 FIXME("info level %d not implemented\n", level );
1882 SetLastError( ERROR_INVALID_PARAMETER );
1883 return INVALID_HANDLE_VALUE;
1886 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1888 SetLastError( ERROR_PATH_NOT_FOUND );
1889 return INVALID_HANDLE_VALUE;
1892 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1894 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1895 goto error;
1898 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1900 static const WCHAR dotW[] = {'.',0};
1901 WCHAR *dir = NULL;
1903 /* we still need to check that the directory can be opened */
1905 if (HIWORD(device))
1907 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1909 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1910 goto error;
1912 memcpy( dir, filename, HIWORD(device) );
1913 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1915 RtlFreeUnicodeString( &nt_name );
1916 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1918 HeapFree( GetProcessHeap(), 0, dir );
1919 SetLastError( ERROR_PATH_NOT_FOUND );
1920 goto error;
1922 HeapFree( GetProcessHeap(), 0, dir );
1923 RtlInitUnicodeString( &info->mask, NULL );
1925 else if (!mask || !*mask)
1927 SetLastError( ERROR_FILE_NOT_FOUND );
1928 goto error;
1930 else
1932 if (!RtlCreateUnicodeString( &info->mask, mask ))
1934 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1935 goto error;
1938 /* truncate dir name before mask */
1939 *mask = 0;
1940 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1943 /* check if path is the root of the drive */
1944 info->is_root = FALSE;
1945 p = nt_name.Buffer + 4; /* skip \??\ prefix */
1946 if (p[0] && p[1] == ':')
1948 p += 2;
1949 while (*p == '\\') p++;
1950 info->is_root = (*p == 0);
1953 attr.Length = sizeof(attr);
1954 attr.RootDirectory = 0;
1955 attr.Attributes = OBJ_CASE_INSENSITIVE;
1956 attr.ObjectName = &nt_name;
1957 attr.SecurityDescriptor = NULL;
1958 attr.SecurityQualityOfService = NULL;
1960 status = NtOpenFile( &info->handle, GENERIC_READ, &attr, &io,
1961 FILE_SHARE_READ | FILE_SHARE_WRITE,
1962 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1964 if (status != STATUS_SUCCESS)
1966 RtlFreeUnicodeString( &info->mask );
1967 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1968 SetLastError( ERROR_PATH_NOT_FOUND );
1969 else
1970 SetLastError( RtlNtStatusToDosError(status) );
1971 goto error;
1974 RtlInitializeCriticalSection( &info->cs );
1975 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1976 info->path = nt_name;
1977 info->magic = FIND_FIRST_MAGIC;
1978 info->data_pos = 0;
1979 info->data_len = 0;
1980 info->data_size = 0;
1981 info->data = NULL;
1982 info->search_op = search_op;
1983 info->level = level;
1985 if (device)
1987 WIN32_FIND_DATAW *wfd = data;
1989 memset( wfd, 0, sizeof(*wfd) );
1990 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1991 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1992 CloseHandle( info->handle );
1993 info->handle = 0;
1995 else
1997 IO_STATUS_BLOCK io;
1998 BOOL has_wildcard = strpbrkW( info->mask.Buffer, wildcardsW ) != NULL;
2000 info->data_size = has_wildcard ? 8192 : max_entry_size * 2;
2002 while (info->data_size)
2004 if (!(info->data = HeapAlloc( GetProcessHeap(), 0, info->data_size )))
2006 FindClose( info );
2007 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2008 return INVALID_HANDLE_VALUE;
2011 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2012 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
2013 if (io.u.Status)
2015 FindClose( info );
2016 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2017 return INVALID_HANDLE_VALUE;
2020 if (io.Information < info->data_size - max_entry_size)
2022 info->data_size = 0; /* we read everything */
2024 else if (info->data_size < 1024 * 1024)
2026 HeapFree( GetProcessHeap(), 0, info->data );
2027 info->data_size *= 2;
2029 else break;
2032 info->data_len = io.Information;
2033 if (!info->data_size && has_wildcard) /* release unused buffer space */
2034 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, info->data, info->data_len );
2036 if (!FindNextFileW( info, data ))
2038 TRACE( "%s not found\n", debugstr_w(filename) );
2039 FindClose( info );
2040 SetLastError( ERROR_FILE_NOT_FOUND );
2041 return INVALID_HANDLE_VALUE;
2043 if (!has_wildcard) /* we can't find two files with the same name */
2045 CloseHandle( info->handle );
2046 HeapFree( GetProcessHeap(), 0, info->data );
2047 info->handle = 0;
2048 info->data = NULL;
2051 return info;
2053 error:
2054 HeapFree( GetProcessHeap(), 0, info );
2055 RtlFreeUnicodeString( &nt_name );
2056 return INVALID_HANDLE_VALUE;
2060 /*************************************************************************
2061 * FindNextFileW (KERNEL32.@)
2063 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2065 FIND_FIRST_INFO *info;
2066 FILE_BOTH_DIR_INFORMATION *dir_info;
2067 BOOL ret = FALSE;
2069 TRACE("%p %p\n", handle, data);
2071 if (!handle || handle == INVALID_HANDLE_VALUE)
2073 SetLastError( ERROR_INVALID_HANDLE );
2074 return ret;
2076 info = handle;
2077 if (info->magic != FIND_FIRST_MAGIC)
2079 SetLastError( ERROR_INVALID_HANDLE );
2080 return ret;
2083 RtlEnterCriticalSection( &info->cs );
2085 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2086 else for (;;)
2088 if (info->data_pos >= info->data_len) /* need to read some more data */
2090 IO_STATUS_BLOCK io;
2092 if (info->data_size)
2093 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2094 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
2095 else
2096 io.u.Status = STATUS_NO_MORE_FILES;
2098 if (io.u.Status)
2100 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2101 if (io.u.Status == STATUS_NO_MORE_FILES)
2103 CloseHandle( info->handle );
2104 HeapFree( GetProcessHeap(), 0, info->data );
2105 info->handle = 0;
2106 info->data = NULL;
2108 break;
2110 info->data_len = io.Information;
2111 info->data_pos = 0;
2114 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2116 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2117 else info->data_pos = info->data_len;
2119 /* don't return '.' and '..' in the root of the drive */
2120 if (info->is_root)
2122 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2123 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2124 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2127 /* check for dir symlink */
2128 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2129 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2130 strpbrkW( info->mask.Buffer, wildcardsW ))
2132 if (!check_dir_symlink( info, dir_info )) continue;
2135 data->dwFileAttributes = dir_info->FileAttributes;
2136 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2137 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2138 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2139 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2140 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2141 data->dwReserved0 = 0;
2142 data->dwReserved1 = 0;
2144 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2145 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2147 if (info->level != FindExInfoBasic)
2149 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2150 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2152 else
2153 data->cAlternateFileName[0] = 0;
2155 TRACE("returning %s (%s)\n",
2156 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2158 ret = TRUE;
2159 break;
2162 RtlLeaveCriticalSection( &info->cs );
2163 return ret;
2167 /*************************************************************************
2168 * FindClose (KERNEL32.@)
2170 BOOL WINAPI FindClose( HANDLE handle )
2172 FIND_FIRST_INFO *info = handle;
2174 if (!handle || handle == INVALID_HANDLE_VALUE)
2176 SetLastError( ERROR_INVALID_HANDLE );
2177 return FALSE;
2180 __TRY
2182 if (info->magic == FIND_FIRST_MAGIC)
2184 RtlEnterCriticalSection( &info->cs );
2185 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2187 info->magic = 0;
2188 if (info->handle) CloseHandle( info->handle );
2189 info->handle = 0;
2190 RtlFreeUnicodeString( &info->mask );
2191 info->mask.Buffer = NULL;
2192 RtlFreeUnicodeString( &info->path );
2193 info->data_pos = 0;
2194 info->data_len = 0;
2195 HeapFree( GetProcessHeap(), 0, info->data );
2196 RtlLeaveCriticalSection( &info->cs );
2197 info->cs.DebugInfo->Spare[0] = 0;
2198 RtlDeleteCriticalSection( &info->cs );
2199 HeapFree( GetProcessHeap(), 0, info );
2203 __EXCEPT_PAGE_FAULT
2205 WARN("Illegal handle %p\n", handle);
2206 SetLastError( ERROR_INVALID_HANDLE );
2207 return FALSE;
2209 __ENDTRY
2211 return TRUE;
2215 /*************************************************************************
2216 * FindFirstFileA (KERNEL32.@)
2218 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2220 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2221 FindExSearchNameMatch, NULL, 0);
2224 /*************************************************************************
2225 * FindFirstFileExA (KERNEL32.@)
2227 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2228 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2229 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2231 HANDLE handle;
2232 WIN32_FIND_DATAA *dataA;
2233 WIN32_FIND_DATAW dataW;
2234 WCHAR *nameW;
2236 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2238 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2239 if (handle == INVALID_HANDLE_VALUE) return handle;
2241 dataA = lpFindFileData;
2242 dataA->dwFileAttributes = dataW.dwFileAttributes;
2243 dataA->ftCreationTime = dataW.ftCreationTime;
2244 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2245 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2246 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2247 dataA->nFileSizeLow = dataW.nFileSizeLow;
2248 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2249 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2250 sizeof(dataA->cAlternateFileName) );
2251 return handle;
2255 /*************************************************************************
2256 * FindFirstFileW (KERNEL32.@)
2258 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2260 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2261 FindExSearchNameMatch, NULL, 0);
2265 /*************************************************************************
2266 * FindNextFileA (KERNEL32.@)
2268 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2270 WIN32_FIND_DATAW dataW;
2272 if (!FindNextFileW( handle, &dataW )) return FALSE;
2273 data->dwFileAttributes = dataW.dwFileAttributes;
2274 data->ftCreationTime = dataW.ftCreationTime;
2275 data->ftLastAccessTime = dataW.ftLastAccessTime;
2276 data->ftLastWriteTime = dataW.ftLastWriteTime;
2277 data->nFileSizeHigh = dataW.nFileSizeHigh;
2278 data->nFileSizeLow = dataW.nFileSizeLow;
2279 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2280 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2281 sizeof(data->cAlternateFileName) );
2282 return TRUE;
2286 /**************************************************************************
2287 * GetFileAttributesW (KERNEL32.@)
2289 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2291 FILE_BASIC_INFORMATION info;
2292 UNICODE_STRING nt_name;
2293 OBJECT_ATTRIBUTES attr;
2294 NTSTATUS status;
2296 TRACE("%s\n", debugstr_w(name));
2298 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2300 SetLastError( ERROR_PATH_NOT_FOUND );
2301 return INVALID_FILE_ATTRIBUTES;
2304 attr.Length = sizeof(attr);
2305 attr.RootDirectory = 0;
2306 attr.Attributes = OBJ_CASE_INSENSITIVE;
2307 attr.ObjectName = &nt_name;
2308 attr.SecurityDescriptor = NULL;
2309 attr.SecurityQualityOfService = NULL;
2311 status = NtQueryAttributesFile( &attr, &info );
2312 RtlFreeUnicodeString( &nt_name );
2314 if (status == STATUS_SUCCESS) return info.FileAttributes;
2316 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2317 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2319 SetLastError( RtlNtStatusToDosError(status) );
2320 return INVALID_FILE_ATTRIBUTES;
2324 /**************************************************************************
2325 * GetFileAttributesA (KERNEL32.@)
2327 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2329 WCHAR *nameW;
2331 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2332 return GetFileAttributesW( nameW );
2336 /**************************************************************************
2337 * SetFileAttributesW (KERNEL32.@)
2339 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2341 UNICODE_STRING nt_name;
2342 OBJECT_ATTRIBUTES attr;
2343 IO_STATUS_BLOCK io;
2344 NTSTATUS status;
2345 HANDLE handle;
2347 TRACE("%s %x\n", debugstr_w(name), attributes);
2349 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2351 SetLastError( ERROR_PATH_NOT_FOUND );
2352 return FALSE;
2355 attr.Length = sizeof(attr);
2356 attr.RootDirectory = 0;
2357 attr.Attributes = OBJ_CASE_INSENSITIVE;
2358 attr.ObjectName = &nt_name;
2359 attr.SecurityDescriptor = NULL;
2360 attr.SecurityQualityOfService = NULL;
2362 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2363 RtlFreeUnicodeString( &nt_name );
2365 if (status == STATUS_SUCCESS)
2367 FILE_BASIC_INFORMATION info;
2369 memset( &info, 0, sizeof(info) );
2370 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2371 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2372 NtClose( handle );
2375 if (status == STATUS_SUCCESS) return TRUE;
2376 SetLastError( RtlNtStatusToDosError(status) );
2377 return FALSE;
2381 /**************************************************************************
2382 * SetFileAttributesA (KERNEL32.@)
2384 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2386 WCHAR *nameW;
2388 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2389 return SetFileAttributesW( nameW, attributes );
2393 /**************************************************************************
2394 * GetFileAttributesExW (KERNEL32.@)
2396 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2398 FILE_NETWORK_OPEN_INFORMATION info;
2399 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2400 UNICODE_STRING nt_name;
2401 OBJECT_ATTRIBUTES attr;
2402 NTSTATUS status;
2404 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2406 if (level != GetFileExInfoStandard)
2408 SetLastError( ERROR_INVALID_PARAMETER );
2409 return FALSE;
2412 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2414 SetLastError( ERROR_PATH_NOT_FOUND );
2415 return FALSE;
2418 attr.Length = sizeof(attr);
2419 attr.RootDirectory = 0;
2420 attr.Attributes = OBJ_CASE_INSENSITIVE;
2421 attr.ObjectName = &nt_name;
2422 attr.SecurityDescriptor = NULL;
2423 attr.SecurityQualityOfService = NULL;
2425 status = NtQueryFullAttributesFile( &attr, &info );
2426 RtlFreeUnicodeString( &nt_name );
2428 if (status != STATUS_SUCCESS)
2430 SetLastError( RtlNtStatusToDosError(status) );
2431 return FALSE;
2434 data->dwFileAttributes = info.FileAttributes;
2435 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2436 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2437 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2438 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2439 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2440 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2441 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2442 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2443 return TRUE;
2447 /**************************************************************************
2448 * GetFileAttributesExA (KERNEL32.@)
2450 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2452 WCHAR *nameW;
2454 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2455 return GetFileAttributesExW( nameW, level, ptr );
2459 /******************************************************************************
2460 * GetCompressedFileSizeW (KERNEL32.@)
2462 * Get the actual number of bytes used on disk.
2464 * RETURNS
2465 * Success: Low-order doubleword of number of bytes
2466 * Failure: INVALID_FILE_SIZE
2468 DWORD WINAPI GetCompressedFileSizeW(
2469 LPCWSTR name, /* [in] Pointer to name of file */
2470 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2472 UNICODE_STRING nt_name;
2473 OBJECT_ATTRIBUTES attr;
2474 IO_STATUS_BLOCK io;
2475 NTSTATUS status;
2476 HANDLE handle;
2477 DWORD ret = INVALID_FILE_SIZE;
2479 TRACE("%s %p\n", debugstr_w(name), size_high);
2481 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2483 SetLastError( ERROR_PATH_NOT_FOUND );
2484 return INVALID_FILE_SIZE;
2487 attr.Length = sizeof(attr);
2488 attr.RootDirectory = 0;
2489 attr.Attributes = OBJ_CASE_INSENSITIVE;
2490 attr.ObjectName = &nt_name;
2491 attr.SecurityDescriptor = NULL;
2492 attr.SecurityQualityOfService = NULL;
2494 status = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2495 RtlFreeUnicodeString( &nt_name );
2497 if (status == STATUS_SUCCESS)
2499 /* we don't support compressed files, simply return the file size */
2500 ret = GetFileSize( handle, size_high );
2501 NtClose( handle );
2503 else SetLastError( RtlNtStatusToDosError(status) );
2505 return ret;
2509 /******************************************************************************
2510 * GetCompressedFileSizeA (KERNEL32.@)
2512 * See GetCompressedFileSizeW.
2514 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2516 WCHAR *nameW;
2518 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2519 return GetCompressedFileSizeW( nameW, size_high );
2523 /***********************************************************************
2524 * OpenVxDHandle (KERNEL32.@)
2526 * This function is supposed to return the corresponding Ring 0
2527 * ("kernel") handle for a Ring 3 handle in Win9x.
2528 * Evidently, Wine will have problems with this. But we try anyway,
2529 * maybe it helps...
2531 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2533 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2534 return hHandleRing3;
2538 /****************************************************************************
2539 * DeviceIoControl (KERNEL32.@)
2541 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2542 LPVOID lpvInBuffer, DWORD cbInBuffer,
2543 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2544 LPDWORD lpcbBytesReturned,
2545 LPOVERLAPPED lpOverlapped)
2547 NTSTATUS status;
2549 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2550 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2551 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2553 /* Check if this is a user defined control code for a VxD */
2555 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2557 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2558 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2559 DeviceIoProc proc = NULL;
2561 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2562 "__wine_vxd_get_proc" );
2563 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2564 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2565 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2568 /* Not a VxD, let ntdll handle it */
2570 if (lpOverlapped)
2572 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2573 lpOverlapped->Internal = STATUS_PENDING;
2574 lpOverlapped->InternalHigh = 0;
2575 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2576 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2577 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2578 dwIoControlCode, lpvInBuffer, cbInBuffer,
2579 lpvOutBuffer, cbOutBuffer);
2580 else
2581 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2582 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2583 dwIoControlCode, lpvInBuffer, cbInBuffer,
2584 lpvOutBuffer, cbOutBuffer);
2585 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2587 else
2589 IO_STATUS_BLOCK iosb;
2591 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2592 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2593 dwIoControlCode, lpvInBuffer, cbInBuffer,
2594 lpvOutBuffer, cbOutBuffer);
2595 else
2596 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2597 dwIoControlCode, lpvInBuffer, cbInBuffer,
2598 lpvOutBuffer, cbOutBuffer);
2599 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2601 if (status) SetLastError( RtlNtStatusToDosError(status) );
2602 return !status;
2606 /***********************************************************************
2607 * OpenFile (KERNEL32.@)
2609 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2611 HANDLE handle;
2612 FILETIME filetime;
2613 WORD filedatetime[2];
2615 if (!ofs) return HFILE_ERROR;
2617 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2618 ((mode & 0x3 )==OF_READ)?"OF_READ":
2619 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2620 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2621 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2622 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2623 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2624 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2625 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2626 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2627 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2628 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2629 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2630 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2631 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2632 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2633 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2634 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2638 ofs->cBytes = sizeof(OFSTRUCT);
2639 ofs->nErrCode = 0;
2640 if (mode & OF_REOPEN) name = ofs->szPathName;
2642 if (!name) return HFILE_ERROR;
2644 TRACE("%s %04x\n", name, mode );
2646 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2647 Are there any cases where getting the path here is wrong?
2648 Uwe Bonnes 1997 Apr 2 */
2649 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2651 /* OF_PARSE simply fills the structure */
2653 if (mode & OF_PARSE)
2655 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2656 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2657 return 0;
2660 /* OF_CREATE is completely different from all other options, so
2661 handle it first */
2663 if (mode & OF_CREATE)
2665 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2666 goto error;
2668 else
2670 /* Now look for the file */
2672 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2673 goto error;
2675 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2677 if (mode & OF_DELETE)
2679 if (!DeleteFileA( ofs->szPathName )) goto error;
2680 TRACE("(%s): OF_DELETE return = OK\n", name);
2681 return TRUE;
2684 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2685 if (handle == INVALID_HANDLE_VALUE) goto error;
2687 GetFileTime( handle, NULL, NULL, &filetime );
2688 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2689 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2691 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2693 CloseHandle( handle );
2694 WARN("(%s): OF_VERIFY failed\n", name );
2695 /* FIXME: what error here? */
2696 SetLastError( ERROR_FILE_NOT_FOUND );
2697 goto error;
2700 ofs->Reserved1 = filedatetime[0];
2701 ofs->Reserved2 = filedatetime[1];
2703 TRACE("(%s): OK, return = %p\n", name, handle );
2704 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2706 CloseHandle( handle );
2707 return TRUE;
2709 return HandleToLong(handle);
2711 error: /* We get here if there was an error opening the file */
2712 ofs->nErrCode = GetLastError();
2713 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2714 return HFILE_ERROR;
2718 /***********************************************************************
2719 * OpenFileById (KERNEL32.@)
2721 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2722 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2724 UINT options;
2725 HANDLE result;
2726 OBJECT_ATTRIBUTES attr;
2727 NTSTATUS status;
2728 IO_STATUS_BLOCK io;
2729 UNICODE_STRING objectName;
2731 if (!id)
2733 SetLastError( ERROR_INVALID_PARAMETER );
2734 return INVALID_HANDLE_VALUE;
2737 options = FILE_OPEN_BY_FILE_ID;
2738 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2739 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2740 else
2741 options |= FILE_NON_DIRECTORY_FILE;
2742 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2743 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2744 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2745 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2747 objectName.Length = sizeof(ULONGLONG);
2748 objectName.Buffer = (WCHAR *)&id->u.FileId;
2749 attr.Length = sizeof(attr);
2750 attr.RootDirectory = handle;
2751 attr.Attributes = 0;
2752 attr.ObjectName = &objectName;
2753 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2754 attr.SecurityQualityOfService = NULL;
2755 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2757 status = NtCreateFile( &result, access, &attr, &io, NULL, flags,
2758 share, OPEN_EXISTING, options, NULL, 0 );
2759 if (status != STATUS_SUCCESS)
2761 SetLastError( RtlNtStatusToDosError( status ) );
2762 return INVALID_HANDLE_VALUE;
2764 return result;
2768 /***********************************************************************
2769 * K32EnumDeviceDrivers (KERNEL32.@)
2771 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2773 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2775 if (needed)
2776 *needed = 0;
2778 return TRUE;
2781 /***********************************************************************
2782 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2784 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR 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 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2797 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2799 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2801 if (base_name && size)
2802 base_name[0] = '\0';
2804 return 0;
2807 /***********************************************************************
2808 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2810 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR 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;
2820 /***********************************************************************
2821 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2823 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2825 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2827 if (file_name && size)
2828 file_name[0] = '\0';
2830 return 0;