VirtualBox

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

Last change on this file since 19346 was 19346, checked in by vboxsync, 16 years ago

Runtime/Aio: Updates

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