quartz: Use nAvgBytesPerSec to calculate length.
[wine.git] / dlls / kernel32 / file.c
blob3e93b0dfd789b7b3102b1f2f629cdadc64df2a18
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 path; /* NT path used to open the directory */
62 BOOL is_root; /* is directory the root of the drive? */
63 BOOL wildcard; /* did the mask contain wildcard characters? */
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[1]; /* 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;
629 status = lpOverlapped->Internal;
630 if (status == STATUS_PENDING) status = STATUS_SUCCESS;
633 *lpTransferred = lpOverlapped->InternalHigh;
635 if (status) SetLastError( RtlNtStatusToDosError(status) );
636 return !status;
639 /***********************************************************************
640 * CancelIoEx (KERNEL32.@)
642 * Cancels pending I/O operations on a file given the overlapped used.
644 * PARAMS
645 * handle [I] File handle.
646 * lpOverlapped [I,OPT] pointer to overlapped (if null, cancel all)
648 * RETURNS
649 * Success: TRUE.
650 * Failure: FALSE, check GetLastError().
652 BOOL WINAPI CancelIoEx(HANDLE handle, LPOVERLAPPED lpOverlapped)
654 IO_STATUS_BLOCK io_status;
656 NtCancelIoFileEx(handle, (PIO_STATUS_BLOCK) lpOverlapped, &io_status);
657 if (io_status.u.Status)
659 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
660 return FALSE;
662 return TRUE;
665 /***********************************************************************
666 * CancelIo (KERNEL32.@)
668 * Cancels pending I/O operations initiated by the current thread on a file.
670 * PARAMS
671 * handle [I] File handle.
673 * RETURNS
674 * Success: TRUE.
675 * Failure: FALSE, check GetLastError().
677 BOOL WINAPI CancelIo(HANDLE handle)
679 IO_STATUS_BLOCK io_status;
681 NtCancelIoFile(handle, &io_status);
682 if (io_status.u.Status)
684 SetLastError( RtlNtStatusToDosError( io_status.u.Status ) );
685 return FALSE;
687 return TRUE;
690 /***********************************************************************
691 * CancelSynchronousIo (KERNEL32.@)
693 * Marks pending synchronous I/O operations issued by the specified thread as cancelled
695 * PARAMS
696 * handle [I] handle to the thread whose I/O operations should be cancelled
698 * RETURNS
699 * Success: TRUE.
700 * Failure: FALSE, check GetLastError().
702 BOOL WINAPI CancelSynchronousIo(HANDLE thread)
704 FIXME("(%p): stub\n", thread);
705 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
706 return FALSE;
709 /***********************************************************************
710 * _hread (KERNEL32.@)
712 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
714 return _lread( hFile, buffer, count );
718 /***********************************************************************
719 * _hwrite (KERNEL32.@)
721 * experimentation yields that _lwrite:
722 * o truncates the file at the current position with
723 * a 0 len write
724 * o returns 0 on a 0 length write
725 * o works with console handles
728 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
730 DWORD result;
732 TRACE("%d %p %d\n", handle, buffer, count );
734 if (!count)
736 /* Expand or truncate at current position */
737 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
738 return 0;
740 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
741 return HFILE_ERROR;
742 return result;
746 /***********************************************************************
747 * _lclose (KERNEL32.@)
749 HFILE WINAPI _lclose( HFILE hFile )
751 TRACE("handle %d\n", hFile );
752 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
756 /***********************************************************************
757 * _lcreat (KERNEL32.@)
759 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
761 HANDLE hfile;
763 /* Mask off all flags not explicitly allowed by the doc */
764 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
765 TRACE("%s %02x\n", path, attr );
766 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
767 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
768 CREATE_ALWAYS, attr, 0 );
769 return HandleToLong(hfile);
773 /***********************************************************************
774 * _lopen (KERNEL32.@)
776 HFILE WINAPI _lopen( LPCSTR path, INT mode )
778 HANDLE hfile;
780 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
781 hfile = create_file_OF( path, mode & ~OF_CREATE );
782 return HandleToLong(hfile);
785 /***********************************************************************
786 * _lread (KERNEL32.@)
788 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
790 DWORD result;
791 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
792 return HFILE_ERROR;
793 return result;
797 /***********************************************************************
798 * _llseek (KERNEL32.@)
800 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
802 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
806 /***********************************************************************
807 * _lwrite (KERNEL32.@)
809 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
811 return (UINT)_hwrite( hFile, buffer, (LONG)count );
815 /***********************************************************************
816 * FlushFileBuffers (KERNEL32.@)
818 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
820 NTSTATUS nts;
821 IO_STATUS_BLOCK ioblk;
823 if (is_console_handle( hFile ))
825 /* this will fail (as expected) for an output handle */
826 return FlushConsoleInputBuffer( hFile );
828 nts = NtFlushBuffersFile( hFile, &ioblk );
829 if (nts != STATUS_SUCCESS)
831 SetLastError( RtlNtStatusToDosError( nts ) );
832 return FALSE;
835 return TRUE;
839 /***********************************************************************
840 * GetFileType (KERNEL32.@)
842 DWORD WINAPI GetFileType( HANDLE hFile )
844 FILE_FS_DEVICE_INFORMATION info;
845 IO_STATUS_BLOCK io;
846 NTSTATUS status;
848 if (hFile == (HANDLE)STD_INPUT_HANDLE || hFile == (HANDLE)STD_OUTPUT_HANDLE
849 || hFile == (HANDLE)STD_ERROR_HANDLE)
850 hFile = GetStdHandle((DWORD_PTR)hFile);
852 if (is_console_handle( hFile )) return FILE_TYPE_CHAR;
854 status = NtQueryVolumeInformationFile( hFile, &io, &info, sizeof(info), FileFsDeviceInformation );
855 if (status != STATUS_SUCCESS)
857 SetLastError( RtlNtStatusToDosError(status) );
858 return FILE_TYPE_UNKNOWN;
861 switch(info.DeviceType)
863 case FILE_DEVICE_NULL:
864 case FILE_DEVICE_SERIAL_PORT:
865 case FILE_DEVICE_PARALLEL_PORT:
866 case FILE_DEVICE_TAPE:
867 case FILE_DEVICE_UNKNOWN:
868 return FILE_TYPE_CHAR;
869 case FILE_DEVICE_NAMED_PIPE:
870 return FILE_TYPE_PIPE;
871 default:
872 return FILE_TYPE_DISK;
877 /***********************************************************************
878 * GetFileInformationByHandle (KERNEL32.@)
880 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
882 FILE_ALL_INFORMATION all_info;
883 IO_STATUS_BLOCK io;
884 NTSTATUS status;
886 status = NtQueryInformationFile( hFile, &io, &all_info, sizeof(all_info), FileAllInformation );
887 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
888 if (status == STATUS_SUCCESS)
890 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
891 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
892 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
893 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
894 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
895 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
896 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
897 info->dwVolumeSerialNumber = 0; /* FIXME */
898 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
899 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
900 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
901 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
902 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
903 return TRUE;
905 SetLastError( RtlNtStatusToDosError(status) );
906 return FALSE;
910 /***********************************************************************
911 * GetFileInformationByHandleEx (KERNEL32.@)
913 BOOL WINAPI GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
914 LPVOID info, DWORD size )
916 NTSTATUS status;
917 IO_STATUS_BLOCK io;
919 switch (class)
921 case FileStreamInfo:
922 case FileCompressionInfo:
923 case FileAttributeTagInfo:
924 case FileRemoteProtocolInfo:
925 case FileFullDirectoryInfo:
926 case FileFullDirectoryRestartInfo:
927 case FileStorageInfo:
928 case FileAlignmentInfo:
929 case FileIdExtdDirectoryInfo:
930 case FileIdExtdDirectoryRestartInfo:
931 FIXME( "%p, %u, %p, %u\n", handle, class, info, size );
932 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
933 return FALSE;
935 case FileBasicInfo:
936 status = NtQueryInformationFile( handle, &io, info, size, FileBasicInformation );
937 break;
939 case FileStandardInfo:
940 status = NtQueryInformationFile( handle, &io, info, size, FileStandardInformation );
941 break;
943 case FileNameInfo:
944 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
945 break;
947 case FileIdInfo:
948 status = NtQueryInformationFile( handle, &io, info, size, FileIdInformation );
949 break;
951 case FileIdBothDirectoryRestartInfo:
952 case FileIdBothDirectoryInfo:
953 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
954 FileIdBothDirectoryInformation, FALSE, NULL,
955 (class == FileIdBothDirectoryRestartInfo) );
956 break;
958 case FileRenameInfo:
959 case FileDispositionInfo:
960 case FileAllocationInfo:
961 case FileIoPriorityHintInfo:
962 case FileEndOfFileInfo:
963 default:
964 SetLastError( ERROR_INVALID_PARAMETER );
965 return FALSE;
968 if (status != STATUS_SUCCESS)
970 SetLastError( RtlNtStatusToDosError( status ) );
971 return FALSE;
973 return TRUE;
977 /***********************************************************************
978 * GetFileSize (KERNEL32.@)
980 * Retrieve the size of a file.
982 * PARAMS
983 * hFile [I] File to retrieve size of.
984 * filesizehigh [O] On return, the high bits of the file size.
986 * RETURNS
987 * Success: The low bits of the file size.
988 * Failure: INVALID_FILE_SIZE. As this is could also be a success value,
989 * check GetLastError() for values other than ERROR_SUCCESS.
991 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
993 LARGE_INTEGER size;
994 if (!GetFileSizeEx( hFile, &size )) return INVALID_FILE_SIZE;
995 if (filesizehigh) *filesizehigh = size.u.HighPart;
996 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError(0);
997 return size.u.LowPart;
1001 /***********************************************************************
1002 * GetFileSizeEx (KERNEL32.@)
1004 * Retrieve the size of a file.
1006 * PARAMS
1007 * hFile [I] File to retrieve size of.
1008 * lpFileSIze [O] On return, the size of the file.
1010 * RETURNS
1011 * Success: TRUE.
1012 * Failure: FALSE, check GetLastError().
1014 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
1016 FILE_STANDARD_INFORMATION info;
1017 IO_STATUS_BLOCK io;
1018 NTSTATUS status;
1020 if (is_console_handle( hFile ))
1022 SetLastError( ERROR_INVALID_HANDLE );
1023 return FALSE;
1026 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileStandardInformation );
1027 if (status == STATUS_SUCCESS)
1029 *lpFileSize = info.EndOfFile;
1030 return TRUE;
1032 SetLastError( RtlNtStatusToDosError(status) );
1033 return FALSE;
1037 /**************************************************************************
1038 * SetEndOfFile (KERNEL32.@)
1040 * Sets the current position as the end of the file.
1042 * PARAMS
1043 * hFile [I] File handle.
1045 * RETURNS
1046 * Success: TRUE.
1047 * Failure: FALSE, check GetLastError().
1049 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1051 FILE_POSITION_INFORMATION pos;
1052 FILE_END_OF_FILE_INFORMATION eof;
1053 IO_STATUS_BLOCK io;
1054 NTSTATUS status;
1056 status = NtQueryInformationFile( hFile, &io, &pos, sizeof(pos), FilePositionInformation );
1057 if (status == STATUS_SUCCESS)
1059 eof.EndOfFile = pos.CurrentByteOffset;
1060 status = NtSetInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation );
1062 if (status == STATUS_SUCCESS) return TRUE;
1063 SetLastError( RtlNtStatusToDosError(status) );
1064 return FALSE;
1067 /**************************************************************************
1068 * SetFileCompletionNotificationModes (KERNEL32.@)
1070 BOOL WINAPI SetFileCompletionNotificationModes( HANDLE handle, UCHAR flags )
1072 FIXME("%p %x - stub\n", handle, flags);
1073 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1074 return FALSE;
1078 /***********************************************************************
1079 * SetFileInformationByHandle (KERNEL32.@)
1081 BOOL WINAPI SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class, VOID *info, DWORD size )
1083 NTSTATUS status;
1084 IO_STATUS_BLOCK io;
1086 TRACE( "%p %u %p %u\n", file, class, info, size );
1088 switch (class)
1090 case FileBasicInfo:
1091 case FileNameInfo:
1092 case FileRenameInfo:
1093 case FileAllocationInfo:
1094 case FileEndOfFileInfo:
1095 case FileStreamInfo:
1096 case FileIdBothDirectoryInfo:
1097 case FileIdBothDirectoryRestartInfo:
1098 case FileIoPriorityHintInfo:
1099 case FileFullDirectoryInfo:
1100 case FileFullDirectoryRestartInfo:
1101 case FileStorageInfo:
1102 case FileAlignmentInfo:
1103 case FileIdInfo:
1104 case FileIdExtdDirectoryInfo:
1105 case FileIdExtdDirectoryRestartInfo:
1106 FIXME( "%p, %u, %p, %u\n", file, class, info, size );
1107 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1108 return FALSE;
1110 case FileDispositionInfo:
1111 status = NtSetInformationFile( file, &io, info, size, FileDispositionInformation );
1112 break;
1114 case FileStandardInfo:
1115 case FileCompressionInfo:
1116 case FileAttributeTagInfo:
1117 case FileRemoteProtocolInfo:
1118 default:
1119 SetLastError( ERROR_INVALID_PARAMETER );
1120 return FALSE;
1123 if (status != STATUS_SUCCESS)
1125 SetLastError( RtlNtStatusToDosError( status ) );
1126 return FALSE;
1128 return TRUE;
1132 /***********************************************************************
1133 * SetFilePointer (KERNEL32.@)
1135 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE hFile, LONG distance, LONG *highword, DWORD method )
1137 LARGE_INTEGER dist, newpos;
1139 if (highword)
1141 dist.u.LowPart = distance;
1142 dist.u.HighPart = *highword;
1144 else dist.QuadPart = distance;
1146 if (!SetFilePointerEx( hFile, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
1148 if (highword) *highword = newpos.u.HighPart;
1149 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1150 return newpos.u.LowPart;
1154 /***********************************************************************
1155 * SetFilePointerEx (KERNEL32.@)
1157 BOOL WINAPI SetFilePointerEx( HANDLE hFile, LARGE_INTEGER distance,
1158 LARGE_INTEGER *newpos, DWORD method )
1160 LONGLONG pos;
1161 IO_STATUS_BLOCK io;
1162 FILE_POSITION_INFORMATION info;
1164 switch(method)
1166 case FILE_BEGIN:
1167 pos = distance.QuadPart;
1168 break;
1169 case FILE_CURRENT:
1170 if (NtQueryInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1171 goto error;
1172 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
1173 break;
1174 case FILE_END:
1176 FILE_END_OF_FILE_INFORMATION eof;
1177 if (NtQueryInformationFile( hFile, &io, &eof, sizeof(eof), FileEndOfFileInformation ))
1178 goto error;
1179 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
1181 break;
1182 default:
1183 SetLastError( ERROR_INVALID_PARAMETER );
1184 return FALSE;
1187 if (pos < 0)
1189 SetLastError( ERROR_NEGATIVE_SEEK );
1190 return FALSE;
1193 info.CurrentByteOffset.QuadPart = pos;
1194 if (NtSetInformationFile( hFile, &io, &info, sizeof(info), FilePositionInformation ))
1195 goto error;
1196 if (newpos) newpos->QuadPart = pos;
1197 return TRUE;
1199 error:
1200 SetLastError( RtlNtStatusToDosError(io.u.Status) );
1201 return FALSE;
1204 /***********************************************************************
1205 * SetFileValidData (KERNEL32.@)
1207 BOOL WINAPI SetFileValidData( HANDLE hFile, LONGLONG ValidDataLength )
1209 FILE_VALID_DATA_LENGTH_INFORMATION info;
1210 IO_STATUS_BLOCK io;
1211 NTSTATUS status;
1213 info.ValidDataLength.QuadPart = ValidDataLength;
1214 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileValidDataLengthInformation );
1216 if (status == STATUS_SUCCESS) return TRUE;
1217 SetLastError( RtlNtStatusToDosError(status) );
1218 return FALSE;
1221 /***********************************************************************
1222 * GetFileTime (KERNEL32.@)
1224 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1225 FILETIME *lpLastAccessTime, FILETIME *lpLastWriteTime )
1227 FILE_BASIC_INFORMATION info;
1228 IO_STATUS_BLOCK io;
1229 NTSTATUS status;
1231 status = NtQueryInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1232 if (status == STATUS_SUCCESS)
1234 if (lpCreationTime)
1236 lpCreationTime->dwHighDateTime = info.CreationTime.u.HighPart;
1237 lpCreationTime->dwLowDateTime = info.CreationTime.u.LowPart;
1239 if (lpLastAccessTime)
1241 lpLastAccessTime->dwHighDateTime = info.LastAccessTime.u.HighPart;
1242 lpLastAccessTime->dwLowDateTime = info.LastAccessTime.u.LowPart;
1244 if (lpLastWriteTime)
1246 lpLastWriteTime->dwHighDateTime = info.LastWriteTime.u.HighPart;
1247 lpLastWriteTime->dwLowDateTime = info.LastWriteTime.u.LowPart;
1249 return TRUE;
1251 SetLastError( RtlNtStatusToDosError(status) );
1252 return FALSE;
1256 /***********************************************************************
1257 * SetFileTime (KERNEL32.@)
1259 BOOL WINAPI SetFileTime( HANDLE hFile, const FILETIME *ctime,
1260 const FILETIME *atime, const FILETIME *mtime )
1262 FILE_BASIC_INFORMATION info;
1263 IO_STATUS_BLOCK io;
1264 NTSTATUS status;
1266 memset( &info, 0, sizeof(info) );
1267 if (ctime)
1269 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
1270 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
1272 if (atime)
1274 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
1275 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
1277 if (mtime)
1279 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
1280 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
1283 status = NtSetInformationFile( hFile, &io, &info, sizeof(info), FileBasicInformation );
1284 if (status == STATUS_SUCCESS) return TRUE;
1285 SetLastError( RtlNtStatusToDosError(status) );
1286 return FALSE;
1290 /**************************************************************************
1291 * LockFile (KERNEL32.@)
1293 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1294 DWORD count_low, DWORD count_high )
1296 NTSTATUS status;
1297 LARGE_INTEGER count, offset;
1299 TRACE( "%p %x%08x %x%08x\n",
1300 hFile, offset_high, offset_low, count_high, count_low );
1302 count.u.LowPart = count_low;
1303 count.u.HighPart = count_high;
1304 offset.u.LowPart = offset_low;
1305 offset.u.HighPart = offset_high;
1307 status = NtLockFile( hFile, 0, NULL, NULL,
1308 NULL, &offset, &count, NULL, TRUE, TRUE );
1310 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1311 return !status;
1315 /**************************************************************************
1316 * LockFileEx [KERNEL32.@]
1318 * Locks a byte range within an open file for shared or exclusive access.
1320 * RETURNS
1321 * success: TRUE
1322 * failure: FALSE
1324 * NOTES
1325 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
1327 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
1328 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
1330 NTSTATUS status;
1331 LARGE_INTEGER count, offset;
1332 LPVOID cvalue = NULL;
1334 if (reserved)
1336 SetLastError( ERROR_INVALID_PARAMETER );
1337 return FALSE;
1340 TRACE( "%p %x%08x %x%08x flags %x\n",
1341 hFile, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset,
1342 count_high, count_low, flags );
1344 count.u.LowPart = count_low;
1345 count.u.HighPart = count_high;
1346 offset.u.LowPart = overlapped->u.s.Offset;
1347 offset.u.HighPart = overlapped->u.s.OffsetHigh;
1349 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1351 status = NtLockFile( hFile, overlapped->hEvent, NULL, cvalue,
1352 NULL, &offset, &count, NULL,
1353 flags & LOCKFILE_FAIL_IMMEDIATELY,
1354 flags & LOCKFILE_EXCLUSIVE_LOCK );
1356 if (status) SetLastError( RtlNtStatusToDosError(status) );
1357 return !status;
1361 /**************************************************************************
1362 * UnlockFile (KERNEL32.@)
1364 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
1365 DWORD count_low, DWORD count_high )
1367 NTSTATUS status;
1368 LARGE_INTEGER count, offset;
1370 count.u.LowPart = count_low;
1371 count.u.HighPart = count_high;
1372 offset.u.LowPart = offset_low;
1373 offset.u.HighPart = offset_high;
1375 status = NtUnlockFile( hFile, NULL, &offset, &count, NULL);
1376 if (status) SetLastError( RtlNtStatusToDosError(status) );
1377 return !status;
1381 /**************************************************************************
1382 * UnlockFileEx (KERNEL32.@)
1384 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
1385 LPOVERLAPPED overlapped )
1387 if (reserved)
1389 SetLastError( ERROR_INVALID_PARAMETER );
1390 return FALSE;
1392 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
1394 return UnlockFile( hFile, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
1398 /*************************************************************************
1399 * SetHandleCount (KERNEL32.@)
1401 UINT WINAPI SetHandleCount( UINT count )
1403 return count;
1407 /**************************************************************************
1408 * Operations on file names *
1409 **************************************************************************/
1412 /*************************************************************************
1413 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
1415 * Creates or opens an object, and returns a handle that can be used to
1416 * access that object.
1418 * PARAMS
1420 * filename [in] pointer to filename to be accessed
1421 * access [in] access mode requested
1422 * sharing [in] share mode
1423 * sa [in] pointer to security attributes
1424 * creation [in] how to create the file
1425 * attributes [in] attributes for newly created file
1426 * template [in] handle to file with extended attributes to copy
1428 * RETURNS
1429 * Success: Open handle to specified file
1430 * Failure: INVALID_HANDLE_VALUE
1432 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
1433 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1434 DWORD attributes, HANDLE template )
1436 NTSTATUS status;
1437 UINT options;
1438 OBJECT_ATTRIBUTES attr;
1439 UNICODE_STRING nameW;
1440 IO_STATUS_BLOCK io;
1441 HANDLE ret;
1442 DWORD dosdev;
1443 const WCHAR *vxd_name = NULL;
1444 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
1445 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
1446 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
1447 SECURITY_QUALITY_OF_SERVICE qos;
1449 static const UINT nt_disposition[5] =
1451 FILE_CREATE, /* CREATE_NEW */
1452 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
1453 FILE_OPEN, /* OPEN_EXISTING */
1454 FILE_OPEN_IF, /* OPEN_ALWAYS */
1455 FILE_OVERWRITE /* TRUNCATE_EXISTING */
1459 /* sanity checks */
1461 if (!filename || !filename[0])
1463 SetLastError( ERROR_PATH_NOT_FOUND );
1464 return INVALID_HANDLE_VALUE;
1467 TRACE("%s %s%s%s%s%s%s%s creation %d attributes 0x%x\n", debugstr_w(filename),
1468 (access & GENERIC_READ)?"GENERIC_READ ":"",
1469 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
1470 (access & GENERIC_EXECUTE)?"GENERIC_EXECUTE ":"",
1471 (!access)?"QUERY_ACCESS ":"",
1472 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
1473 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
1474 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
1475 creation, attributes);
1477 /* Open a console for CONIN$ or CONOUT$ */
1479 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
1481 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle),
1482 creation ? OPEN_EXISTING : 0);
1483 if (ret == INVALID_HANDLE_VALUE) SetLastError(ERROR_INVALID_PARAMETER);
1484 goto done;
1487 if (!strncmpW(filename, bkslashes_with_dotW, 4))
1489 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
1490 static const WCHAR mailslotW[] = {'M','A','I','L','S','L','O','T','\\',0};
1492 if ((isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0') ||
1493 !strncmpiW( filename + 4, pipeW, 5 ) ||
1494 !strncmpiW( filename + 4, mailslotW, 9 ))
1496 dosdev = 0;
1498 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
1500 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
1502 else if (GetVersion() & 0x80000000)
1504 vxd_name = filename + 4;
1505 if (!creation) creation = OPEN_EXISTING;
1508 else dosdev = RtlIsDosDeviceName_U( filename );
1510 if (dosdev)
1512 static const WCHAR conW[] = {'C','O','N'};
1514 if (LOWORD(dosdev) == sizeof(conW) &&
1515 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)/sizeof(WCHAR)))
1517 switch (access & (GENERIC_READ|GENERIC_WRITE))
1519 case GENERIC_READ:
1520 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1521 goto done;
1522 case GENERIC_WRITE:
1523 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), OPEN_EXISTING);
1524 goto done;
1525 default:
1526 SetLastError( ERROR_FILE_NOT_FOUND );
1527 return INVALID_HANDLE_VALUE;
1532 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
1534 SetLastError( ERROR_INVALID_PARAMETER );
1535 return INVALID_HANDLE_VALUE;
1538 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
1540 SetLastError( ERROR_PATH_NOT_FOUND );
1541 return INVALID_HANDLE_VALUE;
1544 /* now call NtCreateFile */
1546 options = 0;
1547 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
1548 options |= FILE_OPEN_FOR_BACKUP_INTENT;
1549 else
1550 options |= FILE_NON_DIRECTORY_FILE;
1551 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
1553 options |= FILE_DELETE_ON_CLOSE;
1554 access |= DELETE;
1556 if (attributes & FILE_FLAG_NO_BUFFERING)
1557 options |= FILE_NO_INTERMEDIATE_BUFFERING;
1558 if (!(attributes & FILE_FLAG_OVERLAPPED))
1559 options |= FILE_SYNCHRONOUS_IO_NONALERT;
1560 if (attributes & FILE_FLAG_RANDOM_ACCESS)
1561 options |= FILE_RANDOM_ACCESS;
1562 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
1564 attr.Length = sizeof(attr);
1565 attr.RootDirectory = 0;
1566 attr.Attributes = OBJ_CASE_INSENSITIVE;
1567 attr.ObjectName = &nameW;
1568 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1569 if (attributes & SECURITY_SQOS_PRESENT)
1571 qos.Length = sizeof(qos);
1572 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
1573 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
1574 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
1575 attr.SecurityQualityOfService = &qos;
1577 else
1578 attr.SecurityQualityOfService = NULL;
1580 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
1582 status = NtCreateFile( &ret, access | SYNCHRONIZE, &attr, &io, NULL, attributes,
1583 sharing, nt_disposition[creation - CREATE_NEW],
1584 options, NULL, 0 );
1585 if (status)
1587 if (vxd_name && vxd_name[0])
1589 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
1590 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
1591 "__wine_vxd_open" );
1592 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
1595 WARN("Unable to create file %s (status %x)\n", debugstr_w(filename), status);
1596 ret = INVALID_HANDLE_VALUE;
1598 /* In the case file creation was rejected due to CREATE_NEW flag
1599 * was specified and file with that name already exists, correct
1600 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
1601 * Note: RtlNtStatusToDosError is not the subject to blame here.
1603 if (status == STATUS_OBJECT_NAME_COLLISION)
1604 SetLastError( ERROR_FILE_EXISTS );
1605 else
1606 SetLastError( RtlNtStatusToDosError(status) );
1608 else
1610 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
1611 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
1612 SetLastError( ERROR_ALREADY_EXISTS );
1613 else
1614 SetLastError( 0 );
1616 RtlFreeUnicodeString( &nameW );
1618 done:
1619 if (!ret) ret = INVALID_HANDLE_VALUE;
1620 TRACE("returning %p\n", ret);
1621 return ret;
1626 /*************************************************************************
1627 * CreateFileA (KERNEL32.@)
1629 * See CreateFileW.
1631 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
1632 LPSECURITY_ATTRIBUTES sa, DWORD creation,
1633 DWORD attributes, HANDLE template)
1635 WCHAR *nameW;
1637 if ((GetVersion() & 0x80000000) && IsBadStringPtrA(filename, -1)) return INVALID_HANDLE_VALUE;
1638 if (!(nameW = FILE_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1639 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
1642 /*************************************************************************
1643 * CreateFile2 (KERNEL32.@)
1645 HANDLE WINAPI CreateFile2( LPCWSTR filename, DWORD access, DWORD sharing, DWORD creation,
1646 CREATEFILE2_EXTENDED_PARAMETERS *exparams )
1648 LPSECURITY_ATTRIBUTES sa = exparams ? exparams->lpSecurityAttributes : NULL;
1649 DWORD attributes = exparams ? exparams->dwFileAttributes : 0;
1650 HANDLE template = exparams ? exparams->hTemplateFile : NULL;
1652 FIXME("(%s %x %x %x %p), partial stub\n", debugstr_w(filename), access, sharing, creation, exparams);
1654 return CreateFileW( filename, access, sharing, sa, creation, attributes, template );
1657 /***********************************************************************
1658 * DeleteFileW (KERNEL32.@)
1660 * Delete a file.
1662 * PARAMS
1663 * path [I] Path to the file to delete.
1665 * RETURNS
1666 * Success: TRUE.
1667 * Failure: FALSE, check GetLastError().
1669 BOOL WINAPI DeleteFileW( LPCWSTR path )
1671 UNICODE_STRING nameW;
1672 OBJECT_ATTRIBUTES attr;
1673 NTSTATUS status;
1674 HANDLE hFile;
1675 IO_STATUS_BLOCK io;
1677 TRACE("%s\n", debugstr_w(path) );
1679 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
1681 SetLastError( ERROR_PATH_NOT_FOUND );
1682 return FALSE;
1685 attr.Length = sizeof(attr);
1686 attr.RootDirectory = 0;
1687 attr.Attributes = OBJ_CASE_INSENSITIVE;
1688 attr.ObjectName = &nameW;
1689 attr.SecurityDescriptor = NULL;
1690 attr.SecurityQualityOfService = NULL;
1692 status = NtCreateFile(&hFile, SYNCHRONIZE | DELETE, &attr, &io, NULL, 0,
1693 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1694 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
1695 if (status == STATUS_SUCCESS) status = NtClose(hFile);
1697 RtlFreeUnicodeString( &nameW );
1698 if (status)
1700 SetLastError( RtlNtStatusToDosError(status) );
1701 return FALSE;
1703 return TRUE;
1707 /***********************************************************************
1708 * DeleteFileA (KERNEL32.@)
1710 * See DeleteFileW.
1712 BOOL WINAPI DeleteFileA( LPCSTR path )
1714 WCHAR *pathW;
1716 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1717 return DeleteFileW( pathW );
1721 /**************************************************************************
1722 * ReplaceFileW (KERNEL32.@)
1723 * ReplaceFile (KERNEL32.@)
1725 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName, LPCWSTR lpReplacementFileName,
1726 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
1727 LPVOID lpExclude, LPVOID lpReserved)
1729 UNICODE_STRING nt_replaced_name, nt_replacement_name;
1730 ANSI_STRING unix_replaced_name, unix_replacement_name, unix_backup_name;
1731 HANDLE hReplaced = NULL, hReplacement = NULL, hBackup = NULL;
1732 DWORD error = ERROR_SUCCESS;
1733 UINT replaced_flags;
1734 BOOL ret = FALSE;
1735 NTSTATUS status;
1736 IO_STATUS_BLOCK io;
1737 OBJECT_ATTRIBUTES attr;
1739 TRACE("%s %s %s 0x%08x %p %p\n", debugstr_w(lpReplacedFileName),
1740 debugstr_w(lpReplacementFileName), debugstr_w(lpBackupFileName),
1741 dwReplaceFlags, lpExclude, lpReserved);
1743 if (dwReplaceFlags)
1744 FIXME("Ignoring flags %x\n", dwReplaceFlags);
1746 /* First two arguments are mandatory */
1747 if (!lpReplacedFileName || !lpReplacementFileName)
1749 SetLastError(ERROR_INVALID_PARAMETER);
1750 return FALSE;
1753 unix_replaced_name.Buffer = NULL;
1754 unix_replacement_name.Buffer = NULL;
1755 unix_backup_name.Buffer = NULL;
1757 attr.Length = sizeof(attr);
1758 attr.RootDirectory = 0;
1759 attr.Attributes = OBJ_CASE_INSENSITIVE;
1760 attr.ObjectName = NULL;
1761 attr.SecurityDescriptor = NULL;
1762 attr.SecurityQualityOfService = NULL;
1764 /* Open the "replaced" file for reading and writing */
1765 if (!(RtlDosPathNameToNtPathName_U(lpReplacedFileName, &nt_replaced_name, NULL, NULL)))
1767 error = ERROR_PATH_NOT_FOUND;
1768 goto fail;
1770 replaced_flags = lpBackupFileName ? FILE_OPEN : FILE_OPEN_IF;
1771 attr.ObjectName = &nt_replaced_name;
1772 status = NtOpenFile(&hReplaced, GENERIC_READ|GENERIC_WRITE|DELETE|SYNCHRONIZE,
1773 &attr, &io,
1774 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
1775 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1776 if (status == STATUS_SUCCESS)
1777 status = wine_nt_to_unix_file_name(&nt_replaced_name, &unix_replaced_name, replaced_flags, FALSE);
1778 RtlFreeUnicodeString(&nt_replaced_name);
1779 if (status != STATUS_SUCCESS)
1781 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1782 error = ERROR_FILE_NOT_FOUND;
1783 else
1784 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1785 goto fail;
1789 * Open the replacement file for reading, writing, and deleting
1790 * (writing and deleting are needed when finished)
1792 if (!(RtlDosPathNameToNtPathName_U(lpReplacementFileName, &nt_replacement_name, NULL, NULL)))
1794 error = ERROR_PATH_NOT_FOUND;
1795 goto fail;
1797 attr.ObjectName = &nt_replacement_name;
1798 status = NtOpenFile(&hReplacement,
1799 GENERIC_READ|GENERIC_WRITE|DELETE|WRITE_DAC|SYNCHRONIZE,
1800 &attr, &io, 0,
1801 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE);
1802 if (status == STATUS_SUCCESS)
1803 status = wine_nt_to_unix_file_name(&nt_replacement_name, &unix_replacement_name, FILE_OPEN, FALSE);
1804 RtlFreeUnicodeString(&nt_replacement_name);
1805 if (status != STATUS_SUCCESS)
1807 error = RtlNtStatusToDosError(status);
1808 goto fail;
1811 /* If the user wants a backup then that needs to be performed first */
1812 if (lpBackupFileName)
1814 UNICODE_STRING nt_backup_name;
1815 FILE_BASIC_INFORMATION replaced_info;
1817 /* Obtain the file attributes from the "replaced" file */
1818 status = NtQueryInformationFile(hReplaced, &io, &replaced_info,
1819 sizeof(replaced_info),
1820 FileBasicInformation);
1821 if (status != STATUS_SUCCESS)
1823 error = RtlNtStatusToDosError(status);
1824 goto fail;
1827 if (!(RtlDosPathNameToNtPathName_U(lpBackupFileName, &nt_backup_name, NULL, NULL)))
1829 error = ERROR_PATH_NOT_FOUND;
1830 goto fail;
1832 attr.ObjectName = &nt_backup_name;
1833 /* Open the backup with permissions to write over it */
1834 status = NtCreateFile(&hBackup, GENERIC_WRITE | SYNCHRONIZE,
1835 &attr, &io, NULL, replaced_info.FileAttributes,
1836 FILE_SHARE_WRITE, FILE_OPEN_IF,
1837 FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,
1838 NULL, 0);
1839 if (status == STATUS_SUCCESS)
1840 status = wine_nt_to_unix_file_name(&nt_backup_name, &unix_backup_name, FILE_OPEN_IF, FALSE);
1841 RtlFreeUnicodeString(&nt_backup_name);
1842 if (status != STATUS_SUCCESS)
1844 error = RtlNtStatusToDosError(status);
1845 goto fail;
1848 /* If an existing backup exists then copy over it */
1849 if (rename(unix_replaced_name.Buffer, unix_backup_name.Buffer) == -1)
1851 error = ERROR_UNABLE_TO_REMOVE_REPLACED; /* is this correct? */
1852 goto fail;
1857 * Now that the backup has been performed (if requested), copy the replacement
1858 * into place
1860 if (rename(unix_replacement_name.Buffer, unix_replaced_name.Buffer) == -1)
1862 if (errno == EACCES)
1864 /* Inappropriate permissions on "replaced", rename will fail */
1865 error = ERROR_UNABLE_TO_REMOVE_REPLACED;
1866 goto fail;
1868 /* on failure we need to indicate whether a backup was made */
1869 if (!lpBackupFileName)
1870 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT;
1871 else
1872 error = ERROR_UNABLE_TO_MOVE_REPLACEMENT_2;
1873 goto fail;
1875 /* Success! */
1876 ret = TRUE;
1878 /* Perform resource cleanup */
1879 fail:
1880 if (hBackup) CloseHandle(hBackup);
1881 if (hReplaced) CloseHandle(hReplaced);
1882 if (hReplacement) CloseHandle(hReplacement);
1883 RtlFreeAnsiString(&unix_backup_name);
1884 RtlFreeAnsiString(&unix_replacement_name);
1885 RtlFreeAnsiString(&unix_replaced_name);
1887 /* If there was an error, set the error code */
1888 if(!ret)
1889 SetLastError(error);
1890 return ret;
1894 /**************************************************************************
1895 * ReplaceFileA (KERNEL32.@)
1897 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
1898 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
1899 LPVOID lpExclude, LPVOID lpReserved)
1901 WCHAR *replacedW, *replacementW, *backupW = NULL;
1902 BOOL ret;
1904 /* This function only makes sense when the first two parameters are defined */
1905 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
1907 SetLastError(ERROR_INVALID_PARAMETER);
1908 return FALSE;
1910 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
1912 HeapFree( GetProcessHeap(), 0, replacedW );
1913 SetLastError(ERROR_INVALID_PARAMETER);
1914 return FALSE;
1916 /* The backup parameter, however, is optional */
1917 if (lpBackupFileName)
1919 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
1921 HeapFree( GetProcessHeap(), 0, replacedW );
1922 HeapFree( GetProcessHeap(), 0, replacementW );
1923 SetLastError(ERROR_INVALID_PARAMETER);
1924 return FALSE;
1927 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
1928 HeapFree( GetProcessHeap(), 0, replacedW );
1929 HeapFree( GetProcessHeap(), 0, replacementW );
1930 HeapFree( GetProcessHeap(), 0, backupW );
1931 return ret;
1935 /*************************************************************************
1936 * FindFirstFileExW (KERNEL32.@)
1938 * NOTE: The FindExSearchLimitToDirectories is ignored - it gives the same
1939 * results as FindExSearchNameMatch
1941 HANDLE WINAPI FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1942 LPVOID data, FINDEX_SEARCH_OPS search_op,
1943 LPVOID filter, DWORD flags)
1945 WCHAR *mask;
1946 BOOL has_wildcard = FALSE;
1947 FIND_FIRST_INFO *info = NULL;
1948 UNICODE_STRING nt_name;
1949 OBJECT_ATTRIBUTES attr;
1950 IO_STATUS_BLOCK io;
1951 NTSTATUS status;
1952 DWORD size, device = 0;
1954 TRACE("%s %d %p %d %p %x\n", debugstr_w(filename), level, data, search_op, filter, flags);
1956 if (flags != 0)
1958 FIXME("flags not implemented 0x%08x\n", flags );
1960 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1962 FIXME("search_op not implemented 0x%08x\n", search_op);
1963 SetLastError( ERROR_INVALID_PARAMETER );
1964 return INVALID_HANDLE_VALUE;
1966 if (level != FindExInfoStandard && level != FindExInfoBasic)
1968 FIXME("info level %d not implemented\n", level );
1969 SetLastError( ERROR_INVALID_PARAMETER );
1970 return INVALID_HANDLE_VALUE;
1973 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1975 SetLastError( ERROR_PATH_NOT_FOUND );
1976 return INVALID_HANDLE_VALUE;
1979 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1981 static const WCHAR dotW[] = {'.',0};
1982 WCHAR *dir = NULL;
1984 /* we still need to check that the directory can be opened */
1986 if (HIWORD(device))
1988 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1990 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1991 goto error;
1993 memcpy( dir, filename, HIWORD(device) );
1994 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1996 RtlFreeUnicodeString( &nt_name );
1997 if (!RtlDosPathNameToNtPathName_U( dir ? dir : dotW, &nt_name, &mask, NULL ))
1999 HeapFree( GetProcessHeap(), 0, dir );
2000 SetLastError( ERROR_PATH_NOT_FOUND );
2001 goto error;
2003 HeapFree( GetProcessHeap(), 0, dir );
2004 size = 0;
2006 else if (!mask || !*mask)
2008 SetLastError( ERROR_FILE_NOT_FOUND );
2009 goto error;
2011 else
2013 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
2014 has_wildcard = strpbrkW( mask, wildcardsW ) != NULL;
2015 size = has_wildcard ? 8192 : max_entry_size;
2018 if (!(info = HeapAlloc( GetProcessHeap(), 0, offsetof( FIND_FIRST_INFO, data[size] ))))
2020 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2021 goto error;
2024 /* check if path is the root of the drive, skipping the \??\ prefix */
2025 info->is_root = FALSE;
2026 if (nt_name.Length >= 6 * sizeof(WCHAR) && nt_name.Buffer[5] == ':')
2028 DWORD pos = 6;
2029 while (pos * sizeof(WCHAR) < nt_name.Length && nt_name.Buffer[pos] == '\\') pos++;
2030 info->is_root = (pos * sizeof(WCHAR) >= nt_name.Length);
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 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
2047 SetLastError( ERROR_PATH_NOT_FOUND );
2048 else
2049 SetLastError( RtlNtStatusToDosError(status) );
2050 goto error;
2053 RtlInitializeCriticalSection( &info->cs );
2054 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
2055 info->path = nt_name;
2056 info->magic = FIND_FIRST_MAGIC;
2057 info->wildcard = has_wildcard;
2058 info->data_pos = 0;
2059 info->data_len = 0;
2060 info->data_size = size;
2061 info->search_op = search_op;
2062 info->level = level;
2064 if (device)
2066 WIN32_FIND_DATAW *wfd = data;
2068 memset( wfd, 0, sizeof(*wfd) );
2069 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
2070 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
2071 CloseHandle( info->handle );
2072 info->handle = 0;
2074 else
2076 UNICODE_STRING mask_str;
2078 RtlInitUnicodeString( &mask_str, mask );
2079 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2080 FileBothDirectoryInformation, FALSE, &mask_str, TRUE );
2081 if (status)
2083 FindClose( info );
2084 SetLastError( RtlNtStatusToDosError( status ) );
2085 return INVALID_HANDLE_VALUE;
2088 info->data_len = io.Information;
2089 if (!has_wildcard || info->data_len < info->data_size - max_entry_size)
2091 if (has_wildcard) /* release unused buffer space */
2092 HeapReAlloc( GetProcessHeap(), HEAP_REALLOC_IN_PLACE_ONLY,
2093 info, offsetof( FIND_FIRST_INFO, data[info->data_len] ));
2094 info->data_size = 0; /* we read everything */
2097 if (!FindNextFileW( info, data ))
2099 TRACE( "%s not found\n", debugstr_w(filename) );
2100 FindClose( info );
2101 SetLastError( ERROR_FILE_NOT_FOUND );
2102 return INVALID_HANDLE_VALUE;
2104 if (!has_wildcard) /* we can't find two files with the same name */
2106 CloseHandle( info->handle );
2107 info->handle = 0;
2110 return info;
2112 error:
2113 HeapFree( GetProcessHeap(), 0, info );
2114 RtlFreeUnicodeString( &nt_name );
2115 return INVALID_HANDLE_VALUE;
2119 /*************************************************************************
2120 * FindNextFileW (KERNEL32.@)
2122 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
2124 FIND_FIRST_INFO *info;
2125 FILE_BOTH_DIR_INFORMATION *dir_info;
2126 BOOL ret = FALSE;
2127 NTSTATUS status;
2129 TRACE("%p %p\n", handle, data);
2131 if (!handle || handle == INVALID_HANDLE_VALUE)
2133 SetLastError( ERROR_INVALID_HANDLE );
2134 return ret;
2136 info = handle;
2137 if (info->magic != FIND_FIRST_MAGIC)
2139 SetLastError( ERROR_INVALID_HANDLE );
2140 return ret;
2143 RtlEnterCriticalSection( &info->cs );
2145 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
2146 else for (;;)
2148 if (info->data_pos >= info->data_len) /* need to read some more data */
2150 IO_STATUS_BLOCK io;
2152 if (info->data_size)
2153 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
2154 FileBothDirectoryInformation, FALSE, NULL, FALSE );
2155 else
2156 status = STATUS_NO_MORE_FILES;
2158 if (status)
2160 SetLastError( RtlNtStatusToDosError( status ) );
2161 if (status == STATUS_NO_MORE_FILES)
2163 CloseHandle( info->handle );
2164 info->handle = 0;
2166 break;
2168 info->data_len = io.Information;
2169 info->data_pos = 0;
2172 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
2174 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
2175 else info->data_pos = info->data_len;
2177 /* don't return '.' and '..' in the root of the drive */
2178 if (info->is_root)
2180 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
2181 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
2182 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
2185 /* check for dir symlink */
2186 if ((dir_info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
2187 (dir_info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
2188 info->wildcard)
2190 if (!check_dir_symlink( info, dir_info )) continue;
2193 data->dwFileAttributes = dir_info->FileAttributes;
2194 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
2195 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
2196 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
2197 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
2198 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
2199 data->dwReserved0 = 0;
2200 data->dwReserved1 = 0;
2202 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
2203 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
2205 if (info->level != FindExInfoBasic)
2207 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
2208 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
2210 else
2211 data->cAlternateFileName[0] = 0;
2213 TRACE("returning %s (%s)\n",
2214 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
2216 ret = TRUE;
2217 break;
2220 RtlLeaveCriticalSection( &info->cs );
2221 return ret;
2225 /*************************************************************************
2226 * FindClose (KERNEL32.@)
2228 BOOL WINAPI FindClose( HANDLE handle )
2230 FIND_FIRST_INFO *info = handle;
2232 if (!handle || handle == INVALID_HANDLE_VALUE)
2234 SetLastError( ERROR_INVALID_HANDLE );
2235 return FALSE;
2238 __TRY
2240 if (info->magic == FIND_FIRST_MAGIC)
2242 RtlEnterCriticalSection( &info->cs );
2243 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
2245 info->magic = 0;
2246 if (info->handle) CloseHandle( info->handle );
2247 info->handle = 0;
2248 RtlFreeUnicodeString( &info->path );
2249 info->data_pos = 0;
2250 info->data_len = 0;
2251 RtlLeaveCriticalSection( &info->cs );
2252 info->cs.DebugInfo->Spare[0] = 0;
2253 RtlDeleteCriticalSection( &info->cs );
2254 HeapFree( GetProcessHeap(), 0, info );
2258 __EXCEPT_PAGE_FAULT
2260 WARN("Illegal handle %p\n", handle);
2261 SetLastError( ERROR_INVALID_HANDLE );
2262 return FALSE;
2264 __ENDTRY
2266 return TRUE;
2270 /*************************************************************************
2271 * FindFirstFileA (KERNEL32.@)
2273 HANDLE WINAPI FindFirstFileA( LPCSTR lpFileName, WIN32_FIND_DATAA *lpFindData )
2275 return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
2276 FindExSearchNameMatch, NULL, 0);
2279 /*************************************************************************
2280 * FindFirstFileExA (KERNEL32.@)
2282 HANDLE WINAPI FindFirstFileExA( LPCSTR lpFileName, FINDEX_INFO_LEVELS fInfoLevelId,
2283 LPVOID lpFindFileData, FINDEX_SEARCH_OPS fSearchOp,
2284 LPVOID lpSearchFilter, DWORD dwAdditionalFlags)
2286 HANDLE handle;
2287 WIN32_FIND_DATAA *dataA;
2288 WIN32_FIND_DATAW dataW;
2289 WCHAR *nameW;
2291 if (!(nameW = FILE_name_AtoW( lpFileName, FALSE ))) return INVALID_HANDLE_VALUE;
2293 handle = FindFirstFileExW(nameW, fInfoLevelId, &dataW, fSearchOp, lpSearchFilter, dwAdditionalFlags);
2294 if (handle == INVALID_HANDLE_VALUE) return handle;
2296 dataA = lpFindFileData;
2297 dataA->dwFileAttributes = dataW.dwFileAttributes;
2298 dataA->ftCreationTime = dataW.ftCreationTime;
2299 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
2300 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
2301 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
2302 dataA->nFileSizeLow = dataW.nFileSizeLow;
2303 FILE_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
2304 FILE_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
2305 sizeof(dataA->cAlternateFileName) );
2306 return handle;
2310 /*************************************************************************
2311 * FindFirstFileW (KERNEL32.@)
2313 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
2315 return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
2316 FindExSearchNameMatch, NULL, 0);
2320 /*************************************************************************
2321 * FindNextFileA (KERNEL32.@)
2323 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
2325 WIN32_FIND_DATAW dataW;
2327 if (!FindNextFileW( handle, &dataW )) return FALSE;
2328 data->dwFileAttributes = dataW.dwFileAttributes;
2329 data->ftCreationTime = dataW.ftCreationTime;
2330 data->ftLastAccessTime = dataW.ftLastAccessTime;
2331 data->ftLastWriteTime = dataW.ftLastWriteTime;
2332 data->nFileSizeHigh = dataW.nFileSizeHigh;
2333 data->nFileSizeLow = dataW.nFileSizeLow;
2334 FILE_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
2335 FILE_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
2336 sizeof(data->cAlternateFileName) );
2337 return TRUE;
2341 /**************************************************************************
2342 * GetFileAttributesW (KERNEL32.@)
2344 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
2346 FILE_BASIC_INFORMATION info;
2347 UNICODE_STRING nt_name;
2348 OBJECT_ATTRIBUTES attr;
2349 NTSTATUS status;
2351 TRACE("%s\n", debugstr_w(name));
2353 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2355 SetLastError( ERROR_PATH_NOT_FOUND );
2356 return INVALID_FILE_ATTRIBUTES;
2359 attr.Length = sizeof(attr);
2360 attr.RootDirectory = 0;
2361 attr.Attributes = OBJ_CASE_INSENSITIVE;
2362 attr.ObjectName = &nt_name;
2363 attr.SecurityDescriptor = NULL;
2364 attr.SecurityQualityOfService = NULL;
2366 status = NtQueryAttributesFile( &attr, &info );
2367 RtlFreeUnicodeString( &nt_name );
2369 if (status == STATUS_SUCCESS) return info.FileAttributes;
2371 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
2372 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
2374 SetLastError( RtlNtStatusToDosError(status) );
2375 return INVALID_FILE_ATTRIBUTES;
2379 /**************************************************************************
2380 * GetFileAttributesA (KERNEL32.@)
2382 DWORD WINAPI GetFileAttributesA( LPCSTR name )
2384 WCHAR *nameW;
2386 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
2387 return GetFileAttributesW( nameW );
2391 /**************************************************************************
2392 * SetFileAttributesW (KERNEL32.@)
2394 BOOL WINAPI SetFileAttributesW( LPCWSTR name, DWORD attributes )
2396 UNICODE_STRING nt_name;
2397 OBJECT_ATTRIBUTES attr;
2398 IO_STATUS_BLOCK io;
2399 NTSTATUS status;
2400 HANDLE handle;
2402 TRACE("%s %x\n", debugstr_w(name), attributes);
2404 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2406 SetLastError( ERROR_PATH_NOT_FOUND );
2407 return FALSE;
2410 attr.Length = sizeof(attr);
2411 attr.RootDirectory = 0;
2412 attr.Attributes = OBJ_CASE_INSENSITIVE;
2413 attr.ObjectName = &nt_name;
2414 attr.SecurityDescriptor = NULL;
2415 attr.SecurityQualityOfService = NULL;
2417 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2418 RtlFreeUnicodeString( &nt_name );
2420 if (status == STATUS_SUCCESS)
2422 FILE_BASIC_INFORMATION info;
2424 memset( &info, 0, sizeof(info) );
2425 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2426 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2427 NtClose( handle );
2430 if (status == STATUS_SUCCESS) return TRUE;
2431 SetLastError( RtlNtStatusToDosError(status) );
2432 return FALSE;
2436 /**************************************************************************
2437 * SetFileAttributesA (KERNEL32.@)
2439 BOOL WINAPI SetFileAttributesA( LPCSTR name, DWORD attributes )
2441 WCHAR *nameW;
2443 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2444 return SetFileAttributesW( nameW, attributes );
2448 /**************************************************************************
2449 * GetFileAttributesExW (KERNEL32.@)
2451 BOOL WINAPI GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2453 FILE_NETWORK_OPEN_INFORMATION info;
2454 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
2455 UNICODE_STRING nt_name;
2456 OBJECT_ATTRIBUTES attr;
2457 NTSTATUS status;
2459 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
2461 if (level != GetFileExInfoStandard)
2463 SetLastError( ERROR_INVALID_PARAMETER );
2464 return FALSE;
2467 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2469 SetLastError( ERROR_PATH_NOT_FOUND );
2470 return FALSE;
2473 attr.Length = sizeof(attr);
2474 attr.RootDirectory = 0;
2475 attr.Attributes = OBJ_CASE_INSENSITIVE;
2476 attr.ObjectName = &nt_name;
2477 attr.SecurityDescriptor = NULL;
2478 attr.SecurityQualityOfService = NULL;
2480 status = NtQueryFullAttributesFile( &attr, &info );
2481 RtlFreeUnicodeString( &nt_name );
2483 if (status != STATUS_SUCCESS)
2485 SetLastError( RtlNtStatusToDosError(status) );
2486 return FALSE;
2489 data->dwFileAttributes = info.FileAttributes;
2490 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
2491 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
2492 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
2493 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
2494 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
2495 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
2496 data->nFileSizeLow = info.EndOfFile.u.LowPart;
2497 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
2498 return TRUE;
2502 /**************************************************************************
2503 * GetFileAttributesExA (KERNEL32.@)
2505 BOOL WINAPI GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID ptr )
2507 WCHAR *nameW;
2509 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2510 return GetFileAttributesExW( nameW, level, ptr );
2514 /******************************************************************************
2515 * GetCompressedFileSizeW (KERNEL32.@)
2517 * Get the actual number of bytes used on disk.
2519 * RETURNS
2520 * Success: Low-order doubleword of number of bytes
2521 * Failure: INVALID_FILE_SIZE
2523 DWORD WINAPI GetCompressedFileSizeW(
2524 LPCWSTR name, /* [in] Pointer to name of file */
2525 LPDWORD size_high ) /* [out] Receives high-order doubleword of size */
2527 UNICODE_STRING nt_name;
2528 OBJECT_ATTRIBUTES attr;
2529 IO_STATUS_BLOCK io;
2530 NTSTATUS status;
2531 HANDLE handle;
2532 DWORD ret = INVALID_FILE_SIZE;
2534 TRACE("%s %p\n", debugstr_w(name), size_high);
2536 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2538 SetLastError( ERROR_PATH_NOT_FOUND );
2539 return INVALID_FILE_SIZE;
2542 attr.Length = sizeof(attr);
2543 attr.RootDirectory = 0;
2544 attr.Attributes = OBJ_CASE_INSENSITIVE;
2545 attr.ObjectName = &nt_name;
2546 attr.SecurityDescriptor = NULL;
2547 attr.SecurityQualityOfService = NULL;
2549 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2550 RtlFreeUnicodeString( &nt_name );
2552 if (status == STATUS_SUCCESS)
2554 /* we don't support compressed files, simply return the file size */
2555 ret = GetFileSize( handle, size_high );
2556 NtClose( handle );
2558 else SetLastError( RtlNtStatusToDosError(status) );
2560 return ret;
2564 /******************************************************************************
2565 * GetCompressedFileSizeA (KERNEL32.@)
2567 * See GetCompressedFileSizeW.
2569 DWORD WINAPI GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
2571 WCHAR *nameW;
2573 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
2574 return GetCompressedFileSizeW( nameW, size_high );
2578 /***********************************************************************
2579 * OpenVxDHandle (KERNEL32.@)
2581 * This function is supposed to return the corresponding Ring 0
2582 * ("kernel") handle for a Ring 3 handle in Win9x.
2583 * Evidently, Wine will have problems with this. But we try anyway,
2584 * maybe it helps...
2586 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
2588 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
2589 return hHandleRing3;
2593 /****************************************************************************
2594 * DeviceIoControl (KERNEL32.@)
2596 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
2597 LPVOID lpvInBuffer, DWORD cbInBuffer,
2598 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
2599 LPDWORD lpcbBytesReturned,
2600 LPOVERLAPPED lpOverlapped)
2602 NTSTATUS status;
2604 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
2605 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
2606 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
2608 /* Check if this is a user defined control code for a VxD */
2610 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
2612 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
2613 static DeviceIoProc (*vxd_get_proc)(HANDLE);
2614 DeviceIoProc proc = NULL;
2616 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleA("krnl386.exe16"),
2617 "__wine_vxd_get_proc" );
2618 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
2619 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
2620 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
2623 /* Not a VxD, let ntdll handle it */
2625 if (lpOverlapped)
2627 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
2628 lpOverlapped->Internal = STATUS_PENDING;
2629 lpOverlapped->InternalHigh = 0;
2630 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2631 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
2632 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2633 dwIoControlCode, lpvInBuffer, cbInBuffer,
2634 lpvOutBuffer, cbOutBuffer);
2635 else
2636 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
2637 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
2638 dwIoControlCode, lpvInBuffer, cbInBuffer,
2639 lpvOutBuffer, cbOutBuffer);
2640 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
2642 else
2644 IO_STATUS_BLOCK iosb;
2646 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
2647 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
2648 dwIoControlCode, lpvInBuffer, cbInBuffer,
2649 lpvOutBuffer, cbOutBuffer);
2650 else
2651 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
2652 dwIoControlCode, lpvInBuffer, cbInBuffer,
2653 lpvOutBuffer, cbOutBuffer);
2654 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
2656 if (status) SetLastError( RtlNtStatusToDosError(status) );
2657 return !status;
2661 /***********************************************************************
2662 * OpenFile (KERNEL32.@)
2664 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
2666 HANDLE handle;
2667 FILETIME filetime;
2668 WORD filedatetime[2];
2670 if (!ofs) return HFILE_ERROR;
2672 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
2673 ((mode & 0x3 )==OF_READ)?"OF_READ":
2674 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
2675 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
2676 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
2677 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
2678 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
2679 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
2680 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
2681 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
2682 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
2683 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
2684 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
2685 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
2686 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
2687 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
2688 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
2689 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
2693 ofs->cBytes = sizeof(OFSTRUCT);
2694 ofs->nErrCode = 0;
2695 if (mode & OF_REOPEN) name = ofs->szPathName;
2697 if (!name) return HFILE_ERROR;
2699 TRACE("%s %04x\n", name, mode );
2701 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
2702 Are there any cases where getting the path here is wrong?
2703 Uwe Bonnes 1997 Apr 2 */
2704 if (!GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL )) goto error;
2706 /* OF_PARSE simply fills the structure */
2708 if (mode & OF_PARSE)
2710 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
2711 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
2712 return 0;
2715 /* OF_CREATE is completely different from all other options, so
2716 handle it first */
2718 if (mode & OF_CREATE)
2720 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
2721 goto error;
2723 else
2725 /* Now look for the file */
2727 if (!SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL ))
2728 goto error;
2730 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
2732 if (mode & OF_DELETE)
2734 if (!DeleteFileA( ofs->szPathName )) goto error;
2735 TRACE("(%s): OF_DELETE return = OK\n", name);
2736 return TRUE;
2739 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
2740 if (handle == INVALID_HANDLE_VALUE) goto error;
2742 GetFileTime( handle, NULL, NULL, &filetime );
2743 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
2744 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
2746 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
2748 CloseHandle( handle );
2749 WARN("(%s): OF_VERIFY failed\n", name );
2750 /* FIXME: what error here? */
2751 SetLastError( ERROR_FILE_NOT_FOUND );
2752 goto error;
2755 ofs->Reserved1 = filedatetime[0];
2756 ofs->Reserved2 = filedatetime[1];
2758 TRACE("(%s): OK, return = %p\n", name, handle );
2759 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
2761 CloseHandle( handle );
2762 return TRUE;
2764 return HandleToLong(handle);
2766 error: /* We get here if there was an error opening the file */
2767 ofs->nErrCode = GetLastError();
2768 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
2769 return HFILE_ERROR;
2773 /***********************************************************************
2774 * OpenFileById (KERNEL32.@)
2776 HANDLE WINAPI OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
2777 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
2779 UINT options;
2780 HANDLE result;
2781 OBJECT_ATTRIBUTES attr;
2782 NTSTATUS status;
2783 IO_STATUS_BLOCK io;
2784 UNICODE_STRING objectName;
2786 if (!id)
2788 SetLastError( ERROR_INVALID_PARAMETER );
2789 return INVALID_HANDLE_VALUE;
2792 options = FILE_OPEN_BY_FILE_ID;
2793 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
2794 options |= FILE_OPEN_FOR_BACKUP_INTENT;
2795 else
2796 options |= FILE_NON_DIRECTORY_FILE;
2797 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
2798 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
2799 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
2800 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
2802 objectName.Length = sizeof(ULONGLONG);
2803 objectName.Buffer = (WCHAR *)&id->u.FileId;
2804 attr.Length = sizeof(attr);
2805 attr.RootDirectory = handle;
2806 attr.Attributes = 0;
2807 attr.ObjectName = &objectName;
2808 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
2809 attr.SecurityQualityOfService = NULL;
2810 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
2812 status = NtCreateFile( &result, access | SYNCHRONIZE, &attr, &io, NULL, flags,
2813 share, OPEN_EXISTING, options, NULL, 0 );
2814 if (status != STATUS_SUCCESS)
2816 SetLastError( RtlNtStatusToDosError( status ) );
2817 return INVALID_HANDLE_VALUE;
2819 return result;
2823 /***********************************************************************
2824 * K32EnumDeviceDrivers (KERNEL32.@)
2826 BOOL WINAPI K32EnumDeviceDrivers(void **image_base, DWORD cb, DWORD *needed)
2828 FIXME("(%p, %d, %p): stub\n", image_base, cb, needed);
2830 if (needed)
2831 *needed = 0;
2833 return TRUE;
2836 /***********************************************************************
2837 * K32GetDeviceDriverBaseNameA (KERNEL32.@)
2839 DWORD WINAPI K32GetDeviceDriverBaseNameA(void *image_base, LPSTR base_name, DWORD size)
2841 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2843 if (base_name && size)
2844 base_name[0] = '\0';
2846 return 0;
2849 /***********************************************************************
2850 * K32GetDeviceDriverBaseNameW (KERNEL32.@)
2852 DWORD WINAPI K32GetDeviceDriverBaseNameW(void *image_base, LPWSTR base_name, DWORD size)
2854 FIXME("(%p, %p, %d): stub\n", image_base, base_name, size);
2856 if (base_name && size)
2857 base_name[0] = '\0';
2859 return 0;
2862 /***********************************************************************
2863 * K32GetDeviceDriverFileNameA (KERNEL32.@)
2865 DWORD WINAPI K32GetDeviceDriverFileNameA(void *image_base, LPSTR file_name, DWORD size)
2867 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2869 if (file_name && size)
2870 file_name[0] = '\0';
2872 return 0;
2875 /***********************************************************************
2876 * K32GetDeviceDriverFileNameW (KERNEL32.@)
2878 DWORD WINAPI K32GetDeviceDriverFileNameW(void *image_base, LPWSTR file_name, DWORD size)
2880 FIXME("(%p, %p, %d): stub\n", image_base, file_name, size);
2882 if (file_name && size)
2883 file_name[0] = '\0';
2885 return 0;
2888 /***********************************************************************
2889 * GetFinalPathNameByHandleW (KERNEL32.@)
2891 DWORD WINAPI GetFinalPathNameByHandleW(HANDLE file, LPWSTR path, DWORD charcount, DWORD flags)
2893 WCHAR buffer[sizeof(OBJECT_NAME_INFORMATION) + MAX_PATH + 1];
2894 OBJECT_NAME_INFORMATION *info = (OBJECT_NAME_INFORMATION*)&buffer;
2895 WCHAR drive_part[MAX_PATH];
2896 DWORD drive_part_len = 0;
2897 NTSTATUS status;
2898 DWORD result = 0;
2899 ULONG dummy;
2900 WCHAR *ptr;
2902 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags );
2904 if (flags & ~(FILE_NAME_OPENED | VOLUME_NAME_GUID | VOLUME_NAME_NONE | VOLUME_NAME_NT))
2906 WARN("Unknown flags: %x\n", flags);
2907 SetLastError( ERROR_INVALID_PARAMETER );
2908 return 0;
2911 /* get object name */
2912 status = NtQueryObject( file, ObjectNameInformation, &buffer, sizeof(buffer) - sizeof(WCHAR), &dummy );
2913 if (status != STATUS_SUCCESS)
2915 SetLastError( RtlNtStatusToDosError( status ) );
2916 return 0;
2918 if (!info->Name.Buffer)
2920 SetLastError( ERROR_INVALID_HANDLE );
2921 return 0;
2923 if (info->Name.Length < 4 * sizeof(WCHAR) || info->Name.Buffer[0] != '\\' ||
2924 info->Name.Buffer[1] != '?' || info->Name.Buffer[2] != '?' || info->Name.Buffer[3] != '\\' )
2926 FIXME("Unexpected object name: %s\n", debugstr_wn(info->Name.Buffer, info->Name.Length / sizeof(WCHAR)));
2927 SetLastError( ERROR_GEN_FAILURE );
2928 return 0;
2931 /* add terminating null character, remove "\\??\\" */
2932 info->Name.Buffer[info->Name.Length / sizeof(WCHAR)] = 0;
2933 info->Name.Length -= 4 * sizeof(WCHAR);
2934 info->Name.Buffer += 4;
2936 /* FILE_NAME_OPENED is not supported yet, and would require Wineserver changes */
2937 if (flags & FILE_NAME_OPENED)
2939 FIXME("FILE_NAME_OPENED not supported\n");
2940 flags &= ~FILE_NAME_OPENED;
2943 /* Get information required for VOLUME_NAME_NONE, VOLUME_NAME_GUID and VOLUME_NAME_NT */
2944 if (flags == VOLUME_NAME_NONE || flags == VOLUME_NAME_GUID || flags == VOLUME_NAME_NT)
2946 if (!GetVolumePathNameW( info->Name.Buffer, drive_part, MAX_PATH ))
2947 return 0;
2949 drive_part_len = strlenW(drive_part);
2950 if (!drive_part_len || drive_part_len > strlenW(info->Name.Buffer) ||
2951 drive_part[drive_part_len-1] != '\\' ||
2952 strncmpiW( info->Name.Buffer, drive_part, drive_part_len ))
2954 FIXME("Path %s returned by GetVolumePathNameW does not match file path %s\n",
2955 debugstr_w(drive_part), debugstr_w(info->Name.Buffer));
2956 SetLastError( ERROR_GEN_FAILURE );
2957 return 0;
2961 if (flags == VOLUME_NAME_NONE)
2963 ptr = info->Name.Buffer + drive_part_len - 1;
2964 result = strlenW(ptr);
2965 if (result < charcount)
2966 memcpy(path, ptr, (result + 1) * sizeof(WCHAR));
2967 else result++;
2969 else if (flags == VOLUME_NAME_GUID)
2971 WCHAR volume_prefix[51];
2973 /* GetVolumeNameForVolumeMountPointW sets error code on failure */
2974 if (!GetVolumeNameForVolumeMountPointW( drive_part, volume_prefix, 50 ))
2975 return 0;
2977 ptr = info->Name.Buffer + drive_part_len;
2978 result = strlenW(volume_prefix) + strlenW(ptr);
2979 if (result < charcount)
2981 path[0] = 0;
2982 strcatW(path, volume_prefix);
2983 strcatW(path, ptr);
2985 else
2987 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2988 result++;
2991 else if (flags == VOLUME_NAME_NT)
2993 WCHAR nt_prefix[MAX_PATH];
2995 /* QueryDosDeviceW sets error code on failure */
2996 drive_part[drive_part_len - 1] = 0;
2997 if (!QueryDosDeviceW( drive_part, nt_prefix, MAX_PATH ))
2998 return 0;
3000 ptr = info->Name.Buffer + drive_part_len - 1;
3001 result = strlenW(nt_prefix) + strlenW(ptr);
3002 if (result < charcount)
3004 path[0] = 0;
3005 strcatW(path, nt_prefix);
3006 strcatW(path, ptr);
3008 else
3010 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3011 result++;
3014 else if (flags == VOLUME_NAME_DOS)
3016 static const WCHAR dos_prefix[] = {'\\','\\','?','\\', '\0'};
3018 result = strlenW(dos_prefix) + strlenW(info->Name.Buffer);
3019 if (result < charcount)
3021 path[0] = 0;
3022 strcatW(path, dos_prefix);
3023 strcatW(path, info->Name.Buffer);
3025 else
3027 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3028 result++;
3031 else
3033 /* Windows crashes here, but we prefer returning ERROR_INVALID_PARAMETER */
3034 WARN("Invalid combination of flags: %x\n", flags);
3035 SetLastError( ERROR_INVALID_PARAMETER );
3038 return result;
3041 /***********************************************************************
3042 * GetFinalPathNameByHandleA (KERNEL32.@)
3044 DWORD WINAPI GetFinalPathNameByHandleA(HANDLE file, LPSTR path, DWORD charcount, DWORD flags)
3046 WCHAR *str;
3047 DWORD result, len, cp;
3049 TRACE( "(%p,%p,%d,%x)\n", file, path, charcount, flags);
3051 len = GetFinalPathNameByHandleW(file, NULL, 0, flags);
3052 if (len == 0)
3053 return 0;
3055 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
3056 if (!str)
3058 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3059 return 0;
3062 result = GetFinalPathNameByHandleW(file, str, len, flags);
3063 if (result != len - 1)
3065 HeapFree(GetProcessHeap(), 0, str);
3066 WARN("GetFinalPathNameByHandleW failed unexpectedly: %u\n", result);
3067 return 0;
3070 cp = oem_file_apis ? CP_OEMCP : CP_ACP;
3072 len = WideCharToMultiByte(cp, 0, str, -1, NULL, 0, NULL, NULL);
3073 if (!len)
3075 HeapFree(GetProcessHeap(), 0, str);
3076 WARN("Failed to get multibyte length\n");
3077 return 0;
3080 if (charcount < len)
3082 HeapFree(GetProcessHeap(), 0, str);
3083 return len - 1;
3086 len = WideCharToMultiByte(cp, 0, str, -1, path, charcount, NULL, NULL);
3087 if (!len)
3089 HeapFree(GetProcessHeap(), 0, str);
3090 WARN("WideCharToMultiByte failed\n");
3091 return 0;
3094 HeapFree(GetProcessHeap(), 0, str);
3096 return len - 1;