VirtualBox

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

Last change on this file since 103914 was 100561, checked in by vboxsync, 17 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
Line 
1/* $Id: fileio-posix.cpp 100561 2023-07-13 09:58:36Z 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 /*
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
367 rtPathFreeNative(pszNativeFilename, pszFilename);
368 if (fh >= 0)
369 {
370 iErr = 0;
371
372 /*
373 * Mark the file handle close on exec, unless inherit is specified.
374 */
375 if ( !(fOpen & RTFILE_O_INHERIT)
376#ifdef O_NOINHERIT
377 && !(fOpenMode & O_NOINHERIT) /* Take care since it might be a zero value dummy. */
378#endif
379#ifdef O_CLOEXEC
380 && fHave_O_CLOEXEC <= 0
381#endif
382 )
383 iErr = fcntl(fh, F_SETFD, FD_CLOEXEC) >= 0 ? 0 : errno;
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))
391 {
392# if defined(RT_OS_DARWIN)
393 iErr = fcntl(fh, F_NOCACHE, 1) >= 0 ? 0 : errno;
394# else
395 iErr = directio(fh, DIRECTIO_ON) >= 0 ? 0 : errno;
396# endif
397 }
398#endif
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)
414 {
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;
433 }
434 iErr = flock(fh, iLockOp | LOCK_NB);
435 if (iErr != 0)
436 iErr = errno == EAGAIN ? ETXTBSY : 0;
437 }
438#endif /* 0 && RT_OS_LINUX */
439#if defined(DEBUG_bird) && !defined(RT_OS_SOLARIS)
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 {
475 *phFile = (RTFILE)(uintptr_t)fh;
476 Assert((intptr_t)*phFile == fh);
477 LogFlow(("RTFileOpen(%p:{%RTfile}, %p:{%s}, %#llx): returns %Rrc\n",
478 phFile, *phFile, pszFilename, pszFilename, fOpen, rc));
479 return VINF_SUCCESS;
480 }
481
482 close(fh);
483 }
484 return RTErrConvertFromErrno(iErr);
485}
486
487
488RTR3DECL(int) RTFileOpenBitBucket(PRTFILE phFile, uint64_t fAccess)
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
498RTR3DECL(int) RTFileClose(RTFILE hFile)
499{
500 if (hFile == NIL_RTFILE)
501 return VINF_SUCCESS;
502 if (close(RTFileToNative(hFile)) == 0)
503 return VINF_SUCCESS;
504 return RTErrConvertFromErrno(errno);
505}
506
507
508RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
509{
510 AssertCompile(sizeof(uNative) == sizeof(*pFile));
511 if (uNative < 0)
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
522RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE hFile)
523{
524 AssertReturn(hFile != NIL_RTFILE, -1);
525 return (intptr_t)hFile;
526}
527
528
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;
545 return (RTFILE)(intptr_t)fd;
546}
547
548
549RTR3DECL(int) RTFileDelete(const char *pszFilename)
550{
551 char const *pszNativeFilename;
552 int rc = rtPathToNative(&pszNativeFilename, pszFilename, NULL);
553 if (RT_SUCCESS(rc))
554 {
555 if (unlink(pszNativeFilename) != 0)
556 rc = RTErrConvertFromErrno(errno);
557 rtPathFreeNative(pszNativeFilename, pszFilename);
558 }
559 return rc;
560}
561
562
563RTR3DECL(int) RTFileSeek(RTFILE hFile, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
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
590 off_t offCurrent = lseek(RTFileToNative(hFile), (off_t)offSeek, aSeekRecode[uMethod]);
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
601RTR3DECL(int) RTFileRead(RTFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
602{
603 if (cbToRead <= 0)
604 {
605 if (pcbRead)
606 *pcbRead = 0;
607 return VINF_SUCCESS;
608 }
609
610 /*
611 * Attempt read.
612 */
613 ssize_t cbRead = read(RTFileToNative(hFile), pvBuf, cbToRead);
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 {
624 ssize_t cbReadPart = read(RTFileToNative(hFile), (char*)pvBuf + cbRead, cbToRead - cbRead);
625 if (cbReadPart <= 0)
626 {
627 if (cbReadPart == 0)
628 return VERR_EOF;
629 return RTErrConvertFromErrno(errno);
630 }
631 cbRead += cbReadPart;
632 }
633 }
634 return VINF_SUCCESS;
635 }
636
637 return RTErrConvertFromErrno(errno);
638}
639
640
641RTR3DECL(int) RTFileWrite(RTFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
642{
643 if (cbToWrite <= 0)
644 return VINF_SUCCESS;
645
646 /*
647 * Attempt write.
648 */
649 ssize_t cbWritten = write(RTFileToNative(hFile), pvBuf, cbToWrite);
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 {
660 ssize_t cbWrittenPart = write(RTFileToNative(hFile), (const char *)pvBuf + cbWritten, cbToWrite - cbWritten);
661 if (cbWrittenPart <= 0)
662 return cbWrittenPart < 0 ? RTErrConvertFromErrno(errno) : VERR_TRY_AGAIN;
663 cbWritten += cbWrittenPart;
664 }
665 }
666 return VINF_SUCCESS;
667 }
668 return RTErrConvertFromErrno(errno);
669}
670
671
672RTR3DECL(int) RTFileSetSize(RTFILE hFile, uint64_t cbSize)
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
684#if defined(_MSC_VER) || (defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006))
685 if (chsize(RTFileToNative(hFile), (off_t)cbSize) == 0)
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 */
691 if (ftruncate(RTFileToNative(hFile), (off_t)cbSize) == 0)
692#endif
693 return VINF_SUCCESS;
694 return RTErrConvertFromErrno(errno);
695}
696
697
698RTR3DECL(int) RTFileQuerySize(RTFILE hFile, uint64_t *pcbSize)
699{
700 /*
701 * Ask fstat() first.
702 */
703 struct stat st;
704 if (!fstat(RTFileToNative(hFile), &st))
705 {
706 *pcbSize = st.st_size;
707 if ( st.st_size != 0
708#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
709 || (!S_ISBLK(st.st_mode) && !S_ISCHR(st.st_mode))
710#elif defined(RT_OS_FREEBSD) || defined(RT_OS_NETBSD) || defined(RT_OS_DARWIN)
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
734 /* Always fail block devices. Character devices doesn't all need to be
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))
738 return VINF_SUCCESS;
739
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. */
764 uint64_t offSaved = UINT64_MAX;
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
774 }
775 return RTErrConvertFromErrno(errno);
776}
777
778
779RTR3DECL(int) RTFileQueryMaxSizeEx(RTFILE hFile, PRTFOFF pcbMax)
780{
781 /*
782 * Save the current location
783 */
784 uint64_t offOld = UINT64_MAX;
785 int rc = RTFileSeek(hFile, 0, RTFILE_SEEK_CURRENT, &offOld);
786 if (RT_FAILURE(rc))
787 return rc;
788
789 uint64_t offLow = 0;
790 uint64_t offHigh = INT64_MAX; /* we don't need bigger files */
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. */
794
795 /*
796 * Quickly guess the order of magnitude for offHigh and offLow.
797 */
798 {
799 uint64_t offHighPrev = offHigh;
800 while (offHigh >= INT32_MAX)
801 {
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 }
814 }
815 }
816
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)
822 {
823 rc = RTFileSeek(hFile, offOld, RTFILE_SEEK_BEGIN, NULL);
824 if (RT_SUCCESS(rc))
825 rc = VERR_NOT_IMPLEMENTED;
826
827 return rc;
828 }
829
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);
837 if (RT_FAILURE(rc))
838 offHigh = offMid - 1;
839 else
840 offLow = offMid + 1;
841 }
842
843 if (pcbMax)
844 *pcbMax = RT_MIN(offLow, offHigh);
845 return RTFileSeek(hFile, offOld, RTFILE_SEEK_BEGIN, NULL);
846}
847
848
849RTR3DECL(bool) RTFileIsValid(RTFILE hFile)
850{
851 if (hFile != NIL_RTFILE)
852 {
853 int fFlags = fcntl(RTFileToNative(hFile), F_GETFD);
854 if (fFlags >= 0)
855 return true;
856 }
857 return false;
858}
859
860
861RTR3DECL(int) RTFileFlush(RTFILE hFile)
862{
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);
870}
871
872
873RTR3DECL(int) RTFileIoCtl(RTFILE hFile, unsigned long ulRequest, void *pvData, unsigned cbData, int *piRet)
874{
875 NOREF(cbData);
876 int rc = ioctl(RTFileToNative(hFile), ulRequest, pvData);
877 if (piRet)
878 *piRet = rc;
879 return rc >= 0 ? VINF_SUCCESS : RTErrConvertFromErrno(errno);
880}
881
882
883RTR3DECL(int) RTFileSetMode(RTFILE hFile, RTFMODE fMode)
884{
885 /*
886 * Normalize the mode and call the API.
887 */
888 fMode = rtFsModeNormalize(fMode, NULL, 0, RTFS_TYPE_FILE);
889 if (!rtFsModeIsValid(fMode))
890 return VERR_INVALID_PARAMETER;
891
892 if (fchmod(RTFileToNative(hFile), fMode & RTFS_UNIX_MASK))
893 {
894 int rc = RTErrConvertFromErrno(errno);
895 Log(("RTFileSetMode(%RTfile,%RTfmode): returns %Rrc\n", hFile, fMode, rc));
896 return rc;
897 }
898 return VINF_SUCCESS;
899}
900
901
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
915RTR3DECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
916{
917 /*
918 * Validate input.
919 */
920 AssertPtrReturn(pszSrc, VERR_INVALID_POINTER);
921 AssertPtrReturn(pszDst, VERR_INVALID_POINTER);
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.

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