| 1 | /** |
| 2 | * This file has no copyright assigned and is placed in the Public Domain. |
| 3 | * This file is part of the mingw-w64 runtime package. |
| 4 | * No warranty is given; refer to the file DISCLAIMER.PD within this package. |
| 5 | */ |
| 6 | |
| 7 | #include <sys/stat.h> |
| 8 | #include <stdlib.h> |
| 9 | #include "__mingw_fix_stat.h" |
| 10 | |
| 11 | /** |
| 12 | * Returns _path without trailing slash if any |
| 13 | * |
| 14 | * - if _path has no trailing slash, the function returns it |
| 15 | * - if _path has a trailing slash, but is of the form C:/, then it returns it |
| 16 | * - otherwise, the function creates a new string, which is a copy of _path |
| 17 | * without the trailing slash. It is then the responsibility of the caller |
| 18 | * to free it. |
| 19 | */ |
| 20 | |
| 21 | wchar_t* __mingw_fix_wstat_path (const wchar_t* _path) |
| 22 | { |
| 23 | size_t len; |
| 24 | wchar_t *p; |
| 25 | |
| 26 | p = (wchar_t*)_path; |
| 27 | |
| 28 | if (_path && *_path) { |
| 29 | len = wcslen (_path); |
| 30 | |
| 31 | /* Ignore X:\ */ |
| 32 | |
| 33 | if (len <= 1 || ((len == 2 || len == 3) && _path[1] == L':')) |
| 34 | return p; |
| 35 | |
| 36 | /* Check UNC \\abc\<name>\ */ |
| 37 | if ((_path[0] == L'\\' || _path[0] == L'/') |
| 38 | 	&& (_path[1] == L'\\' || _path[1] == L'/')) |
| 39 | { |
| 40 | 	const wchar_t *r = &_path[2]; |
| 41 | 	while (*r != 0 && *r != L'\\' && *r != L'/') |
| 42 | 	 ++r; |
| 43 | 	if (*r != 0) |
| 44 | 	 ++r; |
| 45 | 	if (*r == 0) |
| 46 | 	 return p; |
| 47 | 	while (*r != 0 && *r != L'\\' && *r != L'/') |
| 48 | 	 ++r; |
| 49 | 	if (*r != 0) |
| 50 | 	 ++r; |
| 51 | 	if (*r == 0) |
| 52 | 	 return p; |
| 53 | } |
| 54 | |
| 55 | if (_path[len - 1] == L'/' || _path[len - 1] == L'\\') |
| 56 | { |
| 57 | 	p = (wchar_t*)malloc (len * sizeof(wchar_t)); |
| 58 | 	if (p == NULL) |
| 59 | 	 return NULL; /* malloc has set errno. */ |
| 60 | 	memcpy (p, _path, (len - 1) * sizeof(wchar_t)); |
| 61 | 	p[len - 1] = L'\0'; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | return p; |
| 66 | } |