TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / dlls / kernel32 / file.c
blobb6dba6ac763d678f1666ee3b8afa0252917272aa
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 * CancelSynchronousIo (KERNEL32.@)
691 * Marks pending synchronous I/O operations issued by the specified thread as cancelled
693 * PARAMS
694 * handle [I] handle to the thread whose I/O operations should be cancelled
696 * RETURNS
697 * Success: TRUE.
698 * Failure: FALSE, check GetLastError().
700 BOOL WINAPI CancelSynchronousIo(HANDLE thread)
702 FIXME("(%p): stub\n", thread);
703 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
704 return FALSE;
707 /***********************************************************************
708 * _hread (KERNEL32.@)
710 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
712 return _lread( hFile, buffer, count );
716 /***********************************************************************
717 * _hwrite (KERNEL32.@)
719 * experimentation yields that _lwrite:
720 * o truncates the file at the current position with
721 * a 0 len write
722 * o returns 0 on a 0 length write
723 * o works with console handles
726 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
728 DWORD result;
730 TRACE("%d %p %d\n", handle, buffer, count );
732 if (!count)
734 /* Expand or truncate at current position */
735 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
736 return 0;
738 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
739 return HFILE_ERROR;
740 return result;
744 /***********************************************************************
745 * _lclose (KERNEL32.@)
747 HFILE WINAPI _lclose( HFILE hFile )
749 TRACE("handle %d\n", hFile );
750 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
754 /***********************************************************************
755 * _lcreat (KERNEL32.@)
757 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
759 HANDLE hfile;
761 /* Mask off all flags not explicitly allowed by the doc */
762 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
763 TRACE("%s %02x\n", path, attr );
764 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
765 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
766 CREATE_ALWAYS, attr, 0 );
767 return HandleToLong(hfile);
771 /***********************************************************************
772 * _lopen (KERNEL32.@)
774 HFILE WINAPI _lopen( LPCSTR path, INT mode )
776 HANDLE hfile;
778 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
779 hfile = create_file_OF( path, mode & ~OF_CREATE );
780 return HandleToLong(hfile);
783 /***********************************************************************
784 * _lread (KERNEL32.@)
786 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
788 DWORD result;
789 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
790 return HFILE_ERROR;
791 return result;
795 /***********************************************************************
796 * _llseek (KERNEL32.@)
798 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
800 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
804 /***********************************************************************
805 * _lwrite (KERNEL32.@)
807 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
809 return (UINT)_hwrite( hFile, buffer, (LONG)count );
813 /***********************************************************************
814 * FlushFileBuffers (KERNEL32.@)
816 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
818 NTSTATUS nts;
819 IO_STATUS_BLOCK ioblk;
821 if (is_console_handle( hFile ))
823 /* this will fail (as expected) for an output handle */
824 return FlushConsoleInputBuffer( hFile );
826 nts = NtFlushBuffersFile( hFile, &ioblk );
827 if (nts != STATUS_SUCCESS)
829 SetLastError( RtlNtStatusToDosError( nts ) );
830 return FALSE;
833 return TRUE;
837 /***********************************************************************
838 * GetFileType (KERNEL32.@)
840 DWORD WINAPI GetFileType( HANDLE hFile )
842 FILE_FS_DEVICE_INFORMATION info;
843 IO_STATUS_BLOCK io;
844 NTSTATUS status;
846 if (hFile == (HANDLE)STD_INPUT_HANDLE || hFile == (HANDLE)STD_OUTPUT_HANDLE
847 || hFile == (HANDLE)STD_ERROR_HANDLE)
848 hFile = GetStdHandle((DWORD_PTR)hFile);
850 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
852 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
853 if (status != STATUS_SUCCESS)
855 SetLastError( RtlNtStatusToDosError(status) );
856 return FILE_TYPE_UNKNOWN;
859 switch(info.DeviceType)
861 case FILE_DEVICE_NULL:
862 case FILE_DEVICE_SERIAL_PORT:
863 case FILE_DEVICE_PARALLEL_PORT:
864 case FILE_DEVICE_TAPE:
865 case FILE_DEVICE_UNKNOWN:
866 return FILE_TYPE_CHAR;
867 case FILE_DEVICE_NAMED_PIPE:
868 return FILE_TYPE_PIPE;
869 default:
870 return FILE_TYPE_DISK;
875 /***********************************************************************
876 * GetFileInformationByHandle (KERNEL32.@)
878 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
880 FILE_ALL_INFORMATION all_info;
881 IO_STATUS_BLOCK io;
882 NTSTATUS status;
884 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
885 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
886 if (status == STATUS_SUCCESS)
888 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
889 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
890 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
891 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
892 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
893 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
894 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
895 info->dwVolumeSerialNumber = 0; /* FIXME */
896 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
897 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
898 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
899 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
900 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
901 return TRUE;
903 SetLastError( RtlNtStatusToDosError(status) );
904 return FALSE;
908 /***********************************************************************
909 * GetFileInformationByHandleEx (KERNEL32.@)
911 BOOL WINAPI GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
912 LPVOID info, DWORD size )
914 NTSTATUS status;
915 IO_STATUS_BLOCK io;
917 switch (class)
919 case FileStreamInfo:
920 case FileCompressionInfo:
921 case FileAttributeTagInfo:
922 case FileRemoteProtocolInfo:
923 case FileFullDirectoryInfo:
924 case FileFullDirectoryRestartInfo:
925 case FileStorageInfo:
926 case FileAlignmentInfo:
927 case FileIdInfo:
928 case FileIdExtdDirectoryInfo:
929 case FileIdExtdDirectoryRestartInfo:
930 FIXME( "%p, %u, %p, %u\n", handle, class, info, size );
931 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
932 return FALSE;
934 case FileBasicInfo:
935 status = NtQueryInformationFile( handle, &io, info, size, FileBasicInformation );
936 break;
938 case FileStandardInfo:
939 status = NtQueryInformationFile( handle, &io, info, size, FileStandardInformation );
940 break;
942 case FileNameInfo:
943 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
944 break;
946 case FileIdBothDirectoryRestartInfo:
947 case FileIdBothDirectoryInfo:
948 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
949 FileIdBothDirectoryInformation, FALSE, NULL,
950 (class == FileIdBothDirectoryRestartInfo) );
951 break;
953 case FileRenameInfo:
954 case FileDispositionInfo:
955 case FileAllocationInfo:
956 case FileIoPriorityHintInfo:
957 case FileEndOfFileInfo:
958 default:
959 SetLastError( ERROR_INVALID_PARAMETER );
960 return FALSE;
963 if (status != STATUS_SUCCESS)
965 SetLastError( RtlNtStatusToDosError( status ) );
966 return FALSE;
968 return TRUE;
972 /***********************************************************************
973 * GetFileSize (KERNEL32.@)
975 * Retrieve the size of a file.
977 * PARAMS
978 * hFile [I] File to retrieve size of.
979 * filesizehigh [O] On return, the high bits of the file size.
981 * RETURNS
982 * Success: The low bits of the file size.
983 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
984 * check GetLastError() for values other than ERROR_SUCCESS.
986 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
988 LARGE_INTEGER size;
989 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
990 if (filesizehigh) *filesizehigh = size.u.HighPart;
991 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
992 return size.u.LowPart;
996 /***********************************************************************
997 * GetFileSizeEx (KERNEL32.@)
999 * Retrieve the size of a file.
1001 * PARAMS
1002 * hFile [I] File to retrieve size of.
1003 * lpFileSIze [O] On return, the size of the file.
1005 * RETURNS
1006 * Success: TRUE.
1007 * Failure: FALSE, check GetLastError().
1009 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
1011 FILE_STANDARD_INFORMATION info;
1012 IO_STATUS_BLOCK io;
1013 NTSTATUS status;
1015 if (is_console_handle( hFile ))
1017 SetLastError( ERROR_INVALID_HANDLE );
1018 return FALSE;
1021 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
1022 if (status == STATUS_SUCCESS)
1024 *lpFileSize = info.EndOfFile;
1025 return TRUE;
1027 SetLastError( RtlNtStatusToDosError(status) );
1028 return FALSE;
1032 /**************************************************************************
1033 * SetEndOfFile (KERNEL32.@)
1035 * Sets the current position as the end of the file.
1037 * PARAMS
1038 * hFile [I] File handle.
1040 * RETURNS
1041 * Success: TRUE.
1042 * Failure: FALSE, check GetLastError().
1044 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1046 FILE_POSITION_INFORMATION pos;
1047 FILE_END_OF_FILE_INFORMATION eof;
1048 IO_STATUS_BLOCK io;
1049 NTSTATUS status;
1051 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
1052 if (status == STATUS_SUCCESS)
1054 eof.EndOfFile = pos.CurrentByteOffset;
1055 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
1057 if (status == STATUS_SUCCESS) return TRUE;
1058 SetLastError( RtlNtStatusToDosError(status) );
1059 return FALSE;
1062 /**************************************************************************
1063 * SetFileCompletionNotificationModes (KERNEL32.@)
1065 BOOL WINAPI SetFileCompletionNotificationModes( HANDLE handle, UCHAR flags )
1067 FIXME("%p %x - stub\n", handle, flags);
1068 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1069 return FALSE;
1073 /***********************************************************************
1074 * SetFileInformationByHandle (KERNEL32.@)
1076 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1078 NTSTATUS status;
1079 IO_STATUS_BLOCK io;
1081 TRACE( "%p %u %p %u\n", file, class, info, size );
1083 switch (class)
1085 case FileBasicInfo:
1086 case FileNameInfo:
1087 case FileRenameInfo:
1088 case FileAllocationInfo:
1089 case FileEndOfFileInfo:
1090 case FileStreamInfo:
1091 case FileIdBothDirectoryInfo:
1092 case FileIdBothDirectoryRestartInfo:
1093 case FileIoPriorityHintInfo:
1094 case FileFullDirectoryInfo:
1095 case FileFullDirectoryRestartInfo:
1096 case FileStorageInfo:
1097 case FileAlignmentInfo:
1098 case FileIdInfo:
1099 case FileIdExtdDirectoryInfo:
1100 case FileIdExtdDirectoryRestartInfo:
1101 FIXME( "%p, %u, %p, %u\n", file, class, info, size );
1102 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1103 return FALSE;
1105 case FileDispositionInfo:
1106 status = NtSetInformationFile( file, &io, info, size, FileDispositionInformation );
1107 break;
1109 case FileStandardInfo:
1110 case FileCompressionInfo:
1111 case FileAttributeTagInfo:
1112 case FileRemoteProtocolInfo:
1113 default:
1114 SetLastError( ERROR_INVALID_PARAMETER );
1115 return FALSE;
1118 if (status != STATUS_SUCCESS)
1120 SetLastError( RtlNtStatusToDosError( status ) );
1121 return FALSE;
1123 return TRUE;
1127 /***********************************************************************
1128 * SetFilePointer (KERNEL32.@)
1130 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1132 LARGE_INTEGER dist, newpos;
1134 if (highword)
1136 dist.u.LowPart = distance;
1137 dist.u.HighPart = *highword;
1139 else dist.QuadPart = distance;
1141 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1143 if (highword) *highword = newpos.u.HighPart;
1144 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1145 return newpos.u.LowPart;
1149 /***********************************************************************
1150 * SetFilePointerEx (KERNEL32.@)
1152 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1153 LARGE_INTEGER *newpos, DWORD method )
1155 LONGLONG pos;
1156 IO_STATUS_BLOCK io;
1157 FILE_POSITION_INFORMATION info;
1159 switch(method)
1161 case FILE_BEGIN:
1162 pos = distance.QuadPart;
1163 break;
1164 case FILE_CURRENT:
1165 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1166 goto error;
1167 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1168 break;
1169 case FILE_END:
1171 FILE_END_OF_FILE_INFORMATION eof;
1172 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1173 goto error;
1174 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1176 break;
1177 default:
1178 SetLastError( ERROR_INVALID_PARAMETER );
1179 return FALSE;
1182 if (pos < 0)
1184 SetLastError( ERROR_NEGATIVE_SEEK );
1185 return FALSE;
1188 info.CurrentByteOffset.QuadPart = pos;
1189 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1190 goto error;
1191 if (newpos) newpos->QuadPart = pos;
1192 return TRUE;
1194 error:
1195 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1196 return FALSE;
1199 /***********************************************************************
1200 * SetFileValidData (KERNEL32.@)
1202 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1204 FILE_VALID_DATA_LENGTH_INFORMATION info;
1205 IO_STATUS_BLOCK io;
1206 NTSTATUS status;
1208 info.ValidDataLength.QuadPart = ValidDataLength;
1209 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1211 if (status == STATUS_SUCCESS) return TRUE;
1212 SetLastError( RtlNtStatusToDosError(status) );
1213 return FALSE;
1216 /***********************************************************************
1217 * GetFileTime (KERNEL32.@)
1219 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1220 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1222 FILE_BASIC_INFORMATION info;
1223 IO_STATUS_BLOCK io;
1224 NTSTATUS status;
1226 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1227 if (status == STATUS_SUCCESS)
1229 if (lpCreationTime)
1231 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1232 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1234 if (lpLastAccessTime)
1236 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1237 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1239 if (lpLastWriteTime)
1241 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1242 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1244 return TRUE;
1246 SetLastError( RtlNtStatusToDosError(status) );
1247 return FALSE;
1251 /***********************************************************************
1252 * SetFileTime (KERNEL32.@)
1254 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1255 const FILETIME *atime, const FILETIME *mtime )
1257 FILE_BASIC_INFORMATION info;
1258 IO_STATUS_BLOCK io;
1259 NTSTATUS status;
1261 memset( &info, 0, sizeof(info) );
1262 if (ctime)
1264 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1265 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1267 if (atime)
1269 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1270 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1272 if (mtime)
1274 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1275 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1278 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1279 if (status == STATUS_SUCCESS) return TRUE;
1280 SetLastError( RtlNtStatusToDosError(status) );
1281 return FALSE;
1285 /**************************************************************************
1286 * LockFile (KERNEL32.@)
1288 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1289 DWORD count_low, DWORD count_high )
1291 NTSTATUS status;
1292 LARGE_INTEGER count, offset;
1294 TRACE( "%p %x%08x %x%08x\n",
1295 hFile, offset_high, offset_low, count_high, count_low );
1297 count.u.LowPart = count_low;
1298 count.u.HighPart = count_high;
1299 offset.u.LowPart = offset_low;
1300 offset.u.HighPart = offset_high;
1302 status = NtLockFile( hFile, 0, NULL, NULL,
1303 NULL, &offset, &count, NULL, TRUE, TRUE );
1305 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1306 return !status;
1310 /**************************************************************************
1311 * LockFileEx [KERNEL32.@]
1313 * Locks a byte range within an open file for shared or exclusive access.
1315 * RETURNS
1316 * success: TRUE
1317 * failure: FALSE
1319 * NOTES
1320 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1322 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1323 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1325 NTSTATUS status;
1326 LARGE_INTEGER count, offset;
1327 LPVOID cvalue = NULL;
1329 if (reserved)
1331 SetLastError( ERROR_INVALID_PARAMETER );
1332 return FALSE;
1335 TRACE( "%p %x%08x %x%08x flags %x\n",
1336 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1337 count_high, count_low, flags );
1339 count.u.LowPart = count_low;
1340 count.u.HighPart = count_high;
1341 offset.u.LowPart = overlapped->u.s.Offset;
1342 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1344 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1346 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1347 NULL, &offset, &count, NULL,
1348 flags & LOCKFILE_FAIL_IMMEDIATELY,
1349 flags & LOCKFILE_EXCLUSIVE_LOCK );
1351 if (status) SetLastError( RtlNtStatusToDosError(status) );
1352 return !status;
1356 /**************************************************************************
1357 * UnlockFile (KERNEL32.@)
1359 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1360 DWORD count_low, DWORD count_high )
1362 NTSTATUS status;
1363 LARGE_INTEGER count, offset;
1365 count.u.LowPart = count_low;
1366 count.u.HighPart = count_high;
1367 offset.u.LowPart = offset_low;
1368 offset.u.HighPart = offset_high;
1370 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1371 if (status) SetLastError( RtlNtStatusToDosError(status) );
1372 return !status;
1376 /**************************************************************************
1377 * UnlockFileEx (KERNEL32.@)
1379 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1380 LPOVERLAPPED overlapped )
1382 if (reserved)
1384 SetLastError( ERROR_INVALID_PARAMETER );
1385 return FALSE;
1387 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1389 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1393 /*************************************************************************
1394 * SetHandleCount (KERNEL32.@)
1396 UINT WINAPI SetHandleCount( UINT count )
1398 return count;
1402 /**************************************************************************
1403 * Operations on file names *
1404 **************************************************************************/
1407 /*************************************************************************
1408 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1410 * Creates or opens an object, and returns a handle that can be used to
1411 * access that object.
1413 * PARAMS
1415 * filename [in] pointer to filename to be accessed
1416 * access [in] access mode requested
1417 * sharing [in] share mode
1418 * sa [in] pointer to security attributes
1419 * creation [in] how to create the file
1420 * attributes [in] attributes for newly created file
1421 * template [in] handle to file with extended attributes to copy
1423 * RETURNS
1424 * Success: Open handle to specified file
1425 * Failure: INVALID_HANDLE_VALUE
1427 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1428 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1429 DWORD attributes, HANDLE template )
1431 NTSTATUS status;
1432 UINT options;
1433 OBJECT_ATTRIBUTES attr;
1434 UNICODE_STRING nameW;
1435 IO_STATUS_BLOCK io;
1436 HANDLE ret;
1437 DWORD dosdev;
1438 const WCHAR *vxd_name = NULL;
1439 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1440 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1441 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1442 SECURITY_QUALITY_OF_SERVICE qos;
1444 static const UINT nt_disposition[5] =
1446 FILE_CREATE, /* CREATE_NEW */
1447 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1448 FILE_OPEN, /* OPEN_EXISTING */
1449 FILE_OPEN_IF, /* OPEN_ALWAYS */
1450 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1454 /* sanity checks */
1456 if (!filename || !filename[0])
1458 SetLastError( ERROR_PATH_NOT_FOUND );
1459 return INVALID_HANDLE_VALUE;
1462 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1463 (access & GENERIC_READ)?"GENERIC_READ ":"",
1464 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1465 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1466 (!access)?"QUERY_ACCESS ":"",
1467 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1468 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1469 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1470 creation, attributes);
1472 /* Open a console for CONIN$ or CONOUT$ */
1474 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1476 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1477 creation ? OPEN_EXISTING : 0);
1478 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1479 goto done;
1482 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1484 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1485 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1487 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1488 !strncmpiW( filename + 4, pipeW, 5 ) ||
1489 !strncmpiW( filename + 4, mailslotW, 9 ))
1491 dosdev = 0;
1493 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1495 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1497 else if (GetVersion() & 0x80000000)
1499 vxd_name = filename + 4;
1500 if (!creation) creation = OPEN_EXISTING;
1503 else dosdev = RtlIsDosDeviceName_U( filename );
1505 if (dosdev)
1507 static const WCHAR conW[] = {'C','O','N'};
1509 if (LOWORD(dosdev) == sizeof(conW) &&
1510 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1512 switch (access & (GENERIC_READ|GENERIC_WRITE))
1514 case GENERIC_READ:
1515 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1516 goto done;
1517 case GENERIC_WRITE:
1518 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1519 goto done;
1520 default:
1521 SetLastError( ERROR_FILE_NOT_FOUND );
1522 return INVALID_HANDLE_VALUE;
1527 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1529 SetLastError( ERROR_INVALID_PARAMETER );
1530 return INVALID_HANDLE_VALUE;
1533 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1535 SetLastError( ERROR_PATH_NOT_FOUND );
1536 return INVALID_HANDLE_VALUE;
1539 /* now call NtCreateFile */
1541 options = 0;
1542 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1543 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1544 else
1545 options |= FILE_NON_DIRECTORY_FILE;
1546 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1548 options |= FILE_DELETE_ON_CLOSE;
1549 access |= DELETE;
1551 if (attributes & FILE_FLAG_NO_BUFFERING)
1552 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1553 if (!(attributes & FILE_FLAG_OVERLAPPED))
1554 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1555 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1556 options |= FILE_RANDOM_ACCESS;
1557 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1559 attr.Length = sizeof(attr);
1560 attr.RootDirectory = 0;
1561 attr.Attributes = OBJ_CASE_INSENSITIVE;
1562 attr.ObjectName = &nameW;
1563 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1564 if (attributes & SECURITY_SQOS_PRESENT)
1566 qos.Length = sizeof(qos);
1567 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1568 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1569 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1570 attr.SecurityQualityOfService = &qos;
1572 else
1573 attr.SecurityQualityOfService = NULL;
1575 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1577 status = NtCreateFile( &ret, access | SYNCHRONIZE, &attr, &io, NULL, attributes,
1578 sharing, nt_disposition[creation - CREATE_NEW],
1579 options, NULL, 0 );
1580 if (status)
1582 if (vxd_name && vxd_name[0])
1584 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1585 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1586 "__wine_vxd_open" );
1587 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1590 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1591 ret = INVALID_HANDLE_VALUE;
1593 /* In the case file creation was rejected due to CREATE_NEW flag
1594 * was specified and file with that name already exists, correct
1595 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1596 * Note: RtlNtStatusToDosError is not the subject to blame here.
1598 if (status == STATUS_OBJECT_NAME_COLLISION)
1599 SetLastError( ERROR_FILE_EXISTS );
1600 else
1601 SetLastError( RtlNtStatusToDosError(status) );
1603 else
1605 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1606 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1607 SetLastError( ERROR_ALREADY_EXISTS );
1608 else
1609 SetLastError( 0 );
1611 RtlFreeUnicodeString( &nameW );
1613 done:
1614 if (!ret) ret = INVALID_HANDLE_VALUE;
1615 TRACE("returning %p\n", ret);
1616 return ret;
1621 /*************************************************************************
1622 * CreateFileA (KERNEL32.@)
1624 * See CreateFileW.
1626 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1627 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1628 DWORD attributes, HANDLE template)
1630 WCHAR *nameW;
1632 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1633 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1636 /*************************************************************************
1637 * CreateFile2 (KERNEL32.@)
1639 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1640 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1642 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1643 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1644 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1646 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1648 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1651 /***********************************************************************
1652 * DeleteFileW (KERNEL32.@)
1654 * Delete a file.
1656 * PARAMS
1657 * path [I] Path to the file to delete.
1659 * RETURNS
1660 * Success: TRUE.
1661 * Failure: FALSE, check GetLastError().
1663 BOOL WINAPI DeleteFileW( LPCWSTR path )
1665 UNICODE_STRING nameW;
1666 OBJECT_ATTRIBUTES attr;
1667 NTSTATUS status;
1668 HANDLE hFile;
1669 IO_STATUS_BLOCK io;
1671 TRACE("%s\n", debugstr_w(path) );
1673 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1675 SetLastError( ERROR_PATH_NOT_FOUND );
1676 return FALSE;
1679 attr.Length = sizeof(attr);
1680 attr.RootDirectory = 0;
1681 attr.Attributes = OBJ_CASE_INSENSITIVE;
1682 attr.ObjectName = &nameW;
1683 attr.SecurityDescriptor = NULL;
1684 attr.SecurityQualityOfService = NULL;
1686 status = NtCreateFile(&hFile, SYNCHRONIZE | DELETE, &attr, &io, NULL, 0,
1687 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1688 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1689 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1691 RtlFreeUnicodeString( &nameW );
1692 if (status)
1694 SetLastError( RtlNtStatusToDosError(status) );
1695 return FALSE;
1697 return TRUE;
1701 /***********************************************************************
1702 * DeleteFileA (KERNEL32.@)
1704 * See DeleteFileW.
1706 BOOL WINAPI DeleteFileA( LPCSTR path )
1708 WCHAR *pathW;
1710 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1711 return DeleteFileW( pathW );
1715 /**************************************************************************
1716 * ReplaceFileW (KERNEL32.@)
1717 * ReplaceFile (KERNEL32.@)
1719 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1720 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1721 LPVOID lpExclude, LPVOID lpReserved)
1723 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1724 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1725 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1726 DWORD error = ERROR_SUCCESS;
1727 UINT replaced_flags;
1728 BOOL ret = FALSE;
1729 NTSTATUS status;
1730 IO_STATUS_BLOCK io;
1731 OBJECT_ATTRIBUTES attr;
1733 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1734 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1735 dwReplaceFlags, lpExclude, lpReserved);
1737 if (dwReplaceFlags)
1738 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1740 /* First two arguments are mandatory */
1741 if (!lpReplacedFileName || !lpReplacementFileName)
1743 SetLastError(ERROR_INVALID_PARAMETER);
1744 return FALSE;
1747 unix_replaced_name.Buffer = NULL;
1748 unix_replacement_name.Buffer = NULL;
1749 unix_backup_name.Buffer = NULL;
1751 attr.Length = sizeof(attr);
1752 attr.RootDirectory = 0;
1753 attr.Attributes = OBJ_CASE_INSENSITIVE;
1754 attr.ObjectName = NULL;
1755 attr.SecurityDescriptor = NULL;
1756 attr.SecurityQualityOfService = NULL;
1758 /* Open the "replaced" file for reading and writing */
1759 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1761 error = ERROR_PATH_NOT_FOUND;
1762 goto fail;
1764 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1765 attr.ObjectName = &nt_replaced_name;
1766 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1767 &attr, &io,
1768 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1769 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1770 if (status == STATUS_SUCCESS)
1771 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1772 RtlFreeUnicodeString(&nt_replaced_name);
1773 if (status != STATUS_SUCCESS)
1775 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1776 error = ERROR_FILE_NOT_FOUND;
1777 else
1778 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1779 goto fail;
1783 * Open the replacement file for reading, writing, and deleting
1784 * (writing and deleting are needed when finished)
1786 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1788 error = ERROR_PATH_NOT_FOUND;
1789 goto fail;
1791 attr.ObjectName = &nt_replacement_name;
1792 status = NtOpenFile(&hReplacement,
1793 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1794 &attr, &io, 0,
1795 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1796 if (status == STATUS_SUCCESS)
1797 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1798 RtlFreeUnicodeString(&nt_replacement_name);
1799 if (status != STATUS_SUCCESS)
1801 error = RtlNtStatusToDosError(status);
1802 goto fail;
1805 /* If the user wants a backup then that needs to be performed first */
1806 if (lpBackupFileName)
1808 UNICODE_STRING nt_backup_name;
1809 FILE_BASIC_INFORMATION replaced_info;
1811 /* Obtain the file attributes from the "replaced" file */
1812 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1813 sizeof(replaced_info),
1814 FileBasicInformation);
1815 if (status != STATUS_SUCCESS)
1817 error = RtlNtStatusToDosError(status);
1818 goto fail;
1821 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1823 error = ERROR_PATH_NOT_FOUND;
1824 goto fail;
1826 attr.ObjectName = &nt_backup_name;
1827 /* Open the backup with permissions to write over it */
1828 status = NtCreateFile(&hBackup, GENERIC_WRITE | SYNCHRONIZE,
1829 &attr, &io, NULL, replaced_info.FileAttributes,
1830 FILE_SHARE_WRITE, FILE_OPEN_IF,
1831 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1832 NULL, 0);
1833 if (status == STATUS_SUCCESS)
1834 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1835 RtlFreeUnicodeString(&nt_backup_name);
1836 if (status != STATUS_SUCCESS)
1838 error = RtlNtStatusToDosError(status);
1839 goto fail;
1842 /* If an existing backup exists then copy over it */
1843 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1845 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1846 goto fail;
1851 * Now that the backup has been performed (if requested), copy the replacement
1852 * into place
1854 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1856 if (errno == EACCES)
1858 /* Inappropriate permissions on "replaced", rename will fail */
1859 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1860 goto fail;
1862 /* on failure we need to indicate whether a backup was made */
1863 if (!lpBackupFileName)
1864 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1865 else
1866 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1867 goto fail;
1869 /* Success! */
1870 ret = TRUE;
1872 /* Perform resource cleanup */
1873 fail:
1874 if (hBackup) CloseHandle(hBackup);
1875 if (hReplaced) CloseHandle(hReplaced);
1876 if (hReplacement) CloseHandle(hReplacement);
1877 RtlFreeAnsiString(&unix_backup_name);
1878 RtlFreeAnsiString(&unix_replacement_name);
1879 RtlFreeAnsiString(&unix_replaced_name);
1881 /* If there was an error, set the error code */
1882 if(!ret)
1883 SetLastError(error);
1884 return ret;
1888 /**************************************************************************
1889 * ReplaceFileA (KERNEL32.@)
1891 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1892 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1893 LPVOID lpExclude, LPVOID lpReserved)
1895 WCHAR *replacedW, *replacementW, *backupW = NULL;
1896 BOOL ret;
1898 /* This function only makes sense when the first two parameters are defined */
1899 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1901 SetLastError(ERROR_INVALID_PARAMETER);
1902 return FALSE;
1904 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1906 HeapFree( GetProcessHeap(), 0, replacedW );
1907 SetLastError(ERROR_INVALID_PARAMETER);
1908 return FALSE;
1910 /* The backup parameter, however, is optional */
1911 if (lpBackupFileName)
1913 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1915 HeapFree( GetProcessHeap(), 0, replacedW );
1916 HeapFree( GetProcessHeap(), 0, replacementW );
1917 SetLastError(ERROR_INVALID_PARAMETER);
1918 return FALSE;
1921 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1922 HeapFree( GetProcessHeap(), 0, replacedW );
1923 HeapFree( GetProcessHeap(), 0, replacementW );
1924 HeapFree( GetProcessHeap(), 0, backupW );
1925 return ret;
1929 /*************************************************************************
1930 * FindFirstFileExW (KERNEL32.@)
1932 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1933 * results as FindExSearchNameMatch
1935 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1936 LPVOID data, FINDEX_SEARCH_OPS search_op,
1937 LPVOID filter, DWORD flags)
1939 WCHAR *mask, *p;
1940 FIND_FIRST_INFO *info = NULL;
1941 UNICODE_STRING nt_name;
1942 OBJECT_ATTRIBUTES attr;
1943 IO_STATUS_BLOCK io;
1944 NTSTATUS status;
1945 DWORD device = 0;
1947 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1949 if (flags != 0)
1951 FIXME("flags not implemented 0x%08x\n", flags );
1953 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1955 FIXME("search_op not implemented 0x%08x\n", search_op);
1956 SetLastError( ERROR_INVALID_PARAMETER );
1957 return INVALID_HANDLE_VALUE;
1959 if (level != FindExInfoStandard && level != FindExInfoBasic)
1961 FIXME("info level %d not implemented\n", level );
1962 SetLastError( ERROR_INVALID_PARAMETER );
1963 return INVALID_HANDLE_VALUE;
1966 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1968 SetLastError( ERROR_PATH_NOT_FOUND );
1969 return INVALID_HANDLE_VALUE;
1972 if (!(info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info))))
1974 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1975 goto error;
1978 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1980 static const WCHAR dotW[] = {'.',0};
1981 WCHAR *dir = NULL;
1983 /* we still need to check that the directory can be opened */
1985 if (HIWORD(device))
1987 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1989 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1990 goto error;
1992 memcpy( dir, filename, HIWORD(device) );
1993 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1995 RtlFreeUnicodeString( &nt_name );
1996 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1998 HeapFree( GetProcessHeap(), 0, dir );
1999 SetLastError( ERROR_PATH_NOT_FOUND );
2000 goto error;
2002 HeapFree( GetProcessHeap(), 0, dir );
2003 RtlInitUnicodeString( &info->mask, NULL );
2005 else if (!mask || !*mask)
2007 SetLastError( ERROR_FILE_NOT_FOUND );
2008 goto error;
2010 else
2012 if (!RtlCreateUnicodeString( &info->mask, mask ))
2014 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2015 goto error;
2018 /* truncate dir name before mask */
2019 *mask = 0;
2020 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
2023 /* check if path is the root of the drive */
2024 info->is_root = FALSE;
2025 p = nt_name.Buffer + 4; /* skip \??\ prefix */
2026 if (p[0] && p[1] == ':')
2028 p += 2;
2029 while (*p == '\\') p++;
2030 info->is_root = (*p == 0);
2033 attr.Length = sizeof(attr);
2034 attr.RootDirectory = 0;
2035 attr.Attributes = OBJ_CASE_INSENSITIVE;
2036 attr.ObjectName = &nt_name;
2037 attr.SecurityDescriptor = NULL;
2038 attr.SecurityQualityOfService = NULL;
2040 status = NtOpenFile( &info->handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2041 FILE_SHARE_READ | FILE_SHARE_WRITE,
2042 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2044 if (status != STATUS_SUCCESS)
2046 RtlFreeUnicodeString( &info->mask );
2047 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
2048 SetLastError( ERROR_PATH_NOT_FOUND );
2049 else
2050 SetLastError( RtlNtStatusToDosError(status) );
2051 goto error;
2054 RtlInitializeCriticalSection( &info->cs );
2055 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
2056 info->path = nt_name;
2057 info->magic = FIND_FIRST_MAGIC;
2058 info->data_pos = 0;
2059 info->data_len = 0;
2060 info->data_size = 0;
2061 info->data = NULL;
2062 info->search_op = search_op;
2063 info->level = level;
2065 if (device)
2067 WIN32_FIND_DATAW *wfd = data;
2069 memset( wfd, 0, sizeof(*wfd) );
2070 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
2071 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
2072 CloseHandle( info->handle );
2073 info->handle = 0;
2075 else
2077 IO_STATUS_BLOCK io;
2078 BOOL has_wildcard = strpbrkW( info->mask.Buffer, wildcardsW ) != NULL;
2080 info->data_size = has_wildcard ? 8192 : max_entry_size * 2;
2082 while (info->data_size)
2084 if (!(info->data = HeapAlloc( GetProcessHeap(), 0, info->data_size )))
2086 FindClose( info );
2087 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2088 return INVALID_HANDLE_VALUE;
2091 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2092 FileBothDirectoryInformation, FALSE, &info->mask, TRUE );
2093 if (io.u.Status)
2095 FindClose( info );
2096 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2097 return INVALID_HANDLE_VALUE;
2100 if (io.Information < info->data_size - max_entry_size)
2102 info->data_size = 0; /* we read everything */
2104 else if (info->data_size < 1024 * 1024)
2106 HeapFree( GetProcessHeap(), 0, info->data );
2107 info->data_size *= 2;
2109 else break;
2112 info->data_len = io.Information;
2113 if (!info->data_size && has_wildcard) /* release unused buffer space */
2114 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY, info->data, info->data_len );
2116 if (!FindNextFileW( info, data ))
2118 TRACE( "%s not found\n", debugstr_w(filename) );
2119 FindClose( info );
2120 SetLastError( ERROR_FILE_NOT_FOUND );
2121 return INVALID_HANDLE_VALUE;
2123 if (!has_wildcard) /* we can't find two files with the same name */
2125 CloseHandle( info->handle );
2126 HeapFree( GetProcessHeap(), 0, info->data );
2127 info->handle = 0;
2128 info->data = NULL;
2131 return info;
2133 error:
2134 HeapFree( GetProcessHeap(), 0, info );
2135 RtlFreeUnicodeString( &nt_name );
2136 return INVALID_HANDLE_VALUE;
2140 /*************************************************************************
2141 * FindNextFileW (KERNEL32.@)
2143 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2145 FIND_FIRST_INFO *info;
2146 FILE_BOTH_DIR_INFORMATION *dir_info;
2147 BOOL ret = FALSE;
2149 TRACE("%p %p\n", handle, data);
2151 if (!handle || handle == INVALID_HANDLE_VALUE)
2153 SetLastError( ERROR_INVALID_HANDLE );
2154 return ret;
2156 info = handle;
2157 if (info->magic != FIND_FIRST_MAGIC)
2159 SetLastError( ERROR_INVALID_HANDLE );
2160 return ret;
2163 RtlEnterCriticalSection( &info->cs );
2165 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2166 else for (;;)
2168 if (info->data_pos >= info->data_len) /* need to read some more data */
2170 IO_STATUS_BLOCK io;
2172 if (info->data_size)
2173 NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2174 FileBothDirectoryInformation, FALSE, &info->mask, FALSE );
2175 else
2176 io.u.Status = STATUS_NO_MORE_FILES;
2178 if (io.u.Status)
2180 SetLastError( RtlNtStatusToDosError( io.u.Status ) );
2181 if (io.u.Status == STATUS_NO_MORE_FILES)
2183 CloseHandle( info->handle );
2184 HeapFree( GetProcessHeap(), 0, info->data );
2185 info->handle = 0;
2186 info->data = NULL;
2188 break;
2190 info->data_len = io.Information;
2191 info->data_pos = 0;
2194 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2196 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2197 else info->data_pos = info->data_len;
2199 /* don't return '.' and '..' in the root of the drive */
2200 if (info->is_root)
2202 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2203 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2204 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2207 /* check for dir symlink */
2208 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2209 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2210 strpbrkW( info->mask.Buffer, wildcardsW ))
2212 if (!check_dir_symlink( info, dir_info )) continue;
2215 data->dwFileAttributes = dir_info->FileAttributes;
2216 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2217 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2218 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2219 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2220 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2221 data->dwReserved0 = 0;
2222 data->dwReserved1 = 0;
2224 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2225 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2227 if (info->level != FindExInfoBasic)
2229 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2230 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2232 else
2233 data->cAlternateFileName[0] = 0;
2235 TRACE("returning %s (%s)\n",
2236 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2238 ret = TRUE;
2239 break;
2242 RtlLeaveCriticalSection( &info->cs );
2243 return ret;
2247 /*************************************************************************
2248 * FindClose (KERNEL32.@)
2250 BOOL WINAPI FindClose( HANDLE handle )
2252 FIND_FIRST_INFO *info = handle;
2254 if (!handle || handle == INVALID_HANDLE_VALUE)
2256 SetLastError( ERROR_INVALID_HANDLE );
2257 return FALSE;
2260 __TRY
2262 if (info->magic == FIND_FIRST_MAGIC)
2264 RtlEnterCriticalSection( &info->cs );
2265 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2267 info->magic = 0;
2268 if (info->handle) CloseHandle( info->handle );
2269 info->handle = 0;
2270 RtlFreeUnicodeString( &info->mask );
2271 info->mask.Buffer = NULL;
2272 RtlFreeUnicodeString( &info->path );
2273 info->data_pos = 0;
2274 info->data_len = 0;
2275 HeapFree( GetProcessHeap(), 0, info->data );
2276 RtlLeaveCriticalSection( &info->cs );
2277 info->cs.DebugInfo->Spare[0] = 0;
2278 RtlDeleteCriticalSection( &info->cs );
2279 HeapFree( GetProcessHeap(), 0, info );
2283 __EXCEPT_PAGE_FAULT
2285 WARN("Illegal handle %p\n", handle);
2286 SetLastError( ERROR_INVALID_HANDLE );
2287 return FALSE;
2289 __ENDTRY
2291 return TRUE;
2295 /*************************************************************************
2296 * FindFirstFileA (KERNEL32.@)
2298 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2300 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2301 FindExSearchNameMatch, NULL, 0);
2304 /*************************************************************************
2305 * FindFirstFileExA (KERNEL32.@)
2307 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2308 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2309 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2311 HANDLE handle;
2312 WIN32_FIND_DATAA *dataA;
2313 WIN32_FIND_DATAW dataW;
2314 WCHAR *nameW;
2316 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2318 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2319 if (handle == INVALID_HANDLE_VALUE) return handle;
2321 dataA = lpFindFileData;
2322 dataA->dwFileAttributes = dataW.dwFileAttributes;
2323 dataA->ftCreationTime = dataW.ftCreationTime;
2324 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2325 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2326 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2327 dataA->nFileSizeLow = dataW.nFileSizeLow;
2328 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2329 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2330 sizeof(dataA->cAlternateFileName) );
2331 return handle;
2335 /*************************************************************************
2336 * FindFirstFileW (KERNEL32.@)
2338 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2340 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2341 FindExSearchNameMatch, NULL, 0);
2345 /*************************************************************************
2346 * FindNextFileA (KERNEL32.@)
2348 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2350 WIN32_FIND_DATAW dataW;
2352 if (!FindNextFileW( handle, &dataW )) return FALSE;
2353 data->dwFileAttributes = dataW.dwFileAttributes;
2354 data->ftCreationTime = dataW.ftCreationTime;
2355 data->ftLastAccessTime = dataW.ftLastAccessTime;
2356 data->ftLastWriteTime = dataW.ftLastWriteTime;
2357 data->nFileSizeHigh = dataW.nFileSizeHigh;
2358 data->nFileSizeLow = dataW.nFileSizeLow;
2359 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2360 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2361 sizeof(data->cAlternateFileName) );
2362 return TRUE;
2366 /**************************************************************************
2367 * GetFileAttributesW (KERNEL32.@)
2369 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2371 FILE_BASIC_INFORMATION info;
2372 UNICODE_STRING nt_name;
2373 OBJECT_ATTRIBUTES attr;
2374 NTSTATUS status;
2376 TRACE("%s\n", debugstr_w(name));
2378 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2380 SetLastError( ERROR_PATH_NOT_FOUND );
2381 return INVALID_FILE_ATTRIBUTES;
2384 attr.Length = sizeof(attr);
2385 attr.RootDirectory = 0;
2386 attr.Attributes = OBJ_CASE_INSENSITIVE;
2387 attr.ObjectName = &nt_name;
2388 attr.SecurityDescriptor = NULL;
2389 attr.SecurityQualityOfService = NULL;
2391 status = NtQueryAttributesFile( &attr, &info );
2392 RtlFreeUnicodeString( &nt_name );
2394 if (status == STATUS_SUCCESS) return info.FileAttributes;
2396 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2397 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2399 SetLastError( RtlNtStatusToDosError(status) );
2400 return INVALID_FILE_ATTRIBUTES;
2404 /**************************************************************************
2405 * GetFileAttributesA (KERNEL32.@)
2407 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2409 WCHAR *nameW;
2411 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2412 return GetFileAttributesW( nameW );
2416 /**************************************************************************
2417 * SetFileAttributesW (KERNEL32.@)
2419 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2421 UNICODE_STRING nt_name;
2422 OBJECT_ATTRIBUTES attr;
2423 IO_STATUS_BLOCK io;
2424 NTSTATUS status;
2425 HANDLE handle;
2427 TRACE("%s %x\n", debugstr_w(name), attributes);
2429 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2431 SetLastError( ERROR_PATH_NOT_FOUND );
2432 return FALSE;
2435 attr.Length = sizeof(attr);
2436 attr.RootDirectory = 0;
2437 attr.Attributes = OBJ_CASE_INSENSITIVE;
2438 attr.ObjectName = &nt_name;
2439 attr.SecurityDescriptor = NULL;
2440 attr.SecurityQualityOfService = NULL;
2442 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2443 RtlFreeUnicodeString( &nt_name );
2445 if (status == STATUS_SUCCESS)
2447 FILE_BASIC_INFORMATION info;
2449 memset( &info, 0, sizeof(info) );
2450 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2451 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2452 NtClose( handle );
2455 if (status == STATUS_SUCCESS) return TRUE;
2456 SetLastError( RtlNtStatusToDosError(status) );
2457 return FALSE;
2461 /**************************************************************************
2462 * SetFileAttributesA (KERNEL32.@)
2464 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2466 WCHAR *nameW;
2468 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2469 return SetFileAttributesW( nameW, attributes );
2473 /**************************************************************************
2474 * GetFileAttributesExW (KERNEL32.@)
2476 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2478 FILE_NETWORK_OPEN_INFORMATION info;
2479 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2480 UNICODE_STRING nt_name;
2481 OBJECT_ATTRIBUTES attr;
2482 NTSTATUS status;
2484 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2486 if (level != GetFileExInfoStandard)
2488 SetLastError( ERROR_INVALID_PARAMETER );
2489 return FALSE;
2492 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2494 SetLastError( ERROR_PATH_NOT_FOUND );
2495 return FALSE;
2498 attr.Length = sizeof(attr);
2499 attr.RootDirectory = 0;
2500 attr.Attributes = OBJ_CASE_INSENSITIVE;
2501 attr.ObjectName = &nt_name;
2502 attr.SecurityDescriptor = NULL;
2503 attr.SecurityQualityOfService = NULL;
2505 status = NtQueryFullAttributesFile( &attr, &info );
2506 RtlFreeUnicodeString( &nt_name );
2508 if (status != STATUS_SUCCESS)
2510 SetLastError( RtlNtStatusToDosError(status) );
2511 return FALSE;
2514 data->dwFileAttributes = info.FileAttributes;
2515 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2516 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2517 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2518 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2519 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2520 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2521 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2522 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2523 return TRUE;
2527 /**************************************************************************
2528 * GetFileAttributesExA (KERNEL32.@)
2530 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2532 WCHAR *nameW;
2534 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2535 return GetFileAttributesExW( nameW, level, ptr );
2539 /******************************************************************************
2540 * GetCompressedFileSizeW (KERNEL32.@)
2542 * Get the actual number of bytes used on disk.
2544 * RETURNS
2545 * Success: Low-order doubleword of number of bytes
2546 * Failure: INVALID_FILE_SIZE
2548 DWORD WINAPI GetCompressedFileSizeW(
2549 LPCWSTR name, /* [in] Pointer to name of file */
2550 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2552 UNICODE_STRING nt_name;
2553 OBJECT_ATTRIBUTES attr;
2554 IO_STATUS_BLOCK io;
2555 NTSTATUS status;
2556 HANDLE handle;
2557 DWORD ret = INVALID_FILE_SIZE;
2559 TRACE("%s %p\n", debugstr_w(name), size_high);
2561 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2563 SetLastError( ERROR_PATH_NOT_FOUND );
2564 return INVALID_FILE_SIZE;
2567 attr.Length = sizeof(attr);
2568 attr.RootDirectory = 0;
2569 attr.Attributes = OBJ_CASE_INSENSITIVE;
2570 attr.ObjectName = &nt_name;
2571 attr.SecurityDescriptor = NULL;
2572 attr.SecurityQualityOfService = NULL;
2574 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2575 RtlFreeUnicodeString( &nt_name );
2577 if (status == STATUS_SUCCESS)
2579 /* we don't support compressed files, simply return the file size */
2580 ret = GetFileSize( handle, size_high );
2581 NtClose( handle );
2583 else SetLastError( RtlNtStatusToDosError(status) );
2585 return ret;
2589 /******************************************************************************
2590 * GetCompressedFileSizeA (KERNEL32.@)
2592 * See GetCompressedFileSizeW.
2594 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2596 WCHAR *nameW;
2598 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2599 return GetCompressedFileSizeW( nameW, size_high );
2603 /***********************************************************************
2604 * OpenVxDHandle (KERNEL32.@)
2606 * This function is supposed to return the corresponding Ring 0
2607 * ("kernel") handle for a Ring 3 handle in Win9x.
2608 * Evidently, Wine will have problems with this. But we try anyway,
2609 * maybe it helps...
2611 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2613 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2614 return hHandleRing3;
2618 /****************************************************************************
2619 * DeviceIoControl (KERNEL32.@)
2621 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2622 LPVOID lpvInBuffer, DWORD cbInBuffer,
2623 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2624 LPDWORD lpcbBytesReturned,
2625 LPOVERLAPPED lpOverlapped)
2627 NTSTATUS status;
2629 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2630 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2631 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2633 /* Check if this is a user defined control code for a VxD */
2635 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2637 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2638 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2639 DeviceIoProc proc = NULL;
2641 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2642 "__wine_vxd_get_proc" );
2643 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2644 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2645 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2648 /* Not a VxD, let ntdll handle it */
2650 if (lpOverlapped)
2652 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2653 lpOverlapped->Internal = STATUS_PENDING;
2654 lpOverlapped->InternalHigh = 0;
2655 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2656 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2657 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2658 dwIoControlCode, lpvInBuffer, cbInBuffer,
2659 lpvOutBuffer, cbOutBuffer);
2660 else
2661 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2662 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2663 dwIoControlCode, lpvInBuffer, cbInBuffer,
2664 lpvOutBuffer, cbOutBuffer);
2665 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2667 else
2669 IO_STATUS_BLOCK iosb;
2671 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2672 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2673 dwIoControlCode, lpvInBuffer, cbInBuffer,
2674 lpvOutBuffer, cbOutBuffer);
2675 else
2676 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2677 dwIoControlCode, lpvInBuffer, cbInBuffer,
2678 lpvOutBuffer, cbOutBuffer);
2679 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2681 if (status) SetLastError( RtlNtStatusToDosError(status) );
2682 return !status;
2686 /***********************************************************************
2687 * OpenFile (KERNEL32.@)
2689 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2691 HANDLE handle;
2692 FILETIME filetime;
2693 WORD filedatetime[2];
2695 if (!ofs) return HFILE_ERROR;
2697 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2698 ((mode & 0x3 )==OF_READ)?"OF_READ":
2699 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2700 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2701 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2702 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2703 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2704 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2705 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2706 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2707 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2708 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2709 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2710 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2711 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2712 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2713 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2714 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2718 ofs->cBytes = sizeof(OFSTRUCT);
2719 ofs->nErrCode = 0;
2720 if (mode & OF_REOPEN) name = ofs->szPathName;
2722 if (!name) return HFILE_ERROR;
2724 TRACE("%s %04x\n", name, mode );
2726 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2727 Are there any cases where getting the path here is wrong?
2728 Uwe Bonnes 1997 Apr 2 */
2729 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2731 /* OF_PARSE simply fills the structure */
2733 if (mode & OF_PARSE)
2735 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2736 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2737 return 0;
2740 /* OF_CREATE is completely different from all other options, so
2741 handle it first */
2743 if (mode & OF_CREATE)
2745 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2746 goto error;
2748 else
2750 /* Now look for the file */
2752 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2753 goto error;
2755 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2757 if (mode & OF_DELETE)
2759 if (!DeleteFileA( ofs->szPathName )) goto error;
2760 TRACE("(%s): OF_DELETE return = OK\n", name);
2761 return TRUE;
2764 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2765 if (handle == INVALID_HANDLE_VALUE) goto error;
2767 GetFileTime( handle, NULL, NULL, &filetime );
2768 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2769 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2771 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2773 CloseHandle( handle );
2774 WARN("(%s): OF_VERIFY failed\n", name );
2775 /* FIXME: what error here? */
2776 SetLastError( ERROR_FILE_NOT_FOUND );
2777 goto error;
2780 ofs->Reserved1 = filedatetime[0];
2781 ofs->Reserved2 = filedatetime[1];
2783 TRACE("(%s): OK, return = %p\n", name, handle );
2784 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2786 CloseHandle( handle );
2787 return TRUE;
2789 return HandleToLong(handle);
2791 error: /* We get here if there was an error opening the file */
2792 ofs->nErrCode = GetLastError();
2793 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2794 return HFILE_ERROR;
2798 /***********************************************************************
2799 * OpenFileById (KERNEL32.@)
2801 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2802 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2804 UINT options;
2805 HANDLE result;
2806 OBJECT_ATTRIBUTES attr;
2807 NTSTATUS status;
2808 IO_STATUS_BLOCK io;
2809 UNICODE_STRING objectName;
2811 if (!id)
2813 SetLastError( ERROR_INVALID_PARAMETER );
2814 return INVALID_HANDLE_VALUE;
2817 options = FILE_OPEN_BY_FILE_ID;
2818 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2819 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2820 else
2821 options |= FILE_NON_DIRECTORY_FILE;
2822 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2823 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2824 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2825 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2827 objectName.Length = sizeof(ULONGLONG);
2828 objectName.Buffer = (WCHAR *)&id->u.FileId;
2829 attr.Length = sizeof(attr);
2830 attr.RootDirectory = handle;
2831 attr.Attributes = 0;
2832 attr.ObjectName = &objectName;
2833 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2834 attr.SecurityQualityOfService = NULL;
2835 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2837 status = NtCreateFile( &result, access | SYNCHRONIZE, &attr, &io, NULL, flags,
2838 share, OPEN_EXISTING, options, NULL, 0 );
2839 if (status != STATUS_SUCCESS)
2841 SetLastError( RtlNtStatusToDosError( status ) );
2842 return INVALID_HANDLE_VALUE;
2844 return result;
2848 /***********************************************************************
2849 * K32EnumDeviceDrivers (KERNEL32.@)
2851 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2853 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2855 if (needed)
2856 *needed = 0;
2858 return TRUE;
2861 /***********************************************************************
2862 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2864 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2866 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2868 if (base_name && size)
2869 base_name[0] = '\0';
2871 return 0;
2874 /***********************************************************************
2875 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2877 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2879 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2881 if (base_name && size)
2882 base_name[0] = '\0';
2884 return 0;
2887 /***********************************************************************
2888 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2890 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2892 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2894 if (file_name && size)
2895 file_name[0] = '\0';
2897 return 0;
2900 /***********************************************************************
2901 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2903 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2905 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2907 if (file_name && size)
2908 file_name[0] = '\0';
2910 return 0;