VirtualBox

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

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

IPRT: Removed VERR_LOGON_FAILURE in favor of VERR_AUTHENTICATION_FAILURE. Cleaned up nits in process-win.cpp and adding some missing function docs. Hope it compiles...

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