oleaut32/tests: Add a test to show that support for coercion to arrays of variants...
[wine/multimedia.git] / dlls / kernel32 / path.c
blob09b8b7f7c59c82487712ce6cdd005470d246c616
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[] = {'M','a','c','h','i','n','e','\\',
124 'S','y','s','t','e','m','\\',
125 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
126 'C','o','n','t','r','o','l','\\',
127 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
128 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
130 OBJECT_ATTRIBUTES attr;
131 UNICODE_STRING nameW, source_name, dest_name;
132 KEY_VALUE_PARTIAL_INFORMATION *info;
133 BOOL rc = FALSE;
134 HANDLE Reboot = 0;
135 DWORD len1, len2;
136 DWORD DataSize = 0;
137 BYTE *Buffer = NULL;
138 WCHAR *p;
140 if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
142 SetLastError( ERROR_PATH_NOT_FOUND );
143 return FALSE;
145 dest_name.Buffer = NULL;
146 if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
148 RtlFreeUnicodeString( &source_name );
149 SetLastError( ERROR_PATH_NOT_FOUND );
150 return FALSE;
153 attr.Length = sizeof(attr);
154 attr.RootDirectory = 0;
155 attr.ObjectName = &nameW;
156 attr.Attributes = 0;
157 attr.SecurityDescriptor = NULL;
158 attr.SecurityQualityOfService = NULL;
159 RtlInitUnicodeString( &nameW, SessionW );
161 if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
163 WARN("Error creating key for reboot management [%s]\n",
164 "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
165 RtlFreeUnicodeString( &source_name );
166 RtlFreeUnicodeString( &dest_name );
167 return FALSE;
170 len1 = source_name.Length + sizeof(WCHAR);
171 if (dest)
173 len2 = dest_name.Length + sizeof(WCHAR);
174 if (flags & MOVEFILE_REPLACE_EXISTING)
175 len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
177 else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
179 RtlInitUnicodeString( &nameW, ValueName );
181 /* First we check if the key exists and if so how many bytes it already contains. */
182 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
183 NULL, 0, &DataSize ) == STATUS_BUFFER_TOO_SMALL)
185 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
186 goto Quit;
187 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
188 Buffer, DataSize, &DataSize )) goto Quit;
189 info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
190 if (info->Type != REG_MULTI_SZ) goto Quit;
191 if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR); /* remove terminating null (will be added back later) */
193 else
195 DataSize = info_size;
196 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
197 goto Quit;
200 memcpy( Buffer + DataSize, source_name.Buffer, len1 );
201 DataSize += len1;
202 p = (WCHAR *)(Buffer + DataSize);
203 if (dest)
205 if (flags & MOVEFILE_REPLACE_EXISTING)
206 *p++ = '!';
207 memcpy( p, dest_name.Buffer, len2 );
208 DataSize += len2;
210 else
212 *p = 0;
213 DataSize += sizeof(WCHAR);
216 /* add final null */
217 p = (WCHAR *)(Buffer + DataSize);
218 *p = 0;
219 DataSize += sizeof(WCHAR);
221 rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
223 Quit:
224 RtlFreeUnicodeString( &source_name );
225 RtlFreeUnicodeString( &dest_name );
226 if (Reboot) NtClose(Reboot);
227 HeapFree( GetProcessHeap(), 0, Buffer );
228 return(rc);
232 /***********************************************************************
233 * GetFullPathNameW (KERNEL32.@)
234 * NOTES
235 * if the path closed with '\', *lastpart is 0
237 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
238 LPWSTR *lastpart )
240 return RtlGetFullPathName_U(name, len * sizeof(WCHAR), buffer, lastpart) / sizeof(WCHAR);
243 /***********************************************************************
244 * GetFullPathNameA (KERNEL32.@)
245 * NOTES
246 * if the path closed with '\', *lastpart is 0
248 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
249 LPSTR *lastpart )
251 WCHAR *nameW;
252 WCHAR bufferW[MAX_PATH], *lastpartW = NULL;
253 DWORD ret;
255 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
257 ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, &lastpartW);
259 if (!ret) return 0;
260 if (ret > MAX_PATH)
262 SetLastError(ERROR_FILENAME_EXCED_RANGE);
263 return 0;
265 ret = copy_filename_WtoA( bufferW, buffer, len );
266 if (ret < len && lastpart)
268 if (lastpartW)
269 *lastpart = buffer + FILE_name_WtoA( bufferW, lastpartW - bufferW, NULL, 0 );
270 else
271 *lastpart = NULL;
273 return ret;
277 /***********************************************************************
278 * GetLongPathNameW (KERNEL32.@)
280 * NOTES
281 * observed (Win2000):
282 * shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
283 * shortpath="": LastError=ERROR_PATH_NOT_FOUND, ret=0
285 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
287 WCHAR tmplongpath[MAX_PATHNAME_LEN];
288 LPCWSTR p;
289 DWORD sp = 0, lp = 0;
290 DWORD tmplen;
291 BOOL unixabsolute;
292 WIN32_FIND_DATAW wfd;
293 HANDLE goit;
295 if (!shortpath)
297 SetLastError(ERROR_INVALID_PARAMETER);
298 return 0;
300 if (!shortpath[0])
302 SetLastError(ERROR_PATH_NOT_FOUND);
303 return 0;
306 TRACE("%s,%p,%d\n", debugstr_w(shortpath), longpath, longlen);
308 if (shortpath[0] == '\\' && shortpath[1] == '\\')
310 FIXME("UNC pathname %s\n", debugstr_w(shortpath));
312 tmplen = strlenW(shortpath);
313 if (tmplen < longlen)
315 if (longpath != shortpath) strcpyW( longpath, shortpath );
316 return tmplen;
318 return tmplen + 1;
321 unixabsolute = (shortpath[0] == '/');
323 /* check for drive letter */
324 if (!unixabsolute && shortpath[1] == ':' )
326 tmplongpath[0] = shortpath[0];
327 tmplongpath[1] = ':';
328 lp = sp = 2;
331 while (shortpath[sp])
333 /* check for path delimiters and reproduce them */
334 if (shortpath[sp] == '\\' || shortpath[sp] == '/')
336 if (!lp || tmplongpath[lp-1] != '\\')
338 /* strip double "\\" */
339 tmplongpath[lp++] = '\\';
341 tmplongpath[lp] = 0; /* terminate string */
342 sp++;
343 continue;
346 p = shortpath + sp;
347 if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
349 tmplongpath[lp++] = *p++;
350 tmplongpath[lp++] = *p++;
352 for (; *p && *p != '/' && *p != '\\'; p++);
353 tmplen = p - (shortpath + sp);
354 lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
356 if (tmplongpath[lp] == '.')
358 if (tmplen == 1 || (tmplen == 2 && tmplongpath[lp + 1] == '.'))
360 lp += tmplen;
361 sp += tmplen;
362 continue;
366 /* Check if the file exists and use the existing file name */
367 goit = FindFirstFileW(tmplongpath, &wfd);
368 if (goit == INVALID_HANDLE_VALUE)
370 TRACE("not found %s!\n", debugstr_w(tmplongpath));
371 SetLastError ( ERROR_FILE_NOT_FOUND );
372 return 0;
374 FindClose(goit);
375 strcpyW(tmplongpath + lp, wfd.cFileName);
376 lp += strlenW(tmplongpath + lp);
377 sp += tmplen;
379 tmplen = strlenW(shortpath) - 1;
380 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
381 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
382 tmplongpath[lp++] = shortpath[tmplen];
383 tmplongpath[lp] = 0;
385 tmplen = strlenW(tmplongpath) + 1;
386 if (tmplen <= longlen)
388 strcpyW(longpath, tmplongpath);
389 TRACE("returning %s\n", debugstr_w(longpath));
390 tmplen--; /* length without 0 */
393 return tmplen;
396 /***********************************************************************
397 * GetLongPathNameA (KERNEL32.@)
399 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
401 WCHAR *shortpathW;
402 WCHAR longpathW[MAX_PATH];
403 DWORD ret;
405 TRACE("%s\n", debugstr_a(shortpath));
407 if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
409 ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
411 if (!ret) return 0;
412 if (ret > MAX_PATH)
414 SetLastError(ERROR_FILENAME_EXCED_RANGE);
415 return 0;
417 return copy_filename_WtoA( longpathW, longpath, longlen );
421 /***********************************************************************
422 * GetShortPathNameW (KERNEL32.@)
424 * NOTES
425 * observed:
426 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
427 * longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
429 * more observations ( with NT 3.51 (WinDD) ):
430 * longpath <= 8.3 -> just copy longpath to shortpath
431 * longpath > 8.3 ->
432 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
433 * b) file does exist -> set the short filename.
434 * - trailing slashes are reproduced in the short name, even if the
435 * file is not a directory
436 * - the absolute/relative path of the short name is reproduced like found
437 * in the long name
438 * - longpath and shortpath may have the same address
439 * Peter Ganten, 1999
441 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
443 WCHAR *tmpshortpath;
444 LPCWSTR p;
445 DWORD sp = 0, lp = 0;
446 DWORD tmplen, buf_len;
447 WIN32_FIND_DATAW wfd;
448 HANDLE goit;
450 TRACE("%s\n", debugstr_w(longpath));
452 if (!longpath)
454 SetLastError(ERROR_INVALID_PARAMETER);
455 return 0;
457 if (!longpath[0])
459 SetLastError(ERROR_BAD_PATHNAME);
460 return 0;
463 /* code below only removes characters from string, never adds, so this is
464 * the largest buffer that tmpshortpath will need to have */
465 buf_len = strlenW(longpath) + 1;
466 tmpshortpath = HeapAlloc(GetProcessHeap(), 0, buf_len * sizeof(WCHAR));
467 if (!tmpshortpath)
469 SetLastError(ERROR_OUTOFMEMORY);
470 return 0;
473 if (longpath[0] == '\\' && longpath[1] == '\\' && longpath[2] == '?' && longpath[3] == '\\')
475 memcpy(tmpshortpath, longpath, 4 * sizeof(WCHAR));
476 sp = lp = 4;
479 /* check for drive letter */
480 if (longpath[lp] != '/' && longpath[lp + 1] == ':' )
482 tmpshortpath[sp] = longpath[lp];
483 tmpshortpath[sp + 1] = ':';
484 sp += 2;
485 lp += 2;
488 while (longpath[lp])
490 /* check for path delimiters and reproduce them */
491 if (longpath[lp] == '\\' || longpath[lp] == '/')
493 if (!sp || tmpshortpath[sp-1] != '\\')
495 /* strip double "\\" */
496 tmpshortpath[sp] = '\\';
497 sp++;
499 tmpshortpath[sp] = 0; /* terminate string */
500 lp++;
501 continue;
504 p = longpath + lp;
505 if (lp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
507 tmpshortpath[sp++] = *p++;
508 tmpshortpath[sp++] = *p++;
510 for (; *p && *p != '/' && *p != '\\'; p++);
511 tmplen = p - (longpath + lp);
512 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
514 if (tmpshortpath[sp] == '.')
516 if (tmplen == 1 || (tmplen == 2 && tmpshortpath[sp + 1] == '.'))
518 sp += tmplen;
519 lp += tmplen;
520 continue;
524 /* Check if the file exists and use the existing short file name */
525 goit = FindFirstFileW(tmpshortpath, &wfd);
526 if (goit == INVALID_HANDLE_VALUE) goto notfound;
527 FindClose(goit);
529 /* In rare cases (like "a.abcd") short path may be longer than original path.
530 * Make sure we have enough space in temp buffer. */
531 if (wfd.cAlternateFileName[0] && tmplen < strlenW(wfd.cAlternateFileName))
533 WCHAR *new_buf;
534 buf_len += strlenW(wfd.cAlternateFileName) - tmplen;
535 new_buf = HeapReAlloc(GetProcessHeap(), 0, tmpshortpath, buf_len * sizeof(WCHAR));
536 if(!new_buf)
538 HeapFree(GetProcessHeap(), 0, tmpshortpath);
539 SetLastError(ERROR_OUTOFMEMORY);
540 return 0;
542 tmpshortpath = new_buf;
545 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName);
546 sp += strlenW(tmpshortpath + sp);
547 lp += tmplen;
549 tmpshortpath[sp] = 0;
551 tmplen = strlenW(tmpshortpath) + 1;
552 if (tmplen <= shortlen)
554 strcpyW(shortpath, tmpshortpath);
555 TRACE("returning %s\n", debugstr_w(shortpath));
556 tmplen--; /* length without 0 */
559 HeapFree(GetProcessHeap(), 0, tmpshortpath);
560 return tmplen;
562 notfound:
563 HeapFree(GetProcessHeap(), 0, tmpshortpath);
564 TRACE("not found!\n" );
565 SetLastError ( ERROR_FILE_NOT_FOUND );
566 return 0;
569 /***********************************************************************
570 * GetShortPathNameA (KERNEL32.@)
572 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
574 WCHAR *longpathW;
575 WCHAR shortpathW[MAX_PATH];
576 DWORD ret;
578 TRACE("%s\n", debugstr_a(longpath));
580 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
582 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
584 if (!ret) return 0;
585 if (ret > MAX_PATH)
587 SetLastError(ERROR_FILENAME_EXCED_RANGE);
588 return 0;
590 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
594 /***********************************************************************
595 * GetTempPathA (KERNEL32.@)
597 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
599 WCHAR pathW[MAX_PATH];
600 UINT ret;
602 ret = GetTempPathW(MAX_PATH, pathW);
604 if (!ret)
605 return 0;
607 if (ret > MAX_PATH)
609 SetLastError(ERROR_FILENAME_EXCED_RANGE);
610 return 0;
612 return copy_filename_WtoA( pathW, path, count );
616 /***********************************************************************
617 * GetTempPathW (KERNEL32.@)
619 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
621 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
622 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
623 static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
624 WCHAR tmp_path[MAX_PATH];
625 UINT ret;
627 TRACE("%u,%p\n", count, path);
629 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
630 !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
631 !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
632 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
633 return 0;
635 if (ret > MAX_PATH)
637 SetLastError(ERROR_FILENAME_EXCED_RANGE);
638 return 0;
641 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
642 if (!ret) return 0;
644 if (ret > MAX_PATH - 2)
646 SetLastError(ERROR_FILENAME_EXCED_RANGE);
647 return 0;
650 if (tmp_path[ret-1] != '\\')
652 tmp_path[ret++] = '\\';
653 tmp_path[ret] = '\0';
656 ret++; /* add space for terminating 0 */
658 if (count >= ret)
660 lstrcpynW(path, tmp_path, count);
661 /* the remaining buffer must be zeroed up to 32766 bytes in XP or 32767
662 * bytes after it, we will assume the > XP behavior for now */
663 memset(path + ret, 0, (min(count, 32767) - ret) * sizeof(WCHAR));
664 ret--; /* return length without 0 */
666 else if (count)
668 /* the buffer must be cleared if contents will not fit */
669 memset(path, 0, count * sizeof(WCHAR));
672 TRACE("returning %u, %s\n", ret, debugstr_w(path));
673 return ret;
677 /***********************************************************************
678 * GetTempFileNameA (KERNEL32.@)
680 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
682 WCHAR *pathW, *prefixW = NULL;
683 WCHAR bufferW[MAX_PATH];
684 UINT ret;
686 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
687 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
689 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
690 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
692 HeapFree( GetProcessHeap(), 0, prefixW );
693 return ret;
696 /***********************************************************************
697 * GetTempFileNameW (KERNEL32.@)
699 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
701 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
703 int i;
704 LPWSTR p;
705 DWORD attr;
707 if ( !path || !buffer )
709 SetLastError( ERROR_INVALID_PARAMETER );
710 return 0;
713 /* ensure that the provided directory exists */
714 attr = GetFileAttributesW(path);
715 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
717 TRACE("path not found %s\n", debugstr_w(path));
718 SetLastError( ERROR_DIRECTORY );
719 return 0;
722 strcpyW( buffer, path );
723 p = buffer + strlenW(buffer);
725 /* add a \, if there isn't one */
726 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
728 if (prefix)
729 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
731 unique &= 0xffff;
733 if (unique) sprintfW( p, formatW, unique );
734 else
736 /* get a "random" unique number and try to create the file */
737 HANDLE handle;
738 UINT num = GetTickCount() & 0xffff;
739 static UINT last;
741 /* avoid using the same name twice in a short interval */
742 if (last - num < 10) num = last + 1;
743 if (!num) num = 1;
744 unique = num;
747 sprintfW( p, formatW, unique );
748 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
749 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
750 if (handle != INVALID_HANDLE_VALUE)
751 { /* We created it */
752 TRACE("created %s\n", debugstr_w(buffer) );
753 CloseHandle( handle );
754 last = unique;
755 break;
757 if (GetLastError() != ERROR_FILE_EXISTS &&
758 GetLastError() != ERROR_SHARING_VIOLATION)
759 break; /* No need to go on */
760 if (!(++unique & 0xffff)) unique = 1;
761 } while (unique != num);
764 TRACE("returning %s\n", debugstr_w(buffer) );
765 return unique;
769 /***********************************************************************
770 * contains_pathW
772 * Check if the file name contains a path; helper for SearchPathW.
773 * A relative path is not considered a path unless it starts with ./ or ../
775 static inline BOOL contains_pathW (LPCWSTR name)
777 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
778 if (name[0] != '.') return FALSE;
779 if (name[1] == '/' || name[1] == '\\') return TRUE;
780 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
783 /***********************************************************************
784 * find_actctx_dllpath
786 * Find the path (if any) of the dll from the activation context.
787 * Returned path doesn't include a name.
789 static NTSTATUS find_actctx_dllpath(const WCHAR *libname, WCHAR **path)
791 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
792 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
794 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
795 ACTCTX_SECTION_KEYED_DATA data;
796 UNICODE_STRING nameW;
797 NTSTATUS status;
798 SIZE_T needed, size = 1024;
799 WCHAR *p;
801 RtlInitUnicodeString( &nameW, libname );
802 data.cbSize = sizeof(data);
803 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
804 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
805 &nameW, &data );
806 if (status != STATUS_SUCCESS) return status;
808 for (;;)
810 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
812 status = STATUS_NO_MEMORY;
813 goto done;
815 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
816 AssemblyDetailedInformationInActivationContext,
817 info, size, &needed );
818 if (status == STATUS_SUCCESS) break;
819 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
820 HeapFree( GetProcessHeap(), 0, info );
821 size = needed;
822 /* restart with larger buffer */
825 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
827 status = STATUS_SXS_KEY_NOT_FOUND;
828 goto done;
831 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
833 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
835 p++;
836 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
838 /* manifest name does not match directory name, so it's not a global
839 * windows/winsxs manifest; use the manifest directory name instead */
840 dirlen = p - info->lpAssemblyManifestPath;
841 needed = (dirlen + 1) * sizeof(WCHAR);
842 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
844 status = STATUS_NO_MEMORY;
845 goto done;
847 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
848 *(p + dirlen) = 0;
849 goto done;
853 needed = (strlenW( DIR_Windows ) * sizeof(WCHAR) +
854 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + 2*sizeof(WCHAR));
856 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
858 status = STATUS_NO_MEMORY;
859 goto done;
861 strcpyW( p, DIR_Windows );
862 p += strlenW(p);
863 memcpy( p, winsxsW, sizeof(winsxsW) );
864 p += sizeof(winsxsW) / sizeof(WCHAR);
865 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
866 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
867 *p++ = '\\';
868 *p = 0;
869 done:
870 HeapFree( GetProcessHeap(), 0, info );
871 RtlReleaseActivationContext( data.hActCtx );
872 return status;
875 /***********************************************************************
876 * SearchPathW [KERNEL32.@]
878 * Searches for a specified file in the search path.
880 * PARAMS
881 * path [I] Path to search (NULL means default)
882 * name [I] Filename to search for.
883 * ext [I] File extension to append to file name. The first
884 * character must be a period. This parameter is
885 * specified only if the filename given does not
886 * contain an extension.
887 * buflen [I] size of buffer, in characters
888 * buffer [O] buffer for found filename
889 * lastpart [O] address of pointer to last used character in
890 * buffer (the final '\')
892 * RETURNS
893 * Success: length of string copied into buffer, not including
894 * terminating null character. If the filename found is
895 * longer than the length of the buffer, the length of the
896 * filename is returned.
897 * Failure: Zero
899 * NOTES
900 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
901 * (tested on NT 4.0)
903 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
904 LPWSTR buffer, LPWSTR *lastpart )
906 DWORD ret = 0;
908 if (!name || !name[0])
910 SetLastError(ERROR_INVALID_PARAMETER);
911 return 0;
914 /* If the name contains an explicit path, ignore the path */
916 if (contains_pathW(name))
918 /* try first without extension */
919 if (RtlDoesFileExists_U( name ))
920 return GetFullPathNameW( name, buflen, buffer, lastpart );
922 if (ext)
924 LPCWSTR p = strrchrW( name, '.' );
925 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
926 ext = NULL; /* Ignore the specified extension */
929 /* Allocate a buffer for the file name and extension */
930 if (ext)
932 LPWSTR tmp;
933 DWORD len = strlenW(name) + strlenW(ext);
935 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
937 SetLastError( ERROR_OUTOFMEMORY );
938 return 0;
940 strcpyW( tmp, name );
941 strcatW( tmp, ext );
942 if (RtlDoesFileExists_U( tmp ))
943 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
944 HeapFree( GetProcessHeap(), 0, tmp );
947 else if (path && path[0]) /* search in the specified path */
949 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
950 buffer, lastpart ) / sizeof(WCHAR);
952 else /* search in active context and default path */
954 WCHAR *dll_path = NULL, *search = NULL;
955 DWORD req_len, name_len;
957 req_len = name_len = strlenW(name);
959 if (strchrW( name, '.' )) ext = NULL;
960 if (ext)
962 DWORD ext_len = strlenW(ext);
964 req_len += ext_len;
965 name_len += ext_len;
967 search = HeapAlloc( GetProcessHeap(), 0, (name_len + ext_len + 1) * sizeof(WCHAR) );
968 if (!search)
970 SetLastError( ERROR_OUTOFMEMORY );
971 return 0;
973 strcpyW( search, name );
974 strcatW( search, ext );
975 name = search;
977 /* now that we have combined name we don't need extension any more */
980 /* When file is found with activation context no attempt is made
981 to check if it's really exist, path is returned only basing on context info. */
982 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
984 DWORD path_len;
986 path_len = strlenW(dll_path);
987 req_len += path_len;
989 if (lastpart) *lastpart = NULL;
991 /* count null termination char too */
992 if (req_len + 1 <= buflen)
994 memcpy( buffer, dll_path, path_len * sizeof(WCHAR) );
995 memcpy( &buffer[path_len], name, name_len * sizeof(WCHAR) );
996 buffer[req_len] = 0;
997 if (lastpart) *lastpart = buffer + path_len;
998 ret = req_len;
1000 else
1001 ret = req_len + 1;
1003 HeapFree( GetProcessHeap(), 0, dll_path );
1004 HeapFree( GetProcessHeap(), 0, search );
1006 else
1008 if ((dll_path = MODULE_get_dll_load_path( NULL )))
1010 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
1011 buffer, lastpart ) / sizeof(WCHAR);
1012 HeapFree( GetProcessHeap(), 0, dll_path );
1013 HeapFree( GetProcessHeap(), 0, search );
1015 else
1017 SetLastError( ERROR_OUTOFMEMORY );
1018 return 0;
1023 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
1024 else TRACE( "found %s\n", debugstr_w(buffer) );
1025 return ret;
1029 /***********************************************************************
1030 * SearchPathA (KERNEL32.@)
1032 * See SearchPathW.
1034 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
1035 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
1037 WCHAR *pathW = NULL, *nameW, *extW = NULL;
1038 WCHAR bufferW[MAX_PATH];
1039 DWORD ret;
1041 if (!name)
1043 SetLastError(ERROR_INVALID_PARAMETER);
1044 return 0;
1047 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
1048 if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
1050 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
1052 HeapFree( GetProcessHeap(), 0, pathW );
1053 return 0;
1056 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
1058 HeapFree( GetProcessHeap(), 0, pathW );
1059 HeapFree( GetProcessHeap(), 0, extW );
1061 if (!ret) return 0;
1062 if (ret > MAX_PATH)
1064 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1065 return 0;
1067 ret = copy_filename_WtoA( bufferW, buffer, buflen );
1068 if (buflen > ret && lastpart)
1069 *lastpart = strrchr(buffer, '\\') + 1;
1070 return ret;
1073 static BOOL is_same_file(HANDLE h1, HANDLE h2)
1075 int fd1;
1076 BOOL ret = FALSE;
1077 if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
1079 int fd2;
1080 if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
1082 struct stat stat1, stat2;
1083 if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
1084 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
1085 wine_server_release_fd(h2, fd2);
1087 wine_server_release_fd(h1, fd1);
1089 return ret;
1092 /**************************************************************************
1093 * CopyFileW (KERNEL32.@)
1095 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1097 return CopyFileExW( source, dest, NULL, NULL, NULL,
1098 fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
1102 /**************************************************************************
1103 * CopyFileA (KERNEL32.@)
1105 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1107 WCHAR *sourceW, *destW;
1108 BOOL ret;
1110 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1111 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1113 ret = CopyFileW( sourceW, destW, fail_if_exists );
1115 HeapFree( GetProcessHeap(), 0, destW );
1116 return ret;
1120 /**************************************************************************
1121 * CopyFileExW (KERNEL32.@)
1123 BOOL WINAPI CopyFileExW(LPCWSTR source, LPCWSTR dest,
1124 LPPROGRESS_ROUTINE progress, LPVOID param,
1125 LPBOOL cancel_ptr, DWORD flags)
1127 static const int buffer_size = 65536;
1128 HANDLE h1, h2;
1129 BY_HANDLE_FILE_INFORMATION info;
1130 DWORD count;
1131 BOOL ret = FALSE;
1132 char *buffer;
1134 if (!source || !dest)
1136 SetLastError(ERROR_INVALID_PARAMETER);
1137 return FALSE;
1139 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1141 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1142 return FALSE;
1145 TRACE("%s -> %s, %x\n", debugstr_w(source), debugstr_w(dest), flags);
1147 if ((h1 = CreateFileW(source, GENERIC_READ,
1148 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1149 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1151 WARN("Unable to open source %s\n", debugstr_w(source));
1152 HeapFree( GetProcessHeap(), 0, buffer );
1153 return FALSE;
1156 if (!GetFileInformationByHandle( h1, &info ))
1158 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1159 HeapFree( GetProcessHeap(), 0, buffer );
1160 CloseHandle( h1 );
1161 return FALSE;
1164 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
1166 BOOL same_file = FALSE;
1167 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1168 OPEN_EXISTING, 0, 0);
1169 if (h2 != INVALID_HANDLE_VALUE)
1171 same_file = is_same_file( h1, h2 );
1172 CloseHandle( h2 );
1174 if (same_file)
1176 HeapFree( GetProcessHeap(), 0, buffer );
1177 CloseHandle( h1 );
1178 SetLastError( ERROR_SHARING_VIOLATION );
1179 return FALSE;
1183 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1184 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
1185 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1187 WARN("Unable to open dest %s\n", debugstr_w(dest));
1188 HeapFree( GetProcessHeap(), 0, buffer );
1189 CloseHandle( h1 );
1190 return FALSE;
1193 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
1195 char *p = buffer;
1196 while (count != 0)
1198 DWORD res;
1199 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1200 p += res;
1201 count -= res;
1204 ret = TRUE;
1205 done:
1206 /* Maintain the timestamp of source file to destination file */
1207 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
1208 HeapFree( GetProcessHeap(), 0, buffer );
1209 CloseHandle( h1 );
1210 CloseHandle( h2 );
1211 return ret;
1215 /**************************************************************************
1216 * CopyFileExA (KERNEL32.@)
1218 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1219 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1220 LPBOOL cancelFlagPointer, DWORD copyFlags)
1222 WCHAR *sourceW, *destW;
1223 BOOL ret;
1225 /* can't use the TEB buffer since we may have a callback routine */
1226 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1227 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1229 HeapFree( GetProcessHeap(), 0, sourceW );
1230 return FALSE;
1232 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1233 cancelFlagPointer, copyFlags);
1234 HeapFree( GetProcessHeap(), 0, sourceW );
1235 HeapFree( GetProcessHeap(), 0, destW );
1236 return ret;
1240 /**************************************************************************
1241 * MoveFileWithProgressW (KERNEL32.@)
1243 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1244 LPPROGRESS_ROUTINE fnProgress,
1245 LPVOID param, DWORD flag )
1247 FILE_BASIC_INFORMATION info;
1248 UNICODE_STRING nt_name;
1249 OBJECT_ATTRIBUTES attr;
1250 IO_STATUS_BLOCK io;
1251 NTSTATUS status;
1252 HANDLE source_handle = 0, dest_handle;
1253 ANSI_STRING source_unix, dest_unix;
1255 TRACE("(%s,%s,%p,%p,%04x)\n",
1256 debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1258 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1259 return add_boot_rename_entry( source, dest, flag );
1261 if (!dest)
1262 return DeleteFileW( source );
1264 if (flag & MOVEFILE_WRITE_THROUGH)
1265 FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1267 /* check if we are allowed to rename the source */
1269 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1271 SetLastError( ERROR_PATH_NOT_FOUND );
1272 return FALSE;
1274 source_unix.Buffer = NULL;
1275 dest_unix.Buffer = NULL;
1276 attr.Length = sizeof(attr);
1277 attr.RootDirectory = 0;
1278 attr.Attributes = OBJ_CASE_INSENSITIVE;
1279 attr.ObjectName = &nt_name;
1280 attr.SecurityDescriptor = NULL;
1281 attr.SecurityQualityOfService = NULL;
1283 status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1284 if (status == STATUS_SUCCESS)
1285 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1286 RtlFreeUnicodeString( &nt_name );
1287 if (status != STATUS_SUCCESS)
1289 SetLastError( RtlNtStatusToDosError(status) );
1290 goto error;
1292 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1293 if (status != STATUS_SUCCESS)
1295 SetLastError( RtlNtStatusToDosError(status) );
1296 goto error;
1299 /* we must have write access to the destination, and it must */
1300 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1302 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1304 SetLastError( ERROR_PATH_NOT_FOUND );
1305 goto error;
1307 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1308 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1309 if (status == STATUS_SUCCESS) /* destination exists */
1311 NtClose( dest_handle );
1312 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1314 SetLastError( ERROR_ALREADY_EXISTS );
1315 RtlFreeUnicodeString( &nt_name );
1316 goto error;
1318 else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1320 SetLastError( ERROR_ACCESS_DENIED );
1321 goto error;
1324 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1326 SetLastError( RtlNtStatusToDosError(status) );
1327 RtlFreeUnicodeString( &nt_name );
1328 goto error;
1331 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1332 RtlFreeUnicodeString( &nt_name );
1333 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1335 SetLastError( RtlNtStatusToDosError(status) );
1336 goto error;
1339 /* now perform the rename */
1341 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1343 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1345 NtClose( source_handle );
1346 RtlFreeAnsiString( &source_unix );
1347 RtlFreeAnsiString( &dest_unix );
1348 if (!CopyFileExW( source, dest, fnProgress,
1349 param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1350 return FALSE;
1351 return DeleteFileW( source );
1353 FILE_SetDosError();
1354 /* if we created the destination, remove it */
1355 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1356 goto error;
1359 /* fixup executable permissions */
1361 if (is_executable( source ) != is_executable( dest ))
1363 struct stat fstat;
1364 if (stat( dest_unix.Buffer, &fstat ) != -1)
1366 if (is_executable( dest ))
1367 /* set executable bit where read bit is set */
1368 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1369 else
1370 fstat.st_mode &= ~0111;
1371 chmod( dest_unix.Buffer, fstat.st_mode );
1375 NtClose( source_handle );
1376 RtlFreeAnsiString( &source_unix );
1377 RtlFreeAnsiString( &dest_unix );
1378 return TRUE;
1380 error:
1381 if (source_handle) NtClose( source_handle );
1382 RtlFreeAnsiString( &source_unix );
1383 RtlFreeAnsiString( &dest_unix );
1384 return FALSE;
1387 /**************************************************************************
1388 * MoveFileWithProgressA (KERNEL32.@)
1390 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1391 LPPROGRESS_ROUTINE fnProgress,
1392 LPVOID param, DWORD flag )
1394 WCHAR *sourceW, *destW;
1395 BOOL ret;
1397 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1398 if (dest)
1400 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1402 else
1403 destW = NULL;
1405 ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1406 HeapFree( GetProcessHeap(), 0, destW );
1407 return ret;
1410 /**************************************************************************
1411 * MoveFileExW (KERNEL32.@)
1413 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1415 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1418 /**************************************************************************
1419 * MoveFileExA (KERNEL32.@)
1421 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1423 return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1427 /**************************************************************************
1428 * MoveFileW (KERNEL32.@)
1430 * Move file or directory
1432 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1434 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1438 /**************************************************************************
1439 * MoveFileA (KERNEL32.@)
1441 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1443 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1447 /*************************************************************************
1448 * CreateHardLinkW (KERNEL32.@)
1450 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1451 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1453 NTSTATUS status;
1454 UNICODE_STRING ntDest, ntSource;
1455 ANSI_STRING unixDest, unixSource;
1456 BOOL ret = FALSE;
1458 TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1459 debugstr_w(lpExistingFileName), lpSecurityAttributes);
1461 ntDest.Buffer = ntSource.Buffer = NULL;
1462 if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1463 !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1465 SetLastError( ERROR_PATH_NOT_FOUND );
1466 goto err;
1469 unixSource.Buffer = unixDest.Buffer = NULL;
1470 status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1471 if (!status)
1473 status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1474 if (!status) /* destination must not exist */
1476 status = STATUS_OBJECT_NAME_EXISTS;
1477 } else if (status == STATUS_NO_SUCH_FILE)
1479 status = STATUS_SUCCESS;
1483 if (status)
1484 SetLastError( RtlNtStatusToDosError(status) );
1485 else if (!link( unixSource.Buffer, unixDest.Buffer ))
1487 TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1488 debugstr_a( unixSource.Buffer ));
1489 ret = TRUE;
1491 else
1492 FILE_SetDosError();
1494 RtlFreeAnsiString( &unixSource );
1495 RtlFreeAnsiString( &unixDest );
1497 err:
1498 RtlFreeUnicodeString( &ntSource );
1499 RtlFreeUnicodeString( &ntDest );
1500 return ret;
1504 /*************************************************************************
1505 * CreateHardLinkA (KERNEL32.@)
1507 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1508 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1510 WCHAR *sourceW, *destW;
1511 BOOL res;
1513 if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1515 return FALSE;
1517 if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1519 HeapFree( GetProcessHeap(), 0, sourceW );
1520 return FALSE;
1523 res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1525 HeapFree( GetProcessHeap(), 0, sourceW );
1526 HeapFree( GetProcessHeap(), 0, destW );
1528 return res;
1532 /***********************************************************************
1533 * CreateDirectoryW (KERNEL32.@)
1534 * RETURNS:
1535 * TRUE : success
1536 * FALSE : failure
1537 * ERROR_DISK_FULL: on full disk
1538 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1539 * ERROR_ACCESS_DENIED: on permission problems
1540 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1542 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1544 OBJECT_ATTRIBUTES attr;
1545 UNICODE_STRING nt_name;
1546 IO_STATUS_BLOCK io;
1547 NTSTATUS status;
1548 HANDLE handle;
1549 BOOL ret = FALSE;
1551 TRACE( "%s\n", debugstr_w(path) );
1553 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1555 SetLastError( ERROR_PATH_NOT_FOUND );
1556 return FALSE;
1558 attr.Length = sizeof(attr);
1559 attr.RootDirectory = 0;
1560 attr.Attributes = OBJ_CASE_INSENSITIVE;
1561 attr.ObjectName = &nt_name;
1562 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1563 attr.SecurityQualityOfService = NULL;
1565 status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1566 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1567 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1569 if (status == STATUS_SUCCESS)
1571 NtClose( handle );
1572 ret = TRUE;
1574 else SetLastError( RtlNtStatusToDosError(status) );
1576 RtlFreeUnicodeString( &nt_name );
1577 return ret;
1581 /***********************************************************************
1582 * CreateDirectoryA (KERNEL32.@)
1584 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1586 WCHAR *pathW;
1588 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1589 return CreateDirectoryW( pathW, sa );
1593 /***********************************************************************
1594 * CreateDirectoryExA (KERNEL32.@)
1596 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1598 WCHAR *pathW, *templateW = NULL;
1599 BOOL ret;
1601 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1602 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1604 ret = CreateDirectoryExW( templateW, pathW, sa );
1605 HeapFree( GetProcessHeap(), 0, templateW );
1606 return ret;
1610 /***********************************************************************
1611 * CreateDirectoryExW (KERNEL32.@)
1613 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1615 return CreateDirectoryW( path, sa );
1619 /***********************************************************************
1620 * RemoveDirectoryW (KERNEL32.@)
1622 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1624 OBJECT_ATTRIBUTES attr;
1625 UNICODE_STRING nt_name;
1626 ANSI_STRING unix_name;
1627 IO_STATUS_BLOCK io;
1628 NTSTATUS status;
1629 HANDLE handle;
1630 BOOL ret = FALSE;
1632 TRACE( "%s\n", debugstr_w(path) );
1634 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1636 SetLastError( ERROR_PATH_NOT_FOUND );
1637 return FALSE;
1639 attr.Length = sizeof(attr);
1640 attr.RootDirectory = 0;
1641 attr.Attributes = OBJ_CASE_INSENSITIVE;
1642 attr.ObjectName = &nt_name;
1643 attr.SecurityDescriptor = NULL;
1644 attr.SecurityQualityOfService = NULL;
1646 status = NtOpenFile( &handle, DELETE, &attr, &io,
1647 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1648 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1649 if (status == STATUS_SUCCESS)
1650 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1651 RtlFreeUnicodeString( &nt_name );
1653 if (status != STATUS_SUCCESS)
1655 SetLastError( RtlNtStatusToDosError(status) );
1656 return FALSE;
1659 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1660 RtlFreeAnsiString( &unix_name );
1661 NtClose( handle );
1662 return ret;
1666 /***********************************************************************
1667 * RemoveDirectoryA (KERNEL32.@)
1669 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1671 WCHAR *pathW;
1673 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1674 return RemoveDirectoryW( pathW );
1678 /***********************************************************************
1679 * GetCurrentDirectoryW (KERNEL32.@)
1681 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1683 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1687 /***********************************************************************
1688 * GetCurrentDirectoryA (KERNEL32.@)
1690 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1692 WCHAR bufferW[MAX_PATH];
1693 DWORD ret;
1695 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1697 /* Win9x catches access violations here, returning zero.
1698 * This behaviour resulted in some people not noticing
1699 * that they got the argument order wrong. So let's be
1700 * nice and fail gracefully if buf is invalid and looks
1701 * more like a buflen. */
1702 SetLastError(ERROR_INVALID_PARAMETER);
1703 return 0;
1706 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1707 if (!ret) return 0;
1708 if (ret > sizeof(bufferW))
1710 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1711 return 0;
1713 return copy_filename_WtoA( bufferW, buf, buflen );
1717 /***********************************************************************
1718 * SetCurrentDirectoryW (KERNEL32.@)
1720 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1722 UNICODE_STRING dirW;
1723 NTSTATUS status;
1725 RtlInitUnicodeString( &dirW, dir );
1726 status = RtlSetCurrentDirectory_U( &dirW );
1727 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1728 return !status;
1732 /***********************************************************************
1733 * SetCurrentDirectoryA (KERNEL32.@)
1735 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1737 WCHAR *dirW;
1738 UNICODE_STRING strW;
1739 NTSTATUS status;
1741 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1742 RtlInitUnicodeString( &strW, dirW );
1743 status = RtlSetCurrentDirectory_U( &strW );
1744 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1745 return !status;
1749 /***********************************************************************
1750 * GetWindowsDirectoryW (KERNEL32.@)
1752 * See comment for GetWindowsDirectoryA.
1754 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1756 UINT len = strlenW( DIR_Windows ) + 1;
1757 if (path && count >= len)
1759 strcpyW( path, DIR_Windows );
1760 len--;
1762 return len;
1766 /***********************************************************************
1767 * GetWindowsDirectoryA (KERNEL32.@)
1769 * Return value:
1770 * If buffer is large enough to hold full path and terminating '\0' character
1771 * function copies path to buffer and returns length of the path without '\0'.
1772 * Otherwise function returns required size including '\0' character and
1773 * does not touch the buffer.
1775 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1777 return copy_filename_WtoA( DIR_Windows, path, count );
1781 /***********************************************************************
1782 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1784 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1786 return GetWindowsDirectoryA( path, count );
1790 /***********************************************************************
1791 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1793 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1795 return GetWindowsDirectoryW( path, count );
1799 /***********************************************************************
1800 * GetSystemDirectoryW (KERNEL32.@)
1802 * See comment for GetWindowsDirectoryA.
1804 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1806 UINT len = strlenW( DIR_System ) + 1;
1807 if (path && count >= len)
1809 strcpyW( path, DIR_System );
1810 len--;
1812 return len;
1816 /***********************************************************************
1817 * GetSystemDirectoryA (KERNEL32.@)
1819 * See comment for GetWindowsDirectoryA.
1821 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1823 return copy_filename_WtoA( DIR_System, path, count );
1827 /***********************************************************************
1828 * GetSystemWow64DirectoryW (KERNEL32.@)
1830 * As seen on MSDN
1831 * - On Win32 we should return ERROR_CALL_NOT_IMPLEMENTED
1832 * - On Win64 we should return the SysWow64 (system64) directory
1834 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1836 UINT len;
1838 if (!DIR_SysWow64)
1840 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1841 return 0;
1843 len = strlenW( DIR_SysWow64 ) + 1;
1844 if (path && count >= len)
1846 strcpyW( path, DIR_SysWow64 );
1847 len--;
1849 return len;
1853 /***********************************************************************
1854 * GetSystemWow64DirectoryA (KERNEL32.@)
1856 * See comment for GetWindowsWow64DirectoryW.
1858 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1860 if (!DIR_SysWow64)
1862 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1863 return 0;
1865 return copy_filename_WtoA( DIR_SysWow64, path, count );
1869 /***********************************************************************
1870 * Wow64EnableWow64FsRedirection (KERNEL32.@)
1872 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1874 NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1875 if (status) SetLastError( RtlNtStatusToDosError(status) );
1876 return !status;
1880 /***********************************************************************
1881 * Wow64DisableWow64FsRedirection (KERNEL32.@)
1883 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1885 NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1886 if (status) SetLastError( RtlNtStatusToDosError(status) );
1887 return !status;
1891 /***********************************************************************
1892 * Wow64RevertWow64FsRedirection (KERNEL32.@)
1894 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1896 NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1897 if (status) SetLastError( RtlNtStatusToDosError(status) );
1898 return !status;
1902 /***********************************************************************
1903 * NeedCurrentDirectoryForExePathW (KERNEL32.@)
1905 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1907 static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1908 'C','u','r','r','e','n','t',
1909 'D','i','r','e','c','t','o','r','y',
1910 'I','n','E','x','e','P','a','t','h',0};
1911 WCHAR env_val;
1913 /* MSDN mentions some 'registry location'. We do not use registry. */
1914 FIXME("(%s): partial stub\n", debugstr_w(name));
1916 if (strchrW(name, '\\'))
1917 return TRUE;
1919 /* Check the existence of the variable, not value */
1920 if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1921 return TRUE;
1923 return FALSE;
1927 /***********************************************************************
1928 * NeedCurrentDirectoryForExePathA (KERNEL32.@)
1930 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1932 WCHAR *nameW;
1934 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1935 return NeedCurrentDirectoryForExePathW( nameW );
1939 /***********************************************************************
1940 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1942 * Return the full Unix file name for a given path.
1943 * Returned buffer must be freed by caller.
1945 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1947 UNICODE_STRING nt_name;
1948 ANSI_STRING unix_name;
1949 NTSTATUS status;
1951 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1952 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1953 RtlFreeUnicodeString( &nt_name );
1954 if (status && status != STATUS_NO_SUCH_FILE)
1956 SetLastError( RtlNtStatusToDosError( status ) );
1957 return NULL;
1959 return unix_name.Buffer;
1963 /***********************************************************************
1964 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1966 * Return the full DOS file name for a given Unix path.
1967 * Returned buffer must be freed by caller.
1969 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1971 UNICODE_STRING nt_name;
1972 ANSI_STRING unix_name;
1973 NTSTATUS status;
1974 DWORD len;
1976 RtlInitAnsiString( &unix_name, str );
1977 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1978 if (status)
1980 SetLastError( RtlNtStatusToDosError( status ) );
1981 return NULL;
1983 if (nt_name.Buffer[5] == ':')
1985 /* get rid of the \??\ prefix */
1986 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1987 len = nt_name.Length - 4 * sizeof(WCHAR);
1988 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1989 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1991 else
1992 nt_name.Buffer[1] = '\\';
1993 return nt_name.Buffer;
1996 /*************************************************************************
1997 * CreateSymbolicLinkW (KERNEL32.@)
1999 BOOL WINAPI CreateSymbolicLinkW(LPCWSTR link, LPCWSTR target, DWORD flags)
2001 FIXME("(%s %s %d): stub\n", debugstr_w(link), debugstr_w(target), flags);
2002 return TRUE;
2005 /*************************************************************************
2006 * CreateSymbolicLinkA (KERNEL32.@)
2008 BOOL WINAPI CreateSymbolicLinkA(LPCSTR link, LPCSTR target, DWORD flags)
2010 FIXME("(%s %s %d): stub\n", debugstr_a(link), debugstr_a(target), flags);
2011 return TRUE;
2014 /*************************************************************************
2015 * CreateHardLinkTransactedA (KERNEL32.@)
2017 BOOL WINAPI CreateHardLinkTransactedA(LPCSTR link, LPCSTR target, LPSECURITY_ATTRIBUTES sa, HANDLE transaction)
2019 FIXME("(%s %s %p %p): stub\n", debugstr_a(link), debugstr_a(target), sa, transaction);
2020 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2021 return FALSE;
2024 /*************************************************************************
2025 * CreateHardLinkTransactedW (KERNEL32.@)
2027 BOOL WINAPI CreateHardLinkTransactedW(LPCWSTR link, LPCWSTR target, LPSECURITY_ATTRIBUTES sa, HANDLE transaction)
2029 FIXME("(%s %s %p %p): stub\n", debugstr_w(link), debugstr_w(target), sa, transaction);
2030 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2031 return FALSE;
2034 /*************************************************************************
2035 * CheckNameLegalDOS8Dot3A (KERNEL32.@)
2037 BOOL WINAPI CheckNameLegalDOS8Dot3A(const char *name, char *oemname, DWORD oemname_len,
2038 BOOL *contains_spaces, BOOL *is_legal)
2040 WCHAR *nameW;
2042 TRACE("(%s %p %u %p %p)\n", name, oemname,
2043 oemname_len, contains_spaces, is_legal);
2045 if (!name || !is_legal)
2046 return FALSE;
2048 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
2050 return CheckNameLegalDOS8Dot3W( nameW, oemname, oemname_len, contains_spaces, is_legal );
2053 /*************************************************************************
2054 * CheckNameLegalDOS8Dot3W (KERNEL32.@)
2056 BOOL WINAPI CheckNameLegalDOS8Dot3W(const WCHAR *name, char *oemname, DWORD oemname_len,
2057 BOOL *contains_spaces_ret, BOOL *is_legal)
2059 OEM_STRING oem_str;
2060 UNICODE_STRING nameW;
2061 BOOLEAN contains_spaces;
2063 TRACE("(%s %p %u %p %p)\n", wine_dbgstr_w(name), oemname,
2064 oemname_len, contains_spaces_ret, is_legal);
2066 if (!name || !is_legal)
2067 return FALSE;
2069 RtlInitUnicodeString( &nameW, name );
2071 if (oemname) {
2072 oem_str.Length = oemname_len;
2073 oem_str.MaximumLength = oemname_len;
2074 oem_str.Buffer = oemname;
2077 *is_legal = RtlIsNameLegalDOS8Dot3( &nameW, oemname ? &oem_str : NULL, &contains_spaces );
2078 if (contains_spaces_ret) *contains_spaces_ret = contains_spaces;
2080 return TRUE;