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