kernel32: Call registry functions with full key path.
[wine/multimedia.git] / dlls / kernel32 / path.c
blobff9422744ae5ecf579ad77ee829cec6b800d331d
1 /*
2 * File handling functions
4 * Copyright 1993 Erik Bos
5 * Copyright 1996, 2004 Alexandre Julliard
6 * Copyright 2003 Eric Pouech
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
24 #include "config.h"
25 #include "wine/port.h"
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdarg.h>
31 #include "winerror.h"
32 #include "ntstatus.h"
33 #define WIN32_NO_STATUS
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winternl.h"
38 #include "kernel_private.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(file);
44 #define MAX_PATHNAME_LEN 1024
47 /* check if a file name is for an executable file (.exe or .com) */
48 static inline BOOL is_executable( const WCHAR *name )
50 static const WCHAR exeW[] = {'.','e','x','e',0};
51 static const WCHAR comW[] = {'.','c','o','m',0};
52 int len = strlenW(name);
54 if (len < 4) return FALSE;
55 return (!strcmpiW( name + len - 4, exeW ) || !strcmpiW( name + len - 4, comW ));
58 /***********************************************************************
59 * copy_filename_WtoA
61 * copy a file name back to OEM/Ansi, but only if the buffer is large enough
63 static DWORD copy_filename_WtoA( LPCWSTR nameW, LPSTR buffer, DWORD len )
65 UNICODE_STRING strW;
66 DWORD ret;
67 BOOL is_ansi = AreFileApisANSI();
69 RtlInitUnicodeString( &strW, nameW );
71 ret = is_ansi ? RtlUnicodeStringToAnsiSize(&strW) : RtlUnicodeStringToOemSize(&strW);
72 if (buffer && ret <= len)
74 ANSI_STRING str;
76 str.Buffer = buffer;
77 str.MaximumLength = min( len, UNICODE_STRING_MAX_CHARS );
78 if (is_ansi)
79 RtlUnicodeStringToAnsiString( &str, &strW, FALSE );
80 else
81 RtlUnicodeStringToOemString( &str, &strW, FALSE );
82 ret = str.Length; /* length without terminating 0 */
84 return ret;
87 /***********************************************************************
88 * add_boot_rename_entry
90 * Adds an entry to the registry that is loaded when windows boots and
91 * checks if there are some files to be removed or renamed/moved.
92 * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
93 * non-NULL then the file is moved, otherwise it is deleted. The
94 * entry of the registry key is always appended with two zero
95 * terminated strings. If <fn2> is NULL then the second entry is
96 * simply a single 0-byte. Otherwise the second filename goes
97 * there. The entries are prepended with \??\ before the path and the
98 * second filename gets also a '!' as the first character if
99 * MOVEFILE_REPLACE_EXISTING is set. After the final string another
100 * 0-byte follows to indicate the end of the strings.
101 * i.e.:
102 * \??\D:\test\file1[0]
103 * !\??\D:\test\file1_renamed[0]
104 * \??\D:\Test|delete[0]
105 * [0] <- file is to be deleted, second string empty
106 * \??\D:\test\file2[0]
107 * !\??\D:\test\file2_renamed[0]
108 * [0] <- indicates end of strings
110 * or:
111 * \??\D:\test\file1[0]
112 * !\??\D:\test\file1_renamed[0]
113 * \??\D:\Test|delete[0]
114 * [0] <- file is to be deleted, second string empty
115 * [0] <- indicates end of strings
118 static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
120 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
121 'F','i','l','e','R','e','n','a','m','e',
122 'O','p','e','r','a','t','i','o','n','s',0};
123 static const WCHAR SessionW[] = {'\\','R','e','g','i','s','t','r','y','\\',
124 'M','a','c','h','i','n','e','\\',
125 'S','y','s','t','e','m','\\',
126 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
127 'C','o','n','t','r','o','l','\\',
128 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
129 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
131 OBJECT_ATTRIBUTES attr;
132 UNICODE_STRING nameW, source_name, dest_name;
133 KEY_VALUE_PARTIAL_INFORMATION *info;
134 BOOL rc = FALSE;
135 HANDLE Reboot = 0;
136 DWORD len1, len2;
137 DWORD DataSize = 0;
138 BYTE *Buffer = NULL;
139 WCHAR *p;
141 if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
143 SetLastError( ERROR_PATH_NOT_FOUND );
144 return FALSE;
146 dest_name.Buffer = NULL;
147 if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
149 RtlFreeUnicodeString( &source_name );
150 SetLastError( ERROR_PATH_NOT_FOUND );
151 return FALSE;
154 attr.Length = sizeof(attr);
155 attr.RootDirectory = 0;
156 attr.ObjectName = &nameW;
157 attr.Attributes = 0;
158 attr.SecurityDescriptor = NULL;
159 attr.SecurityQualityOfService = NULL;
160 RtlInitUnicodeString( &nameW, SessionW );
162 if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
164 WARN("Error creating key for reboot management [%s]\n",
165 "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
166 RtlFreeUnicodeString( &source_name );
167 RtlFreeUnicodeString( &dest_name );
168 return FALSE;
171 len1 = source_name.Length + sizeof(WCHAR);
172 if (dest)
174 len2 = dest_name.Length + sizeof(WCHAR);
175 if (flags & MOVEFILE_REPLACE_EXISTING)
176 len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
178 else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
180 RtlInitUnicodeString( &nameW, ValueName );
182 /* First we check if the key exists and if so how many bytes it already contains. */
183 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
184 NULL, 0, &DataSize ) == STATUS_BUFFER_TOO_SMALL)
186 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
187 goto Quit;
188 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
189 Buffer, DataSize, &DataSize )) goto Quit;
190 info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
191 if (info->Type != REG_MULTI_SZ) goto Quit;
192 if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR); /* remove terminating null (will be added back later) */
194 else
196 DataSize = info_size;
197 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
198 goto Quit;
201 memcpy( Buffer + DataSize, source_name.Buffer, len1 );
202 DataSize += len1;
203 p = (WCHAR *)(Buffer + DataSize);
204 if (dest)
206 if (flags & MOVEFILE_REPLACE_EXISTING)
207 *p++ = '!';
208 memcpy( p, dest_name.Buffer, len2 );
209 DataSize += len2;
211 else
213 *p = 0;
214 DataSize += sizeof(WCHAR);
217 /* add final null */
218 p = (WCHAR *)(Buffer + DataSize);
219 *p = 0;
220 DataSize += sizeof(WCHAR);
222 rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
224 Quit:
225 RtlFreeUnicodeString( &source_name );
226 RtlFreeUnicodeString( &dest_name );
227 if (Reboot) NtClose(Reboot);
228 HeapFree( GetProcessHeap(), 0, Buffer );
229 return(rc);
233 /***********************************************************************
234 * GetFullPathNameW (KERNEL32.@)
235 * NOTES
236 * if the path closed with '\', *lastpart is 0
238 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
239 LPWSTR *lastpart )
241 return RtlGetFullPathName_U(name, len * sizeof(WCHAR), buffer, lastpart) / sizeof(WCHAR);
244 /***********************************************************************
245 * GetFullPathNameA (KERNEL32.@)
246 * NOTES
247 * if the path closed with '\', *lastpart is 0
249 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
250 LPSTR *lastpart )
252 WCHAR *nameW;
253 WCHAR bufferW[MAX_PATH], *lastpartW = NULL;
254 DWORD ret;
256 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
258 ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, &lastpartW);
260 if (!ret) return 0;
261 if (ret > MAX_PATH)
263 SetLastError(ERROR_FILENAME_EXCED_RANGE);
264 return 0;
266 ret = copy_filename_WtoA( bufferW, buffer, len );
267 if (ret < len && lastpart)
269 if (lastpartW)
270 *lastpart = buffer + FILE_name_WtoA( bufferW, lastpartW - bufferW, NULL, 0 );
271 else
272 *lastpart = NULL;
274 return ret;
278 /***********************************************************************
279 * GetLongPathNameW (KERNEL32.@)
281 * NOTES
282 * observed (Win2000):
283 * shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
284 * shortpath="": LastError=ERROR_PATH_NOT_FOUND, ret=0
286 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
288 WCHAR tmplongpath[MAX_PATHNAME_LEN];
289 LPCWSTR p;
290 DWORD sp = 0, lp = 0;
291 DWORD tmplen;
292 BOOL unixabsolute;
293 WIN32_FIND_DATAW wfd;
294 HANDLE goit;
296 if (!shortpath)
298 SetLastError(ERROR_INVALID_PARAMETER);
299 return 0;
301 if (!shortpath[0])
303 SetLastError(ERROR_PATH_NOT_FOUND);
304 return 0;
307 TRACE("%s,%p,%d\n", debugstr_w(shortpath), longpath, longlen);
309 if (shortpath[0] == '\\' && shortpath[1] == '\\')
311 FIXME("UNC pathname %s\n", debugstr_w(shortpath));
313 tmplen = strlenW(shortpath);
314 if (tmplen < longlen)
316 if (longpath != shortpath) strcpyW( longpath, shortpath );
317 return tmplen;
319 return tmplen + 1;
322 unixabsolute = (shortpath[0] == '/');
324 /* check for drive letter */
325 if (!unixabsolute && shortpath[1] == ':' )
327 tmplongpath[0] = shortpath[0];
328 tmplongpath[1] = ':';
329 lp = sp = 2;
332 while (shortpath[sp])
334 /* check for path delimiters and reproduce them */
335 if (shortpath[sp] == '\\' || shortpath[sp] == '/')
337 if (!lp || tmplongpath[lp-1] != '\\')
339 /* strip double "\\" */
340 tmplongpath[lp++] = '\\';
342 tmplongpath[lp] = 0; /* terminate string */
343 sp++;
344 continue;
347 p = shortpath + sp;
348 if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
350 tmplongpath[lp++] = *p++;
351 tmplongpath[lp++] = *p++;
353 for (; *p && *p != '/' && *p != '\\'; p++);
354 tmplen = p - (shortpath + sp);
355 lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
357 if (tmplongpath[lp] == '.')
359 if (tmplen == 1 || (tmplen == 2 && tmplongpath[lp + 1] == '.'))
361 lp += tmplen;
362 sp += tmplen;
363 continue;
367 /* Check if the file exists and use the existing file name */
368 goit = FindFirstFileW(tmplongpath, &wfd);
369 if (goit == INVALID_HANDLE_VALUE)
371 TRACE("not found %s!\n", debugstr_w(tmplongpath));
372 SetLastError ( ERROR_FILE_NOT_FOUND );
373 return 0;
375 FindClose(goit);
376 strcpyW(tmplongpath + lp, wfd.cFileName);
377 lp += strlenW(tmplongpath + lp);
378 sp += tmplen;
380 tmplen = strlenW(shortpath) - 1;
381 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
382 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
383 tmplongpath[lp++] = shortpath[tmplen];
384 tmplongpath[lp] = 0;
386 tmplen = strlenW(tmplongpath) + 1;
387 if (tmplen <= longlen)
389 strcpyW(longpath, tmplongpath);
390 TRACE("returning %s\n", debugstr_w(longpath));
391 tmplen--; /* length without 0 */
394 return tmplen;
397 /***********************************************************************
398 * GetLongPathNameA (KERNEL32.@)
400 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
402 WCHAR *shortpathW;
403 WCHAR longpathW[MAX_PATH];
404 DWORD ret;
406 TRACE("%s\n", debugstr_a(shortpath));
408 if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
410 ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
412 if (!ret) return 0;
413 if (ret > MAX_PATH)
415 SetLastError(ERROR_FILENAME_EXCED_RANGE);
416 return 0;
418 return copy_filename_WtoA( longpathW, longpath, longlen );
422 /***********************************************************************
423 * GetShortPathNameW (KERNEL32.@)
425 * NOTES
426 * observed:
427 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
428 * longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
430 * more observations ( with NT 3.51 (WinDD) ):
431 * longpath <= 8.3 -> just copy longpath to shortpath
432 * longpath > 8.3 ->
433 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
434 * b) file does exist -> set the short filename.
435 * - trailing slashes are reproduced in the short name, even if the
436 * file is not a directory
437 * - the absolute/relative path of the short name is reproduced like found
438 * in the long name
439 * - longpath and shortpath may have the same address
440 * Peter Ganten, 1999
442 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
444 WCHAR *tmpshortpath;
445 LPCWSTR p;
446 DWORD sp = 0, lp = 0;
447 DWORD tmplen, buf_len;
448 WIN32_FIND_DATAW wfd;
449 HANDLE goit;
451 TRACE("%s\n", debugstr_w(longpath));
453 if (!longpath)
455 SetLastError(ERROR_INVALID_PARAMETER);
456 return 0;
458 if (!longpath[0])
460 SetLastError(ERROR_BAD_PATHNAME);
461 return 0;
464 /* code below only removes characters from string, never adds, so this is
465 * the largest buffer that tmpshortpath will need to have */
466 buf_len = strlenW(longpath) + 1;
467 tmpshortpath = HeapAlloc(GetProcessHeap(), 0, buf_len * sizeof(WCHAR));
468 if (!tmpshortpath)
470 SetLastError(ERROR_OUTOFMEMORY);
471 return 0;
474 if (longpath[0] == '\\' && longpath[1] == '\\' && longpath[2] == '?' && longpath[3] == '\\')
476 memcpy(tmpshortpath, longpath, 4 * sizeof(WCHAR));
477 sp = lp = 4;
480 /* check for drive letter */
481 if (longpath[lp] != '/' && longpath[lp + 1] == ':' )
483 tmpshortpath[sp] = longpath[lp];
484 tmpshortpath[sp + 1] = ':';
485 sp += 2;
486 lp += 2;
489 while (longpath[lp])
491 /* check for path delimiters and reproduce them */
492 if (longpath[lp] == '\\' || longpath[lp] == '/')
494 if (!sp || tmpshortpath[sp-1] != '\\')
496 /* strip double "\\" */
497 tmpshortpath[sp] = '\\';
498 sp++;
500 tmpshortpath[sp] = 0; /* terminate string */
501 lp++;
502 continue;
505 p = longpath + lp;
506 if (lp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
508 tmpshortpath[sp++] = *p++;
509 tmpshortpath[sp++] = *p++;
510 lp += 2;
512 for (; *p && *p != '/' && *p != '\\'; p++);
513 tmplen = p - (longpath + lp);
514 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
516 if (tmpshortpath[sp] == '.')
518 if (tmplen == 1 || (tmplen == 2 && tmpshortpath[sp + 1] == '.'))
520 sp += tmplen;
521 lp += tmplen;
522 continue;
526 /* Check if the file exists and use the existing short file name */
527 goit = FindFirstFileW(tmpshortpath, &wfd);
528 if (goit == INVALID_HANDLE_VALUE) goto notfound;
529 FindClose(goit);
531 /* In rare cases (like "a.abcd") short path may be longer than original path.
532 * Make sure we have enough space in temp buffer. */
533 if (wfd.cAlternateFileName[0] && tmplen < strlenW(wfd.cAlternateFileName))
535 WCHAR *new_buf;
536 buf_len += strlenW(wfd.cAlternateFileName) - tmplen;
537 new_buf = HeapReAlloc(GetProcessHeap(), 0, tmpshortpath, buf_len * sizeof(WCHAR));
538 if(!new_buf)
540 HeapFree(GetProcessHeap(), 0, tmpshortpath);
541 SetLastError(ERROR_OUTOFMEMORY);
542 return 0;
544 tmpshortpath = new_buf;
547 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName);
548 sp += strlenW(tmpshortpath + sp);
549 lp += tmplen;
551 tmpshortpath[sp] = 0;
553 tmplen = strlenW(tmpshortpath) + 1;
554 if (tmplen <= shortlen)
556 strcpyW(shortpath, tmpshortpath);
557 TRACE("returning %s\n", debugstr_w(shortpath));
558 tmplen--; /* length without 0 */
561 HeapFree(GetProcessHeap(), 0, tmpshortpath);
562 return tmplen;
564 notfound:
565 HeapFree(GetProcessHeap(), 0, tmpshortpath);
566 TRACE("not found!\n" );
567 SetLastError ( ERROR_FILE_NOT_FOUND );
568 return 0;
571 /***********************************************************************
572 * GetShortPathNameA (KERNEL32.@)
574 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
576 WCHAR *longpathW;
577 WCHAR shortpathW[MAX_PATH];
578 DWORD ret;
580 TRACE("%s\n", debugstr_a(longpath));
582 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
584 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
586 if (!ret) return 0;
587 if (ret > MAX_PATH)
589 SetLastError(ERROR_FILENAME_EXCED_RANGE);
590 return 0;
592 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
596 /***********************************************************************
597 * GetTempPathA (KERNEL32.@)
599 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
601 WCHAR pathW[MAX_PATH];
602 UINT ret;
604 ret = GetTempPathW(MAX_PATH, pathW);
606 if (!ret)
607 return 0;
609 if (ret > MAX_PATH)
611 SetLastError(ERROR_FILENAME_EXCED_RANGE);
612 return 0;
614 return copy_filename_WtoA( pathW, path, count );
618 /***********************************************************************
619 * GetTempPathW (KERNEL32.@)
621 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
623 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
624 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
625 static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
626 WCHAR tmp_path[MAX_PATH];
627 UINT ret;
629 TRACE("%u,%p\n", count, path);
631 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
632 !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
633 !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
634 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
635 return 0;
637 if (ret > MAX_PATH)
639 SetLastError(ERROR_FILENAME_EXCED_RANGE);
640 return 0;
643 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
644 if (!ret) return 0;
646 if (ret > MAX_PATH - 2)
648 SetLastError(ERROR_FILENAME_EXCED_RANGE);
649 return 0;
652 if (tmp_path[ret-1] != '\\')
654 tmp_path[ret++] = '\\';
655 tmp_path[ret] = '\0';
658 ret++; /* add space for terminating 0 */
660 if (count >= ret)
662 lstrcpynW(path, tmp_path, count);
663 /* the remaining buffer must be zeroed up to 32766 bytes in XP or 32767
664 * bytes after it, we will assume the > XP behavior for now */
665 memset(path + ret, 0, (min(count, 32767) - ret) * sizeof(WCHAR));
666 ret--; /* return length without 0 */
668 else if (count)
670 /* the buffer must be cleared if contents will not fit */
671 memset(path, 0, count * sizeof(WCHAR));
674 TRACE("returning %u, %s\n", ret, debugstr_w(path));
675 return ret;
679 /***********************************************************************
680 * GetTempFileNameA (KERNEL32.@)
682 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
684 WCHAR *pathW, *prefixW = NULL;
685 WCHAR bufferW[MAX_PATH];
686 UINT ret;
688 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
689 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
691 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
692 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
694 HeapFree( GetProcessHeap(), 0, prefixW );
695 return ret;
698 /***********************************************************************
699 * GetTempFileNameW (KERNEL32.@)
701 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
703 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
705 int i;
706 LPWSTR p;
707 DWORD attr;
709 if ( !path || !buffer )
711 SetLastError( ERROR_INVALID_PARAMETER );
712 return 0;
715 /* ensure that the provided directory exists */
716 attr = GetFileAttributesW(path);
717 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
719 TRACE("path not found %s\n", debugstr_w(path));
720 SetLastError( ERROR_DIRECTORY );
721 return 0;
724 strcpyW( buffer, path );
725 p = buffer + strlenW(buffer);
727 /* add a \, if there isn't one */
728 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
730 if (prefix)
731 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
733 unique &= 0xffff;
735 if (unique) sprintfW( p, formatW, unique );
736 else
738 /* get a "random" unique number and try to create the file */
739 HANDLE handle;
740 UINT num = GetTickCount() & 0xffff;
741 static UINT last;
743 /* avoid using the same name twice in a short interval */
744 if (last - num < 10) num = last + 1;
745 if (!num) num = 1;
746 unique = num;
749 sprintfW( p, formatW, unique );
750 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
751 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
752 if (handle != INVALID_HANDLE_VALUE)
753 { /* We created it */
754 TRACE("created %s\n", debugstr_w(buffer) );
755 CloseHandle( handle );
756 last = unique;
757 break;
759 if (GetLastError() != ERROR_FILE_EXISTS &&
760 GetLastError() != ERROR_SHARING_VIOLATION)
761 break; /* No need to go on */
762 if (!(++unique & 0xffff)) unique = 1;
763 } while (unique != num);
766 TRACE("returning %s\n", debugstr_w(buffer) );
767 return unique;
771 /***********************************************************************
772 * contains_pathW
774 * Check if the file name contains a path; helper for SearchPathW.
775 * A relative path is not considered a path unless it starts with ./ or ../
777 static inline BOOL contains_pathW (LPCWSTR name)
779 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
780 if (name[0] != '.') return FALSE;
781 if (name[1] == '/' || name[1] == '\\') return TRUE;
782 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
785 /***********************************************************************
786 * find_actctx_dllpath
788 * Find the path (if any) of the dll from the activation context.
789 * Returned path doesn't include a name.
791 static NTSTATUS find_actctx_dllpath(const WCHAR *libname, WCHAR **path)
793 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
794 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
796 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
797 ACTCTX_SECTION_KEYED_DATA data;
798 UNICODE_STRING nameW;
799 NTSTATUS status;
800 SIZE_T needed, size = 1024;
801 WCHAR *p;
803 RtlInitUnicodeString( &nameW, libname );
804 data.cbSize = sizeof(data);
805 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
806 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
807 &nameW, &data );
808 if (status != STATUS_SUCCESS) return status;
810 for (;;)
812 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
814 status = STATUS_NO_MEMORY;
815 goto done;
817 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
818 AssemblyDetailedInformationInActivationContext,
819 info, size, &needed );
820 if (status == STATUS_SUCCESS) break;
821 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
822 HeapFree( GetProcessHeap(), 0, info );
823 size = needed;
824 /* restart with larger buffer */
827 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
829 status = STATUS_SXS_KEY_NOT_FOUND;
830 goto done;
833 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
835 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
837 p++;
838 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
840 /* manifest name does not match directory name, so it's not a global
841 * windows/winsxs manifest; use the manifest directory name instead */
842 dirlen = p - info->lpAssemblyManifestPath;
843 needed = (dirlen + 1) * sizeof(WCHAR);
844 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
846 status = STATUS_NO_MEMORY;
847 goto done;
849 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
850 *(p + dirlen) = 0;
851 goto done;
855 needed = (strlenW( DIR_Windows ) * sizeof(WCHAR) +
856 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + 2*sizeof(WCHAR));
858 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
860 status = STATUS_NO_MEMORY;
861 goto done;
863 strcpyW( p, DIR_Windows );
864 p += strlenW(p);
865 memcpy( p, winsxsW, sizeof(winsxsW) );
866 p += sizeof(winsxsW) / sizeof(WCHAR);
867 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
868 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
869 *p++ = '\\';
870 *p = 0;
871 done:
872 HeapFree( GetProcessHeap(), 0, info );
873 RtlReleaseActivationContext( data.hActCtx );
874 return status;
877 /***********************************************************************
878 * SearchPathW [KERNEL32.@]
880 * Searches for a specified file in the search path.
882 * PARAMS
883 * path [I] Path to search (NULL means default)
884 * name [I] Filename to search for.
885 * ext [I] File extension to append to file name. The first
886 * character must be a period. This parameter is
887 * specified only if the filename given does not
888 * contain an extension.
889 * buflen [I] size of buffer, in characters
890 * buffer [O] buffer for found filename
891 * lastpart [O] address of pointer to last used character in
892 * buffer (the final '\')
894 * RETURNS
895 * Success: length of string copied into buffer, not including
896 * terminating null character. If the filename found is
897 * longer than the length of the buffer, the length of the
898 * filename is returned.
899 * Failure: Zero
901 * NOTES
902 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
903 * (tested on NT 4.0)
905 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
906 LPWSTR buffer, LPWSTR *lastpart )
908 DWORD ret = 0;
910 if (!name || !name[0])
912 SetLastError(ERROR_INVALID_PARAMETER);
913 return 0;
916 /* If the name contains an explicit path, ignore the path */
918 if (contains_pathW(name))
920 /* try first without extension */
921 if (RtlDoesFileExists_U( name ))
922 return GetFullPathNameW( name, buflen, buffer, lastpart );
924 if (ext)
926 LPCWSTR p = strrchrW( name, '.' );
927 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
928 ext = NULL; /* Ignore the specified extension */
931 /* Allocate a buffer for the file name and extension */
932 if (ext)
934 LPWSTR tmp;
935 DWORD len = strlenW(name) + strlenW(ext);
937 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
939 SetLastError( ERROR_OUTOFMEMORY );
940 return 0;
942 strcpyW( tmp, name );
943 strcatW( tmp, ext );
944 if (RtlDoesFileExists_U( tmp ))
945 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
946 HeapFree( GetProcessHeap(), 0, tmp );
949 else if (path && path[0]) /* search in the specified path */
951 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
952 buffer, lastpart ) / sizeof(WCHAR);
954 else /* search in active context and default path */
956 WCHAR *dll_path = NULL, *search = NULL;
957 DWORD req_len, name_len;
959 req_len = name_len = strlenW(name);
961 if (strchrW( name, '.' )) ext = NULL;
962 if (ext)
964 DWORD ext_len = strlenW(ext);
966 req_len += ext_len;
967 name_len += ext_len;
969 search = HeapAlloc( GetProcessHeap(), 0, (name_len + ext_len + 1) * sizeof(WCHAR) );
970 if (!search)
972 SetLastError( ERROR_OUTOFMEMORY );
973 return 0;
975 strcpyW( search, name );
976 strcatW( search, ext );
977 name = search;
979 /* now that we have combined name we don't need extension any more */
982 /* When file is found with activation context no attempt is made
983 to check if it's really exist, path is returned only basing on context info. */
984 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
986 DWORD path_len;
988 path_len = strlenW(dll_path);
989 req_len += path_len;
991 if (lastpart) *lastpart = NULL;
993 /* count null termination char too */
994 if (req_len + 1 <= buflen)
996 memcpy( buffer, dll_path, path_len * sizeof(WCHAR) );
997 memcpy( &buffer[path_len], name, name_len * sizeof(WCHAR) );
998 buffer[req_len] = 0;
999 if (lastpart) *lastpart = buffer + path_len;
1000 ret = req_len;
1002 else
1003 ret = req_len + 1;
1005 HeapFree( GetProcessHeap(), 0, dll_path );
1006 HeapFree( GetProcessHeap(), 0, search );
1008 else
1010 if ((dll_path = MODULE_get_dll_load_path( NULL )))
1012 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
1013 buffer, lastpart ) / sizeof(WCHAR);
1014 HeapFree( GetProcessHeap(), 0, dll_path );
1015 HeapFree( GetProcessHeap(), 0, search );
1017 else
1019 SetLastError( ERROR_OUTOFMEMORY );
1020 return 0;
1025 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1026 else TRACE( "found %s\n", debugstr_w(buffer) );
1027 return ret;
1031 /***********************************************************************
1032 * SearchPathA (KERNEL32.@)
1034 * See SearchPathW.
1036 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
1037 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
1039 WCHAR *pathW = NULL, *nameW, *extW = NULL;
1040 WCHAR bufferW[MAX_PATH];
1041 DWORD ret;
1043 if (!name)
1045 SetLastError(ERROR_INVALID_PARAMETER);
1046 return 0;
1049 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
1050 if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
1052 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
1054 HeapFree( GetProcessHeap(), 0, pathW );
1055 return 0;
1058 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
1060 HeapFree( GetProcessHeap(), 0, pathW );
1061 HeapFree( GetProcessHeap(), 0, extW );
1063 if (!ret) return 0;
1064 if (ret > MAX_PATH)
1066 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1067 return 0;
1069 ret = copy_filename_WtoA( bufferW, buffer, buflen );
1070 if (buflen > ret && lastpart)
1071 *lastpart = strrchr(buffer, '\\') + 1;
1072 return ret;
1075 static BOOL is_same_file(HANDLE h1, HANDLE h2)
1077 int fd1;
1078 BOOL ret = FALSE;
1079 if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
1081 int fd2;
1082 if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
1084 struct stat stat1, stat2;
1085 if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
1086 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
1087 wine_server_release_fd(h2, fd2);
1089 wine_server_release_fd(h1, fd1);
1091 return ret;
1094 /**************************************************************************
1095 * CopyFileW (KERNEL32.@)
1097 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1099 return CopyFileExW( source, dest, NULL, NULL, NULL,
1100 fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
1104 /**************************************************************************
1105 * CopyFileA (KERNEL32.@)
1107 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1109 WCHAR *sourceW, *destW;
1110 BOOL ret;
1112 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1113 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1115 ret = CopyFileW( sourceW, destW, fail_if_exists );
1117 HeapFree( GetProcessHeap(), 0, destW );
1118 return ret;
1122 /**************************************************************************
1123 * CopyFileExW (KERNEL32.@)
1125 BOOL WINAPI CopyFileExW(LPCWSTR source, LPCWSTR dest,
1126 LPPROGRESS_ROUTINE progress, LPVOID param,
1127 LPBOOL cancel_ptr, DWORD flags)
1129 static const int buffer_size = 65536;
1130 HANDLE h1, h2;
1131 BY_HANDLE_FILE_INFORMATION info;
1132 DWORD count;
1133 BOOL ret = FALSE;
1134 char *buffer;
1136 if (!source || !dest)
1138 SetLastError(ERROR_INVALID_PARAMETER);
1139 return FALSE;
1141 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1143 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1144 return FALSE;
1147 TRACE("%s -> %s, %x\n", debugstr_w(source), debugstr_w(dest), flags);
1149 if ((h1 = CreateFileW(source, GENERIC_READ,
1150 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1151 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1153 WARN("Unable to open source %s\n", debugstr_w(source));
1154 HeapFree( GetProcessHeap(), 0, buffer );
1155 return FALSE;
1158 if (!GetFileInformationByHandle( h1, &info ))
1160 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1161 HeapFree( GetProcessHeap(), 0, buffer );
1162 CloseHandle( h1 );
1163 return FALSE;
1166 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
1168 BOOL same_file = FALSE;
1169 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1170 OPEN_EXISTING, 0, 0);
1171 if (h2 != INVALID_HANDLE_VALUE)
1173 same_file = is_same_file( h1, h2 );
1174 CloseHandle( h2 );
1176 if (same_file)
1178 HeapFree( GetProcessHeap(), 0, buffer );
1179 CloseHandle( h1 );
1180 SetLastError( ERROR_SHARING_VIOLATION );
1181 return FALSE;
1185 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1186 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
1187 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1189 WARN("Unable to open dest %s\n", debugstr_w(dest));
1190 HeapFree( GetProcessHeap(), 0, buffer );
1191 CloseHandle( h1 );
1192 return FALSE;
1195 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
1197 char *p = buffer;
1198 while (count != 0)
1200 DWORD res;
1201 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1202 p += res;
1203 count -= res;
1206 ret = TRUE;
1207 done:
1208 /* Maintain the timestamp of source file to destination file */
1209 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
1210 HeapFree( GetProcessHeap(), 0, buffer );
1211 CloseHandle( h1 );
1212 CloseHandle( h2 );
1213 return ret;
1217 /**************************************************************************
1218 * CopyFileExA (KERNEL32.@)
1220 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1221 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1222 LPBOOL cancelFlagPointer, DWORD copyFlags)
1224 WCHAR *sourceW, *destW;
1225 BOOL ret;
1227 /* can't use the TEB buffer since we may have a callback routine */
1228 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1229 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1231 HeapFree( GetProcessHeap(), 0, sourceW );
1232 return FALSE;
1234 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1235 cancelFlagPointer, copyFlags);
1236 HeapFree( GetProcessHeap(), 0, sourceW );
1237 HeapFree( GetProcessHeap(), 0, destW );
1238 return ret;
1242 /**************************************************************************
1243 * MoveFileWithProgressW (KERNEL32.@)
1245 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1246 LPPROGRESS_ROUTINE fnProgress,
1247 LPVOID param, DWORD flag )
1249 FILE_BASIC_INFORMATION info;
1250 UNICODE_STRING nt_name;
1251 OBJECT_ATTRIBUTES attr;
1252 IO_STATUS_BLOCK io;
1253 NTSTATUS status;
1254 HANDLE source_handle = 0, dest_handle;
1255 ANSI_STRING source_unix, dest_unix;
1257 TRACE("(%s,%s,%p,%p,%04x)\n",
1258 debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1260 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1261 return add_boot_rename_entry( source, dest, flag );
1263 if (!dest)
1264 return DeleteFileW( source );
1266 if (flag & MOVEFILE_WRITE_THROUGH)
1267 FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1269 /* check if we are allowed to rename the source */
1271 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1273 SetLastError( ERROR_PATH_NOT_FOUND );
1274 return FALSE;
1276 source_unix.Buffer = NULL;
1277 dest_unix.Buffer = NULL;
1278 attr.Length = sizeof(attr);
1279 attr.RootDirectory = 0;
1280 attr.Attributes = OBJ_CASE_INSENSITIVE;
1281 attr.ObjectName = &nt_name;
1282 attr.SecurityDescriptor = NULL;
1283 attr.SecurityQualityOfService = NULL;
1285 status = NtOpenFile( &source_handle, SYNCHRONIZE, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1286 if (status == STATUS_SUCCESS)
1287 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1288 RtlFreeUnicodeString( &nt_name );
1289 if (status != STATUS_SUCCESS)
1291 SetLastError( RtlNtStatusToDosError(status) );
1292 goto error;
1294 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1295 if (status != STATUS_SUCCESS)
1297 SetLastError( RtlNtStatusToDosError(status) );
1298 goto error;
1301 /* we must have write access to the destination, and it must */
1302 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1304 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1306 SetLastError( ERROR_PATH_NOT_FOUND );
1307 goto error;
1309 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, &attr, &io, 0,
1310 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1311 if (status == STATUS_SUCCESS) /* destination exists */
1313 NtClose( dest_handle );
1314 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1316 SetLastError( ERROR_ALREADY_EXISTS );
1317 RtlFreeUnicodeString( &nt_name );
1318 goto error;
1320 else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1322 SetLastError( ERROR_ACCESS_DENIED );
1323 goto error;
1326 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1328 SetLastError( RtlNtStatusToDosError(status) );
1329 RtlFreeUnicodeString( &nt_name );
1330 goto error;
1333 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1334 RtlFreeUnicodeString( &nt_name );
1335 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1337 SetLastError( RtlNtStatusToDosError(status) );
1338 goto error;
1341 /* now perform the rename */
1343 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1345 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1347 NtClose( source_handle );
1348 RtlFreeAnsiString( &source_unix );
1349 RtlFreeAnsiString( &dest_unix );
1350 if (!CopyFileExW( source, dest, fnProgress,
1351 param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1352 return FALSE;
1353 return DeleteFileW( source );
1355 FILE_SetDosError();
1356 /* if we created the destination, remove it */
1357 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1358 goto error;
1361 /* fixup executable permissions */
1363 if (is_executable( source ) != is_executable( dest ))
1365 struct stat fstat;
1366 if (stat( dest_unix.Buffer, &fstat ) != -1)
1368 if (is_executable( dest ))
1369 /* set executable bit where read bit is set */
1370 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1371 else
1372 fstat.st_mode &= ~0111;
1373 chmod( dest_unix.Buffer, fstat.st_mode );
1377 NtClose( source_handle );
1378 RtlFreeAnsiString( &source_unix );
1379 RtlFreeAnsiString( &dest_unix );
1380 return TRUE;
1382 error:
1383 if (source_handle) NtClose( source_handle );
1384 RtlFreeAnsiString( &source_unix );
1385 RtlFreeAnsiString( &dest_unix );
1386 return FALSE;
1389 /**************************************************************************
1390 * MoveFileWithProgressA (KERNEL32.@)
1392 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1393 LPPROGRESS_ROUTINE fnProgress,
1394 LPVOID param, DWORD flag )
1396 WCHAR *sourceW, *destW;
1397 BOOL ret;
1399 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1400 if (dest)
1402 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1404 else
1405 destW = NULL;
1407 ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1408 HeapFree( GetProcessHeap(), 0, destW );
1409 return ret;
1412 /**************************************************************************
1413 * MoveFileExW (KERNEL32.@)
1415 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1417 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1420 /**************************************************************************
1421 * MoveFileExA (KERNEL32.@)
1423 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1425 return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1429 /**************************************************************************
1430 * MoveFileW (KERNEL32.@)
1432 * Move file or directory
1434 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1436 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1440 /**************************************************************************
1441 * MoveFileA (KERNEL32.@)
1443 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1445 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1449 /*************************************************************************
1450 * CreateHardLinkW (KERNEL32.@)
1452 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1453 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1455 NTSTATUS status;
1456 UNICODE_STRING ntDest, ntSource;
1457 ANSI_STRING unixDest, unixSource;
1458 BOOL ret = FALSE;
1460 TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1461 debugstr_w(lpExistingFileName), lpSecurityAttributes);
1463 ntDest.Buffer = ntSource.Buffer = NULL;
1464 if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1465 !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1467 SetLastError( ERROR_PATH_NOT_FOUND );
1468 goto err;
1471 unixSource.Buffer = unixDest.Buffer = NULL;
1472 status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1473 if (!status)
1475 status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1476 if (!status) /* destination must not exist */
1478 status = STATUS_OBJECT_NAME_EXISTS;
1479 } else if (status == STATUS_NO_SUCH_FILE)
1481 status = STATUS_SUCCESS;
1485 if (status)
1486 SetLastError( RtlNtStatusToDosError(status) );
1487 else if (!link( unixSource.Buffer, unixDest.Buffer ))
1489 TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1490 debugstr_a( unixSource.Buffer ));
1491 ret = TRUE;
1493 else
1494 FILE_SetDosError();
1496 RtlFreeAnsiString( &unixSource );
1497 RtlFreeAnsiString( &unixDest );
1499 err:
1500 RtlFreeUnicodeString( &ntSource );
1501 RtlFreeUnicodeString( &ntDest );
1502 return ret;
1506 /*************************************************************************
1507 * CreateHardLinkA (KERNEL32.@)
1509 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1510 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1512 WCHAR *sourceW, *destW;
1513 BOOL res;
1515 if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1517 return FALSE;
1519 if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1521 HeapFree( GetProcessHeap(), 0, sourceW );
1522 return FALSE;
1525 res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1527 HeapFree( GetProcessHeap(), 0, sourceW );
1528 HeapFree( GetProcessHeap(), 0, destW );
1530 return res;
1534 /***********************************************************************
1535 * CreateDirectoryW (KERNEL32.@)
1536 * RETURNS:
1537 * TRUE : success
1538 * FALSE : failure
1539 * ERROR_DISK_FULL: on full disk
1540 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1541 * ERROR_ACCESS_DENIED: on permission problems
1542 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1544 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1546 OBJECT_ATTRIBUTES attr;
1547 UNICODE_STRING nt_name;
1548 IO_STATUS_BLOCK io;
1549 NTSTATUS status;
1550 HANDLE handle;
1551 BOOL ret = FALSE;
1553 TRACE( "%s\n", debugstr_w(path) );
1555 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1557 SetLastError( ERROR_PATH_NOT_FOUND );
1558 return FALSE;
1560 attr.Length = sizeof(attr);
1561 attr.RootDirectory = 0;
1562 attr.Attributes = OBJ_CASE_INSENSITIVE;
1563 attr.ObjectName = &nt_name;
1564 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1565 attr.SecurityQualityOfService = NULL;
1567 status = NtCreateFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io, NULL,
1568 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1569 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1571 if (status == STATUS_SUCCESS)
1573 NtClose( handle );
1574 ret = TRUE;
1576 else SetLastError( RtlNtStatusToDosError(status) );
1578 RtlFreeUnicodeString( &nt_name );
1579 return ret;
1583 /***********************************************************************
1584 * CreateDirectoryA (KERNEL32.@)
1586 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1588 WCHAR *pathW;
1590 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1591 return CreateDirectoryW( pathW, sa );
1595 /***********************************************************************
1596 * CreateDirectoryExA (KERNEL32.@)
1598 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1600 WCHAR *pathW, *templateW = NULL;
1601 BOOL ret;
1603 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1604 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1606 ret = CreateDirectoryExW( templateW, pathW, sa );
1607 HeapFree( GetProcessHeap(), 0, templateW );
1608 return ret;
1612 /***********************************************************************
1613 * CreateDirectoryExW (KERNEL32.@)
1615 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1617 return CreateDirectoryW( path, sa );
1621 /***********************************************************************
1622 * RemoveDirectoryW (KERNEL32.@)
1624 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1626 OBJECT_ATTRIBUTES attr;
1627 UNICODE_STRING nt_name;
1628 ANSI_STRING unix_name;
1629 IO_STATUS_BLOCK io;
1630 NTSTATUS status;
1631 HANDLE handle;
1632 BOOL ret = FALSE;
1634 TRACE( "%s\n", debugstr_w(path) );
1636 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1638 SetLastError( ERROR_PATH_NOT_FOUND );
1639 return FALSE;
1641 attr.Length = sizeof(attr);
1642 attr.RootDirectory = 0;
1643 attr.Attributes = OBJ_CASE_INSENSITIVE;
1644 attr.ObjectName = &nt_name;
1645 attr.SecurityDescriptor = NULL;
1646 attr.SecurityQualityOfService = NULL;
1648 status = NtOpenFile( &handle, DELETE | SYNCHRONIZE, &attr, &io,
1649 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1650 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1651 if (status == STATUS_SUCCESS)
1652 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1653 RtlFreeUnicodeString( &nt_name );
1655 if (status != STATUS_SUCCESS)
1657 SetLastError( RtlNtStatusToDosError(status) );
1658 return FALSE;
1661 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1662 RtlFreeAnsiString( &unix_name );
1663 NtClose( handle );
1664 return ret;
1668 /***********************************************************************
1669 * RemoveDirectoryA (KERNEL32.@)
1671 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1673 WCHAR *pathW;
1675 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1676 return RemoveDirectoryW( pathW );
1680 /***********************************************************************
1681 * GetCurrentDirectoryW (KERNEL32.@)
1683 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1685 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1689 /***********************************************************************
1690 * GetCurrentDirectoryA (KERNEL32.@)
1692 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1694 WCHAR bufferW[MAX_PATH];
1695 DWORD ret;
1697 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1699 /* Win9x catches access violations here, returning zero.
1700 * This behaviour resulted in some people not noticing
1701 * that they got the argument order wrong. So let's be
1702 * nice and fail gracefully if buf is invalid and looks
1703 * more like a buflen. */
1704 SetLastError(ERROR_INVALID_PARAMETER);
1705 return 0;
1708 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1709 if (!ret) return 0;
1710 if (ret > sizeof(bufferW))
1712 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1713 return 0;
1715 return copy_filename_WtoA( bufferW, buf, buflen );
1719 /***********************************************************************
1720 * SetCurrentDirectoryW (KERNEL32.@)
1722 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1724 UNICODE_STRING dirW;
1725 NTSTATUS status;
1727 RtlInitUnicodeString( &dirW, dir );
1728 status = RtlSetCurrentDirectory_U( &dirW );
1729 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1730 return !status;
1734 /***********************************************************************
1735 * SetCurrentDirectoryA (KERNEL32.@)
1737 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1739 WCHAR *dirW;
1740 UNICODE_STRING strW;
1741 NTSTATUS status;
1743 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1744 RtlInitUnicodeString( &strW, dirW );
1745 status = RtlSetCurrentDirectory_U( &strW );
1746 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1747 return !status;
1751 /***********************************************************************
1752 * GetWindowsDirectoryW (KERNEL32.@)
1754 * See comment for GetWindowsDirectoryA.
1756 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1758 UINT len = strlenW( DIR_Windows ) + 1;
1759 if (path && count >= len)
1761 strcpyW( path, DIR_Windows );
1762 len--;
1764 return len;
1768 /***********************************************************************
1769 * GetWindowsDirectoryA (KERNEL32.@)
1771 * Return value:
1772 * If buffer is large enough to hold full path and terminating '\0' character
1773 * function copies path to buffer and returns length of the path without '\0'.
1774 * Otherwise function returns required size including '\0' character and
1775 * does not touch the buffer.
1777 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1779 return copy_filename_WtoA( DIR_Windows, path, count );
1783 /***********************************************************************
1784 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1786 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1788 return GetWindowsDirectoryA( path, count );
1792 /***********************************************************************
1793 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1795 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1797 return GetWindowsDirectoryW( path, count );
1801 /***********************************************************************
1802 * GetSystemDirectoryW (KERNEL32.@)
1804 * See comment for GetWindowsDirectoryA.
1806 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1808 UINT len = strlenW( DIR_System ) + 1;
1809 if (path && count >= len)
1811 strcpyW( path, DIR_System );
1812 len--;
1814 return len;
1818 /***********************************************************************
1819 * GetSystemDirectoryA (KERNEL32.@)
1821 * See comment for GetWindowsDirectoryA.
1823 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1825 return copy_filename_WtoA( DIR_System, path, count );
1829 /***********************************************************************
1830 * GetSystemWow64DirectoryW (KERNEL32.@)
1832 * As seen on MSDN
1833 * - On Win32 we should return ERROR_CALL_NOT_IMPLEMENTED
1834 * - On Win64 we should return the SysWow64 (system64) directory
1836 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1838 UINT len;
1840 if (!DIR_SysWow64)
1842 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1843 return 0;
1845 len = strlenW( DIR_SysWow64 ) + 1;
1846 if (path && count >= len)
1848 strcpyW( path, DIR_SysWow64 );
1849 len--;
1851 return len;
1855 /***********************************************************************
1856 * GetSystemWow64DirectoryA (KERNEL32.@)
1858 * See comment for GetWindowsWow64DirectoryW.
1860 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1862 if (!DIR_SysWow64)
1864 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1865 return 0;
1867 return copy_filename_WtoA( DIR_SysWow64, path, count );
1871 /***********************************************************************
1872 * Wow64EnableWow64FsRedirection (KERNEL32.@)
1874 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1876 NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1877 if (status) SetLastError( RtlNtStatusToDosError(status) );
1878 return !status;
1882 /***********************************************************************
1883 * Wow64DisableWow64FsRedirection (KERNEL32.@)
1885 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1887 NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1888 if (status) SetLastError( RtlNtStatusToDosError(status) );
1889 return !status;
1893 /***********************************************************************
1894 * Wow64RevertWow64FsRedirection (KERNEL32.@)
1896 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1898 NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1899 if (status) SetLastError( RtlNtStatusToDosError(status) );
1900 return !status;
1904 /***********************************************************************
1905 * NeedCurrentDirectoryForExePathW (KERNEL32.@)
1907 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1909 static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1910 'C','u','r','r','e','n','t',
1911 'D','i','r','e','c','t','o','r','y',
1912 'I','n','E','x','e','P','a','t','h',0};
1913 WCHAR env_val;
1915 /* MSDN mentions some 'registry location'. We do not use registry. */
1916 FIXME("(%s): partial stub\n", debugstr_w(name));
1918 if (strchrW(name, '\\'))
1919 return TRUE;
1921 /* Check the existence of the variable, not value */
1922 if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1923 return TRUE;
1925 return FALSE;
1929 /***********************************************************************
1930 * NeedCurrentDirectoryForExePathA (KERNEL32.@)
1932 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1934 WCHAR *nameW;
1936 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1937 return NeedCurrentDirectoryForExePathW( nameW );
1941 /***********************************************************************
1942 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1944 * Return the full Unix file name for a given path.
1945 * Returned buffer must be freed by caller.
1947 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1949 UNICODE_STRING nt_name;
1950 ANSI_STRING unix_name;
1951 NTSTATUS status;
1953 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1954 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1955 RtlFreeUnicodeString( &nt_name );
1956 if (status && status != STATUS_NO_SUCH_FILE)
1958 SetLastError( RtlNtStatusToDosError( status ) );
1959 return NULL;
1961 return unix_name.Buffer;
1965 /***********************************************************************
1966 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1968 * Return the full DOS file name for a given Unix path.
1969 * Returned buffer must be freed by caller.
1971 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1973 UNICODE_STRING nt_name;
1974 ANSI_STRING unix_name;
1975 NTSTATUS status;
1976 DWORD len;
1978 RtlInitAnsiString( &unix_name, str );
1979 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1980 if (status)
1982 SetLastError( RtlNtStatusToDosError( status ) );
1983 return NULL;
1985 if (nt_name.Buffer[5] == ':')
1987 /* get rid of the \??\ prefix */
1988 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1989 len = nt_name.Length - 4 * sizeof(WCHAR);
1990 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1991 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1993 else
1994 nt_name.Buffer[1] = '\\';
1995 return nt_name.Buffer;
1998 /*************************************************************************
1999 * CreateSymbolicLinkW (KERNEL32.@)
2001 BOOLEAN WINAPI CreateSymbolicLinkW(LPCWSTR link, LPCWSTR target, DWORD flags)
2003 FIXME("(%s %s %d): stub\n", debugstr_w(link), debugstr_w(target), flags);
2004 return TRUE;
2007 /*************************************************************************
2008 * CreateSymbolicLinkA (KERNEL32.@)
2010 BOOLEAN WINAPI CreateSymbolicLinkA(LPCSTR link, LPCSTR target, DWORD flags)
2012 FIXME("(%s %s %d): stub\n", debugstr_a(link), debugstr_a(target), flags);
2013 return TRUE;
2016 /*************************************************************************
2017 * CreateHardLinkTransactedA (KERNEL32.@)
2019 BOOL WINAPI CreateHardLinkTransactedA(LPCSTR link, LPCSTR target, LPSECURITY_ATTRIBUTES sa, HANDLE transaction)
2021 FIXME("(%s %s %p %p): stub\n", debugstr_a(link), debugstr_a(target), sa, transaction);
2022 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2023 return FALSE;
2026 /*************************************************************************
2027 * CreateHardLinkTransactedW (KERNEL32.@)
2029 BOOL WINAPI CreateHardLinkTransactedW(LPCWSTR link, LPCWSTR target, LPSECURITY_ATTRIBUTES sa, HANDLE transaction)
2031 FIXME("(%s %s %p %p): stub\n", debugstr_w(link), debugstr_w(target), sa, transaction);
2032 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2033 return FALSE;
2036 /*************************************************************************
2037 * CheckNameLegalDOS8Dot3A (KERNEL32.@)
2039 BOOL WINAPI CheckNameLegalDOS8Dot3A(const char *name, char *oemname, DWORD oemname_len,
2040 BOOL *contains_spaces, BOOL *is_legal)
2042 WCHAR *nameW;
2044 TRACE("(%s %p %u %p %p)\n", name, oemname,
2045 oemname_len, contains_spaces, is_legal);
2047 if (!name || !is_legal)
2048 return FALSE;
2050 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2052 return CheckNameLegalDOS8Dot3W( nameW, oemname, oemname_len, contains_spaces, is_legal );
2055 /*************************************************************************
2056 * CheckNameLegalDOS8Dot3W (KERNEL32.@)
2058 BOOL WINAPI CheckNameLegalDOS8Dot3W(const WCHAR *name, char *oemname, DWORD oemname_len,
2059 BOOL *contains_spaces_ret, BOOL *is_legal)
2061 OEM_STRING oem_str;
2062 UNICODE_STRING nameW;
2063 BOOLEAN contains_spaces;
2065 TRACE("(%s %p %u %p %p)\n", wine_dbgstr_w(name), oemname,
2066 oemname_len, contains_spaces_ret, is_legal);
2068 if (!name || !is_legal)
2069 return FALSE;
2071 RtlInitUnicodeString( &nameW, name );
2073 if (oemname) {
2074 oem_str.Length = oemname_len;
2075 oem_str.MaximumLength = oemname_len;
2076 oem_str.Buffer = oemname;
2079 *is_legal = RtlIsNameLegalDOS8Dot3( &nameW, oemname ? &oem_str : NULL, &contains_spaces );
2080 if (contains_spaces_ret) *contains_spaces_ret = contains_spaces;
2082 return TRUE;