VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestCtrlPrivate.cpp@ 66900

Last change on this file since 66900 was 66900, checked in by vboxsync, 7 years ago

Main/GuestControl: fix iterator increment which was lost in previous change

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.9 KB
Line 
1/* $Id: GuestCtrlPrivate.cpp 66900 2017-05-15 16:30:10Z vboxsync $ */
2/** @file
3 * Internal helpers/structures for guest control functionality.
4 */
5
6/*
7 * Copyright (C) 2011-2017 Oracle Corporation
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
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#ifndef VBOX_WITH_GUEST_CONTROL
23# error "VBOX_WITH_GUEST_CONTROL must defined in this file"
24#endif
25#include "GuestCtrlImplPrivate.h"
26#include "GuestSessionImpl.h"
27#include "VMMDev.h"
28
29#include <iprt/asm.h>
30#include <iprt/cpp/utils.h> /* For unconst(). */
31#include <iprt/ctype.h>
32#ifdef DEBUG
33# include <iprt/file.h>
34#endif /* DEBUG */
35
36#ifdef LOG_GROUP
37 #undef LOG_GROUP
38#endif
39#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
40#include <VBox/log.h>
41
42
43
44int GuestFsObjData::FromLs(const GuestProcessStreamBlock &strmBlk)
45{
46 LogFlowFunc(("\n"));
47
48 int rc = VINF_SUCCESS;
49
50 try
51 {
52#ifdef DEBUG
53 strmBlk.DumpToLog();
54#endif
55 /* Object name. */
56 mName = strmBlk.GetString("name");
57 if (mName.isEmpty()) throw VERR_NOT_FOUND;
58 /* Type. */
59 Utf8Str strType(strmBlk.GetString("ftype"));
60 if (strType.equalsIgnoreCase("-"))
61 mType = FsObjType_File;
62 else if (strType.equalsIgnoreCase("d"))
63 mType = FsObjType_Directory;
64 /** @todo Add more types! */
65 else
66 mType = FsObjType_Unknown;
67 /* Object size. */
68 rc = strmBlk.GetInt64Ex("st_size", &mObjectSize);
69 if (RT_FAILURE(rc)) throw rc;
70 /** @todo Add complete ls info! */
71 }
72 catch (int rc2)
73 {
74 rc = rc2;
75 }
76
77 LogFlowFuncLeaveRC(rc);
78 return rc;
79}
80
81int GuestFsObjData::FromMkTemp(const GuestProcessStreamBlock &strmBlk)
82{
83 LogFlowFunc(("\n"));
84
85 int rc;
86
87 try
88 {
89#ifdef DEBUG
90 strmBlk.DumpToLog();
91#endif
92 /* Object name. */
93 mName = strmBlk.GetString("name");
94 if (mName.isEmpty()) throw VERR_NOT_FOUND;
95 /* Assign the stream block's rc. */
96 rc = strmBlk.GetRc();
97 }
98 catch (int rc2)
99 {
100 rc = rc2;
101 }
102
103 LogFlowFuncLeaveRC(rc);
104 return rc;
105}
106
107int GuestFsObjData::FromStat(const GuestProcessStreamBlock &strmBlk)
108{
109 LogFlowFunc(("\n"));
110
111 int rc = VINF_SUCCESS;
112
113 try
114 {
115#ifdef DEBUG
116 strmBlk.DumpToLog();
117#endif
118 /* Node ID, optional because we don't include this
119 * in older VBoxService (< 4.2) versions. */
120 mNodeID = strmBlk.GetInt64("node_id");
121 /* Object name. */
122 mName = strmBlk.GetString("name");
123 if (mName.isEmpty()) throw VERR_NOT_FOUND;
124 /* Type. */
125 Utf8Str strType(strmBlk.GetString("ftype"));
126 if (strType.equalsIgnoreCase("-"))
127 mType = FsObjType_File;
128 else if (strType.equalsIgnoreCase("d"))
129 mType = FsObjType_Directory;
130 /** @todo Add more types! */
131 else
132 mType = FsObjType_Unknown;
133 /* Object size. */
134 rc = strmBlk.GetInt64Ex("st_size", &mObjectSize);
135 if (RT_FAILURE(rc)) throw rc;
136 /** @todo Add complete stat info! */
137 }
138 catch (int rc2)
139 {
140 rc = rc2;
141 }
142
143 LogFlowFuncLeaveRC(rc);
144 return rc;
145}
146
147///////////////////////////////////////////////////////////////////////////////
148
149/** @todo *NOT* thread safe yet! */
150/** @todo Add exception handling for STL stuff! */
151
152GuestProcessStreamBlock::GuestProcessStreamBlock(void)
153{
154
155}
156
157/*
158GuestProcessStreamBlock::GuestProcessStreamBlock(const GuestProcessStreamBlock &otherBlock)
159{
160 for (GuestCtrlStreamPairsIter it = otherBlock.mPairs.begin();
161 it != otherBlock.end(); ++it)
162 {
163 mPairs[it->first] = new
164 if (it->second.pszValue)
165 {
166 RTMemFree(it->second.pszValue);
167 it->second.pszValue = NULL;
168 }
169 }
170}*/
171
172GuestProcessStreamBlock::~GuestProcessStreamBlock()
173{
174 Clear();
175}
176
177/**
178 * Destroys the currently stored stream pairs.
179 *
180 * @return IPRT status code.
181 */
182void GuestProcessStreamBlock::Clear(void)
183{
184 mPairs.clear();
185}
186
187#ifdef DEBUG
188void GuestProcessStreamBlock::DumpToLog(void) const
189{
190 LogFlowFunc(("Dumping contents of stream block=0x%p (%ld items):\n",
191 this, mPairs.size()));
192
193 for (GuestCtrlStreamPairMapIterConst it = mPairs.begin();
194 it != mPairs.end(); ++it)
195 {
196 LogFlowFunc(("\t%s=%s\n", it->first.c_str(), it->second.mValue.c_str()));
197 }
198}
199#endif
200
201/**
202 * Returns a 64-bit signed integer of a specified key.
203 *
204 * @return IPRT status code. VERR_NOT_FOUND if key was not found.
205 * @param pszKey Name of key to get the value for.
206 * @param piVal Pointer to value to return.
207 */
208int GuestProcessStreamBlock::GetInt64Ex(const char *pszKey, int64_t *piVal) const
209{
210 AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
211 AssertPtrReturn(piVal, VERR_INVALID_POINTER);
212 const char *pszValue = GetString(pszKey);
213 if (pszValue)
214 {
215 *piVal = RTStrToInt64(pszValue);
216 return VINF_SUCCESS;
217 }
218 return VERR_NOT_FOUND;
219}
220
221/**
222 * Returns a 64-bit integer of a specified key.
223 *
224 * @return int64_t Value to return, 0 if not found / on failure.
225 * @param pszKey Name of key to get the value for.
226 */
227int64_t GuestProcessStreamBlock::GetInt64(const char *pszKey) const
228{
229 int64_t iVal;
230 if (RT_SUCCESS(GetInt64Ex(pszKey, &iVal)))
231 return iVal;
232 return 0;
233}
234
235/**
236 * Returns the current number of stream pairs.
237 *
238 * @return uint32_t Current number of stream pairs.
239 */
240size_t GuestProcessStreamBlock::GetCount(void) const
241{
242 return mPairs.size();
243}
244
245/**
246 * Gets the return code (name = "rc") of this stream block.
247 *
248 * @return IPRT status code.
249 */
250int GuestProcessStreamBlock::GetRc(void) const
251{
252 const char *pszValue = GetString("rc");
253 if (pszValue)
254 {
255 return RTStrToInt16(pszValue);
256 }
257 return VERR_NOT_FOUND;
258}
259
260/**
261 * Returns a string value of a specified key.
262 *
263 * @return uint32_t Pointer to string to return, NULL if not found / on failure.
264 * @param pszKey Name of key to get the value for.
265 */
266const char* GuestProcessStreamBlock::GetString(const char *pszKey) const
267{
268 AssertPtrReturn(pszKey, NULL);
269
270 try
271 {
272 GuestCtrlStreamPairMapIterConst itPairs = mPairs.find(Utf8Str(pszKey));
273 if (itPairs != mPairs.end())
274 return itPairs->second.mValue.c_str();
275 }
276 catch (const std::exception &ex)
277 {
278 NOREF(ex);
279 }
280 return NULL;
281}
282
283/**
284 * Returns a 32-bit unsigned integer of a specified key.
285 *
286 * @return IPRT status code. VERR_NOT_FOUND if key was not found.
287 * @param pszKey Name of key to get the value for.
288 * @param puVal Pointer to value to return.
289 */
290int GuestProcessStreamBlock::GetUInt32Ex(const char *pszKey, uint32_t *puVal) const
291{
292 AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
293 AssertPtrReturn(puVal, VERR_INVALID_POINTER);
294 const char *pszValue = GetString(pszKey);
295 if (pszValue)
296 {
297 *puVal = RTStrToUInt32(pszValue);
298 return VINF_SUCCESS;
299 }
300 return VERR_NOT_FOUND;
301}
302
303/**
304 * Returns a 32-bit unsigned integer of a specified key.
305 *
306 * @return uint32_t Value to return, 0 if not found / on failure.
307 * @param pszKey Name of key to get the value for.
308 */
309uint32_t GuestProcessStreamBlock::GetUInt32(const char *pszKey) const
310{
311 uint32_t uVal;
312 if (RT_SUCCESS(GetUInt32Ex(pszKey, &uVal)))
313 return uVal;
314 return 0;
315}
316
317/**
318 * Sets a value to a key or deletes a key by setting a NULL value.
319 *
320 * @return IPRT status code.
321 * @param pszKey Key name to process.
322 * @param pszValue Value to set. Set NULL for deleting the key.
323 */
324int GuestProcessStreamBlock::SetValue(const char *pszKey, const char *pszValue)
325{
326 AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
327
328 int rc = VINF_SUCCESS;
329 try
330 {
331 Utf8Str Utf8Key(pszKey);
332
333 /* Take a shortcut and prevent crashes on some funny versions
334 * of STL if map is empty initially. */
335 if (!mPairs.empty())
336 {
337 GuestCtrlStreamPairMapIter it = mPairs.find(Utf8Key);
338 if (it != mPairs.end())
339 mPairs.erase(it);
340 }
341
342 if (pszValue)
343 {
344 GuestProcessStreamValue val(pszValue);
345 mPairs[Utf8Key] = val;
346 }
347 }
348 catch (const std::exception &ex)
349 {
350 NOREF(ex);
351 }
352 return rc;
353}
354
355///////////////////////////////////////////////////////////////////////////////
356
357GuestProcessStream::GuestProcessStream(void)
358 : m_cbAllocated(0),
359 m_cbUsed(0),
360 m_offBuffer(0),
361 m_pbBuffer(NULL)
362{
363
364}
365
366GuestProcessStream::~GuestProcessStream(void)
367{
368 Destroy();
369}
370
371/**
372 * Adds data to the internal parser buffer. Useful if there
373 * are multiple rounds of adding data needed.
374 *
375 * @return IPRT status code.
376 * @param pbData Pointer to data to add.
377 * @param cbData Size (in bytes) of data to add.
378 */
379int GuestProcessStream::AddData(const BYTE *pbData, size_t cbData)
380{
381 AssertPtrReturn(pbData, VERR_INVALID_POINTER);
382 AssertReturn(cbData, VERR_INVALID_PARAMETER);
383
384 int rc = VINF_SUCCESS;
385
386 /* Rewind the buffer if it's empty. */
387 size_t cbInBuf = m_cbUsed - m_offBuffer;
388 bool const fAddToSet = cbInBuf == 0;
389 if (fAddToSet)
390 m_cbUsed = m_offBuffer = 0;
391
392 /* Try and see if we can simply append the data. */
393 if (cbData + m_cbUsed <= m_cbAllocated)
394 {
395 memcpy(&m_pbBuffer[m_cbUsed], pbData, cbData);
396 m_cbUsed += cbData;
397 }
398 else
399 {
400 /* Move any buffered data to the front. */
401 cbInBuf = m_cbUsed - m_offBuffer;
402 if (cbInBuf == 0)
403 m_cbUsed = m_offBuffer = 0;
404 else if (m_offBuffer) /* Do we have something to move? */
405 {
406 memmove(m_pbBuffer, &m_pbBuffer[m_offBuffer], cbInBuf);
407 m_cbUsed = cbInBuf;
408 m_offBuffer = 0;
409 }
410
411 /* Do we need to grow the buffer? */
412 if (cbData + m_cbUsed > m_cbAllocated)
413 {
414/** @todo Put an upper limit on the allocation? */
415 size_t cbAlloc = m_cbUsed + cbData;
416 cbAlloc = RT_ALIGN_Z(cbAlloc, _64K);
417 void *pvNew = RTMemRealloc(m_pbBuffer, cbAlloc);
418 if (pvNew)
419 {
420 m_pbBuffer = (uint8_t *)pvNew;
421 m_cbAllocated = cbAlloc;
422 }
423 else
424 rc = VERR_NO_MEMORY;
425 }
426
427 /* Finally, copy the data. */
428 if (RT_SUCCESS(rc))
429 {
430 if (cbData + m_cbUsed <= m_cbAllocated)
431 {
432 memcpy(&m_pbBuffer[m_cbUsed], pbData, cbData);
433 m_cbUsed += cbData;
434 }
435 else
436 rc = VERR_BUFFER_OVERFLOW;
437 }
438 }
439
440 return rc;
441}
442
443/**
444 * Destroys the internal data buffer.
445 */
446void GuestProcessStream::Destroy(void)
447{
448 if (m_pbBuffer)
449 {
450 RTMemFree(m_pbBuffer);
451 m_pbBuffer = NULL;
452 }
453
454 m_cbAllocated = 0;
455 m_cbUsed = 0;
456 m_offBuffer = 0;
457}
458
459#ifdef DEBUG
460void GuestProcessStream::Dump(const char *pszFile)
461{
462 LogFlowFunc(("Dumping contents of stream=0x%p (cbAlloc=%u, cbSize=%u, cbOff=%u) to %s\n",
463 m_pbBuffer, m_cbAllocated, m_cbUsed, m_offBuffer, pszFile));
464
465 RTFILE hFile;
466 int rc = RTFileOpen(&hFile, pszFile, RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
467 if (RT_SUCCESS(rc))
468 {
469 rc = RTFileWrite(hFile, m_pbBuffer, m_cbUsed, NULL /* pcbWritten */);
470 RTFileClose(hFile);
471 }
472}
473#endif
474
475/**
476 * Tries to parse the next upcoming pair block within the internal
477 * buffer.
478 *
479 * Returns VERR_NO_DATA is no data is in internal buffer or buffer has been
480 * completely parsed already.
481 *
482 * Returns VERR_MORE_DATA if current block was parsed (with zero or more pairs
483 * stored in stream block) but still contains incomplete (unterminated)
484 * data.
485 *
486 * Returns VINF_SUCCESS if current block was parsed until the next upcoming
487 * block (with zero or more pairs stored in stream block).
488 *
489 * @return IPRT status code.
490 * @param streamBlock Reference to guest stream block to fill.
491 *
492 */
493int GuestProcessStream::ParseBlock(GuestProcessStreamBlock &streamBlock)
494{
495 if ( !m_pbBuffer
496 || !m_cbUsed)
497 {
498 return VERR_NO_DATA;
499 }
500
501 AssertReturn(m_offBuffer <= m_cbUsed, VERR_INVALID_PARAMETER);
502 if (m_offBuffer == m_cbUsed)
503 return VERR_NO_DATA;
504
505 int rc = VINF_SUCCESS;
506
507 char *pszOff = (char*)&m_pbBuffer[m_offBuffer];
508 char *pszStart = pszOff;
509 uint32_t uDistance;
510 while (*pszStart)
511 {
512 size_t pairLen = strlen(pszStart);
513 uDistance = (pszStart - pszOff);
514 if (m_offBuffer + uDistance + pairLen + 1 >= m_cbUsed)
515 {
516 rc = VERR_MORE_DATA;
517 break;
518 }
519 else
520 {
521 char *pszSep = strchr(pszStart, '=');
522 char *pszVal = NULL;
523 if (pszSep)
524 pszVal = pszSep + 1;
525 if (!pszSep || !pszVal)
526 {
527 rc = VERR_MORE_DATA;
528 break;
529 }
530
531 /* Terminate the separator so that we can
532 * use pszStart as our key from now on. */
533 *pszSep = '\0';
534
535 rc = streamBlock.SetValue(pszStart, pszVal);
536 if (RT_FAILURE(rc))
537 return rc;
538 }
539
540 /* Next pair. */
541 pszStart += pairLen + 1;
542 }
543
544 /* If we did not do any movement but we have stuff left
545 * in our buffer just skip the current termination so that
546 * we can try next time. */
547 uDistance = (pszStart - pszOff);
548 if ( !uDistance
549 && *pszStart == '\0'
550 && m_offBuffer < m_cbUsed)
551 {
552 uDistance++;
553 }
554 m_offBuffer += uDistance;
555
556 return rc;
557}
558
559GuestBase::GuestBase(void)
560 : mConsole(NULL),
561 mNextContextID(0)
562{
563}
564
565GuestBase::~GuestBase(void)
566{
567}
568
569int GuestBase::baseInit(void)
570{
571 int rc = RTCritSectInit(&mWaitEventCritSect);
572
573 LogFlowFuncLeaveRC(rc);
574 return rc;
575}
576
577void GuestBase::baseUninit(void)
578{
579 LogFlowThisFuncEnter();
580
581 int rc = RTCritSectDelete(&mWaitEventCritSect);
582 NOREF(rc);
583
584 LogFlowFuncLeaveRC(rc);
585 /* No return value. */
586}
587
588int GuestBase::cancelWaitEvents(void)
589{
590 LogFlowThisFuncEnter();
591
592 int rc = RTCritSectEnter(&mWaitEventCritSect);
593 if (RT_SUCCESS(rc))
594 {
595 GuestEventGroup::iterator itEventGroups = mWaitEventGroups.begin();
596 while (itEventGroups != mWaitEventGroups.end())
597 {
598 GuestWaitEvents::iterator itEvents = itEventGroups->second.begin();
599 while (itEvents != itEventGroups->second.end())
600 {
601 GuestWaitEvent *pEvent = itEvents->second;
602 AssertPtr(pEvent);
603
604 /*
605 * Just cancel the event, but don't remove it from the
606 * wait events map. Don't delete it though, this (hopefully)
607 * is done by the caller using unregisterWaitEvent().
608 */
609 int rc2 = pEvent->Cancel();
610 AssertRC(rc2);
611
612 ++itEvents;
613 }
614
615 ++itEventGroups;
616 }
617
618 int rc2 = RTCritSectLeave(&mWaitEventCritSect);
619 if (RT_SUCCESS(rc))
620 rc = rc2;
621 }
622
623 LogFlowFuncLeaveRC(rc);
624 return rc;
625}
626
627int GuestBase::dispatchGeneric(PVBOXGUESTCTRLHOSTCBCTX pCtxCb, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
628{
629 LogFlowFunc(("pCtxCb=%p, pSvcCb=%p\n", pCtxCb, pSvcCb));
630
631 AssertPtrReturn(pCtxCb, VERR_INVALID_POINTER);
632 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
633
634 int vrc = VINF_SUCCESS;
635
636 try
637 {
638 LogFlowFunc(("uFunc=%RU32, cParms=%RU32\n",
639 pCtxCb->uFunction, pSvcCb->mParms));
640
641 switch (pCtxCb->uFunction)
642 {
643 case GUEST_MSG_PROGRESS_UPDATE:
644 break;
645
646 case GUEST_MSG_REPLY:
647 {
648 if (pSvcCb->mParms >= 3)
649 {
650 int idx = 1; /* Current parameter index. */
651 CALLBACKDATA_MSG_REPLY dataCb;
652 /* pSvcCb->mpaParms[0] always contains the context ID. */
653 vrc = pSvcCb->mpaParms[idx++].getUInt32(&dataCb.uType);
654 AssertRCReturn(vrc, vrc);
655 vrc = pSvcCb->mpaParms[idx++].getUInt32(&dataCb.rc);
656 AssertRCReturn(vrc, vrc);
657 vrc = pSvcCb->mpaParms[idx++].getPointer(&dataCb.pvPayload, &dataCb.cbPayload);
658 AssertRCReturn(vrc, vrc);
659
660 GuestWaitEventPayload evPayload(dataCb.uType, dataCb.pvPayload, dataCb.cbPayload);
661 int rc2 = signalWaitEventInternal(pCtxCb, dataCb.rc, &evPayload);
662 AssertRC(rc2);
663 }
664 else
665 vrc = VERR_INVALID_PARAMETER;
666 break;
667 }
668
669 default:
670 vrc = VERR_NOT_SUPPORTED;
671 break;
672 }
673 }
674 catch (std::bad_alloc)
675 {
676 vrc = VERR_NO_MEMORY;
677 }
678 catch (int rc)
679 {
680 vrc = rc;
681 }
682
683 LogFlowFuncLeaveRC(vrc);
684 return vrc;
685}
686
687int GuestBase::generateContextID(uint32_t uSessionID, uint32_t uObjectID, uint32_t *puContextID)
688{
689 AssertPtrReturn(puContextID, VERR_INVALID_POINTER);
690
691 if ( uSessionID >= VBOX_GUESTCTRL_MAX_SESSIONS
692 || uObjectID >= VBOX_GUESTCTRL_MAX_OBJECTS)
693 return VERR_INVALID_PARAMETER;
694
695 uint32_t uCount = ASMAtomicIncU32(&mNextContextID);
696 if (uCount == VBOX_GUESTCTRL_MAX_CONTEXTS)
697 uCount = 0;
698
699 uint32_t uNewContextID =
700 VBOX_GUESTCTRL_CONTEXTID_MAKE(uSessionID, uObjectID, uCount);
701
702 *puContextID = uNewContextID;
703
704#if 0
705 LogFlowThisFunc(("mNextContextID=%RU32, uSessionID=%RU32, uObjectID=%RU32, uCount=%RU32, uNewContextID=%RU32\n",
706 mNextContextID, uSessionID, uObjectID, uCount, uNewContextID));
707#endif
708 return VINF_SUCCESS;
709}
710
711int GuestBase::registerWaitEvent(uint32_t uSessionID, uint32_t uObjectID,
712 GuestWaitEvent **ppEvent)
713{
714 GuestEventTypes eventTypesEmpty;
715 return registerWaitEvent(uSessionID, uObjectID, eventTypesEmpty, ppEvent);
716}
717
718/**
719 * Registers (creates) a new wait event based on a given session and object ID.
720 *
721 * From those IDs an unique context ID (CID) will be built, which only can be
722 * around once at a time.
723 *
724 * @returns IPRT status code. VERR_ALREADY_EXISTS if an event with the given session
725 * and object ID already has been registered.
726 *
727 * @param uSessionID Session ID to register wait event for.
728 * @param uObjectID Object ID to register wait event for.
729 * @param lstEvents List of events to register the wait event for.
730 * @param ppEvent Pointer to registered (created) wait event on success.
731 * Must be destroyed with unregisterWaitEvent().
732 */
733int GuestBase::registerWaitEvent(uint32_t uSessionID, uint32_t uObjectID,
734 const GuestEventTypes &lstEvents,
735 GuestWaitEvent **ppEvent)
736{
737 AssertPtrReturn(ppEvent, VERR_INVALID_POINTER);
738
739 uint32_t uContextID;
740 int rc = generateContextID(uSessionID, uObjectID, &uContextID);
741 if (RT_FAILURE(rc))
742 return rc;
743
744 rc = RTCritSectEnter(&mWaitEventCritSect);
745 if (RT_SUCCESS(rc))
746 {
747 try
748 {
749 GuestWaitEvent *pEvent = new GuestWaitEvent(uContextID, lstEvents);
750 AssertPtr(pEvent);
751
752 LogFlowThisFunc(("New event=%p, CID=%RU32\n", pEvent, uContextID));
753
754 /* Insert event into matching event group. This is for faster per-group
755 * lookup of all events later. */
756 for (GuestEventTypes::const_iterator itEvents = lstEvents.begin();
757 itEvents != lstEvents.end(); ++itEvents)
758 {
759 /* Check if the event group already has an event with the same
760 * context ID in it (collision). */
761 GuestWaitEvents eventGroup = mWaitEventGroups[(*itEvents)];
762 if (eventGroup.find(uContextID) == eventGroup.end())
763 {
764 /* No, insert. */
765 mWaitEventGroups[(*itEvents)].insert(std::pair<uint32_t, GuestWaitEvent *>(uContextID, pEvent));
766 }
767 else
768 {
769 rc = VERR_ALREADY_EXISTS;
770 break;
771 }
772 }
773
774 if (RT_SUCCESS(rc))
775 {
776 /* Register event in regular event list. */
777 if (mWaitEvents.find(uContextID) == mWaitEvents.end())
778 {
779 mWaitEvents[uContextID] = pEvent;
780 }
781 else
782 rc = VERR_ALREADY_EXISTS;
783 }
784
785 if (RT_SUCCESS(rc))
786 *ppEvent = pEvent;
787 }
788 catch(std::bad_alloc &)
789 {
790 rc = VERR_NO_MEMORY;
791 }
792
793 int rc2 = RTCritSectLeave(&mWaitEventCritSect);
794 if (RT_SUCCESS(rc))
795 rc = rc2;
796 }
797
798 return rc;
799}
800
801int GuestBase::signalWaitEvent(VBoxEventType_T aType, IEvent *aEvent)
802{
803 int rc = RTCritSectEnter(&mWaitEventCritSect);
804#ifdef DEBUG
805 uint32_t cEvents = 0;
806#endif
807 if (RT_SUCCESS(rc))
808 {
809 GuestEventGroup::iterator itGroup = mWaitEventGroups.find(aType);
810 if (itGroup != mWaitEventGroups.end())
811 {
812 GuestWaitEvents::iterator itEvents = itGroup->second.begin();
813 while (itEvents != itGroup->second.end())
814 {
815#ifdef DEBUG
816 LogFlowThisFunc(("Signalling event=%p, type=%ld (CID %RU32: Session=%RU32, Object=%RU32, Count=%RU32) ...\n",
817 itEvents->second, aType, itEvents->first,
818 VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(itEvents->first),
819 VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(itEvents->first),
820 VBOX_GUESTCTRL_CONTEXTID_GET_COUNT(itEvents->first)));
821#endif
822 ComPtr<IEvent> pThisEvent = aEvent;
823 Assert(!pThisEvent.isNull());
824 int rc2 = itEvents->second->SignalExternal(aEvent);
825 if (RT_SUCCESS(rc))
826 rc = rc2;
827
828 if (RT_SUCCESS(rc2))
829 {
830 /* Remove the event from all other event groups (except the
831 * original one!) because it was signalled. */
832 AssertPtr(itEvents->second);
833 const GuestEventTypes evTypes = itEvents->second->Types();
834 for (GuestEventTypes::const_iterator itType = evTypes.begin();
835 itType != evTypes.end(); ++itType)
836 {
837 if ((*itType) != aType) /* Only remove all other groups. */
838 {
839 /* Get current event group. */
840 GuestEventGroup::iterator evGroup = mWaitEventGroups.find((*itType));
841 Assert(evGroup != mWaitEventGroups.end());
842
843 /* Lookup event in event group. */
844 GuestWaitEvents::iterator evEvent = evGroup->second.find(itEvents->first /* Context ID */);
845 Assert(evEvent != evGroup->second.end());
846
847 LogFlowThisFunc(("Removing event=%p (type %ld)\n", evEvent->second, (*itType)));
848 evGroup->second.erase(evEvent);
849
850 LogFlowThisFunc(("%zu events for type=%ld left\n",
851 evGroup->second.size(), aType));
852 }
853 }
854
855 /* Remove the event from the passed-in event group. */
856 GuestWaitEvents::iterator itEventsNext = itEvents;
857 ++itEventsNext;
858 itGroup->second.erase(itEvents);
859 itEvents = itEventsNext;
860 }
861 else
862 ++itEvents;
863#ifdef DEBUG
864 cEvents++;
865#endif
866 }
867 }
868
869 int rc2 = RTCritSectLeave(&mWaitEventCritSect);
870 if (RT_SUCCESS(rc))
871 rc = rc2;
872 }
873
874#ifdef DEBUG
875 LogFlowThisFunc(("Signalled %RU32 events, rc=%Rrc\n", cEvents, rc));
876#endif
877 return rc;
878}
879
880int GuestBase::signalWaitEventInternal(PVBOXGUESTCTRLHOSTCBCTX pCbCtx,
881 int guestRc, const GuestWaitEventPayload *pPayload)
882{
883 if (RT_SUCCESS(guestRc))
884 return signalWaitEventInternalEx(pCbCtx, VINF_SUCCESS,
885 0 /* Guest rc */, pPayload);
886
887 return signalWaitEventInternalEx(pCbCtx, VERR_GSTCTL_GUEST_ERROR,
888 guestRc, pPayload);
889}
890
891int GuestBase::signalWaitEventInternalEx(PVBOXGUESTCTRLHOSTCBCTX pCbCtx,
892 int rc, int guestRc,
893 const GuestWaitEventPayload *pPayload)
894{
895 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
896 /* pPayload is optional. */
897
898 int rc2 = RTCritSectEnter(&mWaitEventCritSect);
899 if (RT_SUCCESS(rc2))
900 {
901 GuestWaitEvents::iterator itEvent = mWaitEvents.find(pCbCtx->uContextID);
902 if (itEvent != mWaitEvents.end())
903 {
904 LogFlowThisFunc(("Signalling event=%p (CID %RU32, rc=%Rrc, guestRc=%Rrc, pPayload=%p) ...\n",
905 itEvent->second, itEvent->first, rc, guestRc, pPayload));
906 GuestWaitEvent *pEvent = itEvent->second;
907 AssertPtr(pEvent);
908 rc2 = pEvent->SignalInternal(rc, guestRc, pPayload);
909 }
910 else
911 rc2 = VERR_NOT_FOUND;
912
913 int rc3 = RTCritSectLeave(&mWaitEventCritSect);
914 if (RT_SUCCESS(rc2))
915 rc2 = rc3;
916 }
917
918 return rc2;
919}
920
921/**
922 * Unregisters (deletes) a wait event.
923 *
924 * After successful unregistration the event will not be valid anymore.
925 *
926 * @returns IPRT status code.
927 * @param pEvent Event to unregister (delete).
928 */
929int GuestBase::unregisterWaitEvent(GuestWaitEvent *pEvent)
930{
931 if (!pEvent) /* Nothing to unregister. */
932 return VINF_SUCCESS;
933
934 int rc = RTCritSectEnter(&mWaitEventCritSect);
935 if (RT_SUCCESS(rc))
936 {
937 LogFlowThisFunc(("pEvent=%p\n", pEvent));
938
939 try
940 {
941 /* Remove the event from all event type groups. */
942 const GuestEventTypes lstTypes = pEvent->Types();
943 for (GuestEventTypes::const_iterator itType = lstTypes.begin();
944 itType != lstTypes.end(); ++itType)
945 {
946 /** @todo Slow O(n) lookup. Optimize this. */
947 GuestWaitEvents::iterator itCurEvent = mWaitEventGroups[(*itType)].begin();
948 while (itCurEvent != mWaitEventGroups[(*itType)].end())
949 {
950 if (itCurEvent->second == pEvent)
951 {
952 mWaitEventGroups[(*itType)].erase(itCurEvent);
953 break;
954 }
955 else
956 ++itCurEvent;
957 }
958 }
959
960 /* Remove the event from the general event list as well. */
961 GuestWaitEvents::iterator itEvent = mWaitEvents.find(pEvent->ContextID());
962
963 Assert(itEvent != mWaitEvents.end());
964 Assert(itEvent->second == pEvent);
965
966 mWaitEvents.erase(itEvent);
967
968 delete pEvent;
969 pEvent = NULL;
970 }
971 catch (const std::exception &ex)
972 {
973 NOREF(ex);
974 AssertFailedStmt(rc = VERR_NOT_FOUND);
975 }
976
977 int rc2 = RTCritSectLeave(&mWaitEventCritSect);
978 if (RT_SUCCESS(rc))
979 rc = rc2;
980 }
981
982 return rc;
983}
984
985/**
986 * Waits for a formerly registered guest event.
987 *
988 * @return IPRT status code.
989 * @param pEvent Pointer to event to wait for.
990 * @param uTimeoutMS Timeout (in ms) for waiting.
991 * @param pType Event type of following IEvent.
992 * Optional.
993 * @param ppEvent Pointer to IEvent which got triggered
994 * for this event. Optional.
995 */
996int GuestBase::waitForEvent(GuestWaitEvent *pEvent, uint32_t uTimeoutMS,
997 VBoxEventType_T *pType, IEvent **ppEvent)
998{
999 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1000 /* pType is optional. */
1001 /* ppEvent is optional. */
1002
1003 int vrc = pEvent->Wait(uTimeoutMS);
1004 if (RT_SUCCESS(vrc))
1005 {
1006 const ComPtr<IEvent> pThisEvent = pEvent->Event();
1007 if (!pThisEvent.isNull()) /* Having a VBoxEventType_ event is optional. */
1008 {
1009 if (pType)
1010 {
1011 HRESULT hr = pThisEvent->COMGETTER(Type)(pType);
1012 if (FAILED(hr))
1013 vrc = VERR_COM_UNEXPECTED;
1014 }
1015 if ( RT_SUCCESS(vrc)
1016 && ppEvent)
1017 pThisEvent.queryInterfaceTo(ppEvent);
1018
1019 unconst(pThisEvent).setNull();
1020 }
1021 }
1022
1023 return vrc;
1024}
1025
1026GuestObject::GuestObject(void)
1027 : mSession(NULL),
1028 mObjectID(0)
1029{
1030}
1031
1032GuestObject::~GuestObject(void)
1033{
1034}
1035
1036int GuestObject::bindToSession(Console *pConsole, GuestSession *pSession, uint32_t uObjectID)
1037{
1038 AssertPtrReturn(pConsole, VERR_INVALID_POINTER);
1039 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1040
1041 mConsole = pConsole;
1042 mSession = pSession;
1043 mObjectID = uObjectID;
1044
1045 return VINF_SUCCESS;
1046}
1047
1048int GuestObject::registerWaitEvent(const GuestEventTypes &lstEvents,
1049 GuestWaitEvent **ppEvent)
1050{
1051 AssertPtr(mSession);
1052 return GuestBase::registerWaitEvent(mSession->i_getId(), mObjectID, lstEvents, ppEvent);
1053}
1054
1055int GuestObject::sendCommand(uint32_t uFunction,
1056 uint32_t cParms, PVBOXHGCMSVCPARM paParms)
1057{
1058#ifndef VBOX_GUESTCTRL_TEST_CASE
1059 ComObjPtr<Console> pConsole = mConsole;
1060 Assert(!pConsole.isNull());
1061
1062 int vrc = VERR_HGCM_SERVICE_NOT_FOUND;
1063
1064 /* Forward the information to the VMM device. */
1065 VMMDev *pVMMDev = pConsole->i_getVMMDev();
1066 if (pVMMDev)
1067 {
1068 LogFlowThisFunc(("uFunction=%RU32, cParms=%RU32\n", uFunction, cParms));
1069 vrc = pVMMDev->hgcmHostCall(HGCMSERVICE_NAME, uFunction, cParms, paParms);
1070 if (RT_FAILURE(vrc))
1071 {
1072 /** @todo What to do here? */
1073 }
1074 }
1075#else
1076 LogFlowThisFuncEnter();
1077
1078 /* Not needed within testcases. */
1079 RT_NOREF(uFunction, cParms, paParms);
1080 int vrc = VINF_SUCCESS;
1081#endif
1082 return vrc;
1083}
1084
1085GuestWaitEventBase::GuestWaitEventBase(void)
1086 : mfAborted(false),
1087 mCID(0),
1088 mEventSem(NIL_RTSEMEVENT),
1089 mRc(VINF_SUCCESS),
1090 mGuestRc(VINF_SUCCESS)
1091{
1092}
1093
1094GuestWaitEventBase::~GuestWaitEventBase(void)
1095{
1096 if (mEventSem != NIL_RTSEMEVENT)
1097 {
1098 RTSemEventDestroy(mEventSem);
1099 mEventSem = NIL_RTSEMEVENT;
1100 }
1101}
1102
1103int GuestWaitEventBase::Init(uint32_t uCID)
1104{
1105 mCID = uCID;
1106
1107 return RTSemEventCreate(&mEventSem);
1108}
1109
1110int GuestWaitEventBase::SignalInternal(int rc, int guestRc,
1111 const GuestWaitEventPayload *pPayload)
1112{
1113 if (ASMAtomicReadBool(&mfAborted))
1114 return VERR_CANCELLED;
1115
1116#ifdef VBOX_STRICT
1117 if (rc == VERR_GSTCTL_GUEST_ERROR)
1118 AssertMsg(RT_FAILURE(guestRc), ("Guest error indicated but no actual guest error set (%Rrc)\n", guestRc));
1119 else
1120 AssertMsg(RT_SUCCESS(guestRc), ("No guest error indicated but actual guest error set (%Rrc)\n", guestRc));
1121#endif
1122
1123 int rc2;
1124 if (pPayload)
1125 rc2 = mPayload.CopyFromDeep(*pPayload);
1126 else
1127 rc2 = VINF_SUCCESS;
1128 if (RT_SUCCESS(rc2))
1129 {
1130 mRc = rc;
1131 mGuestRc = guestRc;
1132
1133 rc2 = RTSemEventSignal(mEventSem);
1134 }
1135
1136 return rc2;
1137}
1138
1139int GuestWaitEventBase::Wait(RTMSINTERVAL uTimeoutMS)
1140{
1141 int rc = VINF_SUCCESS;
1142
1143 if (ASMAtomicReadBool(&mfAborted))
1144 rc = VERR_CANCELLED;
1145
1146 if (RT_SUCCESS(rc))
1147 {
1148 AssertReturn(mEventSem != NIL_RTSEMEVENT, VERR_CANCELLED);
1149
1150 RTMSINTERVAL msInterval = uTimeoutMS;
1151 if (!uTimeoutMS)
1152 msInterval = RT_INDEFINITE_WAIT;
1153 rc = RTSemEventWait(mEventSem, msInterval);
1154 if (ASMAtomicReadBool(&mfAborted))
1155 rc = VERR_CANCELLED;
1156 if (RT_SUCCESS(rc))
1157 {
1158 /* If waiting succeeded, return the overall
1159 * result code. */
1160 rc = mRc;
1161 }
1162 }
1163
1164 return rc;
1165}
1166
1167GuestWaitEvent::GuestWaitEvent(uint32_t uCID,
1168 const GuestEventTypes &lstEvents)
1169{
1170 int rc2 = Init(uCID);
1171 AssertRC(rc2); /** @todo Throw exception here. */
1172
1173 mEventTypes = lstEvents;
1174}
1175
1176GuestWaitEvent::GuestWaitEvent(uint32_t uCID)
1177{
1178 int rc2 = Init(uCID);
1179 AssertRC(rc2); /** @todo Throw exception here. */
1180}
1181
1182GuestWaitEvent::~GuestWaitEvent(void)
1183{
1184
1185}
1186
1187/**
1188 * Cancels the event.
1189 */
1190int GuestWaitEvent::Cancel(void)
1191{
1192 AssertReturn(!mfAborted, VERR_CANCELLED);
1193 ASMAtomicWriteBool(&mfAborted, true);
1194
1195#ifdef DEBUG_andy
1196 LogFlowThisFunc(("Cancelling %p ...\n"));
1197#endif
1198 return RTSemEventSignal(mEventSem);
1199}
1200
1201int GuestWaitEvent::Init(uint32_t uCID)
1202{
1203 return GuestWaitEventBase::Init(uCID);
1204}
1205
1206/**
1207 * Signals the event.
1208 *
1209 * @return IPRT status code.
1210 * @param pEvent Public IEvent to associate.
1211 * Optional.
1212 */
1213int GuestWaitEvent::SignalExternal(IEvent *pEvent)
1214{
1215 AssertReturn(mEventSem != NIL_RTSEMEVENT, VERR_CANCELLED);
1216
1217 if (pEvent)
1218 mEvent = pEvent;
1219
1220 return RTSemEventSignal(mEventSem);
1221}
1222
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