kernel32/tests: Add tabular UTF-7 encoding tests.
[wine.git] / dlls / kernel32 / path.c
blobbb167a0f190d69b69ee55c2524f3ab35c44c4522
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 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
33 #include "winerror.h"
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winternl.h"
40 #include "kernel_private.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(file);
46 #define MAX_PATHNAME_LEN 1024
49 /* check if a file name is for an executable file (.exe or .com) */
50 static inline BOOL is_executable( const WCHAR *name )
52 static const WCHAR exeW[] = {'.','e','x','e',0};
53 static const WCHAR comW[] = {'.','c','o','m',0};
54 int len = strlenW(name);
56 if (len < 4) return FALSE;
57 return (!strcmpiW( name + len - 4, exeW ) || !strcmpiW( name + len - 4, comW ));
60 /***********************************************************************
61 * copy_filename_WtoA
63 * copy a file name back to OEM/Ansi, but only if the buffer is large enough
65 static DWORD copy_filename_WtoA( LPCWSTR nameW, LPSTR buffer, DWORD len )
67 UNICODE_STRING strW;
68 DWORD ret;
69 BOOL is_ansi = AreFileApisANSI();
71 RtlInitUnicodeString( &strW, nameW );
73 ret = is_ansi ? RtlUnicodeStringToAnsiSize(&strW) : RtlUnicodeStringToOemSize(&strW);
74 if (buffer && ret <= len)
76 ANSI_STRING str;
78 str.Buffer = buffer;
79 str.MaximumLength = min( len, UNICODE_STRING_MAX_CHARS );
80 if (is_ansi)
81 RtlUnicodeStringToAnsiString( &str, &strW, FALSE );
82 else
83 RtlUnicodeStringToOemString( &str, &strW, FALSE );
84 ret = str.Length; /* length without terminating 0 */
86 return ret;
89 /***********************************************************************
90 * add_boot_rename_entry
92 * Adds an entry to the registry that is loaded when windows boots and
93 * checks if there are some files to be removed or renamed/moved.
94 * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
95 * non-NULL then the file is moved, otherwise it is deleted. The
96 * entry of the registry key is always appended with two zero
97 * terminated strings. If <fn2> is NULL then the second entry is
98 * simply a single 0-byte. Otherwise the second filename goes
99 * there. The entries are prepended with \??\ before the path and the
100 * second filename gets also a '!' as the first character if
101 * MOVEFILE_REPLACE_EXISTING is set. After the final string another
102 * 0-byte follows to indicate the end of the strings.
103 * i.e.:
104 * \??\D:\test\file1[0]
105 * !\??\D:\test\file1_renamed[0]
106 * \??\D:\Test|delete[0]
107 * [0] <- file is to be deleted, second string empty
108 * \??\D:\test\file2[0]
109 * !\??\D:\test\file2_renamed[0]
110 * [0] <- indicates end of strings
112 * or:
113 * \??\D:\test\file1[0]
114 * !\??\D:\test\file1_renamed[0]
115 * \??\D:\Test|delete[0]
116 * [0] <- file is to be deleted, second string empty
117 * [0] <- indicates end of strings
120 static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
122 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
123 'F','i','l','e','R','e','n','a','m','e',
124 'O','p','e','r','a','t','i','o','n','s',0};
125 static const WCHAR SessionW[] = {'M','a','c','h','i','n','e','\\',
126 'S','y','s','t','e','m','\\',
127 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
128 'C','o','n','t','r','o','l','\\',
129 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
130 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
132 OBJECT_ATTRIBUTES attr;
133 UNICODE_STRING nameW, source_name, dest_name;
134 KEY_VALUE_PARTIAL_INFORMATION *info;
135 BOOL rc = FALSE;
136 HANDLE Reboot = 0;
137 DWORD len1, len2;
138 DWORD DataSize = 0;
139 BYTE *Buffer = NULL;
140 WCHAR *p;
142 if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
144 SetLastError( ERROR_PATH_NOT_FOUND );
145 return FALSE;
147 dest_name.Buffer = NULL;
148 if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
150 RtlFreeUnicodeString( &source_name );
151 SetLastError( ERROR_PATH_NOT_FOUND );
152 return FALSE;
155 attr.Length = sizeof(attr);
156 attr.RootDirectory = 0;
157 attr.ObjectName = &nameW;
158 attr.Attributes = 0;
159 attr.SecurityDescriptor = NULL;
160 attr.SecurityQualityOfService = NULL;
161 RtlInitUnicodeString( &nameW, SessionW );
163 if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
165 WARN("Error creating key for reboot management [%s]\n",
166 "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
167 RtlFreeUnicodeString( &source_name );
168 RtlFreeUnicodeString( &dest_name );
169 return FALSE;
172 len1 = source_name.Length + sizeof(WCHAR);
173 if (dest)
175 len2 = dest_name.Length + sizeof(WCHAR);
176 if (flags & MOVEFILE_REPLACE_EXISTING)
177 len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
179 else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
181 RtlInitUnicodeString( &nameW, ValueName );
183 /* First we check if the key exists and if so how many bytes it already contains. */
184 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
185 NULL, 0, &DataSize ) == STATUS_BUFFER_TOO_SMALL)
187 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
188 goto Quit;
189 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
190 Buffer, DataSize, &DataSize )) goto Quit;
191 info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
192 if (info->Type != REG_MULTI_SZ) goto Quit;
193 if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR); /* remove terminating null (will be added back later) */
195 else
197 DataSize = info_size;
198 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
199 goto Quit;
202 memcpy( Buffer + DataSize, source_name.Buffer, len1 );
203 DataSize += len1;
204 p = (WCHAR *)(Buffer + DataSize);
205 if (dest)
207 if (flags & MOVEFILE_REPLACE_EXISTING)
208 *p++ = '!';
209 memcpy( p, dest_name.Buffer, len2 );
210 DataSize += len2;
212 else
214 *p = 0;
215 DataSize += sizeof(WCHAR);
218 /* add final null */
219 p = (WCHAR *)(Buffer + DataSize);
220 *p = 0;
221 DataSize += sizeof(WCHAR);
223 rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
225 Quit:
226 RtlFreeUnicodeString( &source_name );
227 RtlFreeUnicodeString( &dest_name );
228 if (Reboot) NtClose(Reboot);
229 HeapFree( GetProcessHeap(), 0, Buffer );
230 return(rc);
234 /***********************************************************************
235 * GetFullPathNameW (KERNEL32.@)
236 * NOTES
237 * if the path closed with '\', *lastpart is 0
239 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
240 LPWSTR *lastpart )
242 return RtlGetFullPathName_U(name, len * sizeof(WCHAR), buffer, lastpart) / sizeof(WCHAR);
245 /***********************************************************************
246 * GetFullPathNameA (KERNEL32.@)
247 * NOTES
248 * if the path closed with '\', *lastpart is 0
250 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
251 LPSTR *lastpart )
253 WCHAR *nameW;
254 WCHAR bufferW[MAX_PATH], *lastpartW = NULL;
255 DWORD ret;
257 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
259 ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, &lastpartW);
261 if (!ret) return 0;
262 if (ret > MAX_PATH)
264 SetLastError(ERROR_FILENAME_EXCED_RANGE);
265 return 0;
267 ret = copy_filename_WtoA( bufferW, buffer, len );
268 if (ret < len && lastpart)
270 if (lastpartW)
271 *lastpart = buffer + FILE_name_WtoA( bufferW, lastpartW - bufferW, NULL, 0 );
272 else
273 *lastpart = NULL;
275 return ret;
279 /***********************************************************************
280 * GetLongPathNameW (KERNEL32.@)
282 * NOTES
283 * observed (Win2000):
284 * shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
285 * shortpath="": LastError=ERROR_PATH_NOT_FOUND, ret=0
287 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
289 WCHAR tmplongpath[MAX_PATHNAME_LEN];
290 LPCWSTR p;
291 DWORD sp = 0, lp = 0;
292 DWORD tmplen;
293 BOOL unixabsolute;
294 WIN32_FIND_DATAW wfd;
295 HANDLE goit;
297 if (!shortpath)
299 SetLastError(ERROR_INVALID_PARAMETER);
300 return 0;
302 if (!shortpath[0])
304 SetLastError(ERROR_PATH_NOT_FOUND);
305 return 0;
308 TRACE("%s,%p,%d\n", debugstr_w(shortpath), longpath, longlen);
310 if (shortpath[0] == '\\' && shortpath[1] == '\\')
312 FIXME("UNC pathname %s\n", debugstr_w(shortpath));
314 tmplen = strlenW(shortpath);
315 if (tmplen < longlen)
317 if (longpath != shortpath) strcpyW( longpath, shortpath );
318 return tmplen;
320 return tmplen + 1;
323 unixabsolute = (shortpath[0] == '/');
325 /* check for drive letter */
326 if (!unixabsolute && shortpath[1] == ':' )
328 tmplongpath[0] = shortpath[0];
329 tmplongpath[1] = ':';
330 lp = sp = 2;
333 while (shortpath[sp])
335 /* check for path delimiters and reproduce them */
336 if (shortpath[sp] == '\\' || shortpath[sp] == '/')
338 if (!lp || tmplongpath[lp-1] != '\\')
340 /* strip double "\\" */
341 tmplongpath[lp++] = '\\';
343 tmplongpath[lp] = 0; /* terminate string */
344 sp++;
345 continue;
348 p = shortpath + sp;
349 if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
351 tmplongpath[lp++] = *p++;
352 tmplongpath[lp++] = *p++;
354 for (; *p && *p != '/' && *p != '\\'; p++);
355 tmplen = p - (shortpath + sp);
356 lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
358 if (tmplongpath[lp] == '.')
360 if (tmplen == 1 || (tmplen == 2 && tmplongpath[lp + 1] == '.'))
362 lp += tmplen;
363 sp += tmplen;
364 continue;
368 /* Check if the file exists and use the existing file name */
369 goit = FindFirstFileW(tmplongpath, &wfd);
370 if (goit == INVALID_HANDLE_VALUE)
372 TRACE("not found %s!\n", debugstr_w(tmplongpath));
373 SetLastError ( ERROR_FILE_NOT_FOUND );
374 return 0;
376 FindClose(goit);
377 strcpyW(tmplongpath + lp, wfd.cFileName);
378 lp += strlenW(tmplongpath + lp);
379 sp += tmplen;
381 tmplen = strlenW(shortpath) - 1;
382 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
383 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
384 tmplongpath[lp++] = shortpath[tmplen];
385 tmplongpath[lp] = 0;
387 tmplen = strlenW(tmplongpath) + 1;
388 if (tmplen <= longlen)
390 strcpyW(longpath, tmplongpath);
391 TRACE("returning %s\n", debugstr_w(longpath));
392 tmplen--; /* length without 0 */
395 return tmplen;
398 /***********************************************************************
399 * GetLongPathNameA (KERNEL32.@)
401 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
403 WCHAR *shortpathW;
404 WCHAR longpathW[MAX_PATH];
405 DWORD ret;
407 TRACE("%s\n", debugstr_a(shortpath));
409 if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
411 ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
413 if (!ret) return 0;
414 if (ret > MAX_PATH)
416 SetLastError(ERROR_FILENAME_EXCED_RANGE);
417 return 0;
419 return copy_filename_WtoA( longpathW, longpath, longlen );
423 /***********************************************************************
424 * GetShortPathNameW (KERNEL32.@)
426 * NOTES
427 * observed:
428 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
429 * longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
431 * more observations ( with NT 3.51 (WinDD) ):
432 * longpath <= 8.3 -> just copy longpath to shortpath
433 * longpath > 8.3 ->
434 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
435 * b) file does exist -> set the short filename.
436 * - trailing slashes are reproduced in the short name, even if the
437 * file is not a directory
438 * - the absolute/relative path of the short name is reproduced like found
439 * in the long name
440 * - longpath and shortpath may have the same address
441 * Peter Ganten, 1999
443 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
445 WCHAR tmpshortpath[MAX_PATHNAME_LEN];
446 LPCWSTR p;
447 DWORD sp = 0, lp = 0;
448 DWORD tmplen;
449 WIN32_FIND_DATAW wfd;
450 HANDLE goit;
452 TRACE("%s\n", debugstr_w(longpath));
454 if (!longpath)
456 SetLastError(ERROR_INVALID_PARAMETER);
457 return 0;
459 if (!longpath[0])
461 SetLastError(ERROR_BAD_PATHNAME);
462 return 0;
465 /* check for drive letter */
466 if (longpath[0] != '/' && longpath[1] == ':' )
468 tmpshortpath[0] = longpath[0];
469 tmpshortpath[1] = ':';
470 sp = lp = 2;
473 while (longpath[lp])
475 /* check for path delimiters and reproduce them */
476 if (longpath[lp] == '\\' || longpath[lp] == '/')
478 if (!sp || tmpshortpath[sp-1] != '\\')
480 /* strip double "\\" */
481 tmpshortpath[sp] = '\\';
482 sp++;
484 tmpshortpath[sp] = 0; /* terminate string */
485 lp++;
486 continue;
489 p = longpath + lp;
490 if (lp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
492 tmpshortpath[sp++] = *p++;
493 tmpshortpath[sp++] = *p++;
495 for (; *p && *p != '/' && *p != '\\'; p++);
496 tmplen = p - (longpath + lp);
497 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
499 if (tmpshortpath[sp] == '.')
501 if (tmplen == 1 || (tmplen == 2 && tmpshortpath[sp + 1] == '.'))
503 sp += tmplen;
504 lp += tmplen;
505 continue;
509 /* Check if the file exists and use the existing short file name */
510 goit = FindFirstFileW(tmpshortpath, &wfd);
511 if (goit == INVALID_HANDLE_VALUE) goto notfound;
512 FindClose(goit);
513 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName);
514 sp += strlenW(tmpshortpath + sp);
515 lp += tmplen;
517 tmpshortpath[sp] = 0;
519 tmplen = strlenW(tmpshortpath) + 1;
520 if (tmplen <= shortlen)
522 strcpyW(shortpath, tmpshortpath);
523 TRACE("returning %s\n", debugstr_w(shortpath));
524 tmplen--; /* length without 0 */
527 return tmplen;
529 notfound:
530 TRACE("not found!\n" );
531 SetLastError ( ERROR_FILE_NOT_FOUND );
532 return 0;
535 /***********************************************************************
536 * GetShortPathNameA (KERNEL32.@)
538 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
540 WCHAR *longpathW;
541 WCHAR shortpathW[MAX_PATH];
542 DWORD ret;
544 TRACE("%s\n", debugstr_a(longpath));
546 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
548 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
550 if (!ret) return 0;
551 if (ret > MAX_PATH)
553 SetLastError(ERROR_FILENAME_EXCED_RANGE);
554 return 0;
556 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
560 /***********************************************************************
561 * GetTempPathA (KERNEL32.@)
563 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
565 WCHAR pathW[MAX_PATH];
566 UINT ret;
568 ret = GetTempPathW(MAX_PATH, pathW);
570 if (!ret)
571 return 0;
573 if (ret > MAX_PATH)
575 SetLastError(ERROR_FILENAME_EXCED_RANGE);
576 return 0;
578 return copy_filename_WtoA( pathW, path, count );
582 /***********************************************************************
583 * GetTempPathW (KERNEL32.@)
585 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
587 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
588 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
589 static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
590 WCHAR tmp_path[MAX_PATH];
591 UINT ret;
593 TRACE("%u,%p\n", count, path);
595 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
596 !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
597 !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
598 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
599 return 0;
601 if (ret > MAX_PATH)
603 SetLastError(ERROR_FILENAME_EXCED_RANGE);
604 return 0;
607 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
608 if (!ret) return 0;
610 if (ret > MAX_PATH - 2)
612 SetLastError(ERROR_FILENAME_EXCED_RANGE);
613 return 0;
616 if (tmp_path[ret-1] != '\\')
618 tmp_path[ret++] = '\\';
619 tmp_path[ret] = '\0';
622 ret++; /* add space for terminating 0 */
624 if (count)
626 lstrcpynW(path, tmp_path, count);
627 if (count >= ret)
628 ret--; /* return length without 0 */
629 else if (count < 4)
630 path[0] = 0; /* avoid returning ambiguous "X:" */
633 TRACE("returning %u, %s\n", ret, debugstr_w(path));
634 return ret;
638 /***********************************************************************
639 * GetTempFileNameA (KERNEL32.@)
641 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
643 WCHAR *pathW, *prefixW = NULL;
644 WCHAR bufferW[MAX_PATH];
645 UINT ret;
647 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
648 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
650 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
651 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
653 HeapFree( GetProcessHeap(), 0, prefixW );
654 return ret;
657 /***********************************************************************
658 * GetTempFileNameW (KERNEL32.@)
660 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
662 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
664 int i;
665 LPWSTR p;
666 DWORD attr;
668 if ( !path || !buffer )
670 SetLastError( ERROR_INVALID_PARAMETER );
671 return 0;
674 /* ensure that the provided directory exists */
675 attr = GetFileAttributesW(path);
676 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
678 TRACE("path not found %s\n", debugstr_w(path));
679 SetLastError( ERROR_DIRECTORY );
680 return 0;
683 strcpyW( buffer, path );
684 p = buffer + strlenW(buffer);
686 /* add a \, if there isn't one */
687 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
689 if (prefix)
690 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
692 unique &= 0xffff;
694 if (unique) sprintfW( p, formatW, unique );
695 else
697 /* get a "random" unique number and try to create the file */
698 HANDLE handle;
699 UINT num = GetTickCount() & 0xffff;
700 static UINT last;
702 /* avoid using the same name twice in a short interval */
703 if (last - num < 10) num = last + 1;
704 if (!num) num = 1;
705 unique = num;
708 sprintfW( p, formatW, unique );
709 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
710 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
711 if (handle != INVALID_HANDLE_VALUE)
712 { /* We created it */
713 TRACE("created %s\n", debugstr_w(buffer) );
714 CloseHandle( handle );
715 last = unique;
716 break;
718 if (GetLastError() != ERROR_FILE_EXISTS &&
719 GetLastError() != ERROR_SHARING_VIOLATION)
720 break; /* No need to go on */
721 if (!(++unique & 0xffff)) unique = 1;
722 } while (unique != num);
725 TRACE("returning %s\n", debugstr_w(buffer) );
726 return unique;
730 /***********************************************************************
731 * contains_pathW
733 * Check if the file name contains a path; helper for SearchPathW.
734 * A relative path is not considered a path unless it starts with ./ or ../
736 static inline BOOL contains_pathW (LPCWSTR name)
738 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
739 if (name[0] != '.') return FALSE;
740 if (name[1] == '/' || name[1] == '\\') return TRUE;
741 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
744 /***********************************************************************
745 * find_actctx_dllpath
747 * Find the path (if any) of the dll from the activation context.
748 * Returned path doesn't include a name.
750 static NTSTATUS find_actctx_dllpath(const WCHAR *libname, WCHAR **path)
752 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
753 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
755 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
756 ACTCTX_SECTION_KEYED_DATA data;
757 UNICODE_STRING nameW;
758 NTSTATUS status;
759 SIZE_T needed, size = 1024;
760 WCHAR *p;
762 RtlInitUnicodeString( &nameW, libname );
763 data.cbSize = sizeof(data);
764 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
765 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
766 &nameW, &data );
767 if (status != STATUS_SUCCESS) return status;
769 for (;;)
771 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
773 status = STATUS_NO_MEMORY;
774 goto done;
776 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
777 AssemblyDetailedInformationInActivationContext,
778 info, size, &needed );
779 if (status == STATUS_SUCCESS) break;
780 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
781 HeapFree( GetProcessHeap(), 0, info );
782 size = needed;
783 /* restart with larger buffer */
786 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
788 status = STATUS_SXS_KEY_NOT_FOUND;
789 goto done;
792 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
794 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
796 p++;
797 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
799 /* manifest name does not match directory name, so it's not a global
800 * windows/winsxs manifest; use the manifest directory name instead */
801 dirlen = p - info->lpAssemblyManifestPath;
802 needed = (dirlen + 1) * sizeof(WCHAR);
803 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
805 status = STATUS_NO_MEMORY;
806 goto done;
808 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
809 *(p + dirlen) = 0;
810 goto done;
814 needed = (strlenW( DIR_Windows ) * sizeof(WCHAR) +
815 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + 2*sizeof(WCHAR));
817 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
819 status = STATUS_NO_MEMORY;
820 goto done;
822 strcpyW( p, DIR_Windows );
823 p += strlenW(p);
824 memcpy( p, winsxsW, sizeof(winsxsW) );
825 p += sizeof(winsxsW) / sizeof(WCHAR);
826 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
827 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
828 *p++ = '\\';
829 *p = 0;
830 done:
831 HeapFree( GetProcessHeap(), 0, info );
832 RtlReleaseActivationContext( data.hActCtx );
833 return status;
836 /***********************************************************************
837 * SearchPathW [KERNEL32.@]
839 * Searches for a specified file in the search path.
841 * PARAMS
842 * path [I] Path to search (NULL means default)
843 * name [I] Filename to search for.
844 * ext [I] File extension to append to file name. The first
845 * character must be a period. This parameter is
846 * specified only if the filename given does not
847 * contain an extension.
848 * buflen [I] size of buffer, in characters
849 * buffer [O] buffer for found filename
850 * lastpart [O] address of pointer to last used character in
851 * buffer (the final '\')
853 * RETURNS
854 * Success: length of string copied into buffer, not including
855 * terminating null character. If the filename found is
856 * longer than the length of the buffer, the length of the
857 * filename is returned.
858 * Failure: Zero
860 * NOTES
861 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
862 * (tested on NT 4.0)
864 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
865 LPWSTR buffer, LPWSTR *lastpart )
867 DWORD ret = 0;
869 if (!name || !name[0])
871 SetLastError(ERROR_INVALID_PARAMETER);
872 return 0;
875 /* If the name contains an explicit path, ignore the path */
877 if (contains_pathW(name))
879 /* try first without extension */
880 if (RtlDoesFileExists_U( name ))
881 return GetFullPathNameW( name, buflen, buffer, lastpart );
883 if (ext)
885 LPCWSTR p = strrchrW( name, '.' );
886 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
887 ext = NULL; /* Ignore the specified extension */
890 /* Allocate a buffer for the file name and extension */
891 if (ext)
893 LPWSTR tmp;
894 DWORD len = strlenW(name) + strlenW(ext);
896 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
898 SetLastError( ERROR_OUTOFMEMORY );
899 return 0;
901 strcpyW( tmp, name );
902 strcatW( tmp, ext );
903 if (RtlDoesFileExists_U( tmp ))
904 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
905 HeapFree( GetProcessHeap(), 0, tmp );
908 else if (path && path[0]) /* search in the specified path */
910 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
911 buffer, lastpart ) / sizeof(WCHAR);
913 else /* search in active context and default path */
915 WCHAR *dll_path = NULL, *search = NULL;
916 DWORD req_len, name_len;
918 req_len = name_len = strlenW(name);
920 if (strchrW( name, '.' )) ext = NULL;
921 if (ext)
923 DWORD ext_len = strlenW(ext);
925 req_len += ext_len;
926 name_len += ext_len;
928 search = HeapAlloc( GetProcessHeap(), 0, (name_len + ext_len + 1) * sizeof(WCHAR) );
929 if (!search)
931 SetLastError( ERROR_OUTOFMEMORY );
932 HeapFree( GetProcessHeap(), 0, dll_path );
933 return 0;
935 strcpyW( search, name );
936 strcatW( search, ext );
937 name = search;
939 /* now that we have combined name we don't need extension any more */
942 /* When file is found with activation context no attempt is made
943 to check if it's really exist, path is returned only basing on context info. */
944 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
946 DWORD path_len;
948 path_len = strlenW(dll_path);
949 req_len += path_len;
951 if (lastpart) *lastpart = NULL;
953 /* count null termination char too */
954 if (req_len + 1 <= buflen)
956 memcpy( buffer, dll_path, path_len * sizeof(WCHAR) );
957 memcpy( &buffer[path_len], name, name_len * sizeof(WCHAR) );
958 buffer[req_len] = 0;
959 if (lastpart) *lastpart = buffer + path_len;
960 ret = req_len;
962 else
963 ret = req_len + 1;
965 HeapFree( GetProcessHeap(), 0, dll_path );
966 HeapFree( GetProcessHeap(), 0, search );
968 else
970 if ((dll_path = MODULE_get_dll_load_path( NULL )))
972 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
973 buffer, lastpart ) / sizeof(WCHAR);
974 HeapFree( GetProcessHeap(), 0, dll_path );
975 HeapFree( GetProcessHeap(), 0, search );
977 else
979 SetLastError( ERROR_OUTOFMEMORY );
980 return 0;
985 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
986 else TRACE( "found %s\n", debugstr_w(buffer) );
987 return ret;
991 /***********************************************************************
992 * SearchPathA (KERNEL32.@)
994 * See SearchPathW.
996 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
997 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
999 WCHAR *pathW = NULL, *nameW, *extW = NULL;
1000 WCHAR bufferW[MAX_PATH];
1001 DWORD ret;
1003 if (!name)
1005 SetLastError(ERROR_INVALID_PARAMETER);
1006 return 0;
1009 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
1010 if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
1012 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
1014 HeapFree( GetProcessHeap(), 0, pathW );
1015 return 0;
1018 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
1020 HeapFree( GetProcessHeap(), 0, pathW );
1021 HeapFree( GetProcessHeap(), 0, extW );
1023 if (!ret) return 0;
1024 if (ret > MAX_PATH)
1026 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1027 return 0;
1029 ret = copy_filename_WtoA( bufferW, buffer, buflen );
1030 if (buflen > ret && lastpart)
1031 *lastpart = strrchr(buffer, '\\') + 1;
1032 return ret;
1035 static BOOL is_same_file(HANDLE h1, HANDLE h2)
1037 int fd1;
1038 BOOL ret = FALSE;
1039 if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
1041 int fd2;
1042 if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
1044 struct stat stat1, stat2;
1045 if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
1046 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
1047 wine_server_release_fd(h2, fd2);
1049 wine_server_release_fd(h1, fd1);
1051 return ret;
1054 /**************************************************************************
1055 * CopyFileW (KERNEL32.@)
1057 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1059 return CopyFileExW( source, dest, NULL, NULL, NULL,
1060 fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
1064 /**************************************************************************
1065 * CopyFileA (KERNEL32.@)
1067 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1069 WCHAR *sourceW, *destW;
1070 BOOL ret;
1072 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1073 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1075 ret = CopyFileW( sourceW, destW, fail_if_exists );
1077 HeapFree( GetProcessHeap(), 0, destW );
1078 return ret;
1082 /**************************************************************************
1083 * CopyFileExW (KERNEL32.@)
1085 BOOL WINAPI CopyFileExW(LPCWSTR source, LPCWSTR dest,
1086 LPPROGRESS_ROUTINE progress, LPVOID param,
1087 LPBOOL cancel_ptr, DWORD flags)
1089 static const int buffer_size = 65536;
1090 HANDLE h1, h2;
1091 BY_HANDLE_FILE_INFORMATION info;
1092 DWORD count;
1093 BOOL ret = FALSE;
1094 char *buffer;
1096 if (!source || !dest)
1098 SetLastError(ERROR_INVALID_PARAMETER);
1099 return FALSE;
1101 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1103 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1104 return FALSE;
1107 TRACE("%s -> %s, %x\n", debugstr_w(source), debugstr_w(dest), flags);
1109 if ((h1 = CreateFileW(source, GENERIC_READ,
1110 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1111 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1113 WARN("Unable to open source %s\n", debugstr_w(source));
1114 HeapFree( GetProcessHeap(), 0, buffer );
1115 return FALSE;
1118 if (!GetFileInformationByHandle( h1, &info ))
1120 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1121 HeapFree( GetProcessHeap(), 0, buffer );
1122 CloseHandle( h1 );
1123 return FALSE;
1126 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
1128 BOOL same_file = FALSE;
1129 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1130 OPEN_EXISTING, 0, 0);
1131 if (h2 != INVALID_HANDLE_VALUE)
1133 same_file = is_same_file( h1, h2 );
1134 CloseHandle( h2 );
1136 if (same_file)
1138 HeapFree( GetProcessHeap(), 0, buffer );
1139 CloseHandle( h1 );
1140 SetLastError( ERROR_SHARING_VIOLATION );
1141 return FALSE;
1145 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1146 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
1147 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1149 WARN("Unable to open dest %s\n", debugstr_w(dest));
1150 HeapFree( GetProcessHeap(), 0, buffer );
1151 CloseHandle( h1 );
1152 return FALSE;
1155 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
1157 char *p = buffer;
1158 while (count != 0)
1160 DWORD res;
1161 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1162 p += res;
1163 count -= res;
1166 ret = TRUE;
1167 done:
1168 /* Maintain the timestamp of source file to destination file */
1169 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
1170 HeapFree( GetProcessHeap(), 0, buffer );
1171 CloseHandle( h1 );
1172 CloseHandle( h2 );
1173 return ret;
1177 /**************************************************************************
1178 * CopyFileExA (KERNEL32.@)
1180 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1181 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1182 LPBOOL cancelFlagPointer, DWORD copyFlags)
1184 WCHAR *sourceW, *destW;
1185 BOOL ret;
1187 /* can't use the TEB buffer since we may have a callback routine */
1188 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1189 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1191 HeapFree( GetProcessHeap(), 0, sourceW );
1192 return FALSE;
1194 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1195 cancelFlagPointer, copyFlags);
1196 HeapFree( GetProcessHeap(), 0, sourceW );
1197 HeapFree( GetProcessHeap(), 0, destW );
1198 return ret;
1202 /**************************************************************************
1203 * MoveFileWithProgressW (KERNEL32.@)
1205 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1206 LPPROGRESS_ROUTINE fnProgress,
1207 LPVOID param, DWORD flag )
1209 FILE_BASIC_INFORMATION info;
1210 UNICODE_STRING nt_name;
1211 OBJECT_ATTRIBUTES attr;
1212 IO_STATUS_BLOCK io;
1213 NTSTATUS status;
1214 HANDLE source_handle = 0, dest_handle;
1215 ANSI_STRING source_unix, dest_unix;
1217 TRACE("(%s,%s,%p,%p,%04x)\n",
1218 debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1220 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1221 return add_boot_rename_entry( source, dest, flag );
1223 if (!dest)
1224 return DeleteFileW( source );
1226 if (flag & MOVEFILE_WRITE_THROUGH)
1227 FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1229 /* check if we are allowed to rename the source */
1231 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1233 SetLastError( ERROR_PATH_NOT_FOUND );
1234 return FALSE;
1236 source_unix.Buffer = NULL;
1237 dest_unix.Buffer = NULL;
1238 attr.Length = sizeof(attr);
1239 attr.RootDirectory = 0;
1240 attr.Attributes = OBJ_CASE_INSENSITIVE;
1241 attr.ObjectName = &nt_name;
1242 attr.SecurityDescriptor = NULL;
1243 attr.SecurityQualityOfService = NULL;
1245 status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1246 if (status == STATUS_SUCCESS)
1247 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1248 RtlFreeUnicodeString( &nt_name );
1249 if (status != STATUS_SUCCESS)
1251 SetLastError( RtlNtStatusToDosError(status) );
1252 goto error;
1254 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1255 if (status != STATUS_SUCCESS)
1257 SetLastError( RtlNtStatusToDosError(status) );
1258 goto error;
1261 /* we must have write access to the destination, and it must */
1262 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1264 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1266 SetLastError( ERROR_PATH_NOT_FOUND );
1267 goto error;
1269 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1270 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1271 if (status == STATUS_SUCCESS) /* destination exists */
1273 NtClose( dest_handle );
1274 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1276 SetLastError( ERROR_ALREADY_EXISTS );
1277 RtlFreeUnicodeString( &nt_name );
1278 goto error;
1280 else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1282 SetLastError( ERROR_ACCESS_DENIED );
1283 goto error;
1286 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1288 SetLastError( RtlNtStatusToDosError(status) );
1289 RtlFreeUnicodeString( &nt_name );
1290 goto error;
1293 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1294 RtlFreeUnicodeString( &nt_name );
1295 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1297 SetLastError( RtlNtStatusToDosError(status) );
1298 goto error;
1301 /* now perform the rename */
1303 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1305 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1307 NtClose( source_handle );
1308 RtlFreeAnsiString( &source_unix );
1309 RtlFreeAnsiString( &dest_unix );
1310 if (!CopyFileExW( source, dest, fnProgress,
1311 param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1312 return FALSE;
1313 return DeleteFileW( source );
1315 FILE_SetDosError();
1316 /* if we created the destination, remove it */
1317 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1318 goto error;
1321 /* fixup executable permissions */
1323 if (is_executable( source ) != is_executable( dest ))
1325 struct stat fstat;
1326 if (stat( dest_unix.Buffer, &fstat ) != -1)
1328 if (is_executable( dest ))
1329 /* set executable bit where read bit is set */
1330 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1331 else
1332 fstat.st_mode &= ~0111;
1333 chmod( dest_unix.Buffer, fstat.st_mode );
1337 NtClose( source_handle );
1338 RtlFreeAnsiString( &source_unix );
1339 RtlFreeAnsiString( &dest_unix );
1340 return TRUE;
1342 error:
1343 if (source_handle) NtClose( source_handle );
1344 RtlFreeAnsiString( &source_unix );
1345 RtlFreeAnsiString( &dest_unix );
1346 return FALSE;
1349 /**************************************************************************
1350 * MoveFileWithProgressA (KERNEL32.@)
1352 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1353 LPPROGRESS_ROUTINE fnProgress,
1354 LPVOID param, DWORD flag )
1356 WCHAR *sourceW, *destW;
1357 BOOL ret;
1359 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1360 if (dest)
1362 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1364 else
1365 destW = NULL;
1367 ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1368 HeapFree( GetProcessHeap(), 0, destW );
1369 return ret;
1372 /**************************************************************************
1373 * MoveFileExW (KERNEL32.@)
1375 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1377 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1380 /**************************************************************************
1381 * MoveFileExA (KERNEL32.@)
1383 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1385 return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1389 /**************************************************************************
1390 * MoveFileW (KERNEL32.@)
1392 * Move file or directory
1394 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1396 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1400 /**************************************************************************
1401 * MoveFileA (KERNEL32.@)
1403 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1405 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1409 /*************************************************************************
1410 * CreateHardLinkW (KERNEL32.@)
1412 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1413 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1415 NTSTATUS status;
1416 UNICODE_STRING ntDest, ntSource;
1417 ANSI_STRING unixDest, unixSource;
1418 BOOL ret = FALSE;
1420 TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1421 debugstr_w(lpExistingFileName), lpSecurityAttributes);
1423 ntDest.Buffer = ntSource.Buffer = NULL;
1424 if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1425 !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1427 SetLastError( ERROR_PATH_NOT_FOUND );
1428 goto err;
1431 unixSource.Buffer = unixDest.Buffer = NULL;
1432 status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1433 if (!status)
1435 status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1436 if (!status) /* destination must not exist */
1438 status = STATUS_OBJECT_NAME_EXISTS;
1439 } else if (status == STATUS_NO_SUCH_FILE)
1441 status = STATUS_SUCCESS;
1445 if (status)
1446 SetLastError( RtlNtStatusToDosError(status) );
1447 else if (!link( unixSource.Buffer, unixDest.Buffer ))
1449 TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1450 debugstr_a( unixSource.Buffer ));
1451 ret = TRUE;
1453 else
1454 FILE_SetDosError();
1456 RtlFreeAnsiString( &unixSource );
1457 RtlFreeAnsiString( &unixDest );
1459 err:
1460 RtlFreeUnicodeString( &ntSource );
1461 RtlFreeUnicodeString( &ntDest );
1462 return ret;
1466 /*************************************************************************
1467 * CreateHardLinkA (KERNEL32.@)
1469 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1470 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1472 WCHAR *sourceW, *destW;
1473 BOOL res;
1475 if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1477 return FALSE;
1479 if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1481 HeapFree( GetProcessHeap(), 0, sourceW );
1482 return FALSE;
1485 res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1487 HeapFree( GetProcessHeap(), 0, sourceW );
1488 HeapFree( GetProcessHeap(), 0, destW );
1490 return res;
1494 /***********************************************************************
1495 * CreateDirectoryW (KERNEL32.@)
1496 * RETURNS:
1497 * TRUE : success
1498 * FALSE : failure
1499 * ERROR_DISK_FULL: on full disk
1500 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1501 * ERROR_ACCESS_DENIED: on permission problems
1502 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1504 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1506 OBJECT_ATTRIBUTES attr;
1507 UNICODE_STRING nt_name;
1508 IO_STATUS_BLOCK io;
1509 NTSTATUS status;
1510 HANDLE handle;
1511 BOOL ret = FALSE;
1513 TRACE( "%s\n", debugstr_w(path) );
1515 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1517 SetLastError( ERROR_PATH_NOT_FOUND );
1518 return FALSE;
1520 attr.Length = sizeof(attr);
1521 attr.RootDirectory = 0;
1522 attr.Attributes = OBJ_CASE_INSENSITIVE;
1523 attr.ObjectName = &nt_name;
1524 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1525 attr.SecurityQualityOfService = NULL;
1527 status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1528 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1529 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1531 if (status == STATUS_SUCCESS)
1533 NtClose( handle );
1534 ret = TRUE;
1536 else SetLastError( RtlNtStatusToDosError(status) );
1538 RtlFreeUnicodeString( &nt_name );
1539 return ret;
1543 /***********************************************************************
1544 * CreateDirectoryA (KERNEL32.@)
1546 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1548 WCHAR *pathW;
1550 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1551 return CreateDirectoryW( pathW, sa );
1555 /***********************************************************************
1556 * CreateDirectoryExA (KERNEL32.@)
1558 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1560 WCHAR *pathW, *templateW = NULL;
1561 BOOL ret;
1563 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1564 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1566 ret = CreateDirectoryExW( templateW, pathW, sa );
1567 HeapFree( GetProcessHeap(), 0, templateW );
1568 return ret;
1572 /***********************************************************************
1573 * CreateDirectoryExW (KERNEL32.@)
1575 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1577 return CreateDirectoryW( path, sa );
1581 /***********************************************************************
1582 * RemoveDirectoryW (KERNEL32.@)
1584 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1586 OBJECT_ATTRIBUTES attr;
1587 UNICODE_STRING nt_name;
1588 ANSI_STRING unix_name;
1589 IO_STATUS_BLOCK io;
1590 NTSTATUS status;
1591 HANDLE handle;
1592 BOOL ret = FALSE;
1594 TRACE( "%s\n", debugstr_w(path) );
1596 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1598 SetLastError( ERROR_PATH_NOT_FOUND );
1599 return FALSE;
1601 attr.Length = sizeof(attr);
1602 attr.RootDirectory = 0;
1603 attr.Attributes = OBJ_CASE_INSENSITIVE;
1604 attr.ObjectName = &nt_name;
1605 attr.SecurityDescriptor = NULL;
1606 attr.SecurityQualityOfService = NULL;
1608 status = NtOpenFile( &handle, DELETE, &attr, &io,
1609 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1610 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1611 if (status == STATUS_SUCCESS)
1612 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1613 RtlFreeUnicodeString( &nt_name );
1615 if (status != STATUS_SUCCESS)
1617 SetLastError( RtlNtStatusToDosError(status) );
1618 return FALSE;
1621 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1622 RtlFreeAnsiString( &unix_name );
1623 NtClose( handle );
1624 return ret;
1628 /***********************************************************************
1629 * RemoveDirectoryA (KERNEL32.@)
1631 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1633 WCHAR *pathW;
1635 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1636 return RemoveDirectoryW( pathW );
1640 /***********************************************************************
1641 * GetCurrentDirectoryW (KERNEL32.@)
1643 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1645 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1649 /***********************************************************************
1650 * GetCurrentDirectoryA (KERNEL32.@)
1652 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1654 WCHAR bufferW[MAX_PATH];
1655 DWORD ret;
1657 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1659 /* Win9x catches access violations here, returning zero.
1660 * This behaviour resulted in some people not noticing
1661 * that they got the argument order wrong. So let's be
1662 * nice and fail gracefully if buf is invalid and looks
1663 * more like a buflen. */
1664 SetLastError(ERROR_INVALID_PARAMETER);
1665 return 0;
1668 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1669 if (!ret) return 0;
1670 if (ret > sizeof(bufferW))
1672 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1673 return 0;
1675 return copy_filename_WtoA( bufferW, buf, buflen );
1679 /***********************************************************************
1680 * SetCurrentDirectoryW (KERNEL32.@)
1682 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1684 UNICODE_STRING dirW;
1685 NTSTATUS status;
1687 RtlInitUnicodeString( &dirW, dir );
1688 status = RtlSetCurrentDirectory_U( &dirW );
1689 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1690 return !status;
1694 /***********************************************************************
1695 * SetCurrentDirectoryA (KERNEL32.@)
1697 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1699 WCHAR *dirW;
1700 UNICODE_STRING strW;
1701 NTSTATUS status;
1703 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1704 RtlInitUnicodeString( &strW, dirW );
1705 status = RtlSetCurrentDirectory_U( &strW );
1706 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1707 return !status;
1711 /***********************************************************************
1712 * GetWindowsDirectoryW (KERNEL32.@)
1714 * See comment for GetWindowsDirectoryA.
1716 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1718 UINT len = strlenW( DIR_Windows ) + 1;
1719 if (path && count >= len)
1721 strcpyW( path, DIR_Windows );
1722 len--;
1724 return len;
1728 /***********************************************************************
1729 * GetWindowsDirectoryA (KERNEL32.@)
1731 * Return value:
1732 * If buffer is large enough to hold full path and terminating '\0' character
1733 * function copies path to buffer and returns length of the path without '\0'.
1734 * Otherwise function returns required size including '\0' character and
1735 * does not touch the buffer.
1737 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1739 return copy_filename_WtoA( DIR_Windows, path, count );
1743 /***********************************************************************
1744 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1746 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1748 return GetWindowsDirectoryA( path, count );
1752 /***********************************************************************
1753 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1755 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1757 return GetWindowsDirectoryW( path, count );
1761 /***********************************************************************
1762 * GetSystemDirectoryW (KERNEL32.@)
1764 * See comment for GetWindowsDirectoryA.
1766 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1768 UINT len = strlenW( DIR_System ) + 1;
1769 if (path && count >= len)
1771 strcpyW( path, DIR_System );
1772 len--;
1774 return len;
1778 /***********************************************************************
1779 * GetSystemDirectoryA (KERNEL32.@)
1781 * See comment for GetWindowsDirectoryA.
1783 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1785 return copy_filename_WtoA( DIR_System, path, count );
1789 /***********************************************************************
1790 * GetSystemWow64DirectoryW (KERNEL32.@)
1792 * As seen on MSDN
1793 * - On Win32 we should return ERROR_CALL_NOT_IMPLEMENTED
1794 * - On Win64 we should return the SysWow64 (system64) directory
1796 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1798 UINT len;
1800 if (!DIR_SysWow64)
1802 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1803 return 0;
1805 len = strlenW( DIR_SysWow64 ) + 1;
1806 if (path && count >= len)
1808 strcpyW( path, DIR_SysWow64 );
1809 len--;
1811 return len;
1815 /***********************************************************************
1816 * GetSystemWow64DirectoryA (KERNEL32.@)
1818 * See comment for GetWindowsWow64DirectoryW.
1820 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1822 if (!DIR_SysWow64)
1824 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1825 return 0;
1827 return copy_filename_WtoA( DIR_SysWow64, path, count );
1831 /***********************************************************************
1832 * Wow64EnableWow64FsRedirection (KERNEL32.@)
1834 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1836 NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1837 if (status) SetLastError( RtlNtStatusToDosError(status) );
1838 return !status;
1842 /***********************************************************************
1843 * Wow64DisableWow64FsRedirection (KERNEL32.@)
1845 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1847 NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1848 if (status) SetLastError( RtlNtStatusToDosError(status) );
1849 return !status;
1853 /***********************************************************************
1854 * Wow64RevertWow64FsRedirection (KERNEL32.@)
1856 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1858 NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1859 if (status) SetLastError( RtlNtStatusToDosError(status) );
1860 return !status;
1864 /***********************************************************************
1865 * NeedCurrentDirectoryForExePathW (KERNEL32.@)
1867 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1869 static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1870 'C','u','r','r','e','n','t',
1871 'D','i','r','e','c','t','o','r','y',
1872 'I','n','E','x','e','P','a','t','h',0};
1873 WCHAR env_val;
1875 /* MSDN mentions some 'registry location'. We do not use registry. */
1876 FIXME("(%s): partial stub\n", debugstr_w(name));
1878 if (strchrW(name, '\\'))
1879 return TRUE;
1881 /* Check the existence of the variable, not value */
1882 if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1883 return TRUE;
1885 return FALSE;
1889 /***********************************************************************
1890 * NeedCurrentDirectoryForExePathA (KERNEL32.@)
1892 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1894 WCHAR *nameW;
1896 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1897 return NeedCurrentDirectoryForExePathW( nameW );
1901 /***********************************************************************
1902 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1904 * Return the full Unix file name for a given path.
1905 * Returned buffer must be freed by caller.
1907 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1909 UNICODE_STRING nt_name;
1910 ANSI_STRING unix_name;
1911 NTSTATUS status;
1913 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1914 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1915 RtlFreeUnicodeString( &nt_name );
1916 if (status && status != STATUS_NO_SUCH_FILE)
1918 SetLastError( RtlNtStatusToDosError( status ) );
1919 return NULL;
1921 return unix_name.Buffer;
1925 /***********************************************************************
1926 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1928 * Return the full DOS file name for a given Unix path.
1929 * Returned buffer must be freed by caller.
1931 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1933 UNICODE_STRING nt_name;
1934 ANSI_STRING unix_name;
1935 NTSTATUS status;
1936 DWORD len;
1938 RtlInitAnsiString( &unix_name, str );
1939 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1940 if (status)
1942 SetLastError( RtlNtStatusToDosError( status ) );
1943 return NULL;
1945 if (nt_name.Buffer[5] == ':')
1947 /* get rid of the \??\ prefix */
1948 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1949 len = nt_name.Length - 4 * sizeof(WCHAR);
1950 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1951 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1953 else
1954 nt_name.Buffer[1] = '\\';
1955 return nt_name.Buffer;
1958 /*************************************************************************
1959 * CreateSymbolicLinkW (KERNEL32.@)
1961 BOOL WINAPI CreateSymbolicLinkW(LPCWSTR link, LPCWSTR target, DWORD flags)
1963 FIXME("(%s %s %d): stub\n", debugstr_w(link), debugstr_w(target), flags);
1964 return TRUE;
1967 /*************************************************************************
1968 * CreateSymbolicLinkA (KERNEL32.@)
1970 BOOL WINAPI CreateSymbolicLinkA(LPCSTR link, LPCSTR target, DWORD flags)
1972 FIXME("(%s %s %d): stub\n", debugstr_a(link), debugstr_a(target), flags);
1973 return TRUE;