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