kernelbase: Let GetModuleBaseName succeed on 64bit modules in wow64.
[wine.git] / dlls / kernelbase / file.c
blobac04388acde36a40c057df5f4affae2ef6aa6cf8
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 <stdarg.h>
24 #include <stdio.h>
26 #define NONAMELESSUNION
27 #define NONAMELESSSTRUCT
28 #include "winerror.h"
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winnls.h"
34 #include "winternl.h"
35 #include "winioctl.h"
36 #include "wincon.h"
37 #include "fileapi.h"
38 #include "shlwapi.h"
39 #include "ddk/ntddk.h"
40 #include "ddk/ntddser.h"
42 #include "kernelbase.h"
43 #include "wine/exception.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(file);
48 /* info structure for FindFirstFile handle */
49 typedef struct
51 DWORD magic; /* magic number */
52 HANDLE handle; /* handle to directory */
53 CRITICAL_SECTION cs; /* crit section protecting this structure */
54 FINDEX_SEARCH_OPS search_op; /* Flags passed to FindFirst. */
55 FINDEX_INFO_LEVELS level; /* Level passed to FindFirst */
56 UNICODE_STRING path; /* NT path used to open the directory */
57 BOOL is_root; /* is directory the root of the drive? */
58 BOOL wildcard; /* did the mask contain wildcard characters? */
59 UINT data_pos; /* current position in dir data */
60 UINT data_len; /* length of dir data */
61 UINT data_size; /* size of data buffer, or 0 when everything has been read */
62 BYTE data[1]; /* directory data */
63 } FIND_FIRST_INFO;
65 #define FIND_FIRST_MAGIC 0xc0ffee11
67 static const UINT max_entry_size = offsetof( FILE_BOTH_DIRECTORY_INFORMATION, FileName[256] );
69 const WCHAR windows_dir[] = L"C:\\windows";
70 const WCHAR system_dir[] = L"C:\\windows\\system32";
72 static BOOL oem_file_apis;
75 static void WINAPI read_write_apc( void *apc_user, PIO_STATUS_BLOCK io, ULONG reserved )
77 LPOVERLAPPED_COMPLETION_ROUTINE func = apc_user;
78 func( RtlNtStatusToDosError( io->u.Status ), io->Information, (LPOVERLAPPED)io );
81 static const WCHAR *get_machine_wow64_dir( WORD machine )
83 switch (machine)
85 case IMAGE_FILE_MACHINE_TARGET_HOST: return system_dir;
86 case IMAGE_FILE_MACHINE_I386: return L"C:\\windows\\syswow64";
87 case IMAGE_FILE_MACHINE_ARMNT: return L"C:\\windows\\sysarm32";
88 case IMAGE_FILE_MACHINE_AMD64: return L"C:\\windows\\sysx8664";
89 case IMAGE_FILE_MACHINE_ARM64: return L"C:\\windows\\sysarm64";
90 default: return NULL;
95 /***********************************************************************
96 * Operations on file names
97 ***********************************************************************/
100 /***********************************************************************
101 * contains_path
103 * Check if the file name contains a path; helper for SearchPathW.
104 * A relative path is not considered a path unless it starts with ./ or ../
106 static inline BOOL contains_path( const WCHAR *name )
108 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
109 if (name[0] != '.') return FALSE;
110 if (name[1] == '/' || name[1] == '\\') return TRUE;
111 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
115 /***********************************************************************
116 * add_boot_rename_entry
118 * Adds an entry to the registry that is loaded when windows boots and
119 * checks if there are some files to be removed or renamed/moved.
120 * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
121 * non-NULL then the file is moved, otherwise it is deleted. The
122 * entry of the registry key is always appended with two zero
123 * terminated strings. If <fn2> is NULL then the second entry is
124 * simply a single 0-byte. Otherwise the second filename goes
125 * there. The entries are prepended with \??\ before the path and the
126 * second filename gets also a '!' as the first character if
127 * MOVEFILE_REPLACE_EXISTING is set. After the final string another
128 * 0-byte follows to indicate the end of the strings.
129 * i.e.:
130 * \??\D:\test\file1[0]
131 * !\??\D:\test\file1_renamed[0]
132 * \??\D:\Test|delete[0]
133 * [0] <- file is to be deleted, second string empty
134 * \??\D:\test\file2[0]
135 * !\??\D:\test\file2_renamed[0]
136 * [0] <- indicates end of strings
138 * or:
139 * \??\D:\test\file1[0]
140 * !\??\D:\test\file1_renamed[0]
141 * \??\D:\Test|delete[0]
142 * [0] <- file is to be deleted, second string empty
143 * [0] <- indicates end of strings
146 static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
148 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
150 OBJECT_ATTRIBUTES attr;
151 UNICODE_STRING nameW, source_name, dest_name;
152 KEY_VALUE_PARTIAL_INFORMATION *info;
153 BOOL rc = FALSE;
154 HANDLE key = 0;
155 DWORD len1, len2;
156 DWORD size = 0;
157 BYTE *buffer = NULL;
158 WCHAR *p;
160 if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
162 SetLastError( ERROR_PATH_NOT_FOUND );
163 return FALSE;
165 dest_name.Buffer = NULL;
166 if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
168 RtlFreeUnicodeString( &source_name );
169 SetLastError( ERROR_PATH_NOT_FOUND );
170 return FALSE;
173 attr.Length = sizeof(attr);
174 attr.RootDirectory = 0;
175 attr.ObjectName = &nameW;
176 attr.Attributes = 0;
177 attr.SecurityDescriptor = NULL;
178 attr.SecurityQualityOfService = NULL;
179 RtlInitUnicodeString( &nameW, L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
181 if (NtCreateKey( &key, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
183 RtlFreeUnicodeString( &source_name );
184 RtlFreeUnicodeString( &dest_name );
185 return FALSE;
188 len1 = source_name.Length + sizeof(WCHAR);
189 if (dest)
191 len2 = dest_name.Length + sizeof(WCHAR);
192 if (flags & MOVEFILE_REPLACE_EXISTING)
193 len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
195 else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
197 RtlInitUnicodeString( &nameW, L"PendingFileRenameOperations" );
199 /* First we check if the key exists and if so how many bytes it already contains. */
200 if (NtQueryValueKey( key, &nameW, KeyValuePartialInformation,
201 NULL, 0, &size ) == STATUS_BUFFER_TOO_SMALL)
203 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size + len1 + len2 + sizeof(WCHAR) ))) goto done;
204 if (NtQueryValueKey( key, &nameW, KeyValuePartialInformation, buffer, size, &size )) goto done;
205 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
206 if (info->Type != REG_MULTI_SZ) goto done;
207 if (size > sizeof(info)) size -= sizeof(WCHAR); /* remove terminating null (will be added back later) */
209 else
211 size = info_size;
212 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size + len1 + len2 + sizeof(WCHAR) ))) goto done;
215 memcpy( buffer + size, source_name.Buffer, len1 );
216 size += len1;
217 p = (WCHAR *)(buffer + size);
218 if (dest)
220 if (flags & MOVEFILE_REPLACE_EXISTING) *p++ = '!';
221 memcpy( p, dest_name.Buffer, len2 );
222 size += len2;
224 else
226 *p = 0;
227 size += sizeof(WCHAR);
230 /* add final null */
231 p = (WCHAR *)(buffer + size);
232 *p = 0;
233 size += sizeof(WCHAR);
234 rc = !NtSetValueKey( key, &nameW, 0, REG_MULTI_SZ, buffer + info_size, size - info_size );
236 done:
237 RtlFreeUnicodeString( &source_name );
238 RtlFreeUnicodeString( &dest_name );
239 if (key) NtClose(key);
240 HeapFree( GetProcessHeap(), 0, buffer );
241 return rc;
245 /***********************************************************************
246 * append_ext
248 static WCHAR *append_ext( const WCHAR *name, const WCHAR *ext )
250 const WCHAR *p;
251 WCHAR *ret;
252 DWORD len;
254 if (!ext) return NULL;
255 p = wcsrchr( name, '.' );
256 if (p && !wcschr( p, '/' ) && !wcschr( p, '\\' )) return NULL;
258 len = lstrlenW( name ) + lstrlenW( ext );
259 if ((ret = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
261 lstrcpyW( ret, name );
262 lstrcatW( ret, ext );
264 return ret;
268 /***********************************************************************
269 * find_actctx_dllpath
271 * Find the path (if any) of the dll from the activation context.
272 * Returned path doesn't include a name.
274 static NTSTATUS find_actctx_dllpath( const WCHAR *name, WCHAR **path )
276 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
277 ACTCTX_SECTION_KEYED_DATA data;
278 UNICODE_STRING nameW;
279 NTSTATUS status;
280 SIZE_T needed, size = 1024;
281 WCHAR *p;
283 RtlInitUnicodeString( &nameW, name );
284 data.cbSize = sizeof(data);
285 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
286 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
287 &nameW, &data );
288 if (status != STATUS_SUCCESS) return status;
290 for (;;)
292 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
294 status = STATUS_NO_MEMORY;
295 goto done;
297 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
298 AssemblyDetailedInformationInActivationContext,
299 info, size, &needed );
300 if (status == STATUS_SUCCESS) break;
301 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
302 RtlFreeHeap( GetProcessHeap(), 0, info );
303 size = needed;
304 /* restart with larger buffer */
307 if (!info->lpAssemblyManifestPath)
309 status = STATUS_SXS_KEY_NOT_FOUND;
310 goto done;
313 if ((p = wcsrchr( info->lpAssemblyManifestPath, '\\' )))
315 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
317 p++;
318 if (!dirlen ||
319 CompareStringOrdinal( p, dirlen, info->lpAssemblyDirectoryName, dirlen, TRUE ) != CSTR_EQUAL ||
320 wcsicmp( p + dirlen, L".manifest" ))
322 /* manifest name does not match directory name, so it's not a global
323 * windows/winsxs manifest; use the manifest directory name instead */
324 dirlen = p - info->lpAssemblyManifestPath;
325 needed = (dirlen + 1) * sizeof(WCHAR);
326 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
328 status = STATUS_NO_MEMORY;
329 goto done;
331 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
332 *(p + dirlen) = 0;
333 goto done;
337 if (!info->lpAssemblyDirectoryName)
339 status = STATUS_SXS_KEY_NOT_FOUND;
340 goto done;
343 needed = sizeof(L"C:\\windows\\winsxs\\") + info->ulAssemblyDirectoryNameLength + sizeof(WCHAR);
345 if (!(*path = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
347 status = STATUS_NO_MEMORY;
348 goto done;
350 lstrcpyW( p, L"C:\\windows\\winsxs\\" );
351 p += lstrlenW(p);
352 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
353 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
354 *p++ = '\\';
355 *p = 0;
356 done:
357 RtlFreeHeap( GetProcessHeap(), 0, info );
358 RtlReleaseActivationContext( data.hActCtx );
359 return status;
363 /***********************************************************************
364 * copy_filename
366 static DWORD copy_filename( const WCHAR *name, WCHAR *buffer, DWORD len )
368 UINT ret = lstrlenW( name ) + 1;
369 if (buffer && len >= ret)
371 lstrcpyW( buffer, name );
372 ret--;
374 return ret;
378 /***********************************************************************
379 * copy_filename_WtoA
381 * copy a file name back to OEM/Ansi, but only if the buffer is large enough
383 static DWORD copy_filename_WtoA( LPCWSTR nameW, LPSTR buffer, DWORD len )
385 UNICODE_STRING strW;
386 DWORD ret;
388 RtlInitUnicodeString( &strW, nameW );
390 ret = oem_file_apis ? RtlUnicodeStringToOemSize( &strW ) : RtlUnicodeStringToAnsiSize( &strW );
391 if (buffer && ret <= len)
393 ANSI_STRING str;
395 str.Buffer = buffer;
396 str.MaximumLength = min( len, UNICODE_STRING_MAX_CHARS );
397 if (oem_file_apis)
398 RtlUnicodeStringToOemString( &str, &strW, FALSE );
399 else
400 RtlUnicodeStringToAnsiString( &str, &strW, FALSE );
401 ret = str.Length; /* length without terminating 0 */
403 return ret;
407 /***********************************************************************
408 * file_name_AtoW
410 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
412 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
413 * there is no possibility for the function to do that twice, taking into
414 * account any called function.
416 WCHAR *file_name_AtoW( LPCSTR name, BOOL alloc )
418 ANSI_STRING str;
419 UNICODE_STRING strW, *pstrW;
420 NTSTATUS status;
422 RtlInitAnsiString( &str, name );
423 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
424 if (oem_file_apis)
425 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
426 else
427 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
428 if (status == STATUS_SUCCESS) return pstrW->Buffer;
430 if (status == STATUS_BUFFER_OVERFLOW)
431 SetLastError( ERROR_FILENAME_EXCED_RANGE );
432 else
433 SetLastError( RtlNtStatusToDosError(status) );
434 return NULL;
438 /***********************************************************************
439 * file_name_WtoA
441 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
443 DWORD file_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
445 DWORD ret;
447 if (srclen < 0) srclen = lstrlenW( src ) + 1;
448 if (!destlen)
450 if (oem_file_apis)
452 UNICODE_STRING strW;
453 strW.Buffer = (WCHAR *)src;
454 strW.Length = srclen * sizeof(WCHAR);
455 ret = RtlUnicodeStringToOemSize( &strW ) - 1;
457 else
458 RtlUnicodeToMultiByteSize( &ret, src, srclen * sizeof(WCHAR) );
460 else
462 if (oem_file_apis)
463 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
464 else
465 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
467 return ret;
471 /***********************************************************************
472 * is_same_file
474 static BOOL is_same_file( HANDLE h1, HANDLE h2 )
476 FILE_OBJECTID_BUFFER id1, id2;
477 IO_STATUS_BLOCK io;
479 return (!NtFsControlFile( h1, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &id1, sizeof(id1) ) &&
480 !NtFsControlFile( h2, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &id2, sizeof(id2) ) &&
481 !memcmp( &id1.ObjectId, &id2.ObjectId, sizeof(id1.ObjectId) ));
485 /******************************************************************************
486 * AreFileApisANSI (kernelbase.@)
488 BOOL WINAPI DECLSPEC_HOTPATCH AreFileApisANSI(void)
490 return !oem_file_apis;
494 /***********************************************************************
495 * CopyFileExW (kernelbase.@)
497 BOOL WINAPI CopyFileExW( const WCHAR *source, const WCHAR *dest, LPPROGRESS_ROUTINE progress,
498 void *param, BOOL *cancel_ptr, DWORD flags )
500 static const int buffer_size = 65536;
501 HANDLE h1, h2;
502 FILE_BASIC_INFORMATION info;
503 IO_STATUS_BLOCK io;
504 DWORD count;
505 BOOL ret = FALSE;
506 char *buffer;
508 if (!source || !dest)
510 SetLastError( ERROR_INVALID_PARAMETER );
511 return FALSE;
513 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
515 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
516 return FALSE;
519 TRACE("%s -> %s, %lx\n", debugstr_w(source), debugstr_w(dest), flags);
521 if (flags & COPY_FILE_RESTARTABLE)
522 FIXME("COPY_FILE_RESTARTABLE is not supported\n");
523 if (flags & COPY_FILE_COPY_SYMLINK)
524 FIXME("COPY_FILE_COPY_SYMLINK is not supported\n");
525 if (flags & COPY_FILE_OPEN_SOURCE_FOR_WRITE)
526 FIXME("COPY_FILE_OPEN_SOURCE_FOR_WRITE is not supported\n");
528 if ((h1 = CreateFileW( source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
529 NULL, OPEN_EXISTING, 0, 0 )) == INVALID_HANDLE_VALUE)
531 WARN("Unable to open source %s\n", debugstr_w(source));
532 HeapFree( GetProcessHeap(), 0, buffer );
533 return FALSE;
536 if (!set_ntstatus( NtQueryInformationFile( h1, &io, &info, sizeof(info), FileBasicInformation )))
538 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
539 HeapFree( GetProcessHeap(), 0, buffer );
540 CloseHandle( h1 );
541 return FALSE;
544 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
546 BOOL same_file = FALSE;
547 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
548 if (h2 != INVALID_HANDLE_VALUE)
550 same_file = is_same_file( h1, h2 );
551 CloseHandle( h2 );
553 if (same_file)
555 HeapFree( GetProcessHeap(), 0, buffer );
556 CloseHandle( h1 );
557 SetLastError( ERROR_SHARING_VIOLATION );
558 return FALSE;
562 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
563 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
564 info.FileAttributes, h1 )) == INVALID_HANDLE_VALUE)
566 WARN("Unable to open dest %s\n", debugstr_w(dest));
567 HeapFree( GetProcessHeap(), 0, buffer );
568 CloseHandle( h1 );
569 return FALSE;
572 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
574 char *p = buffer;
575 while (count != 0)
577 DWORD res;
578 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
579 p += res;
580 count -= res;
583 ret = TRUE;
584 done:
585 /* Maintain the timestamp of source file to destination file */
586 info.FileAttributes = 0;
587 NtSetInformationFile( h2, &io, &info, sizeof(info), FileBasicInformation );
588 HeapFree( GetProcessHeap(), 0, buffer );
589 CloseHandle( h1 );
590 CloseHandle( h2 );
591 if (ret) SetLastError( 0 );
592 return ret;
596 /**************************************************************************
597 * CopyFileW (kernelbase.@)
599 BOOL WINAPI DECLSPEC_HOTPATCH CopyFileW( const WCHAR *source, const WCHAR *dest, BOOL fail_if_exists )
601 return CopyFileExW( source, dest, NULL, NULL, NULL, fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
605 /***********************************************************************
606 * CreateDirectoryA (kernelbase.@)
608 BOOL WINAPI DECLSPEC_HOTPATCH CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
610 WCHAR *pathW;
612 if (!(pathW = file_name_AtoW( path, FALSE ))) return FALSE;
613 return CreateDirectoryW( pathW, sa );
617 /***********************************************************************
618 * CreateDirectoryW (kernelbase.@)
620 BOOL WINAPI DECLSPEC_HOTPATCH CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
622 OBJECT_ATTRIBUTES attr;
623 UNICODE_STRING nt_name;
624 IO_STATUS_BLOCK io;
625 NTSTATUS status;
626 HANDLE handle;
628 TRACE( "%s\n", debugstr_w(path) );
630 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
632 SetLastError( ERROR_PATH_NOT_FOUND );
633 return FALSE;
635 attr.Length = sizeof(attr);
636 attr.RootDirectory = 0;
637 attr.Attributes = OBJ_CASE_INSENSITIVE;
638 attr.ObjectName = &nt_name;
639 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
640 attr.SecurityQualityOfService = NULL;
642 status = NtCreateFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io, NULL,
643 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
644 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
645 if (status == STATUS_SUCCESS) NtClose( handle );
647 RtlFreeUnicodeString( &nt_name );
648 return set_ntstatus( status );
652 /***********************************************************************
653 * CreateDirectoryEx (kernelbase.@)
655 BOOL WINAPI DECLSPEC_HOTPATCH CreateDirectoryExW( LPCWSTR template, LPCWSTR path,
656 LPSECURITY_ATTRIBUTES sa )
658 return CreateDirectoryW( path, sa );
662 /*************************************************************************
663 * CreateFile2 (kernelbase.@)
665 HANDLE WINAPI DECLSPEC_HOTPATCH CreateFile2( LPCWSTR name, DWORD access, DWORD sharing, DWORD creation,
666 CREATEFILE2_EXTENDED_PARAMETERS *params )
668 static const DWORD attributes_mask = FILE_ATTRIBUTE_READONLY |
669 FILE_ATTRIBUTE_HIDDEN |
670 FILE_ATTRIBUTE_SYSTEM |
671 FILE_ATTRIBUTE_ARCHIVE |
672 FILE_ATTRIBUTE_NORMAL |
673 FILE_ATTRIBUTE_TEMPORARY |
674 FILE_ATTRIBUTE_OFFLINE |
675 FILE_ATTRIBUTE_ENCRYPTED |
676 FILE_ATTRIBUTE_INTEGRITY_STREAM;
677 static const DWORD flags_mask = FILE_FLAG_BACKUP_SEMANTICS |
678 FILE_FLAG_DELETE_ON_CLOSE |
679 FILE_FLAG_NO_BUFFERING |
680 FILE_FLAG_OPEN_NO_RECALL |
681 FILE_FLAG_OPEN_REPARSE_POINT |
682 FILE_FLAG_OVERLAPPED |
683 FILE_FLAG_POSIX_SEMANTICS |
684 FILE_FLAG_RANDOM_ACCESS |
685 FILE_FLAG_SEQUENTIAL_SCAN |
686 FILE_FLAG_WRITE_THROUGH;
688 LPSECURITY_ATTRIBUTES sa = params ? params->lpSecurityAttributes : NULL;
689 HANDLE template = params ? params->hTemplateFile : NULL;
690 DWORD attributes = params ? params->dwFileAttributes : 0;
691 DWORD flags = params ? params->dwFileFlags : 0;
693 FIXME( "(%s %lx %lx %lx %p), partial stub\n", debugstr_w(name), access, sharing, creation, params );
695 if (attributes & ~attributes_mask) FIXME( "unsupported attributes %#lx\n", attributes );
696 if (flags & ~flags_mask) FIXME( "unsupported flags %#lx\n", flags );
697 attributes &= attributes_mask;
698 flags &= flags_mask;
700 return CreateFileW( name, access, sharing, sa, creation, flags | attributes, template );
704 /*************************************************************************
705 * CreateFileA (kernelbase.@)
707 HANDLE WINAPI DECLSPEC_HOTPATCH CreateFileA( LPCSTR name, DWORD access, DWORD sharing,
708 LPSECURITY_ATTRIBUTES sa, DWORD creation,
709 DWORD attributes, HANDLE template)
711 WCHAR *nameW;
713 if ((GetVersion() & 0x80000000) && IsBadStringPtrA( name, -1 )) return INVALID_HANDLE_VALUE;
714 if (!(nameW = file_name_AtoW( name, FALSE ))) return INVALID_HANDLE_VALUE;
715 return CreateFileW( nameW, access, sharing, sa, creation, attributes, template );
718 static UINT get_nt_file_options( DWORD attributes )
720 UINT options = 0;
722 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
723 options |= FILE_OPEN_FOR_BACKUP_INTENT;
724 else
725 options |= FILE_NON_DIRECTORY_FILE;
726 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
727 options |= FILE_DELETE_ON_CLOSE;
728 if (attributes & FILE_FLAG_NO_BUFFERING)
729 options |= FILE_NO_INTERMEDIATE_BUFFERING;
730 if (!(attributes & FILE_FLAG_OVERLAPPED))
731 options |= FILE_SYNCHRONOUS_IO_NONALERT;
732 if (attributes & FILE_FLAG_RANDOM_ACCESS)
733 options |= FILE_RANDOM_ACCESS;
734 if (attributes & FILE_FLAG_SEQUENTIAL_SCAN)
735 options |= FILE_SEQUENTIAL_ONLY;
736 if (attributes & FILE_FLAG_WRITE_THROUGH)
737 options |= FILE_WRITE_THROUGH;
738 return options;
741 /*************************************************************************
742 * CreateFileW (kernelbase.@)
744 HANDLE WINAPI DECLSPEC_HOTPATCH CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
745 LPSECURITY_ATTRIBUTES sa, DWORD creation,
746 DWORD attributes, HANDLE template )
748 NTSTATUS status;
749 OBJECT_ATTRIBUTES attr;
750 UNICODE_STRING nameW;
751 IO_STATUS_BLOCK io;
752 HANDLE ret;
753 const WCHAR *vxd_name = NULL;
754 SECURITY_QUALITY_OF_SERVICE qos;
756 static const UINT nt_disposition[5] =
758 FILE_CREATE, /* CREATE_NEW */
759 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
760 FILE_OPEN, /* OPEN_EXISTING */
761 FILE_OPEN_IF, /* OPEN_ALWAYS */
762 FILE_OVERWRITE /* TRUNCATE_EXISTING */
766 /* sanity checks */
768 if (!filename || !filename[0])
770 SetLastError( ERROR_PATH_NOT_FOUND );
771 return INVALID_HANDLE_VALUE;
774 TRACE( "%s %s%s%s%s%s%s%s creation %ld attributes 0x%lx\n", debugstr_w(filename),
775 (access & GENERIC_READ) ? "GENERIC_READ " : "",
776 (access & GENERIC_WRITE) ? "GENERIC_WRITE " : "",
777 (access & GENERIC_EXECUTE) ? "GENERIC_EXECUTE " : "",
778 !access ? "QUERY_ACCESS " : "",
779 (sharing & FILE_SHARE_READ) ? "FILE_SHARE_READ " : "",
780 (sharing & FILE_SHARE_WRITE) ? "FILE_SHARE_WRITE " : "",
781 (sharing & FILE_SHARE_DELETE) ? "FILE_SHARE_DELETE " : "",
782 creation, attributes);
784 if ((GetVersion() & 0x80000000) && !wcsncmp( filename, L"\\\\.\\", 4 ) &&
785 !RtlIsDosDeviceName_U( filename + 4 ) &&
786 wcsnicmp( filename + 4, L"PIPE\\", 5 ) &&
787 wcsnicmp( filename + 4, L"MAILSLOT\\", 9 ))
789 vxd_name = filename + 4;
790 if (!creation) creation = OPEN_EXISTING;
793 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
795 SetLastError( ERROR_INVALID_PARAMETER );
796 return INVALID_HANDLE_VALUE;
799 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
801 SetLastError( ERROR_PATH_NOT_FOUND );
802 return INVALID_HANDLE_VALUE;
805 /* now call NtCreateFile */
807 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
808 access |= DELETE;
810 attr.Length = sizeof(attr);
811 attr.RootDirectory = 0;
812 attr.Attributes = OBJ_CASE_INSENSITIVE;
813 attr.ObjectName = &nameW;
814 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
815 if (attributes & SECURITY_SQOS_PRESENT)
817 qos.Length = sizeof(qos);
818 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
819 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
820 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
821 attr.SecurityQualityOfService = &qos;
823 else
824 attr.SecurityQualityOfService = NULL;
826 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
828 status = NtCreateFile( &ret, access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attr, &io,
829 NULL, attributes & FILE_ATTRIBUTE_VALID_FLAGS, sharing,
830 nt_disposition[creation - CREATE_NEW],
831 get_nt_file_options( attributes ), NULL, 0 );
832 if (status)
834 if (vxd_name && vxd_name[0])
836 static HANDLE (*vxd_open)(LPCWSTR,DWORD,SECURITY_ATTRIBUTES*);
837 if (!vxd_open) vxd_open = (void *)GetProcAddress( GetModuleHandleW(L"krnl386.exe16"),
838 "__wine_vxd_open" );
839 if (vxd_open && (ret = vxd_open( vxd_name, access, sa ))) goto done;
842 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
843 ret = INVALID_HANDLE_VALUE;
845 /* In the case file creation was rejected due to CREATE_NEW flag
846 * was specified and file with that name already exists, correct
847 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
848 * Note: RtlNtStatusToDosError is not the subject to blame here.
850 if (status == STATUS_OBJECT_NAME_COLLISION)
851 SetLastError( ERROR_FILE_EXISTS );
852 else
853 SetLastError( RtlNtStatusToDosError(status) );
855 else
857 if ((creation == CREATE_ALWAYS && io.Information == FILE_OVERWRITTEN) ||
858 (creation == OPEN_ALWAYS && io.Information == FILE_OPENED))
859 SetLastError( ERROR_ALREADY_EXISTS );
860 else
861 SetLastError( 0 );
863 RtlFreeUnicodeString( &nameW );
865 done:
866 if (!ret) ret = INVALID_HANDLE_VALUE;
867 TRACE("returning %p\n", ret);
868 return ret;
872 /*************************************************************************
873 * CreateHardLinkA (kernelbase.@)
875 BOOL WINAPI DECLSPEC_HOTPATCH CreateHardLinkA( const char *dest, const char *source,
876 SECURITY_ATTRIBUTES *attr )
878 WCHAR *sourceW, *destW;
879 BOOL res;
881 if (!(sourceW = file_name_AtoW( source, TRUE ))) return FALSE;
882 if (!(destW = file_name_AtoW( dest, TRUE )))
884 HeapFree( GetProcessHeap(), 0, sourceW );
885 return FALSE;
887 res = CreateHardLinkW( destW, sourceW, attr );
888 HeapFree( GetProcessHeap(), 0, sourceW );
889 HeapFree( GetProcessHeap(), 0, destW );
890 return res;
894 /*************************************************************************
895 * CreateHardLinkW (kernelbase.@)
897 BOOL WINAPI CreateHardLinkW( LPCWSTR dest, LPCWSTR source, SECURITY_ATTRIBUTES *sec_attr )
899 UNICODE_STRING ntDest, ntSource;
900 FILE_LINK_INFORMATION *info = NULL;
901 OBJECT_ATTRIBUTES attr;
902 IO_STATUS_BLOCK io;
903 BOOL ret = FALSE;
904 HANDLE file;
905 ULONG size;
907 TRACE( "(%s, %s, %p)\n", debugstr_w(dest), debugstr_w(source), sec_attr );
909 ntDest.Buffer = ntSource.Buffer = NULL;
910 if (!RtlDosPathNameToNtPathName_U( dest, &ntDest, NULL, NULL ) ||
911 !RtlDosPathNameToNtPathName_U( source, &ntSource, NULL, NULL ))
913 SetLastError( ERROR_PATH_NOT_FOUND );
914 goto done;
917 size = offsetof( FILE_LINK_INFORMATION, FileName ) + ntDest.Length;
918 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
920 SetLastError( ERROR_OUTOFMEMORY );
921 goto done;
924 InitializeObjectAttributes( &attr, &ntSource, OBJ_CASE_INSENSITIVE, 0, NULL );
925 if (!(ret = set_ntstatus( NtOpenFile( &file, SYNCHRONIZE, &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE,
926 FILE_SYNCHRONOUS_IO_NONALERT ) )))
927 goto done;
929 info->ReplaceIfExists = FALSE;
930 info->RootDirectory = NULL;
931 info->FileNameLength = ntDest.Length;
932 memcpy( info->FileName, ntDest.Buffer, ntDest.Length );
933 ret = set_ntstatus( NtSetInformationFile( file, &io, info, size, FileLinkInformation ) );
934 NtClose( file );
936 done:
937 RtlFreeUnicodeString( &ntSource );
938 RtlFreeUnicodeString( &ntDest );
939 HeapFree( GetProcessHeap(), 0, info );
940 return ret;
944 /*************************************************************************
945 * CreateSymbolicLinkW (kernelbase.@)
947 BOOLEAN WINAPI /* DECLSPEC_HOTPATCH */ CreateSymbolicLinkW( LPCWSTR link, LPCWSTR target, DWORD flags )
949 FIXME( "(%s %s %ld): stub\n", debugstr_w(link), debugstr_w(target), flags );
950 return TRUE;
954 /***********************************************************************
955 * DeleteFileA (kernelbase.@)
957 BOOL WINAPI DECLSPEC_HOTPATCH DeleteFileA( LPCSTR path )
959 WCHAR *pathW;
961 if (!(pathW = file_name_AtoW( path, FALSE ))) return FALSE;
962 return DeleteFileW( pathW );
966 /***********************************************************************
967 * DeleteFileW (kernelbase.@)
969 BOOL WINAPI DECLSPEC_HOTPATCH DeleteFileW( LPCWSTR path )
971 UNICODE_STRING nameW;
972 OBJECT_ATTRIBUTES attr;
973 NTSTATUS status;
974 HANDLE hFile;
975 IO_STATUS_BLOCK io;
977 TRACE( "%s\n", debugstr_w(path) );
979 if (!RtlDosPathNameToNtPathName_U( path, &nameW, NULL, NULL ))
981 SetLastError( ERROR_PATH_NOT_FOUND );
982 return FALSE;
985 attr.Length = sizeof(attr);
986 attr.RootDirectory = 0;
987 attr.Attributes = OBJ_CASE_INSENSITIVE;
988 attr.ObjectName = &nameW;
989 attr.SecurityDescriptor = NULL;
990 attr.SecurityQualityOfService = NULL;
992 status = NtCreateFile(&hFile, SYNCHRONIZE | DELETE, &attr, &io, NULL, 0,
993 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
994 FILE_OPEN, FILE_DELETE_ON_CLOSE | FILE_NON_DIRECTORY_FILE, NULL, 0);
995 if (status == STATUS_SUCCESS) status = NtClose(hFile);
997 RtlFreeUnicodeString( &nameW );
998 return set_ntstatus( status );
1002 /****************************************************************************
1003 * FindCloseChangeNotification (kernelbase.@)
1005 BOOL WINAPI DECLSPEC_HOTPATCH FindCloseChangeNotification( HANDLE handle )
1007 return CloseHandle( handle );
1011 /****************************************************************************
1012 * FindFirstChangeNotificationA (kernelbase.@)
1014 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstChangeNotificationA( LPCSTR path, BOOL subtree, DWORD filter )
1016 WCHAR *pathW;
1018 if (!(pathW = file_name_AtoW( path, FALSE ))) return INVALID_HANDLE_VALUE;
1019 return FindFirstChangeNotificationW( pathW, subtree, filter );
1024 * NtNotifyChangeDirectoryFile may write back to the IO_STATUS_BLOCK
1025 * asynchronously. We don't care about the contents, but it can't
1026 * be placed on the stack since it will go out of scope when we return.
1028 static IO_STATUS_BLOCK dummy_iosb;
1030 /****************************************************************************
1031 * FindFirstChangeNotificationW (kernelbase.@)
1033 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstChangeNotificationW( LPCWSTR path, BOOL subtree, DWORD filter )
1035 UNICODE_STRING nt_name;
1036 OBJECT_ATTRIBUTES attr;
1037 NTSTATUS status;
1038 HANDLE handle = INVALID_HANDLE_VALUE;
1040 TRACE( "%s %d %lx\n", debugstr_w(path), subtree, filter );
1042 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1044 SetLastError( ERROR_PATH_NOT_FOUND );
1045 return handle;
1048 attr.Length = sizeof(attr);
1049 attr.RootDirectory = 0;
1050 attr.Attributes = OBJ_CASE_INSENSITIVE;
1051 attr.ObjectName = &nt_name;
1052 attr.SecurityDescriptor = NULL;
1053 attr.SecurityQualityOfService = NULL;
1055 status = NtOpenFile( &handle, FILE_LIST_DIRECTORY | SYNCHRONIZE, &attr, &dummy_iosb,
1056 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1057 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1058 RtlFreeUnicodeString( &nt_name );
1060 if (!set_ntstatus( status )) return INVALID_HANDLE_VALUE;
1062 status = NtNotifyChangeDirectoryFile( handle, NULL, NULL, NULL, &dummy_iosb, NULL, 0, filter, subtree );
1063 if (status != STATUS_PENDING)
1065 NtClose( handle );
1066 SetLastError( RtlNtStatusToDosError(status) );
1067 return INVALID_HANDLE_VALUE;
1069 return handle;
1073 /****************************************************************************
1074 * FindNextChangeNotification (kernelbase.@)
1076 BOOL WINAPI DECLSPEC_HOTPATCH FindNextChangeNotification( HANDLE handle )
1078 NTSTATUS status = NtNotifyChangeDirectoryFile( handle, NULL, NULL, NULL, &dummy_iosb,
1079 NULL, 0, FILE_NOTIFY_CHANGE_SIZE, 0 );
1080 if (status == STATUS_PENDING) return TRUE;
1081 return set_ntstatus( status );
1085 /******************************************************************************
1086 * FindFirstFileExA (kernelbase.@)
1088 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstFileExA( const char *filename, FINDEX_INFO_LEVELS level,
1089 void *data, FINDEX_SEARCH_OPS search_op,
1090 void *filter, DWORD flags )
1092 HANDLE handle;
1093 WIN32_FIND_DATAA *dataA = data;
1094 WIN32_FIND_DATAW dataW;
1095 WCHAR *nameW;
1097 if (!(nameW = file_name_AtoW( filename, FALSE ))) return INVALID_HANDLE_VALUE;
1099 handle = FindFirstFileExW( nameW, level, &dataW, search_op, filter, flags );
1100 if (handle == INVALID_HANDLE_VALUE) return handle;
1102 dataA->dwFileAttributes = dataW.dwFileAttributes;
1103 dataA->ftCreationTime = dataW.ftCreationTime;
1104 dataA->ftLastAccessTime = dataW.ftLastAccessTime;
1105 dataA->ftLastWriteTime = dataW.ftLastWriteTime;
1106 dataA->nFileSizeHigh = dataW.nFileSizeHigh;
1107 dataA->nFileSizeLow = dataW.nFileSizeLow;
1108 file_name_WtoA( dataW.cFileName, -1, dataA->cFileName, sizeof(dataA->cFileName) );
1109 file_name_WtoA( dataW.cAlternateFileName, -1, dataA->cAlternateFileName,
1110 sizeof(dataA->cAlternateFileName) );
1111 return handle;
1115 /******************************************************************************
1116 * FindFirstFileExW (kernelbase.@)
1118 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstFileExW( LPCWSTR filename, FINDEX_INFO_LEVELS level,
1119 LPVOID data, FINDEX_SEARCH_OPS search_op,
1120 LPVOID filter, DWORD flags )
1122 WCHAR *mask;
1123 BOOL has_wildcard = FALSE;
1124 FIND_FIRST_INFO *info = NULL;
1125 UNICODE_STRING nt_name;
1126 OBJECT_ATTRIBUTES attr;
1127 IO_STATUS_BLOCK io;
1128 NTSTATUS status;
1129 DWORD size, device = 0;
1131 TRACE( "%s %d %p %d %p %lx\n", debugstr_w(filename), level, data, search_op, filter, flags );
1133 if (flags & ~FIND_FIRST_EX_LARGE_FETCH)
1135 FIXME("flags not implemented 0x%08lx\n", flags );
1137 if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories)
1139 FIXME( "search_op not implemented 0x%08x\n", search_op );
1140 SetLastError( ERROR_INVALID_PARAMETER );
1141 return INVALID_HANDLE_VALUE;
1143 if (level != FindExInfoStandard && level != FindExInfoBasic)
1145 FIXME("info level %d not implemented\n", level );
1146 SetLastError( ERROR_INVALID_PARAMETER );
1147 return INVALID_HANDLE_VALUE;
1150 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, &mask, NULL ))
1152 SetLastError( ERROR_PATH_NOT_FOUND );
1153 return INVALID_HANDLE_VALUE;
1156 if (!mask && (device = RtlIsDosDeviceName_U( filename )))
1158 WCHAR *dir = NULL;
1160 /* we still need to check that the directory can be opened */
1162 if (HIWORD(device))
1164 if (!(dir = HeapAlloc( GetProcessHeap(), 0, HIWORD(device) + sizeof(WCHAR) )))
1166 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1167 goto error;
1169 memcpy( dir, filename, HIWORD(device) );
1170 dir[HIWORD(device)/sizeof(WCHAR)] = 0;
1172 RtlFreeUnicodeString( &nt_name );
1173 if (!RtlDosPathNameToNtPathName_U( dir ? dir : L".", &nt_name, &mask, NULL ))
1175 HeapFree( GetProcessHeap(), 0, dir );
1176 SetLastError( ERROR_PATH_NOT_FOUND );
1177 goto error;
1179 HeapFree( GetProcessHeap(), 0, dir );
1180 size = 0;
1182 else if (!mask || !*mask)
1184 SetLastError( ERROR_FILE_NOT_FOUND );
1185 goto error;
1187 else
1189 nt_name.Length = (mask - nt_name.Buffer) * sizeof(WCHAR);
1190 has_wildcard = wcspbrk( mask, L"*?" ) != NULL;
1191 size = has_wildcard ? 8192 : max_entry_size;
1194 if (!(info = HeapAlloc( GetProcessHeap(), 0, offsetof( FIND_FIRST_INFO, data[size] ))))
1196 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1197 goto error;
1200 /* check if path is the root of the drive, skipping the \??\ prefix */
1201 info->is_root = FALSE;
1202 if (nt_name.Length >= 6 * sizeof(WCHAR) && nt_name.Buffer[5] == ':')
1204 DWORD pos = 6;
1205 while (pos * sizeof(WCHAR) < nt_name.Length && nt_name.Buffer[pos] == '\\') pos++;
1206 info->is_root = (pos * sizeof(WCHAR) >= nt_name.Length);
1209 attr.Length = sizeof(attr);
1210 attr.RootDirectory = 0;
1211 attr.Attributes = OBJ_CASE_INSENSITIVE;
1212 attr.ObjectName = &nt_name;
1213 attr.SecurityDescriptor = NULL;
1214 attr.SecurityQualityOfService = NULL;
1216 status = NtOpenFile( &info->handle, FILE_LIST_DIRECTORY | SYNCHRONIZE, &attr, &io,
1217 FILE_SHARE_READ | FILE_SHARE_WRITE,
1218 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_FOR_BACKUP_INTENT );
1219 if (status != STATUS_SUCCESS)
1221 if (status == STATUS_OBJECT_NAME_NOT_FOUND)
1222 SetLastError( ERROR_PATH_NOT_FOUND );
1223 else
1224 SetLastError( RtlNtStatusToDosError(status) );
1225 goto error;
1228 RtlInitializeCriticalSection( &info->cs );
1229 info->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FIND_FIRST_INFO.cs");
1230 info->path = nt_name;
1231 info->magic = FIND_FIRST_MAGIC;
1232 info->wildcard = has_wildcard;
1233 info->data_pos = 0;
1234 info->data_len = 0;
1235 info->data_size = size;
1236 info->search_op = search_op;
1237 info->level = level;
1239 if (device)
1241 WIN32_FIND_DATAW *wfd = data;
1243 memset( wfd, 0, sizeof(*wfd) );
1244 memcpy( wfd->cFileName, filename + HIWORD(device)/sizeof(WCHAR), LOWORD(device) );
1245 wfd->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1246 CloseHandle( info->handle );
1247 info->handle = 0;
1249 else
1251 UNICODE_STRING mask_str;
1253 RtlInitUnicodeString( &mask_str, mask );
1254 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
1255 FileBothDirectoryInformation, FALSE, &mask_str, TRUE );
1256 if (status)
1258 FindClose( info );
1259 SetLastError( RtlNtStatusToDosError( status ) );
1260 return INVALID_HANDLE_VALUE;
1263 info->data_len = io.Information;
1264 if (!has_wildcard) info->data_size = 0; /* we read everything */
1266 if (!FindNextFileW( info, data ))
1268 TRACE( "%s not found\n", debugstr_w(filename) );
1269 FindClose( info );
1270 SetLastError( ERROR_FILE_NOT_FOUND );
1271 return INVALID_HANDLE_VALUE;
1273 if (!has_wildcard) /* we can't find two files with the same name */
1275 CloseHandle( info->handle );
1276 info->handle = 0;
1279 return info;
1281 error:
1282 HeapFree( GetProcessHeap(), 0, info );
1283 RtlFreeUnicodeString( &nt_name );
1284 return INVALID_HANDLE_VALUE;
1288 /******************************************************************************
1289 * FindFirstFileA (kernelbase.@)
1291 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstFileA( const char *filename, WIN32_FIND_DATAA *data )
1293 return FindFirstFileExA( filename, FindExInfoStandard, data, FindExSearchNameMatch, NULL, 0 );
1297 /******************************************************************************
1298 * FindFirstFileW (kernelbase.@)
1300 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstFileW( const WCHAR *filename, WIN32_FIND_DATAW *data )
1302 return FindFirstFileExW( filename, FindExInfoStandard, data, FindExSearchNameMatch, NULL, 0 );
1306 /**************************************************************************
1307 * FindFirstStreamW (kernelbase.@)
1309 HANDLE WINAPI FindFirstStreamW( const WCHAR *filename, STREAM_INFO_LEVELS level, void *data, DWORD flags )
1311 FIXME("(%s, %d, %p, %lx): stub!\n", debugstr_w(filename), level, data, flags);
1312 SetLastError( ERROR_HANDLE_EOF );
1313 return INVALID_HANDLE_VALUE;
1317 /******************************************************************************
1318 * FindNextFileA (kernelbase.@)
1320 BOOL WINAPI DECLSPEC_HOTPATCH FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1322 WIN32_FIND_DATAW dataW;
1324 if (!FindNextFileW( handle, &dataW )) return FALSE;
1325 data->dwFileAttributes = dataW.dwFileAttributes;
1326 data->ftCreationTime = dataW.ftCreationTime;
1327 data->ftLastAccessTime = dataW.ftLastAccessTime;
1328 data->ftLastWriteTime = dataW.ftLastWriteTime;
1329 data->nFileSizeHigh = dataW.nFileSizeHigh;
1330 data->nFileSizeLow = dataW.nFileSizeLow;
1331 file_name_WtoA( dataW.cFileName, -1, data->cFileName, sizeof(data->cFileName) );
1332 file_name_WtoA( dataW.cAlternateFileName, -1, data->cAlternateFileName,
1333 sizeof(data->cAlternateFileName) );
1334 return TRUE;
1338 /******************************************************************************
1339 * FindNextFileW (kernelbase.@)
1341 BOOL WINAPI DECLSPEC_HOTPATCH FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1343 FIND_FIRST_INFO *info = handle;
1344 FILE_BOTH_DIR_INFORMATION *dir_info;
1345 BOOL ret = FALSE;
1346 NTSTATUS status;
1348 TRACE( "%p %p\n", handle, data );
1350 if (!handle || handle == INVALID_HANDLE_VALUE || info->magic != FIND_FIRST_MAGIC)
1352 SetLastError( ERROR_INVALID_HANDLE );
1353 return ret;
1356 RtlEnterCriticalSection( &info->cs );
1358 if (!info->handle) SetLastError( ERROR_NO_MORE_FILES );
1359 else for (;;)
1361 if (info->data_pos >= info->data_len) /* need to read some more data */
1363 IO_STATUS_BLOCK io;
1365 if (info->data_size)
1366 status = NtQueryDirectoryFile( info->handle, 0, NULL, NULL, &io, info->data, info->data_size,
1367 FileBothDirectoryInformation, FALSE, NULL, FALSE );
1368 else
1369 status = STATUS_NO_MORE_FILES;
1371 if (!set_ntstatus( status ))
1373 if (status == STATUS_NO_MORE_FILES)
1375 CloseHandle( info->handle );
1376 info->handle = 0;
1378 break;
1380 info->data_len = io.Information;
1381 info->data_pos = 0;
1384 dir_info = (FILE_BOTH_DIR_INFORMATION *)(info->data + info->data_pos);
1386 if (dir_info->NextEntryOffset) info->data_pos += dir_info->NextEntryOffset;
1387 else info->data_pos = info->data_len;
1389 /* don't return '.' and '..' in the root of the drive */
1390 if (info->is_root)
1392 if (dir_info->FileNameLength == sizeof(WCHAR) && dir_info->FileName[0] == '.') continue;
1393 if (dir_info->FileNameLength == 2 * sizeof(WCHAR) &&
1394 dir_info->FileName[0] == '.' && dir_info->FileName[1] == '.') continue;
1397 data->dwFileAttributes = dir_info->FileAttributes;
1398 data->ftCreationTime = *(FILETIME *)&dir_info->CreationTime;
1399 data->ftLastAccessTime = *(FILETIME *)&dir_info->LastAccessTime;
1400 data->ftLastWriteTime = *(FILETIME *)&dir_info->LastWriteTime;
1401 data->nFileSizeHigh = dir_info->EndOfFile.QuadPart >> 32;
1402 data->nFileSizeLow = (DWORD)dir_info->EndOfFile.QuadPart;
1403 data->dwReserved0 = 0;
1404 data->dwReserved1 = 0;
1406 memcpy( data->cFileName, dir_info->FileName, dir_info->FileNameLength );
1407 data->cFileName[dir_info->FileNameLength/sizeof(WCHAR)] = 0;
1409 if (info->level != FindExInfoBasic)
1411 memcpy( data->cAlternateFileName, dir_info->ShortName, dir_info->ShortNameLength );
1412 data->cAlternateFileName[dir_info->ShortNameLength/sizeof(WCHAR)] = 0;
1414 else
1415 data->cAlternateFileName[0] = 0;
1417 TRACE( "returning %s (%s)\n",
1418 debugstr_w(data->cFileName), debugstr_w(data->cAlternateFileName) );
1420 ret = TRUE;
1421 break;
1424 RtlLeaveCriticalSection( &info->cs );
1425 return ret;
1429 /**************************************************************************
1430 * FindNextStreamW (kernelbase.@)
1432 BOOL WINAPI FindNextStreamW( HANDLE handle, void *data )
1434 FIXME( "(%p, %p): stub!\n", handle, data );
1435 SetLastError( ERROR_HANDLE_EOF );
1436 return FALSE;
1440 /******************************************************************************
1441 * FindClose (kernelbase.@)
1443 BOOL WINAPI DECLSPEC_HOTPATCH FindClose( HANDLE handle )
1445 FIND_FIRST_INFO *info = handle;
1447 if (!handle || handle == INVALID_HANDLE_VALUE)
1449 SetLastError( ERROR_INVALID_HANDLE );
1450 return FALSE;
1453 __TRY
1455 if (info->magic == FIND_FIRST_MAGIC)
1457 RtlEnterCriticalSection( &info->cs );
1458 if (info->magic == FIND_FIRST_MAGIC) /* in case someone else freed it in the meantime */
1460 info->magic = 0;
1461 if (info->handle) CloseHandle( info->handle );
1462 info->handle = 0;
1463 RtlFreeUnicodeString( &info->path );
1464 info->data_pos = 0;
1465 info->data_len = 0;
1466 RtlLeaveCriticalSection( &info->cs );
1467 info->cs.DebugInfo->Spare[0] = 0;
1468 RtlDeleteCriticalSection( &info->cs );
1469 HeapFree( GetProcessHeap(), 0, info );
1473 __EXCEPT_PAGE_FAULT
1475 WARN( "illegal handle %p\n", handle );
1476 SetLastError( ERROR_INVALID_HANDLE );
1477 return FALSE;
1479 __ENDTRY
1481 return TRUE;
1485 /******************************************************************************
1486 * GetCompressedFileSizeA (kernelbase.@)
1488 DWORD WINAPI DECLSPEC_HOTPATCH GetCompressedFileSizeA( LPCSTR name, LPDWORD size_high )
1490 WCHAR *nameW;
1492 if (!(nameW = file_name_AtoW( name, FALSE ))) return INVALID_FILE_SIZE;
1493 return GetCompressedFileSizeW( nameW, size_high );
1497 /******************************************************************************
1498 * GetCompressedFileSizeW (kernelbase.@)
1500 DWORD WINAPI DECLSPEC_HOTPATCH GetCompressedFileSizeW( LPCWSTR name, LPDWORD size_high )
1502 UNICODE_STRING nt_name;
1503 OBJECT_ATTRIBUTES attr;
1504 IO_STATUS_BLOCK io;
1505 NTSTATUS status;
1506 HANDLE handle;
1507 DWORD ret;
1509 TRACE("%s %p\n", debugstr_w(name), size_high);
1511 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1513 SetLastError( ERROR_PATH_NOT_FOUND );
1514 return INVALID_FILE_SIZE;
1517 attr.Length = sizeof(attr);
1518 attr.RootDirectory = 0;
1519 attr.Attributes = OBJ_CASE_INSENSITIVE;
1520 attr.ObjectName = &nt_name;
1521 attr.SecurityDescriptor = NULL;
1522 attr.SecurityQualityOfService = NULL;
1524 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1525 RtlFreeUnicodeString( &nt_name );
1526 if (!set_ntstatus( status )) return INVALID_FILE_SIZE;
1528 /* we don't support compressed files, simply return the file size */
1529 ret = GetFileSize( handle, size_high );
1530 NtClose( handle );
1531 return ret;
1535 /***********************************************************************
1536 * GetCurrentDirectoryA (kernelbase.@)
1538 UINT WINAPI DECLSPEC_HOTPATCH GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1540 WCHAR bufferW[MAX_PATH];
1541 DWORD ret;
1543 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1545 /* Win9x catches access violations here, returning zero.
1546 * This behaviour resulted in some people not noticing
1547 * that they got the argument order wrong. So let's be
1548 * nice and fail gracefully if buf is invalid and looks
1549 * more like a buflen. */
1550 SetLastError( ERROR_INVALID_PARAMETER );
1551 return 0;
1554 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1555 if (!ret) return 0;
1556 if (ret > sizeof(bufferW))
1558 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1559 return 0;
1561 return copy_filename_WtoA( bufferW, buf, buflen );
1565 /***********************************************************************
1566 * GetCurrentDirectoryW (kernelbase.@)
1568 UINT WINAPI DECLSPEC_HOTPATCH GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1570 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1574 /**************************************************************************
1575 * GetFileAttributesA (kernelbase.@)
1577 DWORD WINAPI DECLSPEC_HOTPATCH GetFileAttributesA( LPCSTR name )
1579 WCHAR *nameW;
1581 if (!(nameW = file_name_AtoW( name, FALSE ))) return INVALID_FILE_ATTRIBUTES;
1582 return GetFileAttributesW( nameW );
1586 /**************************************************************************
1587 * GetFileAttributesW (kernelbase.@)
1589 DWORD WINAPI DECLSPEC_HOTPATCH GetFileAttributesW( LPCWSTR name )
1591 FILE_BASIC_INFORMATION info;
1592 UNICODE_STRING nt_name;
1593 OBJECT_ATTRIBUTES attr;
1594 NTSTATUS status;
1596 TRACE( "%s\n", debugstr_w(name) );
1598 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1600 SetLastError( ERROR_PATH_NOT_FOUND );
1601 return INVALID_FILE_ATTRIBUTES;
1604 attr.Length = sizeof(attr);
1605 attr.RootDirectory = 0;
1606 attr.Attributes = OBJ_CASE_INSENSITIVE;
1607 attr.ObjectName = &nt_name;
1608 attr.SecurityDescriptor = NULL;
1609 attr.SecurityQualityOfService = NULL;
1611 status = NtQueryAttributesFile( &attr, &info );
1612 RtlFreeUnicodeString( &nt_name );
1614 if (status == STATUS_SUCCESS) return info.FileAttributes;
1616 /* NtQueryAttributesFile fails on devices, but GetFileAttributesW succeeds */
1617 if (RtlIsDosDeviceName_U( name )) return FILE_ATTRIBUTE_ARCHIVE;
1619 SetLastError( RtlNtStatusToDosError(status) );
1620 return INVALID_FILE_ATTRIBUTES;
1624 /**************************************************************************
1625 * GetFileAttributesExA (kernelbase.@)
1627 BOOL WINAPI DECLSPEC_HOTPATCH GetFileAttributesExA( LPCSTR name, GET_FILEEX_INFO_LEVELS level, void *ptr )
1629 WCHAR *nameW;
1631 if (!(nameW = file_name_AtoW( name, FALSE ))) return FALSE;
1632 return GetFileAttributesExW( nameW, level, ptr );
1636 /**************************************************************************
1637 * GetFileAttributesExW (kernelbase.@)
1639 BOOL WINAPI DECLSPEC_HOTPATCH GetFileAttributesExW( LPCWSTR name, GET_FILEEX_INFO_LEVELS level, void *ptr )
1641 FILE_NETWORK_OPEN_INFORMATION info;
1642 WIN32_FILE_ATTRIBUTE_DATA *data = ptr;
1643 UNICODE_STRING nt_name;
1644 OBJECT_ATTRIBUTES attr;
1645 NTSTATUS status;
1647 TRACE("%s %d %p\n", debugstr_w(name), level, ptr);
1649 if (level != GetFileExInfoStandard)
1651 SetLastError( ERROR_INVALID_PARAMETER );
1652 return FALSE;
1655 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1657 SetLastError( ERROR_PATH_NOT_FOUND );
1658 return FALSE;
1661 attr.Length = sizeof(attr);
1662 attr.RootDirectory = 0;
1663 attr.Attributes = OBJ_CASE_INSENSITIVE;
1664 attr.ObjectName = &nt_name;
1665 attr.SecurityDescriptor = NULL;
1666 attr.SecurityQualityOfService = NULL;
1668 status = NtQueryFullAttributesFile( &attr, &info );
1669 RtlFreeUnicodeString( &nt_name );
1670 if (!set_ntstatus( status )) return FALSE;
1672 data->dwFileAttributes = info.FileAttributes;
1673 data->ftCreationTime.dwLowDateTime = info.CreationTime.u.LowPart;
1674 data->ftCreationTime.dwHighDateTime = info.CreationTime.u.HighPart;
1675 data->ftLastAccessTime.dwLowDateTime = info.LastAccessTime.u.LowPart;
1676 data->ftLastAccessTime.dwHighDateTime = info.LastAccessTime.u.HighPart;
1677 data->ftLastWriteTime.dwLowDateTime = info.LastWriteTime.u.LowPart;
1678 data->ftLastWriteTime.dwHighDateTime = info.LastWriteTime.u.HighPart;
1679 data->nFileSizeLow = info.EndOfFile.u.LowPart;
1680 data->nFileSizeHigh = info.EndOfFile.u.HighPart;
1681 return TRUE;
1685 /***********************************************************************
1686 * GetFinalPathNameByHandleA (kernelbase.@)
1688 DWORD WINAPI DECLSPEC_HOTPATCH GetFinalPathNameByHandleA( HANDLE file, LPSTR path,
1689 DWORD count, DWORD flags )
1691 WCHAR *str;
1692 DWORD result, len;
1694 TRACE( "(%p,%p,%ld,%lx)\n", file, path, count, flags);
1696 len = GetFinalPathNameByHandleW(file, NULL, 0, flags);
1697 if (len == 0) return 0;
1699 str = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
1700 if (!str)
1702 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1703 return 0;
1706 result = GetFinalPathNameByHandleW(file, str, len, flags);
1707 if (result != len - 1)
1709 HeapFree(GetProcessHeap(), 0, str);
1710 return 0;
1713 len = file_name_WtoA( str, -1, NULL, 0 );
1714 if (count < len)
1716 HeapFree(GetProcessHeap(), 0, str);
1717 return len - 1;
1719 file_name_WtoA( str, -1, path, count );
1720 HeapFree(GetProcessHeap(), 0, str);
1721 return len - 1;
1725 /***********************************************************************
1726 * GetFinalPathNameByHandleW (kernelbase.@)
1728 DWORD WINAPI DECLSPEC_HOTPATCH GetFinalPathNameByHandleW( HANDLE file, LPWSTR path,
1729 DWORD count, DWORD flags )
1731 WCHAR buffer[sizeof(OBJECT_NAME_INFORMATION) + MAX_PATH + 1];
1732 OBJECT_NAME_INFORMATION *info = (OBJECT_NAME_INFORMATION*)&buffer;
1733 WCHAR drive_part[MAX_PATH];
1734 DWORD drive_part_len = 0;
1735 NTSTATUS status;
1736 DWORD result = 0;
1737 ULONG dummy;
1738 WCHAR *ptr;
1740 TRACE( "(%p,%p,%ld,%lx)\n", file, path, count, flags );
1742 if (flags & ~(FILE_NAME_OPENED | VOLUME_NAME_GUID | VOLUME_NAME_NONE | VOLUME_NAME_NT))
1744 WARN("Unknown flags: %lx\n", flags);
1745 SetLastError( ERROR_INVALID_PARAMETER );
1746 return 0;
1749 /* get object name */
1750 status = NtQueryObject( file, ObjectNameInformation, &buffer, sizeof(buffer) - sizeof(WCHAR), &dummy );
1751 if (!set_ntstatus( status )) return 0;
1753 if (!info->Name.Buffer)
1755 SetLastError( ERROR_INVALID_HANDLE );
1756 return 0;
1758 if (info->Name.Length < 4 * sizeof(WCHAR) || info->Name.Buffer[0] != '\\' ||
1759 info->Name.Buffer[1] != '?' || info->Name.Buffer[2] != '?' || info->Name.Buffer[3] != '\\' )
1761 FIXME("Unexpected object name: %s\n", debugstr_wn(info->Name.Buffer, info->Name.Length / sizeof(WCHAR)));
1762 SetLastError( ERROR_GEN_FAILURE );
1763 return 0;
1766 /* add terminating null character, remove "\\??\\" */
1767 info->Name.Buffer[info->Name.Length / sizeof(WCHAR)] = 0;
1768 info->Name.Length -= 4 * sizeof(WCHAR);
1769 info->Name.Buffer += 4;
1771 /* FILE_NAME_OPENED is not supported yet, and would require Wineserver changes */
1772 if (flags & FILE_NAME_OPENED)
1774 FIXME("FILE_NAME_OPENED not supported\n");
1775 flags &= ~FILE_NAME_OPENED;
1778 /* Get information required for VOLUME_NAME_NONE, VOLUME_NAME_GUID and VOLUME_NAME_NT */
1779 if (flags == VOLUME_NAME_NONE || flags == VOLUME_NAME_GUID || flags == VOLUME_NAME_NT)
1781 if (!GetVolumePathNameW( info->Name.Buffer, drive_part, MAX_PATH )) return 0;
1782 drive_part_len = lstrlenW(drive_part);
1783 if (!drive_part_len || drive_part_len > lstrlenW(info->Name.Buffer) ||
1784 drive_part[drive_part_len-1] != '\\' ||
1785 CompareStringOrdinal( info->Name.Buffer, drive_part_len, drive_part, drive_part_len, TRUE ) != CSTR_EQUAL)
1787 FIXME( "Path %s returned by GetVolumePathNameW does not match file path %s\n",
1788 debugstr_w(drive_part), debugstr_w(info->Name.Buffer) );
1789 SetLastError( ERROR_GEN_FAILURE );
1790 return 0;
1794 if (flags == VOLUME_NAME_NONE)
1796 ptr = info->Name.Buffer + drive_part_len - 1;
1797 result = lstrlenW(ptr);
1798 if (result < count) memcpy(path, ptr, (result + 1) * sizeof(WCHAR));
1799 else result++;
1801 else if (flags == VOLUME_NAME_GUID)
1803 WCHAR volume_prefix[51];
1805 /* GetVolumeNameForVolumeMountPointW sets error code on failure */
1806 if (!GetVolumeNameForVolumeMountPointW( drive_part, volume_prefix, 50 )) return 0;
1807 ptr = info->Name.Buffer + drive_part_len;
1808 result = lstrlenW(volume_prefix) + lstrlenW(ptr);
1809 if (result < count)
1811 lstrcpyW(path, volume_prefix);
1812 lstrcatW(path, ptr);
1814 else
1816 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1817 result++;
1820 else if (flags == VOLUME_NAME_NT)
1822 WCHAR nt_prefix[MAX_PATH];
1824 /* QueryDosDeviceW sets error code on failure */
1825 drive_part[drive_part_len - 1] = 0;
1826 if (!QueryDosDeviceW( drive_part, nt_prefix, MAX_PATH )) return 0;
1827 ptr = info->Name.Buffer + drive_part_len - 1;
1828 result = lstrlenW(nt_prefix) + lstrlenW(ptr);
1829 if (result < count)
1831 lstrcpyW(path, nt_prefix);
1832 lstrcatW(path, ptr);
1834 else
1836 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1837 result++;
1840 else if (flags == VOLUME_NAME_DOS)
1842 result = 4 + lstrlenW(info->Name.Buffer);
1843 if (result < count)
1845 lstrcpyW(path, L"\\\\?\\");
1846 lstrcatW(path, info->Name.Buffer);
1848 else
1850 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1851 result++;
1854 else
1856 /* Windows crashes here, but we prefer returning ERROR_INVALID_PARAMETER */
1857 WARN("Invalid combination of flags: %lx\n", flags);
1858 SetLastError( ERROR_INVALID_PARAMETER );
1860 return result;
1864 /***********************************************************************
1865 * GetFullPathNameA (kernelbase.@)
1867 DWORD WINAPI DECLSPEC_HOTPATCH GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer, LPSTR *lastpart )
1869 WCHAR *nameW;
1870 WCHAR bufferW[MAX_PATH], *lastpartW = NULL;
1871 DWORD ret;
1873 if (!(nameW = file_name_AtoW( name, FALSE ))) return 0;
1875 ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, &lastpartW );
1877 if (!ret) return 0;
1878 if (ret > MAX_PATH)
1880 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1881 return 0;
1883 ret = copy_filename_WtoA( bufferW, buffer, len );
1884 if (ret < len && lastpart)
1886 if (lastpartW)
1887 *lastpart = buffer + file_name_WtoA( bufferW, lastpartW - bufferW, NULL, 0 );
1888 else
1889 *lastpart = NULL;
1891 return ret;
1895 /***********************************************************************
1896 * GetFullPathNameW (kernelbase.@)
1898 DWORD WINAPI DECLSPEC_HOTPATCH GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer, LPWSTR *lastpart )
1900 return RtlGetFullPathName_U( name, len * sizeof(WCHAR), buffer, lastpart ) / sizeof(WCHAR);
1904 /***********************************************************************
1905 * GetLongPathNameA (kernelbase.@)
1907 DWORD WINAPI DECLSPEC_HOTPATCH GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
1909 WCHAR *shortpathW;
1910 WCHAR longpathW[MAX_PATH];
1911 DWORD ret;
1913 TRACE( "%s\n", debugstr_a( shortpath ));
1915 if (!(shortpathW = file_name_AtoW( shortpath, FALSE ))) return 0;
1917 ret = GetLongPathNameW( shortpathW, longpathW, MAX_PATH );
1919 if (!ret) return 0;
1920 if (ret > MAX_PATH)
1922 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1923 return 0;
1925 return copy_filename_WtoA( longpathW, longpath, longlen );
1929 /***********************************************************************
1930 * GetLongPathNameW (kernelbase.@)
1932 DWORD WINAPI DECLSPEC_HOTPATCH GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
1934 WCHAR tmplongpath[1024];
1935 DWORD sp = 0, lp = 0, tmplen;
1936 WIN32_FIND_DATAW wfd;
1937 UNICODE_STRING nameW;
1938 LPCWSTR p;
1939 HANDLE handle;
1941 TRACE("%s,%p,%lu\n", debugstr_w(shortpath), longpath, longlen);
1943 if (!shortpath)
1945 SetLastError( ERROR_INVALID_PARAMETER );
1946 return 0;
1948 if (!shortpath[0])
1950 SetLastError( ERROR_PATH_NOT_FOUND );
1951 return 0;
1954 if (shortpath[0] == '\\' && shortpath[1] == '\\')
1956 FIXME( "UNC pathname %s\n", debugstr_w(shortpath) );
1957 tmplen = lstrlenW( shortpath );
1958 if (tmplen < longlen)
1960 if (longpath != shortpath) lstrcpyW( longpath, shortpath );
1961 return tmplen;
1963 return tmplen + 1;
1966 /* check for drive letter */
1967 if (shortpath[0] != '/' && shortpath[1] == ':' )
1969 tmplongpath[0] = shortpath[0];
1970 tmplongpath[1] = ':';
1971 lp = sp = 2;
1974 if (wcspbrk( shortpath + sp, L"*?" ))
1976 SetLastError( ERROR_INVALID_NAME );
1977 return 0;
1980 while (shortpath[sp])
1982 /* check for path delimiters and reproduce them */
1983 if (shortpath[sp] == '\\' || shortpath[sp] == '/')
1985 tmplongpath[lp++] = shortpath[sp++];
1986 tmplongpath[lp] = 0; /* terminate string */
1987 continue;
1990 for (p = shortpath + sp; *p && *p != '/' && *p != '\\'; p++);
1991 tmplen = p - (shortpath + sp);
1992 lstrcpynW( tmplongpath + lp, shortpath + sp, tmplen + 1 );
1994 if (tmplongpath[lp] == '.')
1996 if (tmplen == 1 || (tmplen == 2 && tmplongpath[lp + 1] == '.'))
1998 lp += tmplen;
1999 sp += tmplen;
2000 continue;
2004 /* Check if the file exists */
2005 handle = FindFirstFileW( tmplongpath, &wfd );
2006 if (handle == INVALID_HANDLE_VALUE)
2008 TRACE( "not found %s\n", debugstr_w( tmplongpath ));
2009 SetLastError ( ERROR_FILE_NOT_FOUND );
2010 return 0;
2012 FindClose( handle );
2014 /* Use the existing file name if it's a short name */
2015 RtlInitUnicodeString( &nameW, tmplongpath + lp );
2016 if (RtlIsNameLegalDOS8Dot3( &nameW, NULL, NULL )) lstrcpyW( tmplongpath + lp, wfd.cFileName );
2017 lp += lstrlenW( tmplongpath + lp );
2018 sp += tmplen;
2020 tmplen = lstrlenW( shortpath ) - 1;
2021 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
2022 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
2023 tmplongpath[lp++] = shortpath[tmplen];
2024 tmplongpath[lp] = 0;
2026 tmplen = lstrlenW( tmplongpath ) + 1;
2027 if (tmplen <= longlen)
2029 lstrcpyW( longpath, tmplongpath );
2030 TRACE("returning %s\n", debugstr_w( longpath ));
2031 tmplen--; /* length without 0 */
2033 return tmplen;
2037 /***********************************************************************
2038 * GetShortPathNameW (kernelbase.@)
2040 DWORD WINAPI DECLSPEC_HOTPATCH GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
2042 WIN32_FIND_DATAW wfd;
2043 WCHAR *tmpshortpath;
2044 HANDLE handle;
2045 LPCWSTR p;
2046 DWORD sp = 0, lp = 0, tmplen, buf_len;
2048 TRACE( "%s,%p,%lu\n", debugstr_w(longpath), shortpath, shortlen );
2050 if (!longpath)
2052 SetLastError( ERROR_INVALID_PARAMETER );
2053 return 0;
2055 if (!longpath[0])
2057 SetLastError( ERROR_BAD_PATHNAME );
2058 return 0;
2061 /* code below only removes characters from string, never adds, so this is
2062 * the largest buffer that tmpshortpath will need to have */
2063 buf_len = lstrlenW(longpath) + 1;
2064 tmpshortpath = HeapAlloc( GetProcessHeap(), 0, buf_len * sizeof(WCHAR) );
2065 if (!tmpshortpath)
2067 SetLastError( ERROR_OUTOFMEMORY );
2068 return 0;
2071 if (longpath[0] == '\\' && longpath[1] == '\\' && longpath[2] == '?' && longpath[3] == '\\')
2073 memcpy( tmpshortpath, longpath, 4 * sizeof(WCHAR) );
2074 sp = lp = 4;
2077 if (wcspbrk( longpath + lp, L"*?" ))
2079 HeapFree( GetProcessHeap(), 0, tmpshortpath );
2080 SetLastError( ERROR_INVALID_NAME );
2081 return 0;
2084 /* check for drive letter */
2085 if (longpath[lp] != '/' && longpath[lp + 1] == ':' )
2087 tmpshortpath[sp] = longpath[lp];
2088 tmpshortpath[sp + 1] = ':';
2089 sp += 2;
2090 lp += 2;
2093 while (longpath[lp])
2095 /* check for path delimiters and reproduce them */
2096 if (longpath[lp] == '\\' || longpath[lp] == '/')
2098 tmpshortpath[sp++] = longpath[lp++];
2099 tmpshortpath[sp] = 0; /* terminate string */
2100 continue;
2103 p = longpath + lp;
2104 for (; *p && *p != '/' && *p != '\\'; p++);
2105 tmplen = p - (longpath + lp);
2106 lstrcpynW( tmpshortpath + sp, longpath + lp, tmplen + 1 );
2108 if (tmpshortpath[sp] == '.')
2110 if (tmplen == 1 || (tmplen == 2 && tmpshortpath[sp + 1] == '.'))
2112 sp += tmplen;
2113 lp += tmplen;
2114 continue;
2118 /* Check if the file exists and use the existing short file name */
2119 handle = FindFirstFileW( tmpshortpath, &wfd );
2120 if (handle == INVALID_HANDLE_VALUE) goto notfound;
2121 FindClose( handle );
2123 /* In rare cases (like "a.abcd") short path may be longer than original path.
2124 * Make sure we have enough space in temp buffer. */
2125 if (wfd.cAlternateFileName[0] && tmplen < lstrlenW(wfd.cAlternateFileName))
2127 WCHAR *new_buf;
2128 buf_len += lstrlenW( wfd.cAlternateFileName ) - tmplen;
2129 new_buf = HeapReAlloc( GetProcessHeap(), 0, tmpshortpath, buf_len * sizeof(WCHAR) );
2130 if(!new_buf)
2132 HeapFree( GetProcessHeap(), 0, tmpshortpath );
2133 SetLastError( ERROR_OUTOFMEMORY );
2134 return 0;
2136 tmpshortpath = new_buf;
2139 lstrcpyW( tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName );
2140 sp += lstrlenW( tmpshortpath + sp );
2141 lp += tmplen;
2143 tmpshortpath[sp] = 0;
2145 tmplen = lstrlenW( tmpshortpath ) + 1;
2146 if (tmplen <= shortlen)
2148 lstrcpyW( shortpath, tmpshortpath );
2149 TRACE( "returning %s\n", debugstr_w( shortpath ));
2150 tmplen--; /* length without 0 */
2153 HeapFree( GetProcessHeap(), 0, tmpshortpath );
2154 return tmplen;
2156 notfound:
2157 HeapFree( GetProcessHeap(), 0, tmpshortpath );
2158 TRACE( "not found\n" );
2159 SetLastError( ERROR_FILE_NOT_FOUND );
2160 return 0;
2164 /***********************************************************************
2165 * GetSystemDirectoryA (kernelbase.@)
2167 UINT WINAPI DECLSPEC_HOTPATCH GetSystemDirectoryA( LPSTR path, UINT count )
2169 return copy_filename_WtoA( system_dir, path, count );
2173 /***********************************************************************
2174 * GetSystemDirectoryW (kernelbase.@)
2176 UINT WINAPI DECLSPEC_HOTPATCH GetSystemDirectoryW( LPWSTR path, UINT count )
2178 return copy_filename( system_dir, path, count );
2182 /***********************************************************************
2183 * GetSystemWindowsDirectoryA (kernelbase.@)
2185 UINT WINAPI DECLSPEC_HOTPATCH GetSystemWindowsDirectoryA( LPSTR path, UINT count )
2187 return GetWindowsDirectoryA( path, count );
2191 /***********************************************************************
2192 * GetSystemWindowsDirectoryW (kernelbase.@)
2194 UINT WINAPI DECLSPEC_HOTPATCH GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
2196 return GetWindowsDirectoryW( path, count );
2200 /***********************************************************************
2201 * GetSystemWow64DirectoryA (kernelbase.@)
2203 UINT WINAPI /* DECLSPEC_HOTPATCH */ GetSystemWow64DirectoryA( LPSTR path, UINT count )
2205 if (!is_win64 && !is_wow64)
2207 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
2208 return 0;
2210 return copy_filename_WtoA( get_machine_wow64_dir( IMAGE_FILE_MACHINE_I386 ), path, count );
2214 /***********************************************************************
2215 * GetSystemWow64DirectoryW (kernelbase.@)
2217 UINT WINAPI /* DECLSPEC_HOTPATCH */ GetSystemWow64DirectoryW( LPWSTR path, UINT count )
2219 if (!is_win64 && !is_wow64)
2221 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
2222 return 0;
2224 return copy_filename( get_machine_wow64_dir( IMAGE_FILE_MACHINE_I386 ), path, count );
2228 /***********************************************************************
2229 * GetSystemWow64Directory2A (kernelbase.@)
2231 UINT WINAPI DECLSPEC_HOTPATCH GetSystemWow64Directory2A( LPSTR path, UINT count, WORD machine )
2233 const WCHAR *dir = get_machine_wow64_dir( machine );
2235 return dir ? copy_filename_WtoA( dir, path, count ) : 0;
2239 /***********************************************************************
2240 * GetSystemWow64Directory2W (kernelbase.@)
2242 UINT WINAPI DECLSPEC_HOTPATCH GetSystemWow64Directory2W( LPWSTR path, UINT count, WORD machine )
2244 const WCHAR *dir = get_machine_wow64_dir( machine );
2246 return dir ? copy_filename( dir, path, count ) : 0;
2250 /***********************************************************************
2251 * GetTempFileNameA (kernelbase.@)
2253 UINT WINAPI DECLSPEC_HOTPATCH GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer )
2255 WCHAR *pathW, *prefixW = NULL;
2256 WCHAR bufferW[MAX_PATH];
2257 UINT ret;
2259 if (!(pathW = file_name_AtoW( path, FALSE ))) return 0;
2260 if (prefix && !(prefixW = file_name_AtoW( prefix, TRUE ))) return 0;
2262 ret = GetTempFileNameW( pathW, prefixW, unique, bufferW );
2263 if (ret) file_name_WtoA( bufferW, -1, buffer, MAX_PATH );
2265 HeapFree( GetProcessHeap(), 0, prefixW );
2266 return ret;
2270 /***********************************************************************
2271 * GetTempFileNameW (kernelbase.@)
2273 UINT WINAPI DECLSPEC_HOTPATCH GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
2275 int i;
2276 LPWSTR p;
2277 DWORD attr;
2279 if (!path || !buffer)
2281 SetLastError( ERROR_INVALID_PARAMETER );
2282 return 0;
2285 /* ensure that the provided directory exists */
2286 attr = GetFileAttributesW( path );
2287 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
2289 TRACE( "path not found %s\n", debugstr_w( path ));
2290 SetLastError( ERROR_DIRECTORY );
2291 return 0;
2294 lstrcpyW( buffer, path );
2295 p = buffer + lstrlenW(buffer);
2297 /* add a \, if there isn't one */
2298 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
2300 if (prefix) for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
2302 unique &= 0xffff;
2303 if (unique) swprintf( p, MAX_PATH - (p - buffer), L"%x.tmp", unique );
2304 else
2306 /* get a "random" unique number and try to create the file */
2307 HANDLE handle;
2308 UINT num = NtGetTickCount() & 0xffff;
2309 static UINT last;
2311 /* avoid using the same name twice in a short interval */
2312 if (last - num < 10) num = last + 1;
2313 if (!num) num = 1;
2314 unique = num;
2317 swprintf( p, MAX_PATH - (p - buffer), L"%x.tmp", unique );
2318 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
2319 if (handle != INVALID_HANDLE_VALUE)
2320 { /* We created it */
2321 CloseHandle( handle );
2322 last = unique;
2323 break;
2325 if (GetLastError() != ERROR_FILE_EXISTS && GetLastError() != ERROR_SHARING_VIOLATION)
2326 break; /* No need to go on */
2327 if (!(++unique & 0xffff)) unique = 1;
2328 } while (unique != num);
2330 TRACE( "returning %s\n", debugstr_w( buffer ));
2331 return unique;
2335 /***********************************************************************
2336 * GetTempPathA (kernelbase.@)
2338 DWORD WINAPI DECLSPEC_HOTPATCH GetTempPathA( DWORD count, LPSTR path )
2340 WCHAR pathW[MAX_PATH];
2341 UINT ret;
2343 if (!(ret = GetTempPathW( MAX_PATH, pathW ))) return 0;
2344 if (ret > MAX_PATH)
2346 SetLastError( ERROR_FILENAME_EXCED_RANGE );
2347 return 0;
2349 return copy_filename_WtoA( pathW, path, count );
2353 /***********************************************************************
2354 * GetTempPathW (kernelbase.@)
2356 DWORD WINAPI DECLSPEC_HOTPATCH GetTempPathW( DWORD count, LPWSTR path )
2358 WCHAR tmp_path[MAX_PATH];
2359 UINT ret;
2361 if (!(ret = GetEnvironmentVariableW( L"TMP", tmp_path, MAX_PATH )) &&
2362 !(ret = GetEnvironmentVariableW( L"TEMP", tmp_path, MAX_PATH )) &&
2363 !(ret = GetEnvironmentVariableW( L"USERPROFILE", tmp_path, MAX_PATH )) &&
2364 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
2365 return 0;
2367 if (ret > MAX_PATH)
2369 SetLastError( ERROR_FILENAME_EXCED_RANGE );
2370 return 0;
2372 ret = GetFullPathNameW( tmp_path, MAX_PATH, tmp_path, NULL );
2373 if (!ret) return 0;
2375 if (ret > MAX_PATH - 2)
2377 SetLastError( ERROR_FILENAME_EXCED_RANGE );
2378 return 0;
2380 if (tmp_path[ret-1] != '\\')
2382 tmp_path[ret++] = '\\';
2383 tmp_path[ret] = '\0';
2386 ret++; /* add space for terminating 0 */
2387 if (count >= ret)
2389 lstrcpynW( path, tmp_path, count );
2390 /* the remaining buffer must be zeroed up to 32766 bytes in XP or 32767
2391 * bytes after it, we will assume the > XP behavior for now */
2392 memset( path + ret, 0, (min(count, 32767) - ret) * sizeof(WCHAR) );
2393 ret--; /* return length without 0 */
2395 else if (count)
2397 /* the buffer must be cleared if contents will not fit */
2398 memset( path, 0, count * sizeof(WCHAR) );
2401 TRACE( "returning %u, %s\n", ret, debugstr_w( path ));
2402 return ret;
2406 /***********************************************************************
2407 * GetWindowsDirectoryA (kernelbase.@)
2409 UINT WINAPI DECLSPEC_HOTPATCH GetWindowsDirectoryA( LPSTR path, UINT count )
2411 return copy_filename_WtoA( windows_dir, path, count );
2415 /***********************************************************************
2416 * GetWindowsDirectoryW (kernelbase.@)
2418 UINT WINAPI DECLSPEC_HOTPATCH GetWindowsDirectoryW( LPWSTR path, UINT count )
2420 return copy_filename( windows_dir, path, count );
2424 /**************************************************************************
2425 * MoveFileExW (kernelbase.@)
2427 BOOL WINAPI MoveFileExW( const WCHAR *source, const WCHAR *dest, DWORD flag )
2429 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
2433 /**************************************************************************
2434 * MoveFileWithProgressW (kernelbase.@)
2436 BOOL WINAPI DECLSPEC_HOTPATCH MoveFileWithProgressW( const WCHAR *source, const WCHAR *dest,
2437 LPPROGRESS_ROUTINE progress,
2438 void *param, DWORD flag )
2440 FILE_RENAME_INFORMATION *rename_info;
2441 FILE_BASIC_INFORMATION info;
2442 UNICODE_STRING nt_name;
2443 OBJECT_ATTRIBUTES attr;
2444 IO_STATUS_BLOCK io;
2445 NTSTATUS status;
2446 HANDLE source_handle = 0;
2447 ULONG size;
2449 TRACE( "(%s,%s,%p,%p,%04lx)\n", debugstr_w(source), debugstr_w(dest), progress, param, flag );
2451 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT) return add_boot_rename_entry( source, dest, flag );
2453 if (!dest) return DeleteFileW( source );
2455 /* check if we are allowed to rename the source */
2457 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
2459 SetLastError( ERROR_PATH_NOT_FOUND );
2460 return FALSE;
2462 attr.Length = sizeof(attr);
2463 attr.RootDirectory = 0;
2464 attr.Attributes = OBJ_CASE_INSENSITIVE;
2465 attr.ObjectName = &nt_name;
2466 attr.SecurityDescriptor = NULL;
2467 attr.SecurityQualityOfService = NULL;
2469 status = NtOpenFile( &source_handle, DELETE | SYNCHRONIZE, &attr, &io,
2470 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
2471 FILE_SYNCHRONOUS_IO_NONALERT );
2472 RtlFreeUnicodeString( &nt_name );
2473 if (!set_ntstatus( status )) goto error;
2475 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
2476 if (!set_ntstatus( status )) goto error;
2478 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
2480 SetLastError( ERROR_PATH_NOT_FOUND );
2481 goto error;
2484 size = offsetof( FILE_RENAME_INFORMATION, FileName ) + nt_name.Length;
2485 if (!(rename_info = HeapAlloc( GetProcessHeap(), 0, size ))) goto error;
2487 rename_info->ReplaceIfExists = !!(flag & MOVEFILE_REPLACE_EXISTING);
2488 rename_info->RootDirectory = NULL;
2489 rename_info->FileNameLength = nt_name.Length;
2490 memcpy( rename_info->FileName, nt_name.Buffer, nt_name.Length );
2491 RtlFreeUnicodeString( &nt_name );
2492 status = NtSetInformationFile( source_handle, &io, rename_info, size, FileRenameInformation );
2493 HeapFree( GetProcessHeap(), 0, rename_info );
2494 if (status == STATUS_NOT_SAME_DEVICE && (flag & MOVEFILE_COPY_ALLOWED))
2496 NtClose( source_handle );
2497 if (!CopyFileExW( source, dest, progress, param, NULL,
2498 flag & MOVEFILE_REPLACE_EXISTING ? 0 : COPY_FILE_FAIL_IF_EXISTS ))
2499 return FALSE;
2500 return DeleteFileW( source );
2503 NtClose( source_handle );
2504 return set_ntstatus( status );
2506 error:
2507 if (source_handle) NtClose( source_handle );
2508 return FALSE;
2512 /***********************************************************************
2513 * NeedCurrentDirectoryForExePathA (kernelbase.@)
2515 BOOL WINAPI DECLSPEC_HOTPATCH NeedCurrentDirectoryForExePathA( LPCSTR name )
2517 WCHAR *nameW;
2519 if (!(nameW = file_name_AtoW( name, FALSE ))) return TRUE;
2520 return NeedCurrentDirectoryForExePathW( nameW );
2524 /***********************************************************************
2525 * NeedCurrentDirectoryForExePathW (kernelbase.@)
2527 BOOL WINAPI DECLSPEC_HOTPATCH NeedCurrentDirectoryForExePathW( LPCWSTR name )
2529 WCHAR env_val;
2531 if (wcschr( name, '\\' )) return TRUE;
2532 /* check the existence of the variable, not value */
2533 return !GetEnvironmentVariableW( L"NoDefaultCurrentDirectoryInExePath", &env_val, 1 );
2537 /***********************************************************************
2538 * ReplaceFileW (kernelbase.@)
2540 BOOL WINAPI DECLSPEC_HOTPATCH ReplaceFileW( const WCHAR *replaced, const WCHAR *replacement,
2541 const WCHAR *backup, DWORD flags,
2542 void *exclude, void *reserved )
2544 UNICODE_STRING nt_replaced_name, nt_replacement_name;
2545 HANDLE hReplacement = NULL;
2546 NTSTATUS status;
2547 IO_STATUS_BLOCK io;
2548 OBJECT_ATTRIBUTES attr;
2549 FILE_BASIC_INFORMATION info;
2551 TRACE( "%s %s %s 0x%08lx %p %p\n", debugstr_w(replaced), debugstr_w(replacement), debugstr_w(backup),
2552 flags, exclude, reserved );
2554 if (flags) FIXME("Ignoring flags %lx\n", flags);
2556 /* First two arguments are mandatory */
2557 if (!replaced || !replacement)
2559 SetLastError(ERROR_INVALID_PARAMETER);
2560 return FALSE;
2563 attr.Length = sizeof(attr);
2564 attr.RootDirectory = 0;
2565 attr.Attributes = OBJ_CASE_INSENSITIVE;
2566 attr.ObjectName = NULL;
2567 attr.SecurityDescriptor = NULL;
2568 attr.SecurityQualityOfService = NULL;
2570 /* Open the "replaced" file for reading */
2571 if (!RtlDosPathNameToNtPathName_U( replaced, &nt_replaced_name, NULL, NULL ))
2573 SetLastError( ERROR_PATH_NOT_FOUND );
2574 return FALSE;
2576 attr.ObjectName = &nt_replaced_name;
2578 /* Replacement should fail if replaced is READ_ONLY */
2579 status = NtQueryAttributesFile(&attr, &info);
2580 RtlFreeUnicodeString(&nt_replaced_name);
2581 if (!set_ntstatus( status )) return FALSE;
2583 if (info.FileAttributes & FILE_ATTRIBUTE_READONLY)
2585 SetLastError( ERROR_ACCESS_DENIED );
2586 return FALSE;
2590 * Open the replacement file for reading, writing, and deleting
2591 * (writing and deleting are needed when finished)
2593 if (!RtlDosPathNameToNtPathName_U( replacement, &nt_replacement_name, NULL, NULL ))
2595 SetLastError( ERROR_PATH_NOT_FOUND );
2596 return FALSE;
2598 attr.ObjectName = &nt_replacement_name;
2599 status = NtOpenFile( &hReplacement, GENERIC_READ | GENERIC_WRITE | DELETE | WRITE_DAC | SYNCHRONIZE,
2600 &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE );
2601 RtlFreeUnicodeString(&nt_replacement_name);
2602 if (!set_ntstatus( status )) return FALSE;
2603 NtClose( hReplacement );
2605 /* If the user wants a backup then that needs to be performed first */
2606 if (backup)
2608 if (!MoveFileExW( replaced, backup, MOVEFILE_REPLACE_EXISTING )) return FALSE;
2610 else
2612 /* ReplaceFile() can replace an open target. To do this, we need to move
2613 * it out of the way first. */
2614 WCHAR temp_path[MAX_PATH], temp_file[MAX_PATH];
2616 lstrcpynW( temp_path, replaced, ARRAY_SIZE( temp_path ) );
2617 PathRemoveFileSpecW( temp_path );
2618 if (!GetTempFileNameW( temp_path, L"rf", 0, temp_file ) ||
2619 !MoveFileExW( replaced, temp_file, MOVEFILE_REPLACE_EXISTING ))
2620 return FALSE;
2622 DeleteFileW( temp_file );
2626 * Now that the backup has been performed (if requested), copy the replacement
2627 * into place
2629 if (!MoveFileExW( replacement, replaced, 0 ))
2631 /* on failure we need to indicate whether a backup was made */
2632 if (!backup)
2633 SetLastError( ERROR_UNABLE_TO_MOVE_REPLACEMENT );
2634 else
2635 SetLastError( ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 );
2636 return FALSE;
2638 return TRUE;
2642 /***********************************************************************
2643 * SearchPathA (kernelbase.@)
2645 DWORD WINAPI DECLSPEC_HOTPATCH SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
2646 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
2648 WCHAR *pathW = NULL, *nameW, *extW = NULL;
2649 WCHAR bufferW[MAX_PATH];
2650 DWORD ret;
2652 if (!name)
2654 SetLastError( ERROR_INVALID_PARAMETER );
2655 return 0;
2658 if (!(nameW = file_name_AtoW( name, FALSE ))) return 0;
2659 if (path && !(pathW = file_name_AtoW( path, TRUE ))) return 0;
2660 if (ext && !(extW = file_name_AtoW( ext, TRUE )))
2662 RtlFreeHeap( GetProcessHeap(), 0, pathW );
2663 return 0;
2666 ret = SearchPathW( pathW, nameW, extW, MAX_PATH, bufferW, NULL );
2668 RtlFreeHeap( GetProcessHeap(), 0, pathW );
2669 RtlFreeHeap( GetProcessHeap(), 0, extW );
2671 if (!ret) return 0;
2672 if (ret > MAX_PATH)
2674 SetLastError( ERROR_FILENAME_EXCED_RANGE );
2675 return 0;
2677 ret = copy_filename_WtoA( bufferW, buffer, buflen );
2678 if (buflen > ret && lastpart) *lastpart = strrchr(buffer, '\\') + 1;
2679 return ret;
2683 /***********************************************************************
2684 * SearchPathW (kernelbase.@)
2686 DWORD WINAPI DECLSPEC_HOTPATCH SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
2687 LPWSTR buffer, LPWSTR *lastpart )
2689 DWORD ret = 0;
2690 WCHAR *name_ext;
2692 if (!name || !name[0])
2694 SetLastError( ERROR_INVALID_PARAMETER );
2695 return 0;
2698 /* If the name contains an explicit path, ignore the path */
2700 if (contains_path( name ))
2702 /* try first without extension */
2703 if (RtlDoesFileExists_U( name )) return GetFullPathNameW( name, buflen, buffer, lastpart );
2705 if ((name_ext = append_ext( name, ext )))
2707 if (RtlDoesFileExists_U( name_ext ))
2708 ret = GetFullPathNameW( name_ext, buflen, buffer, lastpart );
2709 RtlFreeHeap( GetProcessHeap(), 0, name_ext );
2712 else if (path && path[0]) /* search in the specified path */
2714 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
2715 buffer, lastpart ) / sizeof(WCHAR);
2717 else /* search in active context and default path */
2719 WCHAR *dll_path = NULL, *name_ext = append_ext( name, ext );
2721 if (name_ext) name = name_ext;
2723 /* When file is found with activation context no attempt is made
2724 to check if it's really exist, path is returned only basing on context info. */
2725 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
2727 ret = lstrlenW( dll_path ) + lstrlenW( name ) + 1;
2729 /* count null termination char too */
2730 if (ret <= buflen)
2732 lstrcpyW( buffer, dll_path );
2733 lstrcatW( buffer, name );
2734 if (lastpart) *lastpart = buffer + lstrlenW( dll_path );
2735 ret--;
2737 else if (lastpart) *lastpart = NULL;
2738 RtlFreeHeap( GetProcessHeap(), 0, dll_path );
2740 else if (!RtlGetSearchPath( &dll_path ))
2742 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
2743 buffer, lastpart ) / sizeof(WCHAR);
2744 RtlReleasePath( dll_path );
2746 RtlFreeHeap( GetProcessHeap(), 0, name_ext );
2749 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
2750 else TRACE( "found %s\n", debugstr_w(buffer) );
2751 return ret;
2755 /***********************************************************************
2756 * SetCurrentDirectoryA (kernelbase.@)
2758 BOOL WINAPI DECLSPEC_HOTPATCH SetCurrentDirectoryA( LPCSTR dir )
2760 WCHAR *dirW;
2761 UNICODE_STRING strW;
2763 if (!(dirW = file_name_AtoW( dir, FALSE ))) return FALSE;
2764 RtlInitUnicodeString( &strW, dirW );
2765 return set_ntstatus( RtlSetCurrentDirectory_U( &strW ));
2769 /***********************************************************************
2770 * SetCurrentDirectoryW (kernelbase.@)
2772 BOOL WINAPI DECLSPEC_HOTPATCH SetCurrentDirectoryW( LPCWSTR dir )
2774 UNICODE_STRING dirW;
2776 RtlInitUnicodeString( &dirW, dir );
2777 return set_ntstatus( RtlSetCurrentDirectory_U( &dirW ));
2781 /**************************************************************************
2782 * SetFileApisToANSI (kernelbase.@)
2784 void WINAPI DECLSPEC_HOTPATCH SetFileApisToANSI(void)
2786 oem_file_apis = FALSE;
2790 /**************************************************************************
2791 * SetFileApisToOEM (kernelbase.@)
2793 void WINAPI DECLSPEC_HOTPATCH SetFileApisToOEM(void)
2795 oem_file_apis = TRUE;
2799 /**************************************************************************
2800 * SetFileAttributesA (kernelbase.@)
2802 BOOL WINAPI DECLSPEC_HOTPATCH SetFileAttributesA( LPCSTR name, DWORD attributes )
2804 WCHAR *nameW;
2806 if (!(nameW = file_name_AtoW( name, FALSE ))) return FALSE;
2807 return SetFileAttributesW( nameW, attributes );
2811 /**************************************************************************
2812 * SetFileAttributesW (kernelbase.@)
2814 BOOL WINAPI DECLSPEC_HOTPATCH SetFileAttributesW( LPCWSTR name, DWORD attributes )
2816 UNICODE_STRING nt_name;
2817 OBJECT_ATTRIBUTES attr;
2818 IO_STATUS_BLOCK io;
2819 NTSTATUS status;
2820 HANDLE handle;
2822 TRACE( "%s %lx\n", debugstr_w(name), attributes );
2824 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
2826 SetLastError( ERROR_PATH_NOT_FOUND );
2827 return FALSE;
2830 attr.Length = sizeof(attr);
2831 attr.RootDirectory = 0;
2832 attr.Attributes = OBJ_CASE_INSENSITIVE;
2833 attr.ObjectName = &nt_name;
2834 attr.SecurityDescriptor = NULL;
2835 attr.SecurityQualityOfService = NULL;
2837 status = NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
2838 RtlFreeUnicodeString( &nt_name );
2840 if (status == STATUS_SUCCESS)
2842 FILE_BASIC_INFORMATION info;
2844 memset( &info, 0, sizeof(info) );
2845 info.FileAttributes = attributes | FILE_ATTRIBUTE_NORMAL; /* make sure it's not zero */
2846 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileBasicInformation );
2847 NtClose( handle );
2849 return set_ntstatus( status );
2853 /***********************************************************************
2854 * Wow64DisableWow64FsRedirection (kernelbase.@)
2856 BOOL WINAPI DECLSPEC_HOTPATCH Wow64DisableWow64FsRedirection( PVOID *old_value )
2858 return set_ntstatus( RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value ));
2862 /***********************************************************************
2863 * Wow64RevertWow64FsRedirection (kernelbase.@)
2865 BOOL WINAPI DECLSPEC_HOTPATCH Wow64RevertWow64FsRedirection( PVOID old_value )
2867 return set_ntstatus( RtlWow64EnableFsRedirection( !old_value ));
2871 /***********************************************************************
2872 * Operations on file handles
2873 ***********************************************************************/
2876 /***********************************************************************
2877 * CancelIo (kernelbase.@)
2879 BOOL WINAPI DECLSPEC_HOTPATCH CancelIo( HANDLE handle )
2881 IO_STATUS_BLOCK io;
2883 return set_ntstatus( NtCancelIoFile( handle, &io ) );
2887 /***********************************************************************
2888 * CancelIoEx (kernelbase.@)
2890 BOOL WINAPI DECLSPEC_HOTPATCH CancelIoEx( HANDLE handle, LPOVERLAPPED overlapped )
2892 IO_STATUS_BLOCK io;
2894 return set_ntstatus( NtCancelIoFileEx( handle, (PIO_STATUS_BLOCK)overlapped, &io ) );
2898 /***********************************************************************
2899 * CancelSynchronousIo (kernelbase.@)
2901 BOOL WINAPI DECLSPEC_HOTPATCH CancelSynchronousIo( HANDLE thread )
2903 IO_STATUS_BLOCK io;
2905 return set_ntstatus( NtCancelSynchronousIoFile( thread, NULL, &io ));
2909 /***********************************************************************
2910 * FlushFileBuffers (kernelbase.@)
2912 BOOL WINAPI DECLSPEC_HOTPATCH FlushFileBuffers( HANDLE file )
2914 IO_STATUS_BLOCK iosb;
2916 return set_ntstatus( NtFlushBuffersFile( file, &iosb ));
2920 /***********************************************************************
2921 * GetFileInformationByHandle (kernelbase.@)
2923 BOOL WINAPI DECLSPEC_HOTPATCH GetFileInformationByHandle( HANDLE file, BY_HANDLE_FILE_INFORMATION *info )
2925 FILE_FS_VOLUME_INFORMATION volume_info;
2926 FILE_ALL_INFORMATION all_info;
2927 IO_STATUS_BLOCK io;
2928 NTSTATUS status;
2930 status = NtQueryInformationFile( file, &io, &all_info, sizeof(all_info), FileAllInformation );
2931 if (status == STATUS_BUFFER_OVERFLOW) status = STATUS_SUCCESS;
2932 if (!set_ntstatus( status )) return FALSE;
2934 info->dwFileAttributes = all_info.BasicInformation.FileAttributes;
2935 info->ftCreationTime.dwHighDateTime = all_info.BasicInformation.CreationTime.u.HighPart;
2936 info->ftCreationTime.dwLowDateTime = all_info.BasicInformation.CreationTime.u.LowPart;
2937 info->ftLastAccessTime.dwHighDateTime = all_info.BasicInformation.LastAccessTime.u.HighPart;
2938 info->ftLastAccessTime.dwLowDateTime = all_info.BasicInformation.LastAccessTime.u.LowPart;
2939 info->ftLastWriteTime.dwHighDateTime = all_info.BasicInformation.LastWriteTime.u.HighPart;
2940 info->ftLastWriteTime.dwLowDateTime = all_info.BasicInformation.LastWriteTime.u.LowPart;
2941 info->dwVolumeSerialNumber = 0;
2942 info->nFileSizeHigh = all_info.StandardInformation.EndOfFile.u.HighPart;
2943 info->nFileSizeLow = all_info.StandardInformation.EndOfFile.u.LowPart;
2944 info->nNumberOfLinks = all_info.StandardInformation.NumberOfLinks;
2945 info->nFileIndexHigh = all_info.InternalInformation.IndexNumber.u.HighPart;
2946 info->nFileIndexLow = all_info.InternalInformation.IndexNumber.u.LowPart;
2948 status = NtQueryVolumeInformationFile( file, &io, &volume_info, sizeof(volume_info), FileFsVolumeInformation );
2949 if (status == STATUS_SUCCESS || status == STATUS_BUFFER_OVERFLOW)
2950 info->dwVolumeSerialNumber = volume_info.VolumeSerialNumber;
2952 return TRUE;
2956 /***********************************************************************
2957 * GetFileInformationByHandleEx (kernelbase.@)
2959 BOOL WINAPI DECLSPEC_HOTPATCH GetFileInformationByHandleEx( HANDLE handle, FILE_INFO_BY_HANDLE_CLASS class,
2960 LPVOID info, DWORD size )
2962 NTSTATUS status;
2963 IO_STATUS_BLOCK io;
2965 switch (class)
2967 case FileRemoteProtocolInfo:
2968 case FileStorageInfo:
2969 case FileDispositionInfoEx:
2970 case FileRenameInfoEx:
2971 case FileCaseSensitiveInfo:
2972 case FileNormalizedNameInfo:
2973 FIXME( "%p, %u, %p, %lu\n", handle, class, info, size );
2974 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
2975 return FALSE;
2977 case FileStreamInfo:
2978 status = NtQueryInformationFile( handle, &io, info, size, FileStreamInformation );
2979 break;
2981 case FileCompressionInfo:
2982 status = NtQueryInformationFile( handle, &io, info, size, FileCompressionInformation );
2983 break;
2985 case FileAlignmentInfo:
2986 status = NtQueryInformationFile( handle, &io, info, size, FileAlignmentInformation );
2987 break;
2989 case FileAttributeTagInfo:
2990 status = NtQueryInformationFile( handle, &io, info, size, FileAttributeTagInformation );
2991 break;
2993 case FileBasicInfo:
2994 status = NtQueryInformationFile( handle, &io, info, size, FileBasicInformation );
2995 break;
2997 case FileStandardInfo:
2998 status = NtQueryInformationFile( handle, &io, info, size, FileStandardInformation );
2999 break;
3001 case FileNameInfo:
3002 status = NtQueryInformationFile( handle, &io, info, size, FileNameInformation );
3003 break;
3005 case FileIdInfo:
3006 status = NtQueryInformationFile( handle, &io, info, size, FileIdInformation );
3007 break;
3009 case FileIdBothDirectoryRestartInfo:
3010 case FileIdBothDirectoryInfo:
3011 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
3012 FileIdBothDirectoryInformation, FALSE, NULL,
3013 (class == FileIdBothDirectoryRestartInfo) );
3014 break;
3016 case FileFullDirectoryInfo:
3017 case FileFullDirectoryRestartInfo:
3018 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
3019 FileFullDirectoryInformation, FALSE, NULL,
3020 (class == FileFullDirectoryRestartInfo) );
3021 break;
3023 case FileIdExtdDirectoryInfo:
3024 case FileIdExtdDirectoryRestartInfo:
3025 status = NtQueryDirectoryFile( handle, NULL, NULL, NULL, &io, info, size,
3026 FileIdExtdDirectoryInformation, FALSE, NULL,
3027 (class == FileIdExtdDirectoryRestartInfo) );
3028 break;
3030 case FileRenameInfo:
3031 case FileDispositionInfo:
3032 case FileAllocationInfo:
3033 case FileIoPriorityHintInfo:
3034 case FileEndOfFileInfo:
3035 default:
3036 SetLastError( ERROR_INVALID_PARAMETER );
3037 return FALSE;
3039 return set_ntstatus( status );
3043 /***********************************************************************
3044 * GetFileSize (kernelbase.@)
3046 DWORD WINAPI DECLSPEC_HOTPATCH GetFileSize( HANDLE file, LPDWORD size_high )
3048 LARGE_INTEGER size;
3050 if (!GetFileSizeEx( file, &size )) return INVALID_FILE_SIZE;
3051 if (size_high) *size_high = size.u.HighPart;
3052 if (size.u.LowPart == INVALID_FILE_SIZE) SetLastError( 0 );
3053 return size.u.LowPart;
3057 /***********************************************************************
3058 * GetFileSizeEx (kernelbase.@)
3060 BOOL WINAPI DECLSPEC_HOTPATCH GetFileSizeEx( HANDLE file, PLARGE_INTEGER size )
3062 FILE_STANDARD_INFORMATION info;
3063 IO_STATUS_BLOCK io;
3065 if (!set_ntstatus( NtQueryInformationFile( file, &io, &info, sizeof(info), FileStandardInformation )))
3066 return FALSE;
3068 *size = info.EndOfFile;
3069 return TRUE;
3073 /***********************************************************************
3074 * GetFileTime (kernelbase.@)
3076 BOOL WINAPI DECLSPEC_HOTPATCH GetFileTime( HANDLE file, FILETIME *creation,
3077 FILETIME *access, FILETIME *write )
3079 FILE_BASIC_INFORMATION info;
3080 IO_STATUS_BLOCK io;
3082 if (!set_ntstatus( NtQueryInformationFile( file, &io, &info, sizeof(info), FileBasicInformation )))
3083 return FALSE;
3085 if (creation)
3087 creation->dwHighDateTime = info.CreationTime.u.HighPart;
3088 creation->dwLowDateTime = info.CreationTime.u.LowPart;
3090 if (access)
3092 access->dwHighDateTime = info.LastAccessTime.u.HighPart;
3093 access->dwLowDateTime = info.LastAccessTime.u.LowPart;
3095 if (write)
3097 write->dwHighDateTime = info.LastWriteTime.u.HighPart;
3098 write->dwLowDateTime = info.LastWriteTime.u.LowPart;
3100 return TRUE;
3104 /***********************************************************************
3105 * GetFileType (kernelbase.@)
3107 DWORD WINAPI DECLSPEC_HOTPATCH GetFileType( HANDLE file )
3109 FILE_FS_DEVICE_INFORMATION info;
3110 IO_STATUS_BLOCK io;
3112 if (file == (HANDLE)STD_INPUT_HANDLE ||
3113 file == (HANDLE)STD_OUTPUT_HANDLE ||
3114 file == (HANDLE)STD_ERROR_HANDLE)
3115 file = GetStdHandle( (DWORD_PTR)file );
3117 if (!set_ntstatus( NtQueryVolumeInformationFile( file, &io, &info, sizeof(info),
3118 FileFsDeviceInformation )))
3119 return FILE_TYPE_UNKNOWN;
3121 switch (info.DeviceType)
3123 case FILE_DEVICE_NULL:
3124 case FILE_DEVICE_CONSOLE:
3125 case FILE_DEVICE_SERIAL_PORT:
3126 case FILE_DEVICE_PARALLEL_PORT:
3127 case FILE_DEVICE_TAPE:
3128 case FILE_DEVICE_UNKNOWN:
3129 return FILE_TYPE_CHAR;
3130 case FILE_DEVICE_NAMED_PIPE:
3131 return FILE_TYPE_PIPE;
3132 default:
3133 return FILE_TYPE_DISK;
3138 /***********************************************************************
3139 * GetOverlappedResult (kernelbase.@)
3141 BOOL WINAPI DECLSPEC_HOTPATCH GetOverlappedResult( HANDLE file, LPOVERLAPPED overlapped,
3142 LPDWORD result, BOOL wait )
3144 return GetOverlappedResultEx( file, overlapped, result, wait ? INFINITE : 0, FALSE );
3148 /***********************************************************************
3149 * GetOverlappedResultEx (kernelbase.@)
3151 BOOL WINAPI DECLSPEC_HOTPATCH GetOverlappedResultEx( HANDLE file, OVERLAPPED *overlapped,
3152 DWORD *result, DWORD timeout, BOOL alertable )
3154 NTSTATUS status;
3155 DWORD ret;
3157 TRACE( "(%p %p %p %lu %d)\n", file, overlapped, result, timeout, alertable );
3159 /* Paired with the write-release in set_async_iosb() in ntdll; see the
3160 * latter for details. */
3161 status = ReadAcquire( (LONG *)&overlapped->Internal );
3162 if (status == STATUS_PENDING)
3164 if (!timeout)
3166 SetLastError( ERROR_IO_INCOMPLETE );
3167 return FALSE;
3169 ret = WaitForSingleObjectEx( overlapped->hEvent ? overlapped->hEvent : file, timeout, alertable );
3170 if (ret == WAIT_FAILED)
3171 return FALSE;
3172 else if (ret)
3174 SetLastError( ret );
3175 return FALSE;
3178 /* We don't need to give this load acquire semantics; the wait above
3179 * already guarantees that the IOSB and output buffer are filled. */
3180 status = overlapped->Internal;
3181 if (status == STATUS_PENDING) status = STATUS_SUCCESS;
3184 *result = overlapped->InternalHigh;
3185 return set_ntstatus( status );
3189 /**************************************************************************
3190 * LockFile (kernelbase.@)
3192 BOOL WINAPI DECLSPEC_HOTPATCH LockFile( HANDLE file, DWORD offset_low, DWORD offset_high,
3193 DWORD count_low, DWORD count_high )
3195 LARGE_INTEGER count, offset;
3197 TRACE( "%p %lx%08lx %lx%08lx\n", file, offset_high, offset_low, count_high, count_low );
3199 count.u.LowPart = count_low;
3200 count.u.HighPart = count_high;
3201 offset.u.LowPart = offset_low;
3202 offset.u.HighPart = offset_high;
3203 return set_ntstatus( NtLockFile( file, 0, NULL, NULL, NULL, &offset, &count, NULL, TRUE, TRUE ));
3207 /**************************************************************************
3208 * LockFileEx (kernelbase.@)
3210 BOOL WINAPI DECLSPEC_HOTPATCH LockFileEx( HANDLE file, DWORD flags, DWORD reserved,
3211 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
3213 LARGE_INTEGER count, offset;
3214 LPVOID cvalue = NULL;
3216 if (reserved)
3218 SetLastError( ERROR_INVALID_PARAMETER );
3219 return FALSE;
3222 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
3223 file, overlapped->u.s.OffsetHigh, overlapped->u.s.Offset, count_high, count_low, flags );
3225 count.u.LowPart = count_low;
3226 count.u.HighPart = count_high;
3227 offset.u.LowPart = overlapped->u.s.Offset;
3228 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3230 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
3232 return set_ntstatus( NtLockFile( file, overlapped->hEvent, NULL, cvalue,
3233 NULL, &offset, &count, NULL,
3234 flags & LOCKFILE_FAIL_IMMEDIATELY,
3235 flags & LOCKFILE_EXCLUSIVE_LOCK ));
3239 /***********************************************************************
3240 * OpenFileById (kernelbase.@)
3242 HANDLE WINAPI DECLSPEC_HOTPATCH OpenFileById( HANDLE handle, LPFILE_ID_DESCRIPTOR id, DWORD access,
3243 DWORD share, LPSECURITY_ATTRIBUTES sec_attr, DWORD flags )
3245 UINT options;
3246 HANDLE result;
3247 OBJECT_ATTRIBUTES attr;
3248 IO_STATUS_BLOCK io;
3249 UNICODE_STRING objectName;
3251 if (!id)
3253 SetLastError( ERROR_INVALID_PARAMETER );
3254 return INVALID_HANDLE_VALUE;
3257 options = FILE_OPEN_BY_FILE_ID;
3258 if (flags & FILE_FLAG_BACKUP_SEMANTICS)
3259 options |= FILE_OPEN_FOR_BACKUP_INTENT;
3260 else
3261 options |= FILE_NON_DIRECTORY_FILE;
3262 if (flags & FILE_FLAG_NO_BUFFERING) options |= FILE_NO_INTERMEDIATE_BUFFERING;
3263 if (!(flags & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
3264 if (flags & FILE_FLAG_RANDOM_ACCESS) options |= FILE_RANDOM_ACCESS;
3265 if (flags & FILE_FLAG_SEQUENTIAL_SCAN) options |= FILE_SEQUENTIAL_ONLY;
3266 flags &= FILE_ATTRIBUTE_VALID_FLAGS;
3268 objectName.Length = sizeof(ULONGLONG);
3269 objectName.Buffer = (WCHAR *)&id->u.FileId;
3270 attr.Length = sizeof(attr);
3271 attr.RootDirectory = handle;
3272 attr.Attributes = 0;
3273 attr.ObjectName = &objectName;
3274 attr.SecurityDescriptor = sec_attr ? sec_attr->lpSecurityDescriptor : NULL;
3275 attr.SecurityQualityOfService = NULL;
3276 if (sec_attr && sec_attr->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
3278 if (!set_ntstatus( NtCreateFile( &result, access | SYNCHRONIZE, &attr, &io, NULL, flags,
3279 share, OPEN_EXISTING, options, NULL, 0 )))
3280 return INVALID_HANDLE_VALUE;
3281 return result;
3285 /***********************************************************************
3286 * ReOpenFile (kernelbase.@)
3288 HANDLE WINAPI DECLSPEC_HOTPATCH ReOpenFile( HANDLE handle, DWORD access, DWORD sharing, DWORD attributes )
3290 SECURITY_QUALITY_OF_SERVICE qos;
3291 OBJECT_ATTRIBUTES attr;
3292 UNICODE_STRING empty = { 0 };
3293 IO_STATUS_BLOCK io;
3294 NTSTATUS status;
3295 HANDLE file;
3297 TRACE("handle %p, access %#lx, sharing %#lx, attributes %#lx.\n", handle, access, sharing, attributes);
3299 if (attributes & 0x7ffff) /* FILE_ATTRIBUTE_* flags are invalid */
3301 SetLastError(ERROR_INVALID_PARAMETER);
3302 return INVALID_HANDLE_VALUE;
3305 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
3306 access |= DELETE;
3308 InitializeObjectAttributes( &attr, &empty, OBJ_CASE_INSENSITIVE, handle, NULL );
3309 if (attributes & SECURITY_SQOS_PRESENT)
3311 qos.Length = sizeof(qos);
3312 qos.ImpersonationLevel = (attributes >> 16) & 0x3;
3313 qos.ContextTrackingMode = attributes & SECURITY_CONTEXT_TRACKING ? SECURITY_DYNAMIC_TRACKING : SECURITY_STATIC_TRACKING;
3314 qos.EffectiveOnly = (attributes & SECURITY_EFFECTIVE_ONLY) != 0;
3315 attr.SecurityQualityOfService = &qos;
3318 status = NtCreateFile( &file, access | SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attr, &io, NULL,
3319 0, sharing, FILE_OPEN, get_nt_file_options( attributes ), NULL, 0 );
3320 if (!set_ntstatus( status ))
3321 return INVALID_HANDLE_VALUE;
3322 return file;
3326 static void WINAPI invoke_completion( void *context, IO_STATUS_BLOCK *io, ULONG res )
3328 LPOVERLAPPED_COMPLETION_ROUTINE completion = context;
3329 completion( RtlNtStatusToDosError( io->u.Status ), io->Information, (LPOVERLAPPED)io );
3332 /****************************************************************************
3333 * ReadDirectoryChangesW (kernelbase.@)
3335 BOOL WINAPI DECLSPEC_HOTPATCH ReadDirectoryChangesW( HANDLE handle, LPVOID buffer, DWORD len,
3336 BOOL subtree, DWORD filter, LPDWORD returned,
3337 LPOVERLAPPED overlapped,
3338 LPOVERLAPPED_COMPLETION_ROUTINE completion )
3340 OVERLAPPED ov, *pov;
3341 IO_STATUS_BLOCK *ios;
3342 NTSTATUS status;
3343 LPVOID cvalue = NULL;
3345 TRACE( "%p %p %08lx %d %08lx %p %p %p\n",
3346 handle, buffer, len, subtree, filter, returned, overlapped, completion );
3348 if (!overlapped)
3350 memset( &ov, 0, sizeof ov );
3351 ov.hEvent = CreateEventW( NULL, 0, 0, NULL );
3352 pov = &ov;
3354 else
3356 pov = overlapped;
3357 if (completion) cvalue = completion;
3358 else if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
3361 ios = (PIO_STATUS_BLOCK)pov;
3362 ios->u.Status = STATUS_PENDING;
3364 status = NtNotifyChangeDirectoryFile( handle, completion && overlapped ? NULL : pov->hEvent,
3365 completion && overlapped ? invoke_completion : NULL,
3366 cvalue, ios, buffer, len, filter, subtree );
3367 if (status == STATUS_PENDING)
3369 if (overlapped) return TRUE;
3370 WaitForSingleObjectEx( ov.hEvent, INFINITE, TRUE );
3371 if (returned) *returned = ios->Information;
3372 status = ios->u.Status;
3374 if (!overlapped) CloseHandle( ov.hEvent );
3375 return set_ntstatus( status );
3379 /***********************************************************************
3380 * ReadFile (kernelbase.@)
3382 BOOL WINAPI DECLSPEC_HOTPATCH ReadFile( HANDLE file, LPVOID buffer, DWORD count,
3383 LPDWORD result, LPOVERLAPPED overlapped )
3385 LARGE_INTEGER offset;
3386 PLARGE_INTEGER poffset = NULL;
3387 IO_STATUS_BLOCK iosb;
3388 PIO_STATUS_BLOCK io_status = &iosb;
3389 HANDLE event = 0;
3390 NTSTATUS status;
3391 LPVOID cvalue = NULL;
3393 TRACE( "%p %p %ld %p %p\n", file, buffer, count, result, overlapped );
3395 if (result) *result = 0;
3397 if (overlapped)
3399 offset.u.LowPart = overlapped->u.s.Offset;
3400 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3401 poffset = &offset;
3402 event = overlapped->hEvent;
3403 io_status = (PIO_STATUS_BLOCK)overlapped;
3404 if (((ULONG_PTR)event & 1) == 0) cvalue = overlapped;
3406 else io_status->Information = 0;
3407 io_status->u.Status = STATUS_PENDING;
3409 status = NtReadFile( file, event, NULL, cvalue, io_status, buffer, count, poffset, NULL);
3411 if (status == STATUS_PENDING && !overlapped)
3413 WaitForSingleObject( file, INFINITE );
3414 status = io_status->u.Status;
3417 if (result) *result = overlapped && status ? 0 : io_status->Information;
3419 if (status == STATUS_END_OF_FILE)
3421 if (overlapped != NULL)
3423 SetLastError( RtlNtStatusToDosError(status) );
3424 return FALSE;
3427 else if (status && status != STATUS_TIMEOUT)
3429 SetLastError( RtlNtStatusToDosError(status) );
3430 return FALSE;
3432 return TRUE;
3436 /***********************************************************************
3437 * ReadFileEx (kernelbase.@)
3439 BOOL WINAPI DECLSPEC_HOTPATCH ReadFileEx( HANDLE file, LPVOID buffer, DWORD count, LPOVERLAPPED overlapped,
3440 LPOVERLAPPED_COMPLETION_ROUTINE completion )
3442 PIO_STATUS_BLOCK io;
3443 LARGE_INTEGER offset;
3444 NTSTATUS status;
3446 TRACE( "(file=%p, buffer=%p, bytes=%lu, ovl=%p, ovl_fn=%p)\n",
3447 file, buffer, count, overlapped, completion );
3449 if (!overlapped)
3451 SetLastError( ERROR_INVALID_PARAMETER );
3452 return FALSE;
3454 offset.u.LowPart = overlapped->u.s.Offset;
3455 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3456 io = (PIO_STATUS_BLOCK)overlapped;
3457 io->u.Status = STATUS_PENDING;
3458 io->Information = 0;
3460 status = NtReadFile( file, NULL, read_write_apc, completion, io, buffer, count, &offset, NULL);
3461 if (status == STATUS_PENDING) return TRUE;
3462 return set_ntstatus( status );
3466 /***********************************************************************
3467 * ReadFileScatter (kernelbase.@)
3469 BOOL WINAPI DECLSPEC_HOTPATCH ReadFileScatter( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
3470 LPDWORD reserved, LPOVERLAPPED overlapped )
3472 PIO_STATUS_BLOCK io;
3473 LARGE_INTEGER offset;
3474 void *cvalue = NULL;
3476 TRACE( "(%p %p %lu %p)\n", file, segments, count, overlapped );
3478 offset.u.LowPart = overlapped->u.s.Offset;
3479 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3480 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
3481 io = (PIO_STATUS_BLOCK)overlapped;
3482 io->u.Status = STATUS_PENDING;
3483 io->Information = 0;
3485 return set_ntstatus( NtReadFileScatter( file, overlapped->hEvent, NULL, cvalue, io,
3486 segments, count, &offset, NULL ));
3490 /***********************************************************************
3491 * RemoveDirectoryA (kernelbase.@)
3493 BOOL WINAPI DECLSPEC_HOTPATCH RemoveDirectoryA( LPCSTR path )
3495 WCHAR *pathW;
3497 if (!(pathW = file_name_AtoW( path, FALSE ))) return FALSE;
3498 return RemoveDirectoryW( pathW );
3502 /***********************************************************************
3503 * RemoveDirectoryW (kernelbase.@)
3505 BOOL WINAPI DECLSPEC_HOTPATCH RemoveDirectoryW( LPCWSTR path )
3507 OBJECT_ATTRIBUTES attr;
3508 UNICODE_STRING nt_name;
3509 IO_STATUS_BLOCK io;
3510 NTSTATUS status;
3511 HANDLE handle;
3513 TRACE( "%s\n", debugstr_w(path) );
3515 status = RtlDosPathNameToNtPathName_U_WithStatus( path, &nt_name, NULL, NULL );
3516 if (!set_ntstatus( status )) return FALSE;
3518 InitializeObjectAttributes( &attr, &nt_name, OBJ_CASE_INSENSITIVE, 0, NULL );
3519 status = NtOpenFile( &handle, DELETE | SYNCHRONIZE, &attr, &io,
3520 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3521 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3522 RtlFreeUnicodeString( &nt_name );
3524 if (!status)
3526 FILE_DISPOSITION_INFORMATION info = { TRUE };
3527 status = NtSetInformationFile( handle, &io, &info, sizeof(info), FileDispositionInformation );
3528 NtClose( handle );
3530 return set_ntstatus( status );
3534 /**************************************************************************
3535 * SetEndOfFile (kernelbase.@)
3537 BOOL WINAPI DECLSPEC_HOTPATCH SetEndOfFile( HANDLE file )
3539 FILE_POSITION_INFORMATION pos;
3540 FILE_END_OF_FILE_INFORMATION eof;
3541 IO_STATUS_BLOCK io;
3542 NTSTATUS status;
3544 if (!(status = NtQueryInformationFile( file, &io, &pos, sizeof(pos), FilePositionInformation )))
3546 eof.EndOfFile = pos.CurrentByteOffset;
3547 status = NtSetInformationFile( file, &io, &eof, sizeof(eof), FileEndOfFileInformation );
3549 return set_ntstatus( status );
3553 /***********************************************************************
3554 * SetFileInformationByHandle (kernelbase.@)
3556 BOOL WINAPI DECLSPEC_HOTPATCH SetFileInformationByHandle( HANDLE file, FILE_INFO_BY_HANDLE_CLASS class,
3557 void *info, DWORD size )
3559 NTSTATUS status;
3560 IO_STATUS_BLOCK io;
3562 TRACE( "%p %u %p %lu\n", file, class, info, size );
3564 switch (class)
3566 case FileNameInfo:
3567 case FileAllocationInfo:
3568 case FileStreamInfo:
3569 case FileIdBothDirectoryInfo:
3570 case FileIdBothDirectoryRestartInfo:
3571 case FileFullDirectoryInfo:
3572 case FileFullDirectoryRestartInfo:
3573 case FileStorageInfo:
3574 case FileAlignmentInfo:
3575 case FileIdInfo:
3576 case FileIdExtdDirectoryInfo:
3577 case FileIdExtdDirectoryRestartInfo:
3578 FIXME( "%p, %u, %p, %lu\n", file, class, info, size );
3579 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
3580 return FALSE;
3582 case FileEndOfFileInfo:
3583 status = NtSetInformationFile( file, &io, info, size, FileEndOfFileInformation );
3584 break;
3585 case FileBasicInfo:
3586 status = NtSetInformationFile( file, &io, info, size, FileBasicInformation );
3587 break;
3588 case FileDispositionInfo:
3589 status = NtSetInformationFile( file, &io, info, size, FileDispositionInformation );
3590 break;
3591 case FileIoPriorityHintInfo:
3592 status = NtSetInformationFile( file, &io, info, size, FileIoPriorityHintInformation );
3593 break;
3594 case FileRenameInfo:
3596 FILE_RENAME_INFORMATION *rename_info;
3597 UNICODE_STRING nt_name;
3598 ULONG size;
3600 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( ((FILE_RENAME_INFORMATION *)info)->FileName,
3601 &nt_name, NULL, NULL )))
3602 break;
3604 size = sizeof(*rename_info) + nt_name.Length;
3605 if ((rename_info = HeapAlloc( GetProcessHeap(), 0, size )))
3607 memcpy( rename_info, info, sizeof(*rename_info) );
3608 memcpy( rename_info->FileName, nt_name.Buffer, nt_name.Length + sizeof(WCHAR) );
3609 rename_info->FileNameLength = nt_name.Length;
3610 status = NtSetInformationFile( file, &io, rename_info, size, FileRenameInformation );
3611 HeapFree( GetProcessHeap(), 0, rename_info );
3613 RtlFreeUnicodeString( &nt_name );
3614 break;
3616 case FileStandardInfo:
3617 case FileCompressionInfo:
3618 case FileAttributeTagInfo:
3619 case FileRemoteProtocolInfo:
3620 default:
3621 SetLastError( ERROR_INVALID_PARAMETER );
3622 return FALSE;
3624 return set_ntstatus( status );
3628 /***********************************************************************
3629 * SetFilePointer (kernelbase.@)
3631 DWORD WINAPI DECLSPEC_HOTPATCH SetFilePointer( HANDLE file, LONG distance, LONG *highword, DWORD method )
3633 LARGE_INTEGER dist, newpos;
3635 if (highword)
3637 dist.u.LowPart = distance;
3638 dist.u.HighPart = *highword;
3640 else dist.QuadPart = distance;
3642 if (!SetFilePointerEx( file, dist, &newpos, method )) return INVALID_SET_FILE_POINTER;
3644 if (highword) *highword = newpos.u.HighPart;
3645 if (newpos.u.LowPart == INVALID_SET_FILE_POINTER) SetLastError( 0 );
3646 return newpos.u.LowPart;
3650 /***********************************************************************
3651 * SetFilePointerEx (kernelbase.@)
3653 BOOL WINAPI DECLSPEC_HOTPATCH SetFilePointerEx( HANDLE file, LARGE_INTEGER distance,
3654 LARGE_INTEGER *newpos, DWORD method )
3656 LONGLONG pos;
3657 IO_STATUS_BLOCK io;
3658 FILE_POSITION_INFORMATION info;
3659 FILE_STANDARD_INFORMATION eof;
3661 switch(method)
3663 case FILE_BEGIN:
3664 pos = distance.QuadPart;
3665 break;
3666 case FILE_CURRENT:
3667 if (NtQueryInformationFile( file, &io, &info, sizeof(info), FilePositionInformation ))
3668 goto error;
3669 pos = info.CurrentByteOffset.QuadPart + distance.QuadPart;
3670 break;
3671 case FILE_END:
3672 if (NtQueryInformationFile( file, &io, &eof, sizeof(eof), FileStandardInformation ))
3673 goto error;
3674 pos = eof.EndOfFile.QuadPart + distance.QuadPart;
3675 break;
3676 default:
3677 SetLastError( ERROR_INVALID_PARAMETER );
3678 return FALSE;
3681 if (pos < 0)
3683 SetLastError( ERROR_NEGATIVE_SEEK );
3684 return FALSE;
3687 info.CurrentByteOffset.QuadPart = pos;
3688 if (!NtSetInformationFile( file, &io, &info, sizeof(info), FilePositionInformation ))
3690 if (newpos) newpos->QuadPart = pos;
3691 return TRUE;
3694 error:
3695 return set_ntstatus( io.u.Status );
3699 /***********************************************************************
3700 * SetFileTime (kernelbase.@)
3702 BOOL WINAPI DECLSPEC_HOTPATCH SetFileTime( HANDLE file, const FILETIME *ctime,
3703 const FILETIME *atime, const FILETIME *mtime )
3705 FILE_BASIC_INFORMATION info;
3706 IO_STATUS_BLOCK io;
3708 memset( &info, 0, sizeof(info) );
3709 if (ctime)
3711 info.CreationTime.u.HighPart = ctime->dwHighDateTime;
3712 info.CreationTime.u.LowPart = ctime->dwLowDateTime;
3714 if (atime)
3716 info.LastAccessTime.u.HighPart = atime->dwHighDateTime;
3717 info.LastAccessTime.u.LowPart = atime->dwLowDateTime;
3719 if (mtime)
3721 info.LastWriteTime.u.HighPart = mtime->dwHighDateTime;
3722 info.LastWriteTime.u.LowPart = mtime->dwLowDateTime;
3725 return set_ntstatus( NtSetInformationFile( file, &io, &info, sizeof(info), FileBasicInformation ));
3729 /***********************************************************************
3730 * SetFileValidData (kernelbase.@)
3732 BOOL WINAPI DECLSPEC_HOTPATCH SetFileValidData( HANDLE file, LONGLONG length )
3734 FILE_VALID_DATA_LENGTH_INFORMATION info;
3735 IO_STATUS_BLOCK io;
3737 info.ValidDataLength.QuadPart = length;
3738 return set_ntstatus( NtSetInformationFile( file, &io, &info, sizeof(info),
3739 FileValidDataLengthInformation ));
3743 /**************************************************************************
3744 * UnlockFile (kernelbase.@)
3746 BOOL WINAPI DECLSPEC_HOTPATCH UnlockFile( HANDLE file, DWORD offset_low, DWORD offset_high,
3747 DWORD count_low, DWORD count_high )
3749 LARGE_INTEGER count, offset;
3751 count.u.LowPart = count_low;
3752 count.u.HighPart = count_high;
3753 offset.u.LowPart = offset_low;
3754 offset.u.HighPart = offset_high;
3755 return set_ntstatus( NtUnlockFile( file, NULL, &offset, &count, NULL ));
3759 /**************************************************************************
3760 * UnlockFileEx (kernelbase.@)
3762 BOOL WINAPI DECLSPEC_HOTPATCH UnlockFileEx( HANDLE file, DWORD reserved,
3763 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
3765 if (reserved)
3767 SetLastError( ERROR_INVALID_PARAMETER );
3768 return FALSE;
3770 if (overlapped->hEvent) FIXME("Unimplemented overlapped operation\n");
3772 return UnlockFile( file, overlapped->u.s.Offset, overlapped->u.s.OffsetHigh, count_low, count_high );
3776 /***********************************************************************
3777 * WriteFile (kernelbase.@)
3779 BOOL WINAPI DECLSPEC_HOTPATCH WriteFile( HANDLE file, LPCVOID buffer, DWORD count,
3780 LPDWORD result, LPOVERLAPPED overlapped )
3782 HANDLE event = NULL;
3783 LARGE_INTEGER offset;
3784 PLARGE_INTEGER poffset = NULL;
3785 NTSTATUS status;
3786 IO_STATUS_BLOCK iosb;
3787 PIO_STATUS_BLOCK piosb = &iosb;
3788 LPVOID cvalue = NULL;
3790 TRACE( "%p %p %ld %p %p\n", file, buffer, count, result, overlapped );
3792 if (overlapped)
3794 offset.u.LowPart = overlapped->u.s.Offset;
3795 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3796 poffset = &offset;
3797 event = overlapped->hEvent;
3798 piosb = (PIO_STATUS_BLOCK)overlapped;
3799 if (((ULONG_PTR)event & 1) == 0) cvalue = overlapped;
3801 else piosb->Information = 0;
3802 piosb->u.Status = STATUS_PENDING;
3804 status = NtWriteFile( file, event, NULL, cvalue, piosb, buffer, count, poffset, NULL );
3806 if (status == STATUS_PENDING && !overlapped)
3808 WaitForSingleObject( file, INFINITE );
3809 status = piosb->u.Status;
3812 if (result) *result = overlapped && status ? 0 : piosb->Information;
3814 if (status && status != STATUS_TIMEOUT)
3816 SetLastError( RtlNtStatusToDosError(status) );
3817 return FALSE;
3819 return TRUE;
3823 /***********************************************************************
3824 * WriteFileEx (kernelbase.@)
3826 BOOL WINAPI DECLSPEC_HOTPATCH WriteFileEx( HANDLE file, LPCVOID buffer,
3827 DWORD count, LPOVERLAPPED overlapped,
3828 LPOVERLAPPED_COMPLETION_ROUTINE completion )
3830 LARGE_INTEGER offset;
3831 NTSTATUS status;
3832 PIO_STATUS_BLOCK io;
3834 TRACE( "%p %p %ld %p %p\n", file, buffer, count, overlapped, completion );
3836 if (!overlapped)
3838 SetLastError( ERROR_INVALID_PARAMETER );
3839 return FALSE;
3841 offset.u.LowPart = overlapped->u.s.Offset;
3842 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3844 io = (PIO_STATUS_BLOCK)overlapped;
3845 io->u.Status = STATUS_PENDING;
3846 io->Information = 0;
3848 status = NtWriteFile( file, NULL, read_write_apc, completion, io, buffer, count, &offset, NULL );
3849 if (status == STATUS_PENDING) return TRUE;
3850 return set_ntstatus( status );
3854 /***********************************************************************
3855 * WriteFileGather (kernelbase.@)
3857 BOOL WINAPI DECLSPEC_HOTPATCH WriteFileGather( HANDLE file, FILE_SEGMENT_ELEMENT *segments, DWORD count,
3858 LPDWORD reserved, LPOVERLAPPED overlapped )
3860 PIO_STATUS_BLOCK io;
3861 LARGE_INTEGER offset;
3862 void *cvalue = NULL;
3864 TRACE( "%p %p %lu %p\n", file, segments, count, overlapped );
3866 offset.u.LowPart = overlapped->u.s.Offset;
3867 offset.u.HighPart = overlapped->u.s.OffsetHigh;
3868 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
3869 io = (PIO_STATUS_BLOCK)overlapped;
3870 io->u.Status = STATUS_PENDING;
3871 io->Information = 0;
3873 return set_ntstatus( NtWriteFileGather( file, overlapped->hEvent, NULL, cvalue,
3874 io, segments, count, &offset, NULL ));
3878 /***********************************************************************
3879 * Operations on file times
3880 ***********************************************************************/
3883 /*********************************************************************
3884 * CompareFileTime (kernelbase.@)
3886 INT WINAPI DECLSPEC_HOTPATCH CompareFileTime( const FILETIME *x, const FILETIME *y )
3888 if (!x || !y) return -1;
3889 if (x->dwHighDateTime > y->dwHighDateTime) return 1;
3890 if (x->dwHighDateTime < y->dwHighDateTime) return -1;
3891 if (x->dwLowDateTime > y->dwLowDateTime) return 1;
3892 if (x->dwLowDateTime < y->dwLowDateTime) return -1;
3893 return 0;
3897 /*********************************************************************
3898 * FileTimeToLocalFileTime (kernelbase.@)
3900 BOOL WINAPI DECLSPEC_HOTPATCH FileTimeToLocalFileTime( const FILETIME *utc, FILETIME *local )
3902 return set_ntstatus( RtlSystemTimeToLocalTime( (const LARGE_INTEGER *)utc, (LARGE_INTEGER *)local ));
3906 /*********************************************************************
3907 * FileTimeToSystemTime (kernelbase.@)
3909 BOOL WINAPI DECLSPEC_HOTPATCH FileTimeToSystemTime( const FILETIME *ft, SYSTEMTIME *systime )
3911 TIME_FIELDS tf;
3912 const LARGE_INTEGER *li = (const LARGE_INTEGER *)ft;
3914 if (li->QuadPart < 0)
3916 SetLastError( ERROR_INVALID_PARAMETER );
3917 return FALSE;
3919 RtlTimeToTimeFields( li, &tf );
3920 systime->wYear = tf.Year;
3921 systime->wMonth = tf.Month;
3922 systime->wDay = tf.Day;
3923 systime->wHour = tf.Hour;
3924 systime->wMinute = tf.Minute;
3925 systime->wSecond = tf.Second;
3926 systime->wMilliseconds = tf.Milliseconds;
3927 systime->wDayOfWeek = tf.Weekday;
3928 return TRUE;
3932 /*********************************************************************
3933 * GetLocalTime (kernelbase.@)
3935 void WINAPI DECLSPEC_HOTPATCH GetLocalTime( SYSTEMTIME *systime )
3937 LARGE_INTEGER ft, ft2;
3939 NtQuerySystemTime( &ft );
3940 RtlSystemTimeToLocalTime( &ft, &ft2 );
3941 FileTimeToSystemTime( (FILETIME *)&ft2, systime );
3945 /*********************************************************************
3946 * GetSystemTime (kernelbase.@)
3948 void WINAPI DECLSPEC_HOTPATCH GetSystemTime( SYSTEMTIME *systime )
3950 LARGE_INTEGER ft;
3952 NtQuerySystemTime( &ft );
3953 FileTimeToSystemTime( (FILETIME *)&ft, systime );
3957 /***********************************************************************
3958 * GetSystemTimeAdjustment (kernelbase.@)
3960 BOOL WINAPI DECLSPEC_HOTPATCH GetSystemTimeAdjustment( DWORD *adjust, DWORD *increment, BOOL *disabled )
3962 SYSTEM_TIME_ADJUSTMENT_QUERY st;
3963 ULONG len;
3965 if (!set_ntstatus( NtQuerySystemInformation( SystemTimeAdjustmentInformation, &st, sizeof(st), &len )))
3966 return FALSE;
3967 *adjust = st.TimeAdjustment;
3968 *increment = st.TimeIncrement;
3969 *disabled = st.TimeAdjustmentDisabled;
3970 return TRUE;
3974 /***********************************************************************
3975 * GetSystemTimeAsFileTime (kernelbase.@)
3977 void WINAPI DECLSPEC_HOTPATCH GetSystemTimeAsFileTime( FILETIME *time )
3979 NtQuerySystemTime( (LARGE_INTEGER *)time );
3983 /***********************************************************************
3984 * GetSystemTimePreciseAsFileTime (kernelbase.@)
3986 void WINAPI DECLSPEC_HOTPATCH GetSystemTimePreciseAsFileTime( FILETIME *time )
3988 LARGE_INTEGER t;
3990 t.QuadPart = RtlGetSystemTimePrecise();
3991 time->dwLowDateTime = t.u.LowPart;
3992 time->dwHighDateTime = t.u.HighPart;
3996 /*********************************************************************
3997 * LocalFileTimeToFileTime (kernelbase.@)
3999 BOOL WINAPI DECLSPEC_HOTPATCH LocalFileTimeToFileTime( const FILETIME *local, FILETIME *utc )
4001 return set_ntstatus( RtlLocalTimeToSystemTime( (const LARGE_INTEGER *)local, (LARGE_INTEGER *)utc ));
4005 /***********************************************************************
4006 * SetLocalTime (kernelbase.@)
4008 BOOL WINAPI DECLSPEC_HOTPATCH SetLocalTime( const SYSTEMTIME *systime )
4010 FILETIME ft;
4011 LARGE_INTEGER st;
4013 if (!SystemTimeToFileTime( systime, &ft )) return FALSE;
4014 RtlLocalTimeToSystemTime( (LARGE_INTEGER *)&ft, &st );
4015 return set_ntstatus( NtSetSystemTime( &st, NULL ));
4019 /***********************************************************************
4020 * SetSystemTime (kernelbase.@)
4022 BOOL WINAPI DECLSPEC_HOTPATCH SetSystemTime( const SYSTEMTIME *systime )
4024 FILETIME ft;
4026 if (!SystemTimeToFileTime( systime, &ft )) return FALSE;
4027 return set_ntstatus( NtSetSystemTime( (LARGE_INTEGER *)&ft, NULL ));
4031 /***********************************************************************
4032 * SetSystemTimeAdjustment (kernelbase.@)
4034 BOOL WINAPI DECLSPEC_HOTPATCH SetSystemTimeAdjustment( DWORD adjust, BOOL disabled )
4036 SYSTEM_TIME_ADJUSTMENT st;
4038 st.TimeAdjustment = adjust;
4039 st.TimeAdjustmentDisabled = disabled;
4040 return set_ntstatus( NtSetSystemInformation( SystemTimeAdjustmentInformation, &st, sizeof(st) ));
4044 /*********************************************************************
4045 * SystemTimeToFileTime (kernelbase.@)
4047 BOOL WINAPI DECLSPEC_HOTPATCH SystemTimeToFileTime( const SYSTEMTIME *systime, FILETIME *ft )
4049 TIME_FIELDS tf;
4051 tf.Year = systime->wYear;
4052 tf.Month = systime->wMonth;
4053 tf.Day = systime->wDay;
4054 tf.Hour = systime->wHour;
4055 tf.Minute = systime->wMinute;
4056 tf.Second = systime->wSecond;
4057 tf.Milliseconds = systime->wMilliseconds;
4058 if (RtlTimeFieldsToTime( &tf, (LARGE_INTEGER *)ft )) return TRUE;
4059 SetLastError( ERROR_INVALID_PARAMETER );
4060 return FALSE;
4064 /***********************************************************************
4065 * I/O controls
4066 ***********************************************************************/
4069 static void dump_dcb( const DCB *dcb )
4071 TRACE( "size=%d rate=%ld fParity=%d Parity=%d stopbits=%d %sIXON %sIXOFF CTS=%d RTS=%d DSR=%d DTR=%d %sCRTSCTS\n",
4072 dcb->ByteSize, dcb->BaudRate, dcb->fParity, dcb->Parity,
4073 (dcb->StopBits == ONESTOPBIT) ? 1 : (dcb->StopBits == TWOSTOPBITS) ? 2 : 0,
4074 dcb->fOutX ? "" : "~", dcb->fInX ? "" : "~",
4075 dcb->fOutxCtsFlow, dcb->fRtsControl, dcb->fOutxDsrFlow, dcb->fDtrControl,
4076 (dcb->fOutxCtsFlow || dcb->fRtsControl == RTS_CONTROL_HANDSHAKE) ? "" : "~" );
4079 /*****************************************************************************
4080 * ClearCommBreak (kernelbase.@)
4082 BOOL WINAPI DECLSPEC_HOTPATCH ClearCommBreak( HANDLE handle )
4084 return EscapeCommFunction( handle, CLRBREAK );
4088 /*****************************************************************************
4089 * ClearCommError (kernelbase.@)
4091 BOOL WINAPI DECLSPEC_HOTPATCH ClearCommError( HANDLE handle, DWORD *errors, COMSTAT *stat )
4093 SERIAL_STATUS ss;
4095 if (!DeviceIoControl( handle, IOCTL_SERIAL_GET_COMMSTATUS, NULL, 0, &ss, sizeof(ss), NULL, NULL ))
4096 return FALSE;
4098 TRACE( "status %#lx,%#lx, in %lu, out %lu, eof %d, wait %d\n", ss.Errors, ss.HoldReasons,
4099 ss.AmountInInQueue, ss.AmountInOutQueue, ss.EofReceived, ss.WaitForImmediate );
4101 if (errors)
4103 *errors = 0;
4104 if (ss.Errors & SERIAL_ERROR_BREAK) *errors |= CE_BREAK;
4105 if (ss.Errors & SERIAL_ERROR_FRAMING) *errors |= CE_FRAME;
4106 if (ss.Errors & SERIAL_ERROR_OVERRUN) *errors |= CE_OVERRUN;
4107 if (ss.Errors & SERIAL_ERROR_QUEUEOVERRUN) *errors |= CE_RXOVER;
4108 if (ss.Errors & SERIAL_ERROR_PARITY) *errors |= CE_RXPARITY;
4110 if (stat)
4112 stat->fCtsHold = !!(ss.HoldReasons & SERIAL_TX_WAITING_FOR_CTS);
4113 stat->fDsrHold = !!(ss.HoldReasons & SERIAL_TX_WAITING_FOR_DSR);
4114 stat->fRlsdHold = !!(ss.HoldReasons & SERIAL_TX_WAITING_FOR_DCD);
4115 stat->fXoffHold = !!(ss.HoldReasons & SERIAL_TX_WAITING_FOR_XON);
4116 stat->fXoffSent = !!(ss.HoldReasons & SERIAL_TX_WAITING_XOFF_SENT);
4117 stat->fEof = !!ss.EofReceived;
4118 stat->fTxim = !!ss.WaitForImmediate;
4119 stat->cbInQue = ss.AmountInInQueue;
4120 stat->cbOutQue = ss.AmountInOutQueue;
4122 return TRUE;
4126 /****************************************************************************
4127 * DeviceIoControl (kernelbase.@)
4129 BOOL WINAPI DECLSPEC_HOTPATCH DeviceIoControl( HANDLE handle, DWORD code, void *in_buff, DWORD in_count,
4130 void *out_buff, DWORD out_count, DWORD *returned,
4131 OVERLAPPED *overlapped )
4133 IO_STATUS_BLOCK iosb, *piosb = &iosb;
4134 void *cvalue = NULL;
4135 HANDLE event = 0;
4136 NTSTATUS status;
4138 TRACE( "(%p,%lx,%p,%ld,%p,%ld,%p,%p)\n",
4139 handle, code, in_buff, in_count, out_buff, out_count, returned, overlapped );
4141 if (overlapped)
4143 piosb = (IO_STATUS_BLOCK *)overlapped;
4144 if (!((ULONG_PTR)overlapped->hEvent & 1)) cvalue = overlapped;
4145 event = overlapped->hEvent;
4146 overlapped->Internal = STATUS_PENDING;
4147 overlapped->InternalHigh = 0;
4150 if (HIWORD(code) == FILE_DEVICE_FILE_SYSTEM)
4151 status = NtFsControlFile( handle, event, NULL, cvalue, piosb, code,
4152 in_buff, in_count, out_buff, out_count );
4153 else
4154 status = NtDeviceIoControlFile( handle, event, NULL, cvalue, piosb, code,
4155 in_buff, in_count, out_buff, out_count );
4157 if (returned && !NT_ERROR(status)) *returned = piosb->Information;
4158 if (status == STATUS_PENDING || !NT_SUCCESS( status )) return set_ntstatus( status );
4159 return TRUE;
4163 /*****************************************************************************
4164 * EscapeCommFunction (kernelbase.@)
4166 BOOL WINAPI DECLSPEC_HOTPATCH EscapeCommFunction( HANDLE handle, DWORD func )
4168 static const DWORD ioctls[] =
4171 IOCTL_SERIAL_SET_XOFF, /* SETXOFF */
4172 IOCTL_SERIAL_SET_XON, /* SETXON */
4173 IOCTL_SERIAL_SET_RTS, /* SETRTS */
4174 IOCTL_SERIAL_CLR_RTS, /* CLRRTS */
4175 IOCTL_SERIAL_SET_DTR, /* SETDTR */
4176 IOCTL_SERIAL_CLR_DTR, /* CLRDTR */
4177 IOCTL_SERIAL_RESET_DEVICE, /* RESETDEV */
4178 IOCTL_SERIAL_SET_BREAK_ON, /* SETBREAK */
4179 IOCTL_SERIAL_SET_BREAK_OFF /* CLRBREAK */
4182 if (func >= ARRAY_SIZE(ioctls) || !ioctls[func])
4184 SetLastError( ERROR_INVALID_PARAMETER );
4185 return FALSE;
4187 return DeviceIoControl( handle, ioctls[func], NULL, 0, NULL, 0, NULL, NULL );
4191 /***********************************************************************
4192 * GetCommConfig (kernelbase.@)
4194 BOOL WINAPI DECLSPEC_HOTPATCH GetCommConfig( HANDLE handle, COMMCONFIG *config, DWORD *size )
4196 if (!config) return FALSE;
4198 TRACE( "(%p, %p, %p %lu)\n", handle, config, size, *size );
4200 if (*size < sizeof(COMMCONFIG))
4202 *size = sizeof(COMMCONFIG);
4203 return FALSE;
4205 *size = sizeof(COMMCONFIG);
4206 config->dwSize = sizeof(COMMCONFIG);
4207 config->wVersion = 1;
4208 config->wReserved = 0;
4209 config->dwProviderSubType = PST_RS232;
4210 config->dwProviderOffset = 0;
4211 config->dwProviderSize = 0;
4212 return GetCommState( handle, &config->dcb );
4216 /*****************************************************************************
4217 * GetCommMask (kernelbase.@)
4219 BOOL WINAPI DECLSPEC_HOTPATCH GetCommMask( HANDLE handle, DWORD *mask )
4221 return DeviceIoControl( handle, IOCTL_SERIAL_GET_WAIT_MASK, NULL, 0, mask, sizeof(*mask),
4222 NULL, NULL );
4226 /***********************************************************************
4227 * GetCommModemStatus (kernelbase.@)
4229 BOOL WINAPI DECLSPEC_HOTPATCH GetCommModemStatus( HANDLE handle, DWORD *status )
4231 return DeviceIoControl( handle, IOCTL_SERIAL_GET_MODEMSTATUS, NULL, 0, status, sizeof(*status),
4232 NULL, NULL );
4236 /***********************************************************************
4237 * GetCommProperties (kernelbase.@)
4239 BOOL WINAPI DECLSPEC_HOTPATCH GetCommProperties( HANDLE handle, COMMPROP *prop )
4241 return DeviceIoControl( handle, IOCTL_SERIAL_GET_PROPERTIES, NULL, 0, prop, sizeof(*prop), NULL, NULL );
4245 /*****************************************************************************
4246 * GetCommState (kernelbase.@)
4248 BOOL WINAPI DECLSPEC_HOTPATCH GetCommState( HANDLE handle, DCB *dcb )
4250 SERIAL_BAUD_RATE sbr;
4251 SERIAL_LINE_CONTROL slc;
4252 SERIAL_HANDFLOW shf;
4253 SERIAL_CHARS sc;
4255 if (!dcb)
4257 SetLastError( ERROR_INVALID_PARAMETER );
4258 return FALSE;
4260 if (!DeviceIoControl(handle, IOCTL_SERIAL_GET_BAUD_RATE, NULL, 0, &sbr, sizeof(sbr), NULL, NULL) ||
4261 !DeviceIoControl(handle, IOCTL_SERIAL_GET_LINE_CONTROL, NULL, 0, &slc, sizeof(slc), NULL, NULL) ||
4262 !DeviceIoControl(handle, IOCTL_SERIAL_GET_HANDFLOW, NULL, 0, &shf, sizeof(shf), NULL, NULL) ||
4263 !DeviceIoControl(handle, IOCTL_SERIAL_GET_CHARS, NULL, 0, &sc, sizeof(sc), NULL, NULL))
4264 return FALSE;
4266 dcb->DCBlength = sizeof(*dcb);
4267 dcb->BaudRate = sbr.BaudRate;
4268 /* yes, they seem no never be (re)set on NT */
4269 dcb->fBinary = 1;
4270 dcb->fParity = 0;
4271 dcb->fOutxCtsFlow = !!(shf.ControlHandShake & SERIAL_CTS_HANDSHAKE);
4272 dcb->fOutxDsrFlow = !!(shf.ControlHandShake & SERIAL_DSR_HANDSHAKE);
4273 dcb->fDsrSensitivity = !!(shf.ControlHandShake & SERIAL_DSR_SENSITIVITY);
4274 dcb->fTXContinueOnXoff = !!(shf.FlowReplace & SERIAL_XOFF_CONTINUE);
4275 dcb->fOutX = !!(shf.FlowReplace & SERIAL_AUTO_TRANSMIT);
4276 dcb->fInX = !!(shf.FlowReplace & SERIAL_AUTO_RECEIVE);
4277 dcb->fErrorChar = !!(shf.FlowReplace & SERIAL_ERROR_CHAR);
4278 dcb->fNull = !!(shf.FlowReplace & SERIAL_NULL_STRIPPING);
4279 dcb->fAbortOnError = !!(shf.ControlHandShake & SERIAL_ERROR_ABORT);
4280 dcb->XonLim = shf.XonLimit;
4281 dcb->XoffLim = shf.XoffLimit;
4282 dcb->ByteSize = slc.WordLength;
4283 dcb->Parity = slc.Parity;
4284 dcb->StopBits = slc.StopBits;
4285 dcb->XonChar = sc.XonChar;
4286 dcb->XoffChar = sc.XoffChar;
4287 dcb->ErrorChar = sc.ErrorChar;
4288 dcb->EofChar = sc.EofChar;
4289 dcb->EvtChar = sc.EventChar;
4291 switch (shf.ControlHandShake & (SERIAL_DTR_CONTROL | SERIAL_DTR_HANDSHAKE))
4293 case SERIAL_DTR_CONTROL: dcb->fDtrControl = DTR_CONTROL_ENABLE; break;
4294 case SERIAL_DTR_HANDSHAKE: dcb->fDtrControl = DTR_CONTROL_HANDSHAKE; break;
4295 default: dcb->fDtrControl = DTR_CONTROL_DISABLE; break;
4297 switch (shf.FlowReplace & (SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE))
4299 case SERIAL_RTS_CONTROL: dcb->fRtsControl = RTS_CONTROL_ENABLE; break;
4300 case SERIAL_RTS_HANDSHAKE: dcb->fRtsControl = RTS_CONTROL_HANDSHAKE; break;
4301 case SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE:
4302 dcb->fRtsControl = RTS_CONTROL_TOGGLE; break;
4303 default: dcb->fRtsControl = RTS_CONTROL_DISABLE; break;
4305 dump_dcb( dcb );
4306 return TRUE;
4310 /*****************************************************************************
4311 * GetCommTimeouts (kernelbase.@)
4313 BOOL WINAPI DECLSPEC_HOTPATCH GetCommTimeouts( HANDLE handle, COMMTIMEOUTS *timeouts )
4315 if (!timeouts)
4317 SetLastError( ERROR_INVALID_PARAMETER );
4318 return FALSE;
4320 return DeviceIoControl( handle, IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, timeouts, sizeof(*timeouts),
4321 NULL, NULL );
4324 /********************************************************************
4325 * PurgeComm (kernelbase.@)
4327 BOOL WINAPI DECLSPEC_HOTPATCH PurgeComm(HANDLE handle, DWORD flags)
4329 return DeviceIoControl( handle, IOCTL_SERIAL_PURGE, &flags, sizeof(flags),
4330 NULL, 0, NULL, NULL );
4334 /*****************************************************************************
4335 * SetCommBreak (kernelbase.@)
4337 BOOL WINAPI DECLSPEC_HOTPATCH SetCommBreak( HANDLE handle )
4339 return EscapeCommFunction( handle, SETBREAK );
4343 /***********************************************************************
4344 * SetCommConfig (kernelbase.@)
4346 BOOL WINAPI DECLSPEC_HOTPATCH SetCommConfig( HANDLE handle, COMMCONFIG *config, DWORD size )
4348 TRACE( "(%p, %p, %lu)\n", handle, config, size );
4349 return SetCommState( handle, &config->dcb );
4353 /*****************************************************************************
4354 * SetCommMask (kernelbase.@)
4356 BOOL WINAPI DECLSPEC_HOTPATCH SetCommMask( HANDLE handle, DWORD mask )
4358 return DeviceIoControl( handle, IOCTL_SERIAL_SET_WAIT_MASK, &mask, sizeof(mask),
4359 NULL, 0, NULL, NULL );
4363 /*****************************************************************************
4364 * SetCommState (kernelbase.@)
4366 BOOL WINAPI DECLSPEC_HOTPATCH SetCommState( HANDLE handle, DCB *dcb )
4368 SERIAL_BAUD_RATE sbr;
4369 SERIAL_LINE_CONTROL slc;
4370 SERIAL_HANDFLOW shf;
4371 SERIAL_CHARS sc;
4373 if (!dcb)
4375 SetLastError( ERROR_INVALID_PARAMETER );
4376 return FALSE;
4378 dump_dcb( dcb );
4380 sbr.BaudRate = dcb->BaudRate;
4381 slc.StopBits = dcb->StopBits;
4382 slc.Parity = dcb->Parity;
4383 slc.WordLength = dcb->ByteSize;
4384 shf.ControlHandShake = 0;
4385 shf.FlowReplace = 0;
4386 if (dcb->fOutxCtsFlow) shf.ControlHandShake |= SERIAL_CTS_HANDSHAKE;
4387 if (dcb->fOutxDsrFlow) shf.ControlHandShake |= SERIAL_DSR_HANDSHAKE;
4388 switch (dcb->fDtrControl)
4390 case DTR_CONTROL_DISABLE: break;
4391 case DTR_CONTROL_ENABLE: shf.ControlHandShake |= SERIAL_DTR_CONTROL; break;
4392 case DTR_CONTROL_HANDSHAKE: shf.ControlHandShake |= SERIAL_DTR_HANDSHAKE; break;
4393 default:
4394 SetLastError( ERROR_INVALID_PARAMETER );
4395 return FALSE;
4397 switch (dcb->fRtsControl)
4399 case RTS_CONTROL_DISABLE: break;
4400 case RTS_CONTROL_ENABLE: shf.FlowReplace |= SERIAL_RTS_CONTROL; break;
4401 case RTS_CONTROL_HANDSHAKE: shf.FlowReplace |= SERIAL_RTS_HANDSHAKE; break;
4402 case RTS_CONTROL_TOGGLE: shf.FlowReplace |= SERIAL_RTS_CONTROL | SERIAL_RTS_HANDSHAKE; break;
4403 default:
4404 SetLastError( ERROR_INVALID_PARAMETER );
4405 return FALSE;
4407 if (dcb->fDsrSensitivity) shf.ControlHandShake |= SERIAL_DSR_SENSITIVITY;
4408 if (dcb->fAbortOnError) shf.ControlHandShake |= SERIAL_ERROR_ABORT;
4409 if (dcb->fErrorChar) shf.FlowReplace |= SERIAL_ERROR_CHAR;
4410 if (dcb->fNull) shf.FlowReplace |= SERIAL_NULL_STRIPPING;
4411 if (dcb->fTXContinueOnXoff) shf.FlowReplace |= SERIAL_XOFF_CONTINUE;
4412 if (dcb->fOutX) shf.FlowReplace |= SERIAL_AUTO_TRANSMIT;
4413 if (dcb->fInX) shf.FlowReplace |= SERIAL_AUTO_RECEIVE;
4414 shf.XonLimit = dcb->XonLim;
4415 shf.XoffLimit = dcb->XoffLim;
4416 sc.EofChar = dcb->EofChar;
4417 sc.ErrorChar = dcb->ErrorChar;
4418 sc.BreakChar = 0;
4419 sc.EventChar = dcb->EvtChar;
4420 sc.XonChar = dcb->XonChar;
4421 sc.XoffChar = dcb->XoffChar;
4423 /* note: change DTR/RTS lines after setting the comm attributes,
4424 * so flow control does not interfere.
4426 return (DeviceIoControl( handle, IOCTL_SERIAL_SET_BAUD_RATE, &sbr, sizeof(sbr), NULL, 0, NULL, NULL ) &&
4427 DeviceIoControl( handle, IOCTL_SERIAL_SET_LINE_CONTROL, &slc, sizeof(slc), NULL, 0, NULL, NULL ) &&
4428 DeviceIoControl( handle, IOCTL_SERIAL_SET_HANDFLOW, &shf, sizeof(shf), NULL, 0, NULL, NULL ) &&
4429 DeviceIoControl( handle, IOCTL_SERIAL_SET_CHARS, &sc, sizeof(sc), NULL, 0, NULL, NULL ));
4433 /*****************************************************************************
4434 * SetCommTimeouts (kernelbase.@)
4436 BOOL WINAPI DECLSPEC_HOTPATCH SetCommTimeouts( HANDLE handle, COMMTIMEOUTS *timeouts )
4438 if (!timeouts)
4440 SetLastError( ERROR_INVALID_PARAMETER );
4441 return FALSE;
4443 return DeviceIoControl( handle, IOCTL_SERIAL_SET_TIMEOUTS, timeouts, sizeof(*timeouts),
4444 NULL, 0, NULL, NULL );
4448 /*****************************************************************************
4449 * SetupComm (kernelbase.@)
4451 BOOL WINAPI DECLSPEC_HOTPATCH SetupComm( HANDLE handle, DWORD in_size, DWORD out_size )
4453 SERIAL_QUEUE_SIZE sqs;
4455 sqs.InSize = in_size;
4456 sqs.OutSize = out_size;
4457 return DeviceIoControl( handle, IOCTL_SERIAL_SET_QUEUE_SIZE, &sqs, sizeof(sqs), NULL, 0, NULL, NULL );
4461 /*****************************************************************************
4462 * TransmitCommChar (kernelbase.@)
4464 BOOL WINAPI DECLSPEC_HOTPATCH TransmitCommChar( HANDLE handle, CHAR ch )
4466 return DeviceIoControl( handle, IOCTL_SERIAL_IMMEDIATE_CHAR, &ch, sizeof(ch), NULL, 0, NULL, NULL );
4470 /***********************************************************************
4471 * WaitCommEvent (kernelbase.@)
4473 BOOL WINAPI DECLSPEC_HOTPATCH WaitCommEvent( HANDLE handle, DWORD *events, OVERLAPPED *overlapped )
4475 return DeviceIoControl( handle, IOCTL_SERIAL_WAIT_ON_MASK, NULL, 0, events, sizeof(*events),
4476 NULL, overlapped );