VirtualBox

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

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

Guest Control: Some todos.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.4 KB
Line 
1/* $Id: GuestImpl.cpp 30071 2010-06-07 13:29:23Z 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.215389.xyz. 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
808 /** @todo Put this stuff into a constructor! */
809 CallbackContext context;
810 context.mType = enmType;
811 context.pvData = pvData;
812 context.cbData = cbData;
813 context.pProgress = pProgress;
814
815 /* Create a new context ID and assign it. */
816 CallbackListIter it;
817 uint32_t uNewContext = 0;
818 do
819 {
820 /* Create a new context ID ... */
821 uNewContext = ASMAtomicIncU32(&mNextContextID);
822 if (uNewContext == UINT32_MAX)
823 ASMAtomicUoWriteU32(&mNextContextID, 1000);
824 /* Is the context ID already used? */
825 it = getCtrlCallbackContextByID(uNewContext);
826 } while(it != mCallbackList.end());
827
828 uint32_t nCallbacks = 0;
829 if ( it == mCallbackList.end()
830 && uNewContext > 0)
831 {
832 /* We apparently got an unused context ID, let's use it! */
833 context.mContextID = uNewContext;
834 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
835 mCallbackList.push_back(context);
836 nCallbacks = mCallbackList.size();
837 }
838 else
839 {
840 /* Should never happen ... */
841 {
842 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
843 nCallbacks = mCallbackList.size();
844 }
845 AssertReleaseMsg(uNewContext, ("No free context ID found! uNewContext=%u, nCallbacks=%u", uNewContext, nCallbacks));
846 }
847
848#if 0
849 if (nCallbacks > 256) /* Don't let the container size get too big! */
850 {
851 Guest::CallbackListIter it = mCallbackList.begin();
852 destroyCtrlCallbackContext(it);
853 {
854 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
855 mCallbackList.erase(it);
856 }
857 }
858#endif
859 return uNewContext;
860}
861#endif /* VBOX_WITH_GUEST_CONTROL */
862
863STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
864 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
865 IN_BSTR aUserName, IN_BSTR aPassword,
866 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
867{
868/** @todo r=bird: Eventually we should clean up all the timeout parameters
869 * in the API and have the same way of specifying infinite waits! */
870#ifndef VBOX_WITH_GUEST_CONTROL
871 ReturnComNotImplemented();
872#else /* VBOX_WITH_GUEST_CONTROL */
873 using namespace guestControl;
874
875 CheckComArgStrNotEmptyOrNull(aCommand);
876 CheckComArgOutPointerValid(aPID);
877 CheckComArgOutPointerValid(aProgress);
878
879 /* Do not allow anonymous executions (with system rights). */
880 if (RT_UNLIKELY((aUserName) == NULL || *(aUserName) == '\0'))
881 return setError(E_INVALIDARG, tr("No user name specified"));
882
883 AutoCaller autoCaller(this);
884 if (FAILED(autoCaller.rc())) return autoCaller.rc();
885
886 if (aFlags != 0) /* Flags are not supported at the moment. */
887 return E_INVALIDARG;
888
889 HRESULT rc = S_OK;
890
891 try
892 {
893 /*
894 * Create progress object. Note that this is a multi operation
895 * object to perform the following steps:
896 * - Operation 1 (0): Create/start process.
897 * - Operation 2 (1): Wait for process to exit.
898 * If this progress completed successfully (S_OK), the process
899 * started and exited normally. In any other case an error/exception
900 * occured.
901 */
902 ComObjPtr <Progress> progress;
903 rc = progress.createObject();
904 if (SUCCEEDED(rc))
905 {
906 rc = progress->init(static_cast<IGuest*>(this),
907 BstrFmt(tr("Executing process")),
908 TRUE,
909 2, /* Number of operations. */
910 BstrFmt(tr("Starting process ..."))); /* Description of first stage. */
911 }
912 if (FAILED(rc)) return rc;
913
914 /*
915 * Prepare process execution.
916 */
917 int vrc = VINF_SUCCESS;
918 Utf8Str Utf8Command(aCommand);
919
920 /* Adjust timeout */
921 if (aTimeoutMS == 0)
922 aTimeoutMS = UINT32_MAX;
923
924 /* Prepare arguments. */
925 char **papszArgv = NULL;
926 uint32_t uNumArgs = 0;
927 if (aArguments > 0)
928 {
929 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
930 uNumArgs = args.size();
931 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
932 AssertReturn(papszArgv, E_OUTOFMEMORY);
933 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
934 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
935 papszArgv[uNumArgs] = NULL;
936 }
937
938 Utf8Str Utf8UserName(aUserName);
939 Utf8Str Utf8Password(aPassword);
940 if (RT_SUCCESS(vrc))
941 {
942 uint32_t uContextID = 0;
943
944 char *pszArgs = NULL;
945 if (uNumArgs > 0)
946 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, 0);
947 if (RT_SUCCESS(vrc))
948 {
949 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
950
951 /* Prepare environment. */
952 void *pvEnv = NULL;
953 uint32_t uNumEnv = 0;
954 uint32_t cbEnv = 0;
955 if (aEnvironment > 0)
956 {
957 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
958
959 for (unsigned i = 0; i < env.size(); i++)
960 {
961 vrc = prepareExecuteEnv(Utf8Str(env[i]).raw(), &pvEnv, &cbEnv, &uNumEnv);
962 if (RT_FAILURE(vrc))
963 break;
964 }
965 }
966
967 if (RT_SUCCESS(vrc))
968 {
969 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECSTATUS));
970 AssertReturn(pData, VBOX_E_IPRT_ERROR);
971 RT_ZERO(*pData);
972 uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_START,
973 pData, sizeof(CALLBACKDATAEXECSTATUS), progress);
974 Assert(uContextID > 0);
975
976 VBOXHGCMSVCPARM paParms[15];
977 int i = 0;
978 paParms[i++].setUInt32(uContextID);
979 paParms[i++].setPointer((void*)Utf8Command.raw(), (uint32_t)strlen(Utf8Command.raw()) + 1);
980 paParms[i++].setUInt32(aFlags);
981 paParms[i++].setUInt32(uNumArgs);
982 paParms[i++].setPointer((void*)pszArgs, cbArgs);
983 paParms[i++].setUInt32(uNumEnv);
984 paParms[i++].setUInt32(cbEnv);
985 paParms[i++].setPointer((void*)pvEnv, cbEnv);
986 paParms[i++].setPointer((void*)Utf8UserName.raw(), (uint32_t)strlen(Utf8UserName.raw()) + 1);
987 paParms[i++].setPointer((void*)Utf8Password.raw(), (uint32_t)strlen(Utf8Password.raw()) + 1);
988 paParms[i++].setUInt32(aTimeoutMS);
989
990 VMMDev *vmmDev;
991 {
992 /* Make sure mParent is valid, so set the read lock while using.
993 * Do not keep this lock while doing the actual call, because in the meanwhile
994 * another thread could request a write lock which would be a bad idea ... */
995 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
996
997 /* Forward the information to the VMM device. */
998 AssertPtr(mParent);
999 vmmDev = mParent->getVMMDev();
1000 }
1001
1002 if (vmmDev)
1003 {
1004 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1005 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1006 i, paParms);
1007 }
1008 else
1009 vrc = VERR_INVALID_VM_HANDLE;
1010 RTMemFree(pvEnv);
1011 }
1012 RTStrFree(pszArgs);
1013 }
1014 if (RT_SUCCESS(vrc))
1015 {
1016 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1017
1018 /*
1019 * Wait for the HGCM low level callback until the process
1020 * has been started (or something went wrong). This is necessary to
1021 * get the PID.
1022 */
1023 CallbackListIter it = getCtrlCallbackContextByID(uContextID);
1024 BOOL fCanceled = FALSE;
1025 if (it != mCallbackList.end())
1026 {
1027 ComAssert(it->pProgress.isNotNull());
1028
1029 /*
1030 * Wait for the first stage (=0) to complete (that is starting the process).
1031 */
1032 PCALLBACKDATAEXECSTATUS pData = NULL;
1033 rc = it->pProgress->WaitForOperationCompletion(0, aTimeoutMS);
1034 if (SUCCEEDED(rc))
1035 {
1036 /* Was the operation canceled by one of the parties? */
1037 rc = it->pProgress->COMGETTER(Canceled)(&fCanceled);
1038 if (FAILED(rc)) throw rc;
1039
1040 if (!fCanceled)
1041 {
1042 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1043
1044 pData = (PCALLBACKDATAEXECSTATUS)it->pvData;
1045 Assert(it->cbData == sizeof(CALLBACKDATAEXECSTATUS));
1046 AssertPtr(pData);
1047
1048 /* Did we get some status? */
1049 switch (pData->u32Status)
1050 {
1051 case PROC_STS_STARTED:
1052 /* Process is (still) running; get PID. */
1053 *aPID = pData->u32PID;
1054 break;
1055
1056 /* In any other case the process either already
1057 * terminated or something else went wrong, so no PID ... */
1058 case PROC_STS_TEN: /* Terminated normally. */
1059 case PROC_STS_TEA: /* Terminated abnormally. */
1060 case PROC_STS_TES: /* Terminated through signal. */
1061 case PROC_STS_TOK:
1062 case PROC_STS_TOA:
1063 case PROC_STS_DWN:
1064 /*
1065 * Process (already) ended, but we want to get the
1066 * PID anyway to retrieve the output in a later call.
1067 */
1068 *aPID = pData->u32PID;
1069 break;
1070
1071 case PROC_STS_ERROR:
1072 vrc = pData->u32Flags; /* u32Flags member contains IPRT error code. */
1073 break;
1074
1075 case PROC_STS_UNDEFINED:
1076 vrc = VERR_TIMEOUT; /* Operation did not complete within time. */
1077 break;
1078
1079 default:
1080 vrc = VERR_INVALID_PARAMETER; /* Unknown status, should never happen! */
1081 break;
1082 }
1083 }
1084 else /* Operation was canceled. */
1085 vrc = VERR_CANCELLED;
1086 }
1087 else /* Operation did not complete within time. */
1088 vrc = VERR_TIMEOUT;
1089
1090 /*
1091 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1092 * else (like end of process) ...
1093 */
1094 if (RT_FAILURE(vrc))
1095 {
1096 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1097 {
1098 rc = setError(VBOX_E_IPRT_ERROR,
1099 tr("The file '%s' was not found on guest"), Utf8Command.raw());
1100 }
1101 else if (vrc == VERR_PATH_NOT_FOUND)
1102 {
1103 rc = setError(VBOX_E_IPRT_ERROR,
1104 tr("The path to file '%s' was not found on guest"), Utf8Command.raw());
1105 }
1106 else if (vrc == VERR_BAD_EXE_FORMAT)
1107 {
1108 rc = setError(VBOX_E_IPRT_ERROR,
1109 tr("The file '%s' is not an executable format on guest"), Utf8Command.raw());
1110 }
1111 else if (vrc == VERR_LOGON_FAILURE)
1112 {
1113 rc = setError(VBOX_E_IPRT_ERROR,
1114 tr("The specified user '%s' was not able to logon on guest"), Utf8UserName.raw());
1115 }
1116 else if (vrc == VERR_TIMEOUT)
1117 {
1118 rc = setError(VBOX_E_IPRT_ERROR,
1119 tr("The guest did not respond within time (%ums)"), aTimeoutMS);
1120 }
1121 else if (vrc == VERR_CANCELLED)
1122 {
1123 rc = setError(VBOX_E_IPRT_ERROR,
1124 tr("The execution operation was canceled"));
1125 }
1126 else if (vrc == VERR_PERMISSION_DENIED)
1127 {
1128 rc = setError(VBOX_E_IPRT_ERROR,
1129 tr("Invalid user/password credentials"));
1130 }
1131 else
1132 {
1133 if (pData && pData->u32Status == PROC_STS_ERROR)
1134 rc = setError(VBOX_E_IPRT_ERROR,
1135 tr("Process could not be started: %Rrc"), pData->u32Flags);
1136 else
1137 rc = setError(E_UNEXPECTED,
1138 tr("The service call failed with error %Rrc"), vrc);
1139 }
1140 }
1141 else /* Execution went fine. */
1142 {
1143 /* Return the progress to the caller. */
1144 progress.queryInterfaceTo(aProgress);
1145 }
1146 }
1147 else /* Callback context not found; should never happen! */
1148 AssertMsg(it != mCallbackList.end(), ("Callback context with ID %u not found!", uContextID));
1149 }
1150 else /* HGCM related error codes .*/
1151 {
1152 if (vrc == VERR_INVALID_VM_HANDLE)
1153 {
1154 rc = setError(VBOX_E_VM_ERROR,
1155 tr("VMM device is not available (is the VM running?)"));
1156 }
1157 else if (vrc == VERR_TIMEOUT)
1158 {
1159 rc = setError(VBOX_E_VM_ERROR,
1160 tr("The guest execution service is not ready"));
1161 }
1162 else /* HGCM call went wrong. */
1163 {
1164 rc = setError(E_UNEXPECTED,
1165 tr("The HGCM call failed with error %Rrc"), vrc);
1166 }
1167 }
1168
1169 for (unsigned i = 0; i < uNumArgs; i++)
1170 RTMemFree(papszArgv[i]);
1171 RTMemFree(papszArgv);
1172 }
1173 }
1174 catch (std::bad_alloc &)
1175 {
1176 rc = E_OUTOFMEMORY;
1177 }
1178 return rc;
1179#endif /* VBOX_WITH_GUEST_CONTROL */
1180}
1181
1182STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
1183{
1184/** @todo r=bird: Eventually we should clean up all the timeout parameters
1185 * in the API and have the same way of specifying infinite waits! */
1186#ifndef VBOX_WITH_GUEST_CONTROL
1187 ReturnComNotImplemented();
1188#else /* VBOX_WITH_GUEST_CONTROL */
1189 using namespace guestControl;
1190
1191 CheckComArgExpr(aPID, aPID > 0);
1192
1193 if (aFlags != 0) /* Flags are not supported at the moment. */
1194 return E_INVALIDARG;
1195
1196 AutoCaller autoCaller(this);
1197 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1198
1199 HRESULT rc = S_OK;
1200
1201 try
1202 {
1203 /*
1204 * Create progress object.
1205 * This progress object, compared to the one in executeProgress() above,
1206 * is only local and is used to determine whether the operation finished
1207 * or got cancelled.
1208 */
1209 ComObjPtr <Progress> progress;
1210 rc = progress.createObject();
1211 if (SUCCEEDED(rc))
1212 {
1213 rc = progress->init(static_cast<IGuest*>(this),
1214 BstrFmt(tr("Getting output of process")),
1215 TRUE);
1216 }
1217 if (FAILED(rc)) return rc;
1218
1219 /* Adjust timeout */
1220 if (aTimeoutMS == 0)
1221 aTimeoutMS = UINT32_MAX;
1222
1223 /* Search for existing PID. */
1224 PCALLBACKDATAEXECOUT pData = (CALLBACKDATAEXECOUT*)RTMemAlloc(sizeof(CALLBACKDATAEXECOUT));
1225 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1226 RT_ZERO(*pData);
1227 uint32_t uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT,
1228 pData, sizeof(CALLBACKDATAEXECOUT), progress);
1229 Assert(uContextID > 0);
1230
1231 size_t cbData = (size_t)RT_MIN(aSize, _64K);
1232 com::SafeArray<BYTE> outputData(cbData);
1233
1234 VBOXHGCMSVCPARM paParms[5];
1235 int i = 0;
1236 paParms[i++].setUInt32(uContextID);
1237 paParms[i++].setUInt32(aPID);
1238 paParms[i++].setUInt32(aFlags); /** @todo Should represent stdout and/or stderr. */
1239
1240 int vrc = VINF_SUCCESS;
1241
1242 {
1243 VMMDev *vmmDev;
1244 {
1245 /* Make sure mParent is valid, so set the read lock while using.
1246 * Do not keep this lock while doing the actual call, because in the meanwhile
1247 * another thread could request a write lock which would be a bad idea ... */
1248 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1249
1250 /* Forward the information to the VMM device. */
1251 AssertPtr(mParent);
1252 vmmDev = mParent->getVMMDev();
1253 }
1254
1255 if (vmmDev)
1256 {
1257 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1258 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
1259 i, paParms);
1260 }
1261 }
1262
1263 if (RT_SUCCESS(vrc))
1264 {
1265 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1266
1267 /*
1268 * Wait for the HGCM low level callback until the process
1269 * has been started (or something went wrong). This is necessary to
1270 * get the PID.
1271 */
1272 CallbackListIter it = getCtrlCallbackContextByID(uContextID);
1273 BOOL fCanceled = FALSE;
1274 if (it != mCallbackList.end())
1275 {
1276 ComAssert(it->pProgress.isNotNull());
1277
1278 /* Wait until operation completed. */
1279 rc = it->pProgress->WaitForCompletion(aTimeoutMS);
1280 if (FAILED(rc)) throw rc;
1281
1282 /* Was the operation canceled by one of the parties? */
1283 rc = it->pProgress->COMGETTER(Canceled)(&fCanceled);
1284 if (FAILED(rc)) throw rc;
1285
1286 if (!fCanceled)
1287 {
1288 BOOL fCompleted;
1289 if ( SUCCEEDED(it->pProgress->COMGETTER(Completed)(&fCompleted))
1290 && fCompleted)
1291 {
1292 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1293
1294 /* Did we get some output? */
1295 pData = (PCALLBACKDATAEXECOUT)it->pvData;
1296 Assert(it->cbData == sizeof(CALLBACKDATAEXECOUT));
1297 AssertPtr(pData);
1298
1299 if (pData->cbData)
1300 {
1301 /* Do we need to resize the array? */
1302 if (pData->cbData > cbData)
1303 outputData.resize(pData->cbData);
1304
1305 /* Fill output in supplied out buffer. */
1306 memcpy(outputData.raw(), pData->pvData, pData->cbData);
1307 outputData.resize(pData->cbData); /* Shrink to fit actual buffer size. */
1308 }
1309 else
1310 vrc = VERR_NO_DATA; /* This is not an error we want to report to COM. */
1311 }
1312 else /* If callback not called within time ... well, that's a timeout! */
1313 vrc = VERR_TIMEOUT;
1314 }
1315 else /* Operation was canceled. */
1316 {
1317 vrc = VERR_CANCELLED;
1318 }
1319
1320 if (RT_FAILURE(vrc))
1321 {
1322 if (vrc == VERR_NO_DATA)
1323 {
1324 /* This is not an error we want to report to COM. */
1325 rc = S_OK;
1326 }
1327 else if (vrc == VERR_TIMEOUT)
1328 {
1329 rc = setError(VBOX_E_IPRT_ERROR,
1330 tr("The guest did not output within time (%ums)"), aTimeoutMS);
1331 }
1332 else if (vrc == VERR_CANCELLED)
1333 {
1334 rc = setError(VBOX_E_IPRT_ERROR,
1335 tr("The output operation was canceled"));
1336 }
1337 else
1338 {
1339 rc = setError(E_UNEXPECTED,
1340 tr("The service call failed with error %Rrc"), vrc);
1341 }
1342 }
1343
1344 {
1345 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1346 destroyCtrlCallbackContext(it);
1347 }
1348
1349 /* Remove callback context (not used anymore). */
1350 mCallbackList.erase(it);
1351 }
1352 else /* PID lookup failed. */
1353 rc = setError(VBOX_E_IPRT_ERROR,
1354 tr("Process (PID %u) not found!"), aPID);
1355 }
1356 else /* HGCM operation failed. */
1357 rc = setError(E_UNEXPECTED,
1358 tr("The HGCM call failed with error %Rrc"), vrc);
1359
1360 /* Cleanup. */
1361 progress->uninit();
1362 progress.setNull();
1363
1364 /* If something failed (or there simply was no data, indicated by VERR_NO_DATA,
1365 * we return an empty array so that the frontend knows when to give up. */
1366 if (RT_FAILURE(vrc) || FAILED(rc))
1367 outputData.resize(0);
1368 outputData.detachTo(ComSafeArrayOutArg(aData));
1369 }
1370 catch (std::bad_alloc &)
1371 {
1372 rc = E_OUTOFMEMORY;
1373 }
1374 return rc;
1375#endif
1376}
1377
1378STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ULONG *aStatus)
1379{
1380#ifndef VBOX_WITH_GUEST_CONTROL
1381 ReturnComNotImplemented();
1382#else /* VBOX_WITH_GUEST_CONTROL */
1383 using namespace guestControl;
1384
1385 AutoCaller autoCaller(this);
1386 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1387
1388 HRESULT rc = S_OK;
1389
1390 try
1391 {
1392 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1393
1394 GuestProcessIterConst it;
1395 for (it = mGuestProcessList.begin(); it != mGuestProcessList.end(); it++)
1396 {
1397 if (it->mPID == aPID)
1398 break;
1399 }
1400
1401 if (it != mGuestProcessList.end())
1402 {
1403 *aExitCode = it->mExitCode;
1404 *aFlags = it->mFlags;
1405 *aStatus = it->mStatus;
1406 }
1407 else
1408 rc = setError(VBOX_E_IPRT_ERROR,
1409 tr("Process (PID %u) not found!"), aPID);
1410 }
1411 catch (std::bad_alloc &)
1412 {
1413 rc = E_OUTOFMEMORY;
1414 }
1415 return rc;
1416#endif
1417}
1418
1419// public methods only for internal purposes
1420/////////////////////////////////////////////////////////////////////////////
1421
1422void Guest::setAdditionsVersion(Bstr aVersion, VBOXOSTYPE aOsType)
1423{
1424 AutoCaller autoCaller(this);
1425 AssertComRCReturnVoid (autoCaller.rc());
1426
1427 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1428
1429 mData.mAdditionsVersion = aVersion;
1430 mData.mAdditionsActive = !aVersion.isEmpty();
1431 /* Older Additions didn't have this finer grained capability bit,
1432 * so enable it by default. Newer Additions will disable it immediately
1433 * if relevant. */
1434 mData.mSupportsGraphics = mData.mAdditionsActive;
1435
1436 mData.mOSTypeId = Global::OSTypeId (aOsType);
1437}
1438
1439void Guest::setSupportsSeamless (BOOL aSupportsSeamless)
1440{
1441 AutoCaller autoCaller(this);
1442 AssertComRCReturnVoid (autoCaller.rc());
1443
1444 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1445
1446 mData.mSupportsSeamless = aSupportsSeamless;
1447}
1448
1449void Guest::setSupportsGraphics (BOOL aSupportsGraphics)
1450{
1451 AutoCaller autoCaller(this);
1452 AssertComRCReturnVoid (autoCaller.rc());
1453
1454 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1455
1456 mData.mSupportsGraphics = aSupportsGraphics;
1457}
1458/* 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