VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/win/path-win.cpp@ 11371

Last change on this file since 11371 was 10911, checked in by vboxsync, 17 years ago

IPRT: Added RTPathSetCurrent.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.5 KB
Line 
1/* $Id: path-win.cpp 10911 2008-07-28 12:58:44Z vboxsync $ */
2/** @file
3 * IPRT - Path manipulation.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#define LOG_GROUP RTLOGGROUP_PATH
36#include <Windows.h>
37
38#include <iprt/path.h>
39#include <iprt/assert.h>
40#include <iprt/string.h>
41#include <iprt/time.h>
42#include <iprt/mem.h>
43#include <iprt/param.h>
44#include <iprt/log.h>
45#include <iprt/err.h>
46#include "internal/path.h"
47#include "internal/fs.h"
48
49
50/**
51 * Get the real (no symlinks, no . or .. components) path, must exist.
52 *
53 * @returns iprt status code.
54 * @param pszPath The path to resolve.
55 * @param pszRealPath Where to store the real path.
56 * @param cchRealPath Size of the buffer.
57 */
58RTDECL(int) RTPathReal(const char *pszPath, char *pszRealPath, unsigned cchRealPath)
59{
60 /*
61 * Convert to UTF-16, call Win32 APIs, convert back.
62 */
63 PRTUTF16 pwszPath;
64 int rc = RTStrToUtf16(pszPath, &pwszPath);
65 if (!RT_SUCCESS(rc))
66 return (rc);
67
68 LPWSTR lpFile;
69 WCHAR wsz[RTPATH_MAX];
70 rc = GetFullPathNameW((LPCWSTR)pwszPath, ELEMENTS(wsz), &wsz[0], &lpFile);
71 if (rc > 0 && rc < ELEMENTS(wsz))
72 {
73 /* Check that it exists. (Use RTPathAbs() to just resolve the name.) */
74 DWORD dwAttr = GetFileAttributesW(wsz);
75 if (dwAttr != INVALID_FILE_ATTRIBUTES)
76 rc = RTUtf16ToUtf8Ex((PRTUTF16)&wsz[0], RTSTR_MAX, &pszRealPath, cchRealPath, NULL);
77 else
78 rc = RTErrConvertFromWin32(GetLastError());
79 }
80 else if (rc <= 0)
81 rc = RTErrConvertFromWin32(GetLastError());
82 else
83 rc = VERR_FILENAME_TOO_LONG;
84
85 RTUtf16Free(pwszPath);
86
87 return rc;
88}
89
90
91/**
92 * Get the absolute path (no symlinks, no . or .. components), doesn't have to exit.
93 *
94 * @returns iprt status code.
95 * @param pszPath The path to resolve.
96 * @param pszAbsPath Where to store the absolute path.
97 * @param cchAbsPath Size of the buffer.
98 */
99RTDECL(int) RTPathAbs(const char *pszPath, char *pszAbsPath, unsigned cchAbsPath)
100{
101 /*
102 * Convert to UTF-16, call Win32 API, convert back.
103 */
104 LPWSTR pwszPath;
105 int rc = RTStrToUtf16(pszPath, &pwszPath);
106 if (!RT_SUCCESS(rc))
107 return (rc);
108
109 LPWSTR pwszFile; /* Ignored */
110 RTUTF16 wsz[RTPATH_MAX];
111 rc = GetFullPathNameW(pwszPath, RT_ELEMENTS(wsz), &wsz[0], &pwszFile);
112 if (rc > 0 && rc < RT_ELEMENTS(wsz))
113 rc = RTUtf16ToUtf8Ex(&wsz[0], RTSTR_MAX, &pszAbsPath, cchAbsPath, NULL);
114 else if (rc <= 0)
115 rc = RTErrConvertFromWin32(GetLastError());
116 else
117 rc = VERR_FILENAME_TOO_LONG;
118
119 RTUtf16Free(pwszPath);
120
121 return rc;
122}
123
124
125/**
126 * Gets the program path.
127 *
128 * @returns iprt status code.
129 * @param pszPath Buffer where to store the path.
130 * @param cchPath Buffer size in bytes.
131 */
132RTDECL(int) RTPathProgram(char *pszPath, unsigned cchPath)
133{
134 /*
135 * First time only.
136 */
137 if (!g_szrtProgramPath[0])
138 {
139 HMODULE hExe = GetModuleHandle(NULL);
140 if (!GetModuleFileName(hExe, &g_szrtProgramPath[0], sizeof(g_szrtProgramPath)))
141 {
142 AssertMsgFailed(("Couldn't get exe module name. lasterr=%d\n", GetLastError()));
143 return RTErrConvertFromWin32(GetLastError());
144 }
145 RTPathStripFilename(g_szrtProgramPath);
146 }
147
148 /*
149 * Calc the length and check if there is space before copying.
150 */
151 unsigned cch = strlen(g_szrtProgramPath) + 1;
152 if (cch <= cchPath)
153 {
154 memcpy(pszPath, g_szrtProgramPath, cch + 1);
155 return VINF_SUCCESS;
156 }
157
158 AssertMsgFailed(("Buffer too small (%d < %d)\n", cchPath, cch));
159 return VERR_BUFFER_OVERFLOW;
160}
161
162
163/**
164 * Gets the user home directory.
165 *
166 * @returns iprt status code.
167 * @param pszPath Buffer where to store the path.
168 * @param cchPath Buffer size in bytes.
169 */
170RTDECL(int) RTPathUserHome(char *pszPath, unsigned cchPath)
171{
172 RTUTF16 wszPath[RTPATH_MAX];
173 DWORD dwAttr;
174
175 /*
176 * There are multiple definitions for what WE think of as user home...
177 */
178 if ( !GetEnvironmentVariableW(L"HOME", &wszPath[0], RTPATH_MAX)
179 || (dwAttr = GetFileAttributesW(&wszPath[0])) == INVALID_FILE_ATTRIBUTES
180 || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
181 {
182 if ( !GetEnvironmentVariableW(L"USERPROFILE", &wszPath[0], RTPATH_MAX)
183 || (dwAttr = GetFileAttributesW(&wszPath[0])) == INVALID_FILE_ATTRIBUTES
184 || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
185 {
186 /* %HOMEDRIVE%%HOMEPATH% */
187 if (!GetEnvironmentVariableW(L"HOMEDRIVE", &wszPath[0], RTPATH_MAX))
188 return VERR_PATH_NOT_FOUND;
189 size_t const cwc = RTUtf16Len(&wszPath[0]);
190 if ( !GetEnvironmentVariableW(L"HOMEPATH", &wszPath[cwc], RTPATH_MAX - cwc)
191 || (dwAttr = GetFileAttributesW(&wszPath[0])) == INVALID_FILE_ATTRIBUTES
192 || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
193 return VERR_PATH_NOT_FOUND;
194 }
195 }
196
197 /*
198 * Convert and return.
199 */
200 return RTUtf16ToUtf8Ex(&wszPath[0], RTSTR_MAX, &pszPath, cchPath, NULL);
201}
202
203
204RTR3DECL(int) RTPathQueryInfo(const char *pszPath, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
205{
206 /*
207 * Validate input.
208 */
209 if (!pszPath)
210 {
211 AssertMsgFailed(("Invalid pszPath=%p\n", pszPath));
212 return VERR_INVALID_PARAMETER;
213 }
214 if (!pObjInfo)
215 {
216 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
217 return VERR_INVALID_PARAMETER;
218 }
219 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
220 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
221 {
222 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
223 return VERR_INVALID_PARAMETER;
224 }
225
226 /*
227 * Query file info.
228 */
229 WIN32_FILE_ATTRIBUTE_DATA Data;
230#ifndef RT_DONT_CONVERT_FILENAMES
231 PRTUTF16 pwszPath;
232 int rc = RTStrToUtf16(pszPath, &pwszPath);
233 if (RT_FAILURE(rc))
234 return rc;
235 if (!GetFileAttributesExW(pwszPath, GetFileExInfoStandard, &Data))
236 {
237 rc = RTErrConvertFromWin32(GetLastError());
238 RTUtf16Free(pwszPath);
239 return rc;
240 }
241 RTUtf16Free(pwszPath);
242#else
243 if (!GetFileAttributesExA(pszPath, GetFileExInfoStandard, &Data))
244 return RTErrConvertFromWin32(GetLastError());
245#endif
246
247 /*
248 * Setup the returned data.
249 */
250 pObjInfo->cbObject = ((uint64_t)Data.nFileSizeHigh << 32)
251 | (uint64_t)Data.nFileSizeLow;
252 pObjInfo->cbAllocated = pObjInfo->cbObject;
253
254 Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
255 RTTimeSpecSetNtTime(&pObjInfo->BirthTime, *(uint64_t *)&Data.ftCreationTime);
256 RTTimeSpecSetNtTime(&pObjInfo->AccessTime, *(uint64_t *)&Data.ftLastAccessTime);
257 RTTimeSpecSetNtTime(&pObjInfo->ModificationTime, *(uint64_t *)&Data.ftLastWriteTime);
258 pObjInfo->ChangeTime = pObjInfo->ModificationTime;
259
260 pObjInfo->Attr.fMode = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT,
261 pszPath, strlen(pszPath));
262
263 /*
264 * Requested attributes (we cannot provide anything actually).
265 */
266 switch (enmAdditionalAttribs)
267 {
268 case RTFSOBJATTRADD_EASIZE:
269 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
270 pObjInfo->Attr.u.EASize.cb = 0;
271 break;
272
273 case RTFSOBJATTRADD_UNIX:
274 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX;
275 pObjInfo->Attr.u.Unix.uid = ~0U;
276 pObjInfo->Attr.u.Unix.gid = ~0U;
277 pObjInfo->Attr.u.Unix.cHardlinks = 1;
278 pObjInfo->Attr.u.Unix.INodeIdDevice = 0;
279 pObjInfo->Attr.u.Unix.INodeId = 0;
280 pObjInfo->Attr.u.Unix.fFlags = 0;
281 pObjInfo->Attr.u.Unix.GenerationId = 0;
282 pObjInfo->Attr.u.Unix.Device = 0;
283 break;
284
285 case RTFSOBJATTRADD_NOTHING:
286 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_NOTHING;
287 break;
288
289 default:
290 AssertMsgFailed(("Impossible!\n"));
291 return VERR_INTERNAL_ERROR;
292 }
293
294 return VINF_SUCCESS;
295}
296
297
298RTR3DECL(int) RTPathSetTimes(const char *pszPath, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
299 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
300{
301 /*
302 * Validate input.
303 */
304 AssertMsgReturn(VALID_PTR(pszPath), ("%p\n", pszPath), VERR_INVALID_POINTER);
305 AssertMsgReturn(*pszPath, ("%p\n", pszPath), VERR_INVALID_PARAMETER);
306 AssertMsgReturn(!pAccessTime || VALID_PTR(pAccessTime), ("%p\n", pAccessTime), VERR_INVALID_POINTER);
307 AssertMsgReturn(!pModificationTime || VALID_PTR(pModificationTime), ("%p\n", pModificationTime), VERR_INVALID_POINTER);
308 AssertMsgReturn(!pChangeTime || VALID_PTR(pChangeTime), ("%p\n", pChangeTime), VERR_INVALID_POINTER);
309 AssertMsgReturn(!pBirthTime || VALID_PTR(pBirthTime), ("%p\n", pBirthTime), VERR_INVALID_POINTER);
310
311 /*
312 * Convert the path.
313 */
314 PRTUTF16 pwszPath;
315 int rc = RTStrToUtf16(pszPath, &pwszPath);
316 if (RT_SUCCESS(rc))
317 {
318 HANDLE hFile = CreateFileW(pwszPath,
319 FILE_WRITE_ATTRIBUTES, /* dwDesiredAccess */
320 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, /* dwShareMode */
321 NULL, /* security attribs */
322 OPEN_EXISTING, /* dwCreationDisposition */
323 FILE_FLAG_BACKUP_SEMANTICS | FILE_ATTRIBUTE_NORMAL,
324 NULL);
325 if (hFile != INVALID_HANDLE_VALUE)
326 {
327 /*
328 * Check if it's a no-op.
329 */
330 if (!pAccessTime && !pModificationTime && !pBirthTime)
331 rc = VINF_SUCCESS; /* NOP */
332 else
333 {
334 /*
335 * Convert the input and call the API.
336 */
337 FILETIME CreationTimeFT;
338 PFILETIME pCreationTimeFT = NULL;
339 if (pBirthTime)
340 pCreationTimeFT = RTTimeSpecGetNtFileTime(pBirthTime, &CreationTimeFT);
341
342 FILETIME LastAccessTimeFT;
343 PFILETIME pLastAccessTimeFT = NULL;
344 if (pAccessTime)
345 pLastAccessTimeFT = RTTimeSpecGetNtFileTime(pAccessTime, &LastAccessTimeFT);
346
347 FILETIME LastWriteTimeFT;
348 PFILETIME pLastWriteTimeFT = NULL;
349 if (pModificationTime)
350 pLastWriteTimeFT = RTTimeSpecGetNtFileTime(pModificationTime, &LastWriteTimeFT);
351
352 if (SetFileTime(hFile, pCreationTimeFT, pLastAccessTimeFT, pLastWriteTimeFT))
353 rc = VINF_SUCCESS;
354 else
355 {
356 DWORD Err = GetLastError();
357 rc = RTErrConvertFromWin32(Err);
358 Log(("RTPathSetTimes('%s', %p, %p, %p, %p): SetFileTime failed with lasterr %d (%Vrc)\n",
359 pszPath, pAccessTime, pModificationTime, pChangeTime, pBirthTime, Err, rc));
360 }
361 }
362 BOOL fRc = CloseHandle(hFile); Assert(fRc); NOREF(fRc);
363 }
364 else
365 {
366 DWORD Err = GetLastError();
367 rc = RTErrConvertFromWin32(Err);
368 Log(("RTPathSetTimes('%s',,,,): failed with %Rrc and lasterr=%u\n", pszPath, rc, Err));
369 }
370
371 RTUtf16Free(pwszPath);
372 }
373
374 LogFlow(("RTPathSetTimes(%p:{%s}, %p:{%RDtimespec}, %p:{%RDtimespec}, %p:{%RDtimespec}, %p:{%RDtimespec}): return %Rrc\n",
375 pszPath, pszPath, pAccessTime, pAccessTime, pModificationTime, pModificationTime,
376 pChangeTime, pChangeTime, pBirthTime, pBirthTime));
377 return rc;
378}
379
380
381
382
383/**
384 * Internal worker for RTFileRename and RTFileMove.
385 *
386 * @returns iprt status code.
387 * @param pszSrc The source filename.
388 * @param pszDst The destination filename.
389 * @param fFlags The windows MoveFileEx flags.
390 * @param fFileType The filetype. We use the RTFMODE filetypes here. If it's 0,
391 * anything goes. If it's RTFS_TYPE_DIRECTORY we'll check that the
392 * source is a directory. If Its RTFS_TYPE_FILE we'll check that it's
393 * not a directory (we are NOT checking whether it's a file).
394 */
395int rtPathWin32MoveRename(const char *pszSrc, const char *pszDst, uint32_t fFlags, RTFMODE fFileType)
396{
397 /*
398 * Convert the strings.
399 */
400 PRTUTF16 pwszSrc;
401 int rc = RTStrToUtf16(pszSrc, &pwszSrc);
402 if (RT_SUCCESS(rc))
403 {
404 PRTUTF16 pwszDst;
405 rc = RTStrToUtf16(pszDst, &pwszDst);
406 if (RT_SUCCESS(rc))
407 {
408 /*
409 * Check object type if requested.
410 * This is open to race conditions.
411 */
412 if (fFileType)
413 {
414 DWORD dwAttr = GetFileAttributesW(pwszSrc);
415 if (dwAttr == INVALID_FILE_ATTRIBUTES)
416 rc = RTErrConvertFromWin32(GetLastError());
417 else if (RTFS_IS_DIRECTORY(fFileType))
418 rc = dwAttr & FILE_ATTRIBUTE_DIRECTORY ? VINF_SUCCESS : VERR_NOT_A_DIRECTORY;
419 else
420 rc = dwAttr & FILE_ATTRIBUTE_DIRECTORY ? VERR_IS_A_DIRECTORY : VINF_SUCCESS;
421 }
422 if (RT_SUCCESS(rc))
423 {
424 if (MoveFileExW(pwszSrc, pwszDst, fFlags))
425 rc = VINF_SUCCESS;
426 else
427 {
428 DWORD Err = GetLastError();
429 rc = RTErrConvertFromWin32(Err);
430 Log(("MoveFileExW('%s', '%s', %#x, %RTfmode): fails with rc=%Rrc & lasterr=%d\n",
431 pszSrc, pszDst, fFlags, fFileType, rc, Err));
432 }
433 }
434 RTUtf16Free(pwszDst);
435 }
436 RTUtf16Free(pwszSrc);
437 }
438 return rc;
439}
440
441
442RTR3DECL(int) RTPathRename(const char *pszSrc, const char *pszDst, unsigned fRename)
443{
444 /*
445 * Validate input.
446 */
447 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
448 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
449 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
450 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
451 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
452
453 /*
454 * Call the worker.
455 */
456 int rc = rtPathWin32MoveRename(pszSrc, pszDst, fRename & RTPATHRENAME_FLAGS_REPLACE ? MOVEFILE_REPLACE_EXISTING : 0, 0);
457
458 LogFlow(("RTPathRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n", pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
459 return rc;
460}
461
462
463/**
464 * Checks if the path exists.
465 *
466 * Symbolic links will all be attempted resolved.
467 *
468 * @returns true if it exists and false if it doesn't
469 * @param pszPath The path to check.
470 */
471RTDECL(bool) RTPathExists(const char *pszPath)
472{
473 /*
474 * Validate input.
475 */
476 AssertPtrReturn(pszPath, false);
477 AssertReturn(*pszPath, false);
478
479 /*
480 * Try query file info.
481 */
482#ifndef RT_DONT_CONVERT_FILENAMES
483 PRTUTF16 pwszPath;
484 int rc = RTStrToUtf16(pszPath, &pwszPath);
485 if (RT_SUCCESS(rc))
486 {
487 if (GetFileAttributesW(pwszPath) == INVALID_FILE_ATTRIBUTES)
488 rc = VERR_GENERAL_FAILURE;
489 RTUtf16Free(pwszPath);
490 }
491#else
492 int rc = VINF_SUCCESS;
493 if (GetFileAttributesExA(pszPath) == INVALID_FILE_ATTRIBUTES)
494 rc = VERR_GENERAL_FAILURE;
495#endif
496
497 return RT_SUCCESS(rc);
498}
499
500
501RTDECL(int) RTPathSetCurrent(const char *pszPath)
502{
503 /*
504 * Validate input.
505 */
506 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
507 AssertReturn(*pszPath, VERR_INVALID_PARAMETER);
508
509 /*
510 * This interface is almost identical to the Windows API.
511 */
512#ifndef RT_DONT_CONVERT_FILENAMES
513 PRTUTF16 pwszPath;
514 int rc = RTStrToUtf16(pszPath, &pwszPath);
515 if (RT_SUCCESS(rc))
516 {
517 /** @todo improove the slash stripping a bit? */
518 size_t cwc = RTUtf16Len(pwszPath);
519 if ( cwc >= 2
520 && ( pwszPath[cwc - 1] == L'/'
521 || pwszPath[cwc - 1] == L'\\')
522 && pwszPath[cwc - 2] != ':')
523 pwszPath[cwc - 1] = L'\0';
524
525 if (!SetCurrentDirectoryW(pwszPath))
526 rc = RTErrConvertFromWin32(GetLastError());
527
528 RTUtf16Free(pwszPath);
529 }
530#else
531 int rc = VINF_SUCCESS;
532 /** @todo improove the slash stripping a bit? */
533 char const *pszEnd = strchr(pszPath, '\0');
534 size_t const cchPath = pszPath - pszEnd;
535 if ( cchPath >= 2
536 && ( pszEnd[-1] == '/'
537 || pszEnd[-1] == '\\')
538 && pszEnd[-2] == ':')
539 {
540 char *pszCopy = (char *)RTMemTmpAlloc(cchPath);
541 if (pszCopy)
542 {
543 memcpy(pszCopy, pszPath, cchPath - 1);
544 pszCopy[cchPath - 1] = '\0';
545 if (!SetCurrentDirectory(pszCopy))
546 rc = RTErrConvertFromWin32(GetLastError());
547 RTMemTmpFree(pszCopy);
548 }
549 else
550 rc = VERR_NO_MEMORY;
551 }
552 else
553 {
554 if (!SetCurrentDirectory(pszPath))
555 rc = RTErrConvertFromWin32(GetLastError());
556 }
557#endif
558 return rc;
559}
560
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette