VirtualBox

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

Last change on this file since 76553 was 76553, checked in by vboxsync, 5 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 38.2 KB
Line 
1/* $Id: fileio-win.cpp 76553 2019-01-01 01:45:53Z vboxsync $ */
2/** @file
3 * IPRT - File I/O, native implementation for the Windows host platform.
4 */
5
6/*
7 * Copyright (C) 2006-2019 Oracle Corporation
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
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/nt/nt-and-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 PRTUTF16 pwszFilename;
293 rc = RTPathWinFromUtf8(&pwszFilename, pszFilename, 0 /*fFlags*/);
294 if (RT_SUCCESS(rc))
295 {
296 HANDLE hFile = CreateFileW(pwszFilename,
297 dwDesiredAccess,
298 dwShareMode,
299 pSecurityAttributes,
300 dwCreationDisposition,
301 dwFlagsAndAttributes,
302 NULL);
303 if (hFile != INVALID_HANDLE_VALUE)
304 {
305 bool fCreated = dwCreationDisposition == CREATE_ALWAYS
306 || dwCreationDisposition == CREATE_NEW
307 || (dwCreationDisposition == OPEN_ALWAYS && GetLastError() == 0);
308
309 /*
310 * Turn off indexing of directory through Windows Indexing Service.
311 */
312 if ( fCreated
313 && (fOpen & RTFILE_O_NOT_CONTENT_INDEXED))
314 {
315 if (!SetFileAttributesW(pwszFilename, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED))
316 rc = RTErrConvertFromWin32(GetLastError());
317 }
318 /*
319 * Do we need to truncate the file?
320 */
321 else if ( !fCreated
322 && (fOpen & (RTFILE_O_TRUNCATE | RTFILE_O_ACTION_MASK))
323 == (RTFILE_O_TRUNCATE | RTFILE_O_OPEN_CREATE))
324 {
325 if (!SetEndOfFile(hFile))
326 rc = RTErrConvertFromWin32(GetLastError());
327 }
328 if (RT_SUCCESS(rc))
329 {
330 *pFile = (RTFILE)hFile;
331 Assert((HANDLE)*pFile == hFile);
332 RTPathWinFree(pwszFilename);
333 return VINF_SUCCESS;
334 }
335
336 CloseHandle(hFile);
337 }
338 else
339 rc = RTErrConvertFromWin32(GetLastError());
340 RTPathWinFree(pwszFilename);
341 }
342 return rc;
343}
344
345
346RTR3DECL(int) RTFileOpenBitBucket(PRTFILE phFile, uint64_t fAccess)
347{
348 AssertReturn( fAccess == RTFILE_O_READ
349 || fAccess == RTFILE_O_WRITE
350 || fAccess == RTFILE_O_READWRITE,
351 VERR_INVALID_PARAMETER);
352 return RTFileOpen(phFile, "NUL", fAccess | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
353}
354
355
356RTR3DECL(int) RTFileClose(RTFILE hFile)
357{
358 if (hFile == NIL_RTFILE)
359 return VINF_SUCCESS;
360 if (CloseHandle((HANDLE)RTFileToNative(hFile)))
361 return VINF_SUCCESS;
362 return RTErrConvertFromWin32(GetLastError());
363}
364
365
366RTFILE rtFileGetStandard(RTHANDLESTD enmStdHandle)
367{
368 DWORD dwStdHandle;
369 switch (enmStdHandle)
370 {
371 case RTHANDLESTD_INPUT: dwStdHandle = STD_INPUT_HANDLE; break;
372 case RTHANDLESTD_OUTPUT: dwStdHandle = STD_OUTPUT_HANDLE; break;
373 case RTHANDLESTD_ERROR: dwStdHandle = STD_ERROR_HANDLE; break;
374 default:
375 AssertFailedReturn(NIL_RTFILE);
376 }
377
378 HANDLE hNative = GetStdHandle(dwStdHandle);
379 if (hNative == INVALID_HANDLE_VALUE)
380 return NIL_RTFILE;
381
382 RTFILE hFile = (RTFILE)(uintptr_t)hNative;
383 AssertReturn((HANDLE)(uintptr_t)hFile == hNative, NIL_RTFILE);
384 return hFile;
385}
386
387
388RTR3DECL(int) RTFileSeek(RTFILE hFile, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
389{
390 static ULONG aulSeekRecode[] =
391 {
392 FILE_BEGIN,
393 FILE_CURRENT,
394 FILE_END,
395 };
396
397 /*
398 * Validate input.
399 */
400 if (uMethod > RTFILE_SEEK_END)
401 {
402 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
403 return VERR_INVALID_PARAMETER;
404 }
405
406 /*
407 * Execute the seek.
408 */
409 if (MySetFilePointer(hFile, offSeek, poffActual, aulSeekRecode[uMethod]))
410 return VINF_SUCCESS;
411 return RTErrConvertFromWin32(GetLastError());
412}
413
414
415RTR3DECL(int) RTFileRead(RTFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
416{
417 if (cbToRead <= 0)
418 return VINF_SUCCESS;
419 ULONG cbToReadAdj = (ULONG)cbToRead;
420 AssertReturn(cbToReadAdj == cbToRead, VERR_NUMBER_TOO_BIG);
421
422 ULONG cbRead = 0;
423 if (ReadFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToReadAdj, &cbRead, NULL))
424 {
425 if (pcbRead)
426 /* Caller can handle partial reads. */
427 *pcbRead = cbRead;
428 else
429 {
430 /* Caller expects everything to be read. */
431 while (cbToReadAdj > cbRead)
432 {
433 ULONG cbReadPart = 0;
434 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbRead, cbToReadAdj - cbRead, &cbReadPart, NULL))
435 return RTErrConvertFromWin32(GetLastError());
436 if (cbReadPart == 0)
437 return VERR_EOF;
438 cbRead += cbReadPart;
439 }
440 }
441 return VINF_SUCCESS;
442 }
443
444 /*
445 * If it's a console, we might bump into out of memory conditions in the
446 * ReadConsole call.
447 */
448 DWORD dwErr = GetLastError();
449 if (dwErr == ERROR_NOT_ENOUGH_MEMORY)
450 {
451 ULONG cbChunk = cbToReadAdj / 2;
452 if (cbChunk > 16*_1K)
453 cbChunk = 16*_1K;
454 else
455 cbChunk = RT_ALIGN_32(cbChunk, 256);
456
457 cbRead = 0;
458 while (cbToReadAdj > cbRead)
459 {
460 ULONG cbToRead = RT_MIN(cbChunk, cbToReadAdj - cbRead);
461 ULONG cbReadPart = 0;
462 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char *)pvBuf + cbRead, cbToRead, &cbReadPart, NULL))
463 {
464 /* If we failed because the buffer is too big, shrink it and
465 try again. */
466 dwErr = GetLastError();
467 if ( dwErr == ERROR_NOT_ENOUGH_MEMORY
468 && cbChunk > 8)
469 {
470 cbChunk /= 2;
471 continue;
472 }
473 return RTErrConvertFromWin32(dwErr);
474 }
475 cbRead += cbReadPart;
476
477 /* Return if the caller can handle partial reads, otherwise try
478 fill the buffer all the way up. */
479 if (pcbRead)
480 {
481 *pcbRead = cbRead;
482 break;
483 }
484 if (cbReadPart == 0)
485 return VERR_EOF;
486 }
487 return VINF_SUCCESS;
488 }
489
490 return RTErrConvertFromWin32(dwErr);
491}
492
493
494RTR3DECL(int) RTFileWrite(RTFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
495{
496 if (cbToWrite <= 0)
497 return VINF_SUCCESS;
498 ULONG const cbToWriteAdj = (ULONG)cbToWrite;
499 AssertReturn(cbToWriteAdj == cbToWrite, VERR_NUMBER_TOO_BIG);
500
501 ULONG cbWritten = 0;
502 if (WriteFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToWriteAdj, &cbWritten, NULL))
503 {
504 if (pcbWritten)
505 /* Caller can handle partial writes. */
506 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
507 else
508 {
509 /* Caller expects everything to be written. */
510 while (cbWritten < cbToWriteAdj)
511 {
512 ULONG cbWrittenPart = 0;
513 if (!WriteFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbWritten,
514 cbToWriteAdj - cbWritten, &cbWrittenPart, NULL))
515 {
516 int rc = RTErrConvertFromWin32(GetLastError());
517 if ( rc == VERR_DISK_FULL
518 && IsBeyondLimit(hFile, cbToWriteAdj - cbWritten, FILE_CURRENT)
519 )
520 rc = VERR_FILE_TOO_BIG;
521 return rc;
522 }
523 if (cbWrittenPart == 0)
524 return VERR_WRITE_ERROR;
525 cbWritten += cbWrittenPart;
526 }
527 }
528 return VINF_SUCCESS;
529 }
530
531 /*
532 * If it's a console, we might bump into out of memory conditions in the
533 * WriteConsole call.
534 */
535 DWORD dwErr = GetLastError();
536 if (dwErr == ERROR_NOT_ENOUGH_MEMORY)
537 {
538 ULONG cbChunk = cbToWriteAdj / 2;
539 if (cbChunk > _32K)
540 cbChunk = _32K;
541 else
542 cbChunk = RT_ALIGN_32(cbChunk, 256);
543
544 cbWritten = 0;
545 while (cbWritten < cbToWriteAdj)
546 {
547 ULONG cbToWrite = RT_MIN(cbChunk, cbToWriteAdj - cbWritten);
548 ULONG cbWrittenPart = 0;
549 if (!WriteFile((HANDLE)RTFileToNative(hFile), (const char *)pvBuf + cbWritten, cbToWrite, &cbWrittenPart, NULL))
550 {
551 /* If we failed because the buffer is too big, shrink it and
552 try again. */
553 dwErr = GetLastError();
554 if ( dwErr == ERROR_NOT_ENOUGH_MEMORY
555 && cbChunk > 8)
556 {
557 cbChunk /= 2;
558 continue;
559 }
560 int rc = RTErrConvertFromWin32(dwErr);
561 if ( rc == VERR_DISK_FULL
562 && IsBeyondLimit(hFile, cbToWriteAdj - cbWritten, FILE_CURRENT))
563 rc = VERR_FILE_TOO_BIG;
564 return rc;
565 }
566 cbWritten += cbWrittenPart;
567
568 /* Return if the caller can handle partial writes, otherwise try
569 write out everything. */
570 if (pcbWritten)
571 {
572 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
573 break;
574 }
575 if (cbWrittenPart == 0)
576 return VERR_WRITE_ERROR;
577 }
578 return VINF_SUCCESS;
579 }
580
581 int rc = RTErrConvertFromWin32(dwErr);
582 if ( rc == VERR_DISK_FULL
583 && IsBeyondLimit(hFile, cbToWriteAdj - cbWritten, FILE_CURRENT))
584 rc = VERR_FILE_TOO_BIG;
585 return rc;
586}
587
588
589RTR3DECL(int) RTFileFlush(RTFILE hFile)
590{
591 if (!FlushFileBuffers((HANDLE)RTFileToNative(hFile)))
592 {
593 int rc = GetLastError();
594 Log(("FlushFileBuffers failed with %d\n", rc));
595 return RTErrConvertFromWin32(rc);
596 }
597 return VINF_SUCCESS;
598}
599
600
601RTR3DECL(int) RTFileSetSize(RTFILE hFile, uint64_t cbSize)
602{
603 /*
604 * Get current file pointer.
605 */
606 int rc;
607 uint64_t offCurrent;
608 if (MySetFilePointer(hFile, 0, &offCurrent, FILE_CURRENT))
609 {
610 /*
611 * Set new file pointer.
612 */
613 if (MySetFilePointer(hFile, cbSize, NULL, FILE_BEGIN))
614 {
615 /* set file pointer */
616 if (SetEndOfFile((HANDLE)RTFileToNative(hFile)))
617 {
618 /*
619 * Restore file pointer and return.
620 * If the old pointer was beyond the new file end, ignore failure.
621 */
622 if ( MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN)
623 || offCurrent > cbSize)
624 return VINF_SUCCESS;
625 }
626
627 /*
628 * Failed, try restoring the file pointer.
629 */
630 rc = GetLastError();
631 MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN);
632 }
633 else
634 rc = GetLastError();
635 }
636 else
637 rc = GetLastError();
638
639 return RTErrConvertFromWin32(rc);
640}
641
642
643RTR3DECL(int) RTFileGetSize(RTFILE hFile, uint64_t *pcbSize)
644{
645 /*
646 * GetFileSize works for most handles.
647 */
648 ULARGE_INTEGER Size;
649 Size.LowPart = GetFileSize((HANDLE)RTFileToNative(hFile), &Size.HighPart);
650 if (Size.LowPart != INVALID_FILE_SIZE)
651 {
652 *pcbSize = Size.QuadPart;
653 return VINF_SUCCESS;
654 }
655 int rc = RTErrConvertFromWin32(GetLastError());
656
657 /*
658 * Could it be a volume or a disk?
659 */
660 DISK_GEOMETRY DriveGeo;
661 DWORD cbDriveGeo;
662 if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
663 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
664 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
665 {
666 if ( DriveGeo.MediaType == FixedMedia
667 || DriveGeo.MediaType == RemovableMedia)
668 {
669 *pcbSize = DriveGeo.Cylinders.QuadPart
670 * DriveGeo.TracksPerCylinder
671 * DriveGeo.SectorsPerTrack
672 * DriveGeo.BytesPerSector;
673
674 GET_LENGTH_INFORMATION DiskLenInfo;
675 DWORD Ignored;
676 if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
677 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
678 &DiskLenInfo, sizeof(DiskLenInfo), &Ignored, (LPOVERLAPPED)NULL))
679 {
680 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
681 *pcbSize = DiskLenInfo.Length.QuadPart;
682 }
683 return VINF_SUCCESS;
684 }
685 }
686
687 /*
688 * Return the GetFileSize result if not a volume/disk.
689 */
690 return rc;
691}
692
693
694RTR3DECL(int) RTFileGetMaxSizeEx(RTFILE hFile, PRTFOFF pcbMax)
695{
696 /** @todo r=bird:
697 * We might have to make this code OS version specific... In the worse
698 * case, we'll have to try GetVolumeInformationByHandle on vista and fall
699 * back on NtQueryVolumeInformationFile(,,,, FileFsAttributeInformation)
700 * else where, and check for known file system names. (For LAN shares we'll
701 * have to figure out the remote file system.) */
702 RT_NOREF_PV(hFile); RT_NOREF_PV(pcbMax);
703 return VERR_NOT_IMPLEMENTED;
704}
705
706
707RTR3DECL(bool) RTFileIsValid(RTFILE hFile)
708{
709 if (hFile != NIL_RTFILE)
710 {
711 DWORD dwType = GetFileType((HANDLE)RTFileToNative(hFile));
712 switch (dwType)
713 {
714 case FILE_TYPE_CHAR:
715 case FILE_TYPE_DISK:
716 case FILE_TYPE_PIPE:
717 case FILE_TYPE_REMOTE:
718 return true;
719
720 case FILE_TYPE_UNKNOWN:
721 if (GetLastError() == NO_ERROR)
722 return true;
723 break;
724
725 default:
726 break;
727 }
728 }
729 return false;
730}
731
732
733#define LOW_DWORD(u64) ((DWORD)u64)
734#define HIGH_DWORD(u64) (((DWORD *)&u64)[1])
735
736RTR3DECL(int) RTFileLock(RTFILE hFile, unsigned fLock, int64_t offLock, uint64_t cbLock)
737{
738 Assert(offLock >= 0);
739
740 /* Check arguments. */
741 if (fLock & ~RTFILE_LOCK_MASK)
742 {
743 AssertMsgFailed(("Invalid fLock=%08X\n", fLock));
744 return VERR_INVALID_PARAMETER;
745 }
746
747 /* Prepare flags. */
748 Assert(RTFILE_LOCK_WRITE);
749 DWORD dwFlags = (fLock & RTFILE_LOCK_WRITE) ? LOCKFILE_EXCLUSIVE_LOCK : 0;
750 Assert(RTFILE_LOCK_WAIT);
751 if (!(fLock & RTFILE_LOCK_WAIT))
752 dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
753
754 /* Windows structure. */
755 OVERLAPPED Overlapped;
756 memset(&Overlapped, 0, sizeof(Overlapped));
757 Overlapped.Offset = LOW_DWORD(offLock);
758 Overlapped.OffsetHigh = HIGH_DWORD(offLock);
759
760 /* Note: according to Microsoft, LockFileEx API call is available starting from NT 3.5 */
761 if (LockFileEx((HANDLE)RTFileToNative(hFile), dwFlags, 0, LOW_DWORD(cbLock), HIGH_DWORD(cbLock), &Overlapped))
762 return VINF_SUCCESS;
763
764 return RTErrConvertFromWin32(GetLastError());
765}
766
767
768RTR3DECL(int) RTFileChangeLock(RTFILE hFile, unsigned fLock, int64_t offLock, uint64_t cbLock)
769{
770 Assert(offLock >= 0);
771
772 /* Check arguments. */
773 if (fLock & ~RTFILE_LOCK_MASK)
774 {
775 AssertMsgFailed(("Invalid fLock=%08X\n", fLock));
776 return VERR_INVALID_PARAMETER;
777 }
778
779 /* Remove old lock. */
780 int rc = RTFileUnlock(hFile, offLock, cbLock);
781 if (RT_FAILURE(rc))
782 return rc;
783
784 /* Set new lock. */
785 rc = RTFileLock(hFile, fLock, offLock, cbLock);
786 if (RT_SUCCESS(rc))
787 return rc;
788
789 /* Try to restore old lock. */
790 unsigned fLockOld = (fLock & RTFILE_LOCK_WRITE) ? fLock & ~RTFILE_LOCK_WRITE : fLock | RTFILE_LOCK_WRITE;
791 rc = RTFileLock(hFile, fLockOld, offLock, cbLock);
792 if (RT_SUCCESS(rc))
793 return VERR_FILE_LOCK_VIOLATION;
794 else
795 return VERR_FILE_LOCK_LOST;
796}
797
798
799RTR3DECL(int) RTFileUnlock(RTFILE hFile, int64_t offLock, uint64_t cbLock)
800{
801 Assert(offLock >= 0);
802
803 if (UnlockFile((HANDLE)RTFileToNative(hFile),
804 LOW_DWORD(offLock), HIGH_DWORD(offLock),
805 LOW_DWORD(cbLock), HIGH_DWORD(cbLock)))
806 return VINF_SUCCESS;
807
808 return RTErrConvertFromWin32(GetLastError());
809}
810
811
812
813RTR3DECL(int) RTFileQueryInfo(RTFILE hFile, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
814{
815 /*
816 * Validate input.
817 */
818 if (hFile == NIL_RTFILE)
819 {
820 AssertMsgFailed(("Invalid hFile=%RTfile\n", hFile));
821 return VERR_INVALID_PARAMETER;
822 }
823 if (!pObjInfo)
824 {
825 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
826 return VERR_INVALID_PARAMETER;
827 }
828 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
829 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
830 {
831 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
832 return VERR_INVALID_PARAMETER;
833 }
834
835 /*
836 * Query file info.
837 */
838 HANDLE hHandle = (HANDLE)RTFileToNative(hFile);
839#if 1
840 uint64_t auBuf[168 / sizeof(uint64_t)]; /* Missing FILE_ALL_INFORMATION here. */
841 int rc = rtPathNtQueryInfoFromHandle(hFile, auBuf, sizeof(auBuf), pObjInfo, enmAdditionalAttribs, NULL, 0);
842 if (RT_SUCCESS(rc))
843 return rc;
844
845 /*
846 * Console I/O handles make trouble here. On older windows versions they
847 * end up with ERROR_INVALID_HANDLE when handed to the above API, while on
848 * more recent ones they cause different errors to appear.
849 *
850 * Thus, we must ignore the latter and doubly verify invalid handle claims.
851 * We use the undocumented VerifyConsoleIoHandle to do this, falling back on
852 * GetFileType should it not be there.
853 */
854 if ( rc == VERR_INVALID_HANDLE
855 || rc == VERR_ACCESS_DENIED
856 || rc == VERR_UNEXPECTED_FS_OBJ_TYPE)
857 {
858 static PFNVERIFYCONSOLEIOHANDLE s_pfnVerifyConsoleIoHandle = NULL;
859 static bool volatile s_fInitialized = false;
860 PFNVERIFYCONSOLEIOHANDLE pfnVerifyConsoleIoHandle;
861 if (s_fInitialized)
862 pfnVerifyConsoleIoHandle = s_pfnVerifyConsoleIoHandle;
863 else
864 {
865 pfnVerifyConsoleIoHandle = (PFNVERIFYCONSOLEIOHANDLE)RTLdrGetSystemSymbol("kernel32.dll", "VerifyConsoleIoHandle");
866 ASMAtomicWriteBool(&s_fInitialized, true);
867 }
868 if ( pfnVerifyConsoleIoHandle
869 ? !pfnVerifyConsoleIoHandle(hHandle)
870 : GetFileType(hHandle) == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR)
871 return VERR_INVALID_HANDLE;
872 }
873 /*
874 * On Windows 10 and (hopefully) 8.1 we get ERROR_INVALID_FUNCTION with console
875 * I/O handles and null device handles. We must ignore these just like the
876 * above invalid handle error.
877 */
878 else if (rc != VERR_INVALID_FUNCTION && rc != VERR_IO_BAD_COMMAND)
879 return rc;
880
881 RT_ZERO(*pObjInfo);
882 pObjInfo->Attr.enmAdditional = enmAdditionalAttribs;
883 pObjInfo->Attr.fMode = rtFsModeFromDos(RTFS_DOS_NT_DEVICE, "", 0, 0);
884 return VINF_SUCCESS;
885#else
886
887 BY_HANDLE_FILE_INFORMATION Data;
888 if (!GetFileInformationByHandle(hHandle, &Data))
889 {
890 /*
891 * Console I/O handles make trouble here. On older windows versions they
892 * end up with ERROR_INVALID_HANDLE when handed to the above API, while on
893 * more recent ones they cause different errors to appear.
894 *
895 * Thus, we must ignore the latter and doubly verify invalid handle claims.
896 * We use the undocumented VerifyConsoleIoHandle to do this, falling back on
897 * GetFileType should it not be there.
898 */
899 DWORD dwErr = GetLastError();
900 if (dwErr == ERROR_INVALID_HANDLE)
901 {
902 static PFNVERIFYCONSOLEIOHANDLE s_pfnVerifyConsoleIoHandle = NULL;
903 static bool volatile s_fInitialized = false;
904 PFNVERIFYCONSOLEIOHANDLE pfnVerifyConsoleIoHandle;
905 if (s_fInitialized)
906 pfnVerifyConsoleIoHandle = s_pfnVerifyConsoleIoHandle;
907 else
908 {
909 pfnVerifyConsoleIoHandle = (PFNVERIFYCONSOLEIOHANDLE)RTLdrGetSystemSymbol("kernel32.dll", "VerifyConsoleIoHandle");
910 ASMAtomicWriteBool(&s_fInitialized, true);
911 }
912 if ( pfnVerifyConsoleIoHandle
913 ? !pfnVerifyConsoleIoHandle(hHandle)
914 : GetFileType(hHandle) == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR)
915 return VERR_INVALID_HANDLE;
916 }
917 /*
918 * On Windows 10 and (hopefully) 8.1 we get ERROR_INVALID_FUNCTION with console I/O
919 * handles. We must ignore these just like the above invalid handle error.
920 */
921 else if (dwErr != ERROR_INVALID_FUNCTION)
922 return RTErrConvertFromWin32(dwErr);
923
924 RT_ZERO(Data);
925 Data.dwFileAttributes = RTFS_DOS_NT_DEVICE;
926 }
927
928 /*
929 * Setup the returned data.
930 */
931 pObjInfo->cbObject = ((uint64_t)Data.nFileSizeHigh << 32)
932 | (uint64_t)Data.nFileSizeLow;
933 pObjInfo->cbAllocated = pObjInfo->cbObject;
934
935 Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
936 RTTimeSpecSetNtTime(&pObjInfo->BirthTime, *(uint64_t *)&Data.ftCreationTime);
937 RTTimeSpecSetNtTime(&pObjInfo->AccessTime, *(uint64_t *)&Data.ftLastAccessTime);
938 RTTimeSpecSetNtTime(&pObjInfo->ModificationTime, *(uint64_t *)&Data.ftLastWriteTime);
939 pObjInfo->ChangeTime = pObjInfo->ModificationTime;
940
941 pObjInfo->Attr.fMode = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT, "", 0,
942 RTFSMODE_SYMLINK_REPARSE_TAG /* (symlink or not, doesn't usually matter here) */);
943
944 /*
945 * Requested attributes (we cannot provide anything actually).
946 */
947 switch (enmAdditionalAttribs)
948 {
949 case RTFSOBJATTRADD_NOTHING:
950 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_NOTHING;
951 break;
952
953 case RTFSOBJATTRADD_UNIX:
954 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX;
955 pObjInfo->Attr.u.Unix.uid = ~0U;
956 pObjInfo->Attr.u.Unix.gid = ~0U;
957 pObjInfo->Attr.u.Unix.cHardlinks = Data.nNumberOfLinks ? Data.nNumberOfLinks : 1;
958 pObjInfo->Attr.u.Unix.INodeIdDevice = Data.dwVolumeSerialNumber;
959 pObjInfo->Attr.u.Unix.INodeId = RT_MAKE_U64(Data.nFileIndexLow, Data.nFileIndexHigh);
960 pObjInfo->Attr.u.Unix.fFlags = 0;
961 pObjInfo->Attr.u.Unix.GenerationId = 0;
962 pObjInfo->Attr.u.Unix.Device = 0;
963 break;
964
965 case RTFSOBJATTRADD_UNIX_OWNER:
966 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_OWNER;
967 pObjInfo->Attr.u.UnixOwner.uid = ~0U;
968 pObjInfo->Attr.u.UnixOwner.szName[0] = '\0'; /** @todo return something sensible here. */
969 break;
970
971 case RTFSOBJATTRADD_UNIX_GROUP:
972 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_GROUP;
973 pObjInfo->Attr.u.UnixGroup.gid = ~0U;
974 pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
975 break;
976
977 case RTFSOBJATTRADD_EASIZE:
978 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
979 pObjInfo->Attr.u.EASize.cb = 0;
980 break;
981
982 default:
983 AssertMsgFailed(("Impossible!\n"));
984 return VERR_INTERNAL_ERROR;
985 }
986
987 return VINF_SUCCESS;
988#endif
989}
990
991
992RTR3DECL(int) RTFileSetTimes(RTFILE hFile, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
993 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
994{
995 RT_NOREF_PV(pChangeTime); /* Not exposed thru the windows API we're using. */
996
997 if (!pAccessTime && !pModificationTime && !pBirthTime)
998 return VINF_SUCCESS; /* NOP */
999
1000 FILETIME CreationTimeFT;
1001 PFILETIME pCreationTimeFT = NULL;
1002 if (pBirthTime)
1003 pCreationTimeFT = RTTimeSpecGetNtFileTime(pBirthTime, &CreationTimeFT);
1004
1005 FILETIME LastAccessTimeFT;
1006 PFILETIME pLastAccessTimeFT = NULL;
1007 if (pAccessTime)
1008 pLastAccessTimeFT = RTTimeSpecGetNtFileTime(pAccessTime, &LastAccessTimeFT);
1009
1010 FILETIME LastWriteTimeFT;
1011 PFILETIME pLastWriteTimeFT = NULL;
1012 if (pModificationTime)
1013 pLastWriteTimeFT = RTTimeSpecGetNtFileTime(pModificationTime, &LastWriteTimeFT);
1014
1015 int rc = VINF_SUCCESS;
1016 if (!SetFileTime((HANDLE)RTFileToNative(hFile), pCreationTimeFT, pLastAccessTimeFT, pLastWriteTimeFT))
1017 {
1018 DWORD Err = GetLastError();
1019 rc = RTErrConvertFromWin32(Err);
1020 Log(("RTFileSetTimes(%RTfile, %p, %p, %p, %p): SetFileTime failed with lasterr %d (%Rrc)\n",
1021 hFile, pAccessTime, pModificationTime, pChangeTime, pBirthTime, Err, rc));
1022 }
1023 return rc;
1024}
1025
1026
1027#if 0 /* RTFileSetMode is implemented by RTFileSetMode-r3-nt.cpp */
1028/* This comes from a source file with a different set of system headers (DDK)
1029 * so it can't be declared in a common header, like internal/file.h.
1030 */
1031extern int rtFileNativeSetAttributes(HANDLE FileHandle, ULONG FileAttributes);
1032
1033
1034RTR3DECL(int) RTFileSetMode(RTFILE hFile, RTFMODE fMode)
1035{
1036 /*
1037 * Normalize the mode and call the API.
1038 */
1039 fMode = rtFsModeNormalize(fMode, NULL, 0);
1040 if (!rtFsModeIsValid(fMode))
1041 return VERR_INVALID_PARAMETER;
1042
1043 ULONG FileAttributes = (fMode & RTFS_DOS_MASK) >> RTFS_DOS_SHIFT;
1044 int Err = rtFileNativeSetAttributes((HANDLE)hFile, FileAttributes);
1045 if (Err != ERROR_SUCCESS)
1046 {
1047 int rc = RTErrConvertFromWin32(Err);
1048 Log(("RTFileSetMode(%RTfile, %RTfmode): rtFileNativeSetAttributes (0x%08X) failed with err %d (%Rrc)\n",
1049 hFile, fMode, FileAttributes, Err, rc));
1050 return rc;
1051 }
1052 return VINF_SUCCESS;
1053}
1054#endif
1055
1056
1057/* RTFileQueryFsSizes is implemented by ../nt/RTFileQueryFsSizes-nt.cpp */
1058
1059
1060RTR3DECL(int) RTFileDelete(const char *pszFilename)
1061{
1062 PRTUTF16 pwszFilename;
1063 int rc = RTPathWinFromUtf8(&pwszFilename, pszFilename, 0 /*fFlags*/);
1064 if (RT_SUCCESS(rc))
1065 {
1066 if (!DeleteFileW(pwszFilename))
1067 rc = RTErrConvertFromWin32(GetLastError());
1068 RTPathWinFree(pwszFilename);
1069 }
1070
1071 return rc;
1072}
1073
1074
1075RTDECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
1076{
1077 /*
1078 * Validate input.
1079 */
1080 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
1081 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
1082 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
1083
1084 /*
1085 * Hand it on to the worker.
1086 */
1087 int rc = rtPathWin32MoveRename(pszSrc, pszDst,
1088 fRename & RTPATHRENAME_FLAGS_REPLACE ? MOVEFILE_REPLACE_EXISTING : 0,
1089 RTFS_TYPE_FILE);
1090
1091 LogFlow(("RTFileMove(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
1092 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
1093 return rc;
1094
1095}
1096
1097
1098RTDECL(int) RTFileMove(const char *pszSrc, const char *pszDst, unsigned fMove)
1099{
1100 /*
1101 * Validate input.
1102 */
1103 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
1104 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
1105 AssertMsgReturn(!(fMove & ~RTFILEMOVE_FLAGS_REPLACE), ("%#x\n", fMove), VERR_INVALID_PARAMETER);
1106
1107 /*
1108 * Hand it on to the worker.
1109 */
1110 int rc = rtPathWin32MoveRename(pszSrc, pszDst,
1111 fMove & RTFILEMOVE_FLAGS_REPLACE
1112 ? MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING
1113 : MOVEFILE_COPY_ALLOWED,
1114 RTFS_TYPE_FILE);
1115
1116 LogFlow(("RTFileMove(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
1117 pszSrc, pszSrc, pszDst, pszDst, fMove, rc));
1118 return rc;
1119}
1120
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use