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