VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/win/fileio-win.cpp@ 74368

Last change on this file since 74368 was 74368, checked in by vboxsync, 7 years ago

IPRT/fileio-win.cpp: Disabled long filename code from r125172. See todo.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 37.6 KB
Line 
1/* $Id: fileio-win.cpp 74368 2018-09-19 11:27:56Z vboxsync $ */
2/** @file
3 * IPRT - File I/O, native implementation for the Windows host platform.
4 */
5
6/*
7 * Copyright (C) 2006-2018 Oracle Corporation
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 (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
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP RTLOGGROUP_DIR
32#ifndef _WIN32_WINNT
33# define _WIN32_WINNT 0x0500
34#endif
35#include <iprt/win/windows.h>
36
37#include <iprt/file.h>
38
39#include <iprt/asm.h>
40#include <iprt/assert.h>
41#include <iprt/path.h>
42#include <iprt/string.h>
43#include <iprt/err.h>
44#include <iprt/ldr.h>
45#include <iprt/log.h>
46#include "internal/file.h"
47#include "internal/fs.h"
48#include "internal/path.h"
49#include "internal-r3-win.h" /* For g_enmWinVer + kRTWinOSType_XXX */
50
51
52/*********************************************************************************************************************************
53* Defined Constants And Macros *
54*********************************************************************************************************************************/
55typedef BOOL WINAPI FNVERIFYCONSOLEIOHANDLE(HANDLE);
56typedef FNVERIFYCONSOLEIOHANDLE *PFNVERIFYCONSOLEIOHANDLE; /* No, nobody fell on the keyboard, really! */
57
58/**
59 * This is wrapper around the ugly SetFilePointer api.
60 *
61 * It's equivalent to SetFilePointerEx which we so unfortunately cannot use because of
62 * it not being present in NT4 GA.
63 *
64 * @returns Success indicator. Extended error information obtainable using GetLastError().
65 * @param hFile Filehandle.
66 * @param offSeek Offset to seek.
67 * @param poffNew Where to store the new file offset. NULL allowed.
68 * @param uMethod Seek method. (The windows one!)
69 */
70DECLINLINE(bool) MySetFilePointer(RTFILE hFile, uint64_t offSeek, uint64_t *poffNew, unsigned uMethod)
71{
72 bool fRc;
73 LARGE_INTEGER off;
74
75 off.QuadPart = offSeek;
76#if 1
77 if (off.LowPart != INVALID_SET_FILE_POINTER)
78 {
79 off.LowPart = SetFilePointer((HANDLE)RTFileToNative(hFile), off.LowPart, &off.HighPart, uMethod);
80 fRc = off.LowPart != INVALID_SET_FILE_POINTER;
81 }
82 else
83 {
84 SetLastError(NO_ERROR);
85 off.LowPart = SetFilePointer((HANDLE)RTFileToNative(hFile), off.LowPart, &off.HighPart, uMethod);
86 fRc = GetLastError() == NO_ERROR;
87 }
88#else
89 fRc = SetFilePointerEx((HANDLE)RTFileToNative(hFile), off, &off, uMethod);
90#endif
91 if (fRc && poffNew)
92 *poffNew = off.QuadPart;
93 return fRc;
94}
95
96
97/**
98 * This is a helper to check if an attempt was made to grow a file beyond the
99 * limit of the filesystem.
100 *
101 * @returns true for file size limit exceeded.
102 * @param hFile Filehandle.
103 * @param offSeek Offset to seek.
104 * @param uMethod The seek method.
105 */
106DECLINLINE(bool) IsBeyondLimit(RTFILE hFile, uint64_t offSeek, unsigned uMethod)
107{
108 bool fIsBeyondLimit = false;
109
110 /*
111 * Get the current file position and try set the new one.
112 * If it fails with a seek error it's because we hit the file system limit.
113 */
114/** @todo r=bird: I'd be very interested to know on which versions of windows and on which file systems
115 * this supposedly works. The fastfat sources in the latest WDK makes no limit checks during
116 * file seeking, only at the time of writing (and some other odd ones we cannot make use of). */
117 uint64_t offCurrent;
118 if (MySetFilePointer(hFile, 0, &offCurrent, FILE_CURRENT))
119 {
120 if (!MySetFilePointer(hFile, offSeek, NULL, uMethod))
121 fIsBeyondLimit = GetLastError() == ERROR_SEEK;
122 else /* Restore file pointer on success. */
123 MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN);
124 }
125
126 return fIsBeyondLimit;
127}
128
129
130RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
131{
132 HANDLE h = (HANDLE)uNative;
133 AssertCompile(sizeof(h) == sizeof(uNative));
134 if (h == INVALID_HANDLE_VALUE)
135 {
136 AssertMsgFailed(("%p\n", uNative));
137 *pFile = NIL_RTFILE;
138 return VERR_INVALID_HANDLE;
139 }
140 *pFile = (RTFILE)h;
141 return VINF_SUCCESS;
142}
143
144
145RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE hFile)
146{
147 AssertReturn(hFile != NIL_RTFILE, (RTHCINTPTR)INVALID_HANDLE_VALUE);
148 return (RTHCINTPTR)hFile;
149}
150
151
152RTR3DECL(int) RTFileOpen(PRTFILE pFile, const char *pszFilename, uint64_t fOpen)
153{
154 /*
155 * Validate input.
156 */
157 if (!pFile)
158 {
159 AssertMsgFailed(("Invalid pFile\n"));
160 return VERR_INVALID_PARAMETER;
161 }
162 *pFile = NIL_RTFILE;
163 if (!pszFilename)
164 {
165 AssertMsgFailed(("Invalid pszFilename\n"));
166 return VERR_INVALID_PARAMETER;
167 }
168
169 /*
170 * Merge forced open flags and validate them.
171 */
172 int rc = rtFileRecalcAndValidateFlags(&fOpen);
173 if (RT_FAILURE(rc))
174 return rc;
175
176 /*
177 * Determine disposition, access, share mode, creation flags, and security attributes
178 * for the CreateFile API call.
179 */
180 DWORD dwCreationDisposition;
181 switch (fOpen & RTFILE_O_ACTION_MASK)
182 {
183 case RTFILE_O_OPEN:
184 dwCreationDisposition = fOpen & RTFILE_O_TRUNCATE ? TRUNCATE_EXISTING : OPEN_EXISTING;
185 break;
186 case RTFILE_O_OPEN_CREATE:
187 dwCreationDisposition = OPEN_ALWAYS;
188 break;
189 case RTFILE_O_CREATE:
190 dwCreationDisposition = CREATE_NEW;
191 break;
192 case RTFILE_O_CREATE_REPLACE:
193 dwCreationDisposition = CREATE_ALWAYS;
194 break;
195 default:
196 AssertMsgFailed(("Impossible fOpen=%#llx\n", fOpen));
197 return VERR_INVALID_PARAMETER;
198 }
199
200 DWORD dwDesiredAccess;
201 switch (fOpen & RTFILE_O_ACCESS_MASK)
202 {
203 case RTFILE_O_READ:
204 dwDesiredAccess = FILE_GENERIC_READ; /* RTFILE_O_APPEND is ignored. */
205 break;
206 case RTFILE_O_WRITE:
207 dwDesiredAccess = fOpen & RTFILE_O_APPEND
208 ? FILE_GENERIC_WRITE & ~FILE_WRITE_DATA
209 : FILE_GENERIC_WRITE;
210 break;
211 case RTFILE_O_READWRITE:
212 dwDesiredAccess = fOpen & RTFILE_O_APPEND
213 ? FILE_GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
214 : FILE_GENERIC_READ | FILE_GENERIC_WRITE;
215 break;
216 case RTFILE_O_ATTR_ONLY:
217 if (fOpen & RTFILE_O_ACCESS_ATTR_MASK)
218 {
219 dwDesiredAccess = 0;
220 break;
221 }
222 RT_FALL_THRU();
223 default:
224 AssertMsgFailed(("Impossible fOpen=%#llx\n", fOpen));
225 return VERR_INVALID_PARAMETER;
226 }
227 if (dwCreationDisposition == TRUNCATE_EXISTING)
228 /* Required for truncating the file (see MSDN), it is *NOT* part of FILE_GENERIC_WRITE. */
229 dwDesiredAccess |= GENERIC_WRITE;
230
231 /* RTFileSetMode needs following rights as well. */
232 switch (fOpen & RTFILE_O_ACCESS_ATTR_MASK)
233 {
234 case RTFILE_O_ACCESS_ATTR_READ: dwDesiredAccess |= FILE_READ_ATTRIBUTES | SYNCHRONIZE; break;
235 case RTFILE_O_ACCESS_ATTR_WRITE: dwDesiredAccess |= FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
236 case RTFILE_O_ACCESS_ATTR_READWRITE: dwDesiredAccess |= FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
237 default:
238 /* Attributes access is the same as the file access. */
239 switch (fOpen & RTFILE_O_ACCESS_MASK)
240 {
241 case RTFILE_O_READ: dwDesiredAccess |= FILE_READ_ATTRIBUTES | SYNCHRONIZE; break;
242 case RTFILE_O_WRITE: dwDesiredAccess |= FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
243 case RTFILE_O_READWRITE: dwDesiredAccess |= FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
244 default:
245 AssertMsgFailed(("Impossible fOpen=%#llx\n", fOpen));
246 return VERR_INVALID_PARAMETER;
247 }
248 }
249
250 DWORD dwShareMode;
251 switch (fOpen & RTFILE_O_DENY_MASK)
252 {
253 case RTFILE_O_DENY_NONE: dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
254 case RTFILE_O_DENY_READ: dwShareMode = FILE_SHARE_WRITE; break;
255 case RTFILE_O_DENY_WRITE: dwShareMode = FILE_SHARE_READ; break;
256 case RTFILE_O_DENY_READWRITE: dwShareMode = 0; break;
257
258 case RTFILE_O_DENY_NOT_DELETE: dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE; break;
259 case RTFILE_O_DENY_NOT_DELETE | RTFILE_O_DENY_READ: dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_WRITE; break;
260 case RTFILE_O_DENY_NOT_DELETE | RTFILE_O_DENY_WRITE: dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ; break;
261 case RTFILE_O_DENY_NOT_DELETE | RTFILE_O_DENY_READWRITE:dwShareMode = FILE_SHARE_DELETE; break;
262 default:
263 AssertMsgFailed(("Impossible fOpen=%#llx\n", fOpen));
264 return VERR_INVALID_PARAMETER;
265 }
266
267 SECURITY_ATTRIBUTES SecurityAttributes;
268 PSECURITY_ATTRIBUTES pSecurityAttributes = NULL;
269 if (fOpen & RTFILE_O_INHERIT)
270 {
271 SecurityAttributes.nLength = sizeof(SecurityAttributes);
272 SecurityAttributes.lpSecurityDescriptor = NULL;
273 SecurityAttributes.bInheritHandle = TRUE;
274 pSecurityAttributes = &SecurityAttributes;
275 }
276
277 DWORD dwFlagsAndAttributes;
278 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
279 if (fOpen & RTFILE_O_WRITE_THROUGH)
280 dwFlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH;
281 if (fOpen & RTFILE_O_ASYNC_IO)
282 dwFlagsAndAttributes |= FILE_FLAG_OVERLAPPED;
283 if (fOpen & RTFILE_O_NO_CACHE)
284 {
285 dwFlagsAndAttributes |= FILE_FLAG_NO_BUFFERING;
286 dwDesiredAccess &= ~FILE_APPEND_DATA;
287 }
288
289 /*
290 * Open/Create the file.
291 *
292 * When opening files with paths longer than 260 chars, CreateFileW() will fail, unless
293 * you explicitly specify a prefix (see [1], RTPATH_WIN_LONG_PATH_PREFIX).
294 *
295 * Note: Relative paths are not supported, so check for this.
296 *
297 * [1] https://docs.microsoft.com/en-gb/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
298 */
299 PRTUTF16 pwszFilename = NULL;
300#if 0 /** @todo r=bird: This stuff just isn't up to scratch. Sorry. RTStrAPrintf2? WTF?!? When using the long path prefix,
301 * the path is just passed right thru to the NT API, so we need to fix unix slashes, resolve '.' and '..' components,
302 * and probably also get rid of extra slashes. Finally, the 260 limit (there is a \#define for it btw) actually
303 * applies to the converted filename (UTF-16), not the UTF-8 one, so this may break stuff (think asian languages)
304 * that isn't over the 260 limit. */
305 if (g_enmWinVer >= kRTWinOSType_XP) /* Not sure since when the prefix is available, so play safe by default. */
306 {
307#define RTPATH_WIN_LONG_PATH_PREFIX "\\\\?\\"
308
309 if ( strlen(pszFilename) > 260
310 && !RTPathStartsWith(pszFilename, RTPATH_WIN_LONG_PATH_PREFIX)
311 && RTPathStartsWithRoot(pszFilename))
312 {
313 char *pszFilenameWithPrefix = RTStrAPrintf2("%s%s", RTPATH_WIN_LONG_PATH_PREFIX, pszFilename);
314 if (pszFilenameWithPrefix)
315 {
316 rc = RTStrToUtf16(pszFilenameWithPrefix, &pwszFilename);
317 RTStrFree(pszFilenameWithPrefix);
318 }
319 else
320 rc = VERR_NO_MEMORY;
321 }
322#undef RTPATH_WIN_LONG_PATH_PREFIX
323 }
324
325 if ( RT_SUCCESS(rc)
326 && !pwszFilename)
327#endif
328 rc = RTStrToUtf16(pszFilename, &pwszFilename);
329
330 if (RT_FAILURE(rc))
331 return rc;
332
333 HANDLE hFile = CreateFileW(pwszFilename,
334 dwDesiredAccess,
335 dwShareMode,
336 pSecurityAttributes,
337 dwCreationDisposition,
338 dwFlagsAndAttributes,
339 NULL);
340 if (hFile != INVALID_HANDLE_VALUE)
341 {
342 bool fCreated = dwCreationDisposition == CREATE_ALWAYS
343 || dwCreationDisposition == CREATE_NEW
344 || (dwCreationDisposition == OPEN_ALWAYS && GetLastError() == 0);
345
346 /*
347 * Turn off indexing of directory through Windows Indexing Service.
348 */
349 if ( fCreated
350 && (fOpen & RTFILE_O_NOT_CONTENT_INDEXED))
351 {
352 if (!SetFileAttributesW(pwszFilename, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED))
353 rc = RTErrConvertFromWin32(GetLastError());
354 }
355 /*
356 * Do we need to truncate the file?
357 */
358 else if ( !fCreated
359 && (fOpen & (RTFILE_O_TRUNCATE | RTFILE_O_ACTION_MASK))
360 == (RTFILE_O_TRUNCATE | RTFILE_O_OPEN_CREATE))
361 {
362 if (!SetEndOfFile(hFile))
363 rc = RTErrConvertFromWin32(GetLastError());
364 }
365 if (RT_SUCCESS(rc))
366 {
367 *pFile = (RTFILE)hFile;
368 Assert((HANDLE)*pFile == hFile);
369 RTUtf16Free(pwszFilename);
370 return VINF_SUCCESS;
371 }
372
373 CloseHandle(hFile);
374 }
375 else
376 rc = RTErrConvertFromWin32(GetLastError());
377 RTUtf16Free(pwszFilename);
378 return rc;
379}
380
381
382RTR3DECL(int) RTFileOpenBitBucket(PRTFILE phFile, uint64_t fAccess)
383{
384 AssertReturn( fAccess == RTFILE_O_READ
385 || fAccess == RTFILE_O_WRITE
386 || fAccess == RTFILE_O_READWRITE,
387 VERR_INVALID_PARAMETER);
388 return RTFileOpen(phFile, "NUL", fAccess | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
389}
390
391
392RTR3DECL(int) RTFileClose(RTFILE hFile)
393{
394 if (hFile == NIL_RTFILE)
395 return VINF_SUCCESS;
396 if (CloseHandle((HANDLE)RTFileToNative(hFile)))
397 return VINF_SUCCESS;
398 return RTErrConvertFromWin32(GetLastError());
399}
400
401
402RTFILE rtFileGetStandard(RTHANDLESTD enmStdHandle)
403{
404 DWORD dwStdHandle;
405 switch (enmStdHandle)
406 {
407 case RTHANDLESTD_INPUT: dwStdHandle = STD_INPUT_HANDLE; break;
408 case RTHANDLESTD_OUTPUT: dwStdHandle = STD_OUTPUT_HANDLE; break;
409 case RTHANDLESTD_ERROR: dwStdHandle = STD_ERROR_HANDLE; break;
410 default:
411 AssertFailedReturn(NIL_RTFILE);
412 }
413
414 HANDLE hNative = GetStdHandle(dwStdHandle);
415 if (hNative == INVALID_HANDLE_VALUE)
416 return NIL_RTFILE;
417
418 RTFILE hFile = (RTFILE)(uintptr_t)hNative;
419 AssertReturn((HANDLE)(uintptr_t)hFile == hNative, NIL_RTFILE);
420 return hFile;
421}
422
423
424RTR3DECL(int) RTFileSeek(RTFILE hFile, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
425{
426 static ULONG aulSeekRecode[] =
427 {
428 FILE_BEGIN,
429 FILE_CURRENT,
430 FILE_END,
431 };
432
433 /*
434 * Validate input.
435 */
436 if (uMethod > RTFILE_SEEK_END)
437 {
438 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
439 return VERR_INVALID_PARAMETER;
440 }
441
442 /*
443 * Execute the seek.
444 */
445 if (MySetFilePointer(hFile, offSeek, poffActual, aulSeekRecode[uMethod]))
446 return VINF_SUCCESS;
447 return RTErrConvertFromWin32(GetLastError());
448}
449
450
451RTR3DECL(int) RTFileRead(RTFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
452{
453 if (cbToRead <= 0)
454 return VINF_SUCCESS;
455 ULONG cbToReadAdj = (ULONG)cbToRead;
456 AssertReturn(cbToReadAdj == cbToRead, VERR_NUMBER_TOO_BIG);
457
458 ULONG cbRead = 0;
459 if (ReadFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToReadAdj, &cbRead, NULL))
460 {
461 if (pcbRead)
462 /* Caller can handle partial reads. */
463 *pcbRead = cbRead;
464 else
465 {
466 /* Caller expects everything to be read. */
467 while (cbToReadAdj > cbRead)
468 {
469 ULONG cbReadPart = 0;
470 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbRead, cbToReadAdj - cbRead, &cbReadPart, NULL))
471 return RTErrConvertFromWin32(GetLastError());
472 if (cbReadPart == 0)
473 return VERR_EOF;
474 cbRead += cbReadPart;
475 }
476 }
477 return VINF_SUCCESS;
478 }
479
480 /*
481 * If it's a console, we might bump into out of memory conditions in the
482 * ReadConsole call.
483 */
484 DWORD dwErr = GetLastError();
485 if (dwErr == ERROR_NOT_ENOUGH_MEMORY)
486 {
487 ULONG cbChunk = cbToReadAdj / 2;
488 if (cbChunk > 16*_1K)
489 cbChunk = 16*_1K;
490 else
491 cbChunk = RT_ALIGN_32(cbChunk, 256);
492
493 cbRead = 0;
494 while (cbToReadAdj > cbRead)
495 {
496 ULONG cbToRead = RT_MIN(cbChunk, cbToReadAdj - cbRead);
497 ULONG cbReadPart = 0;
498 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char *)pvBuf + cbRead, cbToRead, &cbReadPart, NULL))
499 {
500 /* If we failed because the buffer is too big, shrink it and
501 try again. */
502 dwErr = GetLastError();
503 if ( dwErr == ERROR_NOT_ENOUGH_MEMORY
504 && cbChunk > 8)
505 {
506 cbChunk /= 2;
507 continue;
508 }
509 return RTErrConvertFromWin32(dwErr);
510 }
511 cbRead += cbReadPart;
512
513 /* Return if the caller can handle partial reads, otherwise try
514 fill the buffer all the way up. */
515 if (pcbRead)
516 {
517 *pcbRead = cbRead;
518 break;
519 }
520 if (cbReadPart == 0)
521 return VERR_EOF;
522 }
523 return VINF_SUCCESS;
524 }
525
526 return RTErrConvertFromWin32(dwErr);
527}
528
529
530RTR3DECL(int) RTFileWrite(RTFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
531{
532 if (cbToWrite <= 0)
533 return VINF_SUCCESS;
534 ULONG const cbToWriteAdj = (ULONG)cbToWrite;
535 AssertReturn(cbToWriteAdj == cbToWrite, VERR_NUMBER_TOO_BIG);
536
537 ULONG cbWritten = 0;
538 if (WriteFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToWriteAdj, &cbWritten, NULL))
539 {
540 if (pcbWritten)
541 /* Caller can handle partial writes. */
542 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
543 else
544 {
545 /* Caller expects everything to be written. */
546 while (cbWritten < cbToWriteAdj)
547 {
548 ULONG cbWrittenPart = 0;
549 if (!WriteFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbWritten,
550 cbToWriteAdj - cbWritten, &cbWrittenPart, NULL))
551 {
552 int rc = RTErrConvertFromWin32(GetLastError());
553 if ( rc == VERR_DISK_FULL
554 && IsBeyondLimit(hFile, cbToWriteAdj - cbWritten, FILE_CURRENT)
555 )
556 rc = VERR_FILE_TOO_BIG;
557 return rc;
558 }
559 if (cbWrittenPart == 0)
560 return VERR_WRITE_ERROR;
561 cbWritten += cbWrittenPart;
562 }
563 }
564 return VINF_SUCCESS;
565 }
566
567 /*
568 * If it's a console, we might bump into out of memory conditions in the
569 * WriteConsole call.
570 */
571 DWORD dwErr = GetLastError();
572 if (dwErr == ERROR_NOT_ENOUGH_MEMORY)
573 {
574 ULONG cbChunk = cbToWriteAdj / 2;
575 if (cbChunk > _32K)
576 cbChunk = _32K;
577 else
578 cbChunk = RT_ALIGN_32(cbChunk, 256);
579
580 cbWritten = 0;
581 while (cbWritten < cbToWriteAdj)
582 {
583 ULONG cbToWrite = RT_MIN(cbChunk, cbToWriteAdj - cbWritten);
584 ULONG cbWrittenPart = 0;
585 if (!WriteFile((HANDLE)RTFileToNative(hFile), (const char *)pvBuf + cbWritten, cbToWrite, &cbWrittenPart, NULL))
586 {
587 /* If we failed because the buffer is too big, shrink it and
588 try again. */
589 dwErr = GetLastError();
590 if ( dwErr == ERROR_NOT_ENOUGH_MEMORY
591 && cbChunk > 8)
592 {
593 cbChunk /= 2;
594 continue;
595 }
596 int rc = RTErrConvertFromWin32(dwErr);
597 if ( rc == VERR_DISK_FULL
598 && IsBeyondLimit(hFile, cbToWriteAdj - cbWritten, FILE_CURRENT))
599 rc = VERR_FILE_TOO_BIG;
600 return rc;
601 }
602 cbWritten += cbWrittenPart;
603
604 /* Return if the caller can handle partial writes, otherwise try
605 write out everything. */
606 if (pcbWritten)
607 {
608 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
609 break;
610 }
611 if (cbWrittenPart == 0)
612 return VERR_WRITE_ERROR;
613 }
614 return VINF_SUCCESS;
615 }
616
617 int rc = RTErrConvertFromWin32(dwErr);
618 if ( rc == VERR_DISK_FULL
619 && IsBeyondLimit(hFile, cbToWriteAdj - cbWritten, FILE_CURRENT))
620 rc = VERR_FILE_TOO_BIG;
621 return rc;
622}
623
624
625RTR3DECL(int) RTFileFlush(RTFILE hFile)
626{
627 if (!FlushFileBuffers((HANDLE)RTFileToNative(hFile)))
628 {
629 int rc = GetLastError();
630 Log(("FlushFileBuffers failed with %d\n", rc));
631 return RTErrConvertFromWin32(rc);
632 }
633 return VINF_SUCCESS;
634}
635
636
637RTR3DECL(int) RTFileSetSize(RTFILE hFile, uint64_t cbSize)
638{
639 /*
640 * Get current file pointer.
641 */
642 int rc;
643 uint64_t offCurrent;
644 if (MySetFilePointer(hFile, 0, &offCurrent, FILE_CURRENT))
645 {
646 /*
647 * Set new file pointer.
648 */
649 if (MySetFilePointer(hFile, cbSize, NULL, FILE_BEGIN))
650 {
651 /* set file pointer */
652 if (SetEndOfFile((HANDLE)RTFileToNative(hFile)))
653 {
654 /*
655 * Restore file pointer and return.
656 * If the old pointer was beyond the new file end, ignore failure.
657 */
658 if ( MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN)
659 || offCurrent > cbSize)
660 return VINF_SUCCESS;
661 }
662
663 /*
664 * Failed, try restoring the file pointer.
665 */
666 rc = GetLastError();
667 MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN);
668 }
669 else
670 rc = GetLastError();
671 }
672 else
673 rc = GetLastError();
674
675 return RTErrConvertFromWin32(rc);
676}
677
678
679RTR3DECL(int) RTFileGetSize(RTFILE hFile, uint64_t *pcbSize)
680{
681 /*
682 * GetFileSize works for most handles.
683 */
684 ULARGE_INTEGER Size;
685 Size.LowPart = GetFileSize((HANDLE)RTFileToNative(hFile), &Size.HighPart);
686 if (Size.LowPart != INVALID_FILE_SIZE)
687 {
688 *pcbSize = Size.QuadPart;
689 return VINF_SUCCESS;
690 }
691 int rc = RTErrConvertFromWin32(GetLastError());
692
693 /*
694 * Could it be a volume or a disk?
695 */
696 DISK_GEOMETRY DriveGeo;
697 DWORD cbDriveGeo;
698 if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
699 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
700 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
701 {
702 if ( DriveGeo.MediaType == FixedMedia
703 || DriveGeo.MediaType == RemovableMedia)
704 {
705 *pcbSize = DriveGeo.Cylinders.QuadPart
706 * DriveGeo.TracksPerCylinder
707 * DriveGeo.SectorsPerTrack
708 * DriveGeo.BytesPerSector;
709
710 GET_LENGTH_INFORMATION DiskLenInfo;
711 DWORD Ignored;
712 if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
713 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
714 &DiskLenInfo, sizeof(DiskLenInfo), &Ignored, (LPOVERLAPPED)NULL))
715 {
716 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
717 *pcbSize = DiskLenInfo.Length.QuadPart;
718 }
719 return VINF_SUCCESS;
720 }
721 }
722
723 /*
724 * Return the GetFileSize result if not a volume/disk.
725 */
726 return rc;
727}
728
729
730RTR3DECL(int) RTFileGetMaxSizeEx(RTFILE hFile, PRTFOFF pcbMax)
731{
732 /** @todo r=bird:
733 * We might have to make this code OS version specific... In the worse
734 * case, we'll have to try GetVolumeInformationByHandle on vista and fall
735 * back on NtQueryVolumeInformationFile(,,,, FileFsAttributeInformation)
736 * else where, and check for known file system names. (For LAN shares we'll
737 * have to figure out the remote file system.) */
738 RT_NOREF_PV(hFile); RT_NOREF_PV(pcbMax);
739 return VERR_NOT_IMPLEMENTED;
740}
741
742
743RTR3DECL(bool) RTFileIsValid(RTFILE hFile)
744{
745 if (hFile != NIL_RTFILE)
746 {
747 DWORD dwType = GetFileType((HANDLE)RTFileToNative(hFile));
748 switch (dwType)
749 {
750 case FILE_TYPE_CHAR:
751 case FILE_TYPE_DISK:
752 case FILE_TYPE_PIPE:
753 case FILE_TYPE_REMOTE:
754 return true;
755
756 case FILE_TYPE_UNKNOWN:
757 if (GetLastError() == NO_ERROR)
758 return true;
759 break;
760
761 default:
762 break;
763 }
764 }
765 return false;
766}
767
768
769#define LOW_DWORD(u64) ((DWORD)u64)
770#define HIGH_DWORD(u64) (((DWORD *)&u64)[1])
771
772RTR3DECL(int) RTFileLock(RTFILE hFile, unsigned fLock, int64_t offLock, uint64_t cbLock)
773{
774 Assert(offLock >= 0);
775
776 /* Check arguments. */
777 if (fLock & ~RTFILE_LOCK_MASK)
778 {
779 AssertMsgFailed(("Invalid fLock=%08X\n", fLock));
780 return VERR_INVALID_PARAMETER;
781 }
782
783 /* Prepare flags. */
784 Assert(RTFILE_LOCK_WRITE);
785 DWORD dwFlags = (fLock & RTFILE_LOCK_WRITE) ? LOCKFILE_EXCLUSIVE_LOCK : 0;
786 Assert(RTFILE_LOCK_WAIT);
787 if (!(fLock & RTFILE_LOCK_WAIT))
788 dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
789
790 /* Windows structure. */
791 OVERLAPPED Overlapped;
792 memset(&Overlapped, 0, sizeof(Overlapped));
793 Overlapped.Offset = LOW_DWORD(offLock);
794 Overlapped.OffsetHigh = HIGH_DWORD(offLock);
795
796 /* Note: according to Microsoft, LockFileEx API call is available starting from NT 3.5 */
797 if (LockFileEx((HANDLE)RTFileToNative(hFile), dwFlags, 0, LOW_DWORD(cbLock), HIGH_DWORD(cbLock), &Overlapped))
798 return VINF_SUCCESS;
799
800 return RTErrConvertFromWin32(GetLastError());
801}
802
803
804RTR3DECL(int) RTFileChangeLock(RTFILE hFile, unsigned fLock, int64_t offLock, uint64_t cbLock)
805{
806 Assert(offLock >= 0);
807
808 /* Check arguments. */
809 if (fLock & ~RTFILE_LOCK_MASK)
810 {
811 AssertMsgFailed(("Invalid fLock=%08X\n", fLock));
812 return VERR_INVALID_PARAMETER;
813 }
814
815 /* Remove old lock. */
816 int rc = RTFileUnlock(hFile, offLock, cbLock);
817 if (RT_FAILURE(rc))
818 return rc;
819
820 /* Set new lock. */
821 rc = RTFileLock(hFile, fLock, offLock, cbLock);
822 if (RT_SUCCESS(rc))
823 return rc;
824
825 /* Try to restore old lock. */
826 unsigned fLockOld = (fLock & RTFILE_LOCK_WRITE) ? fLock & ~RTFILE_LOCK_WRITE : fLock | RTFILE_LOCK_WRITE;
827 rc = RTFileLock(hFile, fLockOld, offLock, cbLock);
828 if (RT_SUCCESS(rc))
829 return VERR_FILE_LOCK_VIOLATION;
830 else
831 return VERR_FILE_LOCK_LOST;
832}
833
834
835RTR3DECL(int) RTFileUnlock(RTFILE hFile, int64_t offLock, uint64_t cbLock)
836{
837 Assert(offLock >= 0);
838
839 if (UnlockFile((HANDLE)RTFileToNative(hFile),
840 LOW_DWORD(offLock), HIGH_DWORD(offLock),
841 LOW_DWORD(cbLock), HIGH_DWORD(cbLock)))
842 return VINF_SUCCESS;
843
844 return RTErrConvertFromWin32(GetLastError());
845}
846
847
848
849RTR3DECL(int) RTFileQueryInfo(RTFILE hFile, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
850{
851 /*
852 * Validate input.
853 */
854 if (hFile == NIL_RTFILE)
855 {
856 AssertMsgFailed(("Invalid hFile=%RTfile\n", hFile));
857 return VERR_INVALID_PARAMETER;
858 }
859 if (!pObjInfo)
860 {
861 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
862 return VERR_INVALID_PARAMETER;
863 }
864 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
865 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
866 {
867 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
868 return VERR_INVALID_PARAMETER;
869 }
870
871 /*
872 * Query file info.
873 */
874 HANDLE hHandle = (HANDLE)RTFileToNative(hFile);
875
876 BY_HANDLE_FILE_INFORMATION Data;
877 if (!GetFileInformationByHandle(hHandle, &Data))
878 {
879 /*
880 * Console I/O handles make trouble here. On older windows versions they
881 * end up with ERROR_INVALID_HANDLE when handed to the above API, while on
882 * more recent ones they cause different errors to appear.
883 *
884 * Thus, we must ignore the latter and doubly verify invalid handle claims.
885 * We use the undocumented VerifyConsoleIoHandle to do this, falling back on
886 * GetFileType should it not be there.
887 */
888 DWORD dwErr = GetLastError();
889 if (dwErr == ERROR_INVALID_HANDLE)
890 {
891 static PFNVERIFYCONSOLEIOHANDLE s_pfnVerifyConsoleIoHandle = NULL;
892 static bool volatile s_fInitialized = false;
893 PFNVERIFYCONSOLEIOHANDLE pfnVerifyConsoleIoHandle;
894 if (s_fInitialized)
895 pfnVerifyConsoleIoHandle = s_pfnVerifyConsoleIoHandle;
896 else
897 {
898 pfnVerifyConsoleIoHandle = (PFNVERIFYCONSOLEIOHANDLE)RTLdrGetSystemSymbol("kernel32.dll", "VerifyConsoleIoHandle");
899 ASMAtomicWriteBool(&s_fInitialized, true);
900 }
901 if ( pfnVerifyConsoleIoHandle
902 ? !pfnVerifyConsoleIoHandle(hHandle)
903 : GetFileType(hHandle) == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR)
904 return VERR_INVALID_HANDLE;
905 }
906 /*
907 * On Windows 10 and (hopefully) 8.1 we get ERROR_INVALID_FUNCTION with console I/O
908 * handles. We must ignore these just like the above invalid handle error.
909 */
910 else if (dwErr != ERROR_INVALID_FUNCTION)
911 return RTErrConvertFromWin32(dwErr);
912
913 RT_ZERO(Data);
914 Data.dwFileAttributes = RTFS_DOS_NT_DEVICE;
915 }
916
917 /*
918 * Setup the returned data.
919 */
920 pObjInfo->cbObject = ((uint64_t)Data.nFileSizeHigh << 32)
921 | (uint64_t)Data.nFileSizeLow;
922 pObjInfo->cbAllocated = pObjInfo->cbObject;
923
924 Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
925 RTTimeSpecSetNtTime(&pObjInfo->BirthTime, *(uint64_t *)&Data.ftCreationTime);
926 RTTimeSpecSetNtTime(&pObjInfo->AccessTime, *(uint64_t *)&Data.ftLastAccessTime);
927 RTTimeSpecSetNtTime(&pObjInfo->ModificationTime, *(uint64_t *)&Data.ftLastWriteTime);
928 pObjInfo->ChangeTime = pObjInfo->ModificationTime;
929
930 pObjInfo->Attr.fMode = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT, "", 0,
931 RTFSMODE_SYMLINK_REPARSE_TAG /* (symlink or not, doesn't usually matter here) */);
932
933 /*
934 * Requested attributes (we cannot provide anything actually).
935 */
936 switch (enmAdditionalAttribs)
937 {
938 case RTFSOBJATTRADD_NOTHING:
939 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_NOTHING;
940 break;
941
942 case RTFSOBJATTRADD_UNIX:
943 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX;
944 pObjInfo->Attr.u.Unix.uid = ~0U;
945 pObjInfo->Attr.u.Unix.gid = ~0U;
946 pObjInfo->Attr.u.Unix.cHardlinks = Data.nNumberOfLinks ? Data.nNumberOfLinks : 1;
947 pObjInfo->Attr.u.Unix.INodeIdDevice = Data.dwVolumeSerialNumber;
948 pObjInfo->Attr.u.Unix.INodeId = RT_MAKE_U64(Data.nFileIndexLow, Data.nFileIndexHigh);
949 pObjInfo->Attr.u.Unix.fFlags = 0;
950 pObjInfo->Attr.u.Unix.GenerationId = 0;
951 pObjInfo->Attr.u.Unix.Device = 0;
952 break;
953
954 case RTFSOBJATTRADD_UNIX_OWNER:
955 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_OWNER;
956 pObjInfo->Attr.u.UnixOwner.uid = ~0U;
957 pObjInfo->Attr.u.UnixOwner.szName[0] = '\0'; /** @todo return something sensible here. */
958 break;
959
960 case RTFSOBJATTRADD_UNIX_GROUP:
961 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_GROUP;
962 pObjInfo->Attr.u.UnixGroup.gid = ~0U;
963 pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
964 break;
965
966 case RTFSOBJATTRADD_EASIZE:
967 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
968 pObjInfo->Attr.u.EASize.cb = 0;
969 break;
970
971 default:
972 AssertMsgFailed(("Impossible!\n"));
973 return VERR_INTERNAL_ERROR;
974 }
975
976 return VINF_SUCCESS;
977}
978
979
980RTR3DECL(int) RTFileSetTimes(RTFILE hFile, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
981 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
982{
983 RT_NOREF_PV(pChangeTime); /* Not exposed thru the windows API we're using. */
984
985 if (!pAccessTime && !pModificationTime && !pBirthTime)
986 return VINF_SUCCESS; /* NOP */
987
988 FILETIME CreationTimeFT;
989 PFILETIME pCreationTimeFT = NULL;
990 if (pBirthTime)
991 pCreationTimeFT = RTTimeSpecGetNtFileTime(pBirthTime, &CreationTimeFT);
992
993 FILETIME LastAccessTimeFT;
994 PFILETIME pLastAccessTimeFT = NULL;
995 if (pAccessTime)
996 pLastAccessTimeFT = RTTimeSpecGetNtFileTime(pAccessTime, &LastAccessTimeFT);
997
998 FILETIME LastWriteTimeFT;
999 PFILETIME pLastWriteTimeFT = NULL;
1000 if (pModificationTime)
1001 pLastWriteTimeFT = RTTimeSpecGetNtFileTime(pModificationTime, &LastWriteTimeFT);
1002
1003 int rc = VINF_SUCCESS;
1004 if (!SetFileTime((HANDLE)RTFileToNative(hFile), pCreationTimeFT, pLastAccessTimeFT, pLastWriteTimeFT))
1005 {
1006 DWORD Err = GetLastError();
1007 rc = RTErrConvertFromWin32(Err);
1008 Log(("RTFileSetTimes(%RTfile, %p, %p, %p, %p): SetFileTime failed with lasterr %d (%Rrc)\n",
1009 hFile, pAccessTime, pModificationTime, pChangeTime, pBirthTime, Err, rc));
1010 }
1011 return rc;
1012}
1013
1014
1015#if 0 /* RTFileSetMode is implemented by RTFileSetMode-r3-nt.cpp */
1016/* This comes from a source file with a different set of system headers (DDK)
1017 * so it can't be declared in a common header, like internal/file.h.
1018 */
1019extern int rtFileNativeSetAttributes(HANDLE FileHandle, ULONG FileAttributes);
1020
1021
1022RTR3DECL(int) RTFileSetMode(RTFILE hFile, RTFMODE fMode)
1023{
1024 /*
1025 * Normalize the mode and call the API.
1026 */
1027 fMode = rtFsModeNormalize(fMode, NULL, 0);
1028 if (!rtFsModeIsValid(fMode))
1029 return VERR_INVALID_PARAMETER;
1030
1031 ULONG FileAttributes = (fMode & RTFS_DOS_MASK) >> RTFS_DOS_SHIFT;
1032 int Err = rtFileNativeSetAttributes((HANDLE)hFile, FileAttributes);
1033 if (Err != ERROR_SUCCESS)
1034 {
1035 int rc = RTErrConvertFromWin32(Err);
1036 Log(("RTFileSetMode(%RTfile, %RTfmode): rtFileNativeSetAttributes (0x%08X) failed with err %d (%Rrc)\n",
1037 hFile, fMode, FileAttributes, Err, rc));
1038 return rc;
1039 }
1040 return VINF_SUCCESS;
1041}
1042#endif
1043
1044
1045/* RTFileQueryFsSizes is implemented by ../nt/RTFileQueryFsSizes-nt.cpp */
1046
1047
1048RTR3DECL(int) RTFileDelete(const char *pszFilename)
1049{
1050 PRTUTF16 pwszFilename;
1051 int rc = RTStrToUtf16(pszFilename, &pwszFilename);
1052 if (RT_SUCCESS(rc))
1053 {
1054 if (!DeleteFileW(pwszFilename))
1055 rc = RTErrConvertFromWin32(GetLastError());
1056 RTUtf16Free(pwszFilename);
1057 }
1058
1059 return rc;
1060}
1061
1062
1063RTDECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
1064{
1065 /*
1066 * Validate input.
1067 */
1068 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
1069 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
1070 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
1071
1072 /*
1073 * Hand it on to the worker.
1074 */
1075 int rc = rtPathWin32MoveRename(pszSrc, pszDst,
1076 fRename & RTPATHRENAME_FLAGS_REPLACE ? MOVEFILE_REPLACE_EXISTING : 0,
1077 RTFS_TYPE_FILE);
1078
1079 LogFlow(("RTFileMove(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
1080 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
1081 return rc;
1082
1083}
1084
1085
1086RTDECL(int) RTFileMove(const char *pszSrc, const char *pszDst, unsigned fMove)
1087{
1088 /*
1089 * Validate input.
1090 */
1091 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
1092 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
1093 AssertMsgReturn(!(fMove & ~RTFILEMOVE_FLAGS_REPLACE), ("%#x\n", fMove), VERR_INVALID_PARAMETER);
1094
1095 /*
1096 * Hand it on to the worker.
1097 */
1098 int rc = rtPathWin32MoveRename(pszSrc, pszDst,
1099 fMove & RTFILEMOVE_FLAGS_REPLACE
1100 ? MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING
1101 : MOVEFILE_COPY_ALLOWED,
1102 RTFS_TYPE_FILE);
1103
1104 LogFlow(("RTFileMove(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
1105 pszSrc, pszSrc, pszDst, pszDst, fMove, rc));
1106 return rc;
1107}
1108
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