VirtualBox

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

Last change on this file since 30787 was 30778, checked in by vboxsync, 14 years ago

Guest Additions status: Use more enums.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 53.2 KB
Line 
1/* $Id: GuestImpl.cpp 30778 2010-07-12 08:40:54Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM class implementation
6 */
7
8/*
9 * Copyright (C) 2006-2010 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 CallbackMapIter it;
127 for (it = mCallbackMap.begin(); it != mCallbackMap.end(); it++)
128 destroyCtrlCallbackContext(it);
129
130 /* Clear process map. */
131 mGuestProcessMap.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 vrc = VINF_SUCCESS;
548
549 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
550
551 AssertPtr(pData);
552 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
553
554 /* Callback can be called several times. */
555 if (it != mCallbackMap.end())
556 {
557 PCALLBACKDATAEXECSTATUS pCBData = (PCALLBACKDATAEXECSTATUS)it->second.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 Utf8Str errMsg;
566
567 /* Was progress canceled before? */
568 BOOL fCanceled;
569 ComAssert(!it->second.pProgress.isNull());
570 if ( SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled))
571 && !fCanceled)
572 {
573 /* Do progress handling. */
574 HRESULT hr;
575 switch (pData->u32Status)
576 {
577 case PROC_STS_STARTED:
578 hr = it->second.pProgress->SetNextOperation(BstrFmt(tr("Waiting for process to exit ...")), 1 /* Weight */);
579 AssertComRC(hr);
580 break;
581
582 case PROC_STS_TEN: /* Terminated normally. */
583 hr = it->second.pProgress->notifyComplete(S_OK);
584 AssertComRC(hr);
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 vrc = VERR_INVALID_PARAMETER;
617 break;
618 }
619
620 /* Handle process map. */
621 /** @todo What happens on/deal with PID reuse? */
622 /** @todo How to deal with multiple updates at once? */
623 if (pCBData->u32PID > 0)
624 {
625 GuestProcessMapIter it_proc = getProcessByPID(pCBData->u32PID);
626 if (it_proc == mGuestProcessMap.end())
627 {
628 /* Not found, add to map. */
629 GuestProcess newProcess;
630 newProcess.mStatus = pCBData->u32Status;
631 newProcess.mExitCode = pCBData->u32Flags; /* Contains exit code. */
632 newProcess.mFlags = 0;
633
634 mGuestProcessMap[pCBData->u32PID] = newProcess;
635 }
636 else /* Update map. */
637 {
638 it_proc->second.mStatus = pCBData->u32Status;
639 it_proc->second.mExitCode = pCBData->u32Flags; /* Contains exit code. */
640 it_proc->second.mFlags = 0;
641 }
642 }
643 }
644 else
645 errMsg = Utf8StrFmt(Guest::tr("Process execution canceled"));
646
647 if (!it->second.pProgress->getCompleted())
648 {
649 if ( errMsg.length()
650 || fCanceled) /* If canceled we have to report E_FAIL! */
651 {
652 HRESULT hr2 = it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
653 COM_IIDOF(IGuest),
654 Guest::getStaticComponentName(),
655 "%s", errMsg.c_str());
656 AssertComRC(hr2);
657 LogFlowFunc(("Process (context ID=%u, status=%u) reported error: %s\n",
658 pData->hdr.u32ContextID, pData->u32Status, errMsg.c_str()));
659 }
660 }
661 }
662 else
663 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
664 LogFlowFunc(("Returned with rc=%Rrc\n", vrc));
665 return vrc;
666}
667
668/* Function for handling the execution output notification. */
669int Guest::notifyCtrlExecOut(uint32_t u32Function,
670 PCALLBACKDATAEXECOUT pData)
671{
672 int rc = VINF_SUCCESS;
673
674 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
675
676 AssertPtr(pData);
677 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
678 if (it != mCallbackMap.end())
679 {
680 PCALLBACKDATAEXECOUT pCBData = (CALLBACKDATAEXECOUT*)it->second.pvData;
681 AssertPtr(pCBData);
682
683 pCBData->u32PID = pData->u32PID;
684 pCBData->u32HandleId = pData->u32HandleId;
685 pCBData->u32Flags = pData->u32Flags;
686
687 /* Make sure we really got something! */
688 if ( pData->cbData
689 && pData->pvData)
690 {
691 /* Allocate data buffer and copy it */
692 pCBData->pvData = RTMemAlloc(pData->cbData);
693 pCBData->cbData = pData->cbData;
694
695 AssertReturn(pCBData->pvData, VERR_NO_MEMORY);
696 memcpy(pCBData->pvData, pData->pvData, pData->cbData);
697 }
698 else
699 {
700 pCBData->pvData = NULL;
701 pCBData->cbData = 0;
702 }
703
704 /* Was progress canceled before? */
705 BOOL fCanceled;
706 ComAssert(!it->second.pProgress.isNull());
707 if (SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled)) && fCanceled)
708 {
709 it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
710 COM_IIDOF(IGuest),
711 Guest::getStaticComponentName(),
712 Guest::tr("The output operation was canceled"));
713 }
714 else
715 it->second.pProgress->notifyComplete(S_OK);
716 }
717 else
718 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
719 return rc;
720}
721
722int Guest::notifyCtrlClientDisconnected(uint32_t u32Function,
723 PCALLBACKDATACLIENTDISCONNECTED pData)
724{
725 int rc = VINF_SUCCESS;
726
727 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
728 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
729 if (it != mCallbackMap.end())
730 {
731 LogFlowFunc(("Client with context ID=%u disconnected\n", it->first));
732 destroyCtrlCallbackContext(it);
733 }
734 return rc;
735}
736
737Guest::CallbackMapIter Guest::getCtrlCallbackContextByID(uint32_t u32ContextID)
738{
739 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
740 return mCallbackMap.find(u32ContextID);
741}
742
743Guest::GuestProcessMapIter Guest::getProcessByPID(uint32_t u32PID)
744{
745 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
746 return mGuestProcessMap.find(u32PID);
747}
748
749/* No locking here; */
750void Guest::destroyCtrlCallbackContext(Guest::CallbackMapIter it)
751{
752 LogFlowFunc(("Destroying callback with CID=%u ...\n", it->first));
753
754 if (it->second.pvData)
755 {
756 RTMemFree(it->second.pvData);
757 it->second.pvData = NULL;
758 it->second.cbData = 0;
759 }
760
761 /* Notify outstanding waits for progress ... */
762 if ( it->second.pProgress
763 && !it->second.pProgress.isNull())
764 {
765 LogFlowFunc(("Handling progress for CID=%u ...\n", it->first));
766
767 /*
768 * Assume we didn't complete to make sure we clean up even if the
769 * following call fails.
770 */
771 BOOL fCompleted = FALSE;
772 it->second.pProgress->COMGETTER(Completed)(&fCompleted);
773 if (!fCompleted)
774 {
775 LogFlowFunc(("Progress of CID=%u *not* completed, cancelling ...\n", it->first));
776
777 /* Only cancel if not canceled before! */
778 BOOL fCanceled;
779 if (SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled)) && !fCanceled)
780 it->second.pProgress->Cancel();
781
782 /*
783 * To get waitForCompletion completed (unblocked) we have to notify it if necessary (only
784 * cancle won't work!). This could happen if the client thread (e.g. VBoxService, thread of a spawned process)
785 * is disconnecting without having the chance to sending a status message before, so we
786 * have to abort here to make sure the host never hangs/gets stuck while waiting for the
787 * progress object to become signalled.
788 */
789 it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
790 COM_IIDOF(IGuest),
791 Guest::getStaticComponentName(),
792 Guest::tr("The operation was canceled because client is shutting down"));
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 map. 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 CallbackMapIter 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 != mCallbackMap.end());
827
828 uint32_t nCallbacks = 0;
829 if ( it == mCallbackMap.end()
830 && uNewContext > 0)
831 {
832 /* We apparently got an unused context ID, let's use it! */
833 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
834 mCallbackMap[uNewContext] = context;
835 nCallbacks = mCallbackMap.size();
836 }
837 else
838 {
839 /* Should never happen ... */
840 {
841 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
842 nCallbacks = mCallbackMap.size();
843 }
844 AssertReleaseMsg(uNewContext, ("No free context ID found! uNewContext=%u, nCallbacks=%u", uNewContext, nCallbacks));
845 }
846
847#if 0
848 if (nCallbacks > 256) /* Don't let the container size get too big! */
849 {
850 Guest::CallbackListIter it = mCallbackList.begin();
851 destroyCtrlCallbackContext(it);
852 {
853 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
854 mCallbackList.erase(it);
855 }
856 }
857#endif
858 return uNewContext;
859}
860#endif /* VBOX_WITH_GUEST_CONTROL */
861
862STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
863 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
864 IN_BSTR aUserName, IN_BSTR aPassword,
865 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
866{
867/** @todo r=bird: Eventually we should clean up all the timeout parameters
868 * in the API and have the same way of specifying infinite waits! */
869#ifndef VBOX_WITH_GUEST_CONTROL
870 ReturnComNotImplemented();
871#else /* VBOX_WITH_GUEST_CONTROL */
872 using namespace guestControl;
873
874 CheckComArgStrNotEmptyOrNull(aCommand);
875 CheckComArgOutPointerValid(aPID);
876 CheckComArgOutPointerValid(aProgress);
877
878 /* Do not allow anonymous executions (with system rights). */
879 if (RT_UNLIKELY((aUserName) == NULL || *(aUserName) == '\0'))
880 return setError(E_INVALIDARG, tr("No user name specified"));
881
882 AutoCaller autoCaller(this);
883 if (FAILED(autoCaller.rc())) return autoCaller.rc();
884
885 if (aFlags != 0) /* Flags are not supported at the moment. */
886 return E_INVALIDARG;
887
888 HRESULT rc = S_OK;
889
890 try
891 {
892 /*
893 * Create progress object. Note that this is a multi operation
894 * object to perform the following steps:
895 * - Operation 1 (0): Create/start process.
896 * - Operation 2 (1): Wait for process to exit.
897 * If this progress completed successfully (S_OK), the process
898 * started and exited normally. In any other case an error/exception
899 * occured.
900 */
901 ComObjPtr <Progress> progress;
902 rc = progress.createObject();
903 if (SUCCEEDED(rc))
904 {
905 rc = progress->init(static_cast<IGuest*>(this),
906 BstrFmt(tr("Executing process")),
907 TRUE,
908 2, /* Number of operations. */
909 BstrFmt(tr("Starting process ..."))); /* Description of first stage. */
910 }
911 if (FAILED(rc)) return rc;
912
913 /*
914 * Prepare process execution.
915 */
916 int vrc = VINF_SUCCESS;
917 Utf8Str Utf8Command(aCommand);
918
919 /* Adjust timeout */
920 if (aTimeoutMS == 0)
921 aTimeoutMS = UINT32_MAX;
922
923 /* Prepare arguments. */
924 char **papszArgv = NULL;
925 uint32_t uNumArgs = 0;
926 if (aArguments > 0)
927 {
928 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
929 uNumArgs = args.size();
930 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
931 AssertReturn(papszArgv, E_OUTOFMEMORY);
932 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
933 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
934 papszArgv[uNumArgs] = NULL;
935 }
936
937 Utf8Str Utf8UserName(aUserName);
938 Utf8Str Utf8Password(aPassword);
939 if (RT_SUCCESS(vrc))
940 {
941 uint32_t uContextID = 0;
942
943 char *pszArgs = NULL;
944 if (uNumArgs > 0)
945 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, 0);
946 if (RT_SUCCESS(vrc))
947 {
948 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
949
950 /* Prepare environment. */
951 void *pvEnv = NULL;
952 uint32_t uNumEnv = 0;
953 uint32_t cbEnv = 0;
954 if (aEnvironment > 0)
955 {
956 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
957
958 for (unsigned i = 0; i < env.size(); i++)
959 {
960 vrc = prepareExecuteEnv(Utf8Str(env[i]).raw(), &pvEnv, &cbEnv, &uNumEnv);
961 if (RT_FAILURE(vrc))
962 break;
963 }
964 }
965
966 if (RT_SUCCESS(vrc))
967 {
968 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECSTATUS));
969 AssertReturn(pData, VBOX_E_IPRT_ERROR);
970 RT_ZERO(*pData);
971 uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_START,
972 pData, sizeof(CALLBACKDATAEXECSTATUS), progress);
973 Assert(uContextID > 0);
974
975 VBOXHGCMSVCPARM paParms[15];
976 int i = 0;
977 paParms[i++].setUInt32(uContextID);
978 paParms[i++].setPointer((void*)Utf8Command.raw(), (uint32_t)strlen(Utf8Command.raw()) + 1);
979 paParms[i++].setUInt32(aFlags);
980 paParms[i++].setUInt32(uNumArgs);
981 paParms[i++].setPointer((void*)pszArgs, cbArgs);
982 paParms[i++].setUInt32(uNumEnv);
983 paParms[i++].setUInt32(cbEnv);
984 paParms[i++].setPointer((void*)pvEnv, cbEnv);
985 paParms[i++].setPointer((void*)Utf8UserName.raw(), (uint32_t)strlen(Utf8UserName.raw()) + 1);
986 paParms[i++].setPointer((void*)Utf8Password.raw(), (uint32_t)strlen(Utf8Password.raw()) + 1);
987 paParms[i++].setUInt32(aTimeoutMS);
988
989 VMMDev *vmmDev;
990 {
991 /* Make sure mParent is valid, so set the read lock while using.
992 * Do not keep this lock while doing the actual call, because in the meanwhile
993 * another thread could request a write lock which would be a bad idea ... */
994 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
995
996 /* Forward the information to the VMM device. */
997 AssertPtr(mParent);
998 vmmDev = mParent->getVMMDev();
999 }
1000
1001 if (vmmDev)
1002 {
1003 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1004 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1005 i, paParms);
1006 }
1007 else
1008 vrc = VERR_INVALID_VM_HANDLE;
1009 RTMemFree(pvEnv);
1010 }
1011 RTStrFree(pszArgs);
1012 }
1013 if (RT_SUCCESS(vrc))
1014 {
1015 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1016
1017 /*
1018 * Wait for the HGCM low level callback until the process
1019 * has been started (or something went wrong). This is necessary to
1020 * get the PID.
1021 */
1022 CallbackMapIter it = getCtrlCallbackContextByID(uContextID);
1023 BOOL fCanceled = FALSE;
1024 if (it != mCallbackMap.end())
1025 {
1026 ComAssert(!it->second.pProgress.isNull());
1027
1028 /*
1029 * Wait for the first stage (=0) to complete (that is starting the process).
1030 */
1031 PCALLBACKDATAEXECSTATUS pData = NULL;
1032 rc = it->second.pProgress->WaitForOperationCompletion(0, aTimeoutMS);
1033 if (SUCCEEDED(rc))
1034 {
1035 /* Was the operation canceled by one of the parties? */
1036 rc = it->second.pProgress->COMGETTER(Canceled)(&fCanceled);
1037 if (FAILED(rc)) throw rc;
1038
1039 if (!fCanceled)
1040 {
1041 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1042
1043 pData = (PCALLBACKDATAEXECSTATUS)it->second.pvData;
1044 Assert(it->second.cbData == sizeof(CALLBACKDATAEXECSTATUS));
1045 AssertPtr(pData);
1046
1047 /* Did we get some status? */
1048 switch (pData->u32Status)
1049 {
1050 case PROC_STS_STARTED:
1051 /* Process is (still) running; get PID. */
1052 *aPID = pData->u32PID;
1053 break;
1054
1055 /* In any other case the process either already
1056 * terminated or something else went wrong, so no PID ... */
1057 case PROC_STS_TEN: /* Terminated normally. */
1058 case PROC_STS_TEA: /* Terminated abnormally. */
1059 case PROC_STS_TES: /* Terminated through signal. */
1060 case PROC_STS_TOK:
1061 case PROC_STS_TOA:
1062 case PROC_STS_DWN:
1063 /*
1064 * Process (already) ended, but we want to get the
1065 * PID anyway to retrieve the output in a later call.
1066 */
1067 *aPID = pData->u32PID;
1068 break;
1069
1070 case PROC_STS_ERROR:
1071 vrc = pData->u32Flags; /* u32Flags member contains IPRT error code. */
1072 break;
1073
1074 case PROC_STS_UNDEFINED:
1075 vrc = VERR_TIMEOUT; /* Operation did not complete within time. */
1076 break;
1077
1078 default:
1079 vrc = VERR_INVALID_PARAMETER; /* Unknown status, should never happen! */
1080 break;
1081 }
1082 }
1083 else /* Operation was canceled. */
1084 vrc = VERR_CANCELLED;
1085 }
1086 else /* Operation did not complete within time. */
1087 vrc = VERR_TIMEOUT;
1088
1089 /*
1090 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1091 * else (like end of process) ...
1092 */
1093 if (RT_FAILURE(vrc))
1094 {
1095 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1096 {
1097 rc = setError(VBOX_E_IPRT_ERROR,
1098 tr("The file '%s' was not found on guest"), Utf8Command.raw());
1099 }
1100 else if (vrc == VERR_PATH_NOT_FOUND)
1101 {
1102 rc = setError(VBOX_E_IPRT_ERROR,
1103 tr("The path to file '%s' was not found on guest"), Utf8Command.raw());
1104 }
1105 else if (vrc == VERR_BAD_EXE_FORMAT)
1106 {
1107 rc = setError(VBOX_E_IPRT_ERROR,
1108 tr("The file '%s' is not an executable format on guest"), Utf8Command.raw());
1109 }
1110 else if (vrc == VERR_AUTHENTICATION_FAILURE)
1111 {
1112 rc = setError(VBOX_E_IPRT_ERROR,
1113 tr("The specified user '%s' was not able to logon on guest"), Utf8UserName.raw());
1114 }
1115 else if (vrc == VERR_TIMEOUT)
1116 {
1117 rc = setError(VBOX_E_IPRT_ERROR,
1118 tr("The guest did not respond within time (%ums)"), aTimeoutMS);
1119 }
1120 else if (vrc == VERR_CANCELLED)
1121 {
1122 rc = setError(VBOX_E_IPRT_ERROR,
1123 tr("The execution operation was canceled"));
1124 }
1125 else if (vrc == VERR_PERMISSION_DENIED)
1126 {
1127 rc = setError(VBOX_E_IPRT_ERROR,
1128 tr("Invalid user/password credentials"));
1129 }
1130 else
1131 {
1132 if (pData && pData->u32Status == PROC_STS_ERROR)
1133 rc = setError(VBOX_E_IPRT_ERROR,
1134 tr("Process could not be started: %Rrc"), pData->u32Flags);
1135 else
1136 rc = setError(E_UNEXPECTED,
1137 tr("The service call failed with error %Rrc"), vrc);
1138 }
1139 }
1140 else /* Execution went fine. */
1141 {
1142 /* Return the progress to the caller. */
1143 progress.queryInterfaceTo(aProgress);
1144 }
1145 }
1146 else /* Callback context not found; should never happen! */
1147 AssertMsg(it != mCallbackMap.end(), ("Callback context with ID %u not found!", uContextID));
1148 }
1149 else /* HGCM related error codes .*/
1150 {
1151 if (vrc == VERR_INVALID_VM_HANDLE)
1152 {
1153 rc = setError(VBOX_E_VM_ERROR,
1154 tr("VMM device is not available (is the VM running?)"));
1155 }
1156 else if (vrc == VERR_TIMEOUT)
1157 {
1158 rc = setError(VBOX_E_VM_ERROR,
1159 tr("The guest execution service is not ready"));
1160 }
1161 else /* HGCM call went wrong. */
1162 {
1163 rc = setError(E_UNEXPECTED,
1164 tr("The HGCM call failed with error %Rrc"), vrc);
1165 }
1166 }
1167
1168 for (unsigned i = 0; i < uNumArgs; i++)
1169 RTMemFree(papszArgv[i]);
1170 RTMemFree(papszArgv);
1171 }
1172 }
1173 catch (std::bad_alloc &)
1174 {
1175 rc = E_OUTOFMEMORY;
1176 }
1177 return rc;
1178#endif /* VBOX_WITH_GUEST_CONTROL */
1179}
1180
1181STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, ULONG64 aSize, ComSafeArrayOut(BYTE, aData))
1182{
1183/** @todo r=bird: Eventually we should clean up all the timeout parameters
1184 * in the API and have the same way of specifying infinite waits! */
1185#ifndef VBOX_WITH_GUEST_CONTROL
1186 ReturnComNotImplemented();
1187#else /* VBOX_WITH_GUEST_CONTROL */
1188 using namespace guestControl;
1189
1190 CheckComArgExpr(aPID, aPID > 0);
1191
1192 if (aFlags != 0) /* Flags are not supported at the moment. */
1193 return E_INVALIDARG;
1194
1195 AutoCaller autoCaller(this);
1196 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1197
1198 HRESULT rc = S_OK;
1199
1200 try
1201 {
1202 /*
1203 * Create progress object.
1204 * This progress object, compared to the one in executeProgress() above,
1205 * is only local and is used to determine whether the operation finished
1206 * or got canceled.
1207 */
1208 ComObjPtr <Progress> progress;
1209 rc = progress.createObject();
1210 if (SUCCEEDED(rc))
1211 {
1212 rc = progress->init(static_cast<IGuest*>(this),
1213 BstrFmt(tr("Getting output of process")),
1214 TRUE);
1215 }
1216 if (FAILED(rc)) return rc;
1217
1218 /* Adjust timeout */
1219 if (aTimeoutMS == 0)
1220 aTimeoutMS = UINT32_MAX;
1221
1222 /* Search for existing PID. */
1223 PCALLBACKDATAEXECOUT pData = (CALLBACKDATAEXECOUT*)RTMemAlloc(sizeof(CALLBACKDATAEXECOUT));
1224 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1225 RT_ZERO(*pData);
1226 uint32_t uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT,
1227 pData, sizeof(CALLBACKDATAEXECOUT), progress);
1228 Assert(uContextID > 0);
1229
1230 size_t cbData = (size_t)RT_MIN(aSize, _64K);
1231 com::SafeArray<BYTE> outputData(cbData);
1232
1233 VBOXHGCMSVCPARM paParms[5];
1234 int i = 0;
1235 paParms[i++].setUInt32(uContextID);
1236 paParms[i++].setUInt32(aPID);
1237 paParms[i++].setUInt32(aFlags); /** @todo Should represent stdout and/or stderr. */
1238
1239 int vrc = VINF_SUCCESS;
1240
1241 {
1242 VMMDev *vmmDev;
1243 {
1244 /* Make sure mParent is valid, so set the read lock while using.
1245 * Do not keep this lock while doing the actual call, because in the meanwhile
1246 * another thread could request a write lock which would be a bad idea ... */
1247 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1248
1249 /* Forward the information to the VMM device. */
1250 AssertPtr(mParent);
1251 vmmDev = mParent->getVMMDev();
1252 }
1253
1254 if (vmmDev)
1255 {
1256 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1257 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
1258 i, paParms);
1259 }
1260 }
1261
1262 if (RT_SUCCESS(vrc))
1263 {
1264 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1265
1266 /*
1267 * Wait for the HGCM low level callback until the process
1268 * has been started (or something went wrong). This is necessary to
1269 * get the PID.
1270 */
1271 CallbackMapIter it = getCtrlCallbackContextByID(uContextID);
1272 BOOL fCanceled = FALSE;
1273 if (it != mCallbackMap.end())
1274 {
1275 ComAssert(!it->second.pProgress.isNull());
1276
1277 /* Wait until operation completed. */
1278 rc = it->second.pProgress->WaitForCompletion(aTimeoutMS);
1279 if (FAILED(rc)) throw rc;
1280
1281 /* Was the operation canceled by one of the parties? */
1282 rc = it->second.pProgress->COMGETTER(Canceled)(&fCanceled);
1283 if (FAILED(rc)) throw rc;
1284
1285 if (!fCanceled)
1286 {
1287 BOOL fCompleted;
1288 if ( SUCCEEDED(it->second.pProgress->COMGETTER(Completed)(&fCompleted))
1289 && fCompleted)
1290 {
1291 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1292
1293 /* Did we get some output? */
1294 pData = (PCALLBACKDATAEXECOUT)it->second.pvData;
1295 Assert(it->second.cbData == sizeof(CALLBACKDATAEXECOUT));
1296 AssertPtr(pData);
1297
1298 if (pData->cbData)
1299 {
1300 /* Do we need to resize the array? */
1301 if (pData->cbData > cbData)
1302 outputData.resize(pData->cbData);
1303
1304 /* Fill output in supplied out buffer. */
1305 memcpy(outputData.raw(), pData->pvData, pData->cbData);
1306 outputData.resize(pData->cbData); /* Shrink to fit actual buffer size. */
1307 }
1308 else
1309 vrc = VERR_NO_DATA; /* This is not an error we want to report to COM. */
1310 }
1311 else /* If callback not called within time ... well, that's a timeout! */
1312 vrc = VERR_TIMEOUT;
1313 }
1314 else /* Operation was canceled. */
1315 {
1316 vrc = VERR_CANCELLED;
1317 }
1318
1319 if (RT_FAILURE(vrc))
1320 {
1321 if (vrc == VERR_NO_DATA)
1322 {
1323 /* This is not an error we want to report to COM. */
1324 rc = S_OK;
1325 }
1326 else if (vrc == VERR_TIMEOUT)
1327 {
1328 rc = setError(VBOX_E_IPRT_ERROR,
1329 tr("The guest did not output within time (%ums)"), aTimeoutMS);
1330 }
1331 else if (vrc == VERR_CANCELLED)
1332 {
1333 rc = setError(VBOX_E_IPRT_ERROR,
1334 tr("The output operation was canceled"));
1335 }
1336 else
1337 {
1338 rc = setError(E_UNEXPECTED,
1339 tr("The service call failed with error %Rrc"), vrc);
1340 }
1341 }
1342
1343 {
1344 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1345 /*
1346 * Destroy locally used progress object.
1347 */
1348 destroyCtrlCallbackContext(it);
1349 }
1350
1351 /* Remove callback context (not used anymore). */
1352 mCallbackMap.erase(it);
1353 }
1354 else /* PID lookup failed. */
1355 rc = setError(VBOX_E_IPRT_ERROR,
1356 tr("Process (PID %u) not found!"), aPID);
1357 }
1358 else /* HGCM operation failed. */
1359 rc = setError(E_UNEXPECTED,
1360 tr("The HGCM call failed with error %Rrc"), vrc);
1361
1362 /* Cleanup. */
1363 progress->uninit();
1364 progress.setNull();
1365
1366 /* If something failed (or there simply was no data, indicated by VERR_NO_DATA,
1367 * we return an empty array so that the frontend knows when to give up. */
1368 if (RT_FAILURE(vrc) || FAILED(rc))
1369 outputData.resize(0);
1370 outputData.detachTo(ComSafeArrayOutArg(aData));
1371 }
1372 catch (std::bad_alloc &)
1373 {
1374 rc = E_OUTOFMEMORY;
1375 }
1376 return rc;
1377#endif
1378}
1379
1380STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ULONG *aStatus)
1381{
1382#ifndef VBOX_WITH_GUEST_CONTROL
1383 ReturnComNotImplemented();
1384#else /* VBOX_WITH_GUEST_CONTROL */
1385 using namespace guestControl;
1386
1387 AutoCaller autoCaller(this);
1388 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1389
1390 HRESULT rc = S_OK;
1391
1392 try
1393 {
1394 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1395
1396 GuestProcessMapIterConst it = getProcessByPID(aPID);
1397 if (it != mGuestProcessMap.end())
1398 {
1399 *aExitCode = it->second.mExitCode;
1400 *aFlags = it->second.mFlags;
1401 *aStatus = it->second.mStatus;
1402 }
1403 else
1404 rc = setError(VBOX_E_IPRT_ERROR,
1405 tr("Process (PID %u) not found!"), aPID);
1406 }
1407 catch (std::bad_alloc &)
1408 {
1409 rc = E_OUTOFMEMORY;
1410 }
1411 return rc;
1412#endif
1413}
1414
1415// public methods only for internal purposes
1416/////////////////////////////////////////////////////////////////////////////
1417
1418/**
1419 * Sets the general Guest Additions information like
1420 * API version and OS type.
1421 *
1422 * @param aVersion
1423 * @param aOsType
1424 */
1425void Guest::setAdditionsInfo(Bstr aVersion, VBOXOSTYPE aOsType)
1426{
1427 AutoCaller autoCaller(this);
1428 AssertComRCReturnVoid (autoCaller.rc());
1429
1430 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1431
1432 /*
1433 * Set the Guest Additions API (interface) version.
1434 * Note that this is *not* the actual Guest Additions version and may differ!
1435 */
1436 mData.mAdditionsVersion = aVersion;
1437 /*
1438 * Older Additions rely on the Additions API version whether they
1439 * are assumed to be active or not. Newer additions will disable
1440 * this immediately.
1441 */
1442 mData.mAdditionsActive = !aVersion.isEmpty();
1443 /*
1444 * Older Additions didn't have this finer grained capability bit,
1445 * so enable it by default. Newer Additions will disable it immediately
1446 * if relevant.
1447 */
1448 mData.mSupportsGraphics = mData.mAdditionsActive;
1449
1450 /*
1451 * Note! There is a race going on between setting mAdditionsActive and
1452 * mSupportsGraphics here and disabling/enabling it later according to
1453 * its real status when using new(er) Guest Additions.
1454 */
1455
1456 mData.mOSTypeId = Global::OSTypeId (aOsType);
1457}
1458
1459/**
1460 * Sets the status of a certain Guest Additions facility.
1461 *
1462 * @param Facility
1463 * @param Status
1464 * @param ulFlags
1465 */
1466void Guest::setAdditionsStatus (VBoxGuestStatusFacility Facility, VBoxGuestStatusCurrent Status, ULONG ulFlags)
1467{
1468 AutoCaller autoCaller(this);
1469 AssertComRCReturnVoid (autoCaller.rc());
1470
1471 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1472
1473 /*
1474 * Only mark Guest Additions as active when VBoxService started up.
1475 */
1476 mData.mAdditionsActive = ( Facility == VBoxGuestStatusFacility_VBoxService
1477 && Status == VBoxGuestStatusCurrent_Active) ? TRUE : FALSE;
1478}
1479
1480/**
1481 * Sets the supported features (and whether they are active or not).
1482 *
1483 * @param ulCaps
1484 * @param ulActive
1485 */
1486void Guest::setSupportedFeatures (ULONG64 ulCaps, ULONG64 ulActive)
1487{
1488 AutoCaller autoCaller(this);
1489 AssertComRCReturnVoid (autoCaller.rc());
1490
1491 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1492
1493 mData.mSupportsSeamless = (ulCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS);
1494 /** @todo Add VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING */
1495 mData.mSupportsGraphics = (ulCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS);
1496}
1497/* vi: set tabstop=4 shiftwidth=4 expandtab: */
1498
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