示例#1
0
int main()
{
    int rc = RTTestInitAndCreate("tstRTFileAio", &g_hTest);
    if (rc)
        return rc;

    /* Check if the API is available. */
    RTTestSub(g_hTest, "RTFileAioGetLimits");
    RTFILEAIOLIMITS AioLimits;
    RT_ZERO(AioLimits);
    RTTESTI_CHECK_RC(rc = RTFileAioGetLimits(&AioLimits), VINF_SUCCESS);
    if (RT_SUCCESS(rc))
    {
        RTTestSub(g_hTest, "Write");
        RTFILE hFile;
        RTTESTI_CHECK_RC(rc = RTFileOpen(&hFile, "tstFileAio#1.tst",
                                         RTFILE_O_READWRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE | RTFILE_O_ASYNC_IO),
                         VINF_SUCCESS);
        if (RT_SUCCESS(rc))
        {
            uint8_t *pbTestBuf = (uint8_t *)RTTestGuardedAllocTail(g_hTest, TSTFILEAIO_BUFFER_SIZE);
            for (unsigned i = 0; i < TSTFILEAIO_BUFFER_SIZE; i++)
                pbTestBuf[i] = i % 256;

            uint32_t cReqsMax = AioLimits.cReqsOutstandingMax < TSTFILEAIO_MAX_REQS_IN_FLIGHT
                              ? AioLimits.cReqsOutstandingMax
                              : TSTFILEAIO_MAX_REQS_IN_FLIGHT;

            /* Basic write test. */
            RTTestIPrintf(RTTESTLVL_ALWAYS, "Preparing test file, this can take some time and needs quite a bit of harddisk space...\n");
            tstFileAioTestReadWriteBasic(hFile, true /*fWrite*/, pbTestBuf, TSTFILEAIO_BUFFER_SIZE, 100*_1M, cReqsMax);

            /* Reopen the file before doing the next test. */
            RTTESTI_CHECK_RC(RTFileClose(hFile), VINF_SUCCESS);
            if (RTTestErrorCount(g_hTest) == 0)
            {
                RTTestSub(g_hTest, "Read/Write");
                RTTESTI_CHECK_RC(rc = RTFileOpen(&hFile, "tstFileAio#1.tst",
                                                 RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_ASYNC_IO),
                                 VINF_SUCCESS);
                if (RT_SUCCESS(rc))
                {
                    tstFileAioTestReadWriteBasic(hFile, false /*fWrite*/, pbTestBuf, TSTFILEAIO_BUFFER_SIZE, 100*_1M, cReqsMax);
                    RTFileClose(hFile);
                }
            }

            /* Cleanup */
            RTFileDelete("tstFileAio#1.tst");
        }
    }

    /*
     * Summary
     */
    return RTTestSummaryAndDestroy(g_hTest);
}
示例#2
0
USBLIB_DECL(int) USBLibInit(void)
{
    LogFlow((USBLIBR3 ":USBLibInit\n"));

    /*
     * Already open?
     * This isn't properly serialized, but we'll be fine with the current usage.
     */
    if (g_cUsers)
    {
        ASMAtomicIncU32(&g_cUsers);
        return VINF_SUCCESS;
    }

    RTFILE File;
    int rc = RTFileOpen(&File, VBOXUSB_DEVICE_NAME, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
    if (RT_FAILURE(rc))
    {
        LogRel((USBLIBR3 ":RTFileOpen failed to open VBoxUSB device.rc=%d\n", rc));
        return rc;
    }
    g_File = File;

    ASMAtomicIncU32(&g_cUsers);
    /*
     * Check the USBMonitor version.
     */
    VBOXUSBREQ_GET_VERSION Req;
    bzero(&Req, sizeof(Req));
    rc = usblibDoIOCtl(VBOXUSBMON_IOCTL_GET_VERSION, &Req, sizeof(Req));
    if (RT_SUCCESS(rc))
    {
        if (   Req.u32Major != VBOXUSBMON_VERSION_MAJOR
            || Req.u32Minor < VBOXUSBMON_VERSION_MINOR)
        {
            rc = VERR_VERSION_MISMATCH;
            LogRel((USBLIBR3 ":USBMonitor version mismatch! driver v%d.%d, expecting ~v%d.%d\n",
                        Req.u32Major, Req.u32Minor, VBOXUSBMON_VERSION_MAJOR, VBOXUSBMON_VERSION_MINOR));

            RTFileClose(File);
            g_File = NIL_RTFILE;
            ASMAtomicDecU32(&g_cUsers);
            return rc;
        }
    }
    else
    {
        LogRel((USBLIBR3 ":USBMonitor driver version query failed. rc=%Rrc\n", rc));
        RTFileClose(File);
        g_File = NIL_RTFILE;
        ASMAtomicDecU32(&g_cUsers);
        return rc;
    }

    return VINF_SUCCESS;
}
RTR3DECL(int) RTProcDaemonize(const char * const *papszArgs, const char *pszDaemonizedOpt)
{
    /*
     * Get the executable name.
     * If this asserts, it's probably because rtR3Init hasn't been called.
     */
    char szExecPath[RTPATH_MAX];
    AssertReturn(RTProcGetExecutablePath(szExecPath, sizeof(szExecPath)) == szExecPath, VERR_WRONG_ORDER);

    /*
     * Create a copy of the argument list with the daemonized option appended.
     */
    unsigned cArgs = 0;
    while (papszArgs[cArgs])
        cArgs++;

    char const **papszNewArgs = (char const **)RTMemAlloc(sizeof(const char *) * (cArgs + 2));
    if (!papszNewArgs)
        return VERR_NO_MEMORY;
    for (unsigned i = 0; i < cArgs; i++)
        papszNewArgs[i] = papszArgs[i];
    papszNewArgs[cArgs] = pszDaemonizedOpt;
    papszNewArgs[cArgs + 1] = NULL;

    /*
     * Open the bitbucket handles and create the detached process.
     */
    RTHANDLE hStdIn;
    int rc = RTFileOpenBitBucket(&hStdIn.u.hFile, RTFILE_O_READ);
    if (RT_SUCCESS(rc))
    {
        hStdIn.enmType = RTHANDLETYPE_FILE;

        RTHANDLE hStdOutAndErr;
        rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
        if (RT_SUCCESS(rc))
        {
            hStdOutAndErr.enmType = RTHANDLETYPE_FILE;

            rc = RTProcCreateEx(szExecPath, papszNewArgs, RTENV_DEFAULT,
                                RTPROC_FLAGS_DETACHED | RTPROC_FLAGS_SAME_CONTRACT,
                                &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
                                NULL /*pszAsUser*/,  NULL /*pszPassword*/, NULL /*phProcess*/);

            RTFileClose(hStdOutAndErr.u.hFile);
        }

        RTFileClose(hStdOutAndErr.u.hFile);
    }
    RTMemFree(papszNewArgs);
    return rc;
}
示例#4
0
文件: tftp.c 项目: ryenus/vbox
DECLINLINE(int) tftpReadDataBlock(PNATState pData,
                                  PTFTPSESSION pcTftpSession,
                                  uint8_t *pu8Data,
                                  int *pcbReadData)
{
    RTFILE  hSessionFile;
    int rc = VINF_SUCCESS;
    uint16_t u16BlkSize = 0;
    AssertPtrReturn(pData, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pcTftpSession, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pu8Data, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pcbReadData, VERR_INVALID_PARAMETER);
    AssertReturn(pcTftpSession->OptionBlkSize.u64Value < UINT16_MAX, VERR_INVALID_PARAMETER);
    LogFlowFunc(("pcTftpSession:%p, pu8Data:%p, pcbReadData:%p\n",
                    pcTftpSession,
                    pu8Data,
                    pcbReadData));

    u16BlkSize = (uint16_t)pcTftpSession->OptionBlkSize.u64Value;
    rc = pftpSessionOpenFile(pData, pcTftpSession, &hSessionFile);
    if (RT_FAILURE(rc))
    {
        LogFlowFuncLeaveRC(rc);
        return rc;
    }

    if (pcbReadData)
    {
        rc = RTFileSeek(hSessionFile,
                        pcTftpSession->cbTransfered,
                        RTFILE_SEEK_BEGIN,
                        NULL);
        if (RT_FAILURE(rc))
        {
            RTFileClose(hSessionFile);
            LogFlowFuncLeaveRC(rc);
            return rc;
        }
        rc = RTFileRead(hSessionFile, pu8Data, u16BlkSize, (size_t *)pcbReadData);
        if (RT_FAILURE(rc))
        {
            RTFileClose(hSessionFile);
            LogFlowFuncLeaveRC(rc);
            return rc;
        }
    }

    rc = RTFileClose(hSessionFile);

    LogFlowFuncLeaveRC(rc);
    return rc;
}
示例#5
0
VBGLR3DECL(void) VbglR3Term(void)
{
    /*
     * Decrement the reference count and see if we're the last one out.
     */
    uint32_t cInits = ASMAtomicDecU32(&g_cInits);
    if (cInits > 0)
        return;
#if !defined(VBOX_VBGLR3_XSERVER)
    AssertReturnVoid(!cInits);

# if defined(RT_OS_WINDOWS)
    HANDLE hFile = g_hFile;
    g_hFile = INVALID_HANDLE_VALUE;
    AssertReturnVoid(hFile != INVALID_HANDLE_VALUE);
    BOOL fRc = CloseHandle(hFile);
    Assert(fRc); NOREF(fRc);

# elif defined(RT_OS_OS2)
    RTFILE File = g_File;
    g_File = NIL_RTFILE;
    AssertReturnVoid(File != NIL_RTFILE);
    APIRET rc = DosClose((uintptr_t)File);
    AssertMsg(!rc, ("%ld\n", rc));

#elif defined(RT_OS_DARWIN)
    io_connect_t    uConnection = g_uConnection;
    RTFILE          hFile       = g_File;
    g_uConnection = 0;
    g_File        = NIL_RTFILE;
    kern_return_t kr = IOServiceClose(uConnection);
    AssertMsg(kr == kIOReturnSuccess, ("%#x (%d)\n", kr, kr));
    int rc = RTFileClose(hFile);
    AssertRC(rc);

# else /* The IPRT case. */
    RTFILE File = g_File;
    g_File = NIL_RTFILE;
    AssertReturnVoid(File != NIL_RTFILE);
    int rc = RTFileClose(File);
    AssertRC(rc);
# endif

#else  /* VBOX_VBGLR3_XSERVER */
    int File = g_File;
    g_File = -1;
    if (File == -1)
        return;
    xf86close(File);
#endif /* VBOX_VBGLR3_XSERVER */
}
示例#6
0
int DnDHGSendFilePrivate::currentMessage(uint32_t uMsg, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    if (!m_pNextMsg)
        return VERR_NO_DATA;

    int rc = m_pNextMsg->getData(uMsg, cParms, paParms);
    clearNextMsg();
    if (RT_FAILURE(rc))
        return rc;

    if (!m_hCurFile)
    {
        rc = RTFileOpen(&m_hCurFile, m_strHostPath.c_str(), RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_ALL);
        if (RT_FAILURE(rc))
            return rc;
    }

    /* How big is the pointer provided by the guest? */
    uint32_t cbToRead = paParms[2].u.pointer.size;
    size_t cbRead;
    rc = RTFileRead(m_hCurFile, paParms[2].u.pointer.addr, cbToRead, &cbRead);
    if (RT_FAILURE(rc))
    {
        /* On error, immediately close the file. */
        RTFileClose(m_hCurFile);
        m_hCurFile = 0;
        return rc;
    }
    m_cbDone += cbRead;
    /* Tell the guest the actual size. */
    paParms[3].setUInt32(cbRead);
    /* Check if we are done. */
    if (m_cbSize == m_cbDone)
    {
        RTFileClose(m_hCurFile);
        m_hCurFile = 0;
    }
    else
    {
        /* More data! Prepare the next message. */
        m_pNextMsg = new HGCM::Message(DragAndDropSvc::HOST_DND_HG_SND_FILE, 5, m_paSkelParms);
    }

    /* Advance progress info */
    if (   RT_SUCCESS(rc)
        && m_pfnProgressCallback)
        rc = m_pfnProgressCallback(cbRead, m_pvProgressUser);

    return rc;
}
RTDECL(int) RTFileCopyEx(const char *pszSrc, const char *pszDst, uint32_t fFlags, PFNRTPROGRESS pfnProgress, void *pvUser)
{
    /*
     * Validate input.
     */
    AssertMsgReturn(VALID_PTR(pszSrc), ("pszSrc=%p\n", pszSrc), VERR_INVALID_PARAMETER);
    AssertMsgReturn(*pszSrc, ("pszSrc=%p\n", pszSrc), VERR_INVALID_PARAMETER);
    AssertMsgReturn(VALID_PTR(pszDst), ("pszDst=%p\n", pszDst), VERR_INVALID_PARAMETER);
    AssertMsgReturn(*pszDst, ("pszDst=%p\n", pszDst), VERR_INVALID_PARAMETER);
    AssertMsgReturn(!pfnProgress || VALID_PTR(pfnProgress), ("pfnProgress=%p\n", pfnProgress), VERR_INVALID_PARAMETER);
    AssertMsgReturn(!(fFlags & ~RTFILECOPY_FLAGS_MASK), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);

    /*
     * Open the files.
     */
    RTFILE FileSrc;
    int rc = RTFileOpen(&FileSrc, pszSrc,
                        RTFILE_O_READ | RTFILE_O_OPEN
                        | (fFlags & RTFILECOPY_FLAGS_NO_SRC_DENY_WRITE ? RTFILE_O_DENY_NONE : RTFILE_O_DENY_WRITE));
    if (RT_SUCCESS(rc))
    {
        RTFILE FileDst;
        rc = RTFileOpen(&FileDst, pszDst,
                        RTFILE_O_WRITE | RTFILE_O_CREATE
                        | (fFlags & RTFILECOPY_FLAGS_NO_DST_DENY_WRITE ? RTFILE_O_DENY_NONE : RTFILE_O_DENY_WRITE));
        if (RT_SUCCESS(rc))
        {
            /*
             * Call the ByHandles version and let it do the job.
             */
            rc = RTFileCopyByHandlesEx(FileSrc, FileDst, pfnProgress, pvUser);

            /*
             * Close the files regardless of the result.
             * Don't bother cleaning up or anything like that.
             */
            int rc2 = RTFileClose(FileDst);
            AssertRC(rc2);
            if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
                rc = rc2;
        }

        int rc2 = RTFileClose(FileSrc);
        AssertRC(rc2);
        if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
            rc = rc2;
    }
    return rc;
}
示例#8
0
/**
 * Writes the stream to a file.
 *
 * @returns IPRT status code
 * @param   pStream             The stream.
 * @param   pszFilenameFmt      The filename format string.
 * @param   ...                 Format arguments.
 */
int ScmStreamWriteToFile(PSCMSTREAM pStream, const char *pszFilenameFmt, ...)
{
    int rc;

#ifdef RT_STRICT
    /*
     * Check that what we're going to write makes sense first.
     */
    rc = ScmStreamCheckItegrity(pStream);
    if (RT_FAILURE(rc))
        return rc;
#endif

    /*
     * Do the actual writing.
     */
    RTFILE hFile;
    va_list va;
    va_start(va, pszFilenameFmt);
    rc = RTFileOpenV(&hFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_WRITE, pszFilenameFmt, va);
    if (RT_SUCCESS(rc))
    {
        rc = RTFileWrite(hFile, pStream->pch, pStream->cb, NULL);
        RTFileClose(hFile);
    }
    va_end(va);
    return rc;
}
示例#9
0
void DnDURIObject::closeInternal(void)
{
    switch (m_Type)
    {
        case File:
        {
            if (u.m_hFile)
            {
                int rc2 = RTFileClose(u.m_hFile);
                AssertRC(rc2);

                u.m_hFile = NULL;
            }
            break;
        }

        case Directory:
            break;

        default:
            break;
    }

    LogFlowThisFuncLeave();
}
示例#10
0
文件: tftp.c 项目: ryenus/vbox
DECLINLINE(int) tftpSessionEvaluateOptions(PNATState pData, PTFTPSESSION pTftpSession)
{
    int rc = VINF_SUCCESS;
    RTFILE hSessionFile;
    uint64_t cbSessionFile = 0;
    LogFlowFunc(("pTftpSession:%p\n", pTftpSession));

    rc = pftpSessionOpenFile(pData, pTftpSession, &hSessionFile);
    if (RT_FAILURE(rc))
    {
        LogFlowFuncLeave();
        return rc;
    }

    rc = RTFileGetSize(hSessionFile, &cbSessionFile);
    RTFileClose(hSessionFile);
    if (RT_FAILURE(rc))
    {
        LogFlowFuncLeave();
        return rc;
    }

    if (pTftpSession->OptionTSize.fRequested)
    {
       pTftpSession->OptionTSize.u64Value = cbSessionFile;
    }
    if (   !pTftpSession->OptionBlkSize.u64Value
        && !pTftpSession->OptionBlkSize.fRequested)
    {
        pTftpSession->OptionBlkSize.u64Value = 1428;
    }
    LogFlowFuncLeaveRC(rc);
    return rc;
}
示例#11
0
/**
 * Destruct a host parallel driver instance.
 *
 * Most VM resources are freed by the VM. This callback is provided so that
 * any non-VM resources can be freed correctly.
 *
 * @param   pDrvIns     The driver instance data.
 */
static DECLCALLBACK(void) drvHostParallelDestruct(PPDMDRVINS pDrvIns)
{
    PDRVHOSTPARALLEL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTPARALLEL);
    LogFlowFunc(("iInstance=%d\n", pDrvIns->iInstance));
    PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);

#ifndef VBOX_WITH_WIN_PARPORT_SUP

    int rc;

    if (pThis->hFileDevice != NIL_RTFILE)
        ioctl(RTFileToNative(pThis->hFileDevice), PPRELEASE);

    rc = RTPipeClose(pThis->hWakeupPipeW); AssertRC(rc);
    pThis->hWakeupPipeW = NIL_RTPIPE;

    rc = RTPipeClose(pThis->hWakeupPipeR); AssertRC(rc);
    pThis->hWakeupPipeR = NIL_RTPIPE;

    rc = RTFileClose(pThis->hFileDevice); AssertRC(rc); /** @todo r=bird: Why aren't this closed on Windows? */
    pThis->hFileDevice = NIL_RTFILE;

    if (pThis->pszDevicePath)
    {
        MMR3HeapFree(pThis->pszDevicePath);
        pThis->pszDevicePath = NULL;
    }
#endif /* VBOX_WITH_WIN_PARPORT_SUP */
}
/**
 * Closes the object's internal handles (to files / ...).
 *
 */
void DnDURIObject::closeInternal(void)
{
    LogFlowThisFuncEnter();

    switch (m_enmType)
    {
        case Type_File:
        {
            RTFileClose(u.File.hFile);
            u.File.hFile = NIL_RTFILE;
            RT_ZERO(u.File.objInfo);
            break;
        }

        case Type_Directory:
        {
            RTDirClose(u.Dir.hDir);
            u.Dir.hDir = NIL_RTDIR;
            RT_ZERO(u.Dir.objInfo);
            break;
        }

        default:
            break;
    }
}
/**
 * EMT Rendezvous worker function for DBGFR3CoreWrite().
 *
 * @param   pVM              Pointer to the VM.
 * @param   pVCpu            The handle of the calling VCPU.
 * @param   pvData           Opaque data.
 *
 * @return VBox status code.
 */
static DECLCALLBACK(VBOXSTRICTRC) dbgfR3CoreWriteRendezvous(PVM pVM, PVMCPU pVCpu, void *pvData)
{
    /*
     * Validate input.
     */
    AssertReturn(pVM, VERR_INVALID_VM_HANDLE);
    AssertReturn(pVCpu, VERR_INVALID_VMCPU_HANDLE);
    AssertReturn(pvData, VERR_INVALID_POINTER);

    PDBGFCOREDATA pDbgfData = (PDBGFCOREDATA)pvData;

    /*
     * Create the core file.
     */
    uint32_t fFlags = (pDbgfData->fReplaceFile ? RTFILE_O_CREATE_REPLACE : RTFILE_O_CREATE)
                    | RTFILE_O_WRITE
                    | RTFILE_O_DENY_ALL
                    | (0600 << RTFILE_O_CREATE_MODE_SHIFT);
    RTFILE   hFile;
    int rc = RTFileOpen(&hFile, pDbgfData->pszFilename, fFlags);
    if (RT_SUCCESS(rc))
    {
        rc = dbgfR3CoreWriteWorker(pVM, hFile);
        RTFileClose(hFile);
    }
    else
        LogRel((DBGFLOG_NAME ": RTFileOpen failed for '%s' rc=%Rrc\n", pDbgfData->pszFilename, rc));
    return rc;
}
/**
 * Handles VMMDevCpuEventType_Unplug.
 *
 * @param   idCpuCore       The CPU core ID.
 * @param   idCpuPackage    The CPU package ID.
 */
static void VBoxServiceCpuHotPlugHandleUnplugEvent(uint32_t idCpuCore, uint32_t idCpuPackage)
{
#ifdef RT_OS_LINUX
    char *pszCpuDevicePath = NULL;
    int rc = VBoxServiceCpuHotPlugGetACPIDevicePath(&pszCpuDevicePath, idCpuCore, idCpuPackage);
    if (RT_SUCCESS(rc))
    {
        RTFILE hFileCpuEject;
        rc = RTFileOpenF(&hFileCpuEject, RTFILE_O_WRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE,
                         "%s/eject", pszCpuDevicePath);
        if (RT_SUCCESS(rc))
        {
            /* Write a 1 to eject the CPU */
            rc = RTFileWrite(hFileCpuEject, "1", 1, NULL);
            if (RT_SUCCESS(rc))
                VBoxServiceVerbose(1, "CpuHotPlug: CPU %u/%u was ejected\n", idCpuPackage, idCpuCore);
            else
                VBoxServiceError("CpuHotPlug: Failed to eject CPU %u/%u rc=%Rrc\n", idCpuPackage, idCpuCore, rc);

            RTFileClose(hFileCpuEject);
        }
        else
            VBoxServiceError("CpuHotPlug: Failed to open \"%s/eject\" rc=%Rrc\n", pszCpuDevicePath, rc);
        RTStrFree(pszCpuDevicePath);
    }
    else
        VBoxServiceError("CpuHotPlug: Failed to get CPU device path rc=%Rrc\n", rc);
#else
# error "Port me"
#endif
}
/**
 * Creates a PID File and returns the open file descriptor.
 *
 * On DOS based system, file sharing (deny write) is used for locking the PID
 * file.
 *
 * On Unix-y systems, an exclusive advisory lock is used for locking the PID
 * file since the file sharing support is usually missing there.
 *
 * This API will overwrite any existing PID Files without a lock on them, on the
 * assumption that they are stale files which an old process did not properly
 * clean up.
 *
 * @returns IPRT status code.
 * @param   pszPath  The path and filename to create the PID File under
 * @param   phFile   Where to store the file descriptor of the open (and locked
 *                   on Unix-y systems) PID File. On failure, or if another
 *                   process owns the PID File, this will be set to NIL_RTFILE.
 */
VBGLR3DECL(int) VbglR3PidFile(const char *pszPath, PRTFILE phFile)
{
    AssertPtrReturn(pszPath, VERR_INVALID_PARAMETER);
    AssertPtrReturn(phFile, VERR_INVALID_PARAMETER);
    *phFile = NIL_RTFILE;

    RTFILE hPidFile;
    int rc = RTFileOpen(&hPidFile, pszPath,
                        RTFILE_O_READWRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE
                        | (0644 << RTFILE_O_CREATE_MODE_SHIFT));
    if (RT_SUCCESS(rc))
    {
#if !defined(RT_OS_WINDOWS) && !defined(RT_OS_OS2)
        /** @todo using size 0 for locking means lock all on Posix.
         * We should adopt this as our convention too, or something
         * similar. */
        rc = RTFileLock(hPidFile, RTFILE_LOCK_WRITE, 0, 0);
        if (RT_FAILURE(rc))
            RTFileClose(hPidFile);
        else
#endif
        {
            char szBuf[256];
            size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n",
                                       RTProcSelf());
            RTFileWrite(hPidFile, szBuf, cbPid, NULL);
            *phFile = hPidFile;
        }
    }
    return rc;
}
示例#16
0
DECLHIDDEN(int) drvHostBaseMediaRefreshOs(PDRVHOSTBASE pThis)
{
    /*
     * Need to re-open the device because it will kill off any cached data
     * that Linux for some peculiar reason thinks should survive a media change.
     */
    if (pThis->Os.hFileDevice != NIL_RTFILE)
    {
        RTFileClose(pThis->Os.hFileDevice);
        pThis->Os.hFileDevice = NIL_RTFILE;
    }
    int rc = drvHostBaseOpenOs(pThis, pThis->fReadOnlyConfig);
    if (RT_FAILURE(rc))
    {
        if (!pThis->fReadOnlyConfig)
        {
            LogFlow(("%s-%d: drvHostBaseMediaRefreshOs: '%s' - retry readonly (%Rrc)\n",
                     pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
            rc = drvHostBaseOpenOs(pThis, true);
        }
        if (RT_FAILURE(rc))
        {
            LogFlow(("%s-%d: failed to open device '%s', rc=%Rrc\n",
                     pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
            return rc;
        }
        pThis->fReadOnly = true;
    }
    else
        pThis->fReadOnly = pThis->fReadOnlyConfig;

    return rc;
}
示例#17
0
static void test1(const char *pszSubTest, const char *pszFilename)
{
    int rc;
    RTTestISub(pszSubTest);

    RTFILE hFile;
    rc = RTFileOpen(&hFile, pszFilename, RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
    if (RT_FAILURE(rc))
    {
        if (   rc == VERR_ACCESS_DENIED
            || rc == VERR_PERMISSION_DENIED
            || rc == VERR_FILE_NOT_FOUND)
        {
            RTTestIPrintf(RTTESTLVL_ALWAYS, "Cannot access '%s', skipping.", pszFilename);
            return;
        }
        RTTESTI_CHECK_RC_RETV(RTFileOpen(&hFile, pszFilename, RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN), VINF_SUCCESS);
    }

    uint64_t    cbFile = UINT64_MAX - 42;
    RTTESTI_CHECK_RC(rc = RTFileGetSize(hFile, &cbFile), VINF_SUCCESS);
    if (RT_SUCCESS(rc))
    {
        RTTESTI_CHECK(cbFile != UINT64_MAX - 42);
        RTTestIValue(pszSubTest, cbFile, RTTESTUNIT_BYTES);
    }

    RTFileClose(hFile);
    RTTestISubDone();
}
示例#18
0
DECLHIDDEN(void) drvHostBaseDestructOs(PDRVHOSTBASE pThis)
{
    /*
     * Unlock the drive if we've locked it or we're in passthru mode.
     */
    if (    pThis->fLocked
            &&  pThis->Os.hFileDevice != NIL_RTFILE
            &&  pThis->pfnDoLock)
    {
        int rc = pThis->pfnDoLock(pThis, false);
        if (RT_SUCCESS(rc))
            pThis->fLocked = false;
    }

    if (pThis->Os.pbDoubleBuffer)
    {
        RTMemFree(pThis->Os.pbDoubleBuffer);
        pThis->Os.pbDoubleBuffer = NULL;
    }

    if (pThis->Os.hFileDevice != NIL_RTFILE)
    {
        int rc = RTFileClose(pThis->Os.hFileDevice);
        AssertRC(rc);
        pThis->Os.hFileDevice = NIL_RTFILE;
    }
}
示例#19
0
RTDECL(int) RTHandleClose(PRTHANDLE ph)
{
    int rc = VINF_SUCCESS;
    if (ph)
    {
        switch (ph->enmType)
        {
            case RTHANDLETYPE_FILE:
                rc = RTFileClose(ph->u.hFile);
                ph->u.hFile = NIL_RTFILE;
                break;

            case RTHANDLETYPE_PIPE:
                rc = RTPipeClose(ph->u.hPipe);
                ph->u.hPipe = NIL_RTPIPE;
                break;

            case RTHANDLETYPE_SOCKET:
                AssertMsgFailed(("Socket not supported\n"));
                rc = VERR_NOT_SUPPORTED;
                break;

            case RTHANDLETYPE_THREAD:
                AssertMsgFailed(("Thread not supported\n"));
                rc = VERR_NOT_SUPPORTED;
                break;

            default:
                AssertMsgFailed(("Invalid type %d\n", ph->enmType));
                rc = VERR_INVALID_PARAMETER;
                break;
        }
    }
    return rc;
}
DECL_FORCE_INLINE(int) benchmarkFileOpenCloseOp(const char *pszFilename)
{
    RTFILE hFile;
    int rc = RTFileOpen(&hFile, pszFilename, RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN);
    if (RT_SUCCESS(rc))
        rc = RTFileClose(hFile);
    return rc;
}
RTDECL(int) RTFileCompareEx(const char *pszFile1, const char *pszFile2, uint32_t fFlags, PFNRTPROGRESS pfnProgress, void *pvUser)
{
    /*
     * Validate input.
     */
    AssertPtrReturn(pszFile1, VERR_INVALID_POINTER);
    AssertReturn(*pszFile1, VERR_INVALID_PARAMETER);
    AssertPtrReturn(pszFile2, VERR_INVALID_POINTER);
    AssertReturn(*pszFile2, VERR_INVALID_PARAMETER);
    AssertMsgReturn(!pfnProgress || VALID_PTR(pfnProgress), ("pfnProgress=%p\n", pfnProgress), VERR_INVALID_PARAMETER);
    AssertMsgReturn(!(fFlags & ~RTFILECOMP_FLAGS_MASK), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);

    /*
     * Open the files.
     */
    RTFILE hFile1;
    int rc = RTFileOpen(&hFile1, pszFile1,
                        RTFILE_O_READ | RTFILE_O_OPEN
                        | (fFlags & RTFILECOMP_FLAGS_NO_DENY_WRITE_FILE1 ? RTFILE_O_DENY_NONE : RTFILE_O_DENY_WRITE));
    if (RT_SUCCESS(rc))
    {
        RTFILE hFile2;
        rc = RTFileOpen(&hFile2, pszFile2,
                        RTFILE_O_READ | RTFILE_O_OPEN
                        | (fFlags & RTFILECOMP_FLAGS_NO_DENY_WRITE_FILE2 ? RTFILE_O_DENY_NONE : RTFILE_O_DENY_WRITE));
        if (RT_SUCCESS(rc))
        {
            /*
             * Call the ByHandles version and let it do the job.
             */
            rc = RTFileCompareByHandlesEx(hFile1, hFile2, fFlags,  pfnProgress, pvUser);

            /* Clean up */
            int rc2 = RTFileClose(hFile2);
            AssertRC(rc2);
            if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
                rc = rc2;
        }

        int rc2 = RTFileClose(hFile1);
        AssertRC(rc2);
        if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
            rc = rc2;
    }
    return rc;
}
示例#22
0
文件: s3.cpp 项目: mcenirm/vbox
RTR3DECL(int) RTS3GetKey(RTS3 hS3, const char *pszBucketName, const char *pszKeyName, const char *pszFilename)
{
    PRTS3INTERNAL pS3Int = hS3;
    RTS3_VALID_RETURN(pS3Int);

    /* Reset the CURL object to an defined state */
    rtS3ReinitCurl(pS3Int);

    /* Open the file */
    RTFILE hFile;
    int rc = RTFileOpen(&hFile, pszFilename, RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE);
    if (RT_FAILURE(rc))
        return rc;

    char* pszUrl = rtS3Host(pszBucketName, pszKeyName, pS3Int->pszBaseUrl);
    curl_easy_setopt(pS3Int->pCurl, CURLOPT_URL, pszUrl);
    RTStrFree(pszUrl);

    /* Create the three basic header entries */
    char *apszHead[3] =
    {
        rtS3HostHeader(pszBucketName, pS3Int->pszBaseUrl), /* Host entry */
        rtS3DateHeader(),                                  /* Date entry */
        NULL                                               /* Authorization entry */
    };
    /* Create the authorization header entry */
    apszHead[RT_ELEMENTS(apszHead)-1] = rtS3CreateAuthHeader(pS3Int, "GET", pszBucketName, pszKeyName, apszHead, RT_ELEMENTS(apszHead));

    /* Add all headers to curl */
    struct curl_slist* pHeaders = NULL; /* Init to NULL is important */
    for(size_t i=0; i < RT_ELEMENTS(apszHead); ++i)
        pHeaders = curl_slist_append(pHeaders, apszHead[i]);

    /* Pass our list of custom made headers */
    curl_easy_setopt(pS3Int->pCurl, CURLOPT_HTTPHEADER, pHeaders);

    /* Set the callback which receive the content */
    curl_easy_setopt(pS3Int->pCurl, CURLOPT_WRITEFUNCTION, rtS3WriteFileCallback);
    curl_easy_setopt(pS3Int->pCurl, CURLOPT_WRITEDATA, &hFile);

    /* Start the request */
    rc = rtS3Perform(pS3Int);

    /* Regardless of the result, free all used resources first*/
    curl_slist_free_all(pHeaders);
    for(size_t i=0; i < RT_ELEMENTS(apszHead); ++i)
        RTStrFree(apszHead[i]);

    /* Close the open file */
    RTFileClose(hFile);

    /* If there was an error delete the newly created file */
    if (RT_FAILURE(rc))
        RTFileDelete(pszFilename);

    return rc;
}
示例#23
0
文件: UsbTest.cpp 项目: mcenirm/vbox
/**
 * Search for a USB test device and return the device path.
 *
 * @returns Path to the USB test device or NULL if none was found.
 */
static char *usbTestFindDevice(void)
{
    /*
     * Very crude and quick way to search for the correct test device.
     * Assumption is that the path looks like /dev/bus/usb/%3d/%3d.
     */
    uint8_t uBus = 1;
    bool fBusExists = false;
    char aszDevPath[64];

    RT_ZERO(aszDevPath);

    do
    {
        RTStrPrintf(aszDevPath, sizeof(aszDevPath), "/dev/bus/usb/%03d", uBus);

        fBusExists = RTPathExists(aszDevPath);

        if (fBusExists)
        {
            /* Check every device. */
            bool fDevExists = false;
            uint8_t uDev = 1;

            do
            {
                RTStrPrintf(aszDevPath, sizeof(aszDevPath), "/dev/bus/usb/%03d/%03d", uBus, uDev);

                fDevExists = RTPathExists(aszDevPath);

                if (fDevExists)
                {
                    RTFILE hFileDev;
                    int rc = RTFileOpen(&hFileDev, aszDevPath, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
                    if (RT_SUCCESS(rc))
                    {
                        USBDEVDESC DevDesc;

                        rc = RTFileRead(hFileDev, &DevDesc, sizeof(DevDesc), NULL);
                        RTFileClose(hFileDev);

                        if (   RT_SUCCESS(rc)
                            && DevDesc.idVendor == 0x0525
                            && DevDesc.idProduct == 0xa4a0)
                            return RTStrDup(aszDevPath);
                    }
                }

                uDev++;
            } while (fDevExists);
        }

        uBus++;
    } while (fBusExists);

    return NULL;
}
示例#24
0
void DnDURIObject::closeInternal(void)
{
    if (m_Type == File)
    {
        if (u.m_hFile)
        {
            RTFileClose(u.m_hFile);
            u.m_hFile = NULL;
        }
    }
}
示例#25
0
/**
 * Adds a debug file to the cache.
 *
 * @returns IPRT status code
 * @param   pszPath             The path to the debug file in question.
 * @param   pCfg                The configuration.
 */
static int rtDbgSymCacheAddDebugFile(const char *pszPath, PCRTDBGSYMCACHEADDCFG pCfg)
{
    /*
     * Need to extract an identifier of sorts here in order to put them in
     * the right place in the cache.  Currently only implemnted for Mach-O
     * files since these use executable containers.
     *
     * We take a look at the file header in hope to figure out what to do
     * with the file.
     */
    RTFILE hFile;
    int rc = RTFileOpen(&hFile, pszPath, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
    if (RT_FAILURE(rc))
        return RTMsgErrorRc(rc, "Error opening '%s': %Rrc", pszPath, rc);

    union
    {
        uint64_t au64[16];
        uint32_t au32[16];
        uint16_t au16[32];
        uint8_t  ab[64];
    } uBuf;
    rc = RTFileRead(hFile, &uBuf, sizeof(uBuf), NULL);
    if (RT_SUCCESS(rc))
    {
        /*
         * Look for magics and call workers.
         */
        if (!memcmp(uBuf.ab, RT_STR_TUPLE("Microsoft C/C++ MSF 7.00")))
            rc = rtDbgSymCacheAddDebugPdb(pszPath, pCfg, hFile);
        else if (   uBuf.au32[0] == IMAGE_FAT_SIGNATURE
                 || uBuf.au32[0] == IMAGE_FAT_SIGNATURE_OE
                 || uBuf.au32[0] == IMAGE_MACHO32_SIGNATURE
                 || uBuf.au32[0] == IMAGE_MACHO64_SIGNATURE
                 || uBuf.au32[0] == IMAGE_MACHO32_SIGNATURE_OE
                 || uBuf.au32[0] == IMAGE_MACHO64_SIGNATURE_OE)
            rc = rtDbgSymCacheAddDebugMachO(pszPath, pCfg);
        else
            rc = RTMsgErrorRc(VERR_INVALID_MAGIC, "Unsupported debug file '%s' magic: %#010x", pszPath, uBuf.au32[0]);
    }
    else
        rc = RTMsgErrorRc(rc, "Error reading '%s': %Rrc", pszPath, rc);

    /* close the file. */
    int rc2 = RTFileClose(hFile);
    if (RT_FAILURE(rc2))
    {
        RTMsgError("Error closing '%s': %Rrc", pszPath, rc2);
        if (RT_SUCCESS(rc))
            rc = rc2;
    }
    return rc;
}
示例#26
0
/**
 * If any Usbfs-related resources are currently allocated, then free them
 * and mark them as freed.
 */
void USBProxyBackendLinux::doUsbfsCleanupAsNeeded()
{
    /*
     * Free resources.
     */
    RTFileClose(mhFile);
    mhFile = NIL_RTFILE;

    RTPipeClose(mhWakeupPipeR);
    RTPipeClose(mhWakeupPipeW);
    mhWakeupPipeW = mhWakeupPipeR = NIL_RTPIPE;
}
示例#27
0
/** @copydoc KRDROPS::pfnCreate */
static int krdrRTFileCreate(PPKRDR ppRdr, const char *pszFilename)
{
    KSIZE       cchFilename;
    PKRDRFILE   pRdrFile;
    RTFILE      File;
    uint64_t    cb;
    int         rc;
    char        szFilename[RTPATH_MAX];

    /*
     * Open the file, determin its size and correct filename.
     */
    rc = RTFileOpen(&File, pszFilename, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
    if (RT_FAILURE(rc))
        return rc;

    rc = RTFileGetSize(File, &cb);
    if (RT_SUCCESS(rc))
    {
        rc = RTPathReal(pszFilename, szFilename, sizeof(szFilename));
        if (RT_SUCCESS(rc))
        {
            /*
             * Allocate the reader instance.
             */
            cchFilename = strlen(szFilename);
            pRdrFile = (PKRDRFILE)RTMemAlloc(sizeof(*pRdrFile) + cchFilename);
            if (pRdrFile)
            {
                /*
                 * Initialize it and return successfully.
                 */
                pRdrFile->Core.u32Magic = KRDR_MAGIC;
                pRdrFile->Core.pOps = &g_kRdrFileOps;
                pRdrFile->File = File;
                pRdrFile->cb = cb;
                pRdrFile->off = 0;
                pRdrFile->cMappings = 0;
                pRdrFile->cPreps = 0;
                memcpy(&pRdrFile->szFilename[0], szFilename, cchFilename + 1);

                *ppRdr = &pRdrFile->Core;
                return 0;
            }

            rc = KERR_NO_MEMORY;
        }
    }

    RTFileClose(File);
    return rc;
}
示例#28
0
void GuestProcessStream::Dump(const char *pszFile)
{
    LogFlowFunc(("Dumping contents of stream=0x%p (cbAlloc=%u, cbSize=%u, cbOff=%u) to %s\n",
                 m_pbBuffer, m_cbAllocated, m_cbSize, m_cbOffset, pszFile));

    RTFILE hFile;
    int rc = RTFileOpen(&hFile, pszFile, RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
    if (RT_SUCCESS(rc))
    {
        rc = RTFileWrite(hFile, m_pbBuffer, m_cbSize, NULL /* pcbWritten */);
        RTFileClose(hFile);
    }
}
示例#29
0
File::~File()
{
    if (m->flushOnClose)
    {
        RTFileFlush(m->handle);
        if (!m->strFileName.isEmpty())
            RTDirFlushParent(m->strFileName.c_str());
    }

    if (m->opened)
        RTFileClose(m->handle);
    delete m;
}
/**
 * Close and remove an open PID File.
 *
 * @param  pszPath  The path to the PID File,
 * @param  hFile    The handle for the file. NIL_RTFILE is ignored as usual.
 */
VBGLR3DECL(void) VbglR3ClosePidFile(const char *pszPath, RTFILE hFile)
{
    AssertPtrReturnVoid(pszPath);
    if (hFile != NIL_RTFILE)
    {
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
        RTFileWriteAt(hFile, 0, "-1", 2, NULL);
#else
        RTFileDelete(pszPath);
#endif
        RTFileClose(hFile);
    }
}