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