VirtualBox

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

Last change on this file since 5702 was 5702, checked in by vboxsync, 18 years ago

Free a previously allocated memory.

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