shell32/tests: Some tests for IShellWindows.
[wine.git] / dlls / kernel32 / path.c
blobc2833b1a6827f0003174cc34d60013f188aff57f
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[MAX_PATHNAME_LEN];
444 LPCWSTR p;
445 DWORD sp = 0, lp = 0;
446 DWORD tmplen;
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 /* check for drive letter */
464 if (longpath[0] != '/' && longpath[1] == ':' )
466 tmpshortpath[0] = longpath[0];
467 tmpshortpath[1] = ':';
468 sp = lp = 2;
471 while (longpath[lp])
473 /* check for path delimiters and reproduce them */
474 if (longpath[lp] == '\\' || longpath[lp] == '/')
476 if (!sp || tmpshortpath[sp-1] != '\\')
478 /* strip double "\\" */
479 tmpshortpath[sp] = '\\';
480 sp++;
482 tmpshortpath[sp] = 0; /* terminate string */
483 lp++;
484 continue;
487 p = longpath + lp;
488 if (lp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
490 tmpshortpath[sp++] = *p++;
491 tmpshortpath[sp++] = *p++;
493 for (; *p && *p != '/' && *p != '\\'; p++);
494 tmplen = p - (longpath + lp);
495 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
497 if (tmpshortpath[sp] == '.')
499 if (tmplen == 1 || (tmplen == 2 && tmpshortpath[sp + 1] == '.'))
501 sp += tmplen;
502 lp += tmplen;
503 continue;
507 /* Check if the file exists and use the existing short file name */
508 goit = FindFirstFileW(tmpshortpath, &wfd);
509 if (goit == INVALID_HANDLE_VALUE) goto notfound;
510 FindClose(goit);
511 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName);
512 sp += strlenW(tmpshortpath + sp);
513 lp += tmplen;
515 tmpshortpath[sp] = 0;
517 tmplen = strlenW(tmpshortpath) + 1;
518 if (tmplen <= shortlen)
520 strcpyW(shortpath, tmpshortpath);
521 TRACE("returning %s\n", debugstr_w(shortpath));
522 tmplen--; /* length without 0 */
525 return tmplen;
527 notfound:
528 TRACE("not found!\n" );
529 SetLastError ( ERROR_FILE_NOT_FOUND );
530 return 0;
533 /***********************************************************************
534 * GetShortPathNameA (KERNEL32.@)
536 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
538 WCHAR *longpathW;
539 WCHAR shortpathW[MAX_PATH];
540 DWORD ret;
542 TRACE("%s\n", debugstr_a(longpath));
544 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
546 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
548 if (!ret) return 0;
549 if (ret > MAX_PATH)
551 SetLastError(ERROR_FILENAME_EXCED_RANGE);
552 return 0;
554 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
558 /***********************************************************************
559 * GetTempPathA (KERNEL32.@)
561 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
563 WCHAR pathW[MAX_PATH];
564 UINT ret;
566 ret = GetTempPathW(MAX_PATH, pathW);
568 if (!ret)
569 return 0;
571 if (ret > MAX_PATH)
573 SetLastError(ERROR_FILENAME_EXCED_RANGE);
574 return 0;
576 return copy_filename_WtoA( pathW, path, count );
580 /***********************************************************************
581 * GetTempPathW (KERNEL32.@)
583 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
585 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
586 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
587 static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
588 WCHAR tmp_path[MAX_PATH];
589 UINT ret;
591 TRACE("%u,%p\n", count, path);
593 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
594 !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
595 !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
596 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
597 return 0;
599 if (ret > MAX_PATH)
601 SetLastError(ERROR_FILENAME_EXCED_RANGE);
602 return 0;
605 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
606 if (!ret) return 0;
608 if (ret > MAX_PATH - 2)
610 SetLastError(ERROR_FILENAME_EXCED_RANGE);
611 return 0;
614 if (tmp_path[ret-1] != '\\')
616 tmp_path[ret++] = '\\';
617 tmp_path[ret] = '\0';
620 ret++; /* add space for terminating 0 */
622 if (count >= ret)
624 lstrcpynW(path, tmp_path, count);
625 /* the remaining buffer must be zeroed up to 32766 bytes in XP or 32767
626 * bytes after it, we will assume the > XP behavior for now */
627 memset(path + ret, 0, (min(count, 32767) - ret) * sizeof(WCHAR));
628 ret--; /* return length without 0 */
630 else if (count)
632 /* the buffer must be cleared if contents will not fit */
633 memset(path, 0, count * sizeof(WCHAR));
636 TRACE("returning %u, %s\n", ret, debugstr_w(path));
637 return ret;
641 /***********************************************************************
642 * GetTempFileNameA (KERNEL32.@)
644 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
646 WCHAR *pathW, *prefixW = NULL;
647 WCHAR bufferW[MAX_PATH];
648 UINT ret;
650 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
651 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
653 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
654 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
656 HeapFree( GetProcessHeap(), 0, prefixW );
657 return ret;
660 /***********************************************************************
661 * GetTempFileNameW (KERNEL32.@)
663 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
665 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
667 int i;
668 LPWSTR p;
669 DWORD attr;
671 if ( !path || !buffer )
673 SetLastError( ERROR_INVALID_PARAMETER );
674 return 0;
677 /* ensure that the provided directory exists */
678 attr = GetFileAttributesW(path);
679 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
681 TRACE("path not found %s\n", debugstr_w(path));
682 SetLastError( ERROR_DIRECTORY );
683 return 0;
686 strcpyW( buffer, path );
687 p = buffer + strlenW(buffer);
689 /* add a \, if there isn't one */
690 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
692 if (prefix)
693 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
695 unique &= 0xffff;
697 if (unique) sprintfW( p, formatW, unique );
698 else
700 /* get a "random" unique number and try to create the file */
701 HANDLE handle;
702 UINT num = GetTickCount() & 0xffff;
703 static UINT last;
705 /* avoid using the same name twice in a short interval */
706 if (last - num < 10) num = last + 1;
707 if (!num) num = 1;
708 unique = num;
711 sprintfW( p, formatW, unique );
712 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
713 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
714 if (handle != INVALID_HANDLE_VALUE)
715 { /* We created it */
716 TRACE("created %s\n", debugstr_w(buffer) );
717 CloseHandle( handle );
718 last = unique;
719 break;
721 if (GetLastError() != ERROR_FILE_EXISTS &&
722 GetLastError() != ERROR_SHARING_VIOLATION)
723 break; /* No need to go on */
724 if (!(++unique & 0xffff)) unique = 1;
725 } while (unique != num);
728 TRACE("returning %s\n", debugstr_w(buffer) );
729 return unique;
733 /***********************************************************************
734 * contains_pathW
736 * Check if the file name contains a path; helper for SearchPathW.
737 * A relative path is not considered a path unless it starts with ./ or ../
739 static inline BOOL contains_pathW (LPCWSTR name)
741 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
742 if (name[0] != '.') return FALSE;
743 if (name[1] == '/' || name[1] == '\\') return TRUE;
744 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
747 /***********************************************************************
748 * find_actctx_dllpath
750 * Find the path (if any) of the dll from the activation context.
751 * Returned path doesn't include a name.
753 static NTSTATUS find_actctx_dllpath(const WCHAR *libname, WCHAR **path)
755 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
756 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
758 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
759 ACTCTX_SECTION_KEYED_DATA data;
760 UNICODE_STRING nameW;
761 NTSTATUS status;
762 SIZE_T needed, size = 1024;
763 WCHAR *p;
765 RtlInitUnicodeString( &nameW, libname );
766 data.cbSize = sizeof(data);
767 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
768 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
769 &nameW, &data );
770 if (status != STATUS_SUCCESS) return status;
772 for (;;)
774 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
776 status = STATUS_NO_MEMORY;
777 goto done;
779 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
780 AssemblyDetailedInformationInActivationContext,
781 info, size, &needed );
782 if (status == STATUS_SUCCESS) break;
783 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
784 HeapFree( GetProcessHeap(), 0, info );
785 size = needed;
786 /* restart with larger buffer */
789 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
791 status = STATUS_SXS_KEY_NOT_FOUND;
792 goto done;
795 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
797 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
799 p++;
800 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
802 /* manifest name does not match directory name, so it's not a global
803 * windows/winsxs manifest; use the manifest directory name instead */
804 dirlen = p - info->lpAssemblyManifestPath;
805 needed = (dirlen + 1) * sizeof(WCHAR);
806 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
808 status = STATUS_NO_MEMORY;
809 goto done;
811 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
812 *(p + dirlen) = 0;
813 goto done;
817 needed = (strlenW( DIR_Windows ) * sizeof(WCHAR) +
818 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + 2*sizeof(WCHAR));
820 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
822 status = STATUS_NO_MEMORY;
823 goto done;
825 strcpyW( p, DIR_Windows );
826 p += strlenW(p);
827 memcpy( p, winsxsW, sizeof(winsxsW) );
828 p += sizeof(winsxsW) / sizeof(WCHAR);
829 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
830 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
831 *p++ = '\\';
832 *p = 0;
833 done:
834 HeapFree( GetProcessHeap(), 0, info );
835 RtlReleaseActivationContext( data.hActCtx );
836 return status;
839 /***********************************************************************
840 * SearchPathW [KERNEL32.@]
842 * Searches for a specified file in the search path.
844 * PARAMS
845 * path [I] Path to search (NULL means default)
846 * name [I] Filename to search for.
847 * ext [I] File extension to append to file name. The first
848 * character must be a period. This parameter is
849 * specified only if the filename given does not
850 * contain an extension.
851 * buflen [I] size of buffer, in characters
852 * buffer [O] buffer for found filename
853 * lastpart [O] address of pointer to last used character in
854 * buffer (the final '\')
856 * RETURNS
857 * Success: length of string copied into buffer, not including
858 * terminating null character. If the filename found is
859 * longer than the length of the buffer, the length of the
860 * filename is returned.
861 * Failure: Zero
863 * NOTES
864 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
865 * (tested on NT 4.0)
867 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
868 LPWSTR buffer, LPWSTR *lastpart )
870 DWORD ret = 0;
872 if (!name || !name[0])
874 SetLastError(ERROR_INVALID_PARAMETER);
875 return 0;
878 /* If the name contains an explicit path, ignore the path */
880 if (contains_pathW(name))
882 /* try first without extension */
883 if (RtlDoesFileExists_U( name ))
884 return GetFullPathNameW( name, buflen, buffer, lastpart );
886 if (ext)
888 LPCWSTR p = strrchrW( name, '.' );
889 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
890 ext = NULL; /* Ignore the specified extension */
893 /* Allocate a buffer for the file name and extension */
894 if (ext)
896 LPWSTR tmp;
897 DWORD len = strlenW(name) + strlenW(ext);
899 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
901 SetLastError( ERROR_OUTOFMEMORY );
902 return 0;
904 strcpyW( tmp, name );
905 strcatW( tmp, ext );
906 if (RtlDoesFileExists_U( tmp ))
907 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
908 HeapFree( GetProcessHeap(), 0, tmp );
911 else if (path && path[0]) /* search in the specified path */
913 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
914 buffer, lastpart ) / sizeof(WCHAR);
916 else /* search in active context and default path */
918 WCHAR *dll_path = NULL, *search = NULL;
919 DWORD req_len, name_len;
921 req_len = name_len = strlenW(name);
923 if (strchrW( name, '.' )) ext = NULL;
924 if (ext)
926 DWORD ext_len = strlenW(ext);
928 req_len += ext_len;
929 name_len += ext_len;
931 search = HeapAlloc( GetProcessHeap(), 0, (name_len + ext_len + 1) * sizeof(WCHAR) );
932 if (!search)
934 SetLastError( ERROR_OUTOFMEMORY );
935 return 0;
937 strcpyW( search, name );
938 strcatW( search, ext );
939 name = search;
941 /* now that we have combined name we don't need extension any more */
944 /* When file is found with activation context no attempt is made
945 to check if it's really exist, path is returned only basing on context info. */
946 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
948 DWORD path_len;
950 path_len = strlenW(dll_path);
951 req_len += path_len;
953 if (lastpart) *lastpart = NULL;
955 /* count null termination char too */
956 if (req_len + 1 <= buflen)
958 memcpy( buffer, dll_path, path_len * sizeof(WCHAR) );
959 memcpy( &buffer[path_len], name, name_len * sizeof(WCHAR) );
960 buffer[req_len] = 0;
961 if (lastpart) *lastpart = buffer + path_len;
962 ret = req_len;
964 else
965 ret = req_len + 1;
967 HeapFree( GetProcessHeap(), 0, dll_path );
968 HeapFree( GetProcessHeap(), 0, search );
970 else
972 if ((dll_path = MODULE_get_dll_load_path( NULL )))
974 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
975 buffer, lastpart ) / sizeof(WCHAR);
976 HeapFree( GetProcessHeap(), 0, dll_path );
977 HeapFree( GetProcessHeap(), 0, search );
979 else
981 SetLastError( ERROR_OUTOFMEMORY );
982 return 0;
987 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
988 else TRACE( "found %s\n", debugstr_w(buffer) );
989 return ret;
993 /***********************************************************************
994 * SearchPathA (KERNEL32.@)
996 * See SearchPathW.
998 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
999 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
1001 WCHAR *pathW = NULL, *nameW, *extW = NULL;
1002 WCHAR bufferW[MAX_PATH];
1003 DWORD ret;
1005 if (!name)
1007 SetLastError(ERROR_INVALID_PARAMETER);
1008 return 0;
1011 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
1012 if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
1014 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
1016 HeapFree( GetProcessHeap(), 0, pathW );
1017 return 0;
1020 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
1022 HeapFree( GetProcessHeap(), 0, pathW );
1023 HeapFree( GetProcessHeap(), 0, extW );
1025 if (!ret) return 0;
1026 if (ret > MAX_PATH)
1028 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1029 return 0;
1031 ret = copy_filename_WtoA( bufferW, buffer, buflen );
1032 if (buflen > ret && lastpart)
1033 *lastpart = strrchr(buffer, '\\') + 1;
1034 return ret;
1037 static BOOL is_same_file(HANDLE h1, HANDLE h2)
1039 int fd1;
1040 BOOL ret = FALSE;
1041 if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
1043 int fd2;
1044 if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
1046 struct stat stat1, stat2;
1047 if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
1048 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
1049 wine_server_release_fd(h2, fd2);
1051 wine_server_release_fd(h1, fd1);
1053 return ret;
1056 /**************************************************************************
1057 * CopyFileW (KERNEL32.@)
1059 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1061 return CopyFileExW( source, dest, NULL, NULL, NULL,
1062 fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
1066 /**************************************************************************
1067 * CopyFileA (KERNEL32.@)
1069 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1071 WCHAR *sourceW, *destW;
1072 BOOL ret;
1074 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1075 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1077 ret = CopyFileW( sourceW, destW, fail_if_exists );
1079 HeapFree( GetProcessHeap(), 0, destW );
1080 return ret;
1084 /**************************************************************************
1085 * CopyFileExW (KERNEL32.@)
1087 BOOL WINAPI CopyFileExW(LPCWSTR source, LPCWSTR dest,
1088 LPPROGRESS_ROUTINE progress, LPVOID param,
1089 LPBOOL cancel_ptr, DWORD flags)
1091 static const int buffer_size = 65536;
1092 HANDLE h1, h2;
1093 BY_HANDLE_FILE_INFORMATION info;
1094 DWORD count;
1095 BOOL ret = FALSE;
1096 char *buffer;
1098 if (!source || !dest)
1100 SetLastError(ERROR_INVALID_PARAMETER);
1101 return FALSE;
1103 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1105 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1106 return FALSE;
1109 TRACE("%s -> %s, %x\n", debugstr_w(source), debugstr_w(dest), flags);
1111 if ((h1 = CreateFileW(source, GENERIC_READ,
1112 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1113 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1115 WARN("Unable to open source %s\n", debugstr_w(source));
1116 HeapFree( GetProcessHeap(), 0, buffer );
1117 return FALSE;
1120 if (!GetFileInformationByHandle( h1, &info ))
1122 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1123 HeapFree( GetProcessHeap(), 0, buffer );
1124 CloseHandle( h1 );
1125 return FALSE;
1128 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
1130 BOOL same_file = FALSE;
1131 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1132 OPEN_EXISTING, 0, 0);
1133 if (h2 != INVALID_HANDLE_VALUE)
1135 same_file = is_same_file( h1, h2 );
1136 CloseHandle( h2 );
1138 if (same_file)
1140 HeapFree( GetProcessHeap(), 0, buffer );
1141 CloseHandle( h1 );
1142 SetLastError( ERROR_SHARING_VIOLATION );
1143 return FALSE;
1147 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1148 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
1149 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1151 WARN("Unable to open dest %s\n", debugstr_w(dest));
1152 HeapFree( GetProcessHeap(), 0, buffer );
1153 CloseHandle( h1 );
1154 return FALSE;
1157 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
1159 char *p = buffer;
1160 while (count != 0)
1162 DWORD res;
1163 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1164 p += res;
1165 count -= res;
1168 ret = TRUE;
1169 done:
1170 /* Maintain the timestamp of source file to destination file */
1171 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
1172 HeapFree( GetProcessHeap(), 0, buffer );
1173 CloseHandle( h1 );
1174 CloseHandle( h2 );
1175 return ret;
1179 /**************************************************************************
1180 * CopyFileExA (KERNEL32.@)
1182 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1183 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1184 LPBOOL cancelFlagPointer, DWORD copyFlags)
1186 WCHAR *sourceW, *destW;
1187 BOOL ret;
1189 /* can't use the TEB buffer since we may have a callback routine */
1190 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1191 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1193 HeapFree( GetProcessHeap(), 0, sourceW );
1194 return FALSE;
1196 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1197 cancelFlagPointer, copyFlags);
1198 HeapFree( GetProcessHeap(), 0, sourceW );
1199 HeapFree( GetProcessHeap(), 0, destW );
1200 return ret;
1204 /**************************************************************************
1205 * MoveFileWithProgressW (KERNEL32.@)
1207 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1208 LPPROGRESS_ROUTINE fnProgress,
1209 LPVOID param, DWORD flag )
1211 FILE_BASIC_INFORMATION info;
1212 UNICODE_STRING nt_name;
1213 OBJECT_ATTRIBUTES attr;
1214 IO_STATUS_BLOCK io;
1215 NTSTATUS status;
1216 HANDLE source_handle = 0, dest_handle;
1217 ANSI_STRING source_unix, dest_unix;
1219 TRACE("(%s,%s,%p,%p,%04x)\n",
1220 debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1222 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1223 return add_boot_rename_entry( source, dest, flag );
1225 if (!dest)
1226 return DeleteFileW( source );
1228 if (flag & MOVEFILE_WRITE_THROUGH)
1229 FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1231 /* check if we are allowed to rename the source */
1233 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1235 SetLastError( ERROR_PATH_NOT_FOUND );
1236 return FALSE;
1238 source_unix.Buffer = NULL;
1239 dest_unix.Buffer = NULL;
1240 attr.Length = sizeof(attr);
1241 attr.RootDirectory = 0;
1242 attr.Attributes = OBJ_CASE_INSENSITIVE;
1243 attr.ObjectName = &nt_name;
1244 attr.SecurityDescriptor = NULL;
1245 attr.SecurityQualityOfService = NULL;
1247 status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1248 if (status == STATUS_SUCCESS)
1249 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1250 RtlFreeUnicodeString( &nt_name );
1251 if (status != STATUS_SUCCESS)
1253 SetLastError( RtlNtStatusToDosError(status) );
1254 goto error;
1256 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1257 if (status != STATUS_SUCCESS)
1259 SetLastError( RtlNtStatusToDosError(status) );
1260 goto error;
1263 /* we must have write access to the destination, and it must */
1264 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1266 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1268 SetLastError( ERROR_PATH_NOT_FOUND );
1269 goto error;
1271 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1272 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1273 if (status == STATUS_SUCCESS) /* destination exists */
1275 NtClose( dest_handle );
1276 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1278 SetLastError( ERROR_ALREADY_EXISTS );
1279 RtlFreeUnicodeString( &nt_name );
1280 goto error;
1282 else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1284 SetLastError( ERROR_ACCESS_DENIED );
1285 goto error;
1288 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1290 SetLastError( RtlNtStatusToDosError(status) );
1291 RtlFreeUnicodeString( &nt_name );
1292 goto error;
1295 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1296 RtlFreeUnicodeString( &nt_name );
1297 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1299 SetLastError( RtlNtStatusToDosError(status) );
1300 goto error;
1303 /* now perform the rename */
1305 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1307 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1309 NtClose( source_handle );
1310 RtlFreeAnsiString( &source_unix );
1311 RtlFreeAnsiString( &dest_unix );
1312 if (!CopyFileExW( source, dest, fnProgress,
1313 param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1314 return FALSE;
1315 return DeleteFileW( source );
1317 FILE_SetDosError();
1318 /* if we created the destination, remove it */
1319 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1320 goto error;
1323 /* fixup executable permissions */
1325 if (is_executable( source ) != is_executable( dest ))
1327 struct stat fstat;
1328 if (stat( dest_unix.Buffer, &fstat ) != -1)
1330 if (is_executable( dest ))
1331 /* set executable bit where read bit is set */
1332 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1333 else
1334 fstat.st_mode &= ~0111;
1335 chmod( dest_unix.Buffer, fstat.st_mode );
1339 NtClose( source_handle );
1340 RtlFreeAnsiString( &source_unix );
1341 RtlFreeAnsiString( &dest_unix );
1342 return TRUE;
1344 error:
1345 if (source_handle) NtClose( source_handle );
1346 RtlFreeAnsiString( &source_unix );
1347 RtlFreeAnsiString( &dest_unix );
1348 return FALSE;
1351 /**************************************************************************
1352 * MoveFileWithProgressA (KERNEL32.@)
1354 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1355 LPPROGRESS_ROUTINE fnProgress,
1356 LPVOID param, DWORD flag )
1358 WCHAR *sourceW, *destW;
1359 BOOL ret;
1361 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1362 if (dest)
1364 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1366 else
1367 destW = NULL;
1369 ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1370 HeapFree( GetProcessHeap(), 0, destW );
1371 return ret;
1374 /**************************************************************************
1375 * MoveFileExW (KERNEL32.@)
1377 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1379 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1382 /**************************************************************************
1383 * MoveFileExA (KERNEL32.@)
1385 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1387 return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1391 /**************************************************************************
1392 * MoveFileW (KERNEL32.@)
1394 * Move file or directory
1396 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1398 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1402 /**************************************************************************
1403 * MoveFileA (KERNEL32.@)
1405 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1407 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1411 /*************************************************************************
1412 * CreateHardLinkW (KERNEL32.@)
1414 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1415 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1417 NTSTATUS status;
1418 UNICODE_STRING ntDest, ntSource;
1419 ANSI_STRING unixDest, unixSource;
1420 BOOL ret = FALSE;
1422 TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1423 debugstr_w(lpExistingFileName), lpSecurityAttributes);
1425 ntDest.Buffer = ntSource.Buffer = NULL;
1426 if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1427 !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1429 SetLastError( ERROR_PATH_NOT_FOUND );
1430 goto err;
1433 unixSource.Buffer = unixDest.Buffer = NULL;
1434 status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1435 if (!status)
1437 status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1438 if (!status) /* destination must not exist */
1440 status = STATUS_OBJECT_NAME_EXISTS;
1441 } else if (status == STATUS_NO_SUCH_FILE)
1443 status = STATUS_SUCCESS;
1447 if (status)
1448 SetLastError( RtlNtStatusToDosError(status) );
1449 else if (!link( unixSource.Buffer, unixDest.Buffer ))
1451 TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1452 debugstr_a( unixSource.Buffer ));
1453 ret = TRUE;
1455 else
1456 FILE_SetDosError();
1458 RtlFreeAnsiString( &unixSource );
1459 RtlFreeAnsiString( &unixDest );
1461 err:
1462 RtlFreeUnicodeString( &ntSource );
1463 RtlFreeUnicodeString( &ntDest );
1464 return ret;
1468 /*************************************************************************
1469 * CreateHardLinkA (KERNEL32.@)
1471 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1472 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1474 WCHAR *sourceW, *destW;
1475 BOOL res;
1477 if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1479 return FALSE;
1481 if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1483 HeapFree( GetProcessHeap(), 0, sourceW );
1484 return FALSE;
1487 res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1489 HeapFree( GetProcessHeap(), 0, sourceW );
1490 HeapFree( GetProcessHeap(), 0, destW );
1492 return res;
1496 /***********************************************************************
1497 * CreateDirectoryW (KERNEL32.@)
1498 * RETURNS:
1499 * TRUE : success
1500 * FALSE : failure
1501 * ERROR_DISK_FULL: on full disk
1502 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1503 * ERROR_ACCESS_DENIED: on permission problems
1504 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1506 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1508 OBJECT_ATTRIBUTES attr;
1509 UNICODE_STRING nt_name;
1510 IO_STATUS_BLOCK io;
1511 NTSTATUS status;
1512 HANDLE handle;
1513 BOOL ret = FALSE;
1515 TRACE( "%s\n", debugstr_w(path) );
1517 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1519 SetLastError( ERROR_PATH_NOT_FOUND );
1520 return FALSE;
1522 attr.Length = sizeof(attr);
1523 attr.RootDirectory = 0;
1524 attr.Attributes = OBJ_CASE_INSENSITIVE;
1525 attr.ObjectName = &nt_name;
1526 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1527 attr.SecurityQualityOfService = NULL;
1529 status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1530 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1531 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1533 if (status == STATUS_SUCCESS)
1535 NtClose( handle );
1536 ret = TRUE;
1538 else SetLastError( RtlNtStatusToDosError(status) );
1540 RtlFreeUnicodeString( &nt_name );
1541 return ret;
1545 /***********************************************************************
1546 * CreateDirectoryA (KERNEL32.@)
1548 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1550 WCHAR *pathW;
1552 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1553 return CreateDirectoryW( pathW, sa );
1557 /***********************************************************************
1558 * CreateDirectoryExA (KERNEL32.@)
1560 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1562 WCHAR *pathW, *templateW = NULL;
1563 BOOL ret;
1565 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1566 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1568 ret = CreateDirectoryExW( templateW, pathW, sa );
1569 HeapFree( GetProcessHeap(), 0, templateW );
1570 return ret;
1574 /***********************************************************************
1575 * CreateDirectoryExW (KERNEL32.@)
1577 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1579 return CreateDirectoryW( path, sa );
1583 /***********************************************************************
1584 * RemoveDirectoryW (KERNEL32.@)
1586 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1588 OBJECT_ATTRIBUTES attr;
1589 UNICODE_STRING nt_name;
1590 ANSI_STRING unix_name;
1591 IO_STATUS_BLOCK io;
1592 NTSTATUS status;
1593 HANDLE handle;
1594 BOOL ret = FALSE;
1596 TRACE( "%s\n", debugstr_w(path) );
1598 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1600 SetLastError( ERROR_PATH_NOT_FOUND );
1601 return FALSE;
1603 attr.Length = sizeof(attr);
1604 attr.RootDirectory = 0;
1605 attr.Attributes = OBJ_CASE_INSENSITIVE;
1606 attr.ObjectName = &nt_name;
1607 attr.SecurityDescriptor = NULL;
1608 attr.SecurityQualityOfService = NULL;
1610 status = NtOpenFile( &handle, DELETE, &attr, &io,
1611 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1612 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1613 if (status == STATUS_SUCCESS)
1614 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1615 RtlFreeUnicodeString( &nt_name );
1617 if (status != STATUS_SUCCESS)
1619 SetLastError( RtlNtStatusToDosError(status) );
1620 return FALSE;
1623 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1624 RtlFreeAnsiString( &unix_name );
1625 NtClose( handle );
1626 return ret;
1630 /***********************************************************************
1631 * RemoveDirectoryA (KERNEL32.@)
1633 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1635 WCHAR *pathW;
1637 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1638 return RemoveDirectoryW( pathW );
1642 /***********************************************************************
1643 * GetCurrentDirectoryW (KERNEL32.@)
1645 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1647 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1651 /***********************************************************************
1652 * GetCurrentDirectoryA (KERNEL32.@)
1654 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1656 WCHAR bufferW[MAX_PATH];
1657 DWORD ret;
1659 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1661 /* Win9x catches access violations here, returning zero.
1662 * This behaviour resulted in some people not noticing
1663 * that they got the argument order wrong. So let's be
1664 * nice and fail gracefully if buf is invalid and looks
1665 * more like a buflen. */
1666 SetLastError(ERROR_INVALID_PARAMETER);
1667 return 0;
1670 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1671 if (!ret) return 0;
1672 if (ret > sizeof(bufferW))
1674 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1675 return 0;
1677 return copy_filename_WtoA( bufferW, buf, buflen );
1681 /***********************************************************************
1682 * SetCurrentDirectoryW (KERNEL32.@)
1684 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1686 UNICODE_STRING dirW;
1687 NTSTATUS status;
1689 RtlInitUnicodeString( &dirW, dir );
1690 status = RtlSetCurrentDirectory_U( &dirW );
1691 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1692 return !status;
1696 /***********************************************************************
1697 * SetCurrentDirectoryA (KERNEL32.@)
1699 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1701 WCHAR *dirW;
1702 UNICODE_STRING strW;
1703 NTSTATUS status;
1705 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1706 RtlInitUnicodeString( &strW, dirW );
1707 status = RtlSetCurrentDirectory_U( &strW );
1708 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1709 return !status;
1713 /***********************************************************************
1714 * GetWindowsDirectoryW (KERNEL32.@)
1716 * See comment for GetWindowsDirectoryA.
1718 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1720 UINT len = strlenW( DIR_Windows ) + 1;
1721 if (path && count >= len)
1723 strcpyW( path, DIR_Windows );
1724 len--;
1726 return len;
1730 /***********************************************************************
1731 * GetWindowsDirectoryA (KERNEL32.@)
1733 * Return value:
1734 * If buffer is large enough to hold full path and terminating '\0' character
1735 * function copies path to buffer and returns length of the path without '\0'.
1736 * Otherwise function returns required size including '\0' character and
1737 * does not touch the buffer.
1739 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1741 return copy_filename_WtoA( DIR_Windows, path, count );
1745 /***********************************************************************
1746 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1748 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1750 return GetWindowsDirectoryA( path, count );
1754 /***********************************************************************
1755 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1757 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1759 return GetWindowsDirectoryW( path, count );
1763 /***********************************************************************
1764 * GetSystemDirectoryW (KERNEL32.@)
1766 * See comment for GetWindowsDirectoryA.
1768 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1770 UINT len = strlenW( DIR_System ) + 1;
1771 if (path && count >= len)
1773 strcpyW( path, DIR_System );
1774 len--;
1776 return len;
1780 /***********************************************************************
1781 * GetSystemDirectoryA (KERNEL32.@)
1783 * See comment for GetWindowsDirectoryA.
1785 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1787 return copy_filename_WtoA( DIR_System, path, count );
1791 /***********************************************************************
1792 * GetSystemWow64DirectoryW (KERNEL32.@)
1794 * As seen on MSDN
1795 * - On Win32 we should return ERROR_CALL_NOT_IMPLEMENTED
1796 * - On Win64 we should return the SysWow64 (system64) directory
1798 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1800 UINT len;
1802 if (!DIR_SysWow64)
1804 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1805 return 0;
1807 len = strlenW( DIR_SysWow64 ) + 1;
1808 if (path && count >= len)
1810 strcpyW( path, DIR_SysWow64 );
1811 len--;
1813 return len;
1817 /***********************************************************************
1818 * GetSystemWow64DirectoryA (KERNEL32.@)
1820 * See comment for GetWindowsWow64DirectoryW.
1822 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1824 if (!DIR_SysWow64)
1826 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1827 return 0;
1829 return copy_filename_WtoA( DIR_SysWow64, path, count );
1833 /***********************************************************************
1834 * Wow64EnableWow64FsRedirection (KERNEL32.@)
1836 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1838 NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1839 if (status) SetLastError( RtlNtStatusToDosError(status) );
1840 return !status;
1844 /***********************************************************************
1845 * Wow64DisableWow64FsRedirection (KERNEL32.@)
1847 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1849 NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1850 if (status) SetLastError( RtlNtStatusToDosError(status) );
1851 return !status;
1855 /***********************************************************************
1856 * Wow64RevertWow64FsRedirection (KERNEL32.@)
1858 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1860 NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1861 if (status) SetLastError( RtlNtStatusToDosError(status) );
1862 return !status;
1866 /***********************************************************************
1867 * NeedCurrentDirectoryForExePathW (KERNEL32.@)
1869 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1871 static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1872 'C','u','r','r','e','n','t',
1873 'D','i','r','e','c','t','o','r','y',
1874 'I','n','E','x','e','P','a','t','h',0};
1875 WCHAR env_val;
1877 /* MSDN mentions some 'registry location'. We do not use registry. */
1878 FIXME("(%s): partial stub\n", debugstr_w(name));
1880 if (strchrW(name, '\\'))
1881 return TRUE;
1883 /* Check the existence of the variable, not value */
1884 if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1885 return TRUE;
1887 return FALSE;
1891 /***********************************************************************
1892 * NeedCurrentDirectoryForExePathA (KERNEL32.@)
1894 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1896 WCHAR *nameW;
1898 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1899 return NeedCurrentDirectoryForExePathW( nameW );
1903 /***********************************************************************
1904 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1906 * Return the full Unix file name for a given path.
1907 * Returned buffer must be freed by caller.
1909 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1911 UNICODE_STRING nt_name;
1912 ANSI_STRING unix_name;
1913 NTSTATUS status;
1915 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1916 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1917 RtlFreeUnicodeString( &nt_name );
1918 if (status && status != STATUS_NO_SUCH_FILE)
1920 SetLastError( RtlNtStatusToDosError( status ) );
1921 return NULL;
1923 return unix_name.Buffer;
1927 /***********************************************************************
1928 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1930 * Return the full DOS file name for a given Unix path.
1931 * Returned buffer must be freed by caller.
1933 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1935 UNICODE_STRING nt_name;
1936 ANSI_STRING unix_name;
1937 NTSTATUS status;
1938 DWORD len;
1940 RtlInitAnsiString( &unix_name, str );
1941 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1942 if (status)
1944 SetLastError( RtlNtStatusToDosError( status ) );
1945 return NULL;
1947 if (nt_name.Buffer[5] == ':')
1949 /* get rid of the \??\ prefix */
1950 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1951 len = nt_name.Length - 4 * sizeof(WCHAR);
1952 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1953 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1955 else
1956 nt_name.Buffer[1] = '\\';
1957 return nt_name.Buffer;
1960 /*************************************************************************
1961 * CreateSymbolicLinkW (KERNEL32.@)
1963 BOOL WINAPI CreateSymbolicLinkW(LPCWSTR link, LPCWSTR target, DWORD flags)
1965 FIXME("(%s %s %d): stub\n", debugstr_w(link), debugstr_w(target), flags);
1966 return TRUE;
1969 /*************************************************************************
1970 * CreateSymbolicLinkA (KERNEL32.@)
1972 BOOL WINAPI CreateSymbolicLinkA(LPCSTR link, LPCSTR target, DWORD flags)
1974 FIXME("(%s %s %d): stub\n", debugstr_a(link), debugstr_a(target), flags);
1975 return TRUE;
1978 /*************************************************************************
1979 * CreateHardLinkTransactedA (KERNEL32.@)
1981 BOOL WINAPI CreateHardLinkTransactedA(LPCSTR link, LPCSTR target, LPSECURITY_ATTRIBUTES sa, HANDLE transaction)
1983 FIXME("(%s %s %p %p): stub\n", debugstr_a(link), debugstr_a(target), sa, transaction);
1984 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1985 return FALSE;
1988 /*************************************************************************
1989 * CreateHardLinkTransactedW (KERNEL32.@)
1991 BOOL WINAPI CreateHardLinkTransactedW(LPCWSTR link, LPCWSTR target, LPSECURITY_ATTRIBUTES sa, HANDLE transaction)
1993 FIXME("(%s %s %p %p): stub\n", debugstr_w(link), debugstr_w(target), sa, transaction);
1994 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1995 return FALSE;