msi: Free the deformatted string.
[wine] / dlls / ntdll / path.c
1 /*
2  * Ntdll path functions
3  *
4  * Copyright 2002, 2003, 2004 Alexandre Julliard
5  * Copyright 2003 Eric Pouech
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdarg.h>
26 #include <sys/types.h>
27 #include <errno.h>
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winioctl.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41 #include "wine/library.h"
42 #include "thread.h"
43 #include "ntdll_misc.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(file);
46
47 static const WCHAR DeviceRootW[] = {'\\','\\','.','\\',0};
48 static const WCHAR NTDosPrefixW[] = {'\\','?','?','\\',0};
49 static const WCHAR UncPfxW[] = {'U','N','C','\\',0};
50
51 #define IS_SEPARATOR(ch)  ((ch) == '\\' || (ch) == '/')
52
53 /***********************************************************************
54  *           remove_last_componentA
55  *
56  * Remove the last component of the path. Helper for find_drive_rootA.
57  */
58 static inline unsigned int remove_last_componentA( const char *path, unsigned int len )
59 {
60     int level = 0;
61
62     while (level < 1)
63     {
64         /* find start of the last path component */
65         unsigned int prev = len;
66         if (prev <= 1) break;  /* reached root */
67         while (prev > 1 && path[prev - 1] != '/') prev--;
68         /* does removing it take us up a level? */
69         if (len - prev != 1 || path[prev] != '.')  /* not '.' */
70         {
71             if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.')  /* is it '..'? */
72                 level--;
73             else
74                 level++;
75         }
76         /* strip off trailing slashes */
77         while (prev > 1 && path[prev - 1] == '/') prev--;
78         len = prev;
79     }
80     return len;
81 }
82
83
84 /***********************************************************************
85  *           find_drive_rootA
86  *
87  * Find a drive for which the root matches the beginning of the given path.
88  * This can be used to translate a Unix path into a drive + DOS path.
89  * Return value is the drive, or -1 on error. On success, ppath is modified
90  * to point to the beginning of the DOS path.
91  */
92 static NTSTATUS find_drive_rootA( LPCSTR *ppath, unsigned int len, int *drive_ret )
93 {
94     /* Starting with the full path, check if the device and inode match any of
95      * the wine 'drives'. If not then remove the last path component and try
96      * again. If the last component was a '..' then skip a normal component
97      * since it's a directory that's ascended back out of.
98      */
99     int drive;
100     char *buffer;
101     const char *path = *ppath;
102     struct stat st;
103     struct drive_info info[MAX_DOS_DRIVES];
104
105     /* get device and inode of all drives */
106     if (!DIR_get_drives_info( info )) return STATUS_OBJECT_PATH_NOT_FOUND;
107
108     /* strip off trailing slashes */
109     while (len > 1 && path[len - 1] == '/') len--;
110
111     /* make a copy of the path */
112     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, len + 1 ))) return STATUS_NO_MEMORY;
113     memcpy( buffer, path, len );
114     buffer[len] = 0;
115
116     for (;;)
117     {
118         if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
119         {
120             /* Find the drive */
121             for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
122             {
123                 if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
124                 {
125                     if (len == 1) len = 0;  /* preserve root slash in returned path */
126                     TRACE( "%s -> drive %c:, root=%s, name=%s\n",
127                            debugstr_a(path), 'A' + drive, debugstr_a(buffer), debugstr_a(path + len));
128                     *ppath += len;
129                     *drive_ret = drive;
130                     RtlFreeHeap( GetProcessHeap(), 0, buffer );
131                     return STATUS_SUCCESS;
132                 }
133             }
134         }
135         if (len <= 1) break;  /* reached root */
136         len = remove_last_componentA( buffer, len );
137         buffer[len] = 0;
138     }
139     RtlFreeHeap( GetProcessHeap(), 0, buffer );
140     return STATUS_OBJECT_PATH_NOT_FOUND;
141 }
142
143
144 /***********************************************************************
145  *           remove_last_componentW
146  *
147  * Remove the last component of the path. Helper for find_drive_rootW.
148  */
149 static inline int remove_last_componentW( const WCHAR *path, int len )
150 {
151     int level = 0;
152
153     while (level < 1)
154     {
155         /* find start of the last path component */
156         int prev = len;
157         if (prev <= 1) break;  /* reached root */
158         while (prev > 1 && !IS_SEPARATOR(path[prev - 1])) prev--;
159         /* does removing it take us up a level? */
160         if (len - prev != 1 || path[prev] != '.')  /* not '.' */
161         {
162             if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.')  /* is it '..'? */
163                 level--;
164             else
165                 level++;
166         }
167         /* strip off trailing slashes */
168         while (prev > 1 && IS_SEPARATOR(path[prev - 1])) prev--;
169         len = prev;
170     }
171     return len;
172 }
173
174
175 /***********************************************************************
176  *           find_drive_rootW
177  *
178  * Find a drive for which the root matches the beginning of the given path.
179  * This can be used to translate a Unix path into a drive + DOS path.
180  * Return value is the drive, or -1 on error. On success, ppath is modified
181  * to point to the beginning of the DOS path.
182  */
183 static int find_drive_rootW( LPCWSTR *ppath )
184 {
185     /* Starting with the full path, check if the device and inode match any of
186      * the wine 'drives'. If not then remove the last path component and try
187      * again. If the last component was a '..' then skip a normal component
188      * since it's a directory that's ascended back out of.
189      */
190     int drive, lenA, lenW;
191     char *buffer, *p;
192     const WCHAR *path = *ppath;
193     struct stat st;
194     struct drive_info info[MAX_DOS_DRIVES];
195
196     /* get device and inode of all drives */
197     if (!DIR_get_drives_info( info )) return -1;
198
199     /* strip off trailing slashes */
200     lenW = strlenW(path);
201     while (lenW > 1 && IS_SEPARATOR(path[lenW - 1])) lenW--;
202
203     /* convert path to Unix encoding */
204     lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
205     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, lenA + 1 ))) return -1;
206     lenA = ntdll_wcstoumbs( 0, path, lenW, buffer, lenA, NULL, NULL );
207     buffer[lenA] = 0;
208     for (p = buffer; *p; p++) if (*p == '\\') *p = '/';
209
210     for (;;)
211     {
212         if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
213         {
214             /* Find the drive */
215             for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
216             {
217                 if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
218                 {
219                     if (lenW == 1) lenW = 0;  /* preserve root slash in returned path */
220                     TRACE( "%s -> drive %c:, root=%s, name=%s\n",
221                            debugstr_w(path), 'A' + drive, debugstr_a(buffer), debugstr_w(path + lenW));
222                     *ppath += lenW;
223                     RtlFreeHeap( GetProcessHeap(), 0, buffer );
224                     return drive;
225                 }
226             }
227         }
228         if (lenW <= 1) break;  /* reached root */
229         lenW = remove_last_componentW( path, lenW );
230
231         /* we only need the new length, buffer already contains the converted string */
232         lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
233         buffer[lenA] = 0;
234     }
235     RtlFreeHeap( GetProcessHeap(), 0, buffer );
236     return -1;
237 }
238
239
240 /***********************************************************************
241  *             RtlDetermineDosPathNameType_U   (NTDLL.@)
242  */
243 DOS_PATHNAME_TYPE WINAPI RtlDetermineDosPathNameType_U( PCWSTR path )
244 {
245     if (IS_SEPARATOR(path[0]))
246     {
247         if (!IS_SEPARATOR(path[1])) return ABSOLUTE_PATH;       /* "/foo" */
248         if (path[2] != '.') return UNC_PATH;                    /* "//foo" */
249         if (IS_SEPARATOR(path[3])) return DEVICE_PATH;          /* "//./foo" */
250         if (path[3]) return UNC_PATH;                           /* "//.foo" */
251         return UNC_DOT_PATH;                                    /* "//." */
252     }
253     else
254     {
255         if (!path[0] || path[1] != ':') return RELATIVE_PATH;   /* "foo" */
256         if (IS_SEPARATOR(path[2])) return ABSOLUTE_DRIVE_PATH;  /* "c:/foo" */
257         return RELATIVE_DRIVE_PATH;                             /* "c:foo" */
258     }
259 }
260
261 /***********************************************************************
262  *             RtlIsDosDeviceName_U   (NTDLL.@)
263  *
264  * Check if the given DOS path contains a DOS device name.
265  *
266  * Returns the length of the device name in the low word and its
267  * position in the high word (both in bytes, not WCHARs), or 0 if no
268  * device name is found.
269  */
270 ULONG WINAPI RtlIsDosDeviceName_U( PCWSTR dos_name )
271 {
272     static const WCHAR consoleW[] = {'\\','\\','.','\\','C','O','N',0};
273     static const WCHAR auxW[3] = {'A','U','X'};
274     static const WCHAR comW[3] = {'C','O','M'};
275     static const WCHAR conW[3] = {'C','O','N'};
276     static const WCHAR lptW[3] = {'L','P','T'};
277     static const WCHAR nulW[3] = {'N','U','L'};
278     static const WCHAR prnW[3] = {'P','R','N'};
279
280     const WCHAR *start, *end, *p;
281
282     switch(RtlDetermineDosPathNameType_U( dos_name ))
283     {
284     case INVALID_PATH:
285     case UNC_PATH:
286         return 0;
287     case DEVICE_PATH:
288         if (!strcmpiW( dos_name, consoleW ))
289             return MAKELONG( sizeof(conW), 4 * sizeof(WCHAR) );  /* 4 is length of \\.\ prefix */
290         return 0;
291     default:
292         break;
293     }
294
295     end = dos_name + strlenW(dos_name) - 1;
296     while (end >= dos_name && *end == ':') end--;  /* remove all trailing ':' */
297
298     /* find start of file name */
299     for (start = end; start >= dos_name; start--)
300     {
301         if (IS_SEPARATOR(start[0])) break;
302         /* check for ':' but ignore if before extension (for things like NUL:.txt) */
303         if (start[0] == ':' && start[1] != '.') break;
304     }
305     start++;
306
307     /* remove extension */
308     if ((p = strchrW( start, '.' )))
309     {
310         end = p - 1;
311         if (end >= dos_name && *end == ':') end--;  /* remove trailing ':' before extension */
312     }
313     /* remove trailing spaces */
314     while (end >= dos_name && *end == ' ') end--;
315
316     /* now we have a potential device name between start and end, check it */
317     switch(end - start + 1)
318     {
319     case 3:
320         if (strncmpiW( start, auxW, 3 ) &&
321             strncmpiW( start, conW, 3 ) &&
322             strncmpiW( start, nulW, 3 ) &&
323             strncmpiW( start, prnW, 3 )) break;
324         return MAKELONG( 3 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
325     case 4:
326         if (strncmpiW( start, comW, 3 ) && strncmpiW( start, lptW, 3 )) break;
327         if (*end <= '0' || *end > '9') break;
328         return MAKELONG( 4 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
329     default:  /* can't match anything */
330         break;
331     }
332     return 0;
333 }
334
335
336 /**************************************************************************
337  *                 RtlDosPathNameToNtPathName_U         [NTDLL.@]
338  *
339  * dos_path: a DOS path name (fully qualified or not)
340  * ntpath:   pointer to a UNICODE_STRING to hold the converted
341  *           path name
342  * file_part:will point (in ntpath) to the file part in the path
343  * cd:       directory reference (optional)
344  *
345  * FIXME:
346  *      + fill the cd structure
347  */
348 BOOLEAN  WINAPI RtlDosPathNameToNtPathName_U(PCWSTR dos_path,
349                                              PUNICODE_STRING ntpath,
350                                              PWSTR* file_part,
351                                              CURDIR* cd)
352 {
353     static const WCHAR LongFileNamePfxW[4] = {'\\','\\','?','\\'};
354     ULONG sz, offset;
355     WCHAR local[MAX_PATH];
356     LPWSTR ptr;
357
358     TRACE("(%s,%p,%p,%p)\n",
359           debugstr_w(dos_path), ntpath, file_part, cd);
360
361     if (cd)
362     {
363         FIXME("Unsupported parameter\n");
364         memset(cd, 0, sizeof(*cd));
365     }
366
367     if (!dos_path || !*dos_path) return FALSE;
368
369     if (!strncmpW(dos_path, LongFileNamePfxW, 4))
370     {
371         ntpath->Length = strlenW(dos_path) * sizeof(WCHAR);
372         ntpath->MaximumLength = ntpath->Length + sizeof(WCHAR);
373         ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
374         if (!ntpath->Buffer) return FALSE;
375         memcpy( ntpath->Buffer, dos_path, ntpath->MaximumLength );
376         ntpath->Buffer[1] = '?';  /* change \\?\ to \??\ */
377         if (file_part)
378         {
379             if ((ptr = strrchrW( ntpath->Buffer, '\\' )) && ptr[1]) *file_part = ptr + 1;
380             else *file_part = NULL;
381         }
382         return TRUE;
383     }
384
385     ptr = local;
386     sz = RtlGetFullPathName_U(dos_path, sizeof(local), ptr, file_part);
387     if (sz == 0) return FALSE;
388     if (sz > sizeof(local))
389     {
390         if (!(ptr = RtlAllocateHeap(GetProcessHeap(), 0, sz))) return FALSE;
391         sz = RtlGetFullPathName_U(dos_path, sz, ptr, file_part);
392     }
393
394     ntpath->MaximumLength = sz + (4 /* unc\ */ + 4 /* \??\ */) * sizeof(WCHAR);
395     ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
396     if (!ntpath->Buffer)
397     {
398         if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
399         return FALSE;
400     }
401
402     strcpyW(ntpath->Buffer, NTDosPrefixW);
403     switch (RtlDetermineDosPathNameType_U(ptr))
404     {
405     case UNC_PATH: /* \\foo */
406         offset = 2;
407         strcatW(ntpath->Buffer, UncPfxW);
408         break;
409     case DEVICE_PATH: /* \\.\foo */
410         offset = 4;
411         break;
412     default:
413         offset = 0;
414         break;
415     }
416
417     strcatW(ntpath->Buffer, ptr + offset);
418     ntpath->Length = strlenW(ntpath->Buffer) * sizeof(WCHAR);
419
420     if (file_part && *file_part)
421         *file_part = ntpath->Buffer + ntpath->Length / sizeof(WCHAR) - strlenW(*file_part);
422
423     /* FIXME: cd filling */
424
425     if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
426     return TRUE;
427 }
428
429 /******************************************************************
430  *              RtlDosSearchPath_U
431  *
432  * Searchs a file of name 'name' into a ';' separated list of paths
433  * (stored in paths)
434  * Doesn't seem to search elsewhere than the paths list
435  * Stores the result in buffer (file_part will point to the position
436  * of the file name in the buffer)
437  * FIXME:
438  * - how long shall the paths be ??? (MAX_PATH or larger with \\?\ constructs ???)
439  */
440 ULONG WINAPI RtlDosSearchPath_U(LPCWSTR paths, LPCWSTR search, LPCWSTR ext, 
441                                 ULONG buffer_size, LPWSTR buffer, 
442                                 LPWSTR* file_part)
443 {
444     DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U(search);
445     ULONG len = 0;
446
447     if (type == RELATIVE_PATH)
448     {
449         ULONG allocated = 0, needed, filelen;
450         WCHAR *name = NULL;
451
452         filelen = 1 /* for \ */ + strlenW(search) + 1 /* \0 */;
453
454         /* Windows only checks for '.' without worrying about path components */
455         if (strchrW( search, '.' )) ext = NULL;
456         if (ext != NULL) filelen += strlenW(ext);
457
458         while (*paths)
459         {
460             LPCWSTR ptr;
461
462             for (needed = 0, ptr = paths; *ptr != 0 && *ptr++ != ';'; needed++);
463             if (needed + filelen > allocated)
464             {
465                 if (!name) name = RtlAllocateHeap(GetProcessHeap(), 0,
466                                                   (needed + filelen) * sizeof(WCHAR));
467                 else
468                 {
469                     WCHAR *newname = RtlReAllocateHeap(GetProcessHeap(), 0, name,
470                                                        (needed + filelen) * sizeof(WCHAR));
471                     if (!newname) RtlFreeHeap(GetProcessHeap(), 0, name);
472                     name = newname;
473                 }
474                 if (!name) return 0;
475                 allocated = needed + filelen;
476             }
477             memmove(name, paths, needed * sizeof(WCHAR));
478             /* append '\\' if none is present */
479             if (needed > 0 && name[needed - 1] != '\\') name[needed++] = '\\';
480             strcpyW(&name[needed], search);
481             if (ext) strcatW(&name[needed], ext);
482             if (RtlDoesFileExists_U(name))
483             {
484                 len = RtlGetFullPathName_U(name, buffer_size, buffer, file_part);
485                 break;
486             }
487             paths = ptr;
488         }
489         RtlFreeHeap(GetProcessHeap(), 0, name);
490     }
491     else if (RtlDoesFileExists_U(search))
492     {
493         len = RtlGetFullPathName_U(search, buffer_size, buffer, file_part);
494     }
495
496     return len;
497 }
498
499
500 /******************************************************************
501  *              collapse_path
502  *
503  * Helper for RtlGetFullPathName_U.
504  * Get rid of . and .. components in the path.
505  */
506 static inline void collapse_path( WCHAR *path, UINT mark )
507 {
508     WCHAR *p, *next;
509
510     /* convert every / into a \ */
511     for (p = path; *p; p++) if (*p == '/') *p = '\\';
512
513     /* collapse duplicate backslashes */
514     next = path + max( 1, mark );
515     for (p = next; *p; p++) if (*p != '\\' || next[-1] != '\\') *next++ = *p;
516     *next = 0;
517
518     p = path + mark;
519     while (*p)
520     {
521         if (*p == '.')
522         {
523             switch(p[1])
524             {
525             case '\\': /* .\ component */
526                 next = p + 2;
527                 memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
528                 continue;
529             case 0:  /* final . */
530                 if (p > path + mark) p--;
531                 *p = 0;
532                 continue;
533             case '.':
534                 if (p[2] == '\\')  /* ..\ component */
535                 {
536                     next = p + 3;
537                     if (p > path + mark)
538                     {
539                         p--;
540                         while (p > path + mark && p[-1] != '\\') p--;
541                     }
542                     memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
543                     continue;
544                 }
545                 else if (!p[2])  /* final .. */
546                 {
547                     if (p > path + mark)
548                     {
549                         p--;
550                         while (p > path + mark && p[-1] != '\\') p--;
551                         if (p > path + mark) p--;
552                     }
553                     *p = 0;
554                     continue;
555                 }
556                 break;
557             }
558         }
559         /* skip to the next component */
560         while (*p && *p != '\\') p++;
561         if (*p == '\\')
562         {
563             /* remove last dot in previous dir name */
564             if (p > path + mark && p[-1] == '.') memmove( p-1, p, (strlenW(p) + 1) * sizeof(WCHAR) );
565             else p++;
566         }
567     }
568
569     /* remove trailing spaces and dots (yes, Windows really does that, don't ask) */
570     while (p > path + mark && (p[-1] == ' ' || p[-1] == '.')) p--;
571     *p = 0;
572 }
573
574
575 /******************************************************************
576  *              skip_unc_prefix
577  *
578  * Skip the \\share\dir\ part of a file name. Helper for RtlGetFullPathName_U.
579  */
580 static const WCHAR *skip_unc_prefix( const WCHAR *ptr )
581 {
582     ptr += 2;
583     while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* share name */
584     while (IS_SEPARATOR(*ptr)) ptr++;
585     while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* dir name */
586     while (IS_SEPARATOR(*ptr)) ptr++;
587     return ptr;
588 }
589
590
591 /******************************************************************
592  *              get_full_path_helper
593  *
594  * Helper for RtlGetFullPathName_U
595  * Note: name and buffer are allowed to point to the same memory spot
596  */
597 static ULONG get_full_path_helper(LPCWSTR name, LPWSTR buffer, ULONG size)
598 {
599     ULONG                       reqsize = 0, mark = 0, dep = 0, deplen;
600     DOS_PATHNAME_TYPE           type;
601     LPWSTR                      ins_str = NULL;
602     LPCWSTR                     ptr;
603     const UNICODE_STRING*       cd;
604     WCHAR                       tmp[4];
605
606     /* return error if name only consists of spaces */
607     for (ptr = name; *ptr; ptr++) if (*ptr != ' ') break;
608     if (!*ptr) return 0;
609
610     RtlAcquirePebLock();
611
612     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
613         cd = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
614     else
615         cd = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
616
617     switch (type = RtlDetermineDosPathNameType_U(name))
618     {
619     case UNC_PATH:              /* \\foo   */
620         ptr = skip_unc_prefix( name );
621         mark = (ptr - name);
622         break;
623
624     case DEVICE_PATH:           /* \\.\foo */
625         mark = 4;
626         break;
627
628     case ABSOLUTE_DRIVE_PATH:   /* c:\foo  */
629         reqsize = sizeof(WCHAR);
630         tmp[0] = toupperW(name[0]);
631         ins_str = tmp;
632         dep = 1;
633         mark = 3;
634         break;
635
636     case RELATIVE_DRIVE_PATH:   /* c:foo   */
637         dep = 2;
638         if (toupperW(name[0]) != toupperW(cd->Buffer[0]) || cd->Buffer[1] != ':')
639         {
640             UNICODE_STRING      var, val;
641
642             tmp[0] = '=';
643             tmp[1] = name[0];
644             tmp[2] = ':';
645             tmp[3] = '\0';
646             var.Length = 3 * sizeof(WCHAR);
647             var.MaximumLength = 4 * sizeof(WCHAR);
648             var.Buffer = tmp;
649             val.Length = 0;
650             val.MaximumLength = size;
651             val.Buffer = RtlAllocateHeap(GetProcessHeap(), 0, size);
652
653             switch (RtlQueryEnvironmentVariable_U(NULL, &var, &val))
654             {
655             case STATUS_SUCCESS:
656                 /* FIXME: Win2k seems to check that the environment variable actually points 
657                  * to an existing directory. If not, root of the drive is used
658                  * (this seems also to be the only spot in RtlGetFullPathName that the 
659                  * existence of a part of a path is checked)
660                  */
661                 /* fall thru */
662             case STATUS_BUFFER_TOO_SMALL:
663                 reqsize = val.Length + sizeof(WCHAR); /* append trailing '\\' */
664                 val.Buffer[val.Length / sizeof(WCHAR)] = '\\';
665                 ins_str = val.Buffer;
666                 break;
667             case STATUS_VARIABLE_NOT_FOUND:
668                 reqsize = 3 * sizeof(WCHAR);
669                 tmp[0] = name[0];
670                 tmp[1] = ':';
671                 tmp[2] = '\\';
672                 ins_str = tmp;
673                 break;
674             default:
675                 ERR("Unsupported status code\n");
676                 break;
677             }
678             mark = 3;
679             break;
680         }
681         /* fall through */
682
683     case RELATIVE_PATH:         /* foo     */
684         reqsize = cd->Length;
685         ins_str = cd->Buffer;
686         if (cd->Buffer[1] != ':')
687         {
688             ptr = skip_unc_prefix( cd->Buffer );
689             mark = ptr - cd->Buffer;
690         }
691         else mark = 3;
692         break;
693
694     case ABSOLUTE_PATH:         /* \xxx    */
695         if (name[0] == '/')  /* may be a Unix path */
696         {
697             const WCHAR *ptr = name;
698             int drive = find_drive_rootW( &ptr );
699             if (drive != -1)
700             {
701                 reqsize = 3 * sizeof(WCHAR);
702                 tmp[0] = 'A' + drive;
703                 tmp[1] = ':';
704                 tmp[2] = '\\';
705                 ins_str = tmp;
706                 mark = 3;
707                 dep = ptr - name;
708                 break;
709             }
710         }
711         if (cd->Buffer[1] == ':')
712         {
713             reqsize = 2 * sizeof(WCHAR);
714             tmp[0] = cd->Buffer[0];
715             tmp[1] = ':';
716             ins_str = tmp;
717             mark = 3;
718         }
719         else
720         {
721             ptr = skip_unc_prefix( cd->Buffer );
722             reqsize = (ptr - cd->Buffer) * sizeof(WCHAR);
723             mark = reqsize / sizeof(WCHAR);
724             ins_str = cd->Buffer;
725         }
726         break;
727
728     case UNC_DOT_PATH:         /* \\.     */
729         reqsize = 4 * sizeof(WCHAR);
730         dep = 3;
731         tmp[0] = '\\';
732         tmp[1] = '\\';
733         tmp[2] = '.';
734         tmp[3] = '\\';
735         ins_str = tmp;
736         mark = 4;
737         break;
738
739     case INVALID_PATH:
740         goto done;
741     }
742
743     /* enough space ? */
744     deplen = strlenW(name + dep) * sizeof(WCHAR);
745     if (reqsize + deplen + sizeof(WCHAR) > size)
746     {
747         /* not enough space, return need size (including terminating '\0') */
748         reqsize += deplen + sizeof(WCHAR);
749         goto done;
750     }
751
752     memmove(buffer + reqsize / sizeof(WCHAR), name + dep, deplen + sizeof(WCHAR));
753     if (reqsize) memcpy(buffer, ins_str, reqsize);
754     reqsize += deplen;
755
756     if (ins_str != tmp && ins_str != cd->Buffer)
757         RtlFreeHeap(GetProcessHeap(), 0, ins_str);
758
759     collapse_path( buffer, mark );
760     reqsize = strlenW(buffer) * sizeof(WCHAR);
761
762 done:
763     RtlReleasePebLock();
764     return reqsize;
765 }
766
767 /******************************************************************
768  *              RtlGetFullPathName_U  (NTDLL.@)
769  *
770  * Returns the number of bytes written to buffer (not including the
771  * terminating NULL) if the function succeeds, or the required number of bytes
772  * (including the terminating NULL) if the buffer is too small.
773  *
774  * file_part will point to the filename part inside buffer (except if we use
775  * DOS device name, in which case file_in_buf is NULL)
776  *
777  */
778 DWORD WINAPI RtlGetFullPathName_U(const WCHAR* name, ULONG size, WCHAR* buffer,
779                                   WCHAR** file_part)
780 {
781     WCHAR*      ptr;
782     DWORD       dosdev;
783     DWORD       reqsize;
784
785     TRACE("(%s %u %p %p)\n", debugstr_w(name), size, buffer, file_part);
786
787     if (!name || !*name) return 0;
788
789     if (file_part) *file_part = NULL;
790
791     /* check for DOS device name */
792     dosdev = RtlIsDosDeviceName_U(name);
793     if (dosdev)
794     {
795         DWORD   offset = HIWORD(dosdev) / sizeof(WCHAR); /* get it in WCHARs, not bytes */
796         DWORD   sz = LOWORD(dosdev); /* in bytes */
797
798         if (8 + sz + 2 > size) return sz + 10;
799         strcpyW(buffer, DeviceRootW);
800         memmove(buffer + 4, name + offset, sz);
801         buffer[4 + sz / sizeof(WCHAR)] = '\0';
802         /* file_part isn't set in this case */
803         return sz + 8;
804     }
805
806     reqsize = get_full_path_helper(name, buffer, size);
807     if (!reqsize) return 0;
808     if (reqsize > size)
809     {
810         LPWSTR tmp = RtlAllocateHeap(GetProcessHeap(), 0, reqsize);
811         reqsize = get_full_path_helper(name, tmp, reqsize);
812         if (reqsize + sizeof(WCHAR) > size)  /* it may have worked the second time */
813         {
814             RtlFreeHeap(GetProcessHeap(), 0, tmp);
815             return reqsize + sizeof(WCHAR);
816         }
817         memcpy( buffer, tmp, reqsize + sizeof(WCHAR) );
818         RtlFreeHeap(GetProcessHeap(), 0, tmp);
819     }
820
821     /* find file part */
822     if (file_part && (ptr = strrchrW(buffer, '\\')) != NULL && ptr >= buffer + 2 && *++ptr)
823         *file_part = ptr;
824     return reqsize;
825 }
826
827 /*************************************************************************
828  * RtlGetLongestNtPathLength    [NTDLL.@]
829  *
830  * Get the longest allowed path length
831  *
832  * PARAMS
833  *  None.
834  *
835  * RETURNS
836  *  The longest allowed path length (277 characters under Win2k).
837  */
838 DWORD WINAPI RtlGetLongestNtPathLength(void)
839 {
840     return MAX_NT_PATH_LENGTH;
841 }
842
843 /******************************************************************
844  *             RtlIsNameLegalDOS8Dot3   (NTDLL.@)
845  *
846  * Returns TRUE iff unicode is a valid DOS (8+3) name.
847  * If the name is valid, oem gets filled with the corresponding OEM string
848  * spaces is set to TRUE if unicode contains spaces
849  */
850 BOOLEAN WINAPI RtlIsNameLegalDOS8Dot3( const UNICODE_STRING *unicode,
851                                        OEM_STRING *oem, BOOLEAN *spaces )
852 {
853     static const char illegal[] = "*?<>|\"+=,;[]:/\\\345";
854     int dot = -1;
855     int i;
856     char buffer[12];
857     OEM_STRING oem_str;
858     BOOLEAN got_space = FALSE;
859
860     if (!oem)
861     {
862         oem_str.Length = sizeof(buffer);
863         oem_str.MaximumLength = sizeof(buffer);
864         oem_str.Buffer = buffer;
865         oem = &oem_str;
866     }
867     if (RtlUpcaseUnicodeStringToCountedOemString( oem, unicode, FALSE ) != STATUS_SUCCESS)
868         return FALSE;
869
870     if (oem->Length > 12) return FALSE;
871
872     /* a starting . is invalid, except for . and .. */
873     if (oem->Buffer[0] == '.')
874     {
875         if (oem->Length != 1 && (oem->Length != 2 || oem->Buffer[1] != '.')) return FALSE;
876         if (spaces) *spaces = FALSE;
877         return TRUE;
878     }
879
880     for (i = 0; i < oem->Length; i++)
881     {
882         switch (oem->Buffer[i])
883         {
884         case ' ':
885             /* leading/trailing spaces not allowed */
886             if (!i || i == oem->Length-1 || oem->Buffer[i+1] == '.') return FALSE;
887             got_space = TRUE;
888             break;
889         case '.':
890             if (dot != -1) return FALSE;
891             dot = i;
892             break;
893         default:
894             if (strchr(illegal, oem->Buffer[i])) return FALSE;
895             break;
896         }
897     }
898     /* check file part is shorter than 8, extension shorter than 3
899      * dot cannot be last in string
900      */
901     if (dot == -1)
902     {
903         if (oem->Length > 8) return FALSE;
904     }
905     else
906     {
907         if (dot > 8 || (oem->Length - dot > 4) || dot == oem->Length - 1) return FALSE;
908     }
909     if (spaces) *spaces = got_space;
910     return TRUE;
911 }
912
913 /******************************************************************
914  *              RtlGetCurrentDirectory_U (NTDLL.@)
915  *
916  */
917 NTSTATUS WINAPI RtlGetCurrentDirectory_U(ULONG buflen, LPWSTR buf)
918 {
919     UNICODE_STRING*     us;
920     ULONG               len;
921
922     TRACE("(%u %p)\n", buflen, buf);
923
924     RtlAcquirePebLock();
925
926     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
927         us = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
928     else
929         us = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
930
931     len = us->Length / sizeof(WCHAR);
932     if (us->Buffer[len - 1] == '\\' && us->Buffer[len - 2] != ':')
933         len--;
934
935     if (buflen / sizeof(WCHAR) > len)
936     {
937         memcpy(buf, us->Buffer, len * sizeof(WCHAR));
938         buf[len] = '\0';
939     }
940     else
941     {
942         len++;
943     }
944
945     RtlReleasePebLock();
946
947     return len * sizeof(WCHAR);
948 }
949
950 /******************************************************************
951  *              RtlSetCurrentDirectory_U (NTDLL.@)
952  *
953  */
954 NTSTATUS WINAPI RtlSetCurrentDirectory_U(const UNICODE_STRING* dir)
955 {
956     FILE_FS_DEVICE_INFORMATION device_info;
957     OBJECT_ATTRIBUTES attr;
958     UNICODE_STRING newdir;
959     IO_STATUS_BLOCK io;
960     CURDIR *curdir;
961     HANDLE handle;
962     NTSTATUS nts;
963     ULONG size;
964     PWSTR ptr;
965
966     newdir.Buffer = NULL;
967
968     RtlAcquirePebLock();
969
970     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
971         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
972     else
973         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
974
975     if (!RtlDosPathNameToNtPathName_U( dir->Buffer, &newdir, NULL, NULL ))
976     {
977         nts = STATUS_OBJECT_NAME_INVALID;
978         goto out;
979     }
980
981     attr.Length = sizeof(attr);
982     attr.RootDirectory = 0;
983     attr.Attributes = OBJ_CASE_INSENSITIVE;
984     attr.ObjectName = &newdir;
985     attr.SecurityDescriptor = NULL;
986     attr.SecurityQualityOfService = NULL;
987
988     nts = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
989     if (nts != STATUS_SUCCESS) goto out;
990
991     /* don't keep the directory handle open on removable media */
992     if (!NtQueryVolumeInformationFile( handle, &io, &device_info,
993                                        sizeof(device_info), FileFsDeviceInformation ) &&
994         (device_info.Characteristics & FILE_REMOVABLE_MEDIA))
995     {
996         NtClose( handle );
997         handle = 0;
998     }
999
1000     if (curdir->Handle) NtClose( curdir->Handle );
1001     curdir->Handle = handle;
1002
1003     /* append trailing \ if missing */
1004     size = newdir.Length / sizeof(WCHAR);
1005     ptr = newdir.Buffer;
1006     ptr += 4;  /* skip \??\ prefix */
1007     size -= 4;
1008     if (size && ptr[size - 1] != '\\') ptr[size++] = '\\';
1009
1010     memcpy( curdir->DosPath.Buffer, ptr, size * sizeof(WCHAR));
1011     curdir->DosPath.Buffer[size] = 0;
1012     curdir->DosPath.Length = size * sizeof(WCHAR);
1013
1014     TRACE( "curdir now %s %p\n", debugstr_w(curdir->DosPath.Buffer), curdir->Handle );
1015
1016  out:
1017     RtlFreeUnicodeString( &newdir );
1018     RtlReleasePebLock();
1019     return nts;
1020 }
1021
1022
1023 /******************************************************************
1024  *           wine_unix_to_nt_file_name  (NTDLL.@) Not a Windows API
1025  */
1026 NTSTATUS wine_unix_to_nt_file_name( const ANSI_STRING *name, UNICODE_STRING *nt )
1027 {
1028     static const WCHAR prefixW[] = {'\\','?','?','\\','a',':','\\'};
1029     unsigned int lenW, lenA = name->Length;
1030     const char *path = name->Buffer;
1031     char *cwd;
1032     WCHAR *p;
1033     NTSTATUS status;
1034     int drive;
1035
1036     if (!lenA || path[0] != '/')
1037     {
1038         char *newcwd, *end;
1039         size_t size;
1040
1041         if ((status = DIR_get_unix_cwd( &cwd )) != STATUS_SUCCESS) return status;
1042
1043         size = strlen(cwd) + lenA + 1;
1044         if (!(newcwd = RtlReAllocateHeap( GetProcessHeap(), 0, cwd, size )))
1045         {
1046             status = STATUS_NO_MEMORY;
1047             goto done;
1048         }
1049         cwd = newcwd;
1050         end = cwd + strlen(cwd);
1051         if (end > cwd && end[-1] != '/') *end++ = '/';
1052         memcpy( end, path, lenA );
1053         lenA += end - cwd;
1054         path = cwd;
1055
1056         status = find_drive_rootA( &path, lenA, &drive );
1057         lenA -= (path - cwd);
1058     }
1059     else
1060     {
1061         cwd = NULL;
1062         status = find_drive_rootA( &path, lenA, &drive );
1063         lenA -= (path - name->Buffer);
1064     }
1065
1066     if (status != STATUS_SUCCESS) goto done;
1067     while (lenA && path[0] == '/') { lenA--; path++; }
1068
1069     lenW = ntdll_umbstowcs( 0, path, lenA, NULL, 0 );
1070     if (!(nt->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1071                                         (lenW + 1) * sizeof(WCHAR) + sizeof(prefixW) )))
1072     {
1073         status = STATUS_NO_MEMORY;
1074         goto done;
1075     }
1076
1077     memcpy( nt->Buffer, prefixW, sizeof(prefixW) );
1078     nt->Buffer[4] += drive;
1079     ntdll_umbstowcs( 0, path, lenA, nt->Buffer + sizeof(prefixW)/sizeof(WCHAR), lenW );
1080     lenW += sizeof(prefixW)/sizeof(WCHAR);
1081     nt->Buffer[lenW] = 0;
1082     nt->Length = lenW * sizeof(WCHAR);
1083     nt->MaximumLength = nt->Length + sizeof(WCHAR);
1084     for (p = nt->Buffer + sizeof(prefixW)/sizeof(WCHAR); *p; p++) if (*p == '/') *p = '\\';
1085
1086 done:
1087     RtlFreeHeap( GetProcessHeap(), 0, cwd );
1088     return status;
1089 }