VirtualBox

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

Last change on this file was 100561, checked in by vboxsync, 10 months ago

Runtime: Reorder some (at this point unused) code, bugref:10261

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 28.5 KB
RevLine 
[1]1/* $Id: fileio-posix.cpp 100561 2023-07-13 09:58:36Z vboxsync $ */
2/** @file
[34016]3 * IPRT - File I/O, POSIX, Part 1.
[1]4 */
5
6/*
[98103]7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
[1]8 *
[96407]9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
[5999]11 *
[96407]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 *
[5999]25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
[96407]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
[5999]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.
[96407]33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
[1]35 */
36
37
[57358]38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
[1]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
[24584]55#ifdef RT_OS_LINUX
56# include <sys/file.h>
57#endif
[3672]58#if defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006)
[1]59# include <io.h>
60#endif
[39030]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 */
[1]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>
[77684]76#include <iprt/thread.h>
[1]77#include "internal/file.h"
78#include "internal/fs.h"
79#include "internal/path.h"
80
81
82
[57358]83/*********************************************************************************************************************************
84* Defined Constants And Macros *
85*********************************************************************************************************************************/
[1]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
[77684]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
[22516]103RTDECL(bool) RTFileExists(const char *pszPath)
104{
105 bool fRc = false;
[28915]106 char const *pszNativePath;
107 int rc = rtPathToNative(&pszNativePath, pszPath, NULL);
[22516]108 if (RT_SUCCESS(rc))
109 {
110 struct stat s;
111 fRc = !stat(pszNativePath, &s)
112 && S_ISREG(s.st_mode);
113
[28877]114 rtPathFreeNative(pszNativePath, pszPath);
[22516]115 }
116
117 LogFlow(("RTFileExists(%p={%s}): returns %RTbool\n", pszPath, pszPath, fRc));
118 return fRc;
119}
120
121
[77684]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
[37596]146RTR3DECL(int) RTFileOpen(PRTFILE pFile, const char *pszFilename, uint64_t fOpen)
[1]147{
[77684]148 return RTFileOpenEx(pszFilename, fOpen, pFile, NULL);
149}
150
151
152RTDECL(int) RTFileOpenEx(const char *pszFilename, uint64_t fOpen, PRTFILE phFile, PRTFILEACTION penmActionTaken)
153{
[1]154 /*
155 * Validate input.
156 */
[77684]157 AssertPtrReturn(phFile, VERR_INVALID_POINTER);
158 *phFile = NIL_RTFILE;
159 if (penmActionTaken)
160 *penmActionTaken = RTFILEACTION_INVALID;
[23973]161 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
[1]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
[77684]170 AssertReturn(!(fOpen & RTFILE_O_NON_BLOCK), VERR_INVALID_FLAGS);
[1]171#endif
[96076]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
[1]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
[31717]184 fOpenMode |= O_LARGEFILE; /* (linux, solaris) */
[1]185#endif
186#ifdef O_NOINHERIT
187 if (!(fOpen & RTFILE_O_INHERIT))
188 fOpenMode |= O_NOINHERIT;
189#endif
[33103]190#ifdef O_CLOEXEC
[77684]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)))
[33103]196 fOpenMode |= O_CLOEXEC;
197#endif
[5581]198#ifdef O_NONBLOCK
[1]199 if (fOpen & RTFILE_O_NON_BLOCK)
[5581]200 fOpenMode |= O_NONBLOCK;
[1]201#endif
202#ifdef O_SYNC
203 if (fOpen & RTFILE_O_WRITE_THROUGH)
204 fOpenMode |= O_SYNC;
205#endif
[19346]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
[62947]211#if defined(O_DIRECT) && (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD))
[21493]212 /* Disable the kernel cache. */
213 if (fOpen & RTFILE_O_NO_CACHE)
214 fOpenMode |= O_DIRECT;
215#endif
[1]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! */
[77684]224 default:
225 AssertMsgFailed(("fOpen=%#llx\n", fOpen));
226 fOpen = (fOpen & ~RTFILE_O_ACTION_MASK) | RTFILE_O_OPEN;
227 break;
228
[1]229 }
[77684]230 if ( (fOpen & RTFILE_O_TRUNCATE)
231 && (fOpen & RTFILE_O_ACTION_MASK) != RTFILE_O_CREATE)
[1]232 fOpenMode |= O_TRUNC;
233
234 switch (fOpen & RTFILE_O_ACCESS_MASK)
235 {
[21582]236 case RTFILE_O_READ:
237 fOpenMode |= O_RDONLY; /* RTFILE_O_APPEND is ignored. */
238 break;
239 case RTFILE_O_WRITE:
[21616]240 fOpenMode |= fOpen & RTFILE_O_APPEND ? O_APPEND | O_WRONLY : O_WRONLY;
[21582]241 break;
242 case RTFILE_O_READWRITE:
[21616]243 fOpenMode |= fOpen & RTFILE_O_APPEND ? O_APPEND | O_RDWR : O_RDWR;
[21582]244 break;
[1]245 default:
[77684]246 AssertMsgFailedReturn(("RTFileOpen received an invalid RW value, fOpen=%#llx\n", fOpen), VERR_INVALID_FLAGS);
[1]247 }
248
[10644]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
[77684]254 /** @todo sharing? */
[1]255
256 /*
257 * Open/create the file.
258 */
[28915]259 char const *pszNativeFilename;
260 rc = rtPathToNative(&pszNativeFilename, pszFilename, NULL);
[1]261 if (RT_FAILURE(rc))
262 return (rc);
263
[77684]264 int fh;
265 int iErr;
266 if (!penmActionTaken)
[33103]267 {
[77684]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)
[33103]276 {
[77684]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;
[33103]351 }
352 }
353
[100561]354 /*
355 * If temporary file, delete it.
356 */
357 if ( fh >= 0
358 && (fOpen & RTFILE_O_TEMP_AUTO_DELETE))
359 {
360 /** @todo Use funlinkat/funlink or similar here when available! Or better,
361 * use O_TMPFILE, only that may require fallback as not supported by
362 * all file system on linux. */
363 iErr = unlink(pszNativeFilename);
364 Assert(iErr == 0);
365 }
366
[28877]367 rtPathFreeNative(pszNativeFilename, pszFilename);
[1]368 if (fh >= 0)
369 {
[24584]370 iErr = 0;
371
[1]372 /*
373 * Mark the file handle close on exec, unless inherit is specified.
374 */
[27289]375 if ( !(fOpen & RTFILE_O_INHERIT)
[1]376#ifdef O_NOINHERIT
[24584]377 && !(fOpenMode & O_NOINHERIT) /* Take care since it might be a zero value dummy. */
[1]378#endif
[33103]379#ifdef O_CLOEXEC
[77684]380 && fHave_O_CLOEXEC <= 0
[33103]381#endif
[24584]382 )
[24585]383 iErr = fcntl(fh, F_SETFD, FD_CLOEXEC) >= 0 ? 0 : errno;
[24584]384
385 /*
386 * Switch direct I/O on now if requested and required.
387 */
388#if defined(RT_OS_DARWIN) \
389 || (defined(RT_OS_SOLARIS) && !defined(IN_GUEST))
390 if (iErr == 0 && (fOpen & RTFILE_O_NO_CACHE))
[1]391 {
[24584]392# if defined(RT_OS_DARWIN)
[24585]393 iErr = fcntl(fh, F_NOCACHE, 1) >= 0 ? 0 : errno;
[24584]394# else
[24585]395 iErr = directio(fh, DIRECTIO_ON) >= 0 ? 0 : errno;
[21493]396# endif
[24584]397 }
[21493]398#endif
[24584]399
400 /*
401 * Implement / emulate file sharing.
402 *
403 * We need another mode which allows skipping this stuff completely
404 * and do things the UNIX way. So for the present this is just a debug
405 * aid that can be enabled by developers too lazy to test on Windows.
406 */
407#if 0 && defined(RT_OS_LINUX)
408 if (iErr == 0)
409 {
410 /* This approach doesn't work because only knfsd checks for these
411 buggers. :-( */
412 int iLockOp;
413 switch (fOpen & RTFILE_O_DENY_MASK)
[21493]414 {
[24584]415 default:
416 AssertFailed();
417 case RTFILE_O_DENY_NONE:
418 case RTFILE_O_DENY_NOT_DELETE:
419 iLockOp = LOCK_MAND | LOCK_READ | LOCK_WRITE;
420 break;
421 case RTFILE_O_DENY_READ:
422 case RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
423 iLockOp = LOCK_MAND | LOCK_WRITE;
424 break;
425 case RTFILE_O_DENY_WRITE:
426 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_NOT_DELETE:
427 iLockOp = LOCK_MAND | LOCK_READ;
428 break;
429 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ:
430 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
431 iLockOp = LOCK_MAND;
432 break;
[21493]433 }
[24584]434 iErr = flock(fh, iLockOp | LOCK_NB);
435 if (iErr != 0)
436 iErr = errno == EAGAIN ? ETXTBSY : 0;
[1]437 }
[24584]438#endif /* 0 && RT_OS_LINUX */
[29263]439#if defined(DEBUG_bird) && !defined(RT_OS_SOLARIS)
[24584]440 if (iErr == 0)
441 {
442 /* This emulation is incomplete but useful. */
443 switch (fOpen & RTFILE_O_DENY_MASK)
444 {
445 default:
446 AssertFailed();
447 case RTFILE_O_DENY_NONE:
448 case RTFILE_O_DENY_NOT_DELETE:
449 case RTFILE_O_DENY_READ:
450 case RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
451 break;
452 case RTFILE_O_DENY_WRITE:
453 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_NOT_DELETE:
454 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ:
455 case RTFILE_O_DENY_WRITE | RTFILE_O_DENY_READ | RTFILE_O_DENY_NOT_DELETE:
456 if (fOpen & RTFILE_O_WRITE)
457 {
458 iErr = flock(fh, LOCK_EX | LOCK_NB);
459 if (iErr != 0)
460 iErr = errno == EAGAIN ? ETXTBSY : 0;
461 }
462 break;
463 }
464 }
465#endif
466#ifdef RT_OS_SOLARIS
467 /** @todo Use fshare_t and associates, it's a perfect match. see sys/fcntl.h */
468#endif
469
470 /*
471 * We're done.
472 */
473 if (iErr == 0)
474 {
[77684]475 *phFile = (RTFILE)(uintptr_t)fh;
476 Assert((intptr_t)*phFile == fh);
[37596]477 LogFlow(("RTFileOpen(%p:{%RTfile}, %p:{%s}, %#llx): returns %Rrc\n",
[77684]478 phFile, *phFile, pszFilename, pszFilename, fOpen, rc));
[24584]479 return VINF_SUCCESS;
480 }
481
[1]482 close(fh);
483 }
484 return RTErrConvertFromErrno(iErr);
485}
486
487
[37596]488RTR3DECL(int) RTFileOpenBitBucket(PRTFILE phFile, uint64_t fAccess)
[26761]489{
490 AssertReturn( fAccess == RTFILE_O_READ
491 || fAccess == RTFILE_O_WRITE
492 || fAccess == RTFILE_O_READWRITE,
493 VERR_INVALID_PARAMETER);
494 return RTFileOpen(phFile, "/dev/null", fAccess | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
495}
496
497
[37596]498RTR3DECL(int) RTFileClose(RTFILE hFile)
[1]499{
[37596]500 if (hFile == NIL_RTFILE)
[34579]501 return VINF_SUCCESS;
[37596]502 if (close(RTFileToNative(hFile)) == 0)
[1]503 return VINF_SUCCESS;
504 return RTErrConvertFromErrno(errno);
505}
506
507
[8561]508RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
509{
[37596]510 AssertCompile(sizeof(uNative) == sizeof(*pFile));
511 if (uNative < 0)
[8561]512 {
513 AssertMsgFailed(("%p\n", uNative));
514 *pFile = NIL_RTFILE;
515 return VERR_INVALID_HANDLE;
516 }
517 *pFile = (RTFILE)uNative;
518 return VINF_SUCCESS;
519}
520
521
[37596]522RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE hFile)
[8561]523{
[37596]524 AssertReturn(hFile != NIL_RTFILE, -1);
525 return (intptr_t)hFile;
[8561]526}
527
528
[36597]529RTFILE rtFileGetStandard(RTHANDLESTD enmStdHandle)
530{
531 int fd;
532 switch (enmStdHandle)
533 {
534 case RTHANDLESTD_INPUT: fd = 0; break;
535 case RTHANDLESTD_OUTPUT: fd = 1; break;
536 case RTHANDLESTD_ERROR: fd = 2; break;
537 default:
538 AssertFailedReturn(NIL_RTFILE);
539 }
540
541 struct stat st;
542 int rc = fstat(fd, &st);
543 if (rc == -1)
544 return NIL_RTFILE;
[37679]545 return (RTFILE)(intptr_t)fd;
[36597]546}
547
548
[1]549RTR3DECL(int) RTFileDelete(const char *pszFilename)
550{
[28915]551 char const *pszNativeFilename;
552 int rc = rtPathToNative(&pszNativeFilename, pszFilename, NULL);
[1]553 if (RT_SUCCESS(rc))
554 {
555 if (unlink(pszNativeFilename) != 0)
556 rc = RTErrConvertFromErrno(errno);
[28877]557 rtPathFreeNative(pszNativeFilename, pszFilename);
[1]558 }
559 return rc;
560}
561
562
[37596]563RTR3DECL(int) RTFileSeek(RTFILE hFile, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
[1]564{
565 static const unsigned aSeekRecode[] =
566 {
567 SEEK_SET,
568 SEEK_CUR,
569 SEEK_END,
570 };
571
572 /*
573 * Validate input.
574 */
575 if (uMethod > RTFILE_SEEK_END)
576 {
577 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
578 return VERR_INVALID_PARAMETER;
579 }
580
581 /* check that within off_t range. */
582 if ( sizeof(off_t) < sizeof(offSeek)
583 && ( (offSeek > 0 && (unsigned)(offSeek >> 32) != 0)
584 || (offSeek < 0 && (unsigned)(-offSeek >> 32) != 0)))
585 {
586 AssertMsgFailed(("64-bit search not supported\n"));
587 return VERR_NOT_SUPPORTED;
588 }
589
[37596]590 off_t offCurrent = lseek(RTFileToNative(hFile), (off_t)offSeek, aSeekRecode[uMethod]);
[1]591 if (offCurrent != ~0)
592 {
593 if (poffActual)
594 *poffActual = (uint64_t)offCurrent;
595 return VINF_SUCCESS;
596 }
597 return RTErrConvertFromErrno(errno);
598}
599
600
[37596]601RTR3DECL(int) RTFileRead(RTFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
[1]602{
603 if (cbToRead <= 0)
[76902]604 {
605 if (pcbRead)
606 *pcbRead = 0;
[1]607 return VINF_SUCCESS;
[76902]608 }
[1]609
610 /*
611 * Attempt read.
612 */
[37596]613 ssize_t cbRead = read(RTFileToNative(hFile), pvBuf, cbToRead);
[1]614 if (cbRead >= 0)
615 {
616 if (pcbRead)
617 /* caller can handle partial read. */
618 *pcbRead = cbRead;
619 else
620 {
621 /* Caller expects all to be read. */
622 while ((ssize_t)cbToRead > cbRead)
623 {
[37596]624 ssize_t cbReadPart = read(RTFileToNative(hFile), (char*)pvBuf + cbRead, cbToRead - cbRead);
[1]625 if (cbReadPart <= 0)
626 {
627 if (cbReadPart == 0)
628 return VERR_EOF;
[4372]629 return RTErrConvertFromErrno(errno);
[1]630 }
631 cbRead += cbReadPart;
632 }
633 }
634 return VINF_SUCCESS;
635 }
636
637 return RTErrConvertFromErrno(errno);
638}
639
640
[37596]641RTR3DECL(int) RTFileWrite(RTFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
[1]642{
643 if (cbToWrite <= 0)
644 return VINF_SUCCESS;
645
646 /*
647 * Attempt write.
648 */
[37596]649 ssize_t cbWritten = write(RTFileToNative(hFile), pvBuf, cbToWrite);
[1]650 if (cbWritten >= 0)
651 {
652 if (pcbWritten)
653 /* caller can handle partial write. */
654 *pcbWritten = cbWritten;
655 else
656 {
657 /* Caller expects all to be write. */
658 while ((ssize_t)cbToWrite > cbWritten)
659 {
[37596]660 ssize_t cbWrittenPart = write(RTFileToNative(hFile), (const char *)pvBuf + cbWritten, cbToWrite - cbWritten);
[1]661 if (cbWrittenPart <= 0)
[77234]662 return cbWrittenPart < 0 ? RTErrConvertFromErrno(errno) : VERR_TRY_AGAIN;
[1]663 cbWritten += cbWrittenPart;
664 }
665 }
666 return VINF_SUCCESS;
667 }
668 return RTErrConvertFromErrno(errno);
669}
670
671
[37596]672RTR3DECL(int) RTFileSetSize(RTFILE hFile, uint64_t cbSize)
[1]673{
674 /*
675 * Validate offset.
676 */
677 if ( sizeof(off_t) < sizeof(cbSize)
678 && (cbSize >> 32) != 0)
679 {
680 AssertMsgFailed(("64-bit filesize not supported! cbSize=%lld\n", cbSize));
681 return VERR_NOT_SUPPORTED;
682 }
683
[3672]684#if defined(_MSC_VER) || (defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006))
[37596]685 if (chsize(RTFileToNative(hFile), (off_t)cbSize) == 0)
[1]686#else
687 /* This relies on a non-standard feature of FreeBSD, Linux, and OS/2
688 * LIBC v0.6 and higher. (SuS doesn't define ftruncate() and size bigger
689 * than the file.)
690 */
[37596]691 if (ftruncate(RTFileToNative(hFile), (off_t)cbSize) == 0)
[1]692#endif
693 return VINF_SUCCESS;
694 return RTErrConvertFromErrno(errno);
695}
696
697
[80585]698RTR3DECL(int) RTFileQuerySize(RTFILE hFile, uint64_t *pcbSize)
[1]699{
[39030]700 /*
701 * Ask fstat() first.
702 */
[1]703 struct stat st;
[37596]704 if (!fstat(RTFileToNative(hFile), &st))
[1]705 {
706 *pcbSize = st.st_size;
[39030]707 if ( st.st_size != 0
[85875]708#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
[39030]709 || (!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode))
[85875]710#elif defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD) || defined(RT_OS_DARWIN)
[39030]711 || !S_ISCHR(st.st_mode)
712#else
713 || !S_ISBLK(st.st_mode)
714#endif
715 )
716 return VINF_SUCCESS;
717
718 /*
719 * It could be a block device. Try determin the size by I/O control
720 * query or seek.
721 */
722#ifdef RT_OS_DARWIN
723 uint64_t cBlocks;
724 if (!ioctl(RTFileToNative(hFile), DKIOCGETBLOCKCOUNT, &cBlocks))
725 {
726 uint32_t cbBlock;
727 if (!ioctl(RTFileToNative(hFile), DKIOCGETBLOCKSIZE, &cbBlock))
728 {
729 *pcbSize = cBlocks * cbBlock;
730 return VINF_SUCCESS;
731 }
732 }
733
[85875]734 /* Always fail block devices. Character devices doesn't all need to be
[86302]735 /dev/rdisk* nodes, they should return ENOTTY but /dev/null returns ENODEV
736 and we include EINVAL just in case. */
737 if (!S_ISBLK(st.st_mode) && (errno == ENOTTY || errno == ENODEV || errno == EINVAL))
[85875]738 return VINF_SUCCESS;
739
[39030]740#elif defined(RT_OS_SOLARIS)
741 struct dk_minfo MediaInfo;
742 if (!ioctl(RTFileToNative(hFile), DKIOCGMEDIAINFO, &MediaInfo))
743 {
744 *pcbSize = MediaInfo.dki_capacity * MediaInfo.dki_lbsize;
745 return VINF_SUCCESS;
746 }
747 /* might not be a block device. */
748 if (errno == EINVAL || errno == ENOTTY)
749 return VINF_SUCCESS;
750
751#elif defined(RT_OS_FREEBSD)
752 off_t cbMedia = 0;
753 if (!ioctl(RTFileToNative(hFile), DIOCGMEDIASIZE, &cbMedia))
754 {
755 *pcbSize = cbMedia;
756 return VINF_SUCCESS;
757 }
758 /* might not be a block device. */
759 if (errno == EINVAL || errno == ENOTTY)
760 return VINF_SUCCESS;
761
762#else
763 /* PORTME! Avoid this path when possible. */
[84506]764 uint64_t offSaved = UINT64_MAX;
[39030]765 int rc = RTFileSeek(hFile, 0, RTFILE_SEEK_CURRENT, &offSaved);
766 if (RT_SUCCESS(rc))
767 {
768 rc = RTFileSeek(hFile, 0, RTFILE_SEEK_END, pcbSize);
769 int rc2 = RTFileSeek(hFile, offSaved, RTFILE_SEEK_BEGIN, NULL);
770 if (RT_SUCCESS(rc))
771 return rc2;
772 }
773#endif
[1]774 }
775 return RTErrConvertFromErrno(errno);
776}
777
778
[80585]779RTR3DECL(int) RTFileQueryMaxSizeEx(RTFILE hFile, PRTFOFF pcbMax)
[8913]780{
781 /*
782 * Save the current location
783 */
[84506]784 uint64_t offOld = UINT64_MAX;
[37596]785 int rc = RTFileSeek(hFile, 0, RTFILE_SEEK_CURRENT, &offOld);
[8913]786 if (RT_FAILURE(rc))
787 return rc;
788
789 uint64_t offLow = 0;
[85492]790 uint64_t offHigh = INT64_MAX; /* we don't need bigger files */
[8913]791 /** @todo Unfortunately this does not work for certain file system types,
792 * for instance cifs mounts. Even worse, statvfs.f_fsid returns 0 for such
793 * file systems. */
[85492]794
795 /*
796 * Quickly guess the order of magnitude for offHigh and offLow.
797 */
[8913]798 {
[85492]799 uint64_t offHighPrev = offHigh;
800 while (offHigh >= INT32_MAX)
[8913]801 {
[85492]802 rc = RTFileSeek(hFile, offHigh, RTFILE_SEEK_BEGIN, NULL);
803 if (RT_SUCCESS(rc))
804 {
805 offLow = offHigh;
806 offHigh = offHighPrev;
807 break;
808 }
809 else
810 {
811 offHighPrev = offHigh;
812 offHigh >>= 8;
813 }
[8913]814 }
[85492]815 }
[8913]816
[85492]817 /*
818 * Sanity: if the seek to the initial offHigh (INT64_MAX) works, then
819 * this algorithm cannot possibly work. Declare defeat.
820 */
821 if (offLow == offHigh)
[85495]822 {
823 rc = RTFileSeek(hFile, offOld, RTFILE_SEEK_BEGIN, NULL);
824 if (RT_SUCCESS(rc))
825 rc = VERR_NOT_IMPLEMENTED;
[85492]826
[85495]827 return rc;
828 }
829
[85492]830 /*
831 * Perform a binary search for the max file size.
832 */
833 while (offLow <= offHigh)
834 {
835 uint64_t offMid = offLow + (offHigh - offLow) / 2;
836 rc = RTFileSeek(hFile, offMid, RTFILE_SEEK_BEGIN, NULL);
[8913]837 if (RT_FAILURE(rc))
[85492]838 offHigh = offMid - 1;
[8913]839 else
[85492]840 offLow = offMid + 1;
[8913]841 }
[85492]842
843 if (pcbMax)
844 *pcbMax = RT_MIN(offLow, offHigh);
845 return RTFileSeek(hFile, offOld, RTFILE_SEEK_BEGIN, NULL);
[8913]846}
847
848
[37596]849RTR3DECL(bool) RTFileIsValid(RTFILE hFile)
[1]850{
[37596]851 if (hFile != NIL_RTFILE)
[1]852 {
[37596]853 int fFlags = fcntl(RTFileToNative(hFile), F_GETFD);
[1]854 if (fFlags >= 0)
855 return true;
856 }
857 return false;
858}
859
860
[94277]861RTR3DECL(int) RTFileFlush(RTFILE hFile)
[1]862{
[94277]863 if (!fsync(RTFileToNative(hFile)))
864 return VINF_SUCCESS;
865 /* Ignore EINVAL here as that's what returned for pseudo ttys
866 and other odd handles. */
867 if (errno == EINVAL)
868 return VINF_NOT_SUPPORTED;
869 return RTErrConvertFromErrno(errno);
[1]870}
871
872
[37596]873RTR3DECL(int) RTFileIoCtl(RTFILE hFile, unsigned long ulRequest, void *pvData, unsigned cbData, int *piRet)
[1]874{
[39083]875 NOREF(cbData);
[37596]876 int rc = ioctl(RTFileToNative(hFile), ulRequest, pvData);
[1]877 if (piRet)
878 *piRet = rc;
879 return rc >= 0 ? VINF_SUCCESS : RTErrConvertFromErrno(errno);
880}
881
882
[37596]883RTR3DECL(int) RTFileSetMode(RTFILE hFile, RTFMODE fMode)
[1]884{
885 /*
886 * Normalize the mode and call the API.
887 */
[79155]888 fMode = rtFsModeNormalize(fMode, NULL, 0, RTFS_TYPE_FILE);
[1]889 if (!rtFsModeIsValid(fMode))
890 return VERR_INVALID_PARAMETER;
891
[37596]892 if (fchmod(RTFileToNative(hFile), fMode & RTFS_UNIX_MASK))
[1]893 {
894 int rc = RTErrConvertFromErrno(errno);
[37596]895 Log(("RTFileSetMode(%RTfile,%RTfmode): returns %Rrc\n", hFile, fMode, rc));
[1]896 return rc;
897 }
898 return VINF_SUCCESS;
899}
900
901
[44298]902RTDECL(int) RTFileSetOwner(RTFILE hFile, uint32_t uid, uint32_t gid)
903{
904 uid_t uidNative = uid != NIL_RTUID ? (uid_t)uid : (uid_t)-1;
905 AssertReturn(uid == uidNative, VERR_INVALID_PARAMETER);
906 gid_t gidNative = gid != NIL_RTGID ? (gid_t)gid : (gid_t)-1;
907 AssertReturn(gid == gidNative, VERR_INVALID_PARAMETER);
908
909 if (fchown(RTFileToNative(hFile), uidNative, gidNative))
910 return RTErrConvertFromErrno(errno);
911 return VINF_SUCCESS;
912}
913
914
[1]915RTR3DECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
916{
917 /*
918 * Validate input.
919 */
[90781]920 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
921 AssertPtrReturn(pszDst, VERR_INVALID_POINTER);
[1]922 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
923 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
924 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
925
926 /*
927 * Take common cause with RTPathRename.
928 */
929 int rc = rtPathPosixRename(pszSrc, pszDst, fRename, RTFS_TYPE_FILE);
930
931 LogFlow(("RTDirRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
932 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
933 return rc;
934}
935
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use