VirtualBox

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

Last change on this file since 22509 was 21616, checked in by vboxsync, 15 years ago

nitpicking.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.2 KB
Line 
1/* $Id: fileio-posix.cpp 21616 2009-07-15 15:27:07Z vboxsync $ */
2/** @file
3 * IPRT - File I/O, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#define LOG_GROUP RTLOGGROUP_FILE
36
37#include <errno.h>
38#include <sys/stat.h>
39#include <sys/types.h>
40#include <sys/ioctl.h>
41#include <sys/fcntl.h>
42#include <fcntl.h>
43#ifdef _MSC_VER
44# include <io.h>
45# include <stdio.h>
46#else
47# include <unistd.h>
48# include <sys/time.h>
49#endif
50#if defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006)
51# include <io.h>
52#endif
53#ifdef RT_OS_L4
54/* This is currently ifdef'ed out in the relevant L4 header file */
55/* Same as `utimes', but takes an open file descriptor instead of a name. */
56extern int futimes(int __fd, __const struct timeval __tvp[2]) __THROW;
57#endif
58
59#ifdef RT_OS_SOLARIS
60# define futimes(filedes, timeval) futimesat(filedes, NULL, timeval)
61#endif
62
63#include <iprt/file.h>
64#include <iprt/path.h>
65#include <iprt/assert.h>
66#include <iprt/string.h>
67#include <iprt/err.h>
68#include <iprt/log.h>
69#include "internal/file.h"
70#include "internal/fs.h"
71#include "internal/path.h"
72
73
74
75/*******************************************************************************
76* Defined Constants And Macros *
77*******************************************************************************/
78/** @def RT_DONT_CONVERT_FILENAMES
79 * Define this to pass UTF-8 unconverted to the kernel. */
80#ifdef __DOXYGEN__
81#define RT_DONT_CONVERT_FILENAMES 1
82#endif
83
84/** Default file permissions for newly created files. */
85#if defined(S_IRUSR) && defined(S_IWUSR)
86# define RT_FILE_PERMISSION (S_IRUSR | S_IWUSR)
87#else
88# define RT_FILE_PERMISSION (00600)
89#endif
90
91
92RTR3DECL(int) RTFileOpen(PRTFILE pFile, const char *pszFilename, unsigned fOpen)
93{
94 /*
95 * Validate input.
96 */
97 if (!VALID_PTR(pFile))
98 {
99 AssertMsgFailed(("Invalid pFile %p\n", pFile));
100 return VERR_INVALID_PARAMETER;
101 }
102 *pFile = NIL_RTFILE;
103 if (!VALID_PTR(pszFilename))
104 {
105 AssertMsgFailed(("Invalid pszFilename %p\n", pszFilename));
106 return VERR_INVALID_PARAMETER;
107 }
108
109 /*
110 * Merge forced open flags and validate them.
111 */
112 int rc = rtFileRecalcAndValidateFlags(&fOpen);
113 if (RT_FAILURE(rc))
114 return rc;
115#ifndef O_NONBLOCK
116 if (fOpen & RTFILE_O_NON_BLOCK)
117 {
118 AssertMsgFailed(("Invalid parameters! fOpen=%#x\n", fOpen));
119 return VERR_INVALID_PARAMETER;
120 }
121#endif
122
123 /*
124 * Calculate open mode flags.
125 */
126 int fOpenMode = 0;
127#ifdef O_BINARY
128 fOpenMode |= O_BINARY; /* (pc) */
129#endif
130#ifdef O_LARGEFILE
131 fOpenMode |= O_LARGEFILE; /* (linux) */
132#endif
133#ifdef O_NOINHERIT
134 if (!(fOpen & RTFILE_O_INHERIT))
135 fOpenMode |= O_NOINHERIT;
136#endif
137#ifdef O_NONBLOCK
138 if (fOpen & RTFILE_O_NON_BLOCK)
139 fOpenMode |= O_NONBLOCK;
140#endif
141#ifdef O_SYNC
142 if (fOpen & RTFILE_O_WRITE_THROUGH)
143 fOpenMode |= O_SYNC;
144#endif
145#if defined(O_DIRECT) && defined(RT_OS_LINUX)
146 /* O_DIRECT is mandatory to get async I/O working on Linux. */
147 if (fOpen & RTFILE_O_ASYNC_IO)
148 fOpenMode |= O_DIRECT;
149#endif
150#if defined(O_DIRECT) && (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD))
151 /* Disable the kernel cache. */
152 if (fOpen & RTFILE_O_NO_CACHE)
153 fOpenMode |= O_DIRECT;
154#endif
155
156 /* create/truncate file */
157 switch (fOpen & RTFILE_O_ACTION_MASK)
158 {
159 case RTFILE_O_OPEN: break;
160 case RTFILE_O_OPEN_CREATE: fOpenMode |= O_CREAT; break;
161 case RTFILE_O_CREATE: fOpenMode |= O_CREAT | O_EXCL; break;
162 case RTFILE_O_CREATE_REPLACE: fOpenMode |= O_CREAT | O_TRUNC; break; /** @todo replacing needs fixing, this is *not* a 1:1 mapping! */
163 }
164 if (fOpen & RTFILE_O_TRUNCATE)
165 fOpenMode |= O_TRUNC;
166
167 switch (fOpen & RTFILE_O_ACCESS_MASK)
168 {
169 case RTFILE_O_READ:
170 fOpenMode |= O_RDONLY; /* RTFILE_O_APPEND is ignored. */
171 break;
172 case RTFILE_O_WRITE:
173 fOpenMode |= fOpen & RTFILE_O_APPEND ? O_APPEND | O_WRONLY : O_WRONLY;
174 break;
175 case RTFILE_O_READWRITE:
176 fOpenMode |= fOpen & RTFILE_O_APPEND ? O_APPEND | O_RDWR : O_RDWR;
177 break;
178 default:
179 AssertMsgFailed(("RTFileOpen received an invalid RW value, fOpen=%#x\n", fOpen));
180 return VERR_INVALID_PARAMETER;
181 }
182
183 /* File mode. */
184 int fMode = (fOpen & RTFILE_O_CREATE_MODE_MASK)
185 ? (fOpen & RTFILE_O_CREATE_MODE_MASK) >> RTFILE_O_CREATE_MODE_SHIFT
186 : RT_FILE_PERMISSION;
187
188 /** @todo sharing! */
189
190 /*
191 * Open/create the file.
192 */
193#ifdef RT_DONT_CONVERT_FILENAMES
194 int fh = open(pszFilename, fOpenMode, fMode);
195 int iErr = errno;
196#else
197 char *pszNativeFilename;
198 rc = rtPathToNative(&pszNativeFilename, pszFilename);
199 if (RT_FAILURE(rc))
200 return (rc);
201
202 int fh = open(pszNativeFilename, fOpenMode, fMode);
203 int iErr = errno;
204 rtPathFreeNative(pszNativeFilename);
205#endif
206 if (fh >= 0)
207 {
208 /*
209 * Mark the file handle close on exec, unless inherit is specified.
210 */
211 if ( !(fOpen & RTFILE_O_INHERIT)
212#ifdef O_NOINHERIT
213 || (fOpenMode & O_NOINHERIT) /* careful since it could be a dummy. */
214#endif
215 || fcntl(fh, F_SETFD, FD_CLOEXEC) >= 0)
216 {
217#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
218 iErr = 0;
219 /* Switch direct I/O on now if requested */
220# if defined(RT_OS_SOLARIS) && !defined(IN_GUEST)
221 if (fOpen & RTFILE_O_NO_CACHE)
222 iErr = directio(fh, DIRECTIO_ON);
223# elif defined(RT_OS_DARWIN)
224 if (fOpen & RTFILE_O_NO_CACHE)
225 iErr = fcntl(fh, F_NOCACHE);
226# endif
227 if (iErr < 0)
228 iErr = errno;
229 else
230#endif
231 {
232 *pFile = (RTFILE)fh;
233 Assert((int)*pFile == fh);
234 LogFlow(("RTFileOpen(%p:{%RTfile}, %p:{%s}, %#x): returns %Rrc\n",
235 pFile, *pFile, pszFilename, pszFilename, fOpen, rc));
236 return VINF_SUCCESS;
237 }
238 }
239 iErr = errno;
240 close(fh);
241 }
242 return RTErrConvertFromErrno(iErr);
243}
244
245
246RTR3DECL(int) RTFileClose(RTFILE File)
247{
248 if (close((int)File) == 0)
249 return VINF_SUCCESS;
250 return RTErrConvertFromErrno(errno);
251}
252
253
254RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
255{
256 if ( uNative < 0
257 || (RTFILE)uNative != (RTUINTPTR)uNative)
258 {
259 AssertMsgFailed(("%p\n", uNative));
260 *pFile = NIL_RTFILE;
261 return VERR_INVALID_HANDLE;
262 }
263 *pFile = (RTFILE)uNative;
264 return VINF_SUCCESS;
265}
266
267
268RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE File)
269{
270 AssertReturn(File != NIL_RTFILE, -1);
271 return (RTHCINTPTR)File;
272}
273
274
275RTR3DECL(int) RTFileDelete(const char *pszFilename)
276{
277 char *pszNativeFilename;
278 int rc = rtPathToNative(&pszNativeFilename, pszFilename);
279 if (RT_SUCCESS(rc))
280 {
281 if (unlink(pszNativeFilename) != 0)
282 rc = RTErrConvertFromErrno(errno);
283 rtPathFreeNative(pszNativeFilename);
284 }
285 return rc;
286}
287
288
289RTR3DECL(int) RTFileSeek(RTFILE File, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
290{
291 static const unsigned aSeekRecode[] =
292 {
293 SEEK_SET,
294 SEEK_CUR,
295 SEEK_END,
296 };
297
298 /*
299 * Validate input.
300 */
301 if (uMethod > RTFILE_SEEK_END)
302 {
303 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
304 return VERR_INVALID_PARAMETER;
305 }
306
307 /* check that within off_t range. */
308 if ( sizeof(off_t) < sizeof(offSeek)
309 && ( (offSeek > 0 && (unsigned)(offSeek >> 32) != 0)
310 || (offSeek < 0 && (unsigned)(-offSeek >> 32) != 0)))
311 {
312 AssertMsgFailed(("64-bit search not supported\n"));
313 return VERR_NOT_SUPPORTED;
314 }
315
316 off_t offCurrent = lseek((int)File, (off_t)offSeek, aSeekRecode[uMethod]);
317 if (offCurrent != ~0)
318 {
319 if (poffActual)
320 *poffActual = (uint64_t)offCurrent;
321 return VINF_SUCCESS;
322 }
323 return RTErrConvertFromErrno(errno);
324}
325
326
327RTR3DECL(int) RTFileRead(RTFILE File, void *pvBuf, size_t cbToRead, size_t *pcbRead)
328{
329 if (cbToRead <= 0)
330 return VINF_SUCCESS;
331
332 /*
333 * Attempt read.
334 */
335 ssize_t cbRead = read((int)File, pvBuf, cbToRead);
336 if (cbRead >= 0)
337 {
338 if (pcbRead)
339 /* caller can handle partial read. */
340 *pcbRead = cbRead;
341 else
342 {
343 /* Caller expects all to be read. */
344 while ((ssize_t)cbToRead > cbRead)
345 {
346 ssize_t cbReadPart = read((int)File, (char*)pvBuf + cbRead, cbToRead - cbRead);
347 if (cbReadPart <= 0)
348 {
349 if (cbReadPart == 0)
350 return VERR_EOF;
351 return RTErrConvertFromErrno(errno);
352 }
353 cbRead += cbReadPart;
354 }
355 }
356 return VINF_SUCCESS;
357 }
358
359 return RTErrConvertFromErrno(errno);
360}
361
362
363RTR3DECL(int) RTFileWrite(RTFILE File, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
364{
365 if (cbToWrite <= 0)
366 return VINF_SUCCESS;
367
368 /*
369 * Attempt write.
370 */
371 ssize_t cbWritten = write((int)File, pvBuf, cbToWrite);
372 if (cbWritten >= 0)
373 {
374 if (pcbWritten)
375 /* caller can handle partial write. */
376 *pcbWritten = cbWritten;
377 else
378 {
379 /* Caller expects all to be write. */
380 while ((ssize_t)cbToWrite > cbWritten)
381 {
382 ssize_t cbWrittenPart = write((int)File, (const char *)pvBuf + cbWritten, cbToWrite - cbWritten);
383 if (cbWrittenPart <= 0)
384 return RTErrConvertFromErrno(errno);
385 cbWritten += cbWrittenPart;
386 }
387 }
388 return VINF_SUCCESS;
389 }
390 return RTErrConvertFromErrno(errno);
391}
392
393
394RTR3DECL(int) RTFileSetSize(RTFILE File, uint64_t cbSize)
395{
396 /*
397 * Validate offset.
398 */
399 if ( sizeof(off_t) < sizeof(cbSize)
400 && (cbSize >> 32) != 0)
401 {
402 AssertMsgFailed(("64-bit filesize not supported! cbSize=%lld\n", cbSize));
403 return VERR_NOT_SUPPORTED;
404 }
405
406#if defined(_MSC_VER) || (defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006))
407 if (chsize((int)File, (off_t)cbSize) == 0)
408#else
409 /* This relies on a non-standard feature of FreeBSD, Linux, and OS/2
410 * LIBC v0.6 and higher. (SuS doesn't define ftruncate() and size bigger
411 * than the file.)
412 */
413 if (ftruncate((int)File, (off_t)cbSize) == 0)
414#endif
415 return VINF_SUCCESS;
416 return RTErrConvertFromErrno(errno);
417}
418
419
420RTR3DECL(int) RTFileGetSize(RTFILE File, uint64_t *pcbSize)
421{
422 struct stat st;
423 if (!fstat((int)File, &st))
424 {
425 *pcbSize = st.st_size;
426 return VINF_SUCCESS;
427 }
428 return RTErrConvertFromErrno(errno);
429}
430
431
432/**
433 * Determine the maximum file size.
434 *
435 * @returns IPRT status code.
436 * @param File Handle to the file.
437 * @param pcbMax Where to store the max file size.
438 * @see RTFileGetMaxSize.
439 */
440RTR3DECL(int) RTFileGetMaxSizeEx(RTFILE File, PRTFOFF pcbMax)
441{
442 /*
443 * Save the current location
444 */
445 uint64_t offOld;
446 int rc = RTFileSeek(File, 0, RTFILE_SEEK_CURRENT, &offOld);
447 if (RT_FAILURE(rc))
448 return rc;
449
450 /*
451 * Perform a binary search for the max file size.
452 */
453 uint64_t offLow = 0;
454 uint64_t offHigh = 8 * _1T; /* we don't need bigger files */
455 /** @todo Unfortunately this does not work for certain file system types,
456 * for instance cifs mounts. Even worse, statvfs.f_fsid returns 0 for such
457 * file systems. */
458 //uint64_t offHigh = INT64_MAX;
459 for (;;)
460 {
461 uint64_t cbInterval = (offHigh - offLow) >> 1;
462 if (cbInterval == 0)
463 {
464 if (pcbMax)
465 *pcbMax = offLow;
466 return RTFileSeek(File, offOld, RTFILE_SEEK_BEGIN, NULL);
467 }
468
469 rc = RTFileSeek(File, offLow + cbInterval, RTFILE_SEEK_BEGIN, NULL);
470 if (RT_FAILURE(rc))
471 offHigh = offLow + cbInterval;
472 else
473 offLow = offLow + cbInterval;
474 }
475}
476
477
478RTR3DECL(bool) RTFileIsValid(RTFILE File)
479{
480 if (File != NIL_RTFILE)
481 {
482 int fFlags = fcntl(File, F_GETFD);
483 if (fFlags >= 0)
484 return true;
485 }
486 return false;
487}
488
489
490RTR3DECL(int) RTFileFlush(RTFILE File)
491{
492 if (fsync((int)File))
493 return RTErrConvertFromErrno(errno);
494 return VINF_SUCCESS;
495}
496
497
498RTR3DECL(int) RTFileIoCtl(RTFILE File, int iRequest, void *pvData, unsigned cbData, int *piRet)
499{
500 int rc = ioctl((int)File, iRequest, pvData);
501 if (piRet)
502 *piRet = rc;
503 return rc >= 0 ? VINF_SUCCESS : RTErrConvertFromErrno(errno);
504}
505
506
507RTR3DECL(int) RTFileQueryInfo(RTFILE File, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
508{
509 /*
510 * Validate input.
511 */
512 if (File == NIL_RTFILE)
513 {
514 AssertMsgFailed(("Invalid File=%RTfile\n", File));
515 return VERR_INVALID_PARAMETER;
516 }
517 if (!pObjInfo)
518 {
519 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
520 return VERR_INVALID_PARAMETER;
521 }
522 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
523 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
524 {
525 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
526 return VERR_INVALID_PARAMETER;
527 }
528
529 /*
530 * Query file info.
531 */
532 struct stat Stat;
533 if (fstat((int)File, &Stat))
534 {
535 int rc = RTErrConvertFromErrno(errno);
536 Log(("RTFileQueryInfo(%RTfile,,%d): returns %Rrc\n", File, enmAdditionalAttribs, rc));
537 return rc;
538 }
539
540 /*
541 * Setup the returned data.
542 */
543 rtFsConvertStatToObjInfo(pObjInfo, &Stat, NULL, 0);
544
545 /*
546 * Requested attributes (we cannot provide anything actually).
547 */
548 switch (enmAdditionalAttribs)
549 {
550 case RTFSOBJATTRADD_EASIZE:
551 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
552 pObjInfo->Attr.u.EASize.cb = 0;
553 break;
554
555 case RTFSOBJATTRADD_NOTHING:
556 case RTFSOBJATTRADD_UNIX:
557 /* done */
558 break;
559
560 default:
561 AssertMsgFailed(("Impossible!\n"));
562 return VERR_INTERNAL_ERROR;
563 }
564
565 LogFlow(("RTFileQueryInfo(%RTfile,,%d): returns VINF_SUCCESS\n", File, enmAdditionalAttribs));
566 return VINF_SUCCESS;
567}
568
569
570RTR3DECL(int) RTFileSetTimes(RTFILE File, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
571 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
572{
573 /*
574 * We can only set AccessTime and ModificationTime, so if neither
575 * are specified we can return immediately.
576 */
577 if (!pAccessTime && !pModificationTime)
578 return VINF_SUCCESS;
579
580 /*
581 * Convert the input to timeval, getting the missing one if necessary,
582 * and call the API which does the change.
583 */
584 struct timeval aTimevals[2];
585 if (pAccessTime && pModificationTime)
586 {
587 RTTimeSpecGetTimeval(pAccessTime, &aTimevals[0]);
588 RTTimeSpecGetTimeval(pModificationTime, &aTimevals[1]);
589 }
590 else
591 {
592 RTFSOBJINFO ObjInfo;
593 int rc = RTFileQueryInfo(File, &ObjInfo, RTFSOBJATTRADD_UNIX);
594 if (RT_FAILURE(rc))
595 return rc;
596 RTTimeSpecGetTimeval(pAccessTime ? pAccessTime : &ObjInfo.AccessTime, &aTimevals[0]);
597 RTTimeSpecGetTimeval(pModificationTime ? pModificationTime : &ObjInfo.ModificationTime, &aTimevals[1]);
598 }
599
600 if (futimes((int)File, aTimevals))
601 {
602 int rc = RTErrConvertFromErrno(errno);
603 Log(("RTFileSetTimes(%RTfile,%p,%p,,): returns %Rrc\n", File, pAccessTime, pModificationTime, rc));
604 return rc;
605 }
606 return VINF_SUCCESS;
607}
608
609
610RTR3DECL(int) RTFileSetMode(RTFILE File, RTFMODE fMode)
611{
612 /*
613 * Normalize the mode and call the API.
614 */
615 fMode = rtFsModeNormalize(fMode, NULL, 0);
616 if (!rtFsModeIsValid(fMode))
617 return VERR_INVALID_PARAMETER;
618
619 if (fchmod((int)File, fMode & RTFS_UNIX_MASK))
620 {
621 int rc = RTErrConvertFromErrno(errno);
622 Log(("RTFileSetMode(%RTfile,%RTfmode): returns %Rrc\n", File, fMode, rc));
623 return rc;
624 }
625 return VINF_SUCCESS;
626}
627
628
629RTR3DECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
630{
631 /*
632 * Validate input.
633 */
634 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
635 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
636 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
637 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
638 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
639
640 /*
641 * Take common cause with RTPathRename.
642 */
643 int rc = rtPathPosixRename(pszSrc, pszDst, fRename, RTFS_TYPE_FILE);
644
645 LogFlow(("RTDirRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
646 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
647 return rc;
648}
649
650
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