include: Move struct WSABUF and WSAMSG to ws2def.h.
[wine.git] / dlls / kernel32 / path.c
blob1728bfac40ea7641f8b7939361ff518a51c981c2
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);
361 /* Check if the file exists and use the existing file name */
362 goit = FindFirstFileW(tmplongpath, &wfd);
363 if (goit == INVALID_HANDLE_VALUE)
365 TRACE("not found %s!\n", debugstr_w(tmplongpath));
366 SetLastError ( ERROR_FILE_NOT_FOUND );
367 return 0;
369 FindClose(goit);
370 strcpyW(tmplongpath + lp, wfd.cFileName);
371 lp += strlenW(tmplongpath + lp);
372 sp += tmplen;
374 tmplen = strlenW(shortpath) - 1;
375 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
376 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
377 tmplongpath[lp++] = shortpath[tmplen];
378 tmplongpath[lp] = 0;
380 tmplen = strlenW(tmplongpath) + 1;
381 if (tmplen <= longlen)
383 strcpyW(longpath, tmplongpath);
384 TRACE("returning %s\n", debugstr_w(longpath));
385 tmplen--; /* length without 0 */
388 return tmplen;
391 /***********************************************************************
392 * GetLongPathNameA (KERNEL32.@)
394 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
396 WCHAR *shortpathW;
397 WCHAR longpathW[MAX_PATH];
398 DWORD ret;
400 TRACE("%s\n", debugstr_a(shortpath));
402 if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
404 ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
406 if (!ret) return 0;
407 if (ret > MAX_PATH)
409 SetLastError(ERROR_FILENAME_EXCED_RANGE);
410 return 0;
412 return copy_filename_WtoA( longpathW, longpath, longlen );
416 /***********************************************************************
417 * GetShortPathNameW (KERNEL32.@)
419 * NOTES
420 * observed:
421 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
422 * longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
424 * more observations ( with NT 3.51 (WinDD) ):
425 * longpath <= 8.3 -> just copy longpath to shortpath
426 * longpath > 8.3 ->
427 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
428 * b) file does exist -> set the short filename.
429 * - trailing slashes are reproduced in the short name, even if the
430 * file is not a directory
431 * - the absolute/relative path of the short name is reproduced like found
432 * in the long name
433 * - longpath and shortpath may have the same address
434 * Peter Ganten, 1999
436 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
438 WCHAR tmpshortpath[MAX_PATHNAME_LEN];
439 LPCWSTR p;
440 DWORD sp = 0, lp = 0;
441 DWORD tmplen;
442 WIN32_FIND_DATAW wfd;
443 HANDLE goit;
445 TRACE("%s\n", debugstr_w(longpath));
447 if (!longpath)
449 SetLastError(ERROR_INVALID_PARAMETER);
450 return 0;
452 if (!longpath[0])
454 SetLastError(ERROR_BAD_PATHNAME);
455 return 0;
458 /* check for drive letter */
459 if (longpath[0] != '/' && longpath[1] == ':' )
461 tmpshortpath[0] = longpath[0];
462 tmpshortpath[1] = ':';
463 sp = lp = 2;
466 while (longpath[lp])
468 /* check for path delimiters and reproduce them */
469 if (longpath[lp] == '\\' || longpath[lp] == '/')
471 if (!sp || tmpshortpath[sp-1] != '\\')
473 /* strip double "\\" */
474 tmpshortpath[sp] = '\\';
475 sp++;
477 tmpshortpath[sp] = 0; /* terminate string */
478 lp++;
479 continue;
482 p = longpath + lp;
483 if (lp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
485 tmpshortpath[sp++] = *p++;
486 tmpshortpath[sp++] = *p++;
488 for (; *p && *p != '/' && *p != '\\'; p++);
489 tmplen = p - (longpath + lp);
490 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
492 /* Check if the file exists and use the existing short file name */
493 goit = FindFirstFileW(tmpshortpath, &wfd);
494 if (goit == INVALID_HANDLE_VALUE) goto notfound;
495 FindClose(goit);
496 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName[0] ? wfd.cAlternateFileName : wfd.cFileName);
497 sp += strlenW(tmpshortpath + sp);
498 lp += tmplen;
500 tmpshortpath[sp] = 0;
502 tmplen = strlenW(tmpshortpath) + 1;
503 if (tmplen <= shortlen)
505 strcpyW(shortpath, tmpshortpath);
506 TRACE("returning %s\n", debugstr_w(shortpath));
507 tmplen--; /* length without 0 */
510 return tmplen;
512 notfound:
513 TRACE("not found!\n" );
514 SetLastError ( ERROR_FILE_NOT_FOUND );
515 return 0;
518 /***********************************************************************
519 * GetShortPathNameA (KERNEL32.@)
521 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
523 WCHAR *longpathW;
524 WCHAR shortpathW[MAX_PATH];
525 DWORD ret;
527 TRACE("%s\n", debugstr_a(longpath));
529 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
531 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
533 if (!ret) return 0;
534 if (ret > MAX_PATH)
536 SetLastError(ERROR_FILENAME_EXCED_RANGE);
537 return 0;
539 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
543 /***********************************************************************
544 * GetTempPathA (KERNEL32.@)
546 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
548 WCHAR pathW[MAX_PATH];
549 UINT ret;
551 ret = GetTempPathW(MAX_PATH, pathW);
553 if (!ret)
554 return 0;
556 if (ret > MAX_PATH)
558 SetLastError(ERROR_FILENAME_EXCED_RANGE);
559 return 0;
561 return copy_filename_WtoA( pathW, path, count );
565 /***********************************************************************
566 * GetTempPathW (KERNEL32.@)
568 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
570 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
571 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
572 static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
573 WCHAR tmp_path[MAX_PATH];
574 UINT ret;
576 TRACE("%u,%p\n", count, path);
578 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
579 !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
580 !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
581 !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
582 return 0;
584 if (ret > MAX_PATH)
586 SetLastError(ERROR_FILENAME_EXCED_RANGE);
587 return 0;
590 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
591 if (!ret) return 0;
593 if (ret > MAX_PATH - 2)
595 SetLastError(ERROR_FILENAME_EXCED_RANGE);
596 return 0;
599 if (tmp_path[ret-1] != '\\')
601 tmp_path[ret++] = '\\';
602 tmp_path[ret] = '\0';
605 ret++; /* add space for terminating 0 */
607 if (count)
609 lstrcpynW(path, tmp_path, count);
610 if (count >= ret)
611 ret--; /* return length without 0 */
612 else if (count < 4)
613 path[0] = 0; /* avoid returning ambiguous "X:" */
616 TRACE("returning %u, %s\n", ret, debugstr_w(path));
617 return ret;
621 /***********************************************************************
622 * GetTempFileNameA (KERNEL32.@)
624 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
626 WCHAR *pathW, *prefixW = NULL;
627 WCHAR bufferW[MAX_PATH];
628 UINT ret;
630 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
631 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
633 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
634 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
636 HeapFree( GetProcessHeap(), 0, prefixW );
637 return ret;
640 /***********************************************************************
641 * GetTempFileNameW (KERNEL32.@)
643 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
645 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
647 int i;
648 LPWSTR p;
649 DWORD attr;
651 if ( !path || !buffer )
653 SetLastError( ERROR_INVALID_PARAMETER );
654 return 0;
657 /* ensure that the provided directory exists */
658 attr = GetFileAttributesW(path);
659 if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY))
661 TRACE("path not found %s\n", debugstr_w(path));
662 SetLastError( ERROR_DIRECTORY );
663 return 0;
666 strcpyW( buffer, path );
667 p = buffer + strlenW(buffer);
669 /* add a \, if there isn't one */
670 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
672 if (prefix)
673 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
675 unique &= 0xffff;
677 if (unique) sprintfW( p, formatW, unique );
678 else
680 /* get a "random" unique number and try to create the file */
681 HANDLE handle;
682 UINT num = GetTickCount() & 0xffff;
683 static UINT last;
685 /* avoid using the same name twice in a short interval */
686 if (last - num < 10) num = last + 1;
687 if (!num) num = 1;
688 unique = num;
691 sprintfW( p, formatW, unique );
692 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
693 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
694 if (handle != INVALID_HANDLE_VALUE)
695 { /* We created it */
696 TRACE("created %s\n", debugstr_w(buffer) );
697 CloseHandle( handle );
698 last = unique;
699 break;
701 if (GetLastError() != ERROR_FILE_EXISTS &&
702 GetLastError() != ERROR_SHARING_VIOLATION)
703 break; /* No need to go on */
704 if (!(++unique & 0xffff)) unique = 1;
705 } while (unique != num);
708 TRACE("returning %s\n", debugstr_w(buffer) );
709 return unique;
713 /***********************************************************************
714 * contains_pathW
716 * Check if the file name contains a path; helper for SearchPathW.
717 * A relative path is not considered a path unless it starts with ./ or ../
719 static inline BOOL contains_pathW (LPCWSTR name)
721 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
722 if (name[0] != '.') return FALSE;
723 if (name[1] == '/' || name[1] == '\\') return TRUE;
724 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
727 /***********************************************************************
728 * find_actctx_dllpath
730 * Find the path (if any) of the dll from the activation context.
731 * Returned path doesn't include a name.
733 static NTSTATUS find_actctx_dllpath(const WCHAR *libname, WCHAR **path)
735 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
736 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
738 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
739 ACTCTX_SECTION_KEYED_DATA data;
740 UNICODE_STRING nameW;
741 NTSTATUS status;
742 SIZE_T needed, size = 1024;
743 WCHAR *p;
745 RtlInitUnicodeString( &nameW, libname );
746 data.cbSize = sizeof(data);
747 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
748 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
749 &nameW, &data );
750 if (status != STATUS_SUCCESS) return status;
752 for (;;)
754 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
756 status = STATUS_NO_MEMORY;
757 goto done;
759 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
760 AssemblyDetailedInformationInActivationContext,
761 info, size, &needed );
762 if (status == STATUS_SUCCESS) break;
763 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
764 HeapFree( GetProcessHeap(), 0, info );
765 size = needed;
766 /* restart with larger buffer */
769 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
771 status = STATUS_SXS_KEY_NOT_FOUND;
772 goto done;
775 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
777 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
779 p++;
780 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
782 /* manifest name does not match directory name, so it's not a global
783 * windows/winsxs manifest; use the manifest directory name instead */
784 dirlen = p - info->lpAssemblyManifestPath;
785 needed = (dirlen + 1) * sizeof(WCHAR);
786 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
788 status = STATUS_NO_MEMORY;
789 goto done;
791 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
792 *(p + dirlen) = 0;
793 goto done;
797 needed = (strlenW( DIR_Windows ) * sizeof(WCHAR) +
798 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + 2*sizeof(WCHAR));
800 if (!(*path = p = HeapAlloc( GetProcessHeap(), 0, needed )))
802 status = STATUS_NO_MEMORY;
803 goto done;
805 strcpyW( p, DIR_Windows );
806 p += strlenW(p);
807 memcpy( p, winsxsW, sizeof(winsxsW) );
808 p += sizeof(winsxsW) / sizeof(WCHAR);
809 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
810 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
811 *p++ = '\\';
812 *p = 0;
813 done:
814 HeapFree( GetProcessHeap(), 0, info );
815 RtlReleaseActivationContext( data.hActCtx );
816 return status;
819 /***********************************************************************
820 * SearchPathW [KERNEL32.@]
822 * Searches for a specified file in the search path.
824 * PARAMS
825 * path [I] Path to search (NULL means default)
826 * name [I] Filename to search for.
827 * ext [I] File extension to append to file name. The first
828 * character must be a period. This parameter is
829 * specified only if the filename given does not
830 * contain an extension.
831 * buflen [I] size of buffer, in characters
832 * buffer [O] buffer for found filename
833 * lastpart [O] address of pointer to last used character in
834 * buffer (the final '\')
836 * RETURNS
837 * Success: length of string copied into buffer, not including
838 * terminating null character. If the filename found is
839 * longer than the length of the buffer, the length of the
840 * filename is returned.
841 * Failure: Zero
843 * NOTES
844 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
845 * (tested on NT 4.0)
847 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
848 LPWSTR buffer, LPWSTR *lastpart )
850 DWORD ret = 0;
852 if (!name || !name[0])
854 SetLastError(ERROR_INVALID_PARAMETER);
855 return 0;
858 /* If the name contains an explicit path, ignore the path */
860 if (contains_pathW(name))
862 /* try first without extension */
863 if (RtlDoesFileExists_U( name ))
864 return GetFullPathNameW( name, buflen, buffer, lastpart );
866 if (ext)
868 LPCWSTR p = strrchrW( name, '.' );
869 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
870 ext = NULL; /* Ignore the specified extension */
873 /* Allocate a buffer for the file name and extension */
874 if (ext)
876 LPWSTR tmp;
877 DWORD len = strlenW(name) + strlenW(ext);
879 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
881 SetLastError( ERROR_OUTOFMEMORY );
882 return 0;
884 strcpyW( tmp, name );
885 strcatW( tmp, ext );
886 if (RtlDoesFileExists_U( tmp ))
887 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
888 HeapFree( GetProcessHeap(), 0, tmp );
891 else if (path && path[0]) /* search in the specified path */
893 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
894 buffer, lastpart ) / sizeof(WCHAR);
896 else /* search in active context and default path */
898 WCHAR *dll_path = NULL, *search = NULL;
899 DWORD req_len, name_len;
901 req_len = name_len = strlenW(name);
903 if (strchrW( name, '.' )) ext = NULL;
904 if (ext)
906 DWORD ext_len = strlenW(ext);
908 req_len += ext_len;
909 name_len += ext_len;
911 search = HeapAlloc( GetProcessHeap(), 0, (name_len + ext_len + 1) * sizeof(WCHAR) );
912 if (!search)
914 SetLastError( ERROR_OUTOFMEMORY );
915 HeapFree( GetProcessHeap(), 0, dll_path );
916 return 0;
918 strcpyW( search, name );
919 strcatW( search, ext );
920 name = search;
922 /* now that we have combined name we don't need extension any more */
925 /* When file is found with activation context no attempt is made
926 to check if it's really exist, path is returned only basing on context info. */
927 if (find_actctx_dllpath( name, &dll_path ) == STATUS_SUCCESS)
929 DWORD path_len;
931 path_len = strlenW(dll_path);
932 req_len += path_len;
934 if (lastpart) *lastpart = NULL;
936 /* count null termination char too */
937 if (req_len + 1 <= buflen)
939 memcpy( buffer, dll_path, path_len * sizeof(WCHAR) );
940 memcpy( &buffer[path_len], name, name_len * sizeof(WCHAR) );
941 buffer[req_len] = 0;
942 if (lastpart) *lastpart = buffer + path_len;
943 ret = req_len;
945 else
946 ret = req_len + 1;
948 HeapFree( GetProcessHeap(), 0, dll_path );
949 HeapFree( GetProcessHeap(), 0, search );
951 else
953 if ((dll_path = MODULE_get_dll_load_path( NULL )))
955 ret = RtlDosSearchPath_U( dll_path, name, NULL, buflen * sizeof(WCHAR),
956 buffer, lastpart ) / sizeof(WCHAR);
957 HeapFree( GetProcessHeap(), 0, dll_path );
958 HeapFree( GetProcessHeap(), 0, search );
960 else
962 SetLastError( ERROR_OUTOFMEMORY );
963 return 0;
968 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
969 else TRACE( "found %s\n", debugstr_w(buffer) );
970 return ret;
974 /***********************************************************************
975 * SearchPathA (KERNEL32.@)
977 * See SearchPathW.
979 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
980 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
982 WCHAR *pathW = NULL, *nameW, *extW = NULL;
983 WCHAR bufferW[MAX_PATH];
984 DWORD ret;
986 if (!name)
988 SetLastError(ERROR_INVALID_PARAMETER);
989 return 0;
992 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
993 if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
995 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
997 HeapFree( GetProcessHeap(), 0, pathW );
998 return 0;
1001 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
1003 HeapFree( GetProcessHeap(), 0, pathW );
1004 HeapFree( GetProcessHeap(), 0, extW );
1006 if (!ret) return 0;
1007 if (ret > MAX_PATH)
1009 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1010 return 0;
1012 ret = copy_filename_WtoA( bufferW, buffer, buflen );
1013 if (buflen > ret && lastpart)
1014 *lastpart = strrchr(buffer, '\\') + 1;
1015 return ret;
1018 static BOOL is_same_file(HANDLE h1, HANDLE h2)
1020 int fd1;
1021 BOOL ret = FALSE;
1022 if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
1024 int fd2;
1025 if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
1027 struct stat stat1, stat2;
1028 if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
1029 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
1030 wine_server_release_fd(h2, fd2);
1032 wine_server_release_fd(h1, fd1);
1034 return ret;
1037 /**************************************************************************
1038 * CopyFileW (KERNEL32.@)
1040 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1042 return CopyFileExW( source, dest, NULL, NULL, NULL,
1043 fail_if_exists ? COPY_FILE_FAIL_IF_EXISTS : 0 );
1047 /**************************************************************************
1048 * CopyFileA (KERNEL32.@)
1050 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1052 WCHAR *sourceW, *destW;
1053 BOOL ret;
1055 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1056 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1058 ret = CopyFileW( sourceW, destW, fail_if_exists );
1060 HeapFree( GetProcessHeap(), 0, destW );
1061 return ret;
1065 /**************************************************************************
1066 * CopyFileExW (KERNEL32.@)
1068 BOOL WINAPI CopyFileExW(LPCWSTR source, LPCWSTR dest,
1069 LPPROGRESS_ROUTINE progress, LPVOID param,
1070 LPBOOL cancel_ptr, DWORD flags)
1072 static const int buffer_size = 65536;
1073 HANDLE h1, h2;
1074 BY_HANDLE_FILE_INFORMATION info;
1075 DWORD count;
1076 BOOL ret = FALSE;
1077 char *buffer;
1079 if (!source || !dest)
1081 SetLastError(ERROR_INVALID_PARAMETER);
1082 return FALSE;
1084 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
1086 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1087 return FALSE;
1090 TRACE("%s -> %s, %x\n", debugstr_w(source), debugstr_w(dest), flags);
1092 if ((h1 = CreateFileW(source, GENERIC_READ,
1093 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1094 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1096 WARN("Unable to open source %s\n", debugstr_w(source));
1097 HeapFree( GetProcessHeap(), 0, buffer );
1098 return FALSE;
1101 if (!GetFileInformationByHandle( h1, &info ))
1103 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1104 HeapFree( GetProcessHeap(), 0, buffer );
1105 CloseHandle( h1 );
1106 return FALSE;
1109 if (!(flags & COPY_FILE_FAIL_IF_EXISTS))
1111 BOOL same_file = FALSE;
1112 h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1113 OPEN_EXISTING, 0, 0);
1114 if (h2 != INVALID_HANDLE_VALUE)
1116 same_file = is_same_file( h1, h2 );
1117 CloseHandle( h2 );
1119 if (same_file)
1121 HeapFree( GetProcessHeap(), 0, buffer );
1122 CloseHandle( h1 );
1123 SetLastError( ERROR_SHARING_VIOLATION );
1124 return FALSE;
1128 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1129 (flags & COPY_FILE_FAIL_IF_EXISTS) ? CREATE_NEW : CREATE_ALWAYS,
1130 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1132 WARN("Unable to open dest %s\n", debugstr_w(dest));
1133 HeapFree( GetProcessHeap(), 0, buffer );
1134 CloseHandle( h1 );
1135 return FALSE;
1138 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
1140 char *p = buffer;
1141 while (count != 0)
1143 DWORD res;
1144 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1145 p += res;
1146 count -= res;
1149 ret = TRUE;
1150 done:
1151 /* Maintain the timestamp of source file to destination file */
1152 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
1153 HeapFree( GetProcessHeap(), 0, buffer );
1154 CloseHandle( h1 );
1155 CloseHandle( h2 );
1156 return ret;
1160 /**************************************************************************
1161 * CopyFileExA (KERNEL32.@)
1163 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1164 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1165 LPBOOL cancelFlagPointer, DWORD copyFlags)
1167 WCHAR *sourceW, *destW;
1168 BOOL ret;
1170 /* can't use the TEB buffer since we may have a callback routine */
1171 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1172 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1174 HeapFree( GetProcessHeap(), 0, sourceW );
1175 return FALSE;
1177 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1178 cancelFlagPointer, copyFlags);
1179 HeapFree( GetProcessHeap(), 0, sourceW );
1180 HeapFree( GetProcessHeap(), 0, destW );
1181 return ret;
1185 /**************************************************************************
1186 * MoveFileWithProgressW (KERNEL32.@)
1188 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1189 LPPROGRESS_ROUTINE fnProgress,
1190 LPVOID param, DWORD flag )
1192 FILE_BASIC_INFORMATION info;
1193 UNICODE_STRING nt_name;
1194 OBJECT_ATTRIBUTES attr;
1195 IO_STATUS_BLOCK io;
1196 NTSTATUS status;
1197 HANDLE source_handle = 0, dest_handle;
1198 ANSI_STRING source_unix, dest_unix;
1200 TRACE("(%s,%s,%p,%p,%04x)\n",
1201 debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1203 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1204 return add_boot_rename_entry( source, dest, flag );
1206 if (!dest)
1207 return DeleteFileW( source );
1209 if (flag & MOVEFILE_WRITE_THROUGH)
1210 FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1212 /* check if we are allowed to rename the source */
1214 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1216 SetLastError( ERROR_PATH_NOT_FOUND );
1217 return FALSE;
1219 source_unix.Buffer = NULL;
1220 dest_unix.Buffer = NULL;
1221 attr.Length = sizeof(attr);
1222 attr.RootDirectory = 0;
1223 attr.Attributes = OBJ_CASE_INSENSITIVE;
1224 attr.ObjectName = &nt_name;
1225 attr.SecurityDescriptor = NULL;
1226 attr.SecurityQualityOfService = NULL;
1228 status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1229 if (status == STATUS_SUCCESS)
1230 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1231 RtlFreeUnicodeString( &nt_name );
1232 if (status != STATUS_SUCCESS)
1234 SetLastError( RtlNtStatusToDosError(status) );
1235 goto error;
1237 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1238 if (status != STATUS_SUCCESS)
1240 SetLastError( RtlNtStatusToDosError(status) );
1241 goto error;
1244 /* we must have write access to the destination, and it must */
1245 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1247 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1249 SetLastError( ERROR_PATH_NOT_FOUND );
1250 goto error;
1252 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1253 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1254 if (status == STATUS_SUCCESS) /* destination exists */
1256 NtClose( dest_handle );
1257 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1259 SetLastError( ERROR_ALREADY_EXISTS );
1260 RtlFreeUnicodeString( &nt_name );
1261 goto error;
1263 else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1265 SetLastError( ERROR_ACCESS_DENIED );
1266 goto error;
1269 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1271 SetLastError( RtlNtStatusToDosError(status) );
1272 RtlFreeUnicodeString( &nt_name );
1273 goto error;
1276 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1277 RtlFreeUnicodeString( &nt_name );
1278 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1280 SetLastError( RtlNtStatusToDosError(status) );
1281 goto error;
1284 /* now perform the rename */
1286 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1288 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1290 NtClose( source_handle );
1291 RtlFreeAnsiString( &source_unix );
1292 RtlFreeAnsiString( &dest_unix );
1293 if (!CopyFileExW( source, dest, fnProgress,
1294 param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1295 return FALSE;
1296 return DeleteFileW( source );
1298 FILE_SetDosError();
1299 /* if we created the destination, remove it */
1300 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1301 goto error;
1304 /* fixup executable permissions */
1306 if (is_executable( source ) != is_executable( dest ))
1308 struct stat fstat;
1309 if (stat( dest_unix.Buffer, &fstat ) != -1)
1311 if (is_executable( dest ))
1312 /* set executable bit where read bit is set */
1313 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1314 else
1315 fstat.st_mode &= ~0111;
1316 chmod( dest_unix.Buffer, fstat.st_mode );
1320 NtClose( source_handle );
1321 RtlFreeAnsiString( &source_unix );
1322 RtlFreeAnsiString( &dest_unix );
1323 return TRUE;
1325 error:
1326 if (source_handle) NtClose( source_handle );
1327 RtlFreeAnsiString( &source_unix );
1328 RtlFreeAnsiString( &dest_unix );
1329 return FALSE;
1332 /**************************************************************************
1333 * MoveFileWithProgressA (KERNEL32.@)
1335 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1336 LPPROGRESS_ROUTINE fnProgress,
1337 LPVOID param, DWORD flag )
1339 WCHAR *sourceW, *destW;
1340 BOOL ret;
1342 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1343 if (dest)
1345 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1347 else
1348 destW = NULL;
1350 ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1351 HeapFree( GetProcessHeap(), 0, destW );
1352 return ret;
1355 /**************************************************************************
1356 * MoveFileExW (KERNEL32.@)
1358 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1360 return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1363 /**************************************************************************
1364 * MoveFileExA (KERNEL32.@)
1366 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1368 return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1372 /**************************************************************************
1373 * MoveFileW (KERNEL32.@)
1375 * Move file or directory
1377 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1379 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1383 /**************************************************************************
1384 * MoveFileA (KERNEL32.@)
1386 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1388 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1392 /*************************************************************************
1393 * CreateHardLinkW (KERNEL32.@)
1395 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1396 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1398 NTSTATUS status;
1399 UNICODE_STRING ntDest, ntSource;
1400 ANSI_STRING unixDest, unixSource;
1401 BOOL ret = FALSE;
1403 TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1404 debugstr_w(lpExistingFileName), lpSecurityAttributes);
1406 ntDest.Buffer = ntSource.Buffer = NULL;
1407 if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1408 !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1410 SetLastError( ERROR_PATH_NOT_FOUND );
1411 goto err;
1414 unixSource.Buffer = unixDest.Buffer = NULL;
1415 status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1416 if (!status)
1418 status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1419 if (!status) /* destination must not exist */
1421 status = STATUS_OBJECT_NAME_EXISTS;
1422 } else if (status == STATUS_NO_SUCH_FILE)
1424 status = STATUS_SUCCESS;
1428 if (status)
1429 SetLastError( RtlNtStatusToDosError(status) );
1430 else if (!link( unixSource.Buffer, unixDest.Buffer ))
1432 TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1433 debugstr_a( unixSource.Buffer ));
1434 ret = TRUE;
1436 else
1437 FILE_SetDosError();
1439 RtlFreeAnsiString( &unixSource );
1440 RtlFreeAnsiString( &unixDest );
1442 err:
1443 RtlFreeUnicodeString( &ntSource );
1444 RtlFreeUnicodeString( &ntDest );
1445 return ret;
1449 /*************************************************************************
1450 * CreateHardLinkA (KERNEL32.@)
1452 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1453 LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1455 WCHAR *sourceW, *destW;
1456 BOOL res;
1458 if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1460 return FALSE;
1462 if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1464 HeapFree( GetProcessHeap(), 0, sourceW );
1465 return FALSE;
1468 res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1470 HeapFree( GetProcessHeap(), 0, sourceW );
1471 HeapFree( GetProcessHeap(), 0, destW );
1473 return res;
1477 /***********************************************************************
1478 * CreateDirectoryW (KERNEL32.@)
1479 * RETURNS:
1480 * TRUE : success
1481 * FALSE : failure
1482 * ERROR_DISK_FULL: on full disk
1483 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1484 * ERROR_ACCESS_DENIED: on permission problems
1485 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1487 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1489 OBJECT_ATTRIBUTES attr;
1490 UNICODE_STRING nt_name;
1491 IO_STATUS_BLOCK io;
1492 NTSTATUS status;
1493 HANDLE handle;
1494 BOOL ret = FALSE;
1496 TRACE( "%s\n", debugstr_w(path) );
1498 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1500 SetLastError( ERROR_PATH_NOT_FOUND );
1501 return FALSE;
1503 attr.Length = sizeof(attr);
1504 attr.RootDirectory = 0;
1505 attr.Attributes = OBJ_CASE_INSENSITIVE;
1506 attr.ObjectName = &nt_name;
1507 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1508 attr.SecurityQualityOfService = NULL;
1510 status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1511 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1512 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1514 if (status == STATUS_SUCCESS)
1516 NtClose( handle );
1517 ret = TRUE;
1519 else SetLastError( RtlNtStatusToDosError(status) );
1521 RtlFreeUnicodeString( &nt_name );
1522 return ret;
1526 /***********************************************************************
1527 * CreateDirectoryA (KERNEL32.@)
1529 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1531 WCHAR *pathW;
1533 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1534 return CreateDirectoryW( pathW, sa );
1538 /***********************************************************************
1539 * CreateDirectoryExA (KERNEL32.@)
1541 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1543 WCHAR *pathW, *templateW = NULL;
1544 BOOL ret;
1546 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1547 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1549 ret = CreateDirectoryExW( templateW, pathW, sa );
1550 HeapFree( GetProcessHeap(), 0, templateW );
1551 return ret;
1555 /***********************************************************************
1556 * CreateDirectoryExW (KERNEL32.@)
1558 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1560 return CreateDirectoryW( path, sa );
1564 /***********************************************************************
1565 * RemoveDirectoryW (KERNEL32.@)
1567 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1569 OBJECT_ATTRIBUTES attr;
1570 UNICODE_STRING nt_name;
1571 ANSI_STRING unix_name;
1572 IO_STATUS_BLOCK io;
1573 NTSTATUS status;
1574 HANDLE handle;
1575 BOOL ret = FALSE;
1577 TRACE( "%s\n", debugstr_w(path) );
1579 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1581 SetLastError( ERROR_PATH_NOT_FOUND );
1582 return FALSE;
1584 attr.Length = sizeof(attr);
1585 attr.RootDirectory = 0;
1586 attr.Attributes = OBJ_CASE_INSENSITIVE;
1587 attr.ObjectName = &nt_name;
1588 attr.SecurityDescriptor = NULL;
1589 attr.SecurityQualityOfService = NULL;
1591 status = NtOpenFile( &handle, DELETE, &attr, &io,
1592 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1593 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1594 if (status == STATUS_SUCCESS)
1595 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1596 RtlFreeUnicodeString( &nt_name );
1598 if (status != STATUS_SUCCESS)
1600 SetLastError( RtlNtStatusToDosError(status) );
1601 return FALSE;
1604 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1605 RtlFreeAnsiString( &unix_name );
1606 NtClose( handle );
1607 return ret;
1611 /***********************************************************************
1612 * RemoveDirectoryA (KERNEL32.@)
1614 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1616 WCHAR *pathW;
1618 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1619 return RemoveDirectoryW( pathW );
1623 /***********************************************************************
1624 * GetCurrentDirectoryW (KERNEL32.@)
1626 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1628 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1632 /***********************************************************************
1633 * GetCurrentDirectoryA (KERNEL32.@)
1635 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1637 WCHAR bufferW[MAX_PATH];
1638 DWORD ret;
1640 if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1642 /* Win9x catches access violations here, returning zero.
1643 * This behaviour resulted in some people not noticing
1644 * that they got the argument order wrong. So let's be
1645 * nice and fail gracefully if buf is invalid and looks
1646 * more like a buflen. */
1647 SetLastError(ERROR_INVALID_PARAMETER);
1648 return 0;
1651 ret = RtlGetCurrentDirectory_U( sizeof(bufferW), bufferW );
1652 if (!ret) return 0;
1653 if (ret > sizeof(bufferW))
1655 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1656 return 0;
1658 return copy_filename_WtoA( bufferW, buf, buflen );
1662 /***********************************************************************
1663 * SetCurrentDirectoryW (KERNEL32.@)
1665 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1667 UNICODE_STRING dirW;
1668 NTSTATUS status;
1670 RtlInitUnicodeString( &dirW, dir );
1671 status = RtlSetCurrentDirectory_U( &dirW );
1672 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1673 return !status;
1677 /***********************************************************************
1678 * SetCurrentDirectoryA (KERNEL32.@)
1680 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1682 WCHAR *dirW;
1683 UNICODE_STRING strW;
1684 NTSTATUS status;
1686 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1687 RtlInitUnicodeString( &strW, dirW );
1688 status = RtlSetCurrentDirectory_U( &strW );
1689 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
1690 return !status;
1694 /***********************************************************************
1695 * GetWindowsDirectoryW (KERNEL32.@)
1697 * See comment for GetWindowsDirectoryA.
1699 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1701 UINT len = strlenW( DIR_Windows ) + 1;
1702 if (path && count >= len)
1704 strcpyW( path, DIR_Windows );
1705 len--;
1707 return len;
1711 /***********************************************************************
1712 * GetWindowsDirectoryA (KERNEL32.@)
1714 * Return value:
1715 * If buffer is large enough to hold full path and terminating '\0' character
1716 * function copies path to buffer and returns length of the path without '\0'.
1717 * Otherwise function returns required size including '\0' character and
1718 * does not touch the buffer.
1720 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1722 return copy_filename_WtoA( DIR_Windows, path, count );
1726 /***********************************************************************
1727 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1729 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1731 return GetWindowsDirectoryA( path, count );
1735 /***********************************************************************
1736 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1738 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1740 return GetWindowsDirectoryW( path, count );
1744 /***********************************************************************
1745 * GetSystemDirectoryW (KERNEL32.@)
1747 * See comment for GetWindowsDirectoryA.
1749 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1751 UINT len = strlenW( DIR_System ) + 1;
1752 if (path && count >= len)
1754 strcpyW( path, DIR_System );
1755 len--;
1757 return len;
1761 /***********************************************************************
1762 * GetSystemDirectoryA (KERNEL32.@)
1764 * See comment for GetWindowsDirectoryA.
1766 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1768 return copy_filename_WtoA( DIR_System, path, count );
1772 /***********************************************************************
1773 * GetSystemWow64DirectoryW (KERNEL32.@)
1775 * As seen on MSDN
1776 * - On Win32 we should return ERROR_CALL_NOT_IMPLEMENTED
1777 * - On Win64 we should return the SysWow64 (system64) directory
1779 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1781 UINT len;
1783 if (!DIR_SysWow64)
1785 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1786 return 0;
1788 len = strlenW( DIR_SysWow64 ) + 1;
1789 if (path && count >= len)
1791 strcpyW( path, DIR_SysWow64 );
1792 len--;
1794 return len;
1798 /***********************************************************************
1799 * GetSystemWow64DirectoryA (KERNEL32.@)
1801 * See comment for GetWindowsWow64DirectoryW.
1803 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1805 if (!DIR_SysWow64)
1807 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1808 return 0;
1810 return copy_filename_WtoA( DIR_SysWow64, path, count );
1814 /***********************************************************************
1815 * Wow64EnableWow64FsRedirection (KERNEL32.@)
1817 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1819 NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1820 if (status) SetLastError( RtlNtStatusToDosError(status) );
1821 return !status;
1825 /***********************************************************************
1826 * Wow64DisableWow64FsRedirection (KERNEL32.@)
1828 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1830 NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1831 if (status) SetLastError( RtlNtStatusToDosError(status) );
1832 return !status;
1836 /***********************************************************************
1837 * Wow64RevertWow64FsRedirection (KERNEL32.@)
1839 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1841 NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1842 if (status) SetLastError( RtlNtStatusToDosError(status) );
1843 return !status;
1847 /***********************************************************************
1848 * NeedCurrentDirectoryForExePathW (KERNEL32.@)
1850 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1852 static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1853 'C','u','r','r','e','n','t',
1854 'D','i','r','e','c','t','o','r','y',
1855 'I','n','E','x','e','P','a','t','h',0};
1856 WCHAR env_val;
1858 /* MSDN mentions some 'registry location'. We do not use registry. */
1859 FIXME("(%s): partial stub\n", debugstr_w(name));
1861 if (strchrW(name, '\\'))
1862 return TRUE;
1864 /* Check the existence of the variable, not value */
1865 if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1866 return TRUE;
1868 return FALSE;
1872 /***********************************************************************
1873 * NeedCurrentDirectoryForExePathA (KERNEL32.@)
1875 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1877 WCHAR *nameW;
1879 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1880 return NeedCurrentDirectoryForExePathW( nameW );
1884 /***********************************************************************
1885 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1887 * Return the full Unix file name for a given path.
1888 * Returned buffer must be freed by caller.
1890 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1892 UNICODE_STRING nt_name;
1893 ANSI_STRING unix_name;
1894 NTSTATUS status;
1896 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1897 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1898 RtlFreeUnicodeString( &nt_name );
1899 if (status && status != STATUS_NO_SUCH_FILE)
1901 SetLastError( RtlNtStatusToDosError( status ) );
1902 return NULL;
1904 return unix_name.Buffer;
1908 /***********************************************************************
1909 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1911 * Return the full DOS file name for a given Unix path.
1912 * Returned buffer must be freed by caller.
1914 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1916 UNICODE_STRING nt_name;
1917 ANSI_STRING unix_name;
1918 NTSTATUS status;
1919 DWORD len;
1921 RtlInitAnsiString( &unix_name, str );
1922 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1923 if (status)
1925 SetLastError( RtlNtStatusToDosError( status ) );
1926 return NULL;
1928 if (nt_name.Buffer[5] == ':')
1930 /* get rid of the \??\ prefix */
1931 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1932 len = nt_name.Length - 4 * sizeof(WCHAR);
1933 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1934 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1936 else
1937 nt_name.Buffer[1] = '\\';
1938 return nt_name.Buffer;