ntdll: Convert PE header to 64-bit when loading a 32-bit IL-only module.
[wine.git] / dlls / ntdll / path.c
blob11483fabbaf1f2b3d0a86af2ff15dc53ce1dd78e
1 /*
2 * Ntdll path functions
4 * Copyright 2002, 2003, 2004 Alexandre Julliard
5 * Copyright 2003 Eric Pouech
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.
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.
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
22 #include "config.h"
23 #include "wine/port.h"
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
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 "ntdll_misc.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(file);
46 static const WCHAR DeviceRootW[] = {'\\','\\','.','\\',0};
47 static const WCHAR NTDosPrefixW[] = {'\\','?','?','\\',0};
48 static const WCHAR UncPfxW[] = {'U','N','C','\\',0};
50 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
52 /***********************************************************************
53 * remove_last_componentA
55 * Remove the last component of the path. Helper for find_drive_rootA.
57 static inline unsigned int remove_last_componentA( const char *path, unsigned int len )
59 int level = 0;
61 while (level < 1)
63 /* find start of the last path component */
64 unsigned int prev = len;
65 if (prev <= 1) break; /* reached root */
66 while (prev > 1 && path[prev - 1] != '/') prev--;
67 /* does removing it take us up a level? */
68 if (len - prev != 1 || path[prev] != '.') /* not '.' */
70 if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.') /* is it '..'? */
71 level--;
72 else
73 level++;
75 /* strip off trailing slashes */
76 while (prev > 1 && path[prev - 1] == '/') prev--;
77 len = prev;
79 return len;
83 /***********************************************************************
84 * find_drive_rootA
86 * Find a drive for which the root matches the beginning of the given path.
87 * This can be used to translate a Unix path into a drive + DOS path.
88 * Return value is the drive, or -1 on error. On success, ppath is modified
89 * to point to the beginning of the DOS path.
91 static NTSTATUS find_drive_rootA( LPCSTR *ppath, unsigned int len, int *drive_ret )
93 /* Starting with the full path, check if the device and inode match any of
94 * the wine 'drives'. If not then remove the last path component and try
95 * again. If the last component was a '..' then skip a normal component
96 * since it's a directory that's ascended back out of.
98 int drive;
99 char *buffer;
100 const char *path = *ppath;
101 struct stat st;
102 struct drive_info info[MAX_DOS_DRIVES];
104 /* get device and inode of all drives */
105 if (!DIR_get_drives_info( info )) return STATUS_OBJECT_PATH_NOT_FOUND;
107 /* strip off trailing slashes */
108 while (len > 1 && path[len - 1] == '/') len--;
110 /* make a copy of the path */
111 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, len + 1 ))) return STATUS_NO_MEMORY;
112 memcpy( buffer, path, len );
113 buffer[len] = 0;
115 for (;;)
117 if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
119 /* Find the drive */
120 for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
122 if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
124 if (len == 1) len = 0; /* preserve root slash in returned path */
125 TRACE( "%s -> drive %c:, root=%s, name=%s\n",
126 debugstr_a(path), 'A' + drive, debugstr_a(buffer), debugstr_a(path + len));
127 *ppath += len;
128 *drive_ret = drive;
129 RtlFreeHeap( GetProcessHeap(), 0, buffer );
130 return STATUS_SUCCESS;
134 if (len <= 1) break; /* reached root */
135 len = remove_last_componentA( buffer, len );
136 buffer[len] = 0;
138 RtlFreeHeap( GetProcessHeap(), 0, buffer );
139 return STATUS_OBJECT_PATH_NOT_FOUND;
143 /***********************************************************************
144 * remove_last_componentW
146 * Remove the last component of the path. Helper for find_drive_rootW.
148 static inline int remove_last_componentW( const WCHAR *path, int len )
150 int level = 0;
152 while (level < 1)
154 /* find start of the last path component */
155 int prev = len;
156 if (prev <= 1) break; /* reached root */
157 while (prev > 1 && !IS_SEPARATOR(path[prev - 1])) prev--;
158 /* does removing it take us up a level? */
159 if (len - prev != 1 || path[prev] != '.') /* not '.' */
161 if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.') /* is it '..'? */
162 level--;
163 else
164 level++;
166 /* strip off trailing slashes */
167 while (prev > 1 && IS_SEPARATOR(path[prev - 1])) prev--;
168 len = prev;
170 return len;
174 /***********************************************************************
175 * find_drive_rootW
177 * Find a drive for which the root matches the beginning of the given path.
178 * This can be used to translate a Unix path into a drive + DOS path.
179 * Return value is the drive, or -1 on error. On success, ppath is modified
180 * to point to the beginning of the DOS path.
182 static int find_drive_rootW( LPCWSTR *ppath )
184 /* Starting with the full path, check if the device and inode match any of
185 * the wine 'drives'. If not then remove the last path component and try
186 * again. If the last component was a '..' then skip a normal component
187 * since it's a directory that's ascended back out of.
189 int drive, lenA, lenW;
190 char *buffer, *p;
191 const WCHAR *path = *ppath;
192 struct stat st;
193 struct drive_info info[MAX_DOS_DRIVES];
195 /* get device and inode of all drives */
196 if (!DIR_get_drives_info( info )) return -1;
198 /* strip off trailing slashes */
199 lenW = strlenW(path);
200 while (lenW > 1 && IS_SEPARATOR(path[lenW - 1])) lenW--;
202 /* convert path to Unix encoding */
203 lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
204 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, lenA + 1 ))) return -1;
205 lenA = ntdll_wcstoumbs( 0, path, lenW, buffer, lenA, NULL, NULL );
206 buffer[lenA] = 0;
207 for (p = buffer; *p; p++) if (*p == '\\') *p = '/';
209 for (;;)
211 if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
213 /* Find the drive */
214 for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
216 if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
218 if (lenW == 1) lenW = 0; /* preserve root slash in returned path */
219 TRACE( "%s -> drive %c:, root=%s, name=%s\n",
220 debugstr_w(path), 'A' + drive, debugstr_a(buffer), debugstr_w(path + lenW));
221 *ppath += lenW;
222 RtlFreeHeap( GetProcessHeap(), 0, buffer );
223 return drive;
227 if (lenW <= 1) break; /* reached root */
228 lenW = remove_last_componentW( path, lenW );
230 /* we only need the new length, buffer already contains the converted string */
231 lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
232 buffer[lenA] = 0;
234 RtlFreeHeap( GetProcessHeap(), 0, buffer );
235 return -1;
239 /***********************************************************************
240 * RtlDetermineDosPathNameType_U (NTDLL.@)
242 DOS_PATHNAME_TYPE WINAPI RtlDetermineDosPathNameType_U( PCWSTR path )
244 if (IS_SEPARATOR(path[0]))
246 if (!IS_SEPARATOR(path[1])) return ABSOLUTE_PATH; /* "/foo" */
247 if (path[2] != '.' && path[2] != '?') return UNC_PATH; /* "//foo" */
248 if (IS_SEPARATOR(path[3])) return DEVICE_PATH; /* "//./foo" or "//?/foo" */
249 if (path[3]) return UNC_PATH; /* "//.foo" or "//?foo" */
250 return UNC_DOT_PATH; /* "//." or "//?" */
252 else
254 if (!path[0] || path[1] != ':') return RELATIVE_PATH; /* "foo" */
255 if (IS_SEPARATOR(path[2])) return ABSOLUTE_DRIVE_PATH; /* "c:/foo" */
256 return RELATIVE_DRIVE_PATH; /* "c:foo" */
260 /***********************************************************************
261 * RtlIsDosDeviceName_U (NTDLL.@)
263 * Check if the given DOS path contains a DOS device name.
265 * Returns the length of the device name in the low word and its
266 * position in the high word (both in bytes, not WCHARs), or 0 if no
267 * device name is found.
269 ULONG WINAPI RtlIsDosDeviceName_U( PCWSTR dos_name )
271 static const WCHAR consoleW[] = {'\\','\\','.','\\','C','O','N',0};
272 static const WCHAR auxW[] = {'A','U','X'};
273 static const WCHAR comW[] = {'C','O','M'};
274 static const WCHAR conW[] = {'C','O','N'};
275 static const WCHAR lptW[] = {'L','P','T'};
276 static const WCHAR nulW[] = {'N','U','L'};
277 static const WCHAR prnW[] = {'P','R','N'};
279 const WCHAR *start, *end, *p;
281 switch(RtlDetermineDosPathNameType_U( dos_name ))
283 case INVALID_PATH:
284 case UNC_PATH:
285 return 0;
286 case DEVICE_PATH:
287 if (!strcmpiW( dos_name, consoleW ))
288 return MAKELONG( sizeof(conW), 4 * sizeof(WCHAR) ); /* 4 is length of \\.\ prefix */
289 return 0;
290 case ABSOLUTE_DRIVE_PATH:
291 case RELATIVE_DRIVE_PATH:
292 start = dos_name + 2; /* skip drive letter */
293 break;
294 default:
295 start = dos_name;
296 break;
299 /* find start of file name */
300 for (p = start; *p; p++) if (IS_SEPARATOR(*p)) start = p + 1;
302 /* truncate at extension and ':' */
303 for (end = start; *end; end++) if (*end == '.' || *end == ':') break;
304 end--;
306 /* remove trailing spaces */
307 while (end >= start && *end == ' ') end--;
309 /* now we have a potential device name between start and end, check it */
310 switch(end - start + 1)
312 case 3:
313 if (strncmpiW( start, auxW, 3 ) &&
314 strncmpiW( start, conW, 3 ) &&
315 strncmpiW( start, nulW, 3 ) &&
316 strncmpiW( start, prnW, 3 )) break;
317 return MAKELONG( 3 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
318 case 4:
319 if (strncmpiW( start, comW, 3 ) && strncmpiW( start, lptW, 3 )) break;
320 if (*end <= '0' || *end > '9') break;
321 return MAKELONG( 4 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
322 default: /* can't match anything */
323 break;
325 return 0;
328 /**************************************************************************
329 * RtlDosPathNameToNtPathName_U_WithStatus [NTDLL.@]
331 * dos_path: a DOS path name (fully qualified or not)
332 * ntpath: pointer to a UNICODE_STRING to hold the converted
333 * path name
334 * file_part:will point (in ntpath) to the file part in the path
335 * cd: directory reference (optional)
337 * FIXME:
338 * + fill the cd structure
340 NTSTATUS WINAPI RtlDosPathNameToNtPathName_U_WithStatus(const WCHAR *dos_path, UNICODE_STRING *ntpath,
341 WCHAR **file_part, CURDIR *cd)
343 static const WCHAR global_prefix[] = {'\\','\\','?','\\'};
344 static const WCHAR global_prefix2[] = {'\\','?','?','\\'};
345 ULONG sz, offset;
346 WCHAR local[MAX_PATH];
347 LPWSTR ptr;
349 TRACE("(%s,%p,%p,%p)\n", debugstr_w(dos_path), ntpath, file_part, cd);
351 if (cd)
353 FIXME("Unsupported parameter\n");
354 memset(cd, 0, sizeof(*cd));
357 if (!dos_path || !*dos_path)
358 return STATUS_OBJECT_NAME_INVALID;
360 if (!memcmp(dos_path, global_prefix, sizeof(global_prefix)) ||
361 (!memcmp(dos_path, global_prefix2, sizeof(global_prefix2)) && dos_path[4]))
363 ntpath->Length = strlenW(dos_path) * sizeof(WCHAR);
364 ntpath->MaximumLength = ntpath->Length + sizeof(WCHAR);
365 ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
366 if (!ntpath->Buffer) return STATUS_NO_MEMORY;
367 memcpy( ntpath->Buffer, dos_path, ntpath->MaximumLength );
368 ntpath->Buffer[1] = '?'; /* change \\?\ to \??\ */
369 if (file_part)
371 if ((ptr = strrchrW( ntpath->Buffer, '\\' )) && ptr[1]) *file_part = ptr + 1;
372 else *file_part = NULL;
374 return STATUS_SUCCESS;
377 ptr = local;
378 sz = RtlGetFullPathName_U(dos_path, sizeof(local), ptr, file_part);
379 if (sz == 0) return STATUS_OBJECT_NAME_INVALID;
381 if (sz > sizeof(local))
383 if (!(ptr = RtlAllocateHeap(GetProcessHeap(), 0, sz))) return STATUS_NO_MEMORY;
384 sz = RtlGetFullPathName_U(dos_path, sz, ptr, file_part);
386 sz += (1 /* NUL */ + 4 /* unc\ */ + 4 /* \??\ */) * sizeof(WCHAR);
387 if (sz > MAXWORD)
389 if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
390 return STATUS_OBJECT_NAME_INVALID;
393 ntpath->MaximumLength = sz;
394 ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
395 if (!ntpath->Buffer)
397 if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
398 return STATUS_NO_MEMORY;
401 strcpyW(ntpath->Buffer, NTDosPrefixW);
402 switch (RtlDetermineDosPathNameType_U(ptr))
404 case UNC_PATH: /* \\foo */
405 offset = 2;
406 strcatW(ntpath->Buffer, UncPfxW);
407 break;
408 case DEVICE_PATH: /* \\.\foo */
409 offset = 4;
410 break;
411 default:
412 offset = 0;
413 break;
416 strcatW(ntpath->Buffer, ptr + offset);
417 ntpath->Length = strlenW(ntpath->Buffer) * sizeof(WCHAR);
419 if (file_part && *file_part)
420 *file_part = ntpath->Buffer + ntpath->Length / sizeof(WCHAR) - strlenW(*file_part);
422 /* FIXME: cd filling */
424 if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
425 return STATUS_SUCCESS;
428 /**************************************************************************
429 * RtlDosPathNameToNtPathName_U [NTDLL.@]
431 * See RtlDosPathNameToNtPathName_U_WithStatus
433 BOOLEAN WINAPI RtlDosPathNameToNtPathName_U(PCWSTR dos_path,
434 PUNICODE_STRING ntpath,
435 PWSTR* file_part,
436 CURDIR* cd)
438 return RtlDosPathNameToNtPathName_U_WithStatus(dos_path, ntpath, file_part, cd) == STATUS_SUCCESS;
441 /**************************************************************************
442 * RtlDosPathNameToRelativeNtPathName_U_WithStatus [NTDLL.@]
444 * See RtlDosPathNameToNtPathName_U_WithStatus (except the last parameter)
446 NTSTATUS WINAPI RtlDosPathNameToRelativeNtPathName_U_WithStatus(const WCHAR *dos_path,
447 UNICODE_STRING *ntpath, WCHAR **file_part, RTL_RELATIVE_NAME *relative)
449 TRACE("(%s,%p,%p,%p)\n", debugstr_w(dos_path), ntpath, file_part, relative);
451 if (relative)
453 FIXME("Unsupported parameter\n");
454 memset(relative, 0, sizeof(*relative));
457 /* FIXME: fill parameter relative */
459 return RtlDosPathNameToNtPathName_U_WithStatus(dos_path, ntpath, file_part, NULL);
462 /**************************************************************************
463 * RtlReleaseRelativeName [NTDLL.@]
465 void WINAPI RtlReleaseRelativeName(RTL_RELATIVE_NAME *relative)
469 /******************************************************************
470 * RtlDosSearchPath_U
472 * Searches a file of name 'name' into a ';' separated list of paths
473 * (stored in paths)
474 * Doesn't seem to search elsewhere than the paths list
475 * Stores the result in buffer (file_part will point to the position
476 * of the file name in the buffer)
477 * FIXME:
478 * - how long shall the paths be ??? (MAX_PATH or larger with \\?\ constructs ???)
480 ULONG WINAPI RtlDosSearchPath_U(LPCWSTR paths, LPCWSTR search, LPCWSTR ext,
481 ULONG buffer_size, LPWSTR buffer,
482 LPWSTR* file_part)
484 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U(search);
485 ULONG len = 0;
487 if (type == RELATIVE_PATH)
489 ULONG allocated = 0, needed, filelen;
490 WCHAR *name = NULL;
492 filelen = 1 /* for \ */ + strlenW(search) + 1 /* \0 */;
494 /* Windows only checks for '.' without worrying about path components */
495 if (strchrW( search, '.' )) ext = NULL;
496 if (ext != NULL) filelen += strlenW(ext);
498 while (*paths)
500 LPCWSTR ptr;
502 for (needed = 0, ptr = paths; *ptr != 0 && *ptr++ != ';'; needed++);
503 if (needed + filelen > allocated)
505 if (!name) name = RtlAllocateHeap(GetProcessHeap(), 0,
506 (needed + filelen) * sizeof(WCHAR));
507 else
509 WCHAR *newname = RtlReAllocateHeap(GetProcessHeap(), 0, name,
510 (needed + filelen) * sizeof(WCHAR));
511 if (!newname) RtlFreeHeap(GetProcessHeap(), 0, name);
512 name = newname;
514 if (!name) return 0;
515 allocated = needed + filelen;
517 memmove(name, paths, needed * sizeof(WCHAR));
518 /* append '\\' if none is present */
519 if (needed > 0 && name[needed - 1] != '\\') name[needed++] = '\\';
520 strcpyW(&name[needed], search);
521 if (ext) strcatW(&name[needed], ext);
522 if (RtlDoesFileExists_U(name))
524 len = RtlGetFullPathName_U(name, buffer_size, buffer, file_part);
525 break;
527 paths = ptr;
529 RtlFreeHeap(GetProcessHeap(), 0, name);
531 else if (RtlDoesFileExists_U(search))
533 len = RtlGetFullPathName_U(search, buffer_size, buffer, file_part);
536 return len;
540 /******************************************************************
541 * collapse_path
543 * Helper for RtlGetFullPathName_U.
544 * Get rid of . and .. components in the path.
546 static inline void collapse_path( WCHAR *path, UINT mark )
548 WCHAR *p, *next;
550 /* convert every / into a \ */
551 for (p = path; *p; p++) if (*p == '/') *p = '\\';
553 /* collapse duplicate backslashes */
554 next = path + max( 1, mark );
555 for (p = next; *p; p++) if (*p != '\\' || next[-1] != '\\') *next++ = *p;
556 *next = 0;
558 p = path + mark;
559 while (*p)
561 if (*p == '.')
563 switch(p[1])
565 case '\\': /* .\ component */
566 next = p + 2;
567 memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
568 continue;
569 case 0: /* final . */
570 if (p > path + mark) p--;
571 *p = 0;
572 continue;
573 case '.':
574 if (p[2] == '\\') /* ..\ component */
576 next = p + 3;
577 if (p > path + mark)
579 p--;
580 while (p > path + mark && p[-1] != '\\') p--;
582 memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
583 continue;
585 else if (!p[2]) /* final .. */
587 if (p > path + mark)
589 p--;
590 while (p > path + mark && p[-1] != '\\') p--;
591 if (p > path + mark) p--;
593 *p = 0;
594 continue;
596 break;
599 /* skip to the next component */
600 while (*p && *p != '\\') p++;
601 if (*p == '\\')
603 /* remove last dot in previous dir name */
604 if (p > path + mark && p[-1] == '.') memmove( p-1, p, (strlenW(p) + 1) * sizeof(WCHAR) );
605 else p++;
609 /* remove trailing spaces and dots (yes, Windows really does that, don't ask) */
610 while (p > path + mark && (p[-1] == ' ' || p[-1] == '.')) p--;
611 *p = 0;
615 /******************************************************************
616 * skip_unc_prefix
618 * Skip the \\share\dir\ part of a file name. Helper for RtlGetFullPathName_U.
620 static const WCHAR *skip_unc_prefix( const WCHAR *ptr )
622 ptr += 2;
623 while (*ptr && !IS_SEPARATOR(*ptr)) ptr++; /* share name */
624 while (IS_SEPARATOR(*ptr)) ptr++;
625 while (*ptr && !IS_SEPARATOR(*ptr)) ptr++; /* dir name */
626 while (IS_SEPARATOR(*ptr)) ptr++;
627 return ptr;
631 /******************************************************************
632 * get_full_path_helper
634 * Helper for RtlGetFullPathName_U
635 * Note: name and buffer are allowed to point to the same memory spot
637 static ULONG get_full_path_helper(LPCWSTR name, LPWSTR buffer, ULONG size)
639 ULONG reqsize = 0, mark = 0, dep = 0, deplen;
640 LPWSTR ins_str = NULL;
641 LPCWSTR ptr;
642 const UNICODE_STRING* cd;
643 WCHAR tmp[4];
645 /* return error if name only consists of spaces */
646 for (ptr = name; *ptr; ptr++) if (*ptr != ' ') break;
647 if (!*ptr) return 0;
649 RtlAcquirePebLock();
651 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
652 cd = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
653 else
654 cd = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
656 switch (RtlDetermineDosPathNameType_U(name))
658 case UNC_PATH: /* \\foo */
659 ptr = skip_unc_prefix( name );
660 mark = (ptr - name);
661 break;
663 case DEVICE_PATH: /* \\.\foo */
664 mark = 4;
665 break;
667 case ABSOLUTE_DRIVE_PATH: /* c:\foo */
668 reqsize = sizeof(WCHAR);
669 tmp[0] = name[0];
670 ins_str = tmp;
671 dep = 1;
672 mark = 3;
673 break;
675 case RELATIVE_DRIVE_PATH: /* c:foo */
676 dep = 2;
677 if (toupperW(name[0]) != toupperW(cd->Buffer[0]) || cd->Buffer[1] != ':')
679 UNICODE_STRING var, val;
681 tmp[0] = '=';
682 tmp[1] = name[0];
683 tmp[2] = ':';
684 tmp[3] = '\0';
685 var.Length = 3 * sizeof(WCHAR);
686 var.MaximumLength = 4 * sizeof(WCHAR);
687 var.Buffer = tmp;
688 val.Length = 0;
689 val.MaximumLength = size;
690 val.Buffer = RtlAllocateHeap(GetProcessHeap(), 0, size);
692 switch (RtlQueryEnvironmentVariable_U(NULL, &var, &val))
694 case STATUS_SUCCESS:
695 /* FIXME: Win2k seems to check that the environment variable actually points
696 * to an existing directory. If not, root of the drive is used
697 * (this seems also to be the only spot in RtlGetFullPathName that the
698 * existence of a part of a path is checked)
700 /* fall through */
701 case STATUS_BUFFER_TOO_SMALL:
702 reqsize = val.Length + sizeof(WCHAR); /* append trailing '\\' */
703 val.Buffer[val.Length / sizeof(WCHAR)] = '\\';
704 ins_str = val.Buffer;
705 break;
706 case STATUS_VARIABLE_NOT_FOUND:
707 reqsize = 3 * sizeof(WCHAR);
708 tmp[0] = name[0];
709 tmp[1] = ':';
710 tmp[2] = '\\';
711 ins_str = tmp;
712 RtlFreeHeap(GetProcessHeap(), 0, val.Buffer);
713 break;
714 default:
715 ERR("Unsupported status code\n");
716 RtlFreeHeap(GetProcessHeap(), 0, val.Buffer);
717 break;
719 mark = 3;
720 break;
722 /* fall through */
724 case RELATIVE_PATH: /* foo */
725 reqsize = cd->Length;
726 ins_str = cd->Buffer;
727 if (cd->Buffer[1] != ':')
729 ptr = skip_unc_prefix( cd->Buffer );
730 mark = ptr - cd->Buffer;
732 else mark = 3;
733 break;
735 case ABSOLUTE_PATH: /* \xxx */
736 if (name[0] == '/') /* may be a Unix path */
738 const WCHAR *ptr = name;
739 int drive = find_drive_rootW( &ptr );
740 if (drive != -1)
742 reqsize = 3 * sizeof(WCHAR);
743 tmp[0] = 'A' + drive;
744 tmp[1] = ':';
745 tmp[2] = '\\';
746 ins_str = tmp;
747 mark = 3;
748 dep = ptr - name;
749 break;
752 if (cd->Buffer[1] == ':')
754 reqsize = 2 * sizeof(WCHAR);
755 tmp[0] = cd->Buffer[0];
756 tmp[1] = ':';
757 ins_str = tmp;
758 mark = 3;
760 else
762 ptr = skip_unc_prefix( cd->Buffer );
763 reqsize = (ptr - cd->Buffer) * sizeof(WCHAR);
764 mark = reqsize / sizeof(WCHAR);
765 ins_str = cd->Buffer;
767 break;
769 case UNC_DOT_PATH: /* \\. */
770 reqsize = 4 * sizeof(WCHAR);
771 dep = 3;
772 tmp[0] = '\\';
773 tmp[1] = '\\';
774 tmp[2] = '.';
775 tmp[3] = '\\';
776 ins_str = tmp;
777 mark = 4;
778 break;
780 case INVALID_PATH:
781 goto done;
784 /* enough space ? */
785 deplen = strlenW(name + dep) * sizeof(WCHAR);
786 if (reqsize + deplen + sizeof(WCHAR) > size)
788 /* not enough space, return need size (including terminating '\0') */
789 reqsize += deplen + sizeof(WCHAR);
790 goto done;
793 memmove(buffer + reqsize / sizeof(WCHAR), name + dep, deplen + sizeof(WCHAR));
794 if (reqsize) memcpy(buffer, ins_str, reqsize);
796 if (ins_str != tmp && ins_str != cd->Buffer)
797 RtlFreeHeap(GetProcessHeap(), 0, ins_str);
799 collapse_path( buffer, mark );
800 reqsize = strlenW(buffer) * sizeof(WCHAR);
802 done:
803 RtlReleasePebLock();
804 return reqsize;
807 /******************************************************************
808 * RtlGetFullPathName_U (NTDLL.@)
810 * Returns the number of bytes written to buffer (not including the
811 * terminating NULL) if the function succeeds, or the required number of bytes
812 * (including the terminating NULL) if the buffer is too small.
814 * file_part will point to the filename part inside buffer (except if we use
815 * DOS device name, in which case file_in_buf is NULL)
818 DWORD WINAPI RtlGetFullPathName_U(const WCHAR* name, ULONG size, WCHAR* buffer,
819 WCHAR** file_part)
821 WCHAR* ptr;
822 DWORD dosdev;
823 DWORD reqsize;
825 TRACE("(%s %u %p %p)\n", debugstr_w(name), size, buffer, file_part);
827 if (!name || !*name) return 0;
829 if (file_part) *file_part = NULL;
831 /* check for DOS device name */
832 dosdev = RtlIsDosDeviceName_U(name);
833 if (dosdev)
835 DWORD offset = HIWORD(dosdev) / sizeof(WCHAR); /* get it in WCHARs, not bytes */
836 DWORD sz = LOWORD(dosdev); /* in bytes */
838 if (8 + sz + 2 > size) return sz + 10;
839 strcpyW(buffer, DeviceRootW);
840 memmove(buffer + 4, name + offset, sz);
841 buffer[4 + sz / sizeof(WCHAR)] = '\0';
842 /* file_part isn't set in this case */
843 return sz + 8;
846 reqsize = get_full_path_helper(name, buffer, size);
847 if (!reqsize) return 0;
848 if (reqsize > size)
850 LPWSTR tmp = RtlAllocateHeap(GetProcessHeap(), 0, reqsize);
851 reqsize = get_full_path_helper(name, tmp, reqsize);
852 if (reqsize + sizeof(WCHAR) > size) /* it may have worked the second time */
854 RtlFreeHeap(GetProcessHeap(), 0, tmp);
855 return reqsize + sizeof(WCHAR);
857 memcpy( buffer, tmp, reqsize + sizeof(WCHAR) );
858 RtlFreeHeap(GetProcessHeap(), 0, tmp);
861 /* find file part */
862 if (file_part && (ptr = strrchrW(buffer, '\\')) != NULL && ptr >= buffer + 2 && *++ptr)
863 *file_part = ptr;
864 return reqsize;
867 /*************************************************************************
868 * RtlGetLongestNtPathLength [NTDLL.@]
870 * Get the longest allowed path length
872 * PARAMS
873 * None.
875 * RETURNS
876 * The longest allowed path length (277 characters under Win2k).
878 DWORD WINAPI RtlGetLongestNtPathLength(void)
880 return MAX_NT_PATH_LENGTH;
883 /******************************************************************
884 * RtlIsNameLegalDOS8Dot3 (NTDLL.@)
886 * Returns TRUE iff unicode is a valid DOS (8+3) name.
887 * If the name is valid, oem gets filled with the corresponding OEM string
888 * spaces is set to TRUE if unicode contains spaces
890 BOOLEAN WINAPI RtlIsNameLegalDOS8Dot3( const UNICODE_STRING *unicode,
891 OEM_STRING *oem, BOOLEAN *spaces )
893 static const char illegal[] = "*?<>|\"+=,;[]:/\\\345";
894 int dot = -1;
895 int i;
896 char buffer[12];
897 OEM_STRING oem_str;
898 BOOLEAN got_space = FALSE;
900 if (!oem)
902 oem_str.Length = sizeof(buffer);
903 oem_str.MaximumLength = sizeof(buffer);
904 oem_str.Buffer = buffer;
905 oem = &oem_str;
907 if (RtlUpcaseUnicodeStringToCountedOemString( oem, unicode, FALSE ) != STATUS_SUCCESS)
908 return FALSE;
910 if (oem->Length > 12) return FALSE;
912 /* a starting . is invalid, except for . and .. */
913 if (oem->Length > 0 && oem->Buffer[0] == '.')
915 if (oem->Length != 1 && (oem->Length != 2 || oem->Buffer[1] != '.')) return FALSE;
916 if (spaces) *spaces = FALSE;
917 return TRUE;
920 for (i = 0; i < oem->Length; i++)
922 switch (oem->Buffer[i])
924 case ' ':
925 /* leading/trailing spaces not allowed */
926 if (!i || i == oem->Length-1 || oem->Buffer[i+1] == '.') return FALSE;
927 got_space = TRUE;
928 break;
929 case '.':
930 if (dot != -1) return FALSE;
931 dot = i;
932 break;
933 default:
934 if (strchr(illegal, oem->Buffer[i])) return FALSE;
935 break;
938 /* check file part is shorter than 8, extension shorter than 3
939 * dot cannot be last in string
941 if (dot == -1)
943 if (oem->Length > 8) return FALSE;
945 else
947 if (dot > 8 || (oem->Length - dot > 4) || dot == oem->Length - 1) return FALSE;
949 if (spaces) *spaces = got_space;
950 return TRUE;
953 /******************************************************************
954 * RtlGetCurrentDirectory_U (NTDLL.@)
957 ULONG WINAPI RtlGetCurrentDirectory_U(ULONG buflen, LPWSTR buf)
959 UNICODE_STRING* us;
960 ULONG len;
962 TRACE("(%u %p)\n", buflen, buf);
964 RtlAcquirePebLock();
966 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
967 us = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
968 else
969 us = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
971 len = us->Length / sizeof(WCHAR);
972 if (us->Buffer[len - 1] == '\\' && us->Buffer[len - 2] != ':')
973 len--;
975 if (buflen / sizeof(WCHAR) > len)
977 memcpy(buf, us->Buffer, len * sizeof(WCHAR));
978 buf[len] = '\0';
980 else
982 len++;
985 RtlReleasePebLock();
987 return len * sizeof(WCHAR);
990 /******************************************************************
991 * RtlSetCurrentDirectory_U (NTDLL.@)
994 NTSTATUS WINAPI RtlSetCurrentDirectory_U(const UNICODE_STRING* dir)
996 FILE_FS_DEVICE_INFORMATION device_info;
997 OBJECT_ATTRIBUTES attr;
998 UNICODE_STRING newdir;
999 IO_STATUS_BLOCK io;
1000 CURDIR *curdir;
1001 HANDLE handle;
1002 NTSTATUS nts;
1003 ULONG size;
1004 PWSTR ptr;
1006 newdir.Buffer = NULL;
1008 RtlAcquirePebLock();
1010 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
1011 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
1012 else
1013 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
1015 if (!RtlDosPathNameToNtPathName_U( dir->Buffer, &newdir, NULL, NULL ))
1017 nts = STATUS_OBJECT_NAME_INVALID;
1018 goto out;
1021 attr.Length = sizeof(attr);
1022 attr.RootDirectory = 0;
1023 attr.Attributes = OBJ_CASE_INSENSITIVE;
1024 attr.ObjectName = &newdir;
1025 attr.SecurityDescriptor = NULL;
1026 attr.SecurityQualityOfService = NULL;
1028 nts = NtOpenFile( &handle, FILE_TRAVERSE | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE,
1029 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1030 if (nts != STATUS_SUCCESS) goto out;
1032 /* don't keep the directory handle open on removable media */
1033 if (!NtQueryVolumeInformationFile( handle, &io, &device_info,
1034 sizeof(device_info), FileFsDeviceInformation ) &&
1035 (device_info.Characteristics & FILE_REMOVABLE_MEDIA))
1037 NtClose( handle );
1038 handle = 0;
1041 if (curdir->Handle) NtClose( curdir->Handle );
1042 curdir->Handle = handle;
1044 /* append trailing \ if missing */
1045 size = newdir.Length / sizeof(WCHAR);
1046 ptr = newdir.Buffer;
1047 ptr += 4; /* skip \??\ prefix */
1048 size -= 4;
1049 if (size && ptr[size - 1] != '\\') ptr[size++] = '\\';
1051 /* convert \??\UNC\ path to \\ prefix */
1052 if (size >= 4 && !strncmpiW(ptr, UncPfxW, 4))
1054 ptr += 2;
1055 size -= 2;
1056 *ptr = '\\';
1059 memcpy( curdir->DosPath.Buffer, ptr, size * sizeof(WCHAR));
1060 curdir->DosPath.Buffer[size] = 0;
1061 curdir->DosPath.Length = size * sizeof(WCHAR);
1063 TRACE( "curdir now %s %p\n", debugstr_w(curdir->DosPath.Buffer), curdir->Handle );
1065 out:
1066 RtlFreeUnicodeString( &newdir );
1067 RtlReleasePebLock();
1068 return nts;
1072 /******************************************************************
1073 * wine_unix_to_nt_file_name (NTDLL.@) Not a Windows API
1075 NTSTATUS CDECL wine_unix_to_nt_file_name( const ANSI_STRING *name, UNICODE_STRING *nt )
1077 static const WCHAR prefixW[] = {'\\','?','?','\\','A',':','\\'};
1078 static const WCHAR unix_prefixW[] = {'\\','?','?','\\','u','n','i','x'};
1079 unsigned int lenW, lenA = name->Length;
1080 const char *path = name->Buffer;
1081 char *cwd;
1082 WCHAR *p;
1083 NTSTATUS status;
1084 int drive;
1086 if (!lenA || path[0] != '/')
1088 char *newcwd, *end;
1089 size_t size;
1091 if ((status = DIR_get_unix_cwd( &cwd )) != STATUS_SUCCESS) return status;
1093 size = strlen(cwd) + lenA + 1;
1094 if (!(newcwd = RtlReAllocateHeap( GetProcessHeap(), 0, cwd, size )))
1096 status = STATUS_NO_MEMORY;
1097 goto done;
1099 cwd = newcwd;
1100 end = cwd + strlen(cwd);
1101 if (end > cwd && end[-1] != '/') *end++ = '/';
1102 memcpy( end, path, lenA );
1103 lenA += end - cwd;
1104 path = cwd;
1106 status = find_drive_rootA( &path, lenA, &drive );
1107 lenA -= (path - cwd);
1109 else
1111 cwd = NULL;
1112 status = find_drive_rootA( &path, lenA, &drive );
1113 lenA -= (path - name->Buffer);
1116 if (status != STATUS_SUCCESS)
1118 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1120 lenW = ntdll_umbstowcs( 0, path, lenA, NULL, 0 );
1121 nt->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1122 (lenW + 1) * sizeof(WCHAR) + sizeof(unix_prefixW) );
1123 if (nt->Buffer == NULL)
1125 status = STATUS_NO_MEMORY;
1126 goto done;
1128 memcpy( nt->Buffer, unix_prefixW, sizeof(unix_prefixW) );
1129 ntdll_umbstowcs( 0, path, lenA, nt->Buffer + ARRAY_SIZE( unix_prefixW ), lenW );
1130 lenW += ARRAY_SIZE( unix_prefixW );
1131 nt->Buffer[lenW] = 0;
1132 nt->Length = lenW * sizeof(WCHAR);
1133 nt->MaximumLength = nt->Length + sizeof(WCHAR);
1134 for (p = nt->Buffer + ARRAY_SIZE( unix_prefixW ); *p; p++) if (*p == '/') *p = '\\';
1135 status = STATUS_SUCCESS;
1137 goto done;
1139 while (lenA && path[0] == '/') { lenA--; path++; }
1141 lenW = ntdll_umbstowcs( 0, path, lenA, NULL, 0 );
1142 if (!(nt->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1143 (lenW + 1) * sizeof(WCHAR) + sizeof(prefixW) )))
1145 status = STATUS_NO_MEMORY;
1146 goto done;
1149 memcpy( nt->Buffer, prefixW, sizeof(prefixW) );
1150 nt->Buffer[4] += drive;
1151 ntdll_umbstowcs( 0, path, lenA, nt->Buffer + ARRAY_SIZE( prefixW ), lenW );
1152 lenW += ARRAY_SIZE( prefixW );
1153 nt->Buffer[lenW] = 0;
1154 nt->Length = lenW * sizeof(WCHAR);
1155 nt->MaximumLength = nt->Length + sizeof(WCHAR);
1156 for (p = nt->Buffer + ARRAY_SIZE( prefixW ); *p; p++) if (*p == '/') *p = '\\';
1158 done:
1159 RtlFreeHeap( GetProcessHeap(), 0, cwd );
1160 return status;