msvcrt: Only check for flag presence in isatty function.
[wine/multimedia.git] / dlls / kernel32 / path.c
blob09fb04be335c93c5e181ffdcd15b7bac8c6749e2
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];
255 DWORD ret;
257 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
259 ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, NULL);
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 LPSTR p = buffer + strlen(buffer) - 1;
272 if (*p != '\\')
274 while ((p > buffer + 2) && (*p != '\\')) p--;
275 *lastpart = p + 1;
277 else *lastpart = NULL;
279 return ret;
283 /***********************************************************************
284 * GetLongPathNameW (KERNEL32.@)
286 * NOTES
287 * observed (Win2000):
288 * shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
289 * shortpath="": LastError=ERROR_PATH_NOT_FOUND, ret=0
291 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
293 WCHAR tmplongpath[MAX_PATHNAME_LEN];
294 LPCWSTR p;
295 DWORD sp = 0, lp = 0;
296 DWORD tmplen;
297 BOOL unixabsolute;
298 WIN32_FIND_DATAW wfd;
299 HANDLE goit;
301 if (!shortpath)
303 SetLastError(ERROR_INVALID_PARAMETER);
304 return 0;
306 if (!shortpath[0])
308 SetLastError(ERROR_PATH_NOT_FOUND);
309 return 0;
312 TRACE("%s,%p,%d\n", debugstr_w(shortpath), longpath, longlen);
314 if (shortpath[0] == '\\' && shortpath[1] == '\\')
316 FIXME("UNC pathname %s\n", debugstr_w(shortpath));
318 tmplen = strlenW(shortpath);
319 if (tmplen < longlen)
321 if (longpath != shortpath) strcpyW( longpath, shortpath );
322 return tmplen;
324 return tmplen + 1;
327 unixabsolute = (shortpath[0] == '/');
329 /* check for drive letter */
330 if (!unixabsolute && shortpath[1] == ':' )
332 tmplongpath[0] = shortpath[0];
333 tmplongpath[1] = ':';
334 lp = sp = 2;
337 while (shortpath[sp])
339 /* check for path delimiters and reproduce them */
340 if (shortpath[sp] == '\\' || shortpath[sp] == '/')
342 if (!lp || tmplongpath[lp-1] != '\\')
344 /* strip double "\\" */
345 tmplongpath[lp++] = '\\';
347 tmplongpath[lp] = 0; /* terminate string */
348 sp++;
349 continue;
352 p = shortpath + sp;
353 if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
355 tmplongpath[lp++] = *p++;
356 tmplongpath[lp++] = *p++;
358 for (; *p && *p != '/' && *p != '\\'; p++);
359 tmplen = p - (shortpath + sp);
360 lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
362 if (tmplongpath[lp] == '.')
364 if (tmplen == 1 || (tmplen == 2 && tmplongpath[lp + 1] == '.'))
366 lp += tmplen;
367 sp += tmplen;
368 continue;
372 /* Check if the file exists and use the existing file name */
373 goit = FindFirstFileW(tmplongpath, &wfd);
374 if (goit == INVALID_HANDLE_VALUE)
376 TRACE("not found %s!\n", debugstr_w(tmplongpath));
377 SetLastError ( ERROR_FILE_NOT_FOUND );
378 return 0;
380 FindClose(goit);
381 strcpyW(tmplongpath + lp, wfd.cFileName);
382 lp += strlenW(tmplongpath + lp);
383 sp += tmplen;
385 tmplen = strlenW(shortpath) - 1;
386 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
387 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
388 tmplongpath[lp++] = shortpath[tmplen];
389 tmplongpath[lp] = 0;
391 tmplen = strlenW(tmplongpath) + 1;
392 if (tmplen <= longlen)
394 strcpyW(longpath, tmplongpath);
395 TRACE("returning %s\n", debugstr_w(longpath));
396 tmplen--; /* length without 0 */
399 return tmplen;
402 /***********************************************************************
403 * GetLongPathNameA (KERNEL32.@)
405 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
407 WCHAR *shortpathW;
408 WCHAR longpathW[MAX_PATH];
409 DWORD ret;
411 TRACE("%s\n", debugstr_a(shortpath));
413 if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
415 ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
417 if (!ret) return 0;
418 if (ret > MAX_PATH)
420 SetLastError(ERROR_FILENAME_EXCED_RANGE);
421 return 0;
423 return copy_filename_WtoA( longpathW, longpath, longlen );
427 /***********************************************************************
428 * GetShortPathNameW (KERNEL32.@)
430 * NOTES
431 * observed:
432 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
433 * longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
435 * more observations ( with NT 3.51 (WinDD) ):
436 * longpath <= 8.3 -> just copy longpath to shortpath
437 * longpath > 8.3 ->
438 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
439 * b) file does exist -> set the short filename.
440 * - trailing slashes are reproduced in the short name, even if the
441 * file is not a directory
442 * - the absolute/relative path of the short name is reproduced like found
443 * in the long name
444 * - longpath and shortpath may have the same address
445 * Peter Ganten, 1999
447 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
449 WCHAR tmpshortpath[MAX_PATHNAME_LEN];
450 LPCWSTR p;
451 DWORD sp = 0, lp = 0;
452 DWORD tmplen;
453 WIN32_FIND_DATAW wfd;
454 HANDLE goit;
456 TRACE("%s\n", debugstr_w(longpath));
458 if (!longpath)
460 SetLastError(ERROR_INVALID_PARAMETER);
461 return 0;
463 if (!longpath[0])
465 SetLastError(ERROR_BAD_PATHNAME);
466 return 0;
469 /* check for drive letter */
470 if (longpath[0] != '/' && longpath[1] == ':' )
472 tmpshortpath[0] = longpath[0];
473 tmpshortpath[1] = ':';
474 sp = lp = 2;
477 while (longpath[lp])
479 /* check for path delimiters and reproduce them */
480 if (longpath[lp] == '\\' || longpath[lp] == '/')
482 if (!sp || tmpshortpath[sp-1] != '\\')
484 /* strip double "\\" */
485 tmpshortpath[sp] = '\\';
486 sp++;
488 tmpshortpath[sp] = 0; /* terminate string */
489 lp++;
490 continue;
493 p = longpath + lp;
494 if (lp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
496 tmpshortpath[sp++] = *p++;
497 tmpshortpath[sp++] = *p++;
499 for (; *p && *p != '/' && *p != '\\'; p++);
500 tmplen = p - (longpath + lp);
501 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
503 if (tmpshortpath[sp] == '.')
505 if (tmplen == 1 || (tmplen == 2 && tmpshortpath[sp + 1] == '.'))
507 sp += tmplen;
508 lp += tmplen;
509 continue;
513 /* Check if the file exists and use the existing short file name */
514 goit = FindFirstFileW(tmpshortpath, &wfd);
515 if (goit == INVALID_HANDLE_VALUE) goto notfound;
516 FindClose(goit);
517 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName);
518 sp += strlenW(tmpshortpath + sp);
519 lp += tmplen;
521 tmpshortpath[sp] = 0;
523 tmplen = strlenW(tmpshortpath) + 1;
524 if (tmplen <= shortlen)
526 strcpyW(shortpath, tmpshortpath);
527 TRACE("returning %s\n", debugstr_w(shortpath));
528 tmplen--; /* length without 0 */
531 return tmplen;
533 notfound:
534 TRACE("not found!\n" );
535 SetLastError ( ERROR_FILE_NOT_FOUND );
536 return 0;
539 /***********************************************************************
540 * GetShortPathNameA (KERNEL32.@)
542 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
544 WCHAR *longpathW;
545 WCHAR shortpathW[MAX_PATH];
546 DWORD ret;
548 TRACE("%s\n", debugstr_a(longpath));
550 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
552 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
554 if (!ret) return 0;
555 if (ret > MAX_PATH)
557 SetLastError(ERROR_FILENAME_EXCED_RANGE);
558 return 0;
560 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
564 /***********************************************************************
565 * GetTempPathA (KERNEL32.@)
567 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
569 WCHAR pathW[MAX_PATH];
570 UINT ret;
572 ret = GetTempPathW(MAX_PATH, pathW);
574 if (!ret)
575 return 0;
577 if (ret > MAX_PATH)
579 SetLastError(ERROR_FILENAME_EXCED_RANGE);
580 return 0;
582 return copy_filename_WtoA( pathW, path, count );
586 /***********************************************************************
587 * GetTempPathW (KERNEL32.@)
589 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
591 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
592 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
593 static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
594 WCHAR tmp_path[MAX_PATH];
595 UINT ret;
597 TRACE("%u,%p\n", count, path);
599 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
600 !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
601 !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
602 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
603 return 0;
605 if (ret > MAX_PATH)
607 SetLastError(ERROR_FILENAME_EXCED_RANGE);
608 return 0;
611 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
612 if (!ret) return 0;
614 if (ret > MAX_PATH - 2)
616 SetLastError(ERROR_FILENAME_EXCED_RANGE);
617 return 0;
620 if (tmp_path[ret-1] != '\\')
622 tmp_path[ret++] = '\\';
623 tmp_path[ret] = '\0';
626 ret++; /* add space for terminating 0 */
628 if (count)
630 lstrcpynW(path, tmp_path, count);
631 if (count >= ret)
632 ret--; /* return length without 0 */
633 else if (count < 4)
634 path[0] = 0; /* avoid returning ambiguous "X:" */
637 TRACE("returning %u, %s\n", ret, debugstr_w(path));
638 return ret;
642 /***********************************************************************
643 * GetTempFileNameA (KERNEL32.@)
645 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
647 WCHAR *pathW, *prefixW = NULL;
648 WCHAR bufferW[MAX_PATH];
649 UINT ret;
651 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
652 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
654 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
655 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
657 HeapFree( GetProcessHeap(), 0, prefixW );
658 return ret;
661 /***********************************************************************
662 * GetTempFileNameW (KERNEL32.@)
664 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
666 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
668 int i;
669 LPWSTR p;
670 DWORD attr;
672 if ( !path || !buffer )
674 SetLastError( ERROR_INVALID_PARAMETER );
675 return 0;
678 /* ensure that the provided directory exists */
679 attr = GetFileAttributesW(path);
680 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
682 TRACE("path not found %s\n", debugstr_w(path));
683 SetLastError( ERROR_DIRECTORY );
684 return 0;
687 strcpyW( buffer, path );
688 p = buffer + strlenW(buffer);
690 /* add a \, if there isn't one */
691 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
693 if (prefix)
694 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
696 unique &= 0xffff;
698 if (unique) sprintfW( p, formatW, unique );
699 else
701 /* get a "random" unique number and try to create the file */
702 HANDLE handle;
703 UINT num = GetTickCount() & 0xffff;
704 static UINT last;
706 /* avoid using the same name twice in a short interval */
707 if (last - num < 10) num = last + 1;
708 if (!num) num = 1;
709 unique = num;
712 sprintfW( p, formatW, unique );
713 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
714 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
715 if (handle != INVALID_HANDLE_VALUE)
716 { /* We created it */
717 TRACE("created %s\n", debugstr_w(buffer) );
718 CloseHandle( handle );
719 last = unique;
720 break;
722 if (GetLastError() != ERROR_FILE_EXISTS &&
723 GetLastError() != ERROR_SHARING_VIOLATION)
724 break; /* No need to go on */
725 if (!(++unique & 0xffff)) unique = 1;
726 } while (unique != num);
729 TRACE("returning %s\n", debugstr_w(buffer) );
730 return unique;
734 /***********************************************************************
735 * contains_pathW
737 * Check if the file name contains a path; helper for SearchPathW.
738 * A relative path is not considered a path unless it starts with ./ or ../
740 static inline BOOL contains_pathW (LPCWSTR name)
742 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
743 if (name[0] != '.') return FALSE;
744 if (name[1] == '/' || name[1] == '\\') return TRUE;
745 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
748 /***********************************************************************
749 * find_actctx_dllpath
751 * Find the path (if any) of the dll from the activation context.
752 * Returned path doesn't include a name.
754 static NTSTATUS find_actctx_dllpath(const WCHAR *libname, WCHAR **path)
756 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
757 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
759 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
760 ACTCTX_SECTION_KEYED_DATA data;
761 UNICODE_STRING nameW;
762 NTSTATUS status;
763 SIZE_T needed, size = 1024;
764 WCHAR *p;
766 RtlInitUnicodeString( &nameW, libname );
767 data.cbSize = sizeof(data);
768 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
769 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
770 &nameW, &data );
771 if (status != STATUS_SUCCESS) return status;
773 for (;;)
775 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
777 status = STATUS_NO_MEMORY;
778 goto done;
780 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
781 AssemblyDetailedInformationInActivationContext,
782 info, size, &needed );
783 if (status == STATUS_SUCCESS) break;
784 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
785 HeapFree( GetProcessHeap(), 0, info );
786 size = needed;
787 /* restart with larger buffer */
790 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
792 status = STATUS_SXS_KEY_NOT_FOUND;
793 goto done;
796 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
798 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
800 p++;
801 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
803 /* manifest name does not match directory name, so it's not a global
804 * windows/winsxs manifest; use the manifest directory name instead */
805 dirlen = p - info->lpAssemblyManifestPath;
806 needed = (dirlen + 1) * sizeof(WCHAR);
807 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
809 status = STATUS_NO_MEMORY;
810 goto done;
812 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
813 *(p + dirlen) = 0;
814 goto done;
818 needed = (strlenW( DIR_Windows ) * sizeof(WCHAR) +
819 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + 2*sizeof(WCHAR));
821 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
823 status = STATUS_NO_MEMORY;
824 goto done;
826 strcpyW( p, DIR_Windows );
827 p += strlenW(p);
828 memcpy( p, winsxsW, sizeof(winsxsW) );
829 p += sizeof(winsxsW) / sizeof(WCHAR);
830 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
831 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
832 *p++ = '\\';
833 *p = 0;
834 done:
835 HeapFree( GetProcessHeap(), 0, info );
836 RtlReleaseActivationContext( data.hActCtx );
837 return status;
840 /***********************************************************************
841 * SearchPathW [KERNEL32.@]
843 * Searches for a specified file in the search path.
845 * PARAMS
846 * path [I] Path to search (NULL means default)
847 * name [I] Filename to search for.
848 * ext [I] File extension to append to file name. The first
849 * character must be a period. This parameter is
850 * specified only if the filename given does not
851 * contain an extension.
852 * buflen [I] size of buffer, in characters
853 * buffer [O] buffer for found filename
854 * lastpart [O] address of pointer to last used character in
855 * buffer (the final '\')
857 * RETURNS
858 * Success: length of string copied into buffer, not including
859 * terminating null character. If the filename found is
860 * longer than the length of the buffer, the length of the
861 * filename is returned.
862 * Failure: Zero
864 * NOTES
865 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
866 * (tested on NT 4.0)
868 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
869 LPWSTR buffer, LPWSTR *lastpart )
871 DWORD ret = 0;
873 if (!name || !name[0])
875 SetLastError(ERROR_INVALID_PARAMETER);
876 return 0;
879 /* If the name contains an explicit path, ignore the path */
881 if (contains_pathW(name))
883 /* try first without extension */
884 if (RtlDoesFileExists_U( name ))
885 return GetFullPathNameW( name, buflen, buffer, lastpart );
887 if (ext)
889 LPCWSTR p = strrchrW( name, '.' );
890 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
891 ext = NULL; /* Ignore the specified extension */
894 /* Allocate a buffer for the file name and extension */
895 if (ext)
897 LPWSTR tmp;
898 DWORD len = strlenW(name) + strlenW(ext);
900 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
902 SetLastError( ERROR_OUTOFMEMORY );
903 return 0;
905 strcpyW( tmp, name );
906 strcatW( tmp, ext );
907 if (RtlDoesFileExists_U( tmp ))
908 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
909 HeapFree( GetProcessHeap(), 0, tmp );
912 else if (path && path[0]) /* search in the specified path */
914 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
915 buffer, lastpart ) / sizeof(WCHAR);
917 else /* search in active context and default path */
919 WCHAR *dll_path = NULL, *search = NULL;
920 DWORD req_len, name_len;
922 req_len = name_len = strlenW(name);
924 if (strchrW( name, '.' )) ext = NULL;
925 if (ext)
927 DWORD ext_len = strlenW(ext);
929 req_len += ext_len;
930 name_len += ext_len;
932 search = HeapAlloc( GetProcessHeap(), 0, (name_len + ext_len + 1) * sizeof(WCHAR) );
933 if (!search)
935 SetLastError( ERROR_OUTOFMEMORY );
936 HeapFree( GetProcessHeap(), 0, dll_path );
937 return 0;
939 strcpyW( search, name );
940 strcatW( search, ext );
941 name = search;
943 /* now that we have combined name we don't need extension any more */
946 /* When file is found with activation context no attempt is made
947 to check if it's really exist, path is returned only basing on context info. */
948 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
950 DWORD path_len;
952 path_len = strlenW(dll_path);
953 req_len += path_len;
955 if (lastpart) *lastpart = NULL;
957 /* count null termination char too */
958 if (req_len + 1 <= buflen)
960 memcpy( buffer, dll_path, path_len * sizeof(WCHAR) );
961 memcpy( &buffer[path_len], name, name_len * sizeof(WCHAR) );
962 buffer[req_len] = 0;
963 if (lastpart) *lastpart = buffer + path_len;
964 ret = req_len;
966 else
967 ret = req_len + 1;
969 HeapFree( GetProcessHeap(), 0, dll_path );
970 HeapFree( GetProcessHeap(), 0, search );
972 else
974 if ((dll_path = MODULE_get_dll_load_path( NULL )))
976 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
977 buffer, lastpart ) / sizeof(WCHAR);
978 HeapFree( GetProcessHeap(), 0, dll_path );
979 HeapFree( GetProcessHeap(), 0, search );
981 else
983 SetLastError( ERROR_OUTOFMEMORY );
984 return 0;
989 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
990 else TRACE( "found %s\n", debugstr_w(buffer) );
991 return ret;
995 /***********************************************************************
996 * SearchPathA (KERNEL32.@)
998 * See SearchPathW.
1000 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
1001 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
1003 WCHAR *pathW = NULL, *nameW, *extW = NULL;
1004 WCHAR bufferW[MAX_PATH];
1005 DWORD ret;
1007 if (!name)
1009 SetLastError(ERROR_INVALID_PARAMETER);
1010 return 0;
1013 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
1014 if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
1016 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
1018 HeapFree( GetProcessHeap(), 0, pathW );
1019 return 0;
1022 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
1024 HeapFree( GetProcessHeap(), 0, pathW );
1025 HeapFree( GetProcessHeap(), 0, extW );
1027 if (!ret) return 0;
1028 if (ret > MAX_PATH)
1030 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1031 return 0;
1033 ret = copy_filename_WtoA( bufferW, buffer, buflen );
1034 if (buflen > ret && lastpart)
1035 *lastpart = strrchr(buffer, '\\') + 1;
1036 return ret;
1039 static BOOL is_same_file(HANDLE h1, HANDLE h2)
1041 int fd1;
1042 BOOL ret = FALSE;
1043 if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
1045 int fd2;
1046 if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
1048 struct stat stat1, stat2;
1049 if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
1050 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
1051 wine_server_release_fd(h2, fd2);
1053 wine_server_release_fd(h1, fd1);
1055 return ret;
1058 /**************************************************************************
1059 * CopyFileW (KERNEL32.@)
1061 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1063 return CopyFileExW( source, dest, NULL, NULL, NULL,
1064 fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
1068 /**************************************************************************
1069 * CopyFileA (KERNEL32.@)
1071 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1073 WCHAR *sourceW, *destW;
1074 BOOL ret;
1076 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1077 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1079 ret = CopyFileW( sourceW, destW, fail_if_exists );
1081 HeapFree( GetProcessHeap(), 0, destW );
1082 return ret;
1086 /**************************************************************************
1087 * CopyFileExW (KERNEL32.@)
1089 BOOL WINAPI CopyFileExW(LPCWSTR source, LPCWSTR dest,
1090 LPPROGRESS_ROUTINE progress, LPVOID param,
1091 LPBOOL cancel_ptr, DWORD flags)
1093 static const int buffer_size = 65536;
1094 HANDLE h1, h2;
1095 BY_HANDLE_FILE_INFORMATION info;
1096 DWORD count;
1097 BOOL ret = FALSE;
1098 char *buffer;
1100 if (!source || !dest)
1102 SetLastError(ERROR_INVALID_PARAMETER);
1103 return FALSE;
1105 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1107 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1108 return FALSE;
1111 TRACE("%s -> %s, %x\n", debugstr_w(source), debugstr_w(dest), flags);
1113 if ((h1 = CreateFileW(source, GENERIC_READ,
1114 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1115 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1117 WARN("Unable to open source %s\n", debugstr_w(source));
1118 HeapFree( GetProcessHeap(), 0, buffer );
1119 return FALSE;
1122 if (!GetFileInformationByHandle( h1, &info ))
1124 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1125 HeapFree( GetProcessHeap(), 0, buffer );
1126 CloseHandle( h1 );
1127 return FALSE;
1130 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
1132 BOOL same_file = FALSE;
1133 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1134 OPEN_EXISTING, 0, 0);
1135 if (h2 != INVALID_HANDLE_VALUE)
1137 same_file = is_same_file( h1, h2 );
1138 CloseHandle( h2 );
1140 if (same_file)
1142 HeapFree( GetProcessHeap(), 0, buffer );
1143 CloseHandle( h1 );
1144 SetLastError( ERROR_SHARING_VIOLATION );
1145 return FALSE;
1149 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1150 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
1151 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1153 WARN("Unable to open dest %s\n", debugstr_w(dest));
1154 HeapFree( GetProcessHeap(), 0, buffer );
1155 CloseHandle( h1 );
1156 return FALSE;
1159 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
1161 char *p = buffer;
1162 while (count != 0)
1164 DWORD res;
1165 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1166 p += res;
1167 count -= res;
1170 ret = TRUE;
1171 done:
1172 /* Maintain the timestamp of source file to destination file */
1173 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
1174 HeapFree( GetProcessHeap(), 0, buffer );
1175 CloseHandle( h1 );
1176 CloseHandle( h2 );
1177 return ret;
1181 /**************************************************************************
1182 * CopyFileExA (KERNEL32.@)
1184 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1185 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1186 LPBOOL cancelFlagPointer, DWORD copyFlags)
1188 WCHAR *sourceW, *destW;
1189 BOOL ret;
1191 /* can't use the TEB buffer since we may have a callback routine */
1192 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1193 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1195 HeapFree( GetProcessHeap(), 0, sourceW );
1196 return FALSE;
1198 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1199 cancelFlagPointer, copyFlags);
1200 HeapFree( GetProcessHeap(), 0, sourceW );
1201 HeapFree( GetProcessHeap(), 0, destW );
1202 return ret;
1206 /**************************************************************************
1207 * MoveFileWithProgressW (KERNEL32.@)
1209 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1210 LPPROGRESS_ROUTINE fnProgress,
1211 LPVOID param, DWORD flag )
1213 FILE_BASIC_INFORMATION info;
1214 UNICODE_STRING nt_name;
1215 OBJECT_ATTRIBUTES attr;
1216 IO_STATUS_BLOCK io;
1217 NTSTATUS status;
1218 HANDLE source_handle = 0, dest_handle;
1219 ANSI_STRING source_unix, dest_unix;
1221 TRACE("(%s,%s,%p,%p,%04x)\n",
1222 debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1224 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1225 return add_boot_rename_entry( source, dest, flag );
1227 if (!dest)
1228 return DeleteFileW( source );
1230 if (flag & MOVEFILE_WRITE_THROUGH)
1231 FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1233 /* check if we are allowed to rename the source */
1235 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1237 SetLastError( ERROR_PATH_NOT_FOUND );
1238 return FALSE;
1240 source_unix.Buffer = NULL;
1241 dest_unix.Buffer = NULL;
1242 attr.Length = sizeof(attr);
1243 attr.RootDirectory = 0;
1244 attr.Attributes = OBJ_CASE_INSENSITIVE;
1245 attr.ObjectName = &nt_name;
1246 attr.SecurityDescriptor = NULL;
1247 attr.SecurityQualityOfService = NULL;
1249 status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1250 if (status == STATUS_SUCCESS)
1251 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1252 RtlFreeUnicodeString( &nt_name );
1253 if (status != STATUS_SUCCESS)
1255 SetLastError( RtlNtStatusToDosError(status) );
1256 goto error;
1258 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1259 if (status != STATUS_SUCCESS)
1261 SetLastError( RtlNtStatusToDosError(status) );
1262 goto error;
1265 /* we must have write access to the destination, and it must */
1266 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1268 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1270 SetLastError( ERROR_PATH_NOT_FOUND );
1271 goto error;
1273 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1274 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1275 if (status == STATUS_SUCCESS) /* destination exists */
1277 NtClose( dest_handle );
1278 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1280 SetLastError( ERROR_ALREADY_EXISTS );
1281 RtlFreeUnicodeString( &nt_name );
1282 goto error;
1284 else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1286 SetLastError( ERROR_ACCESS_DENIED );
1287 goto error;
1290 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1292 SetLastError( RtlNtStatusToDosError(status) );
1293 RtlFreeUnicodeString( &nt_name );
1294 goto error;
1297 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1298 RtlFreeUnicodeString( &nt_name );
1299 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1301 SetLastError( RtlNtStatusToDosError(status) );
1302 goto error;
1305 /* now perform the rename */
1307 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1309 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1311 NtClose( source_handle );
1312 RtlFreeAnsiString( &source_unix );
1313 RtlFreeAnsiString( &dest_unix );
1314 if (!CopyFileExW( source, dest, fnProgress,
1315 param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1316 return FALSE;
1317 return DeleteFileW( source );
1319 FILE_SetDosError();
1320 /* if we created the destination, remove it */
1321 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1322 goto error;
1325 /* fixup executable permissions */
1327 if (is_executable( source ) != is_executable( dest ))
1329 struct stat fstat;
1330 if (stat( dest_unix.Buffer, &fstat ) != -1)
1332 if (is_executable( dest ))
1333 /* set executable bit where read bit is set */
1334 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1335 else
1336 fstat.st_mode &= ~0111;
1337 chmod( dest_unix.Buffer, fstat.st_mode );
1341 NtClose( source_handle );
1342 RtlFreeAnsiString( &source_unix );
1343 RtlFreeAnsiString( &dest_unix );
1344 return TRUE;
1346 error:
1347 if (source_handle) NtClose( source_handle );
1348 RtlFreeAnsiString( &source_unix );
1349 RtlFreeAnsiString( &dest_unix );
1350 return FALSE;
1353 /**************************************************************************
1354 * MoveFileWithProgressA (KERNEL32.@)
1356 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1357 LPPROGRESS_ROUTINE fnProgress,
1358 LPVOID param, DWORD flag )
1360 WCHAR *sourceW, *destW;
1361 BOOL ret;
1363 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1364 if (dest)
1366 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1368 else
1369 destW = NULL;
1371 ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1372 HeapFree( GetProcessHeap(), 0, destW );
1373 return ret;
1376 /**************************************************************************
1377 * MoveFileExW (KERNEL32.@)
1379 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1381 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1384 /**************************************************************************
1385 * MoveFileExA (KERNEL32.@)
1387 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1389 return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1393 /**************************************************************************
1394 * MoveFileW (KERNEL32.@)
1396 * Move file or directory
1398 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1400 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1404 /**************************************************************************
1405 * MoveFileA (KERNEL32.@)
1407 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1409 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1413 /*************************************************************************
1414 * CreateHardLinkW (KERNEL32.@)
1416 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1417 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1419 NTSTATUS status;
1420 UNICODE_STRING ntDest, ntSource;
1421 ANSI_STRING unixDest, unixSource;
1422 BOOL ret = FALSE;
1424 TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1425 debugstr_w(lpExistingFileName), lpSecurityAttributes);
1427 ntDest.Buffer = ntSource.Buffer = NULL;
1428 if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1429 !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1431 SetLastError( ERROR_PATH_NOT_FOUND );
1432 goto err;
1435 unixSource.Buffer = unixDest.Buffer = NULL;
1436 status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1437 if (!status)
1439 status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1440 if (!status) /* destination must not exist */
1442 status = STATUS_OBJECT_NAME_EXISTS;
1443 } else if (status == STATUS_NO_SUCH_FILE)
1445 status = STATUS_SUCCESS;
1449 if (status)
1450 SetLastError( RtlNtStatusToDosError(status) );
1451 else if (!link( unixSource.Buffer, unixDest.Buffer ))
1453 TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1454 debugstr_a( unixSource.Buffer ));
1455 ret = TRUE;
1457 else
1458 FILE_SetDosError();
1460 RtlFreeAnsiString( &unixSource );
1461 RtlFreeAnsiString( &unixDest );
1463 err:
1464 RtlFreeUnicodeString( &ntSource );
1465 RtlFreeUnicodeString( &ntDest );
1466 return ret;
1470 /*************************************************************************
1471 * CreateHardLinkA (KERNEL32.@)
1473 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1474 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1476 WCHAR *sourceW, *destW;
1477 BOOL res;
1479 if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1481 return FALSE;
1483 if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1485 HeapFree( GetProcessHeap(), 0, sourceW );
1486 return FALSE;
1489 res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1491 HeapFree( GetProcessHeap(), 0, sourceW );
1492 HeapFree( GetProcessHeap(), 0, destW );
1494 return res;
1498 /***********************************************************************
1499 * CreateDirectoryW (KERNEL32.@)
1500 * RETURNS:
1501 * TRUE : success
1502 * FALSE : failure
1503 * ERROR_DISK_FULL: on full disk
1504 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1505 * ERROR_ACCESS_DENIED: on permission problems
1506 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1508 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1510 OBJECT_ATTRIBUTES attr;
1511 UNICODE_STRING nt_name;
1512 IO_STATUS_BLOCK io;
1513 NTSTATUS status;
1514 HANDLE handle;
1515 BOOL ret = FALSE;
1517 TRACE( "%s\n", debugstr_w(path) );
1519 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1521 SetLastError( ERROR_PATH_NOT_FOUND );
1522 return FALSE;
1524 attr.Length = sizeof(attr);
1525 attr.RootDirectory = 0;
1526 attr.Attributes = OBJ_CASE_INSENSITIVE;
1527 attr.ObjectName = &nt_name;
1528 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1529 attr.SecurityQualityOfService = NULL;
1531 status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1532 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1533 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1535 if (status == STATUS_SUCCESS)
1537 NtClose( handle );
1538 ret = TRUE;
1540 else SetLastError( RtlNtStatusToDosError(status) );
1542 RtlFreeUnicodeString( &nt_name );
1543 return ret;
1547 /***********************************************************************
1548 * CreateDirectoryA (KERNEL32.@)
1550 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1552 WCHAR *pathW;
1554 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1555 return CreateDirectoryW( pathW, sa );
1559 /***********************************************************************
1560 * CreateDirectoryExA (KERNEL32.@)
1562 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1564 WCHAR *pathW, *templateW = NULL;
1565 BOOL ret;
1567 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1568 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1570 ret = CreateDirectoryExW( templateW, pathW, sa );
1571 HeapFree( GetProcessHeap(), 0, templateW );
1572 return ret;
1576 /***********************************************************************
1577 * CreateDirectoryExW (KERNEL32.@)
1579 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1581 return CreateDirectoryW( path, sa );
1585 /***********************************************************************
1586 * RemoveDirectoryW (KERNEL32.@)
1588 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1590 OBJECT_ATTRIBUTES attr;
1591 UNICODE_STRING nt_name;
1592 ANSI_STRING unix_name;
1593 IO_STATUS_BLOCK io;
1594 NTSTATUS status;
1595 HANDLE handle;
1596 BOOL ret = FALSE;
1598 TRACE( "%s\n", debugstr_w(path) );
1600 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1602 SetLastError( ERROR_PATH_NOT_FOUND );
1603 return FALSE;
1605 attr.Length = sizeof(attr);
1606 attr.RootDirectory = 0;
1607 attr.Attributes = OBJ_CASE_INSENSITIVE;
1608 attr.ObjectName = &nt_name;
1609 attr.SecurityDescriptor = NULL;
1610 attr.SecurityQualityOfService = NULL;
1612 status = NtOpenFile( &handle, DELETE, &attr, &io,
1613 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1614 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1615 if (status == STATUS_SUCCESS)
1616 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1617 RtlFreeUnicodeString( &nt_name );
1619 if (status != STATUS_SUCCESS)
1621 SetLastError( RtlNtStatusToDosError(status) );
1622 return FALSE;
1625 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1626 RtlFreeAnsiString( &unix_name );
1627 NtClose( handle );
1628 return ret;
1632 /***********************************************************************
1633 * RemoveDirectoryA (KERNEL32.@)
1635 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1637 WCHAR *pathW;
1639 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1640 return RemoveDirectoryW( pathW );
1644 /***********************************************************************
1645 * GetCurrentDirectoryW (KERNEL32.@)
1647 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1649 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1653 /***********************************************************************
1654 * GetCurrentDirectoryA (KERNEL32.@)
1656 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1658 WCHAR bufferW[MAX_PATH];
1659 DWORD ret;
1661 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1663 /* Win9x catches access violations here, returning zero.
1664 * This behaviour resulted in some people not noticing
1665 * that they got the argument order wrong. So let's be
1666 * nice and fail gracefully if buf is invalid and looks
1667 * more like a buflen. */
1668 SetLastError(ERROR_INVALID_PARAMETER);
1669 return 0;
1672 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1673 if (!ret) return 0;
1674 if (ret > sizeof(bufferW))
1676 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1677 return 0;
1679 return copy_filename_WtoA( bufferW, buf, buflen );
1683 /***********************************************************************
1684 * SetCurrentDirectoryW (KERNEL32.@)
1686 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1688 UNICODE_STRING dirW;
1689 NTSTATUS status;
1691 RtlInitUnicodeString( &dirW, dir );
1692 status = RtlSetCurrentDirectory_U( &dirW );
1693 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1694 return !status;
1698 /***********************************************************************
1699 * SetCurrentDirectoryA (KERNEL32.@)
1701 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1703 WCHAR *dirW;
1704 UNICODE_STRING strW;
1705 NTSTATUS status;
1707 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1708 RtlInitUnicodeString( &strW, dirW );
1709 status = RtlSetCurrentDirectory_U( &strW );
1710 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1711 return !status;
1715 /***********************************************************************
1716 * GetWindowsDirectoryW (KERNEL32.@)
1718 * See comment for GetWindowsDirectoryA.
1720 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1722 UINT len = strlenW( DIR_Windows ) + 1;
1723 if (path && count >= len)
1725 strcpyW( path, DIR_Windows );
1726 len--;
1728 return len;
1732 /***********************************************************************
1733 * GetWindowsDirectoryA (KERNEL32.@)
1735 * Return value:
1736 * If buffer is large enough to hold full path and terminating '\0' character
1737 * function copies path to buffer and returns length of the path without '\0'.
1738 * Otherwise function returns required size including '\0' character and
1739 * does not touch the buffer.
1741 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1743 return copy_filename_WtoA( DIR_Windows, path, count );
1747 /***********************************************************************
1748 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1750 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1752 return GetWindowsDirectoryA( path, count );
1756 /***********************************************************************
1757 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1759 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1761 return GetWindowsDirectoryW( path, count );
1765 /***********************************************************************
1766 * GetSystemDirectoryW (KERNEL32.@)
1768 * See comment for GetWindowsDirectoryA.
1770 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1772 UINT len = strlenW( DIR_System ) + 1;
1773 if (path && count >= len)
1775 strcpyW( path, DIR_System );
1776 len--;
1778 return len;
1782 /***********************************************************************
1783 * GetSystemDirectoryA (KERNEL32.@)
1785 * See comment for GetWindowsDirectoryA.
1787 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1789 return copy_filename_WtoA( DIR_System, path, count );
1793 /***********************************************************************
1794 * GetSystemWow64DirectoryW (KERNEL32.@)
1796 * As seen on MSDN
1797 * - On Win32 we should return ERROR_CALL_NOT_IMPLEMENTED
1798 * - On Win64 we should return the SysWow64 (system64) directory
1800 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1802 UINT len;
1804 if (!DIR_SysWow64)
1806 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1807 return 0;
1809 len = strlenW( DIR_SysWow64 ) + 1;
1810 if (path && count >= len)
1812 strcpyW( path, DIR_SysWow64 );
1813 len--;
1815 return len;
1819 /***********************************************************************
1820 * GetSystemWow64DirectoryA (KERNEL32.@)
1822 * See comment for GetWindowsWow64DirectoryW.
1824 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1826 if (!DIR_SysWow64)
1828 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1829 return 0;
1831 return copy_filename_WtoA( DIR_SysWow64, path, count );
1835 /***********************************************************************
1836 * Wow64EnableWow64FsRedirection (KERNEL32.@)
1838 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1840 NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1841 if (status) SetLastError( RtlNtStatusToDosError(status) );
1842 return !status;
1846 /***********************************************************************
1847 * Wow64DisableWow64FsRedirection (KERNEL32.@)
1849 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1851 NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1852 if (status) SetLastError( RtlNtStatusToDosError(status) );
1853 return !status;
1857 /***********************************************************************
1858 * Wow64RevertWow64FsRedirection (KERNEL32.@)
1860 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1862 NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1863 if (status) SetLastError( RtlNtStatusToDosError(status) );
1864 return !status;
1868 /***********************************************************************
1869 * NeedCurrentDirectoryForExePathW (KERNEL32.@)
1871 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1873 static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1874 'C','u','r','r','e','n','t',
1875 'D','i','r','e','c','t','o','r','y',
1876 'I','n','E','x','e','P','a','t','h',0};
1877 WCHAR env_val;
1879 /* MSDN mentions some 'registry location'. We do not use registry. */
1880 FIXME("(%s): partial stub\n", debugstr_w(name));
1882 if (strchrW(name, '\\'))
1883 return TRUE;
1885 /* Check the existence of the variable, not value */
1886 if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1887 return TRUE;
1889 return FALSE;
1893 /***********************************************************************
1894 * NeedCurrentDirectoryForExePathA (KERNEL32.@)
1896 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1898 WCHAR *nameW;
1900 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1901 return NeedCurrentDirectoryForExePathW( nameW );
1905 /***********************************************************************
1906 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1908 * Return the full Unix file name for a given path.
1909 * Returned buffer must be freed by caller.
1911 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1913 UNICODE_STRING nt_name;
1914 ANSI_STRING unix_name;
1915 NTSTATUS status;
1917 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1918 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1919 RtlFreeUnicodeString( &nt_name );
1920 if (status && status != STATUS_NO_SUCH_FILE)
1922 SetLastError( RtlNtStatusToDosError( status ) );
1923 return NULL;
1925 return unix_name.Buffer;
1929 /***********************************************************************
1930 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1932 * Return the full DOS file name for a given Unix path.
1933 * Returned buffer must be freed by caller.
1935 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1937 UNICODE_STRING nt_name;
1938 ANSI_STRING unix_name;
1939 NTSTATUS status;
1940 DWORD len;
1942 RtlInitAnsiString( &unix_name, str );
1943 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1944 if (status)
1946 SetLastError( RtlNtStatusToDosError( status ) );
1947 return NULL;
1949 if (nt_name.Buffer[5] == ':')
1951 /* get rid of the \??\ prefix */
1952 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1953 len = nt_name.Length - 4 * sizeof(WCHAR);
1954 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1955 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1957 else
1958 nt_name.Buffer[1] = '\\';
1959 return nt_name.Buffer;