VirtualBox

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

Last change on this file since 103795 was 99828, checked in by vboxsync, 19 months ago

*: A bunch of adjustments that allows using /permissive- with Visual C++ (qt 6.x necessity).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 54.3 KB
Line 
1/* $Id: fileio-win.cpp 99828 2023-05-17 13:48:57Z vboxsync $ */
2/** @file
3 * IPRT - File I/O, native implementation for the Windows host platform.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#define LOG_GROUP RTLOGGROUP_DIR
42#ifndef _WIN32_WINNT
43# define _WIN32_WINNT 0x0500
44#endif
45#include <iprt/nt/nt-and-windows.h>
46
47#include <iprt/file.h>
48
49#include <iprt/asm.h>
50#include <iprt/assert.h>
51#include <iprt/path.h>
52#include <iprt/string.h>
53#include <iprt/err.h>
54#include <iprt/ldr.h>
55#include <iprt/log.h>
56#include <iprt/utf16.h>
57#include "internal/file.h"
58#include "internal/fs.h"
59#include "internal/path.h"
60#include "internal-r3-win.h" /* For g_enmWinVer + kRTWinOSType_XXX */
61
62
63/*********************************************************************************************************************************
64* Defined Constants And Macros *
65*********************************************************************************************************************************/
66typedef BOOL WINAPI FNVERIFYCONSOLEIOHANDLE(HANDLE);
67typedef FNVERIFYCONSOLEIOHANDLE *PFNVERIFYCONSOLEIOHANDLE; /* No, nobody fell on the keyboard, really! */
68
69
70/**
71 * This is wrapper around the ugly SetFilePointer api.
72 *
73 * It's equivalent to SetFilePointerEx which we so unfortunately cannot use because of
74 * it not being present in NT4 GA.
75 *
76 * @returns Success indicator. Extended error information obtainable using GetLastError().
77 * @param hFile Filehandle.
78 * @param offSeek Offset to seek.
79 * @param poffNew Where to store the new file offset. NULL allowed.
80 * @param uMethod Seek method. (The windows one!)
81 */
82DECLINLINE(bool) MySetFilePointer(RTFILE hFile, uint64_t offSeek, uint64_t *poffNew, unsigned uMethod)
83{
84 bool fRc;
85 LARGE_INTEGER off;
86
87 off.QuadPart = offSeek;
88#if 1
89 if (off.LowPart != INVALID_SET_FILE_POINTER)
90 {
91 off.LowPart = SetFilePointer((HANDLE)RTFileToNative(hFile), off.LowPart, &off.HighPart, uMethod);
92 fRc = off.LowPart != INVALID_SET_FILE_POINTER;
93 }
94 else
95 {
96 SetLastError(NO_ERROR);
97 off.LowPart = SetFilePointer((HANDLE)RTFileToNative(hFile), off.LowPart, &off.HighPart, uMethod);
98 fRc = GetLastError() == NO_ERROR;
99 }
100#else
101 fRc = SetFilePointerEx((HANDLE)RTFileToNative(hFile), off, &off, uMethod);
102#endif
103 if (fRc && poffNew)
104 *poffNew = off.QuadPart;
105 return fRc;
106}
107
108
109/**
110 * Helper for checking if a VERR_DISK_FULL isn't a VERR_FILE_TOO_BIG.
111 * @returns VERR_DISK_FULL or VERR_FILE_TOO_BIG.
112 */
113static int rtFileWinCheckIfDiskReallyFull(RTFILE hFile, uint64_t cbDesired)
114{
115 /*
116 * Windows doesn't appear to have a way to query the file size limit of a
117 * file system, so we have to deduce the limit from the file system driver name.
118 * This means it will only work for known file systems.
119 */
120 if (cbDesired >= _2G - 1)
121 {
122 uint64_t cbMaxFile = UINT64_MAX;
123 RTFSTYPE enmFsType;
124 int rc = rtNtQueryFsType((HANDLE)RTFileToNative(hFile), &enmFsType);
125 if (RT_SUCCESS(rc))
126 switch (enmFsType)
127 {
128 case RTFSTYPE_NTFS:
129 case RTFSTYPE_EXFAT:
130 case RTFSTYPE_UDF:
131 cbMaxFile = UINT64_C(0xffffffffffffffff); /* (May be limited by IFS.) */
132 break;
133
134 case RTFSTYPE_ISO9660:
135 cbMaxFile = 8 *_1T;
136 break;
137
138 case RTFSTYPE_FAT:
139 cbMaxFile = _4G;
140 break;
141
142 case RTFSTYPE_HPFS:
143 cbMaxFile = _2G;
144 break;
145
146 default:
147 break;
148 }
149 if (cbDesired >= cbMaxFile)
150 return VERR_FILE_TOO_BIG;
151 }
152 return VERR_DISK_FULL;
153}
154
155
156RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
157{
158 HANDLE h = (HANDLE)uNative;
159 AssertCompile(sizeof(h) == sizeof(uNative));
160 if (h == INVALID_HANDLE_VALUE)
161 {
162 AssertMsgFailed(("%p\n", uNative));
163 *pFile = NIL_RTFILE;
164 return VERR_INVALID_HANDLE;
165 }
166 *pFile = (RTFILE)h;
167 return VINF_SUCCESS;
168}
169
170
171RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE hFile)
172{
173 AssertReturn(hFile != NIL_RTFILE, (RTHCINTPTR)INVALID_HANDLE_VALUE);
174 return (RTHCINTPTR)hFile;
175}
176
177
178RTR3DECL(int) RTFileOpen(PRTFILE pFile, const char *pszFilename, uint64_t fOpen)
179{
180 return RTFileOpenEx(pszFilename, fOpen, pFile, NULL);
181}
182
183
184RTDECL(int) RTFileOpenEx(const char *pszFilename, uint64_t fOpen, PRTFILE phFile, PRTFILEACTION penmActionTaken)
185{
186 /*
187 * Validate input.
188 */
189 AssertReturn(phFile, VERR_INVALID_PARAMETER);
190 *phFile = NIL_RTFILE;
191 if (penmActionTaken)
192 *penmActionTaken = RTFILEACTION_INVALID;
193 AssertReturn(pszFilename, VERR_INVALID_PARAMETER);
194
195 /*
196 * Merge forced open flags and validate them.
197 */
198 int rc = rtFileRecalcAndValidateFlags(&fOpen);
199 if (RT_FAILURE(rc))
200 return rc;
201
202 /*
203 * Determine disposition, access, share mode, creation flags, and security attributes
204 * for the CreateFile API call.
205 */
206 DWORD dwCreationDisposition;
207 switch (fOpen & RTFILE_O_ACTION_MASK)
208 {
209 case RTFILE_O_OPEN:
210 dwCreationDisposition = fOpen & RTFILE_O_TRUNCATE ? TRUNCATE_EXISTING : OPEN_EXISTING;
211 break;
212 case RTFILE_O_OPEN_CREATE:
213 dwCreationDisposition = OPEN_ALWAYS;
214 break;
215 case RTFILE_O_CREATE:
216 dwCreationDisposition = CREATE_NEW;
217 break;
218 case RTFILE_O_CREATE_REPLACE:
219 dwCreationDisposition = CREATE_ALWAYS;
220 break;
221 default:
222 AssertMsgFailedReturn(("Impossible fOpen=%#llx\n", fOpen), VERR_INVALID_FLAGS);
223 }
224
225 DWORD dwDesiredAccess;
226 switch (fOpen & RTFILE_O_ACCESS_MASK)
227 {
228 case RTFILE_O_READ:
229 dwDesiredAccess = FILE_GENERIC_READ; /* RTFILE_O_APPEND is ignored. */
230 break;
231 case RTFILE_O_WRITE:
232 dwDesiredAccess = fOpen & RTFILE_O_APPEND
233 ? FILE_GENERIC_WRITE & ~FILE_WRITE_DATA
234 : FILE_GENERIC_WRITE;
235 break;
236 case RTFILE_O_READWRITE:
237 dwDesiredAccess = fOpen & RTFILE_O_APPEND
238 ? FILE_GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA)
239 : FILE_GENERIC_READ | FILE_GENERIC_WRITE;
240 break;
241 case RTFILE_O_ATTR_ONLY:
242 if (fOpen & RTFILE_O_ACCESS_ATTR_MASK)
243 {
244 dwDesiredAccess = 0;
245 break;
246 }
247 RT_FALL_THRU();
248 default:
249 AssertMsgFailedReturn(("Impossible fOpen=%#llx\n", fOpen), VERR_INVALID_FLAGS);
250 }
251 if (dwCreationDisposition == TRUNCATE_EXISTING)
252 /* Required for truncating the file (see MSDN), it is *NOT* part of FILE_GENERIC_WRITE. */
253 dwDesiredAccess |= GENERIC_WRITE;
254
255 /* RTFileSetMode needs following rights as well. */
256 switch (fOpen & RTFILE_O_ACCESS_ATTR_MASK)
257 {
258 case RTFILE_O_ACCESS_ATTR_READ: dwDesiredAccess |= FILE_READ_ATTRIBUTES | SYNCHRONIZE; break;
259 case RTFILE_O_ACCESS_ATTR_WRITE: dwDesiredAccess |= FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
260 case RTFILE_O_ACCESS_ATTR_READWRITE: dwDesiredAccess |= FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
261 default:
262 /* Attributes access is the same as the file access. */
263 switch (fOpen & RTFILE_O_ACCESS_MASK)
264 {
265 case RTFILE_O_READ: dwDesiredAccess |= FILE_READ_ATTRIBUTES | SYNCHRONIZE; break;
266 case RTFILE_O_WRITE: dwDesiredAccess |= FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
267 case RTFILE_O_READWRITE: dwDesiredAccess |= FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | SYNCHRONIZE; break;
268 default:
269 AssertMsgFailedReturn(("Impossible fOpen=%#llx\n", fOpen), VERR_INVALID_FLAGS);
270 }
271 }
272
273 DWORD dwShareMode;
274 switch (fOpen & RTFILE_O_DENY_MASK)
275 {
276 case RTFILE_O_DENY_NONE: dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
277 case RTFILE_O_DENY_READ: dwShareMode = FILE_SHARE_WRITE; break;
278 case RTFILE_O_DENY_WRITE: dwShareMode = FILE_SHARE_READ; break;
279 case RTFILE_O_DENY_READWRITE: dwShareMode = 0; break;
280
281 case RTFILE_O_DENY_NOT_DELETE: dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE; break;
282 case RTFILE_O_DENY_NOT_DELETE | RTFILE_O_DENY_READ: dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_WRITE; break;
283 case RTFILE_O_DENY_NOT_DELETE | RTFILE_O_DENY_WRITE: dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ; break;
284 case RTFILE_O_DENY_NOT_DELETE | RTFILE_O_DENY_READWRITE:dwShareMode = FILE_SHARE_DELETE; break;
285 default:
286 AssertMsgFailedReturn(("Impossible fOpen=%#llx\n", fOpen), VERR_INVALID_FLAGS);
287 }
288
289 SECURITY_ATTRIBUTES SecurityAttributes;
290 PSECURITY_ATTRIBUTES pSecurityAttributes = NULL;
291 if (fOpen & RTFILE_O_INHERIT)
292 {
293 SecurityAttributes.nLength = sizeof(SecurityAttributes);
294 SecurityAttributes.lpSecurityDescriptor = NULL;
295 SecurityAttributes.bInheritHandle = TRUE;
296 pSecurityAttributes = &SecurityAttributes;
297 }
298
299 DWORD dwFlagsAndAttributes;
300 dwFlagsAndAttributes = !(fOpen & RTFILE_O_TEMP_AUTO_DELETE) ? FILE_ATTRIBUTE_NORMAL : FILE_ATTRIBUTE_TEMPORARY;
301 if (fOpen & RTFILE_O_TEMP_AUTO_DELETE)
302 fOpen |= FILE_FLAG_DELETE_ON_CLOSE;
303 if (fOpen & RTFILE_O_WRITE_THROUGH)
304 dwFlagsAndAttributes |= FILE_FLAG_WRITE_THROUGH;
305 if (fOpen & RTFILE_O_ASYNC_IO)
306 dwFlagsAndAttributes |= FILE_FLAG_OVERLAPPED;
307 if (fOpen & RTFILE_O_NO_CACHE)
308 {
309 dwFlagsAndAttributes |= FILE_FLAG_NO_BUFFERING;
310 dwDesiredAccess &= ~FILE_APPEND_DATA;
311 }
312
313 /*
314 * Open/Create the file.
315 */
316 PRTUTF16 pwszFilename;
317 rc = RTPathWinFromUtf8(&pwszFilename, pszFilename, 0 /*fFlags*/);
318 if (RT_SUCCESS(rc))
319 {
320 HANDLE hFile = CreateFileW(pwszFilename,
321 dwDesiredAccess,
322 dwShareMode,
323 pSecurityAttributes,
324 dwCreationDisposition,
325 dwFlagsAndAttributes,
326 NULL);
327 DWORD const dwErr = GetLastError();
328 if (hFile != INVALID_HANDLE_VALUE)
329 {
330 /*
331 * Calculate the action taken value.
332 */
333 RTFILEACTION enmActionTaken;
334 switch (dwCreationDisposition)
335 {
336 case CREATE_NEW:
337 enmActionTaken = RTFILEACTION_CREATED;
338 break;
339 case CREATE_ALWAYS:
340 AssertMsg(dwErr == ERROR_ALREADY_EXISTS || dwErr == NO_ERROR, ("%u\n", dwErr));
341 enmActionTaken = dwErr == ERROR_ALREADY_EXISTS ? RTFILEACTION_REPLACED : RTFILEACTION_CREATED;
342 break;
343 case OPEN_EXISTING:
344 enmActionTaken = RTFILEACTION_OPENED;
345 break;
346 case OPEN_ALWAYS:
347 AssertMsg(dwErr == ERROR_ALREADY_EXISTS || dwErr == NO_ERROR, ("%u\n", dwErr));
348 enmActionTaken = dwErr == ERROR_ALREADY_EXISTS ? RTFILEACTION_OPENED : RTFILEACTION_CREATED;
349 break;
350 case TRUNCATE_EXISTING:
351 enmActionTaken = RTFILEACTION_TRUNCATED;
352 break;
353 default:
354 AssertMsgFailed(("%d %#x\n", dwCreationDisposition, dwCreationDisposition));
355 enmActionTaken = RTFILEACTION_INVALID;
356 break;
357 }
358
359 /*
360 * Turn off indexing of directory through Windows Indexing Service if
361 * we created a new file or replaced an existing one.
362 */
363 if ( (fOpen & RTFILE_O_NOT_CONTENT_INDEXED)
364 && ( enmActionTaken == RTFILEACTION_CREATED
365 || enmActionTaken == RTFILEACTION_REPLACED) )
366 {
367 /** @todo there must be a way to do this via the handle! */
368 if (!SetFileAttributesW(pwszFilename, FILE_ATTRIBUTE_NOT_CONTENT_INDEXED))
369 rc = RTErrConvertFromWin32(GetLastError());
370 }
371 /*
372 * If RTFILEACTION_OPENED, we may need to truncate the file.
373 */
374 else if ( (fOpen & (RTFILE_O_TRUNCATE | RTFILE_O_ACTION_MASK)) == (RTFILE_O_TRUNCATE | RTFILE_O_OPEN_CREATE)
375 && enmActionTaken == RTFILEACTION_OPENED)
376 {
377 if (SetEndOfFile(hFile))
378 enmActionTaken = RTFILEACTION_TRUNCATED;
379 else
380 rc = RTErrConvertFromWin32(GetLastError());
381 }
382 if (penmActionTaken)
383 *penmActionTaken = enmActionTaken;
384 if (RT_SUCCESS(rc))
385 {
386 *phFile = (RTFILE)hFile;
387 Assert((HANDLE)*phFile == hFile);
388 RTPathWinFree(pwszFilename);
389 return VINF_SUCCESS;
390 }
391
392 CloseHandle(hFile);
393 }
394 else
395 {
396 if ( penmActionTaken
397 && dwCreationDisposition == CREATE_NEW
398 && dwErr == ERROR_FILE_EXISTS)
399 *penmActionTaken = RTFILEACTION_ALREADY_EXISTS;
400 rc = RTErrConvertFromWin32(dwErr);
401 }
402 RTPathWinFree(pwszFilename);
403 }
404 return rc;
405}
406
407
408RTR3DECL(int) RTFileOpenBitBucket(PRTFILE phFile, uint64_t fAccess)
409{
410 AssertReturn( fAccess == RTFILE_O_READ
411 || fAccess == RTFILE_O_WRITE
412 || fAccess == RTFILE_O_READWRITE,
413 VERR_INVALID_PARAMETER);
414 return RTFileOpen(phFile, "NUL", fAccess | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
415}
416
417
418RTDECL(int) RTFileDup(RTFILE hFileSrc, uint64_t fFlags, PRTFILE phFileNew)
419{
420 /*
421 * Validate input.
422 */
423 AssertPtrReturn(phFileNew, VERR_INVALID_POINTER);
424 *phFileNew = NIL_RTFILE;
425 AssertPtrReturn(phFileNew, VERR_INVALID_POINTER);
426 AssertReturn(!(fFlags & ~(uint64_t)RTFILE_O_INHERIT), VERR_INVALID_FLAGS);
427
428 /*
429 * Do the job.
430 */
431 HANDLE hNew = INVALID_HANDLE_VALUE;
432 if (DuplicateHandle(GetCurrentProcess(), (HANDLE)RTFileToNative(hFileSrc),
433 GetCurrentProcess(), &hNew, 0, RT_BOOL(fFlags & RTFILE_O_INHERIT), DUPLICATE_SAME_ACCESS))
434 {
435 *phFileNew = (RTFILE)hNew;
436 return VINF_SUCCESS;
437 }
438 return RTErrConvertFromWin32(GetLastError());
439}
440
441
442RTR3DECL(int) RTFileClose(RTFILE hFile)
443{
444 if (hFile == NIL_RTFILE)
445 return VINF_SUCCESS;
446 if (CloseHandle((HANDLE)RTFileToNative(hFile)))
447 return VINF_SUCCESS;
448 return RTErrConvertFromWin32(GetLastError());
449}
450
451
452RTFILE rtFileGetStandard(RTHANDLESTD enmStdHandle)
453{
454 DWORD dwStdHandle;
455 switch (enmStdHandle)
456 {
457 case RTHANDLESTD_INPUT: dwStdHandle = STD_INPUT_HANDLE; break;
458 case RTHANDLESTD_OUTPUT: dwStdHandle = STD_OUTPUT_HANDLE; break;
459 case RTHANDLESTD_ERROR: dwStdHandle = STD_ERROR_HANDLE; break;
460 default:
461 AssertFailedReturn(NIL_RTFILE);
462 }
463
464 HANDLE hNative = GetStdHandle(dwStdHandle);
465 if (hNative == INVALID_HANDLE_VALUE)
466 return NIL_RTFILE;
467
468 RTFILE hFile = (RTFILE)(uintptr_t)hNative;
469 AssertReturn((HANDLE)(uintptr_t)hFile == hNative, NIL_RTFILE);
470 return hFile;
471}
472
473
474RTR3DECL(int) RTFileSeek(RTFILE hFile, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
475{
476 static ULONG aulSeekRecode[] =
477 {
478 FILE_BEGIN,
479 FILE_CURRENT,
480 FILE_END,
481 };
482
483 /*
484 * Validate input.
485 */
486 if (uMethod > RTFILE_SEEK_END)
487 {
488 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
489 return VERR_INVALID_PARAMETER;
490 }
491
492 /*
493 * Execute the seek.
494 */
495 if (MySetFilePointer(hFile, offSeek, poffActual, aulSeekRecode[uMethod]))
496 return VINF_SUCCESS;
497 return RTErrConvertFromWin32(GetLastError());
498}
499
500
501RTR3DECL(int) RTFileRead(RTFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
502{
503 if (cbToRead <= 0)
504 {
505 if (pcbRead)
506 *pcbRead = 0;
507 return VINF_SUCCESS;
508 }
509 ULONG cbToReadAdj = (ULONG)cbToRead;
510 AssertReturn(cbToReadAdj == cbToRead, VERR_NUMBER_TOO_BIG);
511
512 ULONG cbRead = 0;
513 if (ReadFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToReadAdj, &cbRead, NULL))
514 {
515 if (pcbRead)
516 /* Caller can handle partial reads. */
517 *pcbRead = cbRead;
518 else
519 {
520 /* Caller expects everything to be read. */
521 while (cbToReadAdj > cbRead)
522 {
523 ULONG cbReadPart = 0;
524 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbRead, cbToReadAdj - cbRead, &cbReadPart, NULL))
525 return RTErrConvertFromWin32(GetLastError());
526 if (cbReadPart == 0)
527 return VERR_EOF;
528 cbRead += cbReadPart;
529 }
530 }
531 return VINF_SUCCESS;
532 }
533
534 /*
535 * If it's a console, we might bump into out of memory conditions in the
536 * ReadConsole call.
537 */
538 DWORD dwErr = GetLastError();
539 if (dwErr == ERROR_NOT_ENOUGH_MEMORY)
540 {
541 ULONG cbChunk = cbToReadAdj / 2;
542 if (cbChunk > 16*_1K)
543 cbChunk = 16*_1K;
544 else
545 cbChunk = RT_ALIGN_32(cbChunk, 256);
546
547 cbRead = 0;
548 while (cbToReadAdj > cbRead)
549 {
550 ULONG cbToReadNow = RT_MIN(cbChunk, cbToReadAdj - cbRead);
551 ULONG cbReadPart = 0;
552 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char *)pvBuf + cbRead, cbToReadNow, &cbReadPart, NULL))
553 {
554 /* If we failed because the buffer is too big, shrink it and
555 try again. */
556 dwErr = GetLastError();
557 if ( dwErr == ERROR_NOT_ENOUGH_MEMORY
558 && cbChunk > 8)
559 {
560 cbChunk /= 2;
561 continue;
562 }
563 return RTErrConvertFromWin32(dwErr);
564 }
565 cbRead += cbReadPart;
566
567 /* Return if the caller can handle partial reads, otherwise try
568 fill the buffer all the way up. */
569 if (pcbRead)
570 {
571 *pcbRead = cbRead;
572 break;
573 }
574 if (cbReadPart == 0)
575 return VERR_EOF;
576 }
577 return VINF_SUCCESS;
578 }
579
580 return RTErrConvertFromWin32(dwErr);
581}
582
583
584RTDECL(int) RTFileReadAt(RTFILE hFile, RTFOFF off, void *pvBuf, size_t cbToRead, size_t *pcbRead)
585{
586 ULONG cbToReadAdj = (ULONG)cbToRead;
587 AssertReturn(cbToReadAdj == cbToRead, VERR_NUMBER_TOO_BIG);
588
589 OVERLAPPED Overlapped;
590 Overlapped.Offset = (uint32_t)off;
591 Overlapped.OffsetHigh = (uint32_t)(off >> 32);
592 Overlapped.hEvent = NULL;
593 Overlapped.Internal = 0;
594 Overlapped.InternalHigh = 0;
595
596 ULONG cbRead = 0;
597 if (ReadFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToReadAdj, &cbRead, &Overlapped))
598 {
599 if (pcbRead)
600 /* Caller can handle partial reads. */
601 *pcbRead = cbRead;
602 else
603 {
604 /* Caller expects everything to be read. */
605 while (cbToReadAdj > cbRead)
606 {
607 Overlapped.Offset = (uint32_t)(off + cbRead);
608 Overlapped.OffsetHigh = (uint32_t)((off + cbRead) >> 32);
609 Overlapped.hEvent = NULL;
610 Overlapped.Internal = 0;
611 Overlapped.InternalHigh = 0;
612
613 ULONG cbReadPart = 0;
614 if (!ReadFile((HANDLE)RTFileToNative(hFile), (char *)pvBuf + cbRead, cbToReadAdj - cbRead,
615 &cbReadPart, &Overlapped))
616 return RTErrConvertFromWin32(GetLastError());
617 if (cbReadPart == 0)
618 return VERR_EOF;
619 cbRead += cbReadPart;
620 }
621 }
622 return VINF_SUCCESS;
623 }
624
625 /* We will get an EOF error when using overlapped I/O. So, make sure we don't
626 return it when pcbhRead is not NULL. */
627 DWORD dwErr = GetLastError();
628 if (pcbRead && dwErr == ERROR_HANDLE_EOF)
629 {
630 *pcbRead = 0;
631 return VINF_SUCCESS;
632 }
633 return RTErrConvertFromWin32(dwErr);
634}
635
636
637RTR3DECL(int) RTFileWrite(RTFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
638{
639 if (cbToWrite <= 0)
640 return VINF_SUCCESS;
641 ULONG const cbToWriteAdj = (ULONG)cbToWrite;
642 AssertReturn(cbToWriteAdj == cbToWrite, VERR_NUMBER_TOO_BIG);
643
644 ULONG cbWritten = 0;
645 if (WriteFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToWriteAdj, &cbWritten, NULL))
646 {
647 if (pcbWritten)
648 /* Caller can handle partial writes. */
649 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
650 else
651 {
652 /* Caller expects everything to be written. */
653 while (cbWritten < cbToWriteAdj)
654 {
655 ULONG cbWrittenPart = 0;
656 if (!WriteFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbWritten,
657 cbToWriteAdj - cbWritten, &cbWrittenPart, NULL))
658 {
659 int rc = RTErrConvertFromWin32(GetLastError());
660 if (rc == VERR_DISK_FULL)
661 rc = rtFileWinCheckIfDiskReallyFull(hFile, RTFileTell(hFile) + cbToWriteAdj - cbWritten);
662 return rc;
663 }
664 if (cbWrittenPart == 0)
665 return VERR_WRITE_ERROR;
666 cbWritten += cbWrittenPart;
667 }
668 }
669 return VINF_SUCCESS;
670 }
671
672 /*
673 * If it's a console, we might bump into out of memory conditions in the
674 * WriteConsole call.
675 */
676 DWORD dwErr = GetLastError();
677 if (dwErr == ERROR_NOT_ENOUGH_MEMORY)
678 {
679 ULONG cbChunk = cbToWriteAdj / 2;
680 if (cbChunk > _32K)
681 cbChunk = _32K;
682 else
683 cbChunk = RT_ALIGN_32(cbChunk, 256);
684
685 cbWritten = 0;
686 while (cbWritten < cbToWriteAdj)
687 {
688 ULONG cbToWriteNow = RT_MIN(cbChunk, cbToWriteAdj - cbWritten);
689 ULONG cbWrittenPart = 0;
690 if (!WriteFile((HANDLE)RTFileToNative(hFile), (const char *)pvBuf + cbWritten, cbToWriteNow, &cbWrittenPart, NULL))
691 {
692 /* If we failed because the buffer is too big, shrink it and
693 try again. */
694 dwErr = GetLastError();
695 if ( dwErr == ERROR_NOT_ENOUGH_MEMORY
696 && cbChunk > 8)
697 {
698 cbChunk /= 2;
699 continue;
700 }
701 int rc = RTErrConvertFromWin32(dwErr);
702 if (rc == VERR_DISK_FULL)
703 rc = rtFileWinCheckIfDiskReallyFull(hFile, RTFileTell(hFile) + cbToWriteNow);
704 return rc;
705 }
706 cbWritten += cbWrittenPart;
707
708 /* Return if the caller can handle partial writes, otherwise try
709 write out everything. */
710 if (pcbWritten)
711 {
712 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
713 break;
714 }
715 if (cbWrittenPart == 0)
716 return VERR_WRITE_ERROR;
717 }
718 return VINF_SUCCESS;
719 }
720
721 int rc = RTErrConvertFromWin32(dwErr);
722 if (rc == VERR_DISK_FULL)
723 rc = rtFileWinCheckIfDiskReallyFull(hFile, RTFileTell(hFile) + cbToWriteAdj);
724 return rc;
725}
726
727
728RTDECL(int) RTFileWriteAt(RTFILE hFile, RTFOFF off, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
729{
730 ULONG const cbToWriteAdj = (ULONG)cbToWrite;
731 AssertReturn(cbToWriteAdj == cbToWrite, VERR_NUMBER_TOO_BIG);
732
733 OVERLAPPED Overlapped;
734 Overlapped.Offset = (uint32_t)off;
735 Overlapped.OffsetHigh = (uint32_t)(off >> 32);
736 Overlapped.hEvent = NULL;
737 Overlapped.Internal = 0;
738 Overlapped.InternalHigh = 0;
739
740 ULONG cbWritten = 0;
741 if (WriteFile((HANDLE)RTFileToNative(hFile), pvBuf, cbToWriteAdj, &cbWritten, &Overlapped))
742 {
743 if (pcbWritten)
744 /* Caller can handle partial writes. */
745 *pcbWritten = RT_MIN(cbWritten, cbToWriteAdj); /* paranoia^3 */
746 else
747 {
748 /* Caller expects everything to be written. */
749 while (cbWritten < cbToWriteAdj)
750 {
751 Overlapped.Offset = (uint32_t)(off + cbWritten);
752 Overlapped.OffsetHigh = (uint32_t)((off + cbWritten) >> 32);
753 Overlapped.hEvent = NULL;
754 Overlapped.Internal = 0;
755 Overlapped.InternalHigh = 0;
756
757 ULONG cbWrittenPart = 0;
758 if (!WriteFile((HANDLE)RTFileToNative(hFile), (char*)pvBuf + cbWritten,
759 cbToWriteAdj - cbWritten, &cbWrittenPart, &Overlapped))
760 {
761 int rc = RTErrConvertFromWin32(GetLastError());
762 if (rc == VERR_DISK_FULL)
763 rc = rtFileWinCheckIfDiskReallyFull(hFile, off + cbToWriteAdj);
764 return rc;
765 }
766 if (cbWrittenPart == 0)
767 return VERR_WRITE_ERROR;
768 cbWritten += cbWrittenPart;
769 }
770 }
771 return VINF_SUCCESS;
772 }
773
774 int rc = RTErrConvertFromWin32(GetLastError());
775 if (rc == VERR_DISK_FULL)
776 rc = rtFileWinCheckIfDiskReallyFull(hFile, off + cbToWriteAdj);
777 return rc;
778}
779
780
781RTR3DECL(int) RTFileFlush(RTFILE hFile)
782{
783 if (!FlushFileBuffers((HANDLE)RTFileToNative(hFile)))
784 {
785 int rc = GetLastError();
786 Log(("FlushFileBuffers failed with %d\n", rc));
787 return RTErrConvertFromWin32(rc);
788 }
789 return VINF_SUCCESS;
790}
791
792#if 1
793
794/**
795 * Checks the the two handles refers to the same file.
796 *
797 * @returns true if the same file, false if different ones or invalid handles.
798 * @param hFile1 Handle \#1.
799 * @param hFile2 Handle \#2.
800 */
801static bool rtFileIsSame(HANDLE hFile1, HANDLE hFile2)
802{
803 /*
804 * We retry in case CreationTime or the Object ID is being modified and there
805 * aren't any IndexNumber (file ID) on this kind of file system.
806 */
807 for (uint32_t iTries = 0; iTries < 3; iTries++)
808 {
809 /*
810 * Fetch data to compare (being a little lazy here).
811 */
812 struct
813 {
814 HANDLE hFile;
815 NTSTATUS rcObjId;
816 FILE_OBJECTID_INFORMATION ObjId;
817 FILE_ALL_INFORMATION All;
818 FILE_FS_VOLUME_INFORMATION Vol;
819 } auData[2];
820 auData[0].hFile = hFile1;
821 auData[1].hFile = hFile2;
822
823 for (uintptr_t i = 0; i < RT_ELEMENTS(auData); i++)
824 {
825 RT_ZERO(auData[i].ObjId);
826 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
827 auData[i].rcObjId = NtQueryInformationFile(auData[i].hFile, &Ios, &auData[i].ObjId, sizeof(auData[i].ObjId),
828 FileObjectIdInformation);
829
830 RT_ZERO(auData[i].All);
831 RTNT_IO_STATUS_BLOCK_REINIT(&Ios);
832 NTSTATUS rcNt = NtQueryInformationFile(auData[i].hFile, &Ios, &auData[i].All, sizeof(auData[i].All),
833 FileAllInformation);
834 AssertReturn(rcNt == STATUS_BUFFER_OVERFLOW /* insufficient space for name info */ || NT_SUCCESS(rcNt), false);
835
836 union
837 {
838 FILE_FS_VOLUME_INFORMATION Info;
839 uint8_t abBuf[sizeof(FILE_FS_VOLUME_INFORMATION) + 4096];
840 } uVol;
841 RT_ZERO(uVol.Info);
842 RTNT_IO_STATUS_BLOCK_REINIT(&Ios);
843 rcNt = NtQueryVolumeInformationFile(auData[i].hFile, &Ios, &uVol, sizeof(uVol), FileFsVolumeInformation);
844 if (NT_SUCCESS(rcNt))
845 auData[i].Vol = uVol.Info;
846 else
847 RT_ZERO(auData[i].Vol);
848 }
849
850 /*
851 * Compare it.
852 */
853 if ( auData[0].All.StandardInformation.Directory
854 == auData[1].All.StandardInformation.Directory)
855 { /* likely */ }
856 else
857 break;
858
859 if ( (auData[0].All.BasicInformation.FileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE | FILE_ATTRIBUTE_REPARSE_POINT))
860 == (auData[1].All.BasicInformation.FileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE | FILE_ATTRIBUTE_REPARSE_POINT)))
861 { /* likely */ }
862 else
863 break;
864
865 if ( auData[0].Vol.VolumeSerialNumber
866 == auData[1].Vol.VolumeSerialNumber)
867 { /* likely */ }
868 else
869 break;
870
871 if ( auData[0].All.InternalInformation.IndexNumber.QuadPart
872 == auData[1].All.InternalInformation.IndexNumber.QuadPart)
873 { /* likely */ }
874 else
875 break;
876
877 if ( !NT_SUCCESS(auData[0].rcObjId)
878 || memcmp(&auData[0].ObjId, &auData[1].ObjId, RT_UOFFSETOF(FILE_OBJECTID_INFORMATION, ExtendedInfo)) == 0)
879 {
880 if ( auData[0].All.BasicInformation.CreationTime.QuadPart
881 == auData[1].All.BasicInformation.CreationTime.QuadPart)
882 return true;
883 }
884 }
885
886 return false;
887}
888
889
890/**
891 * If @a hFile is opened in append mode, try return a handle with
892 * FILE_WRITE_DATA permissions.
893 *
894 * @returns Duplicate handle.
895 * @param hFile The NT handle to check & duplicate.
896 *
897 * @todo It would be much easier to implement this by not dropping the
898 * FILE_WRITE_DATA access and instead have the RTFileWrite APIs
899 * enforce the appending. That will require keeping additional
900 * information along side the handle (instance structure). However, on
901 * windows you can grant append permissions w/o giving people access to
902 * overwrite existing data, so the RTFileOpenEx code would have to deal
903 * with those kinds of STATUS_ACCESS_DENIED too then.
904 */
905static HANDLE rtFileReOpenAppendOnlyWithFullWriteAccess(HANDLE hFile)
906{
907 OBJECT_BASIC_INFORMATION BasicInfo = {0};
908 ULONG cbActual = 0;
909 NTSTATUS rcNt = NtQueryObject(hFile, ObjectBasicInformation, &BasicInfo, sizeof(BasicInfo), &cbActual);
910 if (NT_SUCCESS(rcNt))
911 {
912 if ((BasicInfo.GrantedAccess & (FILE_APPEND_DATA | FILE_WRITE_DATA)) == FILE_APPEND_DATA)
913 {
914 /*
915 * We cannot use NtDuplicateObject here as it is not possible to
916 * upgrade the access on files, only making it more strict. So,
917 * query the path and re-open it (we could do by file/object/whatever
918 * id too, but that may not work with all file systems).
919 */
920 for (uint32_t i = 0; i < 16; i++)
921 {
922 UNICODE_STRING NtName;
923 int rc = RTNtPathFromHandle(&NtName, hFile, 0);
924 AssertRCReturn(rc, INVALID_HANDLE_VALUE);
925
926 HANDLE hDupFile = RTNT_INVALID_HANDLE_VALUE;
927 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
928 OBJECT_ATTRIBUTES ObjAttr;
929 InitializeObjectAttributes(&ObjAttr, &NtName, BasicInfo.Attributes & ~OBJ_INHERIT, NULL, NULL);
930
931 rcNt = NtCreateFile(&hDupFile,
932 BasicInfo.GrantedAccess | FILE_WRITE_DATA,
933 &ObjAttr,
934 &Ios,
935 NULL /* AllocationSize*/,
936 FILE_ATTRIBUTE_NORMAL,
937 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
938 FILE_OPEN,
939 FILE_OPEN_FOR_BACKUP_INTENT /*??*/,
940 NULL /*EaBuffer*/,
941 0 /*EaLength*/);
942 RTUtf16Free(NtName.Buffer);
943 if (NT_SUCCESS(rcNt))
944 {
945 /*
946 * Check that we've opened the same file.
947 */
948 if (rtFileIsSame(hFile, hDupFile))
949 return hDupFile;
950 NtClose(hDupFile);
951 }
952 }
953 AssertFailed();
954 }
955 }
956 return INVALID_HANDLE_VALUE;
957}
958
959#endif
960
961RTR3DECL(int) RTFileSetSize(RTFILE hFile, uint64_t cbSize)
962{
963#if 1
964 HANDLE hNtFile = (HANDLE)RTFileToNative(hFile);
965 HANDLE hDupFile = INVALID_HANDLE_VALUE;
966 union
967 {
968 FILE_END_OF_FILE_INFORMATION Eof;
969 FILE_ALLOCATION_INFORMATION Alloc;
970 } uInfo;
971
972 /*
973 * Change the EOF marker.
974 *
975 * HACK ALERT! If the file was opened in RTFILE_O_APPEND mode, we will have
976 * to re-open it with FILE_WRITE_DATA access to get the job done.
977 * This how ftruncate on a unixy system would work but not how
978 * it is done on Windows where appending is a separate permission
979 * rather than just a write modifier, making this hack totally wrong.
980 */
981 /** @todo The right way to fix this is either to add a RTFileSetSizeEx function
982 * for specifically requesting the unixy behaviour, or add an additional
983 * flag to RTFileOpen[Ex] to request the unixy append behaviour there.
984 * The latter would require saving the open flags in a instance data
985 * structure, which is a bit of a risky move, though something we should
986 * do in 6.2 (or later).
987 *
988 * Note! Because handle interitance, it is not realyan option to
989 * always use FILE_WRITE_DATA and implement the RTFILE_O_APPEND
990 * bits in RTFileWrite and friends. Besides, it's not like
991 * RTFILE_O_APPEND is so clearly defined anyway - see
992 * RTFileWriteAt.
993 */
994 IO_STATUS_BLOCK Ios = RTNT_IO_STATUS_BLOCK_INITIALIZER;
995 uInfo.Eof.EndOfFile.QuadPart = cbSize;
996 NTSTATUS rcNt = NtSetInformationFile(hNtFile, &Ios, &uInfo.Eof, sizeof(uInfo.Eof), FileEndOfFileInformation);
997 if (rcNt == STATUS_ACCESS_DENIED)
998 {
999 hDupFile = rtFileReOpenAppendOnlyWithFullWriteAccess(hNtFile);
1000 if (hDupFile != INVALID_HANDLE_VALUE)
1001 {
1002 hNtFile = hDupFile;
1003 uInfo.Eof.EndOfFile.QuadPart = cbSize;
1004 rcNt = NtSetInformationFile(hNtFile, &Ios, &uInfo.Eof, sizeof(uInfo.Eof), FileEndOfFileInformation);
1005 }
1006 }
1007
1008 if (NT_SUCCESS(rcNt))
1009 {
1010 /*
1011 * Change the allocation.
1012 */
1013 uInfo.Alloc.AllocationSize.QuadPart = cbSize;
1014 rcNt = NtSetInformationFile(hNtFile, &Ios, &uInfo.Eof, sizeof(uInfo.Alloc), FileAllocationInformation);
1015 }
1016
1017 /*
1018 * Close the temporary file handle:
1019 */
1020 if (hDupFile != INVALID_HANDLE_VALUE)
1021 NtClose(hDupFile);
1022
1023 if (NT_SUCCESS(rcNt))
1024 return VINF_SUCCESS;
1025 return RTErrConvertFromNtStatus(rcNt);
1026
1027#else /* this version of the code will fail to truncate files when RTFILE_O_APPEND is in effect, which isn't what we want... */
1028 /*
1029 * Get current file pointer.
1030 */
1031 int rc;
1032 uint64_t offCurrent;
1033 if (MySetFilePointer(hFile, 0, &offCurrent, FILE_CURRENT))
1034 {
1035 /*
1036 * Set new file pointer.
1037 */
1038 if (MySetFilePointer(hFile, cbSize, NULL, FILE_BEGIN))
1039 {
1040 /* set file pointer */
1041 if (SetEndOfFile((HANDLE)RTFileToNative(hFile)))
1042 {
1043 /*
1044 * Restore file pointer and return.
1045 * If the old pointer was beyond the new file end, ignore failure.
1046 */
1047 if ( MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN)
1048 || offCurrent > cbSize)
1049 return VINF_SUCCESS;
1050 }
1051
1052 /*
1053 * Failed, try restoring the file pointer.
1054 */
1055 rc = GetLastError();
1056 MySetFilePointer(hFile, offCurrent, NULL, FILE_BEGIN);
1057
1058 if (rc == ERROR_DISK_FULL)
1059 return rtFileWinCheckIfDiskReallyFull(hFile, cbSize);
1060 }
1061 else
1062 rc = GetLastError();
1063 }
1064 else
1065 rc = GetLastError();
1066
1067 return RTErrConvertFromWin32(rc);
1068#endif
1069}
1070
1071
1072RTR3DECL(int) RTFileQuerySize(RTFILE hFile, uint64_t *pcbSize)
1073{
1074 /*
1075 * GetFileSize works for most handles.
1076 */
1077 ULARGE_INTEGER Size;
1078 Size.LowPart = GetFileSize((HANDLE)RTFileToNative(hFile), &Size.HighPart);
1079 if (Size.LowPart != INVALID_FILE_SIZE)
1080 {
1081 *pcbSize = Size.QuadPart;
1082 return VINF_SUCCESS;
1083 }
1084 int rc = RTErrConvertFromWin32(GetLastError());
1085
1086 /*
1087 * Could it be a volume or a disk?
1088 */
1089 DISK_GEOMETRY DriveGeo;
1090 DWORD cbDriveGeo;
1091 if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
1092 IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
1093 &DriveGeo, sizeof(DriveGeo), &cbDriveGeo, NULL))
1094 {
1095 if ( DriveGeo.MediaType == FixedMedia
1096 || DriveGeo.MediaType == RemovableMedia)
1097 {
1098 *pcbSize = DriveGeo.Cylinders.QuadPart
1099 * DriveGeo.TracksPerCylinder
1100 * DriveGeo.SectorsPerTrack
1101 * DriveGeo.BytesPerSector;
1102
1103 GET_LENGTH_INFORMATION DiskLenInfo;
1104 DWORD Ignored;
1105 if (DeviceIoControl((HANDLE)RTFileToNative(hFile),
1106 IOCTL_DISK_GET_LENGTH_INFO, NULL, 0,
1107 &DiskLenInfo, sizeof(DiskLenInfo), &Ignored, (LPOVERLAPPED)NULL))
1108 {
1109 /* IOCTL_DISK_GET_LENGTH_INFO is supported -- override cbSize. */
1110 *pcbSize = DiskLenInfo.Length.QuadPart;
1111 }
1112 return VINF_SUCCESS;
1113 }
1114 }
1115
1116 /*
1117 * Return the GetFileSize result if not a volume/disk.
1118 */
1119 return rc;
1120}
1121
1122
1123RTR3DECL(int) RTFileQueryMaxSizeEx(RTFILE hFile, PRTFOFF pcbMax)
1124{
1125 /** @todo r=bird:
1126 * We might have to make this code OS version specific... In the worse
1127 * case, we'll have to try GetVolumeInformationByHandle on vista and fall
1128 * back on NtQueryVolumeInformationFile(,,,, FileFsAttributeInformation)
1129 * else where, and check for known file system names. (For LAN shares we'll
1130 * have to figure out the remote file system.) */
1131 RT_NOREF_PV(hFile); RT_NOREF_PV(pcbMax);
1132 return VERR_NOT_IMPLEMENTED;
1133}
1134
1135
1136RTR3DECL(bool) RTFileIsValid(RTFILE hFile)
1137{
1138 if (hFile != NIL_RTFILE)
1139 {
1140 DWORD dwType = GetFileType((HANDLE)RTFileToNative(hFile));
1141 switch (dwType)
1142 {
1143 case FILE_TYPE_CHAR:
1144 case FILE_TYPE_DISK:
1145 case FILE_TYPE_PIPE:
1146 case FILE_TYPE_REMOTE:
1147 return true;
1148
1149 case FILE_TYPE_UNKNOWN:
1150 if (GetLastError() == NO_ERROR)
1151 return true;
1152 break;
1153
1154 default:
1155 break;
1156 }
1157 }
1158 return false;
1159}
1160
1161
1162#define LOW_DWORD(u64) ((DWORD)u64)
1163#define HIGH_DWORD(u64) (((DWORD *)&u64)[1])
1164
1165RTR3DECL(int) RTFileLock(RTFILE hFile, unsigned fLock, int64_t offLock, uint64_t cbLock)
1166{
1167 Assert(offLock >= 0);
1168
1169 /* Check arguments. */
1170 if (fLock & ~RTFILE_LOCK_MASK)
1171 {
1172 AssertMsgFailed(("Invalid fLock=%08X\n", fLock));
1173 return VERR_INVALID_PARAMETER;
1174 }
1175
1176 /* Prepare flags. */
1177 Assert(RTFILE_LOCK_WRITE);
1178 DWORD dwFlags = (fLock & RTFILE_LOCK_WRITE) ? LOCKFILE_EXCLUSIVE_LOCK : 0;
1179 Assert(RTFILE_LOCK_WAIT);
1180 if (!(fLock & RTFILE_LOCK_WAIT))
1181 dwFlags |= LOCKFILE_FAIL_IMMEDIATELY;
1182
1183 /* Windows structure. */
1184 OVERLAPPED Overlapped;
1185 memset(&Overlapped, 0, sizeof(Overlapped));
1186 Overlapped.Offset = LOW_DWORD(offLock);
1187 Overlapped.OffsetHigh = HIGH_DWORD(offLock);
1188
1189 /* Note: according to Microsoft, LockFileEx API call is available starting from NT 3.5 */
1190 if (LockFileEx((HANDLE)RTFileToNative(hFile), dwFlags, 0, LOW_DWORD(cbLock), HIGH_DWORD(cbLock), &Overlapped))
1191 return VINF_SUCCESS;
1192
1193 return RTErrConvertFromWin32(GetLastError());
1194}
1195
1196
1197RTR3DECL(int) RTFileChangeLock(RTFILE hFile, unsigned fLock, int64_t offLock, uint64_t cbLock)
1198{
1199 Assert(offLock >= 0);
1200
1201 /* Check arguments. */
1202 if (fLock & ~RTFILE_LOCK_MASK)
1203 {
1204 AssertMsgFailed(("Invalid fLock=%08X\n", fLock));
1205 return VERR_INVALID_PARAMETER;
1206 }
1207
1208 /* Remove old lock. */
1209 int rc = RTFileUnlock(hFile, offLock, cbLock);
1210 if (RT_FAILURE(rc))
1211 return rc;
1212
1213 /* Set new lock. */
1214 rc = RTFileLock(hFile, fLock, offLock, cbLock);
1215 if (RT_SUCCESS(rc))
1216 return rc;
1217
1218 /* Try to restore old lock. */
1219 unsigned fLockOld = (fLock & RTFILE_LOCK_WRITE) ? fLock & ~RTFILE_LOCK_WRITE : fLock | RTFILE_LOCK_WRITE;
1220 rc = RTFileLock(hFile, fLockOld, offLock, cbLock);
1221 if (RT_SUCCESS(rc))
1222 return VERR_FILE_LOCK_VIOLATION;
1223 else
1224 return VERR_FILE_LOCK_LOST;
1225}
1226
1227
1228RTR3DECL(int) RTFileUnlock(RTFILE hFile, int64_t offLock, uint64_t cbLock)
1229{
1230 Assert(offLock >= 0);
1231
1232 if (UnlockFile((HANDLE)RTFileToNative(hFile),
1233 LOW_DWORD(offLock), HIGH_DWORD(offLock),
1234 LOW_DWORD(cbLock), HIGH_DWORD(cbLock)))
1235 return VINF_SUCCESS;
1236
1237 return RTErrConvertFromWin32(GetLastError());
1238}
1239
1240
1241
1242RTR3DECL(int) RTFileQueryInfo(RTFILE hFile, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
1243{
1244 /*
1245 * Validate input.
1246 */
1247 if (hFile == NIL_RTFILE)
1248 {
1249 AssertMsgFailed(("Invalid hFile=%RTfile\n", hFile));
1250 return VERR_INVALID_PARAMETER;
1251 }
1252 if (!pObjInfo)
1253 {
1254 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
1255 return VERR_INVALID_PARAMETER;
1256 }
1257 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
1258 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
1259 {
1260 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
1261 return VERR_INVALID_PARAMETER;
1262 }
1263
1264 /*
1265 * Query file info.
1266 */
1267 HANDLE hHandle = (HANDLE)RTFileToNative(hFile);
1268#if 1
1269 uint64_t auBuf[168 / sizeof(uint64_t)]; /* Missing FILE_ALL_INFORMATION here. */
1270 int rc = rtPathNtQueryInfoFromHandle(hFile, auBuf, sizeof(auBuf), pObjInfo, enmAdditionalAttribs, NULL, 0);
1271 if (RT_SUCCESS(rc))
1272 return rc;
1273
1274 /*
1275 * Console I/O handles make trouble here. On older windows versions they
1276 * end up with ERROR_INVALID_HANDLE when handed to the above API, while on
1277 * more recent ones they cause different errors to appear.
1278 *
1279 * Thus, we must ignore the latter and doubly verify invalid handle claims.
1280 * We use the undocumented VerifyConsoleIoHandle to do this, falling back on
1281 * GetFileType should it not be there.
1282 */
1283 if ( rc == VERR_INVALID_HANDLE
1284 || rc == VERR_ACCESS_DENIED
1285 || rc == VERR_UNEXPECTED_FS_OBJ_TYPE)
1286 {
1287 static PFNVERIFYCONSOLEIOHANDLE s_pfnVerifyConsoleIoHandle = NULL;
1288 static bool volatile s_fInitialized = false;
1289 PFNVERIFYCONSOLEIOHANDLE pfnVerifyConsoleIoHandle;
1290 if (s_fInitialized)
1291 pfnVerifyConsoleIoHandle = s_pfnVerifyConsoleIoHandle;
1292 else
1293 {
1294 pfnVerifyConsoleIoHandle = (PFNVERIFYCONSOLEIOHANDLE)RTLdrGetSystemSymbol("kernel32.dll", "VerifyConsoleIoHandle");
1295 ASMAtomicWriteBool(&s_fInitialized, true);
1296 }
1297 if ( pfnVerifyConsoleIoHandle
1298 ? !pfnVerifyConsoleIoHandle(hHandle)
1299 : GetFileType(hHandle) == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR)
1300 return VERR_INVALID_HANDLE;
1301 }
1302 /*
1303 * On Windows 10 and (hopefully) 8.1 we get ERROR_INVALID_FUNCTION with console
1304 * I/O handles and null device handles. We must ignore these just like the
1305 * above invalid handle error.
1306 */
1307 else if (rc != VERR_INVALID_FUNCTION && rc != VERR_IO_BAD_COMMAND)
1308 return rc;
1309
1310 RT_ZERO(*pObjInfo);
1311 pObjInfo->Attr.enmAdditional = enmAdditionalAttribs;
1312 pObjInfo->Attr.fMode = rtFsModeFromDos(RTFS_DOS_NT_DEVICE, "", 0, 0, 0);
1313 return VINF_SUCCESS;
1314#else
1315
1316 BY_HANDLE_FILE_INFORMATION Data;
1317 if (!GetFileInformationByHandle(hHandle, &Data))
1318 {
1319 /*
1320 * Console I/O handles make trouble here. On older windows versions they
1321 * end up with ERROR_INVALID_HANDLE when handed to the above API, while on
1322 * more recent ones they cause different errors to appear.
1323 *
1324 * Thus, we must ignore the latter and doubly verify invalid handle claims.
1325 * We use the undocumented VerifyConsoleIoHandle to do this, falling back on
1326 * GetFileType should it not be there.
1327 */
1328 DWORD dwErr = GetLastError();
1329 if (dwErr == ERROR_INVALID_HANDLE)
1330 {
1331 static PFNVERIFYCONSOLEIOHANDLE s_pfnVerifyConsoleIoHandle = NULL;
1332 static bool volatile s_fInitialized = false;
1333 PFNVERIFYCONSOLEIOHANDLE pfnVerifyConsoleIoHandle;
1334 if (s_fInitialized)
1335 pfnVerifyConsoleIoHandle = s_pfnVerifyConsoleIoHandle;
1336 else
1337 {
1338 pfnVerifyConsoleIoHandle = (PFNVERIFYCONSOLEIOHANDLE)RTLdrGetSystemSymbol("kernel32.dll", "VerifyConsoleIoHandle");
1339 ASMAtomicWriteBool(&s_fInitialized, true);
1340 }
1341 if ( pfnVerifyConsoleIoHandle
1342 ? !pfnVerifyConsoleIoHandle(hHandle)
1343 : GetFileType(hHandle) == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR)
1344 return VERR_INVALID_HANDLE;
1345 }
1346 /*
1347 * On Windows 10 and (hopefully) 8.1 we get ERROR_INVALID_FUNCTION with console I/O
1348 * handles. We must ignore these just like the above invalid handle error.
1349 */
1350 else if (dwErr != ERROR_INVALID_FUNCTION)
1351 return RTErrConvertFromWin32(dwErr);
1352
1353 RT_ZERO(Data);
1354 Data.dwFileAttributes = RTFS_DOS_NT_DEVICE;
1355 }
1356
1357 /*
1358 * Setup the returned data.
1359 */
1360 pObjInfo->cbObject = ((uint64_t)Data.nFileSizeHigh << 32)
1361 | (uint64_t)Data.nFileSizeLow;
1362 pObjInfo->cbAllocated = pObjInfo->cbObject;
1363
1364 Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
1365 RTTimeSpecSetNtTime(&pObjInfo->BirthTime, *(uint64_t *)&Data.ftCreationTime);
1366 RTTimeSpecSetNtTime(&pObjInfo->AccessTime, *(uint64_t *)&Data.ftLastAccessTime);
1367 RTTimeSpecSetNtTime(&pObjInfo->ModificationTime, *(uint64_t *)&Data.ftLastWriteTime);
1368 pObjInfo->ChangeTime = pObjInfo->ModificationTime;
1369
1370 pObjInfo->Attr.fMode = rtFsModeFromDos((Data.dwFileAttributes << RTFS_DOS_SHIFT) & RTFS_DOS_MASK_NT, "", 0,
1371 RTFSMODE_SYMLINK_REPARSE_TAG /* (symlink or not, doesn't usually matter here) */);
1372
1373 /*
1374 * Requested attributes (we cannot provide anything actually).
1375 */
1376 switch (enmAdditionalAttribs)
1377 {
1378 case RTFSOBJATTRADD_NOTHING:
1379 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_NOTHING;
1380 break;
1381
1382 case RTFSOBJATTRADD_UNIX:
1383 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX;
1384 pObjInfo->Attr.u.Unix.uid = ~0U;
1385 pObjInfo->Attr.u.Unix.gid = ~0U;
1386 pObjInfo->Attr.u.Unix.cHardlinks = Data.nNumberOfLinks ? Data.nNumberOfLinks : 1;
1387 pObjInfo->Attr.u.Unix.INodeIdDevice = Data.dwVolumeSerialNumber;
1388 pObjInfo->Attr.u.Unix.INodeId = RT_MAKE_U64(Data.nFileIndexLow, Data.nFileIndexHigh);
1389 pObjInfo->Attr.u.Unix.fFlags = 0;
1390 pObjInfo->Attr.u.Unix.GenerationId = 0;
1391 pObjInfo->Attr.u.Unix.Device = 0;
1392 break;
1393
1394 case RTFSOBJATTRADD_UNIX_OWNER:
1395 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_OWNER;
1396 pObjInfo->Attr.u.UnixOwner.uid = ~0U;
1397 pObjInfo->Attr.u.UnixOwner.szName[0] = '\0'; /** @todo return something sensible here. */
1398 break;
1399
1400 case RTFSOBJATTRADD_UNIX_GROUP:
1401 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_GROUP;
1402 pObjInfo->Attr.u.UnixGroup.gid = ~0U;
1403 pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
1404 break;
1405
1406 case RTFSOBJATTRADD_EASIZE:
1407 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
1408 pObjInfo->Attr.u.EASize.cb = 0;
1409 break;
1410
1411 default:
1412 AssertMsgFailed(("Impossible!\n"));
1413 return VERR_INTERNAL_ERROR;
1414 }
1415
1416 return VINF_SUCCESS;
1417#endif
1418}
1419
1420
1421RTR3DECL(int) RTFileSetTimes(RTFILE hFile, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
1422 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
1423{
1424 RT_NOREF_PV(pChangeTime); /* Not exposed thru the windows API we're using. */
1425
1426 if (!pAccessTime && !pModificationTime && !pBirthTime)
1427 return VINF_SUCCESS; /* NOP */
1428
1429 FILETIME CreationTimeFT;
1430 PFILETIME pCreationTimeFT = NULL;
1431 if (pBirthTime)
1432 pCreationTimeFT = RTTimeSpecGetNtFileTime(pBirthTime, &CreationTimeFT);
1433
1434 FILETIME LastAccessTimeFT;
1435 PFILETIME pLastAccessTimeFT = NULL;
1436 if (pAccessTime)
1437 pLastAccessTimeFT = RTTimeSpecGetNtFileTime(pAccessTime, &LastAccessTimeFT);
1438
1439 FILETIME LastWriteTimeFT;
1440 PFILETIME pLastWriteTimeFT = NULL;
1441 if (pModificationTime)
1442 pLastWriteTimeFT = RTTimeSpecGetNtFileTime(pModificationTime, &LastWriteTimeFT);
1443
1444 int rc = VINF_SUCCESS;
1445 if (!SetFileTime((HANDLE)RTFileToNative(hFile), pCreationTimeFT, pLastAccessTimeFT, pLastWriteTimeFT))
1446 {
1447 DWORD Err = GetLastError();
1448 rc = RTErrConvertFromWin32(Err);
1449 Log(("RTFileSetTimes(%RTfile, %p, %p, %p, %p): SetFileTime failed with lasterr %d (%Rrc)\n",
1450 hFile, pAccessTime, pModificationTime, pChangeTime, pBirthTime, Err, rc));
1451 }
1452 return rc;
1453}
1454
1455
1456#if 0 /* RTFileSetMode is implemented by RTFileSetMode-r3-nt.cpp */
1457/* This comes from a source file with a different set of system headers (DDK)
1458 * so it can't be declared in a common header, like internal/file.h.
1459 */
1460extern int rtFileNativeSetAttributes(HANDLE FileHandle, ULONG FileAttributes);
1461
1462
1463RTR3DECL(int) RTFileSetMode(RTFILE hFile, RTFMODE fMode)
1464{
1465 /*
1466 * Normalize the mode and call the API.
1467 */
1468 fMode = rtFsModeNormalize(fMode, NULL, 0);
1469 if (!rtFsModeIsValid(fMode))
1470 return VERR_INVALID_PARAMETER;
1471
1472 ULONG FileAttributes = (fMode & RTFS_DOS_MASK) >> RTFS_DOS_SHIFT;
1473 int Err = rtFileNativeSetAttributes((HANDLE)hFile, FileAttributes);
1474 if (Err != ERROR_SUCCESS)
1475 {
1476 int rc = RTErrConvertFromWin32(Err);
1477 Log(("RTFileSetMode(%RTfile, %RTfmode): rtFileNativeSetAttributes (0x%08X) failed with err %d (%Rrc)\n",
1478 hFile, fMode, FileAttributes, Err, rc));
1479 return rc;
1480 }
1481 return VINF_SUCCESS;
1482}
1483#endif
1484
1485
1486/* RTFileQueryFsSizes is implemented by ../nt/RTFileQueryFsSizes-nt.cpp */
1487
1488
1489RTR3DECL(int) RTFileDelete(const char *pszFilename)
1490{
1491 PRTUTF16 pwszFilename;
1492 int rc = RTPathWinFromUtf8(&pwszFilename, pszFilename, 0 /*fFlags*/);
1493 if (RT_SUCCESS(rc))
1494 {
1495 if (!DeleteFileW(pwszFilename))
1496 rc = RTErrConvertFromWin32(GetLastError());
1497 RTPathWinFree(pwszFilename);
1498 }
1499
1500 return rc;
1501}
1502
1503
1504RTDECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
1505{
1506 /*
1507 * Validate input.
1508 */
1509 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
1510 AssertPtrReturn(pszDst, VERR_INVALID_POINTER);
1511 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
1512
1513 /*
1514 * Hand it on to the worker.
1515 */
1516 int rc = rtPathWin32MoveRename(pszSrc, pszDst,
1517 fRename & RTPATHRENAME_FLAGS_REPLACE ? MOVEFILE_REPLACE_EXISTING : 0,
1518 RTFS_TYPE_FILE);
1519
1520 LogFlow(("RTFileMove(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
1521 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
1522 return rc;
1523
1524}
1525
1526
1527RTDECL(int) RTFileMove(const char *pszSrc, const char *pszDst, unsigned fMove)
1528{
1529 /*
1530 * Validate input.
1531 */
1532 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
1533 AssertPtrReturn(pszDst, VERR_INVALID_POINTER);
1534 AssertMsgReturn(!(fMove & ~RTFILEMOVE_FLAGS_REPLACE), ("%#x\n", fMove), VERR_INVALID_PARAMETER);
1535
1536 /*
1537 * Hand it on to the worker.
1538 */
1539 int rc = rtPathWin32MoveRename(pszSrc, pszDst,
1540 fMove & RTFILEMOVE_FLAGS_REPLACE
1541 ? MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING
1542 : MOVEFILE_COPY_ALLOWED,
1543 RTFS_TYPE_FILE);
1544
1545 LogFlow(("RTFileMove(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
1546 pszSrc, pszSrc, pszDst, pszDst, fMove, rc));
1547 return rc;
1548}
1549
Note: See TracBrowser for help on using the repository browser.

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