summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-server/DataStreamImpl.cpp
blob: 6b7d82433a703f1cc52789fd75ee9273a202723d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/* $Id: DataStreamImpl.cpp $ */
/** @file
 * VirtualBox COM class implementation - DataStream
 */

/*
 * Copyright (C) 2018-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_MAIN_DATASTREAM
#include "DataStreamImpl.h"

#include "AutoCaller.h"
#include "LoggingNew.h"
#include <iprt/errcore.h>


/*********************************************************************************************************************************
*   Boilerplate constructor & destructor                                                                                         *
*********************************************************************************************************************************/

DEFINE_EMPTY_CTOR_DTOR(DataStream)

HRESULT DataStream::FinalConstruct()
{
    LogFlowThisFunc(("\n"));
    return BaseFinalConstruct();
}

void DataStream::FinalRelease()
{
    LogFlowThisFuncEnter();
    uninit();
    BaseFinalRelease();
    LogFlowThisFuncLeave();
}


/*********************************************************************************************************************************
*   Initializer & uninitializer                                                                                                  *
*********************************************************************************************************************************/

/**
 * Initializes the DataStream object.
 *
 * @param   aBufferSize     Size of the intermediate buffer.
 *
 */
HRESULT DataStream::init(unsigned long aBufferSize)
{
    LogFlowThisFunc(("cbBuffer=%zu\n", aBufferSize));

    /*
     * Enclose the state transition NotReady->InInit->Ready
     */
    AutoInitSpan autoInitSpan(this);
    AssertReturn(autoInitSpan.isOk(), E_FAIL);

    /*
     * Allocate data instance.
     */
    HRESULT hrc = S_OK;

    m_hSemEvtDataAvail   = NIL_RTSEMEVENT;
    m_hSemEvtBufSpcAvail = NIL_RTSEMEVENT;
    m_pBuffer            = NULL;
    m_fEos               = false;
    int vrc = RTSemEventCreate(&m_hSemEvtDataAvail);
    if (RT_SUCCESS(vrc))
        vrc = RTSemEventCreate(&m_hSemEvtBufSpcAvail);
    if (RT_SUCCESS(vrc))
        vrc = RTCircBufCreate(&m_pBuffer, aBufferSize);

    if (RT_FAILURE(vrc))
        hrc = setErrorBoth(E_FAIL, vrc, tr("Failed to initialize data stream object (%Rrc)"), vrc);

    /*
     * Done. Just update object readiness state.
     */
    if (SUCCEEDED(hrc))
        autoInitSpan.setSucceeded();
    else
        autoInitSpan.setFailed(hrc);

    LogFlowThisFunc(("returns %Rhrc\n", hrc));
    return hrc;
}

/**
 * Uninitializes the instance (called from FinalRelease()).
 */
void DataStream::uninit()
{
    LogFlowThisFuncEnter();

    /* Enclose the state transition Ready->InUninit->NotReady */
    AutoUninitSpan autoUninitSpan(this);
    if (!autoUninitSpan.uninitDone())
    {
        if (m_hSemEvtDataAvail != NIL_RTSEMEVENT)
            RTSemEventDestroy(m_hSemEvtDataAvail);
        if (m_hSemEvtBufSpcAvail != NIL_RTSEMEVENT)
            RTSemEventDestroy(m_hSemEvtBufSpcAvail);
        if (m_pBuffer != NULL)
            RTCircBufDestroy(m_pBuffer);
        m_hSemEvtDataAvail = NIL_RTSEMEVENT;
        m_hSemEvtBufSpcAvail = NIL_RTSEMEVENT;
    }

    LogFlowThisFuncLeave();
}


/*********************************************************************************************************************************
*   IDataStream attributes                                                                                                       *
*********************************************************************************************************************************/

HRESULT DataStream::getReadSize(ULONG *aReadSize)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
    *aReadSize = (ULONG)RTCircBufUsed(m_pBuffer);
    return S_OK;
}


/*********************************************************************************************************************************
*   IDataStream methods                                                                                                          *
*********************************************************************************************************************************/

HRESULT DataStream::read(ULONG aSize, ULONG aTimeoutMS, std::vector<BYTE> &aData)
{
    /*
     * Allocate return buffer.
     */
    try
    {
        aData.resize(aSize);
    }
    catch (std::bad_alloc &)
    {
        return E_OUTOFMEMORY;
    }

    /*
     * Do the reading.  To play safe we exclusivly lock the object while doing this.
     */
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    int vrc = VINF_SUCCESS;
    while (   !RTCircBufUsed(m_pBuffer)
           && !m_fEos
           && RT_SUCCESS(vrc))
    {
        /* Wait for something to become available. */
        alock.release();
        vrc = RTSemEventWait(m_hSemEvtDataAvail, aTimeoutMS == 0 ? RT_INDEFINITE_WAIT : aTimeoutMS);
        alock.acquire();
    }

    /*
     * Manage the result.
     */
    HRESULT hrc = S_OK;
    if (   RT_SUCCESS(vrc)
        && RTCircBufUsed(m_pBuffer))
    {

        size_t off = 0;
        size_t cbCopy = RT_MIN(aSize, RTCircBufUsed(m_pBuffer));
        if (cbCopy != aSize)
        {
            Assert(cbCopy < aSize);
            aData.resize(cbCopy);
        }

        while (cbCopy)
        {
            void *pvSrc = NULL;
            size_t cbThisCopy = 0;

            RTCircBufAcquireReadBlock(m_pBuffer, cbCopy, &pvSrc, &cbThisCopy);
            memcpy(&aData.front() + off, pvSrc, cbThisCopy);
            RTCircBufReleaseReadBlock(m_pBuffer, cbThisCopy);

            cbCopy -= cbThisCopy;
            off    += cbThisCopy;
        }
        vrc = RTSemEventSignal(m_hSemEvtBufSpcAvail);
        AssertRC(vrc);
    }
    else
    {
        Assert(   RT_FAILURE(vrc)
               || (   m_fEos
                   && !RTCircBufUsed(m_pBuffer)));

        aData.resize(0);
        if (vrc == VERR_TIMEOUT)
            hrc = VBOX_E_TIMEOUT;
        else if (RT_FAILURE(vrc))
            hrc = setErrorBoth(E_FAIL, vrc, tr("Error reading %u bytes: %Rrc", "", aSize), aSize, vrc);
    }

    return hrc;
}


/*********************************************************************************************************************************
*   DataStream internal methods                                                                                                  *
*********************************************************************************************************************************/

/**
 * Writes the given data into the temporary buffer blocking if it is full.
 *
 * @returns IPRT status code.
 * @param   pvBuf           The data to write.
 * @param   cbWrite         How much to write.
 * @param   pcbWritten      Where to store the amount of data written.
 */
int DataStream::i_write(const void *pvBuf, size_t cbWrite, size_t *pcbWritten)
{
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
    AssertReturn(!m_fEos, VERR_INVALID_STATE);

    *pcbWritten = 0;

    int vrc = VINF_SUCCESS;
    while (   !RTCircBufFree(m_pBuffer)
           && RT_SUCCESS(vrc))
    {
        /* Wait for space to become available. */
        alock.release();
        vrc = RTSemEventWait(m_hSemEvtBufSpcAvail, RT_INDEFINITE_WAIT);
        alock.acquire();
    }

    if (RT_SUCCESS(vrc))
    {
        const uint8_t *pbBuf = (const uint8_t *)pvBuf;
        size_t cbCopy = RT_MIN(cbWrite, RTCircBufFree(m_pBuffer));

        *pcbWritten = cbCopy;

        while (cbCopy)
        {
            void *pvDst = NULL;
            size_t cbThisCopy = 0;

            RTCircBufAcquireWriteBlock(m_pBuffer, cbCopy, &pvDst, &cbThisCopy);
            memcpy(pvDst, pbBuf, cbThisCopy);
            RTCircBufReleaseWriteBlock(m_pBuffer, cbThisCopy);

            cbCopy -= cbThisCopy;
            pbBuf  += cbThisCopy;
        }

        RTSemEventSignal(m_hSemEvtDataAvail);
    }

    return vrc;
}

/**
 * Marks the end of the stream.
 *
 * @returns IPRT status code.
 */
int DataStream::i_close()
{
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
    m_fEos = true;
    RTSemEventSignal(m_hSemEvtDataAvail);
    return VINF_SUCCESS;
}