VirtualBox

source: vbox/trunk/src/VBox/Main/GuestImpl.cpp@ 30020

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

Guest Control/Main: Get rid of busy waiting, use multi stage progress objects, clean up temporary callback contexts.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 50.9 KB
Line 
1/* $Id: GuestImpl.cpp 30020 2010-06-04 08:09:58Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM class implementation
6 */
7
8/*
9 * Copyright (C) 2006-2008 Oracle Corporation
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 */
19
20#include "GuestImpl.h"
21
22#include "Global.h"
23#include "ConsoleImpl.h"
24#include "ProgressImpl.h"
25#include "VMMDev.h"
26
27#include "AutoCaller.h"
28#include "Logging.h"
29
30#include <VBox/VMMDev.h>
31#ifdef VBOX_WITH_GUEST_CONTROL
32# include <VBox/com/array.h>
33#endif
34#include <iprt/cpp/utils.h>
35#include <iprt/getopt.h>
36#include <VBox/pgm.h>
37
38// defines
39/////////////////////////////////////////////////////////////////////////////
40
41// constructor / destructor
42/////////////////////////////////////////////////////////////////////////////
43
44DEFINE_EMPTY_CTOR_DTOR (Guest)
45
46HRESULT Guest::FinalConstruct()
47{
48 return S_OK;
49}
50
51void Guest::FinalRelease()
52{
53 uninit ();
54}
55
56// public methods only for internal purposes
57/////////////////////////////////////////////////////////////////////////////
58
59/**
60 * Initializes the guest object.
61 */
62HRESULT Guest::init (Console *aParent)
63{
64 LogFlowThisFunc(("aParent=%p\n", aParent));
65
66 ComAssertRet(aParent, E_INVALIDARG);
67
68 /* Enclose the state transition NotReady->InInit->Ready */
69 AutoInitSpan autoInitSpan(this);
70 AssertReturn(autoInitSpan.isOk(), E_FAIL);
71
72 unconst(mParent) = aParent;
73
74 /* mData.mAdditionsActive is FALSE */
75
76 /* Confirm a successful initialization when it's the case */
77 autoInitSpan.setSucceeded();
78
79 ULONG aMemoryBalloonSize;
80 HRESULT ret = mParent->machine()->COMGETTER(MemoryBalloonSize)(&aMemoryBalloonSize);
81 if (ret == S_OK)
82 mMemoryBalloonSize = aMemoryBalloonSize;
83 else
84 mMemoryBalloonSize = 0; /* Default is no ballooning */
85
86 BOOL fPageFusionEnabled;
87 ret = mParent->machine()->COMGETTER(PageFusionEnabled)(&fPageFusionEnabled);
88 if (ret == S_OK)
89 mfPageFusionEnabled = fPageFusionEnabled;
90 else
91 mfPageFusionEnabled = false; /* Default is no page fusion*/
92
93 mStatUpdateInterval = 0; /* Default is not to report guest statistics at all */
94
95 /* Clear statistics. */
96 for (unsigned i = 0 ; i < GUESTSTATTYPE_MAX; i++)
97 mCurrentGuestStat[i] = 0;
98
99#ifdef VBOX_WITH_GUEST_CONTROL
100 /* Init the context ID counter at 1000. */
101 mNextContextID = 1000;
102#endif
103
104 return S_OK;
105}
106
107/**
108 * Uninitializes the instance and sets the ready flag to FALSE.
109 * Called either from FinalRelease() or by the parent when it gets destroyed.
110 */
111void Guest::uninit()
112{
113 LogFlowThisFunc(("\n"));
114
115#ifdef VBOX_WITH_GUEST_CONTROL
116 /* Scope write lock as much as possible. */
117 {
118 /*
119 * Cleanup must be done *before* AutoUninitSpan to cancel all
120 * all outstanding waits in API functions (which hold AutoCaller
121 * ref counts).
122 */
123 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
124
125 /* Clean up callback data. */
126 CallbackListIter it;
127 for (it = mCallbackList.begin(); it != mCallbackList.end(); it++)
128 destroyCtrlCallbackContext(it);
129
130 /* Clear process list. */
131 mGuestProcessList.clear();
132 }
133#endif
134
135 /* Enclose the state transition Ready->InUninit->NotReady */
136 AutoUninitSpan autoUninitSpan(this);
137 if (autoUninitSpan.uninitDone())
138 return;
139
140 unconst(mParent) = NULL;
141}
142
143// IGuest properties
144/////////////////////////////////////////////////////////////////////////////
145
146STDMETHODIMP Guest::COMGETTER(OSTypeId) (BSTR *aOSTypeId)
147{
148 CheckComArgOutPointerValid(aOSTypeId);
149
150 AutoCaller autoCaller(this);
151 if (FAILED(autoCaller.rc())) return autoCaller.rc();
152
153 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
154
155 // redirect the call to IMachine if no additions are installed
156 if (mData.mAdditionsVersion.isEmpty())
157 return mParent->machine()->COMGETTER(OSTypeId)(aOSTypeId);
158
159 mData.mOSTypeId.cloneTo(aOSTypeId);
160
161 return S_OK;
162}
163
164STDMETHODIMP Guest::COMGETTER(AdditionsActive) (BOOL *aAdditionsActive)
165{
166 CheckComArgOutPointerValid(aAdditionsActive);
167
168 AutoCaller autoCaller(this);
169 if (FAILED(autoCaller.rc())) return autoCaller.rc();
170
171 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
172
173 *aAdditionsActive = mData.mAdditionsActive;
174
175 return S_OK;
176}
177
178STDMETHODIMP Guest::COMGETTER(AdditionsVersion) (BSTR *aAdditionsVersion)
179{
180 CheckComArgOutPointerValid(aAdditionsVersion);
181
182 AutoCaller autoCaller(this);
183 if (FAILED(autoCaller.rc())) return autoCaller.rc();
184
185 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
186
187 mData.mAdditionsVersion.cloneTo(aAdditionsVersion);
188
189 return S_OK;
190}
191
192STDMETHODIMP Guest::COMGETTER(SupportsSeamless) (BOOL *aSupportsSeamless)
193{
194 CheckComArgOutPointerValid(aSupportsSeamless);
195
196 AutoCaller autoCaller(this);
197 if (FAILED(autoCaller.rc())) return autoCaller.rc();
198
199 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
200
201 *aSupportsSeamless = mData.mSupportsSeamless;
202
203 return S_OK;
204}
205
206STDMETHODIMP Guest::COMGETTER(SupportsGraphics) (BOOL *aSupportsGraphics)
207{
208 CheckComArgOutPointerValid(aSupportsGraphics);
209
210 AutoCaller autoCaller(this);
211 if (FAILED(autoCaller.rc())) return autoCaller.rc();
212
213 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
214
215 *aSupportsGraphics = mData.mSupportsGraphics;
216
217 return S_OK;
218}
219
220STDMETHODIMP Guest::COMGETTER(PageFusionEnabled) (BOOL *aPageFusionEnabled)
221{
222 CheckComArgOutPointerValid(aPageFusionEnabled);
223
224 AutoCaller autoCaller(this);
225 if (FAILED(autoCaller.rc())) return autoCaller.rc();
226
227 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
228
229 *aPageFusionEnabled = mfPageFusionEnabled;
230
231 return S_OK;
232}
233
234STDMETHODIMP Guest::COMSETTER(PageFusionEnabled) (BOOL aPageFusionEnabled)
235{
236 AutoCaller autoCaller(this);
237 if (FAILED(autoCaller.rc())) return autoCaller.rc();
238
239 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
240
241 /** todo; API complete, but not implemented */
242
243 return E_NOTIMPL;
244}
245
246STDMETHODIMP Guest::COMGETTER(MemoryBalloonSize) (ULONG *aMemoryBalloonSize)
247{
248 CheckComArgOutPointerValid(aMemoryBalloonSize);
249
250 AutoCaller autoCaller(this);
251 if (FAILED(autoCaller.rc())) return autoCaller.rc();
252
253 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
254
255 *aMemoryBalloonSize = mMemoryBalloonSize;
256
257 return S_OK;
258}
259
260STDMETHODIMP Guest::COMSETTER(MemoryBalloonSize) (ULONG aMemoryBalloonSize)
261{
262 AutoCaller autoCaller(this);
263 if (FAILED(autoCaller.rc())) return autoCaller.rc();
264
265 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
266
267 /* We must be 100% sure that IMachine::COMSETTER(MemoryBalloonSize)
268 * does not call us back in any way! */
269 HRESULT ret = mParent->machine()->COMSETTER(MemoryBalloonSize)(aMemoryBalloonSize);
270 if (ret == S_OK)
271 {
272 mMemoryBalloonSize = aMemoryBalloonSize;
273 /* forward the information to the VMM device */
274 VMMDev *pVMMDev = mParent->getVMMDev();
275 if (pVMMDev)
276 {
277 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
278 if (pVMMDevPort)
279 pVMMDevPort->pfnSetMemoryBalloon(pVMMDevPort, aMemoryBalloonSize);
280 }
281 }
282
283 return ret;
284}
285
286STDMETHODIMP Guest::COMGETTER(StatisticsUpdateInterval)(ULONG *aUpdateInterval)
287{
288 CheckComArgOutPointerValid(aUpdateInterval);
289
290 AutoCaller autoCaller(this);
291 if (FAILED(autoCaller.rc())) return autoCaller.rc();
292
293 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
294
295 *aUpdateInterval = mStatUpdateInterval;
296 return S_OK;
297}
298
299STDMETHODIMP Guest::COMSETTER(StatisticsUpdateInterval)(ULONG aUpdateInterval)
300{
301 AutoCaller autoCaller(this);
302 if (FAILED(autoCaller.rc())) return autoCaller.rc();
303
304 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
305
306 mStatUpdateInterval = aUpdateInterval;
307 /* forward the information to the VMM device */
308 VMMDev *pVMMDev = mParent->getVMMDev();
309 if (pVMMDev)
310 {
311 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
312 if (pVMMDevPort)
313 pVMMDevPort->pfnSetStatisticsInterval(pVMMDevPort, aUpdateInterval);
314 }
315
316 return S_OK;
317}
318
319STDMETHODIMP Guest::InternalGetStatistics(ULONG *aCpuUser, ULONG *aCpuKernel, ULONG *aCpuIdle,
320 ULONG *aMemTotal, ULONG *aMemFree, ULONG *aMemBalloon, ULONG *aMemShared,
321 ULONG *aMemCache, ULONG *aPageTotal,
322 ULONG *aMemAllocTotal, ULONG *aMemFreeTotal, ULONG *aMemBalloonTotal, ULONG *aMemSharedTotal)
323{
324 CheckComArgOutPointerValid(aCpuUser);
325 CheckComArgOutPointerValid(aCpuKernel);
326 CheckComArgOutPointerValid(aCpuIdle);
327 CheckComArgOutPointerValid(aMemTotal);
328 CheckComArgOutPointerValid(aMemFree);
329 CheckComArgOutPointerValid(aMemBalloon);
330 CheckComArgOutPointerValid(aMemShared);
331 CheckComArgOutPointerValid(aMemCache);
332 CheckComArgOutPointerValid(aPageTotal);
333 CheckComArgOutPointerValid(aMemAllocTotal);
334 CheckComArgOutPointerValid(aMemFreeTotal);
335 CheckComArgOutPointerValid(aMemBalloonTotal);
336 CheckComArgOutPointerValid(aMemSharedTotal);
337
338 AutoCaller autoCaller(this);
339 if (FAILED(autoCaller.rc())) return autoCaller.rc();
340
341 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
342
343 *aCpuUser = mCurrentGuestStat[GUESTSTATTYPE_CPUUSER];
344 *aCpuKernel = mCurrentGuestStat[GUESTSTATTYPE_CPUKERNEL];
345 *aCpuIdle = mCurrentGuestStat[GUESTSTATTYPE_CPUIDLE];
346 *aMemTotal = mCurrentGuestStat[GUESTSTATTYPE_MEMTOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
347 *aMemFree = mCurrentGuestStat[GUESTSTATTYPE_MEMFREE] * (_4K/_1K); /* page (4K) -> 1KB units */
348 *aMemBalloon = mCurrentGuestStat[GUESTSTATTYPE_MEMBALLOON] * (_4K/_1K); /* page (4K) -> 1KB units */
349 *aMemCache = mCurrentGuestStat[GUESTSTATTYPE_MEMCACHE] * (_4K/_1K); /* page (4K) -> 1KB units */
350 *aPageTotal = mCurrentGuestStat[GUESTSTATTYPE_PAGETOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
351
352 Console::SafeVMPtr pVM (mParent);
353 if (pVM.isOk())
354 {
355 uint64_t uFreeTotal, uAllocTotal, uBalloonedTotal, uSharedTotal;
356 *aMemFreeTotal = 0;
357 int rc = PGMR3QueryVMMMemoryStats(pVM.raw(), &uAllocTotal, &uFreeTotal, &uBalloonedTotal, &uSharedTotal);
358 AssertRC(rc);
359 if (rc == VINF_SUCCESS)
360 {
361 *aMemAllocTotal = (ULONG)(uAllocTotal / _1K); /* bytes -> KB */
362 *aMemFreeTotal = (ULONG)(uFreeTotal / _1K);
363 *aMemBalloonTotal = (ULONG)(uBalloonedTotal / _1K);
364 *aMemSharedTotal = (ULONG)(uSharedTotal / _1K);
365 }
366
367 /* Query the missing per-VM memory statistics. */
368 *aMemShared = 0;
369 uint64_t uTotalMem, uPrivateMem, uSharedMem, uZeroMem;
370 rc = PGMR3QueryMemoryStats(pVM.raw(), &uTotalMem, &uPrivateMem, &uSharedMem, &uZeroMem);
371 if (rc == VINF_SUCCESS)
372 {
373 *aMemShared = (ULONG)(uSharedMem / _1K);
374 }
375 }
376 else
377 {
378 *aMemFreeTotal = 0;
379 *aMemShared = 0;
380 }
381
382 return S_OK;
383}
384
385HRESULT Guest::SetStatistic(ULONG aCpuId, GUESTSTATTYPE enmType, ULONG aVal)
386{
387 AutoCaller autoCaller(this);
388 if (FAILED(autoCaller.rc())) return autoCaller.rc();
389
390 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
391
392 if (enmType >= GUESTSTATTYPE_MAX)
393 return E_INVALIDARG;
394
395 mCurrentGuestStat[enmType] = aVal;
396 return S_OK;
397}
398
399STDMETHODIMP Guest::SetCredentials(IN_BSTR aUserName, IN_BSTR aPassword,
400 IN_BSTR aDomain, BOOL aAllowInteractiveLogon)
401{
402 AutoCaller autoCaller(this);
403 if (FAILED(autoCaller.rc())) return autoCaller.rc();
404
405 /* forward the information to the VMM device */
406 VMMDev *pVMMDev = mParent->getVMMDev();
407 if (pVMMDev)
408 {
409 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
410 if (pVMMDevPort)
411 {
412 uint32_t u32Flags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
413 if (!aAllowInteractiveLogon)
414 u32Flags = VMMDEV_SETCREDENTIALS_NOLOCALLOGON;
415
416 pVMMDevPort->pfnSetCredentials(pVMMDevPort,
417 Utf8Str(aUserName).raw(),
418 Utf8Str(aPassword).raw(),
419 Utf8Str(aDomain).raw(),
420 u32Flags);
421 return S_OK;
422 }
423 }
424
425 return setError(VBOX_E_VM_ERROR,
426 tr("VMM device is not available (is the VM running?)"));
427}
428
429#ifdef VBOX_WITH_GUEST_CONTROL
430/**
431 * Appends environment variables to the environment block. Each var=value pair is separated
432 * by NULL (\0) sequence. The whole block will be stored in one blob and disassembled on the
433 * guest side later to fit into the HGCM param structure.
434 *
435 * @returns VBox status code.
436 *
437 * @todo
438 *
439 */
440int Guest::prepareExecuteEnv(const char *pszEnv, void **ppvList, uint32_t *pcbList, uint32_t *pcEnv)
441{
442 int rc = VINF_SUCCESS;
443 uint32_t cbLen = strlen(pszEnv);
444 if (*ppvList)
445 {
446 uint32_t cbNewLen = *pcbList + cbLen + 1; /* Include zero termination. */
447 char *pvTmp = (char*)RTMemRealloc(*ppvList, cbNewLen);
448 if (NULL == pvTmp)
449 {
450 rc = VERR_NO_MEMORY;
451 }
452 else
453 {
454 memcpy(pvTmp + *pcbList, pszEnv, cbLen);
455 pvTmp[cbNewLen - 1] = '\0'; /* Add zero termination. */
456 *ppvList = (void**)pvTmp;
457 }
458 }
459 else
460 {
461 char *pcTmp;
462 if (RTStrAPrintf(&pcTmp, "%s", pszEnv) > 0)
463 {
464 *ppvList = (void**)pcTmp;
465 /* Reset counters. */
466 *pcEnv = 0;
467 *pcbList = 0;
468 }
469 }
470 if (RT_SUCCESS(rc))
471 {
472 *pcbList += cbLen + 1; /* Include zero termination. */
473 *pcEnv += 1; /* Increase env pairs count. */
474 }
475 return rc;
476}
477
478/**
479 * Static callback function for receiving updates on guest control commands
480 * from the guest. Acts as a dispatcher for the actual class instance.
481 *
482 * @returns VBox status code.
483 *
484 * @todo
485 *
486 */
487DECLCALLBACK(int) Guest::doGuestCtrlNotification(void *pvExtension,
488 uint32_t u32Function,
489 void *pvParms,
490 uint32_t cbParms)
491{
492 using namespace guestControl;
493
494 /*
495 * No locking, as this is purely a notification which does not make any
496 * changes to the object state.
497 */
498#ifdef DEBUG_andy
499 LogFlowFunc(("pvExtension = %p, u32Function = %d, pvParms = %p, cbParms = %d\n",
500 pvExtension, u32Function, pvParms, cbParms));
501#endif
502 ComObjPtr<Guest> pGuest = reinterpret_cast<Guest *>(pvExtension);
503
504 int rc = VINF_SUCCESS;
505 if (u32Function == GUEST_DISCONNECTED)
506 {
507 LogFlowFunc(("GUEST_DISCONNECTED\n"));
508
509 PCALLBACKDATACLIENTDISCONNECTED pCBData = reinterpret_cast<PCALLBACKDATACLIENTDISCONNECTED>(pvParms);
510 AssertPtr(pCBData);
511 AssertReturn(sizeof(CALLBACKDATACLIENTDISCONNECTED) == cbParms, VERR_INVALID_PARAMETER);
512 AssertReturn(CALLBACKDATAMAGICCLIENTDISCONNECTED == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
513
514 rc = pGuest->notifyCtrlClientDisconnected(u32Function, pCBData);
515 }
516 else if (u32Function == GUEST_EXEC_SEND_STATUS)
517 {
518 LogFlowFunc(("GUEST_EXEC_SEND_STATUS\n"));
519
520 PCALLBACKDATAEXECSTATUS pCBData = reinterpret_cast<PCALLBACKDATAEXECSTATUS>(pvParms);
521 AssertPtr(pCBData);
522 AssertReturn(sizeof(CALLBACKDATAEXECSTATUS) == cbParms, VERR_INVALID_PARAMETER);
523 AssertReturn(CALLBACKDATAMAGICEXECSTATUS == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
524
525 rc = pGuest->notifyCtrlExecStatus(u32Function, pCBData);
526 }
527 else if (u32Function == GUEST_EXEC_SEND_OUTPUT)
528 {
529 LogFlowFunc(("GUEST_EXEC_SEND_OUTPUT\n"));
530
531 PCALLBACKDATAEXECOUT pCBData = reinterpret_cast<PCALLBACKDATAEXECOUT>(pvParms);
532 AssertPtr(pCBData);
533 AssertReturn(sizeof(CALLBACKDATAEXECOUT) == cbParms, VERR_INVALID_PARAMETER);
534 AssertReturn(CALLBACKDATAMAGICEXECOUT == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
535
536 rc = pGuest->notifyCtrlExecOut(u32Function, pCBData);
537 }
538 else
539 rc = VERR_NOT_SUPPORTED;
540 return rc;
541}
542
543/* Function for handling the execution start/termination notification. */
544int Guest::notifyCtrlExecStatus(uint32_t u32Function,
545 PCALLBACKDATAEXECSTATUS pData)
546{
547 int rc = VINF_SUCCESS;
548
549 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
550
551 AssertPtr(pData);
552 CallbackListIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
553
554 /* Callback can be called several times. */
555 if (it != mCallbackList.end())
556 {
557 PCALLBACKDATAEXECSTATUS pCBData = (PCALLBACKDATAEXECSTATUS)it->pvData;
558 AssertPtr(pCBData);
559
560 pCBData->u32PID = pData->u32PID;
561 pCBData->u32Status = pData->u32Status;
562 pCBData->u32Flags = pData->u32Flags;
563 /** @todo Copy void* buffer contents! */
564
565 /* Was progress canceled before? */
566 BOOL fCanceled;
567 ComAssert(it->pProgress.isNotNull());
568 it->pProgress->COMGETTER(Canceled)(&fCanceled);
569
570 Utf8Str errMsg;
571 if (!fCanceled)
572 {
573 /* Do progress handling. */
574 switch (pData->u32Status)
575 {
576 case PROC_STS_STARTED:
577 rc = it->pProgress->SetNextOperation(BstrFmt(tr("Waiting for process to exit ...")), 1 /* Weight */);
578 if (FAILED(rc))
579 errMsg = Utf8StrFmt(Guest::tr("Cannot enter waiting for process exit stage! rc=%u"),
580 rc);
581 break;
582
583 case PROC_STS_TEN: /* Terminated normally. */
584 it->pProgress->notifyComplete(S_OK);
585 LogFlowFunc(("Proccess (context ID=%u, status=%u) terminated successfully\n",
586 pData->hdr.u32ContextID, pData->u32Status));
587 break;
588
589 case PROC_STS_TEA: /* Terminated abnormally. */
590 errMsg = Utf8StrFmt(Guest::tr("Process terminated abnormally with status '%u'"),
591 pCBData->u32Flags);
592 break;
593
594 case PROC_STS_TES: /* Terminated through signal. */
595 errMsg = Utf8StrFmt(Guest::tr("Process terminated via signal with status '%u'"),
596 pCBData->u32Flags);
597 break;
598
599 case PROC_STS_TOK:
600 errMsg = Utf8StrFmt(Guest::tr("Process timed out and was killed"));
601 break;
602
603 case PROC_STS_TOA:
604 errMsg = Utf8StrFmt(Guest::tr("Process timed out and could not be killed"));
605 break;
606
607 case PROC_STS_DWN:
608 errMsg = Utf8StrFmt(Guest::tr("Process exited because system is shutting down"));
609 break;
610
611 case PROC_STS_ERROR:
612 errMsg = Utf8StrFmt(Guest::tr("Process execution failed with rc=%Rrc"), pCBData->u32Flags);
613 break;
614
615 default:
616 break;
617 }
618
619 /* Handle process list. */
620 /** @todo What happens on/deal with PID reuse? */
621 /** @todo How to deal with multiple updates at once? */
622 if (pCBData->u32PID > 0)
623 {
624 GuestProcessIter it_proc = getProcessByPID(pCBData->u32PID);
625 if (it_proc == mGuestProcessList.end())
626 {
627 /* Not found, add to list. */
628 GuestProcess p;
629 p.mPID = pCBData->u32PID;
630 p.mStatus = pCBData->u32Status;
631 p.mExitCode = pCBData->u32Flags; /* Contains exit code. */
632 p.mFlags = 0;
633
634 mGuestProcessList.push_back(p);
635 }
636 else /* Update list. */
637 {
638 it_proc->mStatus = pCBData->u32Status;
639 it_proc->mExitCode = pCBData->u32Flags; /* Contains exit code. */
640 it_proc->mFlags = 0;
641 }
642 }
643 }
644 else
645 errMsg = Utf8StrFmt(Guest::tr("Process execution canceled"));
646
647 if (!it->pProgress->getCompleted())
648 {
649 if ( errMsg.length()
650 || fCanceled) /* If cancelled we have to report E_FAIL! */
651 {
652 it->pProgress->notifyComplete(VBOX_E_IPRT_ERROR, COM_IIDOF(IGuest),
653 (CBSTR)Guest::getComponentName(), errMsg.c_str());
654 LogFlowFunc(("Process (context ID=%u, status=%u) reported error: %s\n",
655 pData->hdr.u32ContextID, pData->u32Status, errMsg.c_str()));
656 }
657 }
658 }
659 else
660 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
661 return rc;
662}
663
664/* Function for handling the execution output notification. */
665int Guest::notifyCtrlExecOut(uint32_t u32Function,
666 PCALLBACKDATAEXECOUT pData)
667{
668 int rc = VINF_SUCCESS;
669
670 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
671
672 AssertPtr(pData);
673 CallbackListIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
674 if (it != mCallbackList.end())
675 {
676 PCALLBACKDATAEXECOUT pCBData = (CALLBACKDATAEXECOUT*)it->pvData;
677 AssertPtr(pCBData);
678
679 pCBData->u32PID = pData->u32PID;
680 pCBData->u32HandleId = pData->u32HandleId;
681 pCBData->u32Flags = pData->u32Flags;
682
683 /* Make sure we really got something! */
684 if ( pData->cbData
685 && pData->pvData)
686 {
687 /* Allocate data buffer and copy it */
688 pCBData->pvData = RTMemAlloc(pData->cbData);
689 pCBData->cbData = pData->cbData;
690
691 AssertReturn(pCBData->pvData, VERR_NO_MEMORY);
692 memcpy(pCBData->pvData, pData->pvData, pData->cbData);
693 }
694 else
695 {
696 pCBData->pvData = NULL;
697 pCBData->cbData = 0;
698 }
699
700 /* Was progress canceled before? */
701 BOOL fCanceled;
702 ComAssert(it->pProgress.isNotNull());
703 it->pProgress->COMGETTER(Canceled)(&fCanceled);
704
705 if (!fCanceled)
706 it->pProgress->notifyComplete(S_OK);
707 else
708 it->pProgress->notifyComplete(VBOX_E_IPRT_ERROR, COM_IIDOF(IGuest),
709 (CBSTR)Guest::getComponentName(), Guest::tr("The output operation was cancelled"));
710 }
711 else
712 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
713 return rc;
714}
715
716int Guest::notifyCtrlClientDisconnected(uint32_t u32Function,
717 PCALLBACKDATACLIENTDISCONNECTED pData)
718{
719 int rc = VINF_SUCCESS;
720
721 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
722
723 /** @todo Maybe use a map instead of list for fast context lookup. */
724 CallbackListIter it;
725 for (it = mCallbackList.begin(); it != mCallbackList.end(); it++)
726 {
727 if (it->mContextID == pData->hdr.u32ContextID)
728 {
729 LogFlowFunc(("Client with context ID=%u disconnected\n", it->mContextID));
730 destroyCtrlCallbackContext(it);
731 }
732 }
733 return rc;
734}
735
736Guest::CallbackListIter Guest::getCtrlCallbackContextByID(uint32_t u32ContextID)
737{
738 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
739
740 /** @todo Maybe use a map instead of list for fast context lookup. */
741 CallbackListIter it;
742 for (it = mCallbackList.begin(); it != mCallbackList.end(); it++)
743 {
744 if (it->mContextID == u32ContextID)
745 return (it);
746 }
747 return it;
748}
749
750Guest::GuestProcessIter Guest::getProcessByPID(uint32_t u32PID)
751{
752 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
753
754 /** @todo Maybe use a map instead of list for fast context lookup. */
755 GuestProcessIter it;
756 for (it = mGuestProcessList.begin(); it != mGuestProcessList.end(); it++)
757 {
758 if (it->mPID == u32PID)
759 return (it);
760 }
761 return it;
762}
763
764/* No locking here; */
765void Guest::destroyCtrlCallbackContext(Guest::CallbackListIter it)
766{
767 if (it->pvData)
768 {
769 LogFlowFunc(("Destroying callback with context ID=%u ...\n", it->mContextID));
770
771 RTMemFree(it->pvData);
772 it->pvData = NULL;
773 it->cbData = 0;
774 }
775
776 /* Notify outstanding waits for progress ... */
777 if (it->pProgress && it->pProgress.isNotNull())
778 {
779 LogFlowFunc(("Handling progress of context ID=%u ...\n", it->mContextID));
780
781 BOOL fCompleted;
782 it->pProgress->COMGETTER(Completed)(&fCompleted);
783 if (!fCompleted)
784 {
785 /* Only cancel if not canceled before! */
786 BOOL fCanceled;
787 if (SUCCEEDED(it->pProgress->COMGETTER(Canceled)(&fCanceled)) && !fCanceled)
788 it->pProgress->Cancel();
789
790 /* To get waitForCompletion notified we have to notify it if necessary. */
791 it->pProgress->notifyComplete(VBOX_E_IPRT_ERROR, COM_IIDOF(IGuest),
792 (CBSTR)Guest::getComponentName(), Guest::tr("The operation was canceled during shutdown"));
793 }
794 /*
795 * Do *not NULL pProgress here, because waiting function like executeProcess()
796 * will still rely on this object for checking whether they have to give up!
797 */
798 }
799}
800
801/* Adds a callback with a user provided data block and an optional progress object
802 * to the callback list. A callback is identified by a unique context ID which is used
803 * to identify a callback from the guest side. */
804uint32_t Guest::addCtrlCallbackContext(eVBoxGuestCtrlCallbackType enmType, void *pvData, uint32_t cbData, Progress *pProgress)
805{
806 AssertPtr(pProgress);
807 uint32_t uNewContext = ASMAtomicIncU32(&mNextContextID);
808 if (uNewContext == UINT32_MAX)
809 ASMAtomicUoWriteU32(&mNextContextID, 1000);
810
811 /** @todo Put this stuff into a constructor! */
812 CallbackContext context;
813 context.mContextID = uNewContext;
814 context.mType = enmType;
815 context.pvData = pvData;
816 context.cbData = cbData;
817 context.pProgress = pProgress;
818
819 uint32_t nCallbacks;
820 {
821 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
822 /// @todo r=bird: check if already in the list and find another one.
823 mCallbackList.push_back(context);
824 nCallbacks = mCallbackList.size();
825 }
826
827#if 0
828 if (nCallbacks > 256) /* Don't let the container size get too big! */
829 {
830 Guest::CallbackListIter it = mCallbackList.begin();
831 destroyCtrlCallbackContext(it);
832 {
833 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
834 mCallbackList.erase(it);
835 }
836 }
837#endif
838 return uNewContext;
839}
840#endif /* VBOX_WITH_GUEST_CONTROL */
841
842STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
843 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
844 IN_BSTR aUserName, IN_BSTR aPassword,
845 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
846{
847/** @todo r=bird: Eventually we should clean up all the timeout parameters
848 * in the API and have the same way of specifying infinite waits! */
849#ifndef VBOX_WITH_GUEST_CONTROL
850 ReturnComNotImplemented();
851#else /* VBOX_WITH_GUEST_CONTROL */
852 using namespace guestControl;
853
854 CheckComArgStrNotEmptyOrNull(aCommand);
855 CheckComArgOutPointerValid(aPID);
856 CheckComArgOutPointerValid(aProgress);
857
858 /* Do not allow anonymous executions (with system rights). */
859 if (RT_UNLIKELY((aUserName) == NULL || *(aUserName) == '\0'))
860 return setError(E_INVALIDARG, tr("No user name specified"));
861
862 AutoCaller autoCaller(this);
863 if (FAILED(autoCaller.rc())) return autoCaller.rc();
864
865 if (aFlags != 0) /* Flags are not supported at the moment. */
866 return E_INVALIDARG;
867
868 HRESULT rc = S_OK;
869
870 try
871 {
872 /*
873 * Create progress object. Note that this is a multi operation
874 * object to perform the following steps:
875 * - Operation 1 (0): Create/start process.
876 * - Operation 2 (1): Wait for process to exit.
877 * If this progress completed successfully (S_OK), the process
878 * started and exited normally. In any other case an error/exception
879 * occured.
880 */
881 ComObjPtr <Progress> progress;
882 rc = progress.createObject();
883 if (SUCCEEDED(rc))
884 {
885 rc = progress->init(static_cast<IGuest*>(this),
886 BstrFmt(tr("Executing process")),
887 TRUE,
888 2, /* Number of operations. */
889 BstrFmt(tr("Starting process ..."))); /* Description of first stage. */
890 }
891 if (FAILED(rc)) return rc;
892
893 /*
894 * Prepare process execution.
895 */
896 int vrc = VINF_SUCCESS;
897 Utf8Str Utf8Command(aCommand);
898
899 /* Adjust timeout */
900 if (aTimeoutMS == 0)
901 aTimeoutMS = UINT32_MAX;
902
903 /* Prepare arguments. */
904 char **papszArgv = NULL;
905 uint32_t uNumArgs = 0;
906 if (aArguments > 0)
907 {
908 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
909 uNumArgs = args.size();
910 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
911 AssertReturn(papszArgv, E_OUTOFMEMORY);
912 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
913 {
914 /// @todo r=bird: RTUtf16ToUtf8().
915 int cbLen = RTStrAPrintf(&papszArgv[i], "%s", Utf8Str(args[i]).raw());
916 if (cbLen < 0)
917 vrc = VERR_NO_MEMORY;
918
919 }
920 papszArgv[uNumArgs] = NULL;
921 }
922
923 Utf8Str Utf8UserName(aUserName);
924 Utf8Str Utf8Password(aPassword);
925 if (RT_SUCCESS(vrc))
926 {
927 uint32_t uContextID = 0;
928
929 char *pszArgs = NULL;
930 if (uNumArgs > 0)
931 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, 0);
932 if (RT_SUCCESS(vrc))
933 {
934 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
935
936 /* Prepare environment. */
937 void *pvEnv = NULL;
938 uint32_t uNumEnv = 0;
939 uint32_t cbEnv = 0;
940 if (aEnvironment > 0)
941 {
942 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
943
944 for (unsigned i = 0; i < env.size(); i++)
945 {
946 vrc = prepareExecuteEnv(Utf8Str(env[i]).raw(), &pvEnv, &cbEnv, &uNumEnv);
947 if (RT_FAILURE(vrc))
948 break;
949 }
950 }
951
952 if (RT_SUCCESS(vrc))
953 {
954 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECSTATUS));
955 AssertReturn(pData, VBOX_E_IPRT_ERROR);
956 RT_ZERO(*pData);
957 uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_START,
958 pData, sizeof(CALLBACKDATAEXECSTATUS), progress);
959 Assert(uContextID > 0);
960
961 VBOXHGCMSVCPARM paParms[15];
962 int i = 0;
963 paParms[i++].setUInt32(uContextID);
964 paParms[i++].setPointer((void*)Utf8Command.raw(), (uint32_t)strlen(Utf8Command.raw()) + 1);
965 paParms[i++].setUInt32(aFlags);
966 paParms[i++].setUInt32(uNumArgs);
967 paParms[i++].setPointer((void*)pszArgs, cbArgs);
968 paParms[i++].setUInt32(uNumEnv);
969 paParms[i++].setUInt32(cbEnv);
970 paParms[i++].setPointer((void*)pvEnv, cbEnv);
971 paParms[i++].setPointer((void*)Utf8UserName.raw(), (uint32_t)strlen(Utf8UserName.raw()) + 1);
972 paParms[i++].setPointer((void*)Utf8Password.raw(), (uint32_t)strlen(Utf8Password.raw()) + 1);
973 paParms[i++].setUInt32(aTimeoutMS);
974
975 VMMDev *vmmDev;
976 {
977 /* Make sure mParent is valid, so set the read lock while using.
978 * Do not keep this lock while doing the actual call, because in the meanwhile
979 * another thread could request a write lock which would be a bad idea ... */
980 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
981
982 /* Forward the information to the VMM device. */
983 AssertPtr(mParent);
984 vmmDev = mParent->getVMMDev();
985 }
986
987 if (vmmDev)
988 {
989 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
990 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
991 i, paParms);
992 }
993 else
994 vrc = VERR_INVALID_VM_HANDLE;
995 RTMemFree(pvEnv);
996 }
997 RTStrFree(pszArgs);
998 }
999 if (RT_SUCCESS(vrc))
1000 {
1001 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1002
1003 /*
1004 * Wait for the HGCM low level callback until the process
1005 * has been started (or something went wrong). This is necessary to
1006 * get the PID.
1007 */
1008 CallbackListIter it = getCtrlCallbackContextByID(uContextID);
1009 BOOL fCanceled = FALSE;
1010 if (it != mCallbackList.end())
1011 {
1012 ComAssert(it->pProgress.isNotNull());
1013
1014 /*
1015 * Wait for the first stage (=0) to complete (that is starting the process).
1016 */
1017 PCALLBACKDATAEXECSTATUS pData = NULL;
1018 rc = it->pProgress->WaitForOperationCompletion(0, aTimeoutMS);
1019 if (SUCCEEDED(rc))
1020 {
1021 /* Was the operation canceled by one of the parties? */
1022 rc = it->pProgress->COMGETTER(Canceled)(&fCanceled);
1023 if (FAILED(rc)) throw rc;
1024
1025 if (!fCanceled)
1026 {
1027 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1028
1029 pData = (PCALLBACKDATAEXECSTATUS)it->pvData;
1030 Assert(it->cbData == sizeof(CALLBACKDATAEXECSTATUS));
1031 AssertPtr(pData);
1032
1033 /* Did we get some status? */
1034 switch (pData->u32Status)
1035 {
1036 case PROC_STS_STARTED:
1037 /* Process is (still) running; get PID. */
1038 *aPID = pData->u32PID;
1039 break;
1040
1041 /* In any other case the process either already
1042 * terminated or something else went wrong, so no PID ... */
1043 case PROC_STS_TEN: /* Terminated normally. */
1044 case PROC_STS_TEA: /* Terminated abnormally. */
1045 case PROC_STS_TES: /* Terminated through signal. */
1046 case PROC_STS_TOK:
1047 case PROC_STS_TOA:
1048 case PROC_STS_DWN:
1049 /*
1050 * Process (already) ended, but we want to get the
1051 * PID anyway to retrieve the output in a later call.
1052 */
1053 *aPID = pData->u32PID;
1054 break;
1055
1056 case PROC_STS_ERROR:
1057 vrc = pData->u32Flags; /* u32Flags member contains IPRT error code. */
1058 break;
1059
1060 case PROC_STS_UNDEFINED:
1061 vrc = VERR_TIMEOUT; /* Operation did not complete within time. */
1062 break;
1063
1064 default:
1065 vrc = VERR_INVALID_PARAMETER; /* Unknown status, should never happen! */
1066 break;
1067 }
1068 }
1069 else /* Operation was canceled. */
1070 vrc = VERR_CANCELLED;
1071 }
1072 else /* Operation did not complete within time. */
1073 vrc = VERR_TIMEOUT;
1074
1075 /*
1076 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1077 * else (like end of process) ...
1078 */
1079 if (RT_FAILURE(vrc))
1080 {
1081 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1082 {
1083 rc = setError(VBOX_E_IPRT_ERROR,
1084 tr("The file '%s' was not found on guest"), Utf8Command.raw());
1085 }
1086 else if (vrc == VERR_PATH_NOT_FOUND)
1087 {
1088 rc = setError(VBOX_E_IPRT_ERROR,
1089 tr("The path to file '%s' was not found on guest"), Utf8Command.raw());
1090 }
1091 else if (vrc == VERR_BAD_EXE_FORMAT)
1092 {
1093 rc = setError(VBOX_E_IPRT_ERROR,
1094 tr("The file '%s' is not an executable format on guest"), Utf8Command.raw());
1095 }
1096 else if (vrc == VERR_LOGON_FAILURE)
1097 {
1098 rc = setError(VBOX_E_IPRT_ERROR,
1099 tr("The specified user '%s' was not able to logon on guest"), Utf8UserName.raw());
1100 }
1101 else if (vrc == VERR_TIMEOUT)
1102 {
1103 rc = setError(VBOX_E_IPRT_ERROR,
1104 tr("The guest did not respond within time (%ums)"), aTimeoutMS);
1105 }
1106 else if (vrc == VERR_CANCELLED)
1107 {
1108 rc = setError(VBOX_E_IPRT_ERROR,
1109 tr("The execution operation was canceled"));
1110 }
1111 else if (vrc == VERR_PERMISSION_DENIED)
1112 {
1113 rc = setError(VBOX_E_IPRT_ERROR,
1114 tr("Invalid user/password credentials"));
1115 }
1116 else
1117 {
1118 if (pData && pData->u32Status == PROC_STS_ERROR)
1119 rc = setError(VBOX_E_IPRT_ERROR,
1120 tr("Process could not be started: %Rrc"), pData->u32Flags);
1121 else
1122 rc = setError(E_UNEXPECTED,
1123 tr("The service call failed with error %Rrc"), vrc);
1124 }
1125 }
1126 else /* Execution went fine. */
1127 {
1128 /* Return the progress to the caller. */
1129 progress.queryInterfaceTo(aProgress);
1130 }
1131 }
1132 else /* Callback context not found; should never happen! */
1133 AssertMsg(it != mCallbackList.end(), ("Callback context with ID %u not found!", uContextID));
1134 }
1135 else /* HGCM related error codes .*/
1136 {
1137 if (vrc == VERR_INVALID_VM_HANDLE)
1138 {
1139 rc = setError(VBOX_E_VM_ERROR,
1140 tr("VMM device is not available (is the VM running?)"));
1141 }
1142 else if (vrc == VERR_TIMEOUT)
1143 {
1144 rc = setError(VBOX_E_VM_ERROR,
1145 tr("The guest execution service is not ready"));
1146 }
1147 else /* HGCM call went wrong. */
1148 {
1149 rc = setError(E_UNEXPECTED,
1150 tr("The HGCM call failed with error %Rrc"), vrc);
1151 }
1152 }
1153
1154 for (unsigned i = 0; i < uNumArgs; i++)
1155 RTMemFree(papszArgv[i]);
1156 RTMemFree(papszArgv);
1157 }
1158 }
1159 catch (std::bad_alloc &)
1160 {
1161 rc = E_OUTOFMEMORY;
1162 }
1163 return rc;
1164#endif /* VBOX_WITH_GUEST_CONTROL */
1165}
1166
1167STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
1168{
1169/** @todo r=bird: Eventually we should clean up all the timeout parameters
1170 * in the API and have the same way of specifying infinite waits! */
1171#ifndef VBOX_WITH_GUEST_CONTROL
1172 ReturnComNotImplemented();
1173#else /* VBOX_WITH_GUEST_CONTROL */
1174 using namespace guestControl;
1175
1176 CheckComArgExpr(aPID, aPID > 0);
1177
1178 if (aFlags != 0) /* Flags are not supported at the moment. */
1179 return E_INVALIDARG;
1180
1181 AutoCaller autoCaller(this);
1182 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1183
1184 HRESULT rc = S_OK;
1185
1186 try
1187 {
1188 /*
1189 * Create progress object.
1190 * This progress object, compared to the one in executeProgress() above,
1191 * is only local and is used to determine whether the operation finished
1192 * or got cancelled.
1193 */
1194 ComObjPtr <Progress> progress;
1195 rc = progress.createObject();
1196 if (SUCCEEDED(rc))
1197 {
1198 rc = progress->init(static_cast<IGuest*>(this),
1199 BstrFmt(tr("Getting output of process")),
1200 TRUE);
1201 }
1202 if (FAILED(rc)) return rc;
1203
1204 /* Adjust timeout */
1205 if (aTimeoutMS == 0)
1206 aTimeoutMS = UINT32_MAX;
1207
1208 /* Search for existing PID. */
1209 PCALLBACKDATAEXECOUT pData = (CALLBACKDATAEXECOUT*)RTMemAlloc(sizeof(CALLBACKDATAEXECOUT));
1210 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1211 RT_ZERO(*pData);
1212 uint32_t uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT,
1213 pData, sizeof(CALLBACKDATAEXECOUT), progress);
1214 Assert(uContextID > 0);
1215
1216 size_t cbData = (size_t)RT_MIN(aSize, _64K);
1217 com::SafeArray<BYTE> outputData(cbData);
1218
1219 VBOXHGCMSVCPARM paParms[5];
1220 int i = 0;
1221 paParms[i++].setUInt32(uContextID);
1222 paParms[i++].setUInt32(aPID);
1223 paParms[i++].setUInt32(aFlags); /** @todo Should represent stdout and/or stderr. */
1224
1225 int vrc = VINF_SUCCESS;
1226
1227 {
1228 VMMDev *vmmDev;
1229 {
1230 /* Make sure mParent is valid, so set the read lock while using.
1231 * Do not keep this lock while doing the actual call, because in the meanwhile
1232 * another thread could request a write lock which would be a bad idea ... */
1233 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1234
1235 /* Forward the information to the VMM device. */
1236 AssertPtr(mParent);
1237 vmmDev = mParent->getVMMDev();
1238 }
1239
1240 if (vmmDev)
1241 {
1242 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1243 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
1244 i, paParms);
1245 }
1246 }
1247
1248 if (RT_SUCCESS(vrc))
1249 {
1250 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1251
1252 /*
1253 * Wait for the HGCM low level callback until the process
1254 * has been started (or something went wrong). This is necessary to
1255 * get the PID.
1256 */
1257 CallbackListIter it = getCtrlCallbackContextByID(uContextID);
1258 BOOL fCanceled = FALSE;
1259 if (it != mCallbackList.end())
1260 {
1261 ComAssert(it->pProgress.isNotNull());
1262
1263 /* Wait until operation completed. */
1264 rc = it->pProgress->WaitForCompletion(aTimeoutMS);
1265 if (FAILED(rc)) throw rc;
1266
1267 /* Was the operation canceled by one of the parties? */
1268 rc = it->pProgress->COMGETTER(Canceled)(&fCanceled);
1269 if (FAILED(rc)) throw rc;
1270
1271 if (!fCanceled)
1272 {
1273 BOOL fCompleted;
1274 if ( SUCCEEDED(it->pProgress->COMGETTER(Completed)(&fCompleted))
1275 && fCompleted)
1276 {
1277 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1278
1279 /* Did we get some output? */
1280 pData = (PCALLBACKDATAEXECOUT)it->pvData;
1281 Assert(it->cbData == sizeof(CALLBACKDATAEXECOUT));
1282 AssertPtr(pData);
1283
1284 if (pData->cbData)
1285 {
1286 /* Do we need to resize the array? */
1287 if (pData->cbData > cbData)
1288 outputData.resize(pData->cbData);
1289
1290 /* Fill output in supplied out buffer. */
1291 memcpy(outputData.raw(), pData->pvData, pData->cbData);
1292 outputData.resize(pData->cbData); /* Shrink to fit actual buffer size. */
1293 }
1294 else
1295 vrc = VERR_NO_DATA; /* This is not an error we want to report to COM. */
1296 }
1297 else /* If callback not called within time ... well, that's a timeout! */
1298 vrc = VERR_TIMEOUT;
1299 }
1300 else /* Operation was canceled. */
1301 {
1302 vrc = VERR_CANCELLED;
1303 }
1304
1305 if (RT_FAILURE(vrc))
1306 {
1307 if (vrc == VERR_NO_DATA)
1308 {
1309 /* This is not an error we want to report to COM. */
1310 rc = NO_ERROR;
1311 }
1312 else if (vrc == VERR_TIMEOUT)
1313 {
1314 rc = setError(VBOX_E_IPRT_ERROR,
1315 tr("The guest did not output within time (%ums)"), aTimeoutMS);
1316 }
1317 else if (vrc == VERR_CANCELLED)
1318 {
1319 rc = setError(VBOX_E_IPRT_ERROR,
1320 tr("The output operation was canceled"));
1321 }
1322 else
1323 {
1324 rc = setError(E_UNEXPECTED,
1325 tr("The service call failed with error %Rrc"), vrc);
1326 }
1327 }
1328
1329 {
1330 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1331 destroyCtrlCallbackContext(it);
1332 }
1333
1334 /* Remove callback context (not used anymore). */
1335 mCallbackList.erase(it);
1336 }
1337 else /* PID lookup failed. */
1338 rc = setError(VBOX_E_IPRT_ERROR,
1339 tr("Process (PID %u) not found!"), aPID);
1340 }
1341 else /* HGCM operation failed. */
1342 rc = setError(E_UNEXPECTED,
1343 tr("The HGCM call failed with error %Rrc"), vrc);
1344
1345 /* Cleanup. */
1346 progress->uninit();
1347 progress.setNull();
1348
1349 /* If something failed (or there simply was no data, indicated by VERR_NO_DATA,
1350 * we return an empty array so that the frontend knows when to give up. */
1351 if (RT_FAILURE(vrc) || FAILED(rc))
1352 outputData.resize(0);
1353 outputData.detachTo(ComSafeArrayOutArg(aData));
1354 }
1355 catch (std::bad_alloc &)
1356 {
1357 rc = E_OUTOFMEMORY;
1358 }
1359 return rc;
1360#endif
1361}
1362
1363STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ULONG *aStatus)
1364{
1365#ifndef VBOX_WITH_GUEST_CONTROL
1366 ReturnComNotImplemented();
1367#else /* VBOX_WITH_GUEST_CONTROL */
1368 using namespace guestControl;
1369
1370 AutoCaller autoCaller(this);
1371 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1372
1373 HRESULT rc = S_OK;
1374
1375 try
1376 {
1377 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1378
1379 GuestProcessIterConst it;
1380 for (it = mGuestProcessList.begin(); it != mGuestProcessList.end(); it++)
1381 {
1382 if (it->mPID == aPID)
1383 break;
1384 }
1385
1386 if (it != mGuestProcessList.end())
1387 {
1388 *aExitCode = it->mExitCode;
1389 *aFlags = it->mFlags;
1390 *aStatus = it->mStatus;
1391 }
1392 else
1393 rc = setError(VBOX_E_IPRT_ERROR,
1394 tr("Process (PID %u) not found!"), aPID);
1395 }
1396 catch (std::bad_alloc &)
1397 {
1398 rc = E_OUTOFMEMORY;
1399 }
1400 return rc;
1401#endif
1402}
1403
1404// public methods only for internal purposes
1405/////////////////////////////////////////////////////////////////////////////
1406
1407void Guest::setAdditionsVersion(Bstr aVersion, VBOXOSTYPE aOsType)
1408{
1409 AutoCaller autoCaller(this);
1410 AssertComRCReturnVoid (autoCaller.rc());
1411
1412 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1413
1414 mData.mAdditionsVersion = aVersion;
1415 mData.mAdditionsActive = !aVersion.isEmpty();
1416 /* Older Additions didn't have this finer grained capability bit,
1417 * so enable it by default. Newer Additions will disable it immediately
1418 * if relevant. */
1419 mData.mSupportsGraphics = mData.mAdditionsActive;
1420
1421 mData.mOSTypeId = Global::OSTypeId (aOsType);
1422}
1423
1424void Guest::setSupportsSeamless (BOOL aSupportsSeamless)
1425{
1426 AutoCaller autoCaller(this);
1427 AssertComRCReturnVoid (autoCaller.rc());
1428
1429 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1430
1431 mData.mSupportsSeamless = aSupportsSeamless;
1432}
1433
1434void Guest::setSupportsGraphics (BOOL aSupportsGraphics)
1435{
1436 AutoCaller autoCaller(this);
1437 AssertComRCReturnVoid (autoCaller.rc());
1438
1439 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1440
1441 mData.mSupportsGraphics = aSupportsGraphics;
1442}
1443/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette