*: Updated copyright to 2009 and normalized name & email.
[kbuild-mirror.git] / src / lib / nt_fullpath.c
blob31c30188ef3a269d65f2478fb40f11493fcccebb
1 /* $Id$ */
2 /** @file
3 * fixcase - fixes the case of paths, windows specific.
4 */
6 /*
7 * Copyright (c) 2004-2009 knut st. osmundsen <bird-kBuild-spamix@anduin.net>
9 * This file is part of kBuild.
11 * kBuild is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
16 * kBuild is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with kBuild. If not, see <http://www.gnu.org/licenses/>
26 /*******************************************************************************
27 * Header Files *
28 *******************************************************************************/
29 #include <Windows.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <direct.h>
37 * Corrects the case of a path.
38 * Expects a fullpath!
39 * Added by bird for the $(abspath ) function and w32ify
41 static void w32_fixcase(char *pszPath)
43 static char s_szLast[260];
44 size_t cchLast;
46 #ifndef NDEBUG
47 # define my_assert(expr) \
48 do { \
49 if (!(expr)) { \
50 printf("my_assert: %s, file %s, line %d\npszPath=%s\npsz=%s\n", \
51 #expr, __FILE__, __LINE__, pszPath, psz); \
52 __debugbreak(); \
53 exit(1); \
54 } \
55 } while (0)
56 #else
57 # define my_assert(expr) do {} while (0)
58 #endif
60 char *psz = pszPath;
61 if (*psz == '/' || *psz == '\\')
63 if (psz[1] == '/' || psz[1] == '\\')
65 /* UNC */
66 my_assert(psz[1] == '/' || psz[1] == '\\');
67 my_assert(psz[2] != '/' && psz[2] != '\\');
69 /* skip server name */
70 psz += 2;
71 while (*psz != '\\' && *psz != '/')
73 if (!*psz)
74 return;
75 *psz++ = toupper(*psz);
78 /* skip the share name */
79 psz++;
80 my_assert(*psz != '/' && *psz != '\\');
81 while (*psz != '\\' && *psz != '/')
83 if (!*psz)
84 return;
85 *psz++ = toupper(*psz);
87 my_assert(*psz == '/' || *psz == '\\');
88 psz++;
90 else
92 /* Unix spec */
93 psz++;
96 else
98 /* Drive letter */
99 my_assert(psz[1] == ':');
100 *psz = toupper(*psz);
101 my_assert(psz[0] >= 'A' && psz[0] <= 'Z');
102 my_assert(psz[2] == '/' || psz[2] == '\\');
103 psz += 3;
107 * Try make use of the result from the previous call.
108 * This is ignorant to slashes and similar, but may help even so.
110 if ( s_szLast[0] == pszPath[0]
111 && (psz - pszPath == 1 || s_szLast[1] == pszPath[1])
112 && (psz - pszPath <= 2 || s_szLast[2] == pszPath[2])
115 char *pszLast = &s_szLast[psz - pszPath];
116 char *pszCur = psz;
117 char *pszSrc0 = pszLast;
118 char *pszDst0 = pszCur;
119 for (;;)
121 const char ch1 = *pszCur;
122 const char ch2 = *pszLast;
123 if ( ch1 != ch2
124 && (ch1 != '\\' || ch2 != '/')
125 && (ch1 != '/' || ch2 != '\\')
126 && tolower(ch1) != tolower(ch2)
127 && toupper(ch1) != toupper(ch2))
128 break;
129 if (ch1 == '/' || ch1 == '\\')
131 psz = pszCur + 1;
132 *pszLast = ch1; /* preserve the slashes */
134 else if (ch1 == '\0')
136 psz = pszCur;
137 break;
139 pszCur++;
140 pszLast++;
142 if (psz != pszDst0)
143 memcpy(pszDst0, pszSrc0, psz - pszDst0);
147 * Pointing to the first char after the unc or drive specifier,
148 * or in case of a cache hit, the first non-matching char (following a slash of course).
150 while (*psz)
152 WIN32_FIND_DATA FindFileData;
153 HANDLE hDir;
154 char chSaved0;
155 char chSaved1;
156 char *pszEnd;
157 int iLongNameDiff;
158 size_t cch;
161 /* find the end of the component. */
162 pszEnd = psz;
163 while (*pszEnd && *pszEnd != '/' && *pszEnd != '\\')
164 pszEnd++;
165 cch = pszEnd - psz;
167 /* replace the end with "?\0" */
168 chSaved0 = pszEnd[0];
169 chSaved1 = pszEnd[1];
170 pszEnd[0] = '?';
171 pszEnd[1] = '\0';
173 /* find the right filename. */
174 hDir = FindFirstFile(pszPath, &FindFileData);
175 pszEnd[1] = chSaved1;
176 if (!hDir)
178 cchLast = psz - pszPath;
179 memcpy(s_szLast, pszPath, cchLast + 1);
180 s_szLast[cchLast + 1] = '\0';
181 pszEnd[0] = chSaved0;
182 return;
184 pszEnd[0] = '\0';
185 while ( (iLongNameDiff = stricmp(FindFileData.cFileName, psz))
186 && stricmp(FindFileData.cAlternateFileName, psz))
188 if (!FindNextFile(hDir, &FindFileData))
190 cchLast = psz - pszPath;
191 memcpy(s_szLast, pszPath, cchLast + 1);
192 s_szLast[cchLast + 1] = '\0';
193 pszEnd[0] = chSaved0;
194 return;
197 pszEnd[0] = chSaved0;
198 if ( iLongNameDiff /* matched the short name */
199 || !FindFileData.cAlternateFileName[0] /* no short name */
200 || !memchr(psz, ' ', cch)) /* no spaces in the matching name */
201 memcpy(psz, !iLongNameDiff ? FindFileData.cFileName : FindFileData.cAlternateFileName, cch);
202 else
204 /* replace spacy name with the short name. */
205 const size_t cchAlt = strlen(FindFileData.cAlternateFileName);
206 const size_t cchDelta = cch - cchAlt;
207 my_assert(cchAlt > 0);
208 if (!cchDelta)
209 memcpy(psz, FindFileData.cAlternateFileName, cch);
210 else
212 size_t cbLeft = strlen(pszEnd) + 1;
213 if ((psz - pszPath) + cbLeft + cchAlt <= _MAX_PATH)
215 memmove(psz + cchAlt, pszEnd, cbLeft);
216 pszEnd -= cchDelta;
217 memcpy(psz, FindFileData.cAlternateFileName, cchAlt);
219 else
220 fprintf(stderr, "kBuild: case & space fixed filename is growing too long (%d bytes)! '%s'\n",
221 (psz - pszPath) + cbLeft + cchAlt, pszPath);
224 my_assert(pszEnd[0] == chSaved0);
225 FindClose(hDir);
227 /* advance to the next component */
228 if (!chSaved0)
230 psz = pszEnd;
231 break;
233 psz = pszEnd + 1;
234 my_assert(*psz != '/' && *psz != '\\');
237 /* *psz == '\0', the end. */
238 cchLast = psz - pszPath;
239 memcpy(s_szLast, pszPath, cchLast + 1);
240 #undef my_assert
243 #define MY_FileNameInformation 9
244 typedef struct _MY_FILE_NAME_INFORMATION
246 ULONG FileNameLength;
247 WCHAR FileName[1];
248 } MY_FILE_NAME_INFORMATION, *PMY_FILE_NAME_INFORMATION;
250 #define MY_FileInternalInformation 6
251 typedef struct _MY_FILE_INTERNAL_INFORMATION {
252 LARGE_INTEGER IndexNumber;
253 } MY_FILE_INTERNAL_INFORMATION, *PMY_FILE_INTERNAL_INFORMATION;
255 #define MY_FileFsVolumeInformation 1
256 typedef struct _MY_FILE_FS_VOLUME_INFORMATION
258 LARGE_INTEGER VolumeCreationTime;
259 ULONG VolumeSerialNumber;
260 ULONG VolumeLabelLength;
261 BOOLEAN SupportsObjects;
262 WCHAR VolumeLabel[/*1*/128];
263 } MY_FILE_FS_VOLUME_INFORMATION, *PMY_FILE_FS_VOLUME_INFORMATION;
265 #define MY_FileFsAttributeInformation 5
266 typedef struct _MY_FILE_FS_ATTRIBUTE_INFORMATION
268 ULONG FileSystemAttributes;
269 LONG MaximumComponentNameLength;
270 ULONG FileSystemNameLength;
271 WCHAR FileSystemName[/*1*/64];
272 } MY_FILE_FS_ATTRIBUTE_INFORMATION, *PMY_FILE_FS_ATTRIBUTE_INFORMATION;
274 #define MY_FileFsDeviceInformation 4
275 typedef struct MY_FILE_FS_DEVICE_INFORMATION
277 ULONG DeviceType;
278 ULONG Characteristics;
279 } MY_FILE_FS_DEVICE_INFORMATION, *PMY_FILE_FS_DEVICE_INFORMATION;
280 #define MY_FILE_DEVICE_DISK 7
281 #define MY_FILE_DEVICE_DISK_FILE_SYSTEM 8
282 #define MY_FILE_DEVICE_FILE_SYSTEM 9
283 #define MY_FILE_DEVICE_VIRTUAL_DISK 36
286 typedef struct _IO_STATUS_BLOCK
288 union
290 LONG Status;
291 PVOID Pointer;
293 ULONG_PTR Information;
294 } MY_IO_STATUS_BLOCK, *PMY_IO_STATUS_BLOCK;
296 static BOOL g_fInitialized = FALSE;
297 static int g_afNtfsDrives['Z' - 'A' + 1];
298 static MY_FILE_FS_VOLUME_INFORMATION g_aVolumeInfo['Z' - 'A' + 1];
300 static LONG (NTAPI *g_pfnNtQueryInformationFile)(HANDLE FileHandle,
301 PMY_IO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation,
302 ULONG Length, ULONG FileInformationClass);
303 static LONG (NTAPI *g_pfnNtQueryVolumeInformationFile)(HANDLE FileHandle,
304 PMY_IO_STATUS_BLOCK IoStatusBlock, PVOID FsInformation,
305 ULONG Length, ULONG FsInformationClass);
309 nt_get_filename_info(const char *pszPath, char *pszFull, size_t cchFull)
311 static char abBuf[8192];
312 PMY_FILE_NAME_INFORMATION pFileNameInfo = (PMY_FILE_NAME_INFORMATION)abBuf;
313 PMY_FILE_FS_VOLUME_INFORMATION pFsVolInfo = (PMY_FILE_FS_VOLUME_INFORMATION)abBuf;
314 MY_IO_STATUS_BLOCK Ios;
315 LONG rcNt;
316 HANDLE hFile;
317 int cchOut;
318 char *psz;
319 int iDrv;
320 int rc;
323 * Check for NtQueryInformationFile the first time around.
325 if (!g_fInitialized)
327 g_fInitialized = TRUE;
328 if (!getenv("KMK_DONT_USE_NT_QUERY_INFORMATION_FILE"))
330 *(FARPROC *)&g_pfnNtQueryInformationFile =
331 GetProcAddress(LoadLibrary("ntdll.dll"), "NtQueryInformationFile");
332 *(FARPROC *)&g_pfnNtQueryVolumeInformationFile =
333 GetProcAddress(LoadLibrary("ntdll.dll"), "NtQueryVolumeInformationFile");
335 if ( g_pfnNtQueryInformationFile
336 && g_pfnNtQueryVolumeInformationFile)
338 unsigned i;
339 for (i = 0; i < sizeof(g_afNtfsDrives) / sizeof(g_afNtfsDrives[0]); i++ )
340 g_afNtfsDrives[i] = -1;
342 else
344 g_pfnNtQueryVolumeInformationFile = NULL;
345 g_pfnNtQueryInformationFile = NULL;
348 if (!g_pfnNtQueryInformationFile)
349 return -1;
352 * The FileNameInformation we get is relative to where the volume is mounted,
353 * so we have to extract the driveletter prefix ourselves.
355 * FIXME: This will probably not work for volumes mounted in NTFS sub-directories.
357 psz = pszFull;
358 if (pszPath[0] == '\\' || pszPath[0] == '/')
360 /* unc or root of volume */
361 if ( (pszPath[1] == '\\' || pszPath[1] == '/')
362 && (pszPath[2] != '\\' || pszPath[2] == '/'))
364 #if 0 /* don't bother with unc yet. */
365 /* unc - we get the server + name back */
366 *psz++ = '\\';
367 #endif
368 return -1;
370 /* root slash */
371 *psz++ = _getdrive() + 'A' - 1;
372 *psz++ = ':';
374 else if (pszPath[1] == ':' && isalpha(pszPath[0]))
376 /* drive letter */
377 *psz++ = toupper(pszPath[0]);
378 *psz++ = ':';
380 else
382 /* relative */
383 *psz++ = _getdrive() + 'A' - 1;
384 *psz++ = ':';
386 iDrv = *pszFull - 'A';
389 * Fat32 doesn't return filenames with the correct case, so restrict it
390 * to NTFS volumes for now.
392 if (g_afNtfsDrives[iDrv] == -1)
394 /* FSCTL_GET_REPARSE_POINT? Enumerate mount points? */
395 g_afNtfsDrives[iDrv] = 0;
396 psz[0] = '\\';
397 psz[1] = '\0';
398 #if 1
399 hFile = CreateFile(pszFull,
400 GENERIC_READ,
401 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
402 NULL,
403 OPEN_EXISTING,
404 FILE_FLAG_BACKUP_SEMANTICS,
405 NULL);
406 if (hFile != INVALID_HANDLE_VALUE)
408 PMY_FILE_FS_ATTRIBUTE_INFORMATION pFsAttrInfo = (PMY_FILE_FS_ATTRIBUTE_INFORMATION)abBuf;
410 memset(&Ios, 0, sizeof(Ios));
411 rcNt = g_pfnNtQueryVolumeInformationFile(hFile, &Ios, abBuf, sizeof(abBuf),
412 MY_FileFsAttributeInformation);
413 if ( rcNt >= 0
414 //&& pFsAttrInfo->FileSystemNameLength == 4
415 && pFsAttrInfo->FileSystemName[0] == 'N'
416 && pFsAttrInfo->FileSystemName[1] == 'T'
417 && pFsAttrInfo->FileSystemName[2] == 'F'
418 && pFsAttrInfo->FileSystemName[3] == 'S'
419 && pFsAttrInfo->FileSystemName[4] == '\0')
421 memset(&Ios, 0, sizeof(Ios));
422 rcNt = g_pfnNtQueryVolumeInformationFile(hFile, &Ios, &g_aVolumeInfo[iDrv],
423 sizeof(MY_FILE_FS_VOLUME_INFORMATION),
424 MY_FileFsVolumeInformation);
425 if (rcNt >= 0)
427 DWORD dwDriveType = GetDriveType(pszFull);
428 if ( dwDriveType == DRIVE_FIXED
429 || dwDriveType == DRIVE_RAMDISK)
430 g_afNtfsDrives[iDrv] = 1;
433 CloseHandle(hFile);
435 #else
437 char szFSName[32];
438 if ( GetVolumeInformation(pszFull,
439 NULL, 0, /* volume name */
440 NULL, /* serial number */
441 NULL, /* max component */
442 NULL, /* volume attribs */
443 szFSName,
444 sizeof(szFSName))
445 && !strcmp(szFSName, "NTFS"))
447 g_afNtfsDrives[iDrv] = 1;
450 #endif
452 if (!g_afNtfsDrives[iDrv])
453 return -1;
456 * Try open the path and query its file name information.
458 hFile = CreateFile(pszPath,
459 GENERIC_READ,
460 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
461 NULL,
462 OPEN_EXISTING,
463 FILE_FLAG_BACKUP_SEMANTICS,
464 NULL);
465 if (hFile != INVALID_HANDLE_VALUE)
467 /* check that the driver letter is correct first (reparse / symlink issues). */
468 memset(&Ios, 0, sizeof(Ios));
469 rcNt = g_pfnNtQueryVolumeInformationFile(hFile, &Ios, pFsVolInfo, sizeof(*pFsVolInfo), MY_FileFsVolumeInformation);
470 if (rcNt >= 0)
472 /** @todo do a quick search and try correct the drive letter? */
473 if ( pFsVolInfo->VolumeCreationTime.QuadPart == g_aVolumeInfo[iDrv].VolumeCreationTime.QuadPart
474 && pFsVolInfo->VolumeSerialNumber == g_aVolumeInfo[iDrv].VolumeSerialNumber)
476 memset(&Ios, 0, sizeof(Ios));
477 rcNt = g_pfnNtQueryInformationFile(hFile, &Ios, abBuf, sizeof(abBuf), MY_FileNameInformation);
478 if (rcNt >= 0)
480 cchOut = WideCharToMultiByte(CP_ACP, 0,
481 pFileNameInfo->FileName, pFileNameInfo->FileNameLength / sizeof(WCHAR),
482 psz, (int)(cchFull - (psz - pszFull) - 2), NULL, NULL);
483 if (cchOut > 0)
485 const char *pszEnd;
486 #if 0
487 /* upper case the server and share */
488 if (fUnc)
490 for (psz++; *psz != '/' && *psz != '\\'; psz++)
491 *psz = toupper(*psz);
492 for (psz++; *psz != '/' && *psz != '\\'; psz++)
493 *psz = toupper(*psz);
495 #endif
496 /* add trailing slash on directories if input has it. */
497 pszEnd = strchr(pszPath, '\0');
498 if ( (pszEnd[-1] == '/' || pszEnd[-1] == '\\')
499 && psz[cchOut - 1] != '\\'
500 && psz[cchOut - 1] != '//')
501 psz[cchOut++] = '\\';
503 /* make sure it's terminated */
504 psz[cchOut] = '\0';
505 rc = 0;
507 else
508 rc = -3;
510 else
511 rc = -4;
513 else
514 rc = -5;
516 else
517 rc = -6;
518 CloseHandle(hFile);
520 else
521 rc = -7;
522 return rc;
526 * Somewhat similar to fullpath, except that it will fix
527 * the case of existing path components.
529 void
530 nt_fullpath(const char *pszPath, char *pszFull, size_t cchFull)
532 #if 0
533 static int s_cHits = 0;
534 static int s_cFallbacks = 0;
535 #endif
538 * The simple case, the file / dir / whatever exists and can be
539 * queried without problems and spaces.
541 if (nt_get_filename_info(pszPath, pszFull, cchFull) == 0)
543 /** @todo make nt_get_filename_info return spaceless path. */
544 if (strchr(pszFull, ' '))
545 w32_fixcase(pszFull);
546 #if 0
547 fprintf(stdout, "nt #%d - %s\n", ++s_cHits, pszFull);
548 fprintf(stdout, " #%d - %s\n", s_cHits, pszPath);
549 #endif
550 return;
552 if (g_pfnNtQueryInformationFile)
554 /* do _fullpath and drop off path elements until we get a hit... - later */
558 * For now, simply fall back on the old method.
560 _fullpath(pszFull, pszPath, cchFull);
561 w32_fixcase(pszFull);
562 #if 0
563 fprintf(stderr, "fb #%d - %s\n", ++s_cFallbacks, pszFull);
564 fprintf(stderr, " #%d - %s\n", s_cFallbacks, pszPath);
565 #endif