VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/fileio-posix.cpp@ 98103

Last change on this file since 98103 was 98103, checked in by vboxsync, 16 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 28.5 KB
Line 
1/* $Id: fileio-posix.cpp 98103 2023-01-17 14:15:46Z vboxsync $ */
2/** @file
3 * IPRT - File I/O, POSIX, Part 1.
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_FILE
42
43#include <errno.h>
44#include <sys/stat.h>
45#include <sys/types.h>
46#include <sys/ioctl.h>
47#include <fcntl.h>
48#ifdef _MSC_VER
49# include <io.h>
50# include <stdio.h>
51#else
52# include <unistd.h>
53# include <sys/time.h>
54#endif
55#ifdef RT_OS_LINUX
56# include <sys/file.h>
57#endif
58#if defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006)
59# include <io.h>
60#endif
61#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
62# include <sys/disk.h>
63#endif
64#ifdef RT_OS_SOLARIS
65# include <stropts.h>
66# include <sys/dkio.h>
67# include <sys/vtoc.h>
68#endif /* RT_OS_SOLARIS */
69
70#include <iprt/file.h>
71#include <iprt/path.h>
72#include <iprt/assert.h>
73#include <iprt/string.h>
74#include <iprt/err.h>
75#include <iprt/log.h>
76#include <iprt/thread.h>
77#include "internal/file.h"
78#include "internal/fs.h"
79#include "internal/path.h"
80
81
82
83/*********************************************************************************************************************************
84* Defined Constants And Macros *
85*********************************************************************************************************************************/
86/** Default file permissions for newly created files. */
87#if defined(S_IRUSR) && defined(S_IWUSR)
88# define RT_FILE_PERMISSION (S_IRUSR | S_IWUSR)
89#else
90# define RT_FILE_PERMISSION (00600)
91#endif
92
93
94/*********************************************************************************************************************************
95* Defined Constants And Macros *
96*********************************************************************************************************************************/
97#ifdef O_CLOEXEC
98static int volatile g_fHave_O_CLOEXEC = 0; /* {-1,0,1}; since Linux 2.6.23 */
99#endif
100
101
102
103RTDECL(bool) RTFileExists(const char *pszPath)
104{
105 bool fRc = false;
106 char const *pszNativePath;
107 int rc = rtPathToNative(&pszNativePath, pszPath, NULL);
108 if (RT_SUCCESS(rc))
109 {
110 struct stat s;
111 fRc = !stat(pszNativePath, &s)
112 && S_ISREG(s.st_mode);
113
114 rtPathFreeNative(pszNativePath, pszPath);
115 }
116
117 LogFlow(("RTFileExists(%p={%s}): returns %RTbool\n", pszPath, pszPath, fRc));
118 return fRc;
119}
120
121
122#ifdef O_CLOEXEC
123/** Worker for RTFileOpenEx that detects whether the kernel supports
124 * O_CLOEXEC or not, setting g_fHave_O_CLOEXEC to 1 or -1 accordingly. */
125static int rtFileOpenExDetectCloExecSupport(void)
126{
127 /*
128 * Open /dev/null with O_CLOEXEC and see if FD_CLOEXEC is set or not.
129 */
130 int fHave_O_CLOEXEC = -1;
131 int fd = open("/dev/null", O_RDONLY | O_CLOEXEC, 0);
132 if (fd >= 0)
133 {
134 int fFlags = fcntl(fd, F_GETFD, 0);
135 fHave_O_CLOEXEC = fFlags > 0 && (fFlags & FD_CLOEXEC) ? 1 : -1;
136 close(fd);
137 }
138 else
139 AssertMsg(errno == EINVAL, ("%d\n", errno));
140 g_fHave_O_CLOEXEC = fHave_O_CLOEXEC;
141 return fHave_O_CLOEXEC;
142}
143#endif
144
145
146RTR3DECL(int) RTFileOpen(PRTFILE pFile, const char *pszFilename, uint64_t fOpen)
147{
148 return RTFileOpenEx(pszFilename, fOpen, pFile, NULL);
149}
150
151
152RTDECL(int) RTFileOpenEx(const char *pszFilename, uint64_t fOpen, PRTFILE phFile, PRTFILEACTION penmActionTaken)
153{
154 /*
155 * Validate input.
156 */
157 AssertPtrReturn(phFile, VERR_INVALID_POINTER);
158 *phFile = NIL_RTFILE;
159 if (penmActionTaken)
160 *penmActionTaken = RTFILEACTION_INVALID;
161 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
162
163 /*
164 * Merge forced open flags and validate them.
165 */
166 int rc = rtFileRecalcAndValidateFlags(&fOpen);
167 if (RT_FAILURE(rc))
168 return rc;
169#ifndef O_NONBLOCK
170 AssertReturn(!(fOpen & RTFILE_O_NON_BLOCK), VERR_INVALID_FLAGS);
171#endif
172#if defined(RT_OS_OS2) /* Cannot delete open files on OS/2. */
173 AssertReturn(!(fOpen & RTFILE_O_TEMP_AUTO_DELETE), VERR_NOT_SUPPORTED);
174#endif
175
176 /*
177 * Calculate open mode flags.
178 */
179 int fOpenMode = 0;
180#ifdef O_BINARY
181 fOpenMode |= O_BINARY; /* (pc) */
182#endif
183#ifdef O_LARGEFILE
184 fOpenMode |= O_LARGEFILE; /* (linux, solaris) */
185#endif
186#ifdef O_NOINHERIT
187 if (!(fOpen & RTFILE_O_INHERIT))
188 fOpenMode |= O_NOINHERIT;
189#endif
190#ifdef O_CLOEXEC
191 int fHave_O_CLOEXEC = g_fHave_O_CLOEXEC;
192 if ( !(fOpen & RTFILE_O_INHERIT)
193 && ( fHave_O_CLOEXEC > 0
194 || ( fHave_O_CLOEXEC == 0
195 && (fHave_O_CLOEXEC = rtFileOpenExDetectCloExecSupport()) > 0)))
196 fOpenMode |= O_CLOEXEC;
197#endif
198#ifdef O_NONBLOCK
199 if (fOpen & RTFILE_O_NON_BLOCK)
200 fOpenMode |= O_NONBLOCK;
201#endif
202#ifdef O_SYNC
203 if (fOpen & RTFILE_O_WRITE_THROUGH)
204 fOpenMode |= O_SYNC;
205#endif
206#if defined(O_DIRECT) && defined(RT_OS_LINUX)
207 /* O_DIRECT is mandatory to get async I/O working on Linux. */
208 if (fOpen & RTFILE_O_ASYNC_IO)
209 fOpenMode |= O_DIRECT;
210#endif
211#if defined(O_DIRECT) && (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD))
212 /* Disable the kernel cache. */
213 if (fOpen & RTFILE_O_NO_CACHE)
214 fOpenMode |= O_DIRECT;
215#endif
216
217 /* create/truncate file */
218 switch (fOpen & RTFILE_O_ACTION_MASK)
219 {
220 case RTFILE_O_OPEN: break;
221 case RTFILE_O_OPEN_CREATE: fOpenMode |= O_CREAT; break;
222 case RTFILE_O_CREATE: fOpenMode |= O_CREAT | O_EXCL; break;
223 case RTFILE_O_CREATE_REPLACE: fOpenMode |= O_CREAT | O_TRUNC; break; /** @todo replacing needs fixing, this is *not* a 1:1 mapping! */
224 default:
225 AssertMsgFailed(("fOpen=%#llx\n", fOpen));
226 fOpen = (fOpen & ~RTFILE_O_ACTION_MASK) | RTFILE_O_OPEN;
227 break;
228
229 }
230 if ( (fOpen & RTFILE_O_TRUNCATE)
231 && (fOpen & RTFILE_O_ACTION_MASK) != RTFILE_O_CREATE)
232 fOpenMode |= O_TRUNC;
233
234 switch (fOpen & RTFILE_O_ACCESS_MASK)
235 {
236 case RTFILE_O_READ:
237 fOpenMode |= O_RDONLY; /* RTFILE_O_APPEND is ignored. */
238 break;
239 case RTFILE_O_WRITE:
240 fOpenMode |= fOpen & RTFILE_O_APPEND ? O_APPEND | O_WRONLY : O_WRONLY;
241 break;
242 case RTFILE_O_READWRITE:
243 fOpenMode |= fOpen & RTFILE_O_APPEND ? O_APPEND | O_RDWR : O_RDWR;
244 break;
245 default:
246 AssertMsgFailedReturn(("RTFileOpen received an invalid RW value, fOpen=%#llx\n", fOpen), VERR_INVALID_FLAGS);
247 }
248
249 /* File mode. */
250 int fMode = (fOpen & RTFILE_O_CREATE_MODE_MASK)
251 ? (fOpen & RTFILE_O_CREATE_MODE_MASK) >> RTFILE_O_CREATE_MODE_SHIFT
252 : RT_FILE_PERMISSION;
253
254 /** @todo sharing? */
255
256 /*
257 * Open/create the file.
258 */
259 char const *pszNativeFilename;
260 rc = rtPathToNative(&pszNativeFilename, pszFilename, NULL);
261 if (RT_FAILURE(rc))
262 return (rc);
263
264 int fh;
265 int iErr;
266 if (!penmActionTaken)
267 {
268 fh = open(pszNativeFilename, fOpenMode, fMode);
269 iErr = errno;
270 }
271 else
272 {
273 /* We need to know exactly which action was taken by open, Windows &
274 OS/2 style. Can be tedious and subject to races: */
275 switch (fOpen & RTFILE_O_ACTION_MASK)
276 {
277 case RTFILE_O_OPEN:
278 Assert(!(fOpenMode & O_CREAT));
279 Assert(!(fOpenMode & O_EXCL));
280 fh = open(pszNativeFilename, fOpenMode, fMode);
281 iErr = errno;
282 if (fh >= 0)
283 *penmActionTaken = fOpenMode & O_TRUNC ? RTFILEACTION_TRUNCATED : RTFILEACTION_OPENED;
284 break;
285
286 case RTFILE_O_CREATE:
287 Assert(fOpenMode & O_CREAT);
288 Assert(fOpenMode & O_EXCL);
289 fh = open(pszNativeFilename, fOpenMode, fMode);
290 iErr = errno;
291 if (fh >= 0)
292 *penmActionTaken = RTFILEACTION_CREATED;
293 else if (iErr == EEXIST)
294 *penmActionTaken = RTFILEACTION_ALREADY_EXISTS;
295 break;
296
297 case RTFILE_O_OPEN_CREATE:
298 case RTFILE_O_CREATE_REPLACE:
299 {
300 Assert(fOpenMode & O_CREAT);
301 Assert(!(fOpenMode & O_EXCL));
302 int iTries = 64;
303 while (iTries-- > 0)
304 {
305 /* Yield the CPU if we've raced too long. */
306 if (iTries < 4)
307 RTThreadSleep(2 - (iTries & 1));
308
309 /* Try exclusive creation first: */
310 fh = open(pszNativeFilename, fOpenMode | O_EXCL, fMode);
311 iErr = errno;
312 if (fh >= 0)
313 {
314 *penmActionTaken = RTFILEACTION_CREATED;
315 break;
316 }
317 if (iErr != EEXIST)
318 break;
319
320 /* If the file exists, try open it: */
321 fh = open(pszNativeFilename, fOpenMode & ~O_CREAT, fMode);
322 iErr = errno;
323 if (fh >= 0)
324 {
325 if ((fOpen & RTFILE_O_ACTION_MASK) == RTFILE_O_OPEN_CREATE)
326 *penmActionTaken = fOpenMode & O_TRUNC ? RTFILEACTION_TRUNCATED : RTFILEACTION_OPENED;
327 else
328 *penmActionTaken = RTFILEACTION_REPLACED;
329 break;
330 }
331 if (iErr != ENOENT)
332 break;
333 }
334 Assert(iTries >= 0);
335 if (iTries < 0)
336 {
337 /* Thanks for the race, but we need to get on with things. */
338 fh = open(pszNativeFilename, fOpenMode, fMode);
339 iErr = errno;
340 if (fh >= 0)
341 *penmActionTaken = RTFILEACTION_OPENED;
342 }
343 break;
344 }
345
346 default:
347 AssertMsgFailed(("fOpen=%#llx fOpenMode=%#x\n", fOpen, fOpenMode));
348 iErr = EINVAL;
349 fh = -1;
350 break;
351 }
352 }
353
354 rtPathFreeNative(pszNativeFilename, pszFilename);
355 if (fh >= 0)
356 {
357 iErr = 0;
358
359 /*
360 * If temporary file, delete it.
361 */
362 if (fOpen & RTFILE_O_TEMP_AUTO_DELETE)
363 {
364 /** @todo Use funlinkat/funlink or similar here when available! Or better,
365 * use O_TMPFILE, only that may require fallback as not supported by
366 * all file system on linux. */
367 iErr = unlink(pszNativeFilename);
368 Assert(iErr == 0);
369 }
370
371 /*
372 * Mark the file handle close on exec, unless inherit is specified.
373 */
374 if ( !(fOpen & RTFILE_O_INHERIT)
375#ifdef O_NOINHERIT
376 && !(fOpenMode & O_NOINHERIT) /* Take care since it might be a zero value dummy. */
377#endif
378#ifdef O_CLOEXEC
379 && fHave_O_CLOEXEC <= 0
380#endif
381 )
382 iErr = fcntl(fh, F_SETFD, FD_CLOEXEC) >= 0 ? 0 : errno;
383
384 /*
385 * Switch direct I/O on now if requested and required.
386 */
387#if defined(RT_OS_DARWIN) \
388 || (defined(RT_OS_SOLARIS) && !defined(IN_GUEST))
389 if (iErr == 0 && (fOpen & RTFILE_O_NO_CACHE))
390 {
391# if defined(RT_OS_DARWIN)
392 iErr = fcntl(fh, F_NOCACHE, 1) >= 0 ? 0 : errno;
393# else
394 iErr = directio(fh, DIRECTIO_ON) >= 0 ? 0 : errno;
395# endif
396 }
397#endif
398
399 /*
400 * Implement / emulate file sharing.
401 *
402 * We need another mode which allows skipping this stuff completely
403 * and do things the UNIX way. So for the present this is just a debug
404 * aid that can be enabled by developers too lazy to test on Windows.
405 */
406#if 0 && defined(RT_OS_LINUX)
407 if (iErr == 0)
408 {
409 /* This approach doesn't work because only knfsd checks for these
410 buggers. :-( */
411 int iLockOp;
412 switch (fOpen & RTFILE_O_DENY_MASK)
413 {
414 default:
415 AssertFailed();
416 case RTFILE_O_DENY_NONE:
417 case RTFILE_O_DENY_NOT_DELETE:
418 iLockOp = LOCK_MAND | LOCK_READ | LOCK_WRITE;
419 break;
420 case RTFILE_O_DENY_READ:
421 case RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
422 iLockOp = LOCK_MAND | LOCK_WRITE;
423 break;
424 case RTFILE_O_DENY_WRITE:
425 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_NOT_DELETE:
426 iLockOp = LOCK_MAND | LOCK_READ;
427 break;
428 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ:
429 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
430 iLockOp = LOCK_MAND;
431 break;
432 }
433 iErr = flock(fh, iLockOp | LOCK_NB);
434 if (iErr != 0)
435 iErr = errno == EAGAIN ? ETXTBSY : 0;
436 }
437#endif /* 0 && RT_OS_LINUX */
438#if defined(DEBUG_bird) && !defined(RT_OS_SOLARIS)
439 if (iErr == 0)
440 {
441 /* This emulation is incomplete but useful. */
442 switch (fOpen & RTFILE_O_DENY_MASK)
443 {
444 default:
445 AssertFailed();
446 case RTFILE_O_DENY_NONE:
447 case RTFILE_O_DENY_NOT_DELETE:
448 case RTFILE_O_DENY_READ:
449 case RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
450 break;
451 case RTFILE_O_DENY_WRITE:
452 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_NOT_DELETE:
453 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ:
454 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
455 if (fOpen & RTFILE_O_WRITE)
456 {
457 iErr = flock(fh, LOCK_EX | LOCK_NB);
458 if (iErr != 0)
459 iErr = errno == EAGAIN ? ETXTBSY : 0;
460 }
461 break;
462 }
463 }
464#endif
465#ifdef RT_OS_SOLARIS
466 /** @todo Use fshare_t and associates, it's a perfect match. see sys/fcntl.h */
467#endif
468
469 /*
470 * We're done.
471 */
472 if (iErr == 0)
473 {
474 *phFile = (RTFILE)(uintptr_t)fh;
475 Assert((intptr_t)*phFile == fh);
476 LogFlow(("RTFileOpen(%p:{%RTfile}, %p:{%s}, %#llx): returns %Rrc\n",
477 phFile, *phFile, pszFilename, pszFilename, fOpen, rc));
478 return VINF_SUCCESS;
479 }
480
481 close(fh);
482 }
483 return RTErrConvertFromErrno(iErr);
484}
485
486
487RTR3DECL(int) RTFileOpenBitBucket(PRTFILE phFile, uint64_t fAccess)
488{
489 AssertReturn( fAccess == RTFILE_O_READ
490 || fAccess == RTFILE_O_WRITE
491 || fAccess == RTFILE_O_READWRITE,
492 VERR_INVALID_PARAMETER);
493 return RTFileOpen(phFile, "/dev/null", fAccess | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
494}
495
496
497RTR3DECL(int) RTFileClose(RTFILE hFile)
498{
499 if (hFile == NIL_RTFILE)
500 return VINF_SUCCESS;
501 if (close(RTFileToNative(hFile)) == 0)
502 return VINF_SUCCESS;
503 return RTErrConvertFromErrno(errno);
504}
505
506
507RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
508{
509 AssertCompile(sizeof(uNative) == sizeof(*pFile));
510 if (uNative < 0)
511 {
512 AssertMsgFailed(("%p\n", uNative));
513 *pFile = NIL_RTFILE;
514 return VERR_INVALID_HANDLE;
515 }
516 *pFile = (RTFILE)uNative;
517 return VINF_SUCCESS;
518}
519
520
521RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE hFile)
522{
523 AssertReturn(hFile != NIL_RTFILE, -1);
524 return (intptr_t)hFile;
525}
526
527
528RTFILE rtFileGetStandard(RTHANDLESTD enmStdHandle)
529{
530 int fd;
531 switch (enmStdHandle)
532 {
533 case RTHANDLESTD_INPUT: fd = 0; break;
534 case RTHANDLESTD_OUTPUT: fd = 1; break;
535 case RTHANDLESTD_ERROR: fd = 2; break;
536 default:
537 AssertFailedReturn(NIL_RTFILE);
538 }
539
540 struct stat st;
541 int rc = fstat(fd, &st);
542 if (rc == -1)
543 return NIL_RTFILE;
544 return (RTFILE)(intptr_t)fd;
545}
546
547
548RTR3DECL(int) RTFileDelete(const char *pszFilename)
549{
550 char const *pszNativeFilename;
551 int rc = rtPathToNative(&pszNativeFilename, pszFilename, NULL);
552 if (RT_SUCCESS(rc))
553 {
554 if (unlink(pszNativeFilename) != 0)
555 rc = RTErrConvertFromErrno(errno);
556 rtPathFreeNative(pszNativeFilename, pszFilename);
557 }
558 return rc;
559}
560
561
562RTR3DECL(int) RTFileSeek(RTFILE hFile, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
563{
564 static const unsigned aSeekRecode[] =
565 {
566 SEEK_SET,
567 SEEK_CUR,
568 SEEK_END,
569 };
570
571 /*
572 * Validate input.
573 */
574 if (uMethod > RTFILE_SEEK_END)
575 {
576 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
577 return VERR_INVALID_PARAMETER;
578 }
579
580 /* check that within off_t range. */
581 if ( sizeof(off_t) < sizeof(offSeek)
582 && ( (offSeek > 0 && (unsigned)(offSeek >> 32) != 0)
583 || (offSeek < 0 && (unsigned)(-offSeek >> 32) != 0)))
584 {
585 AssertMsgFailed(("64-bit search not supported\n"));
586 return VERR_NOT_SUPPORTED;
587 }
588
589 off_t offCurrent = lseek(RTFileToNative(hFile), (off_t)offSeek, aSeekRecode[uMethod]);
590 if (offCurrent != ~0)
591 {
592 if (poffActual)
593 *poffActual = (uint64_t)offCurrent;
594 return VINF_SUCCESS;
595 }
596 return RTErrConvertFromErrno(errno);
597}
598
599
600RTR3DECL(int) RTFileRead(RTFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
601{
602 if (cbToRead <= 0)
603 {
604 if (pcbRead)
605 *pcbRead = 0;
606 return VINF_SUCCESS;
607 }
608
609 /*
610 * Attempt read.
611 */
612 ssize_t cbRead = read(RTFileToNative(hFile), pvBuf, cbToRead);
613 if (cbRead >= 0)
614 {
615 if (pcbRead)
616 /* caller can handle partial read. */
617 *pcbRead = cbRead;
618 else
619 {
620 /* Caller expects all to be read. */
621 while ((ssize_t)cbToRead > cbRead)
622 {
623 ssize_t cbReadPart = read(RTFileToNative(hFile), (char*)pvBuf + cbRead, cbToRead - cbRead);
624 if (cbReadPart <= 0)
625 {
626 if (cbReadPart == 0)
627 return VERR_EOF;
628 return RTErrConvertFromErrno(errno);
629 }
630 cbRead += cbReadPart;
631 }
632 }
633 return VINF_SUCCESS;
634 }
635
636 return RTErrConvertFromErrno(errno);
637}
638
639
640RTR3DECL(int) RTFileWrite(RTFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
641{
642 if (cbToWrite <= 0)
643 return VINF_SUCCESS;
644
645 /*
646 * Attempt write.
647 */
648 ssize_t cbWritten = write(RTFileToNative(hFile), pvBuf, cbToWrite);
649 if (cbWritten >= 0)
650 {
651 if (pcbWritten)
652 /* caller can handle partial write. */
653 *pcbWritten = cbWritten;
654 else
655 {
656 /* Caller expects all to be write. */
657 while ((ssize_t)cbToWrite > cbWritten)
658 {
659 ssize_t cbWrittenPart = write(RTFileToNative(hFile), (const char *)pvBuf + cbWritten, cbToWrite - cbWritten);
660 if (cbWrittenPart <= 0)
661 return cbWrittenPart < 0 ? RTErrConvertFromErrno(errno) : VERR_TRY_AGAIN;
662 cbWritten += cbWrittenPart;
663 }
664 }
665 return VINF_SUCCESS;
666 }
667 return RTErrConvertFromErrno(errno);
668}
669
670
671RTR3DECL(int) RTFileSetSize(RTFILE hFile, uint64_t cbSize)
672{
673 /*
674 * Validate offset.
675 */
676 if ( sizeof(off_t) < sizeof(cbSize)
677 && (cbSize >> 32) != 0)
678 {
679 AssertMsgFailed(("64-bit filesize not supported! cbSize=%lld\n", cbSize));
680 return VERR_NOT_SUPPORTED;
681 }
682
683#if defined(_MSC_VER) || (defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006))
684 if (chsize(RTFileToNative(hFile), (off_t)cbSize) == 0)
685#else
686 /* This relies on a non-standard feature of FreeBSD, Linux, and OS/2
687 * LIBC v0.6 and higher. (SuS doesn't define ftruncate() and size bigger
688 * than the file.)
689 */
690 if (ftruncate(RTFileToNative(hFile), (off_t)cbSize) == 0)
691#endif
692 return VINF_SUCCESS;
693 return RTErrConvertFromErrno(errno);
694}
695
696
697RTR3DECL(int) RTFileQuerySize(RTFILE hFile, uint64_t *pcbSize)
698{
699 /*
700 * Ask fstat() first.
701 */
702 struct stat st;
703 if (!fstat(RTFileToNative(hFile), &st))
704 {
705 *pcbSize = st.st_size;
706 if ( st.st_size != 0
707#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
708 || (!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode))
709#elif defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD) || defined(RT_OS_DARWIN)
710 || !S_ISCHR(st.st_mode)
711#else
712 || !S_ISBLK(st.st_mode)
713#endif
714 )
715 return VINF_SUCCESS;
716
717 /*
718 * It could be a block device. Try determin the size by I/O control
719 * query or seek.
720 */
721#ifdef RT_OS_DARWIN
722 uint64_t cBlocks;
723 if (!ioctl(RTFileToNative(hFile), DKIOCGETBLOCKCOUNT, &cBlocks))
724 {
725 uint32_t cbBlock;
726 if (!ioctl(RTFileToNative(hFile), DKIOCGETBLOCKSIZE, &cbBlock))
727 {
728 *pcbSize = cBlocks * cbBlock;
729 return VINF_SUCCESS;
730 }
731 }
732
733 /* Always fail block devices. Character devices doesn't all need to be
734 /dev/rdisk* nodes, they should return ENOTTY but /dev/null returns ENODEV
735 and we include EINVAL just in case. */
736 if (!S_ISBLK(st.st_mode) && (errno == ENOTTY || errno == ENODEV || errno == EINVAL))
737 return VINF_SUCCESS;
738
739#elif defined(RT_OS_SOLARIS)
740 struct dk_minfo MediaInfo;
741 if (!ioctl(RTFileToNative(hFile), DKIOCGMEDIAINFO, &MediaInfo))
742 {
743 *pcbSize = MediaInfo.dki_capacity * MediaInfo.dki_lbsize;
744 return VINF_SUCCESS;
745 }
746 /* might not be a block device. */
747 if (errno == EINVAL || errno == ENOTTY)
748 return VINF_SUCCESS;
749
750#elif defined(RT_OS_FREEBSD)
751 off_t cbMedia = 0;
752 if (!ioctl(RTFileToNative(hFile), DIOCGMEDIASIZE, &cbMedia))
753 {
754 *pcbSize = cbMedia;
755 return VINF_SUCCESS;
756 }
757 /* might not be a block device. */
758 if (errno == EINVAL || errno == ENOTTY)
759 return VINF_SUCCESS;
760
761#else
762 /* PORTME! Avoid this path when possible. */
763 uint64_t offSaved = UINT64_MAX;
764 int rc = RTFileSeek(hFile, 0, RTFILE_SEEK_CURRENT, &offSaved);
765 if (RT_SUCCESS(rc))
766 {
767 rc = RTFileSeek(hFile, 0, RTFILE_SEEK_END, pcbSize);
768 int rc2 = RTFileSeek(hFile, offSaved, RTFILE_SEEK_BEGIN, NULL);
769 if (RT_SUCCESS(rc))
770 return rc2;
771 }
772#endif
773 }
774 return RTErrConvertFromErrno(errno);
775}
776
777
778RTR3DECL(int) RTFileQueryMaxSizeEx(RTFILE hFile, PRTFOFF pcbMax)
779{
780 /*
781 * Save the current location
782 */
783 uint64_t offOld = UINT64_MAX;
784 int rc = RTFileSeek(hFile, 0, RTFILE_SEEK_CURRENT, &offOld);
785 if (RT_FAILURE(rc))
786 return rc;
787
788 uint64_t offLow = 0;
789 uint64_t offHigh = INT64_MAX; /* we don't need bigger files */
790 /** @todo Unfortunately this does not work for certain file system types,
791 * for instance cifs mounts. Even worse, statvfs.f_fsid returns 0 for such
792 * file systems. */
793
794 /*
795 * Quickly guess the order of magnitude for offHigh and offLow.
796 */
797 {
798 uint64_t offHighPrev = offHigh;
799 while (offHigh >= INT32_MAX)
800 {
801 rc = RTFileSeek(hFile, offHigh, RTFILE_SEEK_BEGIN, NULL);
802 if (RT_SUCCESS(rc))
803 {
804 offLow = offHigh;
805 offHigh = offHighPrev;
806 break;
807 }
808 else
809 {
810 offHighPrev = offHigh;
811 offHigh >>= 8;
812 }
813 }
814 }
815
816 /*
817 * Sanity: if the seek to the initial offHigh (INT64_MAX) works, then
818 * this algorithm cannot possibly work. Declare defeat.
819 */
820 if (offLow == offHigh)
821 {
822 rc = RTFileSeek(hFile, offOld, RTFILE_SEEK_BEGIN, NULL);
823 if (RT_SUCCESS(rc))
824 rc = VERR_NOT_IMPLEMENTED;
825
826 return rc;
827 }
828
829 /*
830 * Perform a binary search for the max file size.
831 */
832 while (offLow <= offHigh)
833 {
834 uint64_t offMid = offLow + (offHigh - offLow) / 2;
835 rc = RTFileSeek(hFile, offMid, RTFILE_SEEK_BEGIN, NULL);
836 if (RT_FAILURE(rc))
837 offHigh = offMid - 1;
838 else
839 offLow = offMid + 1;
840 }
841
842 if (pcbMax)
843 *pcbMax = RT_MIN(offLow, offHigh);
844 return RTFileSeek(hFile, offOld, RTFILE_SEEK_BEGIN, NULL);
845}
846
847
848RTR3DECL(bool) RTFileIsValid(RTFILE hFile)
849{
850 if (hFile != NIL_RTFILE)
851 {
852 int fFlags = fcntl(RTFileToNative(hFile), F_GETFD);
853 if (fFlags >= 0)
854 return true;
855 }
856 return false;
857}
858
859
860RTR3DECL(int) RTFileFlush(RTFILE hFile)
861{
862 if (!fsync(RTFileToNative(hFile)))
863 return VINF_SUCCESS;
864 /* Ignore EINVAL here as that's what returned for pseudo ttys
865 and other odd handles. */
866 if (errno == EINVAL)
867 return VINF_NOT_SUPPORTED;
868 return RTErrConvertFromErrno(errno);
869}
870
871
872RTR3DECL(int) RTFileIoCtl(RTFILE hFile, unsigned long ulRequest, void *pvData, unsigned cbData, int *piRet)
873{
874 NOREF(cbData);
875 int rc = ioctl(RTFileToNative(hFile), ulRequest, pvData);
876 if (piRet)
877 *piRet = rc;
878 return rc >= 0 ? VINF_SUCCESS : RTErrConvertFromErrno(errno);
879}
880
881
882RTR3DECL(int) RTFileSetMode(RTFILE hFile, RTFMODE fMode)
883{
884 /*
885 * Normalize the mode and call the API.
886 */
887 fMode = rtFsModeNormalize(fMode, NULL, 0, RTFS_TYPE_FILE);
888 if (!rtFsModeIsValid(fMode))
889 return VERR_INVALID_PARAMETER;
890
891 if (fchmod(RTFileToNative(hFile), fMode & RTFS_UNIX_MASK))
892 {
893 int rc = RTErrConvertFromErrno(errno);
894 Log(("RTFileSetMode(%RTfile,%RTfmode): returns %Rrc\n", hFile, fMode, rc));
895 return rc;
896 }
897 return VINF_SUCCESS;
898}
899
900
901RTDECL(int) RTFileSetOwner(RTFILE hFile, uint32_t uid, uint32_t gid)
902{
903 uid_t uidNative = uid != NIL_RTUID ? (uid_t)uid : (uid_t)-1;
904 AssertReturn(uid == uidNative, VERR_INVALID_PARAMETER);
905 gid_t gidNative = gid != NIL_RTGID ? (gid_t)gid : (gid_t)-1;
906 AssertReturn(gid == gidNative, VERR_INVALID_PARAMETER);
907
908 if (fchown(RTFileToNative(hFile), uidNative, gidNative))
909 return RTErrConvertFromErrno(errno);
910 return VINF_SUCCESS;
911}
912
913
914RTR3DECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
915{
916 /*
917 * Validate input.
918 */
919 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
920 AssertPtrReturn(pszDst, VERR_INVALID_POINTER);
921 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
922 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
923 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
924
925 /*
926 * Take common cause with RTPathRename.
927 */
928 int rc = rtPathPosixRename(pszSrc, pszDst, fRename, RTFS_TYPE_FILE);
929
930 LogFlow(("RTDirRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
931 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
932 return rc;
933}
934
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use