kernel32: Print an error instead of crashing in GetLongPathNameW if shortpath=0.
[wine] / dlls / kernel32 / 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winbase.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     HANDLE 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;
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     unixabsolute = (shortpath[0] == '/');
322
323     /* check for drive letter */
324     if (!unixabsolute && shortpath[1] == ':' )
325     {
326         tmplongpath[0] = shortpath[0];
327         tmplongpath[1] = ':';
328         lp = sp = 2;
329     }
330
331     while (shortpath[sp])
332     {
333         /* check for path delimiters and reproduce them */
334         if (shortpath[sp] == '\\' || shortpath[sp] == '/')
335         {
336             if (!lp || tmplongpath[lp-1] != '\\')
337             {
338                 /* strip double "\\" */
339                 tmplongpath[lp++] = '\\';
340             }
341             tmplongpath[lp] = 0; /* terminate string */
342             sp++;
343             continue;
344         }
345
346         p = shortpath + sp;
347         if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
348         {
349             tmplongpath[lp++] = *p++;
350             tmplongpath[lp++] = *p++;
351         }
352         for (; *p && *p != '/' && *p != '\\'; p++);
353         tmplen = p - (shortpath + sp);
354         lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
355         /* Check if the file exists and use the existing file name */
356         goit = FindFirstFileW(tmplongpath, &wfd);
357         if (goit == INVALID_HANDLE_VALUE)
358         {
359             TRACE("not found %s!\n", debugstr_w(tmplongpath));
360             SetLastError ( ERROR_FILE_NOT_FOUND );
361             return 0;
362         }
363         FindClose(goit);
364         strcpyW(tmplongpath + lp, wfd.cFileName);
365         lp += strlenW(tmplongpath + lp);
366         sp += tmplen;
367     }
368     tmplen = strlenW(shortpath) - 1;
369     if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
370         (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
371         tmplongpath[lp++] = shortpath[tmplen];
372     tmplongpath[lp] = 0;
373
374     tmplen = strlenW(tmplongpath) + 1;
375     if (tmplen <= longlen)
376     {
377         strcpyW(longpath, tmplongpath);
378         TRACE("returning %s\n", debugstr_w(longpath));
379         tmplen--; /* length without 0 */
380     }
381
382     return tmplen;
383 }
384
385 /***********************************************************************
386  *           GetLongPathNameA   (KERNEL32.@)
387  */
388 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
389 {
390     WCHAR *shortpathW;
391     WCHAR longpathW[MAX_PATH];
392     DWORD ret;
393
394     TRACE("%s\n", debugstr_a(shortpath));
395
396     if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
397
398     ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
399
400     if (!ret) return 0;
401     if (ret > MAX_PATH)
402     {
403         SetLastError(ERROR_FILENAME_EXCED_RANGE);
404         return 0;
405     }
406     return copy_filename_WtoA( longpathW, longpath, longlen );
407 }
408
409
410 /***********************************************************************
411  *           GetShortPathNameW   (KERNEL32.@)
412  *
413  * NOTES
414  *  observed:
415  *  longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
416  *  longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
417  *
418  * more observations ( with NT 3.51 (WinDD) ):
419  * longpath <= 8.3 -> just copy longpath to shortpath
420  * longpath > 8.3  ->
421  *             a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
422  *             b) file does exist     -> set the short filename.
423  * - trailing slashes are reproduced in the short name, even if the
424  *   file is not a directory
425  * - the absolute/relative path of the short name is reproduced like found
426  *   in the long name
427  * - longpath and shortpath may have the same address
428  * Peter Ganten, 1999
429  */
430 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
431 {
432     WCHAR               tmpshortpath[MAX_PATHNAME_LEN];
433     LPCWSTR             p;
434     DWORD               sp = 0, lp = 0;
435     DWORD               tmplen;
436     WIN32_FIND_DATAW    wfd;
437     HANDLE              goit;
438     UNICODE_STRING      ustr;
439     WCHAR               ustr_buf[8+1+3+1];
440
441     TRACE("%s\n", debugstr_w(longpath));
442
443     if (!longpath)
444     {
445         SetLastError(ERROR_INVALID_PARAMETER);
446         return 0;
447     }
448     if (!longpath[0])
449     {
450         SetLastError(ERROR_BAD_PATHNAME);
451         return 0;
452     }
453
454     /* check for drive letter */
455     if (longpath[0] != '/' && longpath[1] == ':' )
456     {
457         tmpshortpath[0] = longpath[0];
458         tmpshortpath[1] = ':';
459         sp = lp = 2;
460     }
461
462     ustr.Buffer = ustr_buf;
463     ustr.Length = 0;
464     ustr.MaximumLength = sizeof(ustr_buf);
465
466     while (longpath[lp])
467     {
468         /* check for path delimiters and reproduce them */
469         if (longpath[lp] == '\\' || longpath[lp] == '/')
470         {
471             if (!sp || tmpshortpath[sp-1] != '\\')
472             {
473                 /* strip double "\\" */
474                 tmpshortpath[sp] = '\\';
475                 sp++;
476             }
477             tmpshortpath[sp] = 0; /* terminate string */
478             lp++;
479             continue;
480         }
481
482         for (p = longpath + lp; *p && *p != '/' && *p != '\\'; p++);
483         tmplen = p - (longpath + lp);
484         lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
485         /* Check, if the current element is a valid dos name */
486         if (tmplen <= 8+1+3)
487         {
488             BOOLEAN spaces;
489             memcpy(ustr_buf, longpath + lp, tmplen * sizeof(WCHAR));
490             ustr_buf[tmplen] = '\0';
491             ustr.Length = tmplen * sizeof(WCHAR);
492             if (RtlIsNameLegalDOS8Dot3(&ustr, NULL, &spaces) && !spaces)
493             {
494                 sp += tmplen;
495                 lp += tmplen;
496                 continue;
497             }
498         }
499
500         /* Check if the file exists and use the existing short file name */
501         goit = FindFirstFileW(tmpshortpath, &wfd);
502         if (goit == INVALID_HANDLE_VALUE) goto notfound;
503         FindClose(goit);
504         strcpyW(tmpshortpath + sp, wfd.cAlternateFileName);
505         sp += strlenW(tmpshortpath + sp);
506         lp += tmplen;
507     }
508     tmpshortpath[sp] = 0;
509
510     tmplen = strlenW(tmpshortpath) + 1;
511     if (tmplen <= shortlen)
512     {
513         strcpyW(shortpath, tmpshortpath);
514         TRACE("returning %s\n", debugstr_w(shortpath));
515         tmplen--; /* length without 0 */
516     }
517
518     return tmplen;
519
520  notfound:
521     TRACE("not found!\n" );
522     SetLastError ( ERROR_FILE_NOT_FOUND );
523     return 0;
524 }
525
526 /***********************************************************************
527  *           GetShortPathNameA   (KERNEL32.@)
528  */
529 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
530 {
531     WCHAR *longpathW;
532     WCHAR shortpathW[MAX_PATH];
533     DWORD ret;
534
535     TRACE("%s\n", debugstr_a(longpath));
536
537     if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
538
539     ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
540
541     if (!ret) return 0;
542     if (ret > MAX_PATH)
543     {
544         SetLastError(ERROR_FILENAME_EXCED_RANGE);
545         return 0;
546     }
547     return copy_filename_WtoA( shortpathW, shortpath, shortlen );
548 }
549
550
551 /***********************************************************************
552  *           GetTempPathA   (KERNEL32.@)
553  */
554 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
555 {
556     WCHAR pathW[MAX_PATH];
557     UINT ret;
558
559     ret = GetTempPathW(MAX_PATH, pathW);
560
561     if (!ret)
562         return 0;
563
564     if (ret > MAX_PATH)
565     {
566         SetLastError(ERROR_FILENAME_EXCED_RANGE);
567         return 0;
568     }
569     return copy_filename_WtoA( pathW, path, count );
570 }
571
572
573 /***********************************************************************
574  *           GetTempPathW   (KERNEL32.@)
575  */
576 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
577 {
578     static const WCHAR tmp[]  = { 'T', 'M', 'P', 0 };
579     static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
580     WCHAR tmp_path[MAX_PATH];
581     UINT ret;
582
583     TRACE("%lu,%p\n", count, path);
584
585     if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )))
586         if (!(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )))
587             if (!(ret = GetCurrentDirectoryW( MAX_PATH, tmp_path )))
588                 return 0;
589
590     if (ret > MAX_PATH)
591     {
592         SetLastError(ERROR_FILENAME_EXCED_RANGE);
593         return 0;
594     }
595
596     ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
597     if (!ret) return 0;
598
599     if (ret > MAX_PATH - 2)
600     {
601         SetLastError(ERROR_FILENAME_EXCED_RANGE);
602         return 0;
603     }
604
605     if (tmp_path[ret-1] != '\\')
606     {
607         tmp_path[ret++] = '\\';
608         tmp_path[ret]   = '\0';
609     }
610
611     ret++; /* add space for terminating 0 */
612
613     if (count)
614     {
615         lstrcpynW(path, tmp_path, count);
616         if (count >= ret)
617             ret--; /* return length without 0 */
618         else if (count < 4)
619             path[0] = 0; /* avoid returning ambiguous "X:" */
620     }
621
622     TRACE("returning %u, %s\n", ret, debugstr_w(path));
623     return ret;
624 }
625
626
627 /***********************************************************************
628  *           GetTempFileNameA   (KERNEL32.@)
629  */
630 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
631 {
632     WCHAR *pathW, *prefixW = NULL;
633     WCHAR bufferW[MAX_PATH];
634     UINT ret;
635
636     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
637     if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
638
639     ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
640     if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
641
642     HeapFree( GetProcessHeap(), 0, prefixW );
643     return ret;
644 }
645
646 /***********************************************************************
647  *           GetTempFileNameW   (KERNEL32.@)
648  */
649 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
650 {
651     static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
652
653     int i;
654     LPWSTR p;
655
656     if ( !path || !buffer )
657     {
658         SetLastError( ERROR_INVALID_PARAMETER );
659         return 0;
660     }
661
662     strcpyW( buffer, path );
663     p = buffer + strlenW(buffer);
664
665     /* add a \, if there isn't one  */
666     if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
667
668     if (prefix)
669         for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
670
671     unique &= 0xffff;
672
673     if (unique) sprintfW( p, formatW, unique );
674     else
675     {
676         /* get a "random" unique number and try to create the file */
677         HANDLE handle;
678         UINT num = GetTickCount() & 0xffff;
679
680         if (!num) num = 1;
681         unique = num;
682         do
683         {
684             sprintfW( p, formatW, unique );
685             handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
686                                   CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
687             if (handle != INVALID_HANDLE_VALUE)
688             {  /* We created it */
689                 TRACE("created %s\n", debugstr_w(buffer) );
690                 CloseHandle( handle );
691                 break;
692             }
693             if (GetLastError() != ERROR_FILE_EXISTS &&
694                 GetLastError() != ERROR_SHARING_VIOLATION)
695                 break;  /* No need to go on */
696             if (!(++unique & 0xffff)) unique = 1;
697         } while (unique != num);
698     }
699
700     TRACE("returning %s\n", debugstr_w(buffer) );
701     return unique;
702 }
703
704
705 /***********************************************************************
706  *           contains_pathW
707  *
708  * Check if the file name contains a path; helper for SearchPathW.
709  * A relative path is not considered a path unless it starts with ./ or ../
710  */
711 inline static BOOL contains_pathW (LPCWSTR name)
712 {
713     if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
714     if (name[0] != '.') return FALSE;
715     if (name[1] == '/' || name[1] == '\\') return TRUE;
716     return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
717 }
718
719
720 /***********************************************************************
721  * SearchPathW [KERNEL32.@]
722  *
723  * Searches for a specified file in the search path.
724  *
725  * PARAMS
726  *    path      [I] Path to search (NULL means default)
727  *    name      [I] Filename to search for.
728  *    ext       [I] File extension to append to file name. The first
729  *                  character must be a period. This parameter is
730  *                  specified only if the filename given does not
731  *                  contain an extension.
732  *    buflen    [I] size of buffer, in characters
733  *    buffer    [O] buffer for found filename
734  *    lastpart  [O] address of pointer to last used character in
735  *                  buffer (the final '\')
736  *
737  * RETURNS
738  *    Success: length of string copied into buffer, not including
739  *             terminating null character. If the filename found is
740  *             longer than the length of the buffer, the length of the
741  *             filename is returned.
742  *    Failure: Zero
743  *
744  * NOTES
745  *    If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
746  *    (tested on NT 4.0)
747  */
748 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
749                           LPWSTR buffer, LPWSTR *lastpart )
750 {
751     DWORD ret = 0;
752
753     /* If the name contains an explicit path, ignore the path */
754
755     if (contains_pathW(name))
756     {
757         /* try first without extension */
758         if (RtlDoesFileExists_U( name ))
759             return GetFullPathNameW( name, buflen, buffer, lastpart );
760
761         if (ext)
762         {
763             LPCWSTR p = strrchrW( name, '.' );
764             if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
765                 ext = NULL;  /* Ignore the specified extension */
766         }
767
768         /* Allocate a buffer for the file name and extension */
769         if (ext)
770         {
771             LPWSTR tmp;
772             DWORD len = strlenW(name) + strlenW(ext);
773
774             if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
775             {
776                 SetLastError( ERROR_OUTOFMEMORY );
777                 return 0;
778             }
779             strcpyW( tmp, name );
780             strcatW( tmp, ext );
781             if (RtlDoesFileExists_U( tmp ))
782                 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
783             HeapFree( GetProcessHeap(), 0, tmp );
784         }
785     }
786     else if (path && path[0])  /* search in the specified path */
787     {
788         ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
789                                   buffer, lastpart ) / sizeof(WCHAR);
790     }
791     else  /* search in the default path */
792     {
793         WCHAR *dll_path = MODULE_get_dll_load_path( NULL );
794
795         if (dll_path)
796         {
797             ret = RtlDosSearchPath_U( dll_path, name, ext, buflen * sizeof(WCHAR),
798                                       buffer, lastpart ) / sizeof(WCHAR);
799             HeapFree( GetProcessHeap(), 0, dll_path );
800         }
801         else
802         {
803             SetLastError( ERROR_OUTOFMEMORY );
804             return 0;
805         }
806     }
807
808     if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
809     else TRACE( "found %s\n", debugstr_w(buffer) );
810     return ret;
811 }
812
813
814 /***********************************************************************
815  *           SearchPathA   (KERNEL32.@)
816  *
817  * See SearchPathW.
818  */
819 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
820                           DWORD buflen, LPSTR buffer, LPSTR *lastpart )
821 {
822     WCHAR *pathW = NULL, *nameW = NULL, *extW = NULL;
823     WCHAR bufferW[MAX_PATH];
824     DWORD ret;
825
826     if (!name || !(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
827     if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
828     
829     if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
830     {
831         HeapFree( GetProcessHeap(), 0, pathW );
832         return 0;
833     }
834
835     ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
836
837     HeapFree( GetProcessHeap(), 0, pathW );
838     HeapFree( GetProcessHeap(), 0, extW );
839
840     if (!ret) return 0;
841     if (ret > MAX_PATH)
842     {
843         SetLastError(ERROR_FILENAME_EXCED_RANGE);
844         return 0;
845     }
846     ret = copy_filename_WtoA( bufferW, buffer, buflen );
847     if (buflen > ret && lastpart)
848         *lastpart = strrchr(buffer, '\\') + 1;
849     return ret;
850 }
851
852
853 /**************************************************************************
854  *           CopyFileW   (KERNEL32.@)
855  */
856 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
857 {
858     static const int buffer_size = 65536;
859     HANDLE h1, h2;
860     BY_HANDLE_FILE_INFORMATION info;
861     DWORD count;
862     BOOL ret = FALSE;
863     char *buffer;
864
865     if (!source || !dest)
866     {
867         SetLastError(ERROR_INVALID_PARAMETER);
868         return FALSE;
869     }
870     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
871     {
872         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
873         return FALSE;
874     }
875
876     TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
877
878     if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
879                      NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
880     {
881         WARN("Unable to open source %s\n", debugstr_w(source));
882         return FALSE;
883     }
884
885     if (!GetFileInformationByHandle( h1, &info ))
886     {
887         WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
888         CloseHandle( h1 );
889         return FALSE;
890     }
891
892     if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
893                              fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
894                              info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
895     {
896         WARN("Unable to open dest %s\n", debugstr_w(dest));
897         CloseHandle( h1 );
898         return FALSE;
899     }
900
901     while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
902     {
903         char *p = buffer;
904         while (count != 0)
905         {
906             DWORD res;
907             if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
908             p += res;
909             count -= res;
910         }
911     }
912     ret =  TRUE;
913 done:
914     /* Maintain the timestamp of source file to destination file */
915     SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
916     HeapFree( GetProcessHeap(), 0, buffer );
917     CloseHandle( h1 );
918     CloseHandle( h2 );
919     return ret;
920 }
921
922
923 /**************************************************************************
924  *           CopyFileA   (KERNEL32.@)
925  */
926 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
927 {
928     WCHAR *sourceW, *destW;
929     BOOL ret;
930
931     if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
932     if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
933
934     ret = CopyFileW( sourceW, destW, fail_if_exists );
935
936     HeapFree( GetProcessHeap(), 0, destW );
937     return ret;
938 }
939
940
941 /**************************************************************************
942  *           CopyFileExW   (KERNEL32.@)
943  *
944  * This implementation ignores most of the extra parameters passed-in into
945  * the "ex" version of the method and calls the CopyFile method.
946  * It will have to be fixed eventually.
947  */
948 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
949                         LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
950                         LPBOOL cancelFlagPointer, DWORD copyFlags)
951 {
952     /*
953      * Interpret the only flag that CopyFile can interpret.
954      */
955     return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
956 }
957
958
959 /**************************************************************************
960  *           CopyFileExA   (KERNEL32.@)
961  */
962 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
963                         LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
964                         LPBOOL cancelFlagPointer, DWORD copyFlags)
965 {
966     WCHAR *sourceW, *destW;
967     BOOL ret;
968
969     /* can't use the TEB buffer since we may have a callback routine */
970     if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
971     if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
972     {
973         HeapFree( GetProcessHeap(), 0, sourceW );
974         return FALSE;
975     }
976     ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
977                       cancelFlagPointer, copyFlags);
978     HeapFree( GetProcessHeap(), 0, sourceW );
979     HeapFree( GetProcessHeap(), 0, destW );
980     return ret;
981 }
982
983
984 /**************************************************************************
985  *           MoveFileExW   (KERNEL32.@)
986  */
987 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
988 {
989     FILE_BASIC_INFORMATION info;
990     UNICODE_STRING nt_name;
991     OBJECT_ATTRIBUTES attr;
992     IO_STATUS_BLOCK io;
993     NTSTATUS status;
994     HANDLE source_handle = 0, dest_handle;
995     ANSI_STRING source_unix, dest_unix;
996
997     TRACE("(%s,%s,%04lx)\n", debugstr_w(source), debugstr_w(dest), flag);
998
999     if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1000         return add_boot_rename_entry( source, dest, flag );
1001
1002     if (!dest)
1003         return DeleteFileW( source );
1004
1005     /* check if we are allowed to rename the source */
1006
1007     if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1008     {
1009         SetLastError( ERROR_PATH_NOT_FOUND );
1010         return FALSE;
1011     }
1012     source_unix.Buffer = NULL;
1013     dest_unix.Buffer = NULL;
1014     attr.Length = sizeof(attr);
1015     attr.RootDirectory = 0;
1016     attr.Attributes = OBJ_CASE_INSENSITIVE;
1017     attr.ObjectName = &nt_name;
1018     attr.SecurityDescriptor = NULL;
1019     attr.SecurityQualityOfService = NULL;
1020
1021     status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1022     if (status == STATUS_SUCCESS)
1023         status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1024     RtlFreeUnicodeString( &nt_name );
1025     if (status != STATUS_SUCCESS)
1026     {
1027         SetLastError( RtlNtStatusToDosError(status) );
1028         goto error;
1029     }
1030     status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1031     if (status != STATUS_SUCCESS)
1032     {
1033         SetLastError( RtlNtStatusToDosError(status) );
1034         goto error;
1035     }
1036
1037     if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1038     {
1039         if (flag & MOVEFILE_REPLACE_EXISTING)  /* cannot replace directory */
1040         {
1041             SetLastError( ERROR_INVALID_PARAMETER );
1042             goto error;
1043         }
1044     }
1045
1046     /* we must have write access to the destination, and it must */
1047     /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1048
1049     if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1050     {
1051         SetLastError( ERROR_PATH_NOT_FOUND );
1052         goto error;
1053     }
1054     status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1055                          FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1056     if (status == STATUS_SUCCESS)
1057     {
1058         NtClose( dest_handle );
1059         if (!(flag & MOVEFILE_REPLACE_EXISTING))
1060         {
1061             SetLastError( ERROR_ALREADY_EXISTS );
1062             RtlFreeUnicodeString( &nt_name );
1063             goto error;
1064         }
1065     }
1066     else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1067     {
1068         SetLastError( RtlNtStatusToDosError(status) );
1069         RtlFreeUnicodeString( &nt_name );
1070         goto error;
1071     }
1072
1073     status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1074     RtlFreeUnicodeString( &nt_name );
1075     if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1076     {
1077         SetLastError( RtlNtStatusToDosError(status) );
1078         goto error;
1079     }
1080
1081     /* now perform the rename */
1082
1083     if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1084     {
1085         if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1086         {
1087             NtClose( source_handle );
1088             RtlFreeAnsiString( &source_unix );
1089             RtlFreeAnsiString( &dest_unix );
1090             return (CopyFileW( source, dest, TRUE ) && DeleteFileW( source ));
1091         }
1092         FILE_SetDosError();
1093         /* if we created the destination, remove it */
1094         if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1095         goto error;
1096     }
1097
1098     /* fixup executable permissions */
1099
1100     if (is_executable( source ) != is_executable( dest ))
1101     {
1102         struct stat fstat;
1103         if (stat( dest_unix.Buffer, &fstat ) != -1)
1104         {
1105             if (is_executable( dest ))
1106                 /* set executable bit where read bit is set */
1107                 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1108             else
1109                 fstat.st_mode &= ~0111;
1110             chmod( dest_unix.Buffer, fstat.st_mode );
1111         }
1112     }
1113
1114     NtClose( source_handle );
1115     RtlFreeAnsiString( &source_unix );
1116     RtlFreeAnsiString( &dest_unix );
1117     return TRUE;
1118
1119 error:
1120     if (source_handle) NtClose( source_handle );
1121     RtlFreeAnsiString( &source_unix );
1122     RtlFreeAnsiString( &dest_unix );
1123     return FALSE;
1124 }
1125
1126 /**************************************************************************
1127  *           MoveFileExA   (KERNEL32.@)
1128  */
1129 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1130 {
1131     WCHAR *sourceW, *destW;
1132     BOOL ret;
1133
1134     if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1135     if (dest)
1136     {
1137         if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1138     }
1139     else
1140         destW = NULL;
1141
1142     ret = MoveFileExW( sourceW, destW, flag );
1143     HeapFree( GetProcessHeap(), 0, destW );
1144     return ret;
1145 }
1146
1147
1148 /**************************************************************************
1149  *           MoveFileW   (KERNEL32.@)
1150  *
1151  *  Move file or directory
1152  */
1153 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1154 {
1155     return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1156 }
1157
1158
1159 /**************************************************************************
1160  *           MoveFileA   (KERNEL32.@)
1161  */
1162 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1163 {
1164     return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1165 }
1166
1167
1168 /***********************************************************************
1169  *           CreateDirectoryW   (KERNEL32.@)
1170  * RETURNS:
1171  *      TRUE : success
1172  *      FALSE : failure
1173  *              ERROR_DISK_FULL:        on full disk
1174  *              ERROR_ALREADY_EXISTS:   if directory name exists (even as file)
1175  *              ERROR_ACCESS_DENIED:    on permission problems
1176  *              ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1177  */
1178 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1179 {
1180     OBJECT_ATTRIBUTES attr;
1181     UNICODE_STRING nt_name;
1182     IO_STATUS_BLOCK io;
1183     NTSTATUS status;
1184     HANDLE handle;
1185     BOOL ret = FALSE;
1186
1187     TRACE( "%s\n", debugstr_w(path) );
1188
1189     if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1190     {
1191         SetLastError( ERROR_PATH_NOT_FOUND );
1192         return FALSE;
1193     }
1194     attr.Length = sizeof(attr);
1195     attr.RootDirectory = 0;
1196     attr.Attributes = OBJ_CASE_INSENSITIVE;
1197     attr.ObjectName = &nt_name;
1198     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1199     attr.SecurityQualityOfService = NULL;
1200
1201     status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1202                            FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1203                            FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1204
1205     if (status == STATUS_SUCCESS)
1206     {
1207         NtClose( handle );
1208         ret = TRUE;
1209     }
1210     else SetLastError( RtlNtStatusToDosError(status) );
1211
1212     RtlFreeUnicodeString( &nt_name );
1213     return ret;
1214 }
1215
1216
1217 /***********************************************************************
1218  *           CreateDirectoryA   (KERNEL32.@)
1219  */
1220 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1221 {
1222     WCHAR *pathW;
1223
1224     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1225     return CreateDirectoryW( pathW, sa );
1226 }
1227
1228
1229 /***********************************************************************
1230  *           CreateDirectoryExA   (KERNEL32.@)
1231  */
1232 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1233 {
1234     WCHAR *pathW, *templateW = NULL;
1235     BOOL ret;
1236
1237     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1238     if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1239
1240     ret = CreateDirectoryExW( templateW, pathW, sa );
1241     HeapFree( GetProcessHeap(), 0, templateW );
1242     return ret;
1243 }
1244
1245
1246 /***********************************************************************
1247  *           CreateDirectoryExW   (KERNEL32.@)
1248  */
1249 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1250 {
1251     return CreateDirectoryW( path, sa );
1252 }
1253
1254
1255 /***********************************************************************
1256  *           RemoveDirectoryW   (KERNEL32.@)
1257  */
1258 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1259 {
1260     OBJECT_ATTRIBUTES attr;
1261     UNICODE_STRING nt_name;
1262     ANSI_STRING unix_name;
1263     IO_STATUS_BLOCK io;
1264     NTSTATUS status;
1265     HANDLE handle;
1266     BOOL ret = FALSE;
1267
1268     TRACE( "%s\n", debugstr_w(path) );
1269
1270     if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1271     {
1272         SetLastError( ERROR_PATH_NOT_FOUND );
1273         return FALSE;
1274     }
1275     attr.Length = sizeof(attr);
1276     attr.RootDirectory = 0;
1277     attr.Attributes = OBJ_CASE_INSENSITIVE;
1278     attr.ObjectName = &nt_name;
1279     attr.SecurityDescriptor = NULL;
1280     attr.SecurityQualityOfService = NULL;
1281
1282     status = NtOpenFile( &handle, DELETE, &attr, &io,
1283                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1284                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1285     if (status == STATUS_SUCCESS)
1286         status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1287     RtlFreeUnicodeString( &nt_name );
1288
1289     if (status != STATUS_SUCCESS)
1290     {
1291         SetLastError( RtlNtStatusToDosError(status) );
1292         return FALSE;
1293     }
1294
1295     if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1296     RtlFreeAnsiString( &unix_name );
1297     NtClose( handle );
1298     return ret;
1299 }
1300
1301
1302 /***********************************************************************
1303  *           RemoveDirectoryA   (KERNEL32.@)
1304  */
1305 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1306 {
1307     WCHAR *pathW;
1308
1309     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1310     return RemoveDirectoryW( pathW );
1311 }
1312
1313
1314 /***********************************************************************
1315  *           GetCurrentDirectoryW   (KERNEL32.@)
1316  */
1317 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1318 {
1319     return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1320 }
1321
1322
1323 /***********************************************************************
1324  *           GetCurrentDirectoryA   (KERNEL32.@)
1325  */
1326 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1327 {
1328     WCHAR bufferW[MAX_PATH];
1329     DWORD ret;
1330
1331     if (buflen && buf && !HIWORD(buf))
1332     {
1333         /* Win9x catches access violations here, returning zero.
1334          * This behaviour resulted in some people not noticing
1335          * that they got the argument order wrong. So let's be
1336          * nice and fail gracefully if buf is invalid and looks
1337          * more like a buflen (which is probably MAX_PATH). */
1338         SetLastError(ERROR_INVALID_PARAMETER);
1339         return 0;
1340     }
1341
1342     ret = GetCurrentDirectoryW(MAX_PATH, bufferW);
1343
1344     if (!ret) return 0;
1345     if (ret > MAX_PATH)
1346     {
1347         SetLastError(ERROR_FILENAME_EXCED_RANGE);
1348         return 0;
1349     }
1350     return copy_filename_WtoA( bufferW, buf, buflen );
1351 }
1352
1353
1354 /***********************************************************************
1355  *           SetCurrentDirectoryW   (KERNEL32.@)
1356  */
1357 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1358 {
1359     UNICODE_STRING dirW;
1360     NTSTATUS status;
1361
1362     RtlInitUnicodeString( &dirW, dir );
1363     status = RtlSetCurrentDirectory_U( &dirW );
1364     if (status != STATUS_SUCCESS)
1365     {
1366         SetLastError( RtlNtStatusToDosError(status) );
1367         return FALSE;
1368     }
1369     return TRUE;
1370 }
1371
1372
1373 /***********************************************************************
1374  *           SetCurrentDirectoryA   (KERNEL32.@)
1375  */
1376 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1377 {
1378     WCHAR *dirW;
1379
1380     if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1381     return SetCurrentDirectoryW( dirW );
1382 }
1383
1384
1385 /***********************************************************************
1386  *           GetWindowsDirectoryW   (KERNEL32.@)
1387  *
1388  * See comment for GetWindowsDirectoryA.
1389  */
1390 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1391 {
1392     UINT len = strlenW( DIR_Windows ) + 1;
1393     if (path && count >= len)
1394     {
1395         strcpyW( path, DIR_Windows );
1396         len--;
1397     }
1398     return len;
1399 }
1400
1401
1402 /***********************************************************************
1403  *           GetWindowsDirectoryA   (KERNEL32.@)
1404  *
1405  * Return value:
1406  * If buffer is large enough to hold full path and terminating '\0' character
1407  * function copies path to buffer and returns length of the path without '\0'.
1408  * Otherwise function returns required size including '\0' character and
1409  * does not touch the buffer.
1410  */
1411 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1412 {
1413     return copy_filename_WtoA( DIR_Windows, path, count );
1414 }
1415
1416
1417 /***********************************************************************
1418  *           GetSystemWindowsDirectoryA   (KERNEL32.@) W2K, TS4.0SP4
1419  */
1420 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1421 {
1422     return GetWindowsDirectoryA( path, count );
1423 }
1424
1425
1426 /***********************************************************************
1427  *           GetSystemWindowsDirectoryW   (KERNEL32.@) W2K, TS4.0SP4
1428  */
1429 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1430 {
1431     return GetWindowsDirectoryW( path, count );
1432 }
1433
1434
1435 /***********************************************************************
1436  *           GetSystemDirectoryW   (KERNEL32.@)
1437  *
1438  * See comment for GetWindowsDirectoryA.
1439  */
1440 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1441 {
1442     UINT len = strlenW( DIR_System ) + 1;
1443     if (path && count >= len)
1444     {
1445         strcpyW( path, DIR_System );
1446         len--;
1447     }
1448     return len;
1449 }
1450
1451
1452 /***********************************************************************
1453  *           GetSystemDirectoryA   (KERNEL32.@)
1454  *
1455  * See comment for GetWindowsDirectoryA.
1456  */
1457 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1458 {
1459     return copy_filename_WtoA( DIR_System, path, count );
1460 }
1461
1462
1463 /***********************************************************************
1464  *           GetSystemWow64DirectoryW   (KERNEL32.@)
1465  *
1466  * As seen on MSDN
1467  * - On Win32 we should returns ERROR_CALL_NOT_IMPLEMENTED
1468  * - On Win64 we should returns the SysWow64 (system64) directory
1469  */
1470 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR lpBuffer, UINT uSize )
1471 {
1472     SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1473     return 0;
1474 }
1475
1476
1477 /***********************************************************************
1478  *           GetSystemWow64DirectoryA   (KERNEL32.@)
1479  *
1480  * See comment for GetWindowsWow64DirectoryW.
1481  */
1482 UINT WINAPI GetSystemWow64DirectoryA( LPSTR lpBuffer, UINT uSize )
1483 {
1484     SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1485     return 0;
1486 }
1487
1488
1489 /***********************************************************************
1490  *           wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1491  *
1492  * Return the full Unix file name for a given path.
1493  * Returned buffer must be freed by caller.
1494  */
1495 char *wine_get_unix_file_name( LPCWSTR dosW )
1496 {
1497     UNICODE_STRING nt_name;
1498     ANSI_STRING unix_name;
1499     NTSTATUS status;
1500
1501     if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1502     status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1503     RtlFreeUnicodeString( &nt_name );
1504     if (status && status != STATUS_NO_SUCH_FILE)
1505     {
1506         SetLastError( RtlNtStatusToDosError( status ) );
1507         return NULL;
1508     }
1509     return unix_name.Buffer;
1510 }
1511
1512
1513 /***********************************************************************
1514  *           wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1515  *
1516  * Return the full DOS file name for a given Unix path.
1517  * Returned buffer must be freed by caller.
1518  */
1519 WCHAR *wine_get_dos_file_name( LPCSTR str )
1520 {
1521     UNICODE_STRING nt_name;
1522     ANSI_STRING unix_name;
1523     NTSTATUS status;
1524     DWORD len;
1525
1526     RtlInitAnsiString( &unix_name, str );
1527     status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1528     if (status)
1529     {
1530         SetLastError( RtlNtStatusToDosError( status ) );
1531         return NULL;
1532     }
1533     /* get rid of the \??\ prefix */
1534     /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1535     len = nt_name.Length - 4 * sizeof(WCHAR);
1536     memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1537     nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1538     return nt_name.Buffer;
1539 }