VirtualBox

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

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

Fix add burn with Solaris additions

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 18.0 KB
Line 
1/* $Id: fileio-posix.cpp 21500 2009-07-10 20:40:13Z 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: fOpenMode |= O_RDONLY; break;
170 case RTFILE_O_WRITE: fOpenMode |= O_WRONLY; break;
171 case RTFILE_O_READWRITE: fOpenMode |= O_RDWR; break;
172 default:
173 AssertMsgFailed(("RTFileOpen received an invalid RW value, fOpen=%#x\n", fOpen));
174 return VERR_INVALID_PARAMETER;
175 }
176
177 /* File mode. */
178 int fMode = (fOpen & RTFILE_O_CREATE_MODE_MASK)
179 ? (fOpen & RTFILE_O_CREATE_MODE_MASK) >> RTFILE_O_CREATE_MODE_SHIFT
180 : RT_FILE_PERMISSION;
181
182 /** @todo sharing! */
183
184 /*
185 * Open/create the file.
186 */
187#ifdef RT_DONT_CONVERT_FILENAMES
188 int fh = open(pszFilename, fOpenMode, fMode);
189 int iErr = errno;
190#else
191 char *pszNativeFilename;
192 rc = rtPathToNative(&pszNativeFilename, pszFilename);
193 if (RT_FAILURE(rc))
194 return (rc);
195
196 int fh = open(pszNativeFilename, fOpenMode, fMode);
197 int iErr = errno;
198 rtPathFreeNative(pszNativeFilename);
199#endif
200 if (fh >= 0)
201 {
202 /*
203 * Mark the file handle close on exec, unless inherit is specified.
204 */
205 if ( !(fOpen & RTFILE_O_INHERIT)
206#ifdef O_NOINHERIT
207 || (fOpenMode & O_NOINHERIT) /* careful since it could be a dummy. */
208#endif
209 || fcntl(fh, F_SETFD, FD_CLOEXEC) >= 0)
210 {
211#if defined(RT_OS_SOLARIS) || defined(RT_OS_DARWIN)
212 iErr = 0;
213 /* Switch direct I/O on now if requested */
214# if defined(RT_OS_SOLARIS) && !defined(IN_GUEST)
215 if (fOpen & RTFILE_O_NO_CACHE)
216 iErr = directio(fh, DIRECTIO_ON);
217# elif defined(RT_OS_DARWIN)
218 if (fOpen & RTFILE_O_NO_CACHE)
219 iErr = fcntl(fh, F_NOCACHE);
220# endif
221 if (iErr < 0)
222 iErr = errno;
223 else
224#endif
225 {
226 *pFile = (RTFILE)fh;
227 Assert((int)*pFile == fh);
228 LogFlow(("RTFileOpen(%p:{%RTfile}, %p:{%s}, %#x): returns %Rrc\n",
229 pFile, *pFile, pszFilename, pszFilename, fOpen, rc));
230 return VINF_SUCCESS;
231 }
232 }
233 iErr = errno;
234 close(fh);
235 }
236 return RTErrConvertFromErrno(iErr);
237}
238
239
240RTR3DECL(int) RTFileClose(RTFILE File)
241{
242 if (close((int)File) == 0)
243 return VINF_SUCCESS;
244 return RTErrConvertFromErrno(errno);
245}
246
247
248RTR3DECL(int) RTFileFromNative(PRTFILE pFile, RTHCINTPTR uNative)
249{
250 if ( uNative < 0
251 || (RTFILE)uNative != (RTUINTPTR)uNative)
252 {
253 AssertMsgFailed(("%p\n", uNative));
254 *pFile = NIL_RTFILE;
255 return VERR_INVALID_HANDLE;
256 }
257 *pFile = (RTFILE)uNative;
258 return VINF_SUCCESS;
259}
260
261
262RTR3DECL(RTHCINTPTR) RTFileToNative(RTFILE File)
263{
264 AssertReturn(File != NIL_RTFILE, -1);
265 return (RTHCINTPTR)File;
266}
267
268
269RTR3DECL(int) RTFileDelete(const char *pszFilename)
270{
271 char *pszNativeFilename;
272 int rc = rtPathToNative(&pszNativeFilename, pszFilename);
273 if (RT_SUCCESS(rc))
274 {
275 if (unlink(pszNativeFilename) != 0)
276 rc = RTErrConvertFromErrno(errno);
277 rtPathFreeNative(pszNativeFilename);
278 }
279 return rc;
280}
281
282
283RTR3DECL(int) RTFileSeek(RTFILE File, int64_t offSeek, unsigned uMethod, uint64_t *poffActual)
284{
285 static const unsigned aSeekRecode[] =
286 {
287 SEEK_SET,
288 SEEK_CUR,
289 SEEK_END,
290 };
291
292 /*
293 * Validate input.
294 */
295 if (uMethod > RTFILE_SEEK_END)
296 {
297 AssertMsgFailed(("Invalid uMethod=%d\n", uMethod));
298 return VERR_INVALID_PARAMETER;
299 }
300
301 /* check that within off_t range. */
302 if ( sizeof(off_t) < sizeof(offSeek)
303 && ( (offSeek > 0 && (unsigned)(offSeek >> 32) != 0)
304 || (offSeek < 0 && (unsigned)(-offSeek >> 32) != 0)))
305 {
306 AssertMsgFailed(("64-bit search not supported\n"));
307 return VERR_NOT_SUPPORTED;
308 }
309
310 off_t offCurrent = lseek((int)File, (off_t)offSeek, aSeekRecode[uMethod]);
311 if (offCurrent != ~0)
312 {
313 if (poffActual)
314 *poffActual = (uint64_t)offCurrent;
315 return VINF_SUCCESS;
316 }
317 return RTErrConvertFromErrno(errno);
318}
319
320
321RTR3DECL(int) RTFileRead(RTFILE File, void *pvBuf, size_t cbToRead, size_t *pcbRead)
322{
323 if (cbToRead <= 0)
324 return VINF_SUCCESS;
325
326 /*
327 * Attempt read.
328 */
329 ssize_t cbRead = read((int)File, pvBuf, cbToRead);
330 if (cbRead >= 0)
331 {
332 if (pcbRead)
333 /* caller can handle partial read. */
334 *pcbRead = cbRead;
335 else
336 {
337 /* Caller expects all to be read. */
338 while ((ssize_t)cbToRead > cbRead)
339 {
340 ssize_t cbReadPart = read((int)File, (char*)pvBuf + cbRead, cbToRead - cbRead);
341 if (cbReadPart <= 0)
342 {
343 if (cbReadPart == 0)
344 return VERR_EOF;
345 return RTErrConvertFromErrno(errno);
346 }
347 cbRead += cbReadPart;
348 }
349 }
350 return VINF_SUCCESS;
351 }
352
353 return RTErrConvertFromErrno(errno);
354}
355
356
357RTR3DECL(int) RTFileWrite(RTFILE File, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
358{
359 if (cbToWrite <= 0)
360 return VINF_SUCCESS;
361
362 /*
363 * Attempt write.
364 */
365 ssize_t cbWritten = write((int)File, pvBuf, cbToWrite);
366 if (cbWritten >= 0)
367 {
368 if (pcbWritten)
369 /* caller can handle partial write. */
370 *pcbWritten = cbWritten;
371 else
372 {
373 /* Caller expects all to be write. */
374 while ((ssize_t)cbToWrite > cbWritten)
375 {
376 ssize_t cbWrittenPart = write((int)File, (const char *)pvBuf + cbWritten, cbToWrite - cbWritten);
377 if (cbWrittenPart <= 0)
378 return RTErrConvertFromErrno(errno);
379 cbWritten += cbWrittenPart;
380 }
381 }
382 return VINF_SUCCESS;
383 }
384 return RTErrConvertFromErrno(errno);
385}
386
387
388RTR3DECL(int) RTFileSetSize(RTFILE File, uint64_t cbSize)
389{
390 /*
391 * Validate offset.
392 */
393 if ( sizeof(off_t) < sizeof(cbSize)
394 && (cbSize >> 32) != 0)
395 {
396 AssertMsgFailed(("64-bit filesize not supported! cbSize=%lld\n", cbSize));
397 return VERR_NOT_SUPPORTED;
398 }
399
400#if defined(_MSC_VER) || (defined(RT_OS_OS2) && (!defined(__INNOTEK_LIBC__) || __INNOTEK_LIBC__ < 0x006))
401 if (chsize((int)File, (off_t)cbSize) == 0)
402#else
403 /* This relies on a non-standard feature of FreeBSD, Linux, and OS/2
404 * LIBC v0.6 and higher. (SuS doesn't define ftruncate() and size bigger
405 * than the file.)
406 */
407 if (ftruncate((int)File, (off_t)cbSize) == 0)
408#endif
409 return VINF_SUCCESS;
410 return RTErrConvertFromErrno(errno);
411}
412
413
414RTR3DECL(int) RTFileGetSize(RTFILE File, uint64_t *pcbSize)
415{
416 struct stat st;
417 if (!fstat((int)File, &st))
418 {
419 *pcbSize = st.st_size;
420 return VINF_SUCCESS;
421 }
422 return RTErrConvertFromErrno(errno);
423}
424
425
426/**
427 * Determine the maximum file size.
428 *
429 * @returns IPRT status code.
430 * @param File Handle to the file.
431 * @param pcbMax Where to store the max file size.
432 * @see RTFileGetMaxSize.
433 */
434RTR3DECL(int) RTFileGetMaxSizeEx(RTFILE File, PRTFOFF pcbMax)
435{
436 /*
437 * Save the current location
438 */
439 uint64_t offOld;
440 int rc = RTFileSeek(File, 0, RTFILE_SEEK_CURRENT, &offOld);
441 if (RT_FAILURE(rc))
442 return rc;
443
444 /*
445 * Perform a binary search for the max file size.
446 */
447 uint64_t offLow = 0;
448 uint64_t offHigh = 8 * _1T; /* we don't need bigger files */
449 /** @todo Unfortunately this does not work for certain file system types,
450 * for instance cifs mounts. Even worse, statvfs.f_fsid returns 0 for such
451 * file systems. */
452 //uint64_t offHigh = INT64_MAX;
453 for (;;)
454 {
455 uint64_t cbInterval = (offHigh - offLow) >> 1;
456 if (cbInterval == 0)
457 {
458 if (pcbMax)
459 *pcbMax = offLow;
460 return RTFileSeek(File, offOld, RTFILE_SEEK_BEGIN, NULL);
461 }
462
463 rc = RTFileSeek(File, offLow + cbInterval, RTFILE_SEEK_BEGIN, NULL);
464 if (RT_FAILURE(rc))
465 offHigh = offLow + cbInterval;
466 else
467 offLow = offLow + cbInterval;
468 }
469}
470
471
472RTR3DECL(bool) RTFileIsValid(RTFILE File)
473{
474 if (File != NIL_RTFILE)
475 {
476 int fFlags = fcntl(File, F_GETFD);
477 if (fFlags >= 0)
478 return true;
479 }
480 return false;
481}
482
483
484RTR3DECL(int) RTFileFlush(RTFILE File)
485{
486 if (fsync((int)File))
487 return RTErrConvertFromErrno(errno);
488 return VINF_SUCCESS;
489}
490
491
492RTR3DECL(int) RTFileIoCtl(RTFILE File, int iRequest, void *pvData, unsigned cbData, int *piRet)
493{
494 int rc = ioctl((int)File, iRequest, pvData);
495 if (piRet)
496 *piRet = rc;
497 return rc >= 0 ? VINF_SUCCESS : RTErrConvertFromErrno(errno);
498}
499
500
501RTR3DECL(int) RTFileQueryInfo(RTFILE File, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs)
502{
503 /*
504 * Validate input.
505 */
506 if (File == NIL_RTFILE)
507 {
508 AssertMsgFailed(("Invalid File=%RTfile\n", File));
509 return VERR_INVALID_PARAMETER;
510 }
511 if (!pObjInfo)
512 {
513 AssertMsgFailed(("Invalid pObjInfo=%p\n", pObjInfo));
514 return VERR_INVALID_PARAMETER;
515 }
516 if ( enmAdditionalAttribs < RTFSOBJATTRADD_NOTHING
517 || enmAdditionalAttribs > RTFSOBJATTRADD_LAST)
518 {
519 AssertMsgFailed(("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs));
520 return VERR_INVALID_PARAMETER;
521 }
522
523 /*
524 * Query file info.
525 */
526 struct stat Stat;
527 if (fstat((int)File, &Stat))
528 {
529 int rc = RTErrConvertFromErrno(errno);
530 Log(("RTFileQueryInfo(%RTfile,,%d): returns %Rrc\n", File, enmAdditionalAttribs, rc));
531 return rc;
532 }
533
534 /*
535 * Setup the returned data.
536 */
537 rtFsConvertStatToObjInfo(pObjInfo, &Stat, NULL, 0);
538
539 /*
540 * Requested attributes (we cannot provide anything actually).
541 */
542 switch (enmAdditionalAttribs)
543 {
544 case RTFSOBJATTRADD_EASIZE:
545 pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
546 pObjInfo->Attr.u.EASize.cb = 0;
547 break;
548
549 case RTFSOBJATTRADD_NOTHING:
550 case RTFSOBJATTRADD_UNIX:
551 /* done */
552 break;
553
554 default:
555 AssertMsgFailed(("Impossible!\n"));
556 return VERR_INTERNAL_ERROR;
557 }
558
559 LogFlow(("RTFileQueryInfo(%RTfile,,%d): returns VINF_SUCCESS\n", File, enmAdditionalAttribs));
560 return VINF_SUCCESS;
561}
562
563
564RTR3DECL(int) RTFileSetTimes(RTFILE File, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
565 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
566{
567 /*
568 * We can only set AccessTime and ModificationTime, so if neither
569 * are specified we can return immediately.
570 */
571 if (!pAccessTime && !pModificationTime)
572 return VINF_SUCCESS;
573
574 /*
575 * Convert the input to timeval, getting the missing one if necessary,
576 * and call the API which does the change.
577 */
578 struct timeval aTimevals[2];
579 if (pAccessTime && pModificationTime)
580 {
581 RTTimeSpecGetTimeval(pAccessTime, &aTimevals[0]);
582 RTTimeSpecGetTimeval(pModificationTime, &aTimevals[1]);
583 }
584 else
585 {
586 RTFSOBJINFO ObjInfo;
587 int rc = RTFileQueryInfo(File, &ObjInfo, RTFSOBJATTRADD_UNIX);
588 if (RT_FAILURE(rc))
589 return rc;
590 RTTimeSpecGetTimeval(pAccessTime ? pAccessTime : &ObjInfo.AccessTime, &aTimevals[0]);
591 RTTimeSpecGetTimeval(pModificationTime ? pModificationTime : &ObjInfo.ModificationTime, &aTimevals[1]);
592 }
593
594 if (futimes((int)File, aTimevals))
595 {
596 int rc = RTErrConvertFromErrno(errno);
597 Log(("RTFileSetTimes(%RTfile,%p,%p,,): returns %Rrc\n", File, pAccessTime, pModificationTime, rc));
598 return rc;
599 }
600 return VINF_SUCCESS;
601}
602
603
604RTR3DECL(int) RTFileSetMode(RTFILE File, RTFMODE fMode)
605{
606 /*
607 * Normalize the mode and call the API.
608 */
609 fMode = rtFsModeNormalize(fMode, NULL, 0);
610 if (!rtFsModeIsValid(fMode))
611 return VERR_INVALID_PARAMETER;
612
613 if (fchmod((int)File, fMode & RTFS_UNIX_MASK))
614 {
615 int rc = RTErrConvertFromErrno(errno);
616 Log(("RTFileSetMode(%RTfile,%RTfmode): returns %Rrc\n", File, fMode, rc));
617 return rc;
618 }
619 return VINF_SUCCESS;
620}
621
622
623RTR3DECL(int) RTFileRename(const char *pszSrc, const char *pszDst, unsigned fRename)
624{
625 /*
626 * Validate input.
627 */
628 AssertMsgReturn(VALID_PTR(pszSrc), ("%p\n", pszSrc), VERR_INVALID_POINTER);
629 AssertMsgReturn(VALID_PTR(pszDst), ("%p\n", pszDst), VERR_INVALID_POINTER);
630 AssertMsgReturn(*pszSrc, ("%p\n", pszSrc), VERR_INVALID_PARAMETER);
631 AssertMsgReturn(*pszDst, ("%p\n", pszDst), VERR_INVALID_PARAMETER);
632 AssertMsgReturn(!(fRename & ~RTPATHRENAME_FLAGS_REPLACE), ("%#x\n", fRename), VERR_INVALID_PARAMETER);
633
634 /*
635 * Take common cause with RTPathRename.
636 */
637 int rc = rtPathPosixRename(pszSrc, pszDst, fRename, RTFS_TYPE_FILE);
638
639 LogFlow(("RTDirRename(%p:{%s}, %p:{%s}, %#x): returns %Rrc\n",
640 pszSrc, pszSrc, pszDst, pszDst, fRename, rc));
641 return rc;
642}
643
644
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