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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "wine/port.h"
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
39 #include "kernel_private.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(file);
45 #define MAX_PATHNAME_LEN 1024
48 /* check if a file name is for an executable file (.exe or .com) */
49 inline static BOOL is_executable( const WCHAR *name )
51 static const WCHAR exeW[] = {'.','e','x','e',0};
52 static const WCHAR comW[] = {'.','c','o','m',0};
53 int len = strlenW(name);
55 if (len < 4) return FALSE;
56 return (!strcmpiW( name + len - 4, exeW ) || !strcmpiW( name + len - 4, comW ));
59 /***********************************************************************
62 * copy a file name back to OEM/Ansi, but only if the buffer is large enough
64 static DWORD copy_filename_WtoA( LPCWSTR nameW, LPSTR buffer, DWORD len )
68 BOOL is_ansi = AreFileApisANSI();
70 RtlInitUnicodeString( &strW, nameW );
72 ret = is_ansi ? RtlUnicodeStringToAnsiSize(&strW) : RtlUnicodeStringToOemSize(&strW);
73 if (buffer && ret <= len)
78 str.MaximumLength = len;
80 RtlUnicodeStringToAnsiString( &str, &strW, FALSE );
82 RtlUnicodeStringToOemString( &str, &strW, FALSE );
83 ret = str.Length; /* length without terminating 0 */
88 /***********************************************************************
89 * add_boot_rename_entry
91 * Adds an entry to the registry that is loaded when windows boots and
92 * checks if there are some files to be removed or renamed/moved.
93 * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
94 * non-NULL then the file is moved, otherwise it is deleted. The
95 * entry of the registrykey is always appended with two zero
96 * terminated strings. If <fn2> is NULL then the second entry is
97 * simply a single 0-byte. Otherwise the second filename goes
98 * there. The entries are prepended with \??\ before the path and the
99 * second filename gets also a '!' as the first character if
100 * MOVEFILE_REPLACE_EXISTING is set. After the final string another
101 * 0-byte follows to indicate the end of the strings.
103 * \??\D:\test\file1[0]
104 * !\??\D:\test\file1_renamed[0]
105 * \??\D:\Test|delete[0]
106 * [0] <- file is to be deleted, second string empty
107 * \??\D:\test\file2[0]
108 * !\??\D:\test\file2_renamed[0]
109 * [0] <- indicates end of strings
112 * \??\D:\test\file1[0]
113 * !\??\D:\test\file1_renamed[0]
114 * \??\D:\Test|delete[0]
115 * [0] <- file is to be deleted, second string empty
116 * [0] <- indicates end of strings
119 static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
121 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
122 'F','i','l','e','R','e','n','a','m','e',
123 'O','p','e','r','a','t','i','o','n','s',0};
124 static const WCHAR SessionW[] = {'M','a','c','h','i','n','e','\\',
125 'S','y','s','t','e','m','\\',
126 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
127 'C','o','n','t','r','o','l','\\',
128 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
129 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
131 OBJECT_ATTRIBUTES attr;
132 UNICODE_STRING nameW, source_name, dest_name;
133 KEY_VALUE_PARTIAL_INFORMATION *info;
141 if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
143 SetLastError( ERROR_PATH_NOT_FOUND );
146 dest_name.Buffer = NULL;
147 if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
149 RtlFreeUnicodeString( &source_name );
150 SetLastError( ERROR_PATH_NOT_FOUND );
154 attr.Length = sizeof(attr);
155 attr.RootDirectory = 0;
156 attr.ObjectName = &nameW;
158 attr.SecurityDescriptor = NULL;
159 attr.SecurityQualityOfService = NULL;
160 RtlInitUnicodeString( &nameW, SessionW );
162 if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
164 WARN("Error creating key for reboot managment [%s]\n",
165 "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
166 RtlFreeUnicodeString( &source_name );
167 RtlFreeUnicodeString( &dest_name );
171 len1 = source_name.Length + sizeof(WCHAR);
174 len2 = dest_name.Length + sizeof(WCHAR);
175 if (flags & MOVEFILE_REPLACE_EXISTING)
176 len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
178 else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
180 RtlInitUnicodeString( &nameW, ValueName );
182 /* First we check if the key exists and if so how many bytes it already contains. */
183 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
184 NULL, 0, &DataSize ) == STATUS_BUFFER_OVERFLOW)
186 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
188 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
189 Buffer, DataSize, &DataSize )) goto Quit;
190 info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
191 if (info->Type != REG_MULTI_SZ) goto Quit;
192 if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR); /* remove terminating null (will be added back later) */
196 DataSize = info_size;
197 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
201 memcpy( Buffer + DataSize, source_name.Buffer, len1 );
203 p = (WCHAR *)(Buffer + DataSize);
206 if (flags & MOVEFILE_REPLACE_EXISTING)
208 memcpy( p, dest_name.Buffer, len2 );
214 DataSize += sizeof(WCHAR);
218 p = (WCHAR *)(Buffer + DataSize);
220 DataSize += sizeof(WCHAR);
222 rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
225 RtlFreeUnicodeString( &source_name );
226 RtlFreeUnicodeString( &dest_name );
227 if (Reboot) NtClose(Reboot);
228 HeapFree( GetProcessHeap(), 0, Buffer );
233 /***********************************************************************
234 * GetFullPathNameW (KERNEL32.@)
236 * if the path closed with '\', *lastpart is 0
238 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
241 return RtlGetFullPathName_U(name, len * sizeof(WCHAR), buffer, lastpart) / sizeof(WCHAR);
244 /***********************************************************************
245 * GetFullPathNameA (KERNEL32.@)
247 * if the path closed with '\', *lastpart is 0
249 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
253 WCHAR bufferW[MAX_PATH];
256 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
258 ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, NULL);
263 SetLastError(ERROR_FILENAME_EXCED_RANGE);
266 ret = copy_filename_WtoA( bufferW, buffer, len );
267 if (ret < len && lastpart)
269 LPSTR p = buffer + strlen(buffer) - 1;
273 while ((p > buffer + 2) && (*p != '\\')) p--;
276 else *lastpart = NULL;
282 /***********************************************************************
283 * GetLongPathNameW (KERNEL32.@)
286 * observed (Win2000):
287 * shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
288 * shortpath="": LastError=ERROR_PATH_NOT_FOUND, ret=0
290 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
292 WCHAR tmplongpath[MAX_PATHNAME_LEN];
294 DWORD sp = 0, lp = 0;
296 BOOL unixabsolute = (shortpath[0] == '/');
297 WIN32_FIND_DATAW wfd;
302 SetLastError(ERROR_INVALID_PARAMETER);
307 SetLastError(ERROR_PATH_NOT_FOUND);
311 TRACE("%s,%p,%ld\n", debugstr_w(shortpath), longpath, longlen);
313 if (shortpath[0] == '\\' && shortpath[1] == '\\')
315 ERR("UNC pathname %s\n", debugstr_w(shortpath));
316 lstrcpynW( longpath, shortpath, longlen );
317 return strlenW(longpath);
320 /* check for drive letter */
321 if (!unixabsolute && shortpath[1] == ':' )
323 tmplongpath[0] = shortpath[0];
324 tmplongpath[1] = ':';
328 while (shortpath[sp])
330 /* check for path delimiters and reproduce them */
331 if (shortpath[sp] == '\\' || shortpath[sp] == '/')
333 if (!lp || tmplongpath[lp-1] != '\\')
335 /* strip double "\\" */
336 tmplongpath[lp++] = '\\';
338 tmplongpath[lp] = 0; /* terminate string */
344 if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
346 tmplongpath[lp++] = *p++;
347 tmplongpath[lp++] = *p++;
349 for (; *p && *p != '/' && *p != '\\'; p++);
350 tmplen = p - (shortpath + sp);
351 lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
352 /* Check if the file exists and use the existing file name */
353 goit = FindFirstFileW(tmplongpath, &wfd);
354 if (goit == INVALID_HANDLE_VALUE)
356 TRACE("not found %s!\n", debugstr_w(tmplongpath));
357 SetLastError ( ERROR_FILE_NOT_FOUND );
361 strcpyW(tmplongpath + lp, wfd.cFileName);
362 lp += strlenW(tmplongpath + lp);
365 tmplen = strlenW(shortpath) - 1;
366 if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
367 (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
368 tmplongpath[lp++] = shortpath[tmplen];
371 tmplen = strlenW(tmplongpath) + 1;
372 if (tmplen <= longlen)
374 strcpyW(longpath, tmplongpath);
375 TRACE("returning %s\n", debugstr_w(longpath));
376 tmplen--; /* length without 0 */
382 /***********************************************************************
383 * GetLongPathNameA (KERNEL32.@)
385 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
388 WCHAR longpathW[MAX_PATH];
391 TRACE("%s\n", debugstr_a(shortpath));
393 if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
395 ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
400 SetLastError(ERROR_FILENAME_EXCED_RANGE);
403 return copy_filename_WtoA( longpathW, longpath, longlen );
407 /***********************************************************************
408 * GetShortPathNameW (KERNEL32.@)
412 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
413 * longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
415 * more observations ( with NT 3.51 (WinDD) ):
416 * longpath <= 8.3 -> just copy longpath to shortpath
418 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
419 * b) file does exist -> set the short filename.
420 * - trailing slashes are reproduced in the short name, even if the
421 * file is not a directory
422 * - the absolute/relative path of the short name is reproduced like found
424 * - longpath and shortpath may have the same address
427 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
429 WCHAR tmpshortpath[MAX_PATHNAME_LEN];
431 DWORD sp = 0, lp = 0;
433 BOOL unixabsolute = (longpath[0] == '/');
434 WIN32_FIND_DATAW wfd;
437 WCHAR ustr_buf[8+1+3+1];
439 TRACE("%s\n", debugstr_w(longpath));
443 SetLastError(ERROR_INVALID_PARAMETER);
448 SetLastError(ERROR_BAD_PATHNAME);
452 /* check for drive letter */
453 if (!unixabsolute && longpath[1] == ':' )
455 tmpshortpath[0] = longpath[0];
456 tmpshortpath[1] = ':';
460 ustr.Buffer = ustr_buf;
462 ustr.MaximumLength = sizeof(ustr_buf);
466 /* check for path delimiters and reproduce them */
467 if (longpath[lp] == '\\' || longpath[lp] == '/')
469 if (!sp || tmpshortpath[sp-1] != '\\')
471 /* strip double "\\" */
472 tmpshortpath[sp] = '\\';
475 tmpshortpath[sp] = 0; /* terminate string */
480 for (p = longpath + lp; *p && *p != '/' && *p != '\\'; p++);
481 tmplen = p - (longpath + lp);
482 lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
483 /* Check, if the current element is a valid dos name */
484 if (tmplen <= 8+1+3+1)
487 memcpy(ustr_buf, longpath + lp, tmplen * sizeof(WCHAR));
488 ustr_buf[tmplen] = '\0';
489 ustr.Length = tmplen * sizeof(WCHAR);
490 if (RtlIsNameLegalDOS8Dot3(&ustr, NULL, &spaces) && !spaces)
498 /* Check if the file exists and use the existing short file name */
499 goit = FindFirstFileW(tmpshortpath, &wfd);
500 if (goit == INVALID_HANDLE_VALUE) goto notfound;
502 strcpyW(tmpshortpath + sp, wfd.cAlternateFileName);
503 sp += strlenW(tmpshortpath + sp);
506 tmpshortpath[sp] = 0;
508 tmplen = strlenW(tmpshortpath) + 1;
509 if (tmplen <= shortlen)
511 strcpyW(shortpath, tmpshortpath);
512 TRACE("returning %s\n", debugstr_w(shortpath));
513 tmplen--; /* length without 0 */
519 TRACE("not found!\n" );
520 SetLastError ( ERROR_FILE_NOT_FOUND );
524 /***********************************************************************
525 * GetShortPathNameA (KERNEL32.@)
527 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
530 WCHAR shortpathW[MAX_PATH];
533 TRACE("%s\n", debugstr_a(longpath));
535 if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
537 ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
542 SetLastError(ERROR_FILENAME_EXCED_RANGE);
545 return copy_filename_WtoA( shortpathW, shortpath, shortlen );
549 /***********************************************************************
550 * GetTempPathA (KERNEL32.@)
552 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
554 WCHAR pathW[MAX_PATH];
557 ret = GetTempPathW(MAX_PATH, pathW);
564 SetLastError(ERROR_FILENAME_EXCED_RANGE);
567 return copy_filename_WtoA( pathW, path, count );
571 /***********************************************************************
572 * GetTempPathW (KERNEL32.@)
574 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
576 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
577 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
578 WCHAR tmp_path[MAX_PATH];
581 TRACE("%lu,%p\n", count, path);
583 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )))
584 if (!(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )))
585 if (!(ret = GetCurrentDirectoryW( MAX_PATH, tmp_path )))
590 SetLastError(ERROR_FILENAME_EXCED_RANGE);
594 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
597 if (ret > MAX_PATH - 2)
599 SetLastError(ERROR_FILENAME_EXCED_RANGE);
603 if (tmp_path[ret-1] != '\\')
605 tmp_path[ret++] = '\\';
606 tmp_path[ret] = '\0';
609 ret++; /* add space for terminating 0 */
613 lstrcpynW(path, tmp_path, count);
615 ret--; /* return length without 0 */
617 path[0] = 0; /* avoid returning ambiguous "X:" */
620 TRACE("returning %u, %s\n", ret, debugstr_w(path));
625 /***********************************************************************
626 * GetTempFileNameA (KERNEL32.@)
628 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
630 WCHAR *pathW, *prefixW = NULL;
631 WCHAR bufferW[MAX_PATH];
634 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
635 if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
637 ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
638 if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
640 HeapFree( GetProcessHeap(), 0, prefixW );
644 /***********************************************************************
645 * GetTempFileNameW (KERNEL32.@)
647 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
649 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
654 if ( !path || !buffer )
656 SetLastError( ERROR_INVALID_PARAMETER );
660 strcpyW( buffer, path );
661 p = buffer + strlenW(buffer);
663 /* add a \, if there isn't one */
664 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
667 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
671 if (unique) sprintfW( p, formatW, unique );
674 /* get a "random" unique number and try to create the file */
676 UINT num = GetTickCount() & 0xffff;
682 sprintfW( p, formatW, unique );
683 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
684 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
685 if (handle != INVALID_HANDLE_VALUE)
686 { /* We created it */
687 TRACE("created %s\n", debugstr_w(buffer) );
688 CloseHandle( handle );
691 if (GetLastError() != ERROR_FILE_EXISTS &&
692 GetLastError() != ERROR_SHARING_VIOLATION)
693 break; /* No need to go on */
694 if (!(++unique & 0xffff)) unique = 1;
695 } while (unique != num);
698 TRACE("returning %s\n", debugstr_w(buffer) );
703 /***********************************************************************
706 * Check if the file name contains a path; helper for SearchPathW.
707 * A relative path is not considered a path unless it starts with ./ or ../
709 inline static BOOL contains_pathW (LPCWSTR name)
711 if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
712 if (name[0] != '.') return FALSE;
713 if (name[1] == '/' || name[1] == '\\') return TRUE;
714 return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
718 /***********************************************************************
719 * SearchPathW [KERNEL32.@]
721 * Searches for a specified file in the search path.
724 * path [I] Path to search
725 * name [I] Filename to search for.
726 * ext [I] File extension to append to file name. The first
727 * character must be a period. This parameter is
728 * specified only if the filename given does not
729 * contain an extension.
730 * buflen [I] size of buffer, in characters
731 * buffer [O] buffer for found filename
732 * lastpart [O] address of pointer to last used character in
733 * buffer (the final '\')
736 * Success: length of string copied into buffer, not including
737 * terminating null character. If the filename found is
738 * longer than the length of the buffer, the length of the
739 * filename is returned.
743 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
746 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
747 LPWSTR buffer, LPWSTR *lastpart )
751 /* If the name contains an explicit path, ignore the path */
753 if (contains_pathW(name))
755 /* try first without extension */
756 if (RtlDoesFileExists_U( name ))
757 return GetFullPathNameW( name, buflen, buffer, lastpart );
761 LPCWSTR p = strrchrW( name, '.' );
762 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
763 ext = NULL; /* Ignore the specified extension */
766 /* Allocate a buffer for the file name and extension */
770 DWORD len = strlenW(name) + strlenW(ext);
772 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
774 SetLastError( ERROR_OUTOFMEMORY );
777 strcpyW( tmp, name );
779 if (RtlDoesFileExists_U( tmp ))
780 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
781 HeapFree( GetProcessHeap(), 0, tmp );
784 else if (path && path[0]) /* search in the specified path */
786 ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
787 buffer, lastpart ) / sizeof(WCHAR);
789 else /* search in the default path */
791 WCHAR *dll_path = MODULE_get_dll_load_path( NULL );
795 ret = RtlDosSearchPath_U( dll_path, name, ext, buflen * sizeof(WCHAR),
796 buffer, lastpart ) / sizeof(WCHAR);
797 HeapFree( GetProcessHeap(), 0, dll_path );
801 SetLastError( ERROR_OUTOFMEMORY );
806 if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
807 else TRACE( "found %s\n", debugstr_w(buffer) );
812 /***********************************************************************
813 * SearchPathA (KERNEL32.@)
817 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
818 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
820 WCHAR *pathW, *nameW = NULL, *extW = NULL;
821 WCHAR bufferW[MAX_PATH];
824 if (name && !(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
825 if (!(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
826 if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
828 HeapFree( GetProcessHeap(), 0, pathW );
832 ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
834 HeapFree( GetProcessHeap(), 0, pathW );
835 HeapFree( GetProcessHeap(), 0, extW );
840 SetLastError(ERROR_FILENAME_EXCED_RANGE);
843 ret = copy_filename_WtoA( bufferW, buffer, buflen );
844 if (buflen > ret && lastpart)
845 *lastpart = strrchr(buffer, '\\') + 1;
850 /**************************************************************************
851 * CopyFileW (KERNEL32.@)
853 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
855 static const int buffer_size = 65536;
857 BY_HANDLE_FILE_INFORMATION info;
862 if (!source || !dest)
864 SetLastError(ERROR_INVALID_PARAMETER);
867 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
869 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
873 TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
875 if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
876 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
878 WARN("Unable to open source %s\n", debugstr_w(source));
882 if (!GetFileInformationByHandle( h1, &info ))
884 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
889 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
890 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
891 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
893 WARN("Unable to open dest %s\n", debugstr_w(dest));
898 while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
904 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
911 /* Maintain the timestamp of source file to destination file */
912 SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
913 HeapFree( GetProcessHeap(), 0, buffer );
920 /**************************************************************************
921 * CopyFileA (KERNEL32.@)
923 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
925 WCHAR *sourceW, *destW;
928 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
929 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
931 ret = CopyFileW( sourceW, destW, fail_if_exists );
933 HeapFree( GetProcessHeap(), 0, destW );
938 /**************************************************************************
939 * CopyFileExW (KERNEL32.@)
941 * This implementation ignores most of the extra parameters passed-in into
942 * the "ex" version of the method and calls the CopyFile method.
943 * It will have to be fixed eventually.
945 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
946 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
947 LPBOOL cancelFlagPointer, DWORD copyFlags)
950 * Interpret the only flag that CopyFile can interpret.
952 return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
956 /**************************************************************************
957 * CopyFileExA (KERNEL32.@)
959 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
960 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
961 LPBOOL cancelFlagPointer, DWORD copyFlags)
963 WCHAR *sourceW, *destW;
966 /* can't use the TEB buffer since we may have a callback routine */
967 if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
968 if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
970 HeapFree( GetProcessHeap(), 0, sourceW );
973 ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
974 cancelFlagPointer, copyFlags);
975 HeapFree( GetProcessHeap(), 0, sourceW );
976 HeapFree( GetProcessHeap(), 0, destW );
981 /**************************************************************************
982 * MoveFileExW (KERNEL32.@)
984 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
986 FILE_BASIC_INFORMATION info;
987 UNICODE_STRING nt_name;
988 OBJECT_ATTRIBUTES attr;
991 HANDLE source_handle = 0, dest_handle;
992 ANSI_STRING source_unix, dest_unix;
994 TRACE("(%s,%s,%04lx)\n", debugstr_w(source), debugstr_w(dest), flag);
996 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
997 return add_boot_rename_entry( source, dest, flag );
1000 return DeleteFileW( source );
1002 /* check if we are allowed to rename the source */
1004 if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1006 SetLastError( ERROR_PATH_NOT_FOUND );
1009 source_unix.Buffer = NULL;
1010 dest_unix.Buffer = NULL;
1011 attr.Length = sizeof(attr);
1012 attr.RootDirectory = 0;
1013 attr.Attributes = OBJ_CASE_INSENSITIVE;
1014 attr.ObjectName = &nt_name;
1015 attr.SecurityDescriptor = NULL;
1016 attr.SecurityQualityOfService = NULL;
1018 status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1019 if (status == STATUS_SUCCESS)
1020 status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1021 RtlFreeUnicodeString( &nt_name );
1022 if (status != STATUS_SUCCESS)
1024 SetLastError( RtlNtStatusToDosError(status) );
1027 status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1028 if (status != STATUS_SUCCESS)
1030 SetLastError( RtlNtStatusToDosError(status) );
1034 if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1036 if (flag & MOVEFILE_REPLACE_EXISTING) /* cannot replace directory */
1038 SetLastError( ERROR_INVALID_PARAMETER );
1043 /* we must have write access to the destination, and it must */
1044 /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1046 if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1048 SetLastError( ERROR_PATH_NOT_FOUND );
1051 status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1052 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1053 if (status == STATUS_SUCCESS)
1055 NtClose( dest_handle );
1056 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1058 SetLastError( ERROR_ALREADY_EXISTS );
1059 RtlFreeUnicodeString( &nt_name );
1063 else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1065 SetLastError( RtlNtStatusToDosError(status) );
1066 RtlFreeUnicodeString( &nt_name );
1070 status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1071 RtlFreeUnicodeString( &nt_name );
1072 if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1074 SetLastError( RtlNtStatusToDosError(status) );
1078 /* now perform the rename */
1080 if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1082 if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1084 NtClose( source_handle );
1085 RtlFreeAnsiString( &source_unix );
1086 RtlFreeAnsiString( &dest_unix );
1087 return (CopyFileW( source, dest, TRUE ) && DeleteFileW( source ));
1090 /* if we created the destination, remove it */
1091 if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1095 /* fixup executable permissions */
1097 if (is_executable( source ) != is_executable( dest ))
1100 if (stat( dest_unix.Buffer, &fstat ) != -1)
1102 if (is_executable( dest ))
1103 /* set executable bit where read bit is set */
1104 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1106 fstat.st_mode &= ~0111;
1107 chmod( dest_unix.Buffer, fstat.st_mode );
1111 NtClose( source_handle );
1112 RtlFreeAnsiString( &source_unix );
1113 RtlFreeAnsiString( &dest_unix );
1117 if (source_handle) NtClose( source_handle );
1118 RtlFreeAnsiString( &source_unix );
1119 RtlFreeAnsiString( &dest_unix );
1123 /**************************************************************************
1124 * MoveFileExA (KERNEL32.@)
1126 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1128 WCHAR *sourceW, *destW;
1131 if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1134 if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1139 ret = MoveFileExW( sourceW, destW, flag );
1140 HeapFree( GetProcessHeap(), 0, destW );
1145 /**************************************************************************
1146 * MoveFileW (KERNEL32.@)
1148 * Move file or directory
1150 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1152 return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1156 /**************************************************************************
1157 * MoveFileA (KERNEL32.@)
1159 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1161 return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1165 /***********************************************************************
1166 * CreateDirectoryW (KERNEL32.@)
1170 * ERROR_DISK_FULL: on full disk
1171 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
1172 * ERROR_ACCESS_DENIED: on permission problems
1173 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1175 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1177 OBJECT_ATTRIBUTES attr;
1178 UNICODE_STRING nt_name;
1184 TRACE( "%s\n", debugstr_w(path) );
1186 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1188 SetLastError( ERROR_PATH_NOT_FOUND );
1191 attr.Length = sizeof(attr);
1192 attr.RootDirectory = 0;
1193 attr.Attributes = OBJ_CASE_INSENSITIVE;
1194 attr.ObjectName = &nt_name;
1195 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1196 attr.SecurityQualityOfService = NULL;
1198 status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1199 FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1200 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1202 if (status == STATUS_SUCCESS)
1207 else SetLastError( RtlNtStatusToDosError(status) );
1209 RtlFreeUnicodeString( &nt_name );
1214 /***********************************************************************
1215 * CreateDirectoryA (KERNEL32.@)
1217 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1221 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1222 return CreateDirectoryW( pathW, sa );
1226 /***********************************************************************
1227 * CreateDirectoryExA (KERNEL32.@)
1229 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1231 WCHAR *pathW, *templateW = NULL;
1234 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1235 if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1237 ret = CreateDirectoryExW( templateW, pathW, sa );
1238 HeapFree( GetProcessHeap(), 0, templateW );
1243 /***********************************************************************
1244 * CreateDirectoryExW (KERNEL32.@)
1246 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1248 return CreateDirectoryW( path, sa );
1252 /***********************************************************************
1253 * RemoveDirectoryW (KERNEL32.@)
1255 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1257 OBJECT_ATTRIBUTES attr;
1258 UNICODE_STRING nt_name;
1259 ANSI_STRING unix_name;
1265 TRACE( "%s\n", debugstr_w(path) );
1267 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1269 SetLastError( ERROR_PATH_NOT_FOUND );
1272 attr.Length = sizeof(attr);
1273 attr.RootDirectory = 0;
1274 attr.Attributes = OBJ_CASE_INSENSITIVE;
1275 attr.ObjectName = &nt_name;
1276 attr.SecurityDescriptor = NULL;
1277 attr.SecurityQualityOfService = NULL;
1279 status = NtOpenFile( &handle, GENERIC_READ, &attr, &io,
1280 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1281 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1282 if (status == STATUS_SUCCESS)
1283 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1284 RtlFreeUnicodeString( &nt_name );
1286 if (status != STATUS_SUCCESS)
1288 SetLastError( RtlNtStatusToDosError(status) );
1292 if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1293 RtlFreeAnsiString( &unix_name );
1299 /***********************************************************************
1300 * RemoveDirectoryA (KERNEL32.@)
1302 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1306 if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1307 return RemoveDirectoryW( pathW );
1311 /***********************************************************************
1312 * GetCurrentDirectoryW (KERNEL32.@)
1314 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1316 return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1320 /***********************************************************************
1321 * GetCurrentDirectoryA (KERNEL32.@)
1323 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1325 WCHAR bufferW[MAX_PATH];
1328 if (buflen && buf && !HIWORD(buf))
1330 /* Win9x catches access violations here, returning zero.
1331 * This behaviour resulted in some people not noticing
1332 * that they got the argument order wrong. So let's be
1333 * nice and fail gracefully if buf is invalid and looks
1334 * more like a buflen (which is probably MAX_PATH). */
1335 SetLastError(ERROR_INVALID_PARAMETER);
1339 ret = GetCurrentDirectoryW(MAX_PATH, bufferW);
1344 SetLastError(ERROR_FILENAME_EXCED_RANGE);
1347 return copy_filename_WtoA( bufferW, buf, buflen );
1351 /***********************************************************************
1352 * SetCurrentDirectoryW (KERNEL32.@)
1354 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1356 UNICODE_STRING dirW;
1359 RtlInitUnicodeString( &dirW, dir );
1360 status = RtlSetCurrentDirectory_U( &dirW );
1361 if (status != STATUS_SUCCESS)
1363 SetLastError( RtlNtStatusToDosError(status) );
1370 /***********************************************************************
1371 * SetCurrentDirectoryA (KERNEL32.@)
1373 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1377 if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1378 return SetCurrentDirectoryW( dirW );
1382 /***********************************************************************
1383 * GetWindowsDirectoryW (KERNEL32.@)
1385 * See comment for GetWindowsDirectoryA.
1387 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1389 UINT len = strlenW( DIR_Windows ) + 1;
1390 if (path && count >= len)
1392 strcpyW( path, DIR_Windows );
1399 /***********************************************************************
1400 * GetWindowsDirectoryA (KERNEL32.@)
1403 * If buffer is large enough to hold full path and terminating '\0' character
1404 * function copies path to buffer and returns length of the path without '\0'.
1405 * Otherwise function returns required size including '\0' character and
1406 * does not touch the buffer.
1408 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1410 return copy_filename_WtoA( DIR_Windows, path, count );
1414 /***********************************************************************
1415 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
1417 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1419 return GetWindowsDirectoryA( path, count );
1423 /***********************************************************************
1424 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
1426 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1428 return GetWindowsDirectoryW( path, count );
1432 /***********************************************************************
1433 * GetSystemDirectoryW (KERNEL32.@)
1435 * See comment for GetWindowsDirectoryA.
1437 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1439 UINT len = strlenW( DIR_System ) + 1;
1440 if (path && count >= len)
1442 strcpyW( path, DIR_System );
1449 /***********************************************************************
1450 * GetSystemDirectoryA (KERNEL32.@)
1452 * See comment for GetWindowsDirectoryA.
1454 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1456 return copy_filename_WtoA( DIR_System, path, count );
1460 /***********************************************************************
1461 * GetSystemWow64DirectoryW (KERNEL32.@)
1464 * - On Win32 we should returns ERROR_CALL_NOT_IMPLEMENTED
1465 * - On Win64 we should returns the SysWow64 (system64) directory
1467 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR lpBuffer, UINT uSize )
1469 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1474 /***********************************************************************
1475 * GetSystemWow64DirectoryA (KERNEL32.@)
1477 * See comment for GetWindowsWow64DirectoryW.
1479 UINT WINAPI GetSystemWow64DirectoryA( LPSTR lpBuffer, UINT uSize )
1481 SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1486 /***********************************************************************
1487 * wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1489 * Return the full Unix file name for a given path.
1490 * Returned buffer must be freed by caller.
1492 char *wine_get_unix_file_name( LPCWSTR dosW )
1494 UNICODE_STRING nt_name;
1495 ANSI_STRING unix_name;
1498 if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1499 status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1500 RtlFreeUnicodeString( &nt_name );
1501 if (status && status != STATUS_NO_SUCH_FILE)
1503 SetLastError( RtlNtStatusToDosError( status ) );
1506 return unix_name.Buffer;
1510 /***********************************************************************
1511 * wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1513 * Return the full DOS file name for a given Unix path.
1514 * Returned buffer must be freed by caller.
1516 WCHAR *wine_get_dos_file_name( LPCSTR str )
1518 UNICODE_STRING nt_name;
1519 ANSI_STRING unix_name;
1523 RtlInitAnsiString( &unix_name, str );
1524 status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1527 SetLastError( RtlNtStatusToDosError( status ) );
1530 /* get rid of the \??\ prefix */
1531 /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1532 len = nt_name.Length - 4 * sizeof(WCHAR);
1533 memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1534 nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1535 return nt_name.Buffer;