Do not check for non NULL pointer before HeapFree'ing it. It's
[wine] / dlls / kernel / path.c
1 /*
2  * File handling functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 1996, 2004 Alexandre Julliard
6  * Copyright 2003 Eric Pouech
7  *
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.
12  *
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.
17  *
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
21  *
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdarg.h>
30
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
33 #include "winerror.h"
34 #include "ntstatus.h"
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winreg.h"
38 #include "winternl.h"
39
40 #include "kernel_private.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(file);
45
46 #define MAX_PATHNAME_LEN        1024
47
48
49 /* check if a file name is for an executable file (.exe or .com) */
50 inline static BOOL is_executable( const WCHAR *name )
51 {
52     static const WCHAR exeW[] = {'.','e','x','e',0};
53     static const WCHAR comW[] = {'.','c','o','m',0};
54     int len = strlenW(name);
55
56     if (len < 4) return FALSE;
57     return (!strcmpiW( name + len - 4, exeW ) || !strcmpiW( name + len - 4, comW ));
58 }
59
60 /***********************************************************************
61  *           copy_filename_WtoA
62  *
63  * copy a file name back to OEM/Ansi, but only if the buffer is large enough
64  */
65 static DWORD copy_filename_WtoA( LPCWSTR nameW, LPSTR buffer, DWORD len )
66 {
67     UNICODE_STRING strW;
68     DWORD ret;
69     BOOL is_ansi = AreFileApisANSI();
70
71     RtlInitUnicodeString( &strW, nameW );
72
73     ret = is_ansi ? RtlUnicodeStringToAnsiSize(&strW) : RtlUnicodeStringToOemSize(&strW);
74     if (buffer && ret <= len)
75     {
76         ANSI_STRING str;
77
78         str.Buffer = buffer;
79         str.MaximumLength = len;
80         if (is_ansi)
81             RtlUnicodeStringToAnsiString( &str, &strW, FALSE );
82         else
83             RtlUnicodeStringToOemString( &str, &strW, FALSE );
84         ret = str.Length;  /* length without terminating 0 */
85     }
86     return ret;
87 }
88
89 /***********************************************************************
90  *           add_boot_rename_entry
91  *
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 registrykey 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
111  *
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
118  *
119  */
120 static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
121 {
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 );
131
132     OBJECT_ATTRIBUTES attr;
133     UNICODE_STRING nameW, source_name, dest_name;
134     KEY_VALUE_PARTIAL_INFORMATION *info;
135     BOOL rc = FALSE;
136     HKEY Reboot = 0;
137     DWORD len1, len2;
138     DWORD DataSize = 0;
139     BYTE *Buffer = NULL;
140     WCHAR *p;
141
142     if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
143     {
144         SetLastError( ERROR_PATH_NOT_FOUND );
145         return FALSE;
146     }
147     dest_name.Buffer = NULL;
148     if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
149     {
150         RtlFreeUnicodeString( &source_name );
151         SetLastError( ERROR_PATH_NOT_FOUND );
152         return FALSE;
153     }
154
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 );
162
163     if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
164     {
165         WARN("Error creating key for reboot managment [%s]\n",
166              "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
167         RtlFreeUnicodeString( &source_name );
168         RtlFreeUnicodeString( &dest_name );
169         return FALSE;
170     }
171
172     len1 = source_name.Length + sizeof(WCHAR);
173     if (dest)
174     {
175         len2 = dest_name.Length + sizeof(WCHAR);
176         if (flags & MOVEFILE_REPLACE_EXISTING)
177             len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
178     }
179     else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
180
181     RtlInitUnicodeString( &nameW, ValueName );
182
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_OVERFLOW)
186     {
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) */
194     }
195     else
196     {
197         DataSize = info_size;
198         if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
199             goto Quit;
200     }
201
202     memcpy( Buffer + DataSize, source_name.Buffer, len1 );
203     DataSize += len1;
204     p = (WCHAR *)(Buffer + DataSize);
205     if (dest)
206     {
207         if (flags & MOVEFILE_REPLACE_EXISTING)
208             *p++ = '!';
209         memcpy( p, dest_name.Buffer, len2 );
210         DataSize += len2;
211     }
212     else
213     {
214         *p = 0;
215         DataSize += sizeof(WCHAR);
216     }
217
218     /* add final null */
219     p = (WCHAR *)(Buffer + DataSize);
220     *p = 0;
221     DataSize += sizeof(WCHAR);
222
223     rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
224
225  Quit:
226     RtlFreeUnicodeString( &source_name );
227     RtlFreeUnicodeString( &dest_name );
228     if (Reboot) NtClose(Reboot);
229     HeapFree( GetProcessHeap(), 0, Buffer );
230     return(rc);
231 }
232
233
234 /***********************************************************************
235  *           GetFullPathNameW   (KERNEL32.@)
236  * NOTES
237  *   if the path closed with '\', *lastpart is 0
238  */
239 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
240                                LPWSTR *lastpart )
241 {
242     return RtlGetFullPathName_U(name, len * sizeof(WCHAR), buffer, lastpart) / sizeof(WCHAR);
243 }
244
245 /***********************************************************************
246  *           GetFullPathNameA   (KERNEL32.@)
247  * NOTES
248  *   if the path closed with '\', *lastpart is 0
249  */
250 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
251                                LPSTR *lastpart )
252 {
253     WCHAR *nameW;
254     WCHAR bufferW[MAX_PATH];
255     DWORD ret;
256
257     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
258
259     ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, NULL);
260
261     if (!ret) return 0;
262     if (ret > MAX_PATH)
263     {
264         SetLastError(ERROR_FILENAME_EXCED_RANGE);
265         return 0;
266     }
267     ret = copy_filename_WtoA( bufferW, buffer, len );
268     if (ret < len && lastpart)
269     {
270         LPSTR p = buffer + strlen(buffer) - 1;
271
272         if (*p != '\\')
273         {
274             while ((p > buffer + 2) && (*p != '\\')) p--;
275             *lastpart = p + 1;
276         }
277         else *lastpart = NULL;
278     }
279     return ret;
280 }
281
282
283 /***********************************************************************
284  *           GetLongPathNameW   (KERNEL32.@)
285  *
286  * NOTES
287  *  observed (Win2000):
288  *  shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
289  *  shortpath="":   LastError=ERROR_PATH_NOT_FOUND, ret=0
290  */
291 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
292 {
293     WCHAR               tmplongpath[MAX_PATHNAME_LEN];
294     LPCWSTR             p;
295     DWORD               sp = 0, lp = 0;
296     DWORD               tmplen;
297     BOOL                unixabsolute = (shortpath[0] == '/');
298     WIN32_FIND_DATAW    wfd;
299     HANDLE              goit;
300
301     if (!shortpath)
302     {
303         SetLastError(ERROR_INVALID_PARAMETER);
304         return 0;
305     }
306     if (!shortpath[0])
307     {
308         SetLastError(ERROR_PATH_NOT_FOUND);
309         return 0;
310     }
311
312     TRACE("%s,%p,%ld\n", debugstr_w(shortpath), longpath, longlen);
313
314     if (shortpath[0] == '\\' && shortpath[1] == '\\')
315     {
316         ERR("UNC pathname %s\n", debugstr_w(shortpath));
317         lstrcpynW( longpath, shortpath, longlen );
318         return strlenW(longpath);
319     }
320
321     /* check for drive letter */
322     if (!unixabsolute && shortpath[1] == ':' )
323     {
324         tmplongpath[0] = shortpath[0];
325         tmplongpath[1] = ':';
326         lp = sp = 2;
327     }
328
329     while (shortpath[sp])
330     {
331         /* check for path delimiters and reproduce them */
332         if (shortpath[sp] == '\\' || shortpath[sp] == '/')
333         {
334             if (!lp || tmplongpath[lp-1] != '\\')
335             {
336                 /* strip double "\\" */
337                 tmplongpath[lp++] = '\\';
338             }
339             tmplongpath[lp] = 0; /* terminate string */
340             sp++;
341             continue;
342         }
343
344         p = shortpath + sp;
345         if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
346         {
347             tmplongpath[lp++] = *p++;
348             tmplongpath[lp++] = *p++;
349         }
350         for (; *p && *p != '/' && *p != '\\'; p++);
351         tmplen = p - (shortpath + sp);
352         lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
353         /* Check if the file exists and use the existing file name */
354         goit = FindFirstFileW(tmplongpath, &wfd);
355         if (goit == INVALID_HANDLE_VALUE)
356         {
357             TRACE("not found %s!\n", debugstr_w(tmplongpath));
358             SetLastError ( ERROR_FILE_NOT_FOUND );
359             return 0;
360         }
361         FindClose(goit);
362         strcpyW(tmplongpath + lp, wfd.cFileName);
363         lp += strlenW(tmplongpath + lp);
364         sp += tmplen;
365     }
366     tmplen = strlenW(shortpath) - 1;
367     if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
368         (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
369         tmplongpath[lp++] = shortpath[tmplen];
370     tmplongpath[lp] = 0;
371
372     tmplen = strlenW(tmplongpath) + 1;
373     if (tmplen <= longlen)
374     {
375         strcpyW(longpath, tmplongpath);
376         TRACE("returning %s\n", debugstr_w(longpath));
377         tmplen--; /* length without 0 */
378     }
379
380     return tmplen;
381 }
382
383 /***********************************************************************
384  *           GetLongPathNameA   (KERNEL32.@)
385  */
386 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
387 {
388     WCHAR *shortpathW;
389     WCHAR longpathW[MAX_PATH];
390     DWORD ret;
391
392     TRACE("%s\n", debugstr_a(shortpath));
393
394     if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
395
396     ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
397
398     if (!ret) return 0;
399     if (ret > MAX_PATH)
400     {
401         SetLastError(ERROR_FILENAME_EXCED_RANGE);
402         return 0;
403     }
404     return copy_filename_WtoA( longpathW, longpath, longlen );
405 }
406
407
408 /***********************************************************************
409  *           GetShortPathNameW   (KERNEL32.@)
410  *
411  * NOTES
412  *  observed:
413  *  longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
414  *  longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
415  *
416  * more observations ( with NT 3.51 (WinDD) ):
417  * longpath <= 8.3 -> just copy longpath to shortpath
418  * longpath > 8.3  ->
419  *             a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
420  *             b) file does exist     -> set the short filename.
421  * - trailing slashes are reproduced in the short name, even if the
422  *   file is not a directory
423  * - the absolute/relative path of the short name is reproduced like found
424  *   in the long name
425  * - longpath and shortpath may have the same address
426  * Peter Ganten, 1999
427  */
428 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
429 {
430     WCHAR               tmpshortpath[MAX_PATHNAME_LEN];
431     LPCWSTR             p;
432     DWORD               sp = 0, lp = 0;
433     DWORD               tmplen;
434     BOOL                unixabsolute = (longpath[0] == '/');
435     WIN32_FIND_DATAW    wfd;
436     HANDLE              goit;
437     UNICODE_STRING      ustr;
438     WCHAR               ustr_buf[8+1+3+1];
439
440     TRACE("%s\n", debugstr_w(longpath));
441
442     if (!longpath)
443     {
444         SetLastError(ERROR_INVALID_PARAMETER);
445         return 0;
446     }
447     if (!longpath[0])
448     {
449         SetLastError(ERROR_BAD_PATHNAME);
450         return 0;
451     }
452
453     /* check for drive letter */
454     if (!unixabsolute && longpath[1] == ':' )
455     {
456         tmpshortpath[0] = longpath[0];
457         tmpshortpath[1] = ':';
458         sp = lp = 2;
459     }
460
461     ustr.Buffer = ustr_buf;
462     ustr.Length = 0;
463     ustr.MaximumLength = sizeof(ustr_buf);
464
465     while (longpath[lp])
466     {
467         /* check for path delimiters and reproduce them */
468         if (longpath[lp] == '\\' || longpath[lp] == '/')
469         {
470             if (!sp || tmpshortpath[sp-1] != '\\')
471             {
472                 /* strip double "\\" */
473                 tmpshortpath[sp] = '\\';
474                 sp++;
475             }
476             tmpshortpath[sp] = 0; /* terminate string */
477             lp++;
478             continue;
479         }
480
481         for (p = longpath + lp; *p && *p != '/' && *p != '\\'; p++);
482         tmplen = p - (longpath + lp);
483         lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
484         /* Check, if the current element is a valid dos name */
485         if (tmplen <= 8+1+3+1)
486         {
487             BOOLEAN spaces;
488             memcpy(ustr_buf, longpath + lp, tmplen * sizeof(WCHAR));
489             ustr_buf[tmplen] = '\0';
490             ustr.Length = tmplen * sizeof(WCHAR);
491             if (RtlIsNameLegalDOS8Dot3(&ustr, NULL, &spaces) && !spaces)
492             {
493                 sp += tmplen;
494                 lp += tmplen;
495                 continue;
496             }
497         }
498
499         /* Check if the file exists and use the existing short file name */
500         goit = FindFirstFileW(tmpshortpath, &wfd);
501         if (goit == INVALID_HANDLE_VALUE) goto notfound;
502         FindClose(goit);
503         strcpyW(tmpshortpath + sp, wfd.cAlternateFileName);
504         sp += strlenW(tmpshortpath + sp);
505         lp += tmplen;
506     }
507     tmpshortpath[sp] = 0;
508
509     tmplen = strlenW(tmpshortpath) + 1;
510     if (tmplen <= shortlen)
511     {
512         strcpyW(shortpath, tmpshortpath);
513         TRACE("returning %s\n", debugstr_w(shortpath));
514         tmplen--; /* length without 0 */
515     }
516
517     return tmplen;
518
519  notfound:
520     TRACE("not found!\n" );
521     SetLastError ( ERROR_FILE_NOT_FOUND );
522     return 0;
523 }
524
525 /***********************************************************************
526  *           GetShortPathNameA   (KERNEL32.@)
527  */
528 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
529 {
530     WCHAR *longpathW;
531     WCHAR shortpathW[MAX_PATH];
532     DWORD ret;
533
534     TRACE("%s\n", debugstr_a(longpath));
535
536     if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
537
538     ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
539
540     if (!ret) return 0;
541     if (ret > MAX_PATH)
542     {
543         SetLastError(ERROR_FILENAME_EXCED_RANGE);
544         return 0;
545     }
546     return copy_filename_WtoA( shortpathW, shortpath, shortlen );
547 }
548
549
550 /***********************************************************************
551  *           GetTempPathA   (KERNEL32.@)
552  */
553 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
554 {
555     WCHAR pathW[MAX_PATH];
556     UINT ret;
557
558     ret = GetTempPathW(MAX_PATH, pathW);
559
560     if (!ret)
561         return 0;
562
563     if (ret > MAX_PATH)
564     {
565         SetLastError(ERROR_FILENAME_EXCED_RANGE);
566         return 0;
567     }
568     return copy_filename_WtoA( pathW, path, count );
569 }
570
571
572 /***********************************************************************
573  *           GetTempPathW   (KERNEL32.@)
574  */
575 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
576 {
577     static const WCHAR tmp[]  = { 'T', 'M', 'P', 0 };
578     static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
579     WCHAR tmp_path[MAX_PATH];
580     UINT ret;
581
582     TRACE("%lu,%p\n", count, path);
583
584     if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )))
585         if (!(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )))
586             if (!(ret = GetCurrentDirectoryW( MAX_PATH, tmp_path )))
587                 return 0;
588
589     if (ret > MAX_PATH)
590     {
591         SetLastError(ERROR_FILENAME_EXCED_RANGE);
592         return 0;
593     }
594
595     ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
596     if (!ret) return 0;
597
598     if (ret > MAX_PATH - 2)
599     {
600         SetLastError(ERROR_FILENAME_EXCED_RANGE);
601         return 0;
602     }
603
604     if (tmp_path[ret-1] != '\\')
605     {
606         tmp_path[ret++] = '\\';
607         tmp_path[ret]   = '\0';
608     }
609
610     ret++; /* add space for terminating 0 */
611
612     if (count)
613     {
614         lstrcpynW(path, tmp_path, count);
615         if (count >= ret)
616             ret--; /* return length without 0 */
617         else if (count < 4)
618             path[0] = 0; /* avoid returning ambiguous "X:" */
619     }
620
621     TRACE("returning %u, %s\n", ret, debugstr_w(path));
622     return ret;
623 }
624
625
626 /***********************************************************************
627  *           GetTempFileNameA   (KERNEL32.@)
628  */
629 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
630 {
631     WCHAR *pathW, *prefixW = NULL;
632     WCHAR bufferW[MAX_PATH];
633     UINT ret;
634
635     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
636     if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
637
638     ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
639     if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
640
641     HeapFree( GetProcessHeap(), 0, prefixW );
642     return ret;
643 }
644
645 /***********************************************************************
646  *           GetTempFileNameW   (KERNEL32.@)
647  */
648 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
649 {
650     static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
651
652     int i;
653     LPWSTR p;
654
655     if ( !path || !prefix || !buffer )
656     {
657         SetLastError( ERROR_INVALID_PARAMETER );
658         return 0;
659     }
660
661     strcpyW( buffer, path );
662     p = buffer + strlenW(buffer);
663
664     /* add a \, if there isn't one  */
665     if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
666
667     for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
668
669     unique &= 0xffff;
670
671     if (unique) sprintfW( p, formatW, unique );
672     else
673     {
674         /* get a "random" unique number and try to create the file */
675         HANDLE handle;
676         UINT num = GetTickCount() & 0xffff;
677
678         if (!num) num = 1;
679         unique = num;
680         do
681         {
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 );
689                 break;
690             }
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);
696     }
697
698     TRACE("returning %s\n", debugstr_w(buffer) );
699     return unique;
700 }
701
702
703 /***********************************************************************
704  *           contains_pathW
705  *
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 ../
708  */
709 inline static BOOL contains_pathW (LPCWSTR name)
710 {
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] == '\\'));
715 }
716
717
718 /***********************************************************************
719  * SearchPathW [KERNEL32.@]
720  *
721  * Searches for a specified file in the search path.
722  *
723  * PARAMS
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 '\')
734  *
735  * RETURNS
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.
740  *    Failure: Zero
741  *
742  * NOTES
743  *    If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
744  *    (tested on NT 4.0)
745  */
746 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
747                           LPWSTR buffer, LPWSTR *lastpart )
748 {
749     DWORD ret = 0;
750
751     /* If the name contains an explicit path, ignore the path */
752
753     if (contains_pathW(name))
754     {
755         /* try first without extension */
756         if (RtlDoesFileExists_U( name ))
757             return GetFullPathNameW( name, buflen, buffer, lastpart );
758
759         if (ext)
760         {
761             LPCWSTR p = strrchrW( name, '.' );
762             if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
763                 ext = NULL;  /* Ignore the specified extension */
764         }
765
766         /* Allocate a buffer for the file name and extension */
767         if (ext)
768         {
769             LPWSTR tmp;
770             DWORD len = strlenW(name) + strlenW(ext);
771
772             if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
773             {
774                 SetLastError( ERROR_OUTOFMEMORY );
775                 return 0;
776             }
777             strcpyW( tmp, name );
778             strcatW( tmp, ext );
779             if (RtlDoesFileExists_U( tmp ))
780                 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
781             HeapFree( GetProcessHeap(), 0, tmp );
782         }
783     }
784     else if (path && path[0])  /* search in the specified path */
785     {
786         ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
787                                   buffer, lastpart ) / sizeof(WCHAR);
788     }
789     else  /* search in the default path */
790     {
791         WCHAR *dll_path = MODULE_get_dll_load_path( NULL );
792
793         if (dll_path)
794         {
795             ret = RtlDosSearchPath_U( dll_path, name, ext, buflen * sizeof(WCHAR),
796                                       buffer, lastpart ) / sizeof(WCHAR);
797             HeapFree( GetProcessHeap(), 0, dll_path );
798         }
799         else
800         {
801             SetLastError( ERROR_OUTOFMEMORY );
802             return 0;
803         }
804     }
805
806     if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
807     else TRACE( "found %s\n", debugstr_w(buffer) );
808     return ret;
809 }
810
811
812 /***********************************************************************
813  *           SearchPathA   (KERNEL32.@)
814  */
815 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
816                           DWORD buflen, LPSTR buffer, LPSTR *lastpart )
817 {
818     WCHAR *pathW, *nameW = NULL, *extW = NULL;
819     WCHAR bufferW[MAX_PATH];
820     DWORD ret;
821
822     if (name && !(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
823     if (!(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
824     if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
825     {
826         HeapFree( GetProcessHeap(), 0, pathW );
827         return 0;
828     }
829
830     ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
831
832     HeapFree( GetProcessHeap(), 0, pathW );
833     HeapFree( GetProcessHeap(), 0, extW );
834
835     if (!ret) return 0;
836     if (ret > MAX_PATH)
837     {
838         SetLastError(ERROR_FILENAME_EXCED_RANGE);
839         return 0;
840     }
841     ret = copy_filename_WtoA( bufferW, buffer, buflen );
842     if (buflen > ret && lastpart)
843         *lastpart = strrchr(buffer, '\\') + 1;
844     return ret;
845 }
846
847
848 /**************************************************************************
849  *           CopyFileW   (KERNEL32.@)
850  */
851 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
852 {
853     HANDLE h1, h2;
854     BY_HANDLE_FILE_INFORMATION info;
855     DWORD count;
856     BOOL ret = FALSE;
857     char buffer[2048];
858
859     if (!source || !dest)
860     {
861         SetLastError(ERROR_INVALID_PARAMETER);
862         return FALSE;
863     }
864
865     TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
866
867     if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
868                      NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
869     {
870         WARN("Unable to open source %s\n", debugstr_w(source));
871         return FALSE;
872     }
873
874     if (!GetFileInformationByHandle( h1, &info ))
875     {
876         WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
877         CloseHandle( h1 );
878         return FALSE;
879     }
880
881     if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
882                              fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
883                              info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
884     {
885         WARN("Unable to open dest %s\n", debugstr_w(dest));
886         CloseHandle( h1 );
887         return FALSE;
888     }
889
890     while (ReadFile( h1, buffer, sizeof(buffer), &count, NULL ) && count)
891     {
892         char *p = buffer;
893         while (count != 0)
894         {
895             DWORD res;
896             if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
897             p += res;
898             count -= res;
899         }
900     }
901     ret =  TRUE;
902 done:
903     CloseHandle( h1 );
904     CloseHandle( h2 );
905     return ret;
906 }
907
908
909 /**************************************************************************
910  *           CopyFileA   (KERNEL32.@)
911  */
912 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
913 {
914     WCHAR *sourceW, *destW;
915     BOOL ret;
916
917     if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
918     if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
919
920     ret = CopyFileW( sourceW, destW, fail_if_exists );
921
922     HeapFree( GetProcessHeap(), 0, destW );
923     return ret;
924 }
925
926
927 /**************************************************************************
928  *           CopyFileExW   (KERNEL32.@)
929  *
930  * This implementation ignores most of the extra parameters passed-in into
931  * the "ex" version of the method and calls the CopyFile method.
932  * It will have to be fixed eventually.
933  */
934 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
935                         LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
936                         LPBOOL cancelFlagPointer, DWORD copyFlags)
937 {
938     /*
939      * Interpret the only flag that CopyFile can interpret.
940      */
941     return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
942 }
943
944
945 /**************************************************************************
946  *           CopyFileExA   (KERNEL32.@)
947  */
948 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
949                         LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
950                         LPBOOL cancelFlagPointer, DWORD copyFlags)
951 {
952     WCHAR *sourceW, *destW;
953     BOOL ret;
954
955     /* can't use the TEB buffer since we may have a callback routine */
956     if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
957     if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
958     {
959         HeapFree( GetProcessHeap(), 0, sourceW );
960         return FALSE;
961     }
962     ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
963                       cancelFlagPointer, copyFlags);
964     HeapFree( GetProcessHeap(), 0, sourceW );
965     HeapFree( GetProcessHeap(), 0, destW );
966     return ret;
967 }
968
969
970 /**************************************************************************
971  *           MoveFileExW   (KERNEL32.@)
972  */
973 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
974 {
975     FILE_BASIC_INFORMATION info;
976     UNICODE_STRING nt_name;
977     OBJECT_ATTRIBUTES attr;
978     IO_STATUS_BLOCK io;
979     NTSTATUS status;
980     HANDLE source_handle = 0, dest_handle;
981     ANSI_STRING source_unix, dest_unix;
982
983     TRACE("(%s,%s,%04lx)\n", debugstr_w(source), debugstr_w(dest), flag);
984
985     if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
986         return add_boot_rename_entry( source, dest, flag );
987
988     if (!dest)
989         return DeleteFileW( source );
990
991     /* check if we are allowed to rename the source */
992
993     if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
994     {
995         SetLastError( ERROR_PATH_NOT_FOUND );
996         return FALSE;
997     }
998     source_unix.Buffer = NULL;
999     dest_unix.Buffer = NULL;
1000     attr.Length = sizeof(attr);
1001     attr.RootDirectory = 0;
1002     attr.Attributes = OBJ_CASE_INSENSITIVE;
1003     attr.ObjectName = &nt_name;
1004     attr.SecurityDescriptor = NULL;
1005     attr.SecurityQualityOfService = NULL;
1006
1007     status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1008     if (status == STATUS_SUCCESS)
1009         status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1010     RtlFreeUnicodeString( &nt_name );
1011     if (status != STATUS_SUCCESS)
1012     {
1013         SetLastError( RtlNtStatusToDosError(status) );
1014         goto error;
1015     }
1016     status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1017     if (status != STATUS_SUCCESS)
1018     {
1019         SetLastError( RtlNtStatusToDosError(status) );
1020         goto error;
1021     }
1022
1023     if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1024     {
1025         if (flag & MOVEFILE_REPLACE_EXISTING)  /* cannot replace directory */
1026         {
1027             SetLastError( ERROR_INVALID_PARAMETER );
1028             goto error;
1029         }
1030     }
1031
1032     /* we must have write access to the destination, and it must */
1033     /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1034
1035     if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1036     {
1037         SetLastError( ERROR_PATH_NOT_FOUND );
1038         goto error;
1039     }
1040     status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1041                          FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1042     if (status == STATUS_SUCCESS)
1043     {
1044         NtClose( dest_handle );
1045         if (!(flag & MOVEFILE_REPLACE_EXISTING))
1046         {
1047             SetLastError( ERROR_ALREADY_EXISTS );
1048             RtlFreeUnicodeString( &nt_name );
1049             goto error;
1050         }
1051     }
1052     else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1053     {
1054         SetLastError( RtlNtStatusToDosError(status) );
1055         RtlFreeUnicodeString( &nt_name );
1056         goto error;
1057     }
1058
1059     status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1060     RtlFreeUnicodeString( &nt_name );
1061     if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1062     {
1063         SetLastError( RtlNtStatusToDosError(status) );
1064         goto error;
1065     }
1066
1067     /* now perform the rename */
1068
1069     if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1070     {
1071         if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1072         {
1073             NtClose( source_handle );
1074             RtlFreeAnsiString( &source_unix );
1075             RtlFreeAnsiString( &dest_unix );
1076             return (CopyFileW( source, dest, TRUE ) && DeleteFileW( source ));
1077         }
1078         FILE_SetDosError();
1079         /* if we created the destination, remove it */
1080         if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1081         goto error;
1082     }
1083
1084     /* fixup executable permissions */
1085
1086     if (is_executable( source ) != is_executable( dest ))
1087     {
1088         struct stat fstat;
1089         if (stat( dest_unix.Buffer, &fstat ) != -1)
1090         {
1091             if (is_executable( dest ))
1092                 /* set executable bit where read bit is set */
1093                 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1094             else
1095                 fstat.st_mode &= ~0111;
1096             chmod( dest_unix.Buffer, fstat.st_mode );
1097         }
1098     }
1099
1100     NtClose( source_handle );
1101     RtlFreeAnsiString( &source_unix );
1102     RtlFreeAnsiString( &dest_unix );
1103     return TRUE;
1104
1105 error:
1106     if (source_handle) NtClose( source_handle );
1107     RtlFreeAnsiString( &source_unix );
1108     RtlFreeAnsiString( &dest_unix );
1109     return FALSE;
1110 }
1111
1112 /**************************************************************************
1113  *           MoveFileExA   (KERNEL32.@)
1114  */
1115 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1116 {
1117     WCHAR *sourceW, *destW;
1118     BOOL ret;
1119
1120     if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1121     if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1122     ret = MoveFileExW( sourceW, destW, flag );
1123     HeapFree( GetProcessHeap(), 0, destW );
1124     return ret;
1125 }
1126
1127
1128 /**************************************************************************
1129  *           MoveFileW   (KERNEL32.@)
1130  *
1131  *  Move file or directory
1132  */
1133 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1134 {
1135     return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1136 }
1137
1138
1139 /**************************************************************************
1140  *           MoveFileA   (KERNEL32.@)
1141  */
1142 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1143 {
1144     return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1145 }
1146
1147
1148 /***********************************************************************
1149  *           CreateDirectoryW   (KERNEL32.@)
1150  * RETURNS:
1151  *      TRUE : success
1152  *      FALSE : failure
1153  *              ERROR_DISK_FULL:        on full disk
1154  *              ERROR_ALREADY_EXISTS:   if directory name exists (even as file)
1155  *              ERROR_ACCESS_DENIED:    on permission problems
1156  *              ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1157  */
1158 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1159 {
1160     OBJECT_ATTRIBUTES attr;
1161     UNICODE_STRING nt_name;
1162     IO_STATUS_BLOCK io;
1163     NTSTATUS status;
1164     HANDLE handle;
1165     BOOL ret = FALSE;
1166
1167     TRACE( "%s\n", debugstr_w(path) );
1168
1169     if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1170     {
1171         SetLastError( ERROR_PATH_NOT_FOUND );
1172         return FALSE;
1173     }
1174     attr.Length = sizeof(attr);
1175     attr.RootDirectory = 0;
1176     attr.Attributes = OBJ_CASE_INSENSITIVE;
1177     attr.ObjectName = &nt_name;
1178     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1179     attr.SecurityQualityOfService = NULL;
1180
1181     status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1182                            FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1183                            FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1184
1185     if (status == STATUS_SUCCESS)
1186     {
1187         NtClose( handle );
1188         ret = TRUE;
1189     }
1190     else SetLastError( RtlNtStatusToDosError(status) );
1191
1192     RtlFreeUnicodeString( &nt_name );
1193     return ret;
1194 }
1195
1196
1197 /***********************************************************************
1198  *           CreateDirectoryA   (KERNEL32.@)
1199  */
1200 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1201 {
1202     WCHAR *pathW;
1203
1204     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1205     return CreateDirectoryW( pathW, sa );
1206 }
1207
1208
1209 /***********************************************************************
1210  *           CreateDirectoryExA   (KERNEL32.@)
1211  */
1212 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1213 {
1214     WCHAR *pathW, *templateW = NULL;
1215     BOOL ret;
1216
1217     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1218     if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1219
1220     ret = CreateDirectoryExW( templateW, pathW, sa );
1221     HeapFree( GetProcessHeap(), 0, templateW );
1222     return ret;
1223 }
1224
1225
1226 /***********************************************************************
1227  *           CreateDirectoryExW   (KERNEL32.@)
1228  */
1229 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1230 {
1231     return CreateDirectoryW( path, sa );
1232 }
1233
1234
1235 /***********************************************************************
1236  *           RemoveDirectoryW   (KERNEL32.@)
1237  */
1238 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1239 {
1240     OBJECT_ATTRIBUTES attr;
1241     UNICODE_STRING nt_name;
1242     ANSI_STRING unix_name;
1243     IO_STATUS_BLOCK io;
1244     NTSTATUS status;
1245     HANDLE handle;
1246     BOOL ret = FALSE;
1247
1248     TRACE( "%s\n", debugstr_w(path) );
1249
1250     if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1251     {
1252         SetLastError( ERROR_PATH_NOT_FOUND );
1253         return FALSE;
1254     }
1255     attr.Length = sizeof(attr);
1256     attr.RootDirectory = 0;
1257     attr.Attributes = OBJ_CASE_INSENSITIVE;
1258     attr.ObjectName = &nt_name;
1259     attr.SecurityDescriptor = NULL;
1260     attr.SecurityQualityOfService = NULL;
1261
1262     status = NtOpenFile( &handle, GENERIC_READ, &attr, &io,
1263                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1264                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1265     if (status == STATUS_SUCCESS)
1266         status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1267     RtlFreeUnicodeString( &nt_name );
1268
1269     if (status != STATUS_SUCCESS)
1270     {
1271         SetLastError( RtlNtStatusToDosError(status) );
1272         return FALSE;
1273     }
1274
1275     if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1276     RtlFreeAnsiString( &unix_name );
1277     NtClose( handle );
1278     return ret;
1279 }
1280
1281
1282 /***********************************************************************
1283  *           RemoveDirectoryA   (KERNEL32.@)
1284  */
1285 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1286 {
1287     WCHAR *pathW;
1288
1289     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1290     return RemoveDirectoryW( pathW );
1291 }
1292
1293
1294 /***********************************************************************
1295  *           GetCurrentDirectoryW   (KERNEL32.@)
1296  */
1297 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1298 {
1299     return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1300 }
1301
1302
1303 /***********************************************************************
1304  *           GetCurrentDirectoryA   (KERNEL32.@)
1305  */
1306 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1307 {
1308     WCHAR bufferW[MAX_PATH];
1309     DWORD ret;
1310
1311     ret = GetCurrentDirectoryW(MAX_PATH, bufferW);
1312
1313     if (!ret) return 0;
1314     if (ret > MAX_PATH)
1315     {
1316         SetLastError(ERROR_FILENAME_EXCED_RANGE);
1317         return 0;
1318     }
1319     return copy_filename_WtoA( bufferW, buf, buflen );
1320 }
1321
1322
1323 /***********************************************************************
1324  *           SetCurrentDirectoryW   (KERNEL32.@)
1325  */
1326 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1327 {
1328     UNICODE_STRING dirW;
1329     NTSTATUS status;
1330
1331     RtlInitUnicodeString( &dirW, dir );
1332     status = RtlSetCurrentDirectory_U( &dirW );
1333     if (status != STATUS_SUCCESS)
1334     {
1335         SetLastError( RtlNtStatusToDosError(status) );
1336         return FALSE;
1337     }
1338     return TRUE;
1339 }
1340
1341
1342 /***********************************************************************
1343  *           SetCurrentDirectoryA   (KERNEL32.@)
1344  */
1345 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1346 {
1347     WCHAR *dirW;
1348
1349     if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1350     return SetCurrentDirectoryW( dirW );
1351 }
1352
1353
1354 /***********************************************************************
1355  *           GetWindowsDirectoryW   (KERNEL32.@)
1356  *
1357  * See comment for GetWindowsDirectoryA.
1358  */
1359 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1360 {
1361     UINT len = strlenW( DIR_Windows ) + 1;
1362     if (path && count >= len)
1363     {
1364         strcpyW( path, DIR_Windows );
1365         len--;
1366     }
1367     return len;
1368 }
1369
1370
1371 /***********************************************************************
1372  *           GetWindowsDirectoryA   (KERNEL32.@)
1373  *
1374  * Return value:
1375  * If buffer is large enough to hold full path and terminating '\0' character
1376  * function copies path to buffer and returns length of the path without '\0'.
1377  * Otherwise function returns required size including '\0' character and
1378  * does not touch the buffer.
1379  */
1380 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1381 {
1382     return copy_filename_WtoA( DIR_Windows, path, count );
1383 }
1384
1385
1386 /***********************************************************************
1387  *           GetSystemWindowsDirectoryA   (KERNEL32.@) W2K, TS4.0SP4
1388  */
1389 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1390 {
1391     return GetWindowsDirectoryA( path, count );
1392 }
1393
1394
1395 /***********************************************************************
1396  *           GetSystemWindowsDirectoryW   (KERNEL32.@) W2K, TS4.0SP4
1397  */
1398 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1399 {
1400     return GetWindowsDirectoryW( path, count );
1401 }
1402
1403
1404 /***********************************************************************
1405  *           GetSystemDirectoryW   (KERNEL32.@)
1406  *
1407  * See comment for GetWindowsDirectoryA.
1408  */
1409 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1410 {
1411     UINT len = strlenW( DIR_System ) + 1;
1412     if (path && count >= len)
1413     {
1414         strcpyW( path, DIR_System );
1415         len--;
1416     }
1417     return len;
1418 }
1419
1420
1421 /***********************************************************************
1422  *           GetSystemDirectoryA   (KERNEL32.@)
1423  *
1424  * See comment for GetWindowsDirectoryA.
1425  */
1426 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1427 {
1428     return copy_filename_WtoA( DIR_System, path, count );
1429 }
1430
1431
1432 /***********************************************************************
1433  *           GetSystemWow64DirectoryW   (KERNEL32.@)
1434  *
1435  * As seen on MSDN
1436  * - On Win32 we should returns ERROR_CALL_NOT_IMPLEMENTED
1437  * - On Win64 we should returns the SysWow64 (system64) directory
1438  */
1439 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR lpBuffer, UINT uSize )
1440 {
1441     SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1442     return 0;
1443 }
1444
1445
1446 /***********************************************************************
1447  *           GetSystemWow64DirectoryA   (KERNEL32.@)
1448  *
1449  * See comment for GetWindowsWow64DirectoryW.
1450  */
1451 UINT WINAPI GetSystemWow64DirectoryA( LPSTR lpBuffer, UINT uSize )
1452 {
1453     SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1454     return 0;
1455 }
1456
1457
1458 /***********************************************************************
1459  *           wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1460  *
1461  * Return the full Unix file name for a given path.
1462  * Returned buffer must be freed by caller.
1463  */
1464 char *wine_get_unix_file_name( LPCWSTR dosW )
1465 {
1466     UNICODE_STRING nt_name;
1467     ANSI_STRING unix_name;
1468     NTSTATUS status;
1469
1470     if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1471     status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1472     RtlFreeUnicodeString( &nt_name );
1473     if (status && status != STATUS_NO_SUCH_FILE) return NULL;
1474     return unix_name.Buffer;
1475 }