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