VirtualBox

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

Last change on this file since 32854 was 32852, checked in by vboxsync, 14 years ago

Guest Execution:

  • Implemented "ignore orphaned childs" flag (--flags ignoreorphanedchilds); this flag will tell the host to not bitch about an executed process which still is alive when VBoxService (or the entire guest OS) shuts down.
  • Fixed shutdown/notification hang when waiting for std output which never arrives.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 63.0 KB
Line 
1/* $Id: GuestImpl.cpp 32852 2010-09-30 15:49:35Z 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 /* Confirm a successful initialization when it's the case */
75 autoInitSpan.setSucceeded();
76
77 ULONG aMemoryBalloonSize;
78 HRESULT ret = mParent->machine()->COMGETTER(MemoryBalloonSize)(&aMemoryBalloonSize);
79 if (ret == S_OK)
80 mMemoryBalloonSize = aMemoryBalloonSize;
81 else
82 mMemoryBalloonSize = 0; /* Default is no ballooning */
83
84 BOOL fPageFusionEnabled;
85 ret = mParent->machine()->COMGETTER(PageFusionEnabled)(&fPageFusionEnabled);
86 if (ret == S_OK)
87 mfPageFusionEnabled = fPageFusionEnabled;
88 else
89 mfPageFusionEnabled = false; /* Default is no page fusion*/
90
91 mStatUpdateInterval = 0; /* Default is not to report guest statistics at all */
92
93 /* Clear statistics. */
94 for (unsigned i = 0 ; i < GUESTSTATTYPE_MAX; i++)
95 mCurrentGuestStat[i] = 0;
96
97#ifdef VBOX_WITH_GUEST_CONTROL
98 /* Init the context ID counter at 1000. */
99 mNextContextID = 1000;
100#endif
101
102 return S_OK;
103}
104
105/**
106 * Uninitializes the instance and sets the ready flag to FALSE.
107 * Called either from FinalRelease() or by the parent when it gets destroyed.
108 */
109void Guest::uninit()
110{
111 LogFlowThisFunc(("\n"));
112
113#ifdef VBOX_WITH_GUEST_CONTROL
114 /* Scope write lock as much as possible. */
115 {
116 /*
117 * Cleanup must be done *before* AutoUninitSpan to cancel all
118 * all outstanding waits in API functions (which hold AutoCaller
119 * ref counts).
120 */
121 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
122
123 /* Clean up callback data. */
124 CallbackMapIter it;
125 for (it = mCallbackMap.begin(); it != mCallbackMap.end(); it++)
126 destroyCtrlCallbackContext(it);
127
128 /* Clear process map. */
129 mGuestProcessMap.clear();
130 }
131#endif
132
133 /* Enclose the state transition Ready->InUninit->NotReady */
134 AutoUninitSpan autoUninitSpan(this);
135 if (autoUninitSpan.uninitDone())
136 return;
137
138 unconst(mParent) = NULL;
139}
140
141// IGuest properties
142/////////////////////////////////////////////////////////////////////////////
143
144STDMETHODIMP Guest::COMGETTER(OSTypeId) (BSTR *aOSTypeId)
145{
146 CheckComArgOutPointerValid(aOSTypeId);
147
148 AutoCaller autoCaller(this);
149 if (FAILED(autoCaller.rc())) return autoCaller.rc();
150
151 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
152
153 // redirect the call to IMachine if no additions are installed
154 if (mData.mAdditionsVersion.isEmpty())
155 return mParent->machine()->COMGETTER(OSTypeId)(aOSTypeId);
156
157 mData.mOSTypeId.cloneTo(aOSTypeId);
158
159 return S_OK;
160}
161
162STDMETHODIMP Guest::COMGETTER(AdditionsRunLevel) (AdditionsRunLevelType_T *aRunLevel)
163{
164 AutoCaller autoCaller(this);
165 if (FAILED(autoCaller.rc())) return autoCaller.rc();
166
167 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
168
169 *aRunLevel = mData.mAdditionsRunLevel;
170
171 return S_OK;
172}
173
174STDMETHODIMP Guest::COMGETTER(AdditionsVersion) (BSTR *aAdditionsVersion)
175{
176 CheckComArgOutPointerValid(aAdditionsVersion);
177
178 AutoCaller autoCaller(this);
179 if (FAILED(autoCaller.rc())) return autoCaller.rc();
180
181 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
182
183 HRESULT hr = S_OK;
184 if ( mData.mAdditionsVersion.isEmpty()
185 /* Only try alternative way if GA are active! */
186 && mData.mAdditionsRunLevel > AdditionsRunLevelType_None)
187 {
188 /*
189 * If we got back an empty string from GetAdditionsVersion() we either
190 * really don't have the Guest Additions version yet or the guest is running
191 * older Guest Additions (< 3.2.0) which don't provide VMMDevReq_ReportGuestInfo2,
192 * so get the version + revision from the (hopefully) provided guest properties
193 * instead.
194 */
195 Bstr addVersion;
196 LONG64 u64Timestamp;
197 Bstr flags;
198 hr = mParent->machine()->GetGuestProperty(Bstr("/VirtualBox/GuestAdd/Version").raw(),
199 addVersion.asOutParam(), &u64Timestamp, flags.asOutParam());
200 if (hr == S_OK)
201 {
202 Bstr addRevision;
203 hr = mParent->machine()->GetGuestProperty(Bstr("/VirtualBox/GuestAdd/Revision").raw(),
204 addRevision.asOutParam(), &u64Timestamp, flags.asOutParam());
205 if ( hr == S_OK
206 && !addVersion.isEmpty()
207 && !addRevision.isEmpty())
208 {
209 /* Some Guest Additions versions had interchanged version + revision values,
210 * so check if the version value at least has a dot to identify it and change
211 * both values to reflect the right content. */
212 if (!Utf8Str(addVersion).contains("."))
213 {
214 Bstr addTemp = addVersion;
215 addVersion = addRevision;
216 addRevision = addTemp;
217 }
218
219 Bstr additionsVersion = BstrFmt("%ls r%ls",
220 addVersion.raw(), addRevision.raw());
221 additionsVersion.cloneTo(aAdditionsVersion);
222 }
223 /** @todo r=bird: else: Should not return failure! */
224 }
225 else
226 {
227 /* If getting the version + revision above fails or they simply aren't there
228 * because of *really* old Guest Additions we only can report the interface
229 * version to at least have something. */
230 mData.mInterfaceVersion.cloneTo(aAdditionsVersion);
231 /** @todo r=bird: hr is still indicating failure! */
232 }
233 }
234 else
235 mData.mAdditionsVersion.cloneTo(aAdditionsVersion);
236
237 return hr;
238}
239
240STDMETHODIMP Guest::COMGETTER(SupportsSeamless) (BOOL *aSupportsSeamless)
241{
242 CheckComArgOutPointerValid(aSupportsSeamless);
243
244 AutoCaller autoCaller(this);
245 if (FAILED(autoCaller.rc())) return autoCaller.rc();
246
247 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
248
249 *aSupportsSeamless = mData.mSupportsSeamless;
250
251 return S_OK;
252}
253
254STDMETHODIMP Guest::COMGETTER(SupportsGraphics) (BOOL *aSupportsGraphics)
255{
256 CheckComArgOutPointerValid(aSupportsGraphics);
257
258 AutoCaller autoCaller(this);
259 if (FAILED(autoCaller.rc())) return autoCaller.rc();
260
261 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
262
263 *aSupportsGraphics = mData.mSupportsGraphics;
264
265 return S_OK;
266}
267
268BOOL Guest::isPageFusionEnabled()
269{
270 AutoCaller autoCaller(this);
271 if (FAILED(autoCaller.rc())) return false;
272
273 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
274
275 return mfPageFusionEnabled;
276}
277
278STDMETHODIMP Guest::COMGETTER(MemoryBalloonSize) (ULONG *aMemoryBalloonSize)
279{
280 CheckComArgOutPointerValid(aMemoryBalloonSize);
281
282 AutoCaller autoCaller(this);
283 if (FAILED(autoCaller.rc())) return autoCaller.rc();
284
285 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
286
287 *aMemoryBalloonSize = mMemoryBalloonSize;
288
289 return S_OK;
290}
291
292STDMETHODIMP Guest::COMSETTER(MemoryBalloonSize) (ULONG aMemoryBalloonSize)
293{
294 AutoCaller autoCaller(this);
295 if (FAILED(autoCaller.rc())) return autoCaller.rc();
296
297 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
298
299 /* We must be 100% sure that IMachine::COMSETTER(MemoryBalloonSize)
300 * does not call us back in any way! */
301 HRESULT ret = mParent->machine()->COMSETTER(MemoryBalloonSize)(aMemoryBalloonSize);
302 if (ret == S_OK)
303 {
304 mMemoryBalloonSize = aMemoryBalloonSize;
305 /* forward the information to the VMM device */
306 VMMDev *pVMMDev = mParent->getVMMDev();
307 /* MUST release all locks before calling VMM device as its critsect
308 * has higher lock order than anything in Main. */
309 alock.release();
310 if (pVMMDev)
311 {
312 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
313 if (pVMMDevPort)
314 pVMMDevPort->pfnSetMemoryBalloon(pVMMDevPort, aMemoryBalloonSize);
315 }
316 }
317
318 return ret;
319}
320
321STDMETHODIMP Guest::COMGETTER(StatisticsUpdateInterval)(ULONG *aUpdateInterval)
322{
323 CheckComArgOutPointerValid(aUpdateInterval);
324
325 AutoCaller autoCaller(this);
326 if (FAILED(autoCaller.rc())) return autoCaller.rc();
327
328 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
329
330 *aUpdateInterval = mStatUpdateInterval;
331 return S_OK;
332}
333
334STDMETHODIMP Guest::COMSETTER(StatisticsUpdateInterval)(ULONG aUpdateInterval)
335{
336 AutoCaller autoCaller(this);
337 if (FAILED(autoCaller.rc())) return autoCaller.rc();
338
339 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
340
341 mStatUpdateInterval = aUpdateInterval;
342 /* forward the information to the VMM device */
343 VMMDev *pVMMDev = mParent->getVMMDev();
344 /* MUST release all locks before calling VMM device as its critsect
345 * has higher lock order than anything in Main. */
346 alock.release();
347 if (pVMMDev)
348 {
349 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
350 if (pVMMDevPort)
351 pVMMDevPort->pfnSetStatisticsInterval(pVMMDevPort, aUpdateInterval);
352 }
353
354 return S_OK;
355}
356
357STDMETHODIMP Guest::InternalGetStatistics(ULONG *aCpuUser, ULONG *aCpuKernel, ULONG *aCpuIdle,
358 ULONG *aMemTotal, ULONG *aMemFree, ULONG *aMemBalloon, ULONG *aMemShared,
359 ULONG *aMemCache, ULONG *aPageTotal,
360 ULONG *aMemAllocTotal, ULONG *aMemFreeTotal, ULONG *aMemBalloonTotal, ULONG *aMemSharedTotal)
361{
362 CheckComArgOutPointerValid(aCpuUser);
363 CheckComArgOutPointerValid(aCpuKernel);
364 CheckComArgOutPointerValid(aCpuIdle);
365 CheckComArgOutPointerValid(aMemTotal);
366 CheckComArgOutPointerValid(aMemFree);
367 CheckComArgOutPointerValid(aMemBalloon);
368 CheckComArgOutPointerValid(aMemShared);
369 CheckComArgOutPointerValid(aMemCache);
370 CheckComArgOutPointerValid(aPageTotal);
371 CheckComArgOutPointerValid(aMemAllocTotal);
372 CheckComArgOutPointerValid(aMemFreeTotal);
373 CheckComArgOutPointerValid(aMemBalloonTotal);
374 CheckComArgOutPointerValid(aMemSharedTotal);
375
376 AutoCaller autoCaller(this);
377 if (FAILED(autoCaller.rc())) return autoCaller.rc();
378
379 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
380
381 *aCpuUser = mCurrentGuestStat[GUESTSTATTYPE_CPUUSER];
382 *aCpuKernel = mCurrentGuestStat[GUESTSTATTYPE_CPUKERNEL];
383 *aCpuIdle = mCurrentGuestStat[GUESTSTATTYPE_CPUIDLE];
384 *aMemTotal = mCurrentGuestStat[GUESTSTATTYPE_MEMTOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
385 *aMemFree = mCurrentGuestStat[GUESTSTATTYPE_MEMFREE] * (_4K/_1K); /* page (4K) -> 1KB units */
386 *aMemBalloon = mCurrentGuestStat[GUESTSTATTYPE_MEMBALLOON] * (_4K/_1K); /* page (4K) -> 1KB units */
387 *aMemCache = mCurrentGuestStat[GUESTSTATTYPE_MEMCACHE] * (_4K/_1K); /* page (4K) -> 1KB units */
388 *aPageTotal = mCurrentGuestStat[GUESTSTATTYPE_PAGETOTAL] * (_4K/_1K); /* page (4K) -> 1KB units */
389
390 /* MUST release all locks before calling any PGM statistics queries,
391 * as they are executed by EMT and that might deadlock us by VMM device
392 * activity which waits for the Guest object lock. */
393 alock.release();
394 Console::SafeVMPtr pVM (mParent);
395 if (pVM.isOk())
396 {
397 uint64_t uFreeTotal, uAllocTotal, uBalloonedTotal, uSharedTotal;
398 *aMemFreeTotal = 0;
399 int rc = PGMR3QueryVMMMemoryStats(pVM.raw(), &uAllocTotal, &uFreeTotal, &uBalloonedTotal, &uSharedTotal);
400 AssertRC(rc);
401 if (rc == VINF_SUCCESS)
402 {
403 *aMemAllocTotal = (ULONG)(uAllocTotal / _1K); /* bytes -> KB */
404 *aMemFreeTotal = (ULONG)(uFreeTotal / _1K);
405 *aMemBalloonTotal = (ULONG)(uBalloonedTotal / _1K);
406 *aMemSharedTotal = (ULONG)(uSharedTotal / _1K);
407 }
408
409 /* Query the missing per-VM memory statistics. */
410 *aMemShared = 0;
411 uint64_t uTotalMem, uPrivateMem, uSharedMem, uZeroMem;
412 rc = PGMR3QueryMemoryStats(pVM.raw(), &uTotalMem, &uPrivateMem, &uSharedMem, &uZeroMem);
413 if (rc == VINF_SUCCESS)
414 {
415 *aMemShared = (ULONG)(uSharedMem / _1K);
416 }
417 }
418 else
419 {
420 *aMemFreeTotal = 0;
421 *aMemShared = 0;
422 }
423
424 return S_OK;
425}
426
427HRESULT Guest::setStatistic(ULONG aCpuId, GUESTSTATTYPE enmType, ULONG aVal)
428{
429 AutoCaller autoCaller(this);
430 if (FAILED(autoCaller.rc())) return autoCaller.rc();
431
432 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
433
434 if (enmType >= GUESTSTATTYPE_MAX)
435 return E_INVALIDARG;
436
437 mCurrentGuestStat[enmType] = aVal;
438 return S_OK;
439}
440
441STDMETHODIMP Guest::GetAdditionsStatus(AdditionsRunLevelType_T aLevel, BOOL *aActive)
442{
443 AutoCaller autoCaller(this);
444 if (FAILED(autoCaller.rc())) return autoCaller.rc();
445
446 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
447
448 HRESULT rc = S_OK;
449 switch (aLevel)
450 {
451 case AdditionsRunLevelType_System:
452 *aActive = (mData.mAdditionsRunLevel > AdditionsRunLevelType_None);
453 break;
454
455 case AdditionsRunLevelType_Userland:
456 *aActive = (mData.mAdditionsRunLevel >= AdditionsRunLevelType_Userland);
457 break;
458
459 case AdditionsRunLevelType_Desktop:
460 *aActive = (mData.mAdditionsRunLevel >= AdditionsRunLevelType_Desktop);
461 break;
462
463 default:
464 rc = setError(VBOX_E_NOT_SUPPORTED,
465 tr("Invalid status level defined: %u"), aLevel);
466 break;
467 }
468
469 return rc;
470}
471
472STDMETHODIMP Guest::SetCredentials(IN_BSTR aUserName, IN_BSTR aPassword,
473 IN_BSTR aDomain, BOOL aAllowInteractiveLogon)
474{
475 AutoCaller autoCaller(this);
476 if (FAILED(autoCaller.rc())) return autoCaller.rc();
477
478 /* forward the information to the VMM device */
479 VMMDev *pVMMDev = mParent->getVMMDev();
480 if (pVMMDev)
481 {
482 PPDMIVMMDEVPORT pVMMDevPort = pVMMDev->getVMMDevPort();
483 if (pVMMDevPort)
484 {
485 uint32_t u32Flags = VMMDEV_SETCREDENTIALS_GUESTLOGON;
486 if (!aAllowInteractiveLogon)
487 u32Flags = VMMDEV_SETCREDENTIALS_NOLOCALLOGON;
488
489 pVMMDevPort->pfnSetCredentials(pVMMDevPort,
490 Utf8Str(aUserName).c_str(),
491 Utf8Str(aPassword).c_str(),
492 Utf8Str(aDomain).c_str(),
493 u32Flags);
494 return S_OK;
495 }
496 }
497
498 return setError(VBOX_E_VM_ERROR,
499 tr("VMM device is not available (is the VM running?)"));
500}
501
502#ifdef VBOX_WITH_GUEST_CONTROL
503/**
504 * Appends environment variables to the environment block. Each var=value pair is separated
505 * by NULL (\0) sequence. The whole block will be stored in one blob and disassembled on the
506 * guest side later to fit into the HGCM param structure.
507 *
508 * @returns VBox status code.
509 *
510 * @todo
511 *
512 */
513int Guest::prepareExecuteEnv(const char *pszEnv, void **ppvList, uint32_t *pcbList, uint32_t *pcEnv)
514{
515 int rc = VINF_SUCCESS;
516 uint32_t cbLen = strlen(pszEnv);
517 if (*ppvList)
518 {
519 uint32_t cbNewLen = *pcbList + cbLen + 1; /* Include zero termination. */
520 char *pvTmp = (char*)RTMemRealloc(*ppvList, cbNewLen);
521 if (NULL == pvTmp)
522 {
523 rc = VERR_NO_MEMORY;
524 }
525 else
526 {
527 memcpy(pvTmp + *pcbList, pszEnv, cbLen);
528 pvTmp[cbNewLen - 1] = '\0'; /* Add zero termination. */
529 *ppvList = (void**)pvTmp;
530 }
531 }
532 else
533 {
534 char *pcTmp;
535 if (RTStrAPrintf(&pcTmp, "%s", pszEnv) > 0)
536 {
537 *ppvList = (void**)pcTmp;
538 /* Reset counters. */
539 *pcEnv = 0;
540 *pcbList = 0;
541 }
542 }
543 if (RT_SUCCESS(rc))
544 {
545 *pcbList += cbLen + 1; /* Include zero termination. */
546 *pcEnv += 1; /* Increase env pairs count. */
547 }
548 return rc;
549}
550
551/**
552 * Static callback function for receiving updates on guest control commands
553 * from the guest. Acts as a dispatcher for the actual class instance.
554 *
555 * @returns VBox status code.
556 *
557 * @todo
558 *
559 */
560DECLCALLBACK(int) Guest::doGuestCtrlNotification(void *pvExtension,
561 uint32_t u32Function,
562 void *pvParms,
563 uint32_t cbParms)
564{
565 using namespace guestControl;
566
567 /*
568 * No locking, as this is purely a notification which does not make any
569 * changes to the object state.
570 */
571#ifdef DEBUG_andy
572 LogFlowFunc(("pvExtension = %p, u32Function = %d, pvParms = %p, cbParms = %d\n",
573 pvExtension, u32Function, pvParms, cbParms));
574#endif
575 ComObjPtr<Guest> pGuest = reinterpret_cast<Guest *>(pvExtension);
576
577 int rc = VINF_SUCCESS;
578 if (u32Function == GUEST_DISCONNECTED)
579 {
580 //LogFlowFunc(("GUEST_DISCONNECTED\n"));
581
582 PCALLBACKDATACLIENTDISCONNECTED pCBData = reinterpret_cast<PCALLBACKDATACLIENTDISCONNECTED>(pvParms);
583 AssertPtr(pCBData);
584 AssertReturn(sizeof(CALLBACKDATACLIENTDISCONNECTED) == cbParms, VERR_INVALID_PARAMETER);
585 AssertReturn(CALLBACKDATAMAGICCLIENTDISCONNECTED == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
586
587 rc = pGuest->notifyCtrlClientDisconnected(u32Function, pCBData);
588 }
589 else if (u32Function == GUEST_EXEC_SEND_STATUS)
590 {
591 //LogFlowFunc(("GUEST_EXEC_SEND_STATUS\n"));
592
593 PCALLBACKDATAEXECSTATUS pCBData = reinterpret_cast<PCALLBACKDATAEXECSTATUS>(pvParms);
594 AssertPtr(pCBData);
595 AssertReturn(sizeof(CALLBACKDATAEXECSTATUS) == cbParms, VERR_INVALID_PARAMETER);
596 AssertReturn(CALLBACKDATAMAGICEXECSTATUS == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
597
598 rc = pGuest->notifyCtrlExecStatus(u32Function, pCBData);
599 }
600 else if (u32Function == GUEST_EXEC_SEND_OUTPUT)
601 {
602 //LogFlowFunc(("GUEST_EXEC_SEND_OUTPUT\n"));
603
604 PCALLBACKDATAEXECOUT pCBData = reinterpret_cast<PCALLBACKDATAEXECOUT>(pvParms);
605 AssertPtr(pCBData);
606 AssertReturn(sizeof(CALLBACKDATAEXECOUT) == cbParms, VERR_INVALID_PARAMETER);
607 AssertReturn(CALLBACKDATAMAGICEXECOUT == pCBData->hdr.u32Magic, VERR_INVALID_PARAMETER);
608
609 rc = pGuest->notifyCtrlExecOut(u32Function, pCBData);
610 }
611 else
612 rc = VERR_NOT_SUPPORTED;
613 return rc;
614}
615
616/* Function for handling the execution start/termination notification. */
617int Guest::notifyCtrlExecStatus(uint32_t u32Function,
618 PCALLBACKDATAEXECSTATUS pData)
619{
620 int vrc = VINF_SUCCESS;
621
622 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
623
624 AssertPtr(pData);
625 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
626
627 /* Callback can be called several times. */
628 if (it != mCallbackMap.end())
629 {
630 PCALLBACKDATAEXECSTATUS pCBData = (PCALLBACKDATAEXECSTATUS)it->second.pvData;
631 AssertPtr(pCBData);
632
633 pCBData->u32PID = pData->u32PID;
634 pCBData->u32Status = pData->u32Status;
635 pCBData->u32Flags = pData->u32Flags;
636 /** @todo Copy void* buffer contents! */
637
638 Utf8Str errMsg;
639
640 /* Was progress canceled before? */
641 BOOL fCanceled;
642 ComAssert(!it->second.pProgress.isNull());
643 if ( SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled))
644 && !fCanceled)
645 {
646 /* Do progress handling. */
647 HRESULT hr;
648 switch (pData->u32Status)
649 {
650 case PROC_STS_STARTED:
651 LogRel(("Guest process (PID %u) started\n", pCBData->u32PID)); /** @todo Add process name */
652 hr = it->second.pProgress->SetNextOperation(Bstr(tr("Waiting for process to exit ...")).raw(), 1 /* Weight */);
653 AssertComRC(hr);
654 break;
655
656 case PROC_STS_TEN: /* Terminated normally. */
657 LogRel(("Guest process (PID %u) exited normally\n", pCBData->u32PID)); /** @todo Add process name */
658 hr = it->second.pProgress->notifyComplete(S_OK);
659 AssertComRC(hr);
660 LogFlowFunc(("Proccess (context ID=%u, status=%u) terminated successfully\n",
661 pData->hdr.u32ContextID, pData->u32Status));
662 break;
663
664 case PROC_STS_TEA: /* Terminated abnormally. */
665 LogRel(("Guest process (PID %u) terminated abnormally with exit code = %u\n",
666 pCBData->u32PID, pCBData->u32Flags)); /** @todo Add process name */
667 errMsg = Utf8StrFmt(Guest::tr("Process terminated abnormally with status '%u'"),
668 pCBData->u32Flags);
669 break;
670
671 case PROC_STS_TES: /* Terminated through signal. */
672 LogRel(("Guest process (PID %u) terminated through signal with exit code = %u\n",
673 pCBData->u32PID, pCBData->u32Flags)); /** @todo Add process name */
674 errMsg = Utf8StrFmt(Guest::tr("Process terminated via signal with status '%u'"),
675 pCBData->u32Flags);
676 break;
677
678 case PROC_STS_TOK:
679 LogRel(("Guest process (PID %u) timed out and was killed\n", pCBData->u32PID)); /** @todo Add process name */
680 errMsg = Utf8StrFmt(Guest::tr("Process timed out and was killed"));
681 break;
682
683 case PROC_STS_TOA:
684 LogRel(("Guest process (PID %u) timed out and could not be killed\n", pCBData->u32PID)); /** @todo Add process name */
685 errMsg = Utf8StrFmt(Guest::tr("Process timed out and could not be killed"));
686 break;
687
688 case PROC_STS_DWN:
689 LogRel(("Guest process (PID %u) killed because system is shutting down\n", pCBData->u32PID)); /** @todo Add process name */
690 /*
691 * If u32Flags has ExecuteProcessFlag_IgnoreOrphanedProcesses set, we don't report an error to
692 * our progress object. This is helpful for waiters which rely on the success of our progress object
693 * even if the executed process was killed because the system/VBoxService is shutting down.
694 *
695 * In this case u32Flags contains the actual execution flags reached in via Guest::ExecuteProcess().
696 */
697 if (pData->u32Flags & ExecuteProcessFlag_IgnoreOrphanedProcesses)
698 {
699 hr = it->second.pProgress->notifyComplete(S_OK);
700 AssertComRC(hr);
701 }
702 else
703 {
704 errMsg = Utf8StrFmt(Guest::tr("Process killed because system is shutting down"));
705 }
706 break;
707
708 case PROC_STS_ERROR:
709 LogRel(("Guest process (PID %u) could not be started because of rc=%Rrc\n",
710 pCBData->u32PID, pCBData->u32Flags)); /** @todo Add process name */
711 errMsg = Utf8StrFmt(Guest::tr("Process execution failed with rc=%Rrc"), pCBData->u32Flags);
712 break;
713
714 default:
715 vrc = VERR_INVALID_PARAMETER;
716 break;
717 }
718
719 /* Handle process map. */
720 /** @todo What happens on/deal with PID reuse? */
721 /** @todo How to deal with multiple updates at once? */
722 if (pCBData->u32PID > 0)
723 {
724 GuestProcessMapIter it_proc = getProcessByPID(pCBData->u32PID);
725 if (it_proc == mGuestProcessMap.end())
726 {
727 /* Not found, add to map. */
728 GuestProcess newProcess;
729 newProcess.mStatus = pCBData->u32Status;
730 newProcess.mExitCode = pCBData->u32Flags; /* Contains exit code. */
731 newProcess.mFlags = 0;
732
733 mGuestProcessMap[pCBData->u32PID] = newProcess;
734 }
735 else /* Update map. */
736 {
737 it_proc->second.mStatus = pCBData->u32Status;
738 it_proc->second.mExitCode = pCBData->u32Flags; /* Contains exit code. */
739 it_proc->second.mFlags = 0;
740 }
741 }
742 }
743 else
744 errMsg = Utf8StrFmt(Guest::tr("Process execution canceled"));
745
746 if (!it->second.pProgress->getCompleted())
747 {
748 if ( errMsg.length()
749 || fCanceled) /* If canceled we have to report E_FAIL! */
750 {
751 /* Destroy all callbacks which are still waiting on something
752 * which is related to the current PID. */
753 CallbackMapIter it2;
754 for (it2 = mCallbackMap.begin(); it2 != mCallbackMap.end(); it2++)
755 {
756 switch(it2->second.mType)
757 {
758 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_START:
759 break;
760
761 /* When waiting for process output while the process is destroyed,
762 * make sure we also destroy the actual waiting operation (internal progress object)
763 * in order to not block the caller. */
764 case VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT:
765 {
766 PCALLBACKDATAEXECOUT pItData = (CALLBACKDATAEXECOUT*)it2->second.pvData;
767 AssertPtr(pItData);
768 if (pItData->u32PID == pCBData->u32PID)
769 destroyCtrlCallbackContext(it2);
770 break;
771 }
772 }
773 }
774
775 HRESULT hr2 = it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
776 COM_IIDOF(IGuest),
777 Guest::getStaticComponentName(),
778 "%s", errMsg.c_str());
779 AssertComRC(hr2);
780 LogFlowFunc(("Process (context ID=%u, status=%u) reported error: %s\n",
781 pData->hdr.u32ContextID, pData->u32Status, errMsg.c_str()));
782 }
783 }
784 }
785 else
786 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
787 LogFlowFunc(("Returned with rc=%Rrc\n", vrc));
788 return vrc;
789}
790
791/* Function for handling the execution output notification. */
792int Guest::notifyCtrlExecOut(uint32_t u32Function,
793 PCALLBACKDATAEXECOUT pData)
794{
795 int rc = VINF_SUCCESS;
796
797 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
798
799 AssertPtr(pData);
800 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
801 if (it != mCallbackMap.end())
802 {
803 PCALLBACKDATAEXECOUT pCBData = (CALLBACKDATAEXECOUT*)it->second.pvData;
804 AssertPtr(pCBData);
805
806 pCBData->u32PID = pData->u32PID;
807 pCBData->u32HandleId = pData->u32HandleId;
808 pCBData->u32Flags = pData->u32Flags;
809
810 /* Make sure we really got something! */
811 if ( pData->cbData
812 && pData->pvData)
813 {
814 /* Allocate data buffer and copy it */
815 pCBData->pvData = RTMemAlloc(pData->cbData);
816 pCBData->cbData = pData->cbData;
817
818 AssertReturn(pCBData->pvData, VERR_NO_MEMORY);
819 memcpy(pCBData->pvData, pData->pvData, pData->cbData);
820 }
821 else
822 {
823 pCBData->pvData = NULL;
824 pCBData->cbData = 0;
825 }
826
827 /* Was progress canceled before? */
828 BOOL fCanceled;
829 ComAssert(!it->second.pProgress.isNull());
830 if (SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled)) && fCanceled)
831 {
832 it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
833 COM_IIDOF(IGuest),
834 Guest::getStaticComponentName(),
835 Guest::tr("The output operation was canceled"));
836 }
837 else
838 it->second.pProgress->notifyComplete(S_OK);
839 }
840 else
841 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
842 return rc;
843}
844
845int Guest::notifyCtrlClientDisconnected(uint32_t u32Function,
846 PCALLBACKDATACLIENTDISCONNECTED pData)
847{
848 int rc = VINF_SUCCESS;
849
850 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
851 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
852 if (it != mCallbackMap.end())
853 {
854 LogFlowFunc(("Client with context ID=%u disconnected\n", it->first));
855 destroyCtrlCallbackContext(it);
856 }
857 return rc;
858}
859
860Guest::CallbackMapIter Guest::getCtrlCallbackContextByID(uint32_t u32ContextID)
861{
862 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
863 return mCallbackMap.find(u32ContextID);
864}
865
866Guest::GuestProcessMapIter Guest::getProcessByPID(uint32_t u32PID)
867{
868 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
869 return mGuestProcessMap.find(u32PID);
870}
871
872/* No locking here; */
873void Guest::destroyCtrlCallbackContext(Guest::CallbackMapIter it)
874{
875 LogFlowFunc(("Destroying callback with CID=%u ...\n", it->first));
876
877 if (it->second.pvData)
878 {
879 RTMemFree(it->second.pvData);
880 it->second.pvData = NULL;
881 it->second.cbData = 0;
882 }
883
884 /* Notify outstanding waits for progress ... */
885 if ( it->second.pProgress
886 && !it->second.pProgress.isNull())
887 {
888 LogFlowFunc(("Handling progress for CID=%u ...\n", it->first));
889
890 /*
891 * Assume we didn't complete to make sure we clean up even if the
892 * following call fails.
893 */
894 BOOL fCompleted = FALSE;
895 it->second.pProgress->COMGETTER(Completed)(&fCompleted);
896 if (!fCompleted)
897 {
898 LogFlowFunc(("Progress of CID=%u *not* completed, cancelling ...\n", it->first));
899
900 /* Only cancel if not canceled before! */
901 BOOL fCanceled;
902 if (SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled)) && !fCanceled)
903 it->second.pProgress->Cancel();
904
905 /*
906 * To get waitForCompletion completed (unblocked) we have to notify it if necessary (only
907 * cancle won't work!). This could happen if the client thread (e.g. VBoxService, thread of a spawned process)
908 * is disconnecting without having the chance to sending a status message before, so we
909 * have to abort here to make sure the host never hangs/gets stuck while waiting for the
910 * progress object to become signalled.
911 */
912 it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
913 COM_IIDOF(IGuest),
914 Guest::getStaticComponentName(),
915 Guest::tr("The operation was canceled because client is shutting down"));
916 }
917 /*
918 * Do *not* NULL pProgress here, because waiting function like executeProcess()
919 * will still rely on this object for checking whether they have to give up!
920 */
921 }
922}
923
924/* Adds a callback with a user provided data block and an optional progress object
925 * to the callback map. A callback is identified by a unique context ID which is used
926 * to identify a callback from the guest side. */
927uint32_t Guest::addCtrlCallbackContext(eVBoxGuestCtrlCallbackType enmType, void *pvData, uint32_t cbData, Progress *pProgress)
928{
929 AssertPtr(pProgress);
930
931 /** @todo Put this stuff into a constructor! */
932 CallbackContext context;
933 context.mType = enmType;
934 context.pvData = pvData;
935 context.cbData = cbData;
936 context.pProgress = pProgress;
937
938 /* Create a new context ID and assign it. */
939 CallbackMapIter it;
940 uint32_t uNewContext = 0;
941 do
942 {
943 /* Create a new context ID ... */
944 uNewContext = ASMAtomicIncU32(&mNextContextID);
945 if (uNewContext == UINT32_MAX)
946 ASMAtomicUoWriteU32(&mNextContextID, 1000);
947 /* Is the context ID already used? */
948 it = getCtrlCallbackContextByID(uNewContext);
949 } while(it != mCallbackMap.end());
950
951 uint32_t nCallbacks = 0;
952 if ( it == mCallbackMap.end()
953 && uNewContext > 0)
954 {
955 /* We apparently got an unused context ID, let's use it! */
956 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
957 mCallbackMap[uNewContext] = context;
958 nCallbacks = mCallbackMap.size();
959 }
960 else
961 {
962 /* Should never happen ... */
963 {
964 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
965 nCallbacks = mCallbackMap.size();
966 }
967 AssertReleaseMsg(uNewContext, ("No free context ID found! uNewContext=%u, nCallbacks=%u", uNewContext, nCallbacks));
968 }
969
970#if 0
971 if (nCallbacks > 256) /* Don't let the container size get too big! */
972 {
973 Guest::CallbackListIter it = mCallbackList.begin();
974 destroyCtrlCallbackContext(it);
975 {
976 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
977 mCallbackList.erase(it);
978 }
979 }
980#endif
981 return uNewContext;
982}
983#endif /* VBOX_WITH_GUEST_CONTROL */
984
985STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
986 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
987 IN_BSTR aUserName, IN_BSTR aPassword,
988 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
989{
990/** @todo r=bird: Eventually we should clean up all the timeout parameters
991 * in the API and have the same way of specifying infinite waits! */
992#ifndef VBOX_WITH_GUEST_CONTROL
993 ReturnComNotImplemented();
994#else /* VBOX_WITH_GUEST_CONTROL */
995 using namespace guestControl;
996
997 CheckComArgStrNotEmptyOrNull(aCommand);
998 CheckComArgOutPointerValid(aPID);
999 CheckComArgOutPointerValid(aProgress);
1000
1001 /* Do not allow anonymous executions (with system rights). */
1002 if (RT_UNLIKELY((aUserName) == NULL || *(aUserName) == '\0'))
1003 return setError(E_INVALIDARG, tr("No user name specified"));
1004
1005 AutoCaller autoCaller(this);
1006 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1007
1008 /* Validate flags. */
1009 if (aFlags)
1010 {
1011 if (!(aFlags & ExecuteProcessFlag_IgnoreOrphanedProcesses))
1012 return E_INVALIDARG;
1013 }
1014
1015 HRESULT rc = S_OK;
1016
1017 try
1018 {
1019 /*
1020 * Create progress object. Note that this is a multi operation
1021 * object to perform the following steps:
1022 * - Operation 1 (0): Create/start process.
1023 * - Operation 2 (1): Wait for process to exit.
1024 * If this progress completed successfully (S_OK), the process
1025 * started and exited normally. In any other case an error/exception
1026 * occured.
1027 */
1028 ComObjPtr <Progress> progress;
1029 rc = progress.createObject();
1030 if (SUCCEEDED(rc))
1031 {
1032 rc = progress->init(static_cast<IGuest*>(this),
1033 Bstr(tr("Executing process")).raw(),
1034 TRUE,
1035 2, /* Number of operations. */
1036 Bstr(tr("Starting process ...")).raw()); /* Description of first stage. */
1037 }
1038 if (FAILED(rc)) return rc;
1039
1040 /*
1041 * Prepare process execution.
1042 */
1043 int vrc = VINF_SUCCESS;
1044 Utf8Str Utf8Command(aCommand);
1045
1046 /* Adjust timeout */
1047 if (aTimeoutMS == 0)
1048 aTimeoutMS = UINT32_MAX;
1049
1050 /* Prepare arguments. */
1051 char **papszArgv = NULL;
1052 uint32_t uNumArgs = 0;
1053 if (aArguments > 0)
1054 {
1055 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
1056 uNumArgs = args.size();
1057 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
1058 AssertReturn(papszArgv, E_OUTOFMEMORY);
1059 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
1060 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
1061 papszArgv[uNumArgs] = NULL;
1062 }
1063
1064 Utf8Str Utf8UserName(aUserName);
1065 Utf8Str Utf8Password(aPassword);
1066 if (RT_SUCCESS(vrc))
1067 {
1068 uint32_t uContextID = 0;
1069
1070 char *pszArgs = NULL;
1071 if (uNumArgs > 0)
1072 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, 0);
1073 if (RT_SUCCESS(vrc))
1074 {
1075 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1076
1077 /* Prepare environment. */
1078 void *pvEnv = NULL;
1079 uint32_t uNumEnv = 0;
1080 uint32_t cbEnv = 0;
1081 if (aEnvironment > 0)
1082 {
1083 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
1084
1085 for (unsigned i = 0; i < env.size(); i++)
1086 {
1087 vrc = prepareExecuteEnv(Utf8Str(env[i]).c_str(), &pvEnv, &cbEnv, &uNumEnv);
1088 if (RT_FAILURE(vrc))
1089 break;
1090 }
1091 }
1092
1093 LogRel(("Executing guest process \"%s\" as user \"%s\" ...\n",
1094 Utf8Command.c_str(), Utf8UserName.c_str()));
1095
1096 if (RT_SUCCESS(vrc))
1097 {
1098 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECSTATUS));
1099 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1100 RT_ZERO(*pData);
1101 uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_START,
1102 pData, sizeof(CALLBACKDATAEXECSTATUS), progress);
1103 Assert(uContextID > 0);
1104
1105 VBOXHGCMSVCPARM paParms[15];
1106 int i = 0;
1107 paParms[i++].setUInt32(uContextID);
1108 paParms[i++].setPointer((void*)Utf8Command.c_str(), (uint32_t)Utf8Command.length() + 1);
1109 paParms[i++].setUInt32(aFlags);
1110 paParms[i++].setUInt32(uNumArgs);
1111 paParms[i++].setPointer((void*)pszArgs, cbArgs);
1112 paParms[i++].setUInt32(uNumEnv);
1113 paParms[i++].setUInt32(cbEnv);
1114 paParms[i++].setPointer((void*)pvEnv, cbEnv);
1115 paParms[i++].setPointer((void*)Utf8UserName.c_str(), (uint32_t)Utf8UserName.length() + 1);
1116 paParms[i++].setPointer((void*)Utf8Password.c_str(), (uint32_t)Utf8Password.length() + 1);
1117 paParms[i++].setUInt32(aTimeoutMS);
1118
1119 VMMDev *vmmDev;
1120 {
1121 /* Make sure mParent is valid, so set the read lock while using.
1122 * Do not keep this lock while doing the actual call, because in the meanwhile
1123 * another thread could request a write lock which would be a bad idea ... */
1124 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1125
1126 /* Forward the information to the VMM device. */
1127 AssertPtr(mParent);
1128 vmmDev = mParent->getVMMDev();
1129 }
1130
1131 if (vmmDev)
1132 {
1133 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1134 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1135 i, paParms);
1136 }
1137 else
1138 vrc = VERR_INVALID_VM_HANDLE;
1139 RTMemFree(pvEnv);
1140 }
1141 RTStrFree(pszArgs);
1142 }
1143 if (RT_SUCCESS(vrc))
1144 {
1145 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1146
1147 /*
1148 * Wait for the HGCM low level callback until the process
1149 * has been started (or something went wrong). This is necessary to
1150 * get the PID.
1151 */
1152 CallbackMapIter it = getCtrlCallbackContextByID(uContextID);
1153 BOOL fCanceled = FALSE;
1154 if (it != mCallbackMap.end())
1155 {
1156 ComAssert(!it->second.pProgress.isNull());
1157
1158 /*
1159 * Wait for the first stage (=0) to complete (that is starting the process).
1160 */
1161 PCALLBACKDATAEXECSTATUS pData = NULL;
1162 rc = it->second.pProgress->WaitForOperationCompletion(0, aTimeoutMS);
1163 if (SUCCEEDED(rc))
1164 {
1165 /* Was the operation canceled by one of the parties? */
1166 rc = it->second.pProgress->COMGETTER(Canceled)(&fCanceled);
1167 if (FAILED(rc)) throw rc;
1168
1169 if (!fCanceled)
1170 {
1171 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1172
1173 pData = (PCALLBACKDATAEXECSTATUS)it->second.pvData;
1174 Assert(it->second.cbData == sizeof(CALLBACKDATAEXECSTATUS));
1175 AssertPtr(pData);
1176
1177 /* Did we get some status? */
1178 switch (pData->u32Status)
1179 {
1180 case PROC_STS_STARTED:
1181 /* Process is (still) running; get PID. */
1182 *aPID = pData->u32PID;
1183 break;
1184
1185 /* In any other case the process either already
1186 * terminated or something else went wrong, so no PID ... */
1187 case PROC_STS_TEN: /* Terminated normally. */
1188 case PROC_STS_TEA: /* Terminated abnormally. */
1189 case PROC_STS_TES: /* Terminated through signal. */
1190 case PROC_STS_TOK:
1191 case PROC_STS_TOA:
1192 case PROC_STS_DWN:
1193 /*
1194 * Process (already) ended, but we want to get the
1195 * PID anyway to retrieve the output in a later call.
1196 */
1197 *aPID = pData->u32PID;
1198 break;
1199
1200 case PROC_STS_ERROR:
1201 vrc = pData->u32Flags; /* u32Flags member contains IPRT error code. */
1202 break;
1203
1204 case PROC_STS_UNDEFINED:
1205 vrc = VERR_TIMEOUT; /* Operation did not complete within time. */
1206 break;
1207
1208 default:
1209 vrc = VERR_INVALID_PARAMETER; /* Unknown status, should never happen! */
1210 break;
1211 }
1212 }
1213 else /* Operation was canceled. */
1214 vrc = VERR_CANCELLED;
1215 }
1216 else /* Operation did not complete within time. */
1217 vrc = VERR_TIMEOUT;
1218
1219 /*
1220 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1221 * else (like end of process) ...
1222 */
1223 if (RT_FAILURE(vrc))
1224 {
1225 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1226 rc = setError(VBOX_E_IPRT_ERROR,
1227 tr("The file '%s' was not found on guest"), Utf8Command.c_str());
1228 else if (vrc == VERR_PATH_NOT_FOUND)
1229 rc = setError(VBOX_E_IPRT_ERROR,
1230 tr("The path to file '%s' was not found on guest"), Utf8Command.c_str());
1231 else if (vrc == VERR_BAD_EXE_FORMAT)
1232 rc = setError(VBOX_E_IPRT_ERROR,
1233 tr("The file '%s' is not an executable format on guest"), Utf8Command.c_str());
1234 else if (vrc == VERR_AUTHENTICATION_FAILURE)
1235 rc = setError(VBOX_E_IPRT_ERROR,
1236 tr("The specified user '%s' was not able to logon on guest"), Utf8UserName.c_str());
1237 else if (vrc == VERR_TIMEOUT)
1238 rc = setError(VBOX_E_IPRT_ERROR,
1239 tr("The guest did not respond within time (%ums)"), aTimeoutMS);
1240 else if (vrc == VERR_CANCELLED)
1241 rc = setError(VBOX_E_IPRT_ERROR,
1242 tr("The execution operation was canceled"));
1243 else if (vrc == VERR_PERMISSION_DENIED)
1244 rc = setError(VBOX_E_IPRT_ERROR,
1245 tr("Invalid user/password credentials"));
1246 else
1247 {
1248 if (pData && pData->u32Status == PROC_STS_ERROR)
1249 rc = setError(VBOX_E_IPRT_ERROR,
1250 tr("Process could not be started: %Rrc"), pData->u32Flags);
1251 else
1252 rc = setError(E_UNEXPECTED,
1253 tr("The service call failed with error %Rrc"), vrc);
1254 }
1255 }
1256 else /* Execution went fine. */
1257 {
1258 /* Return the progress to the caller. */
1259 progress.queryInterfaceTo(aProgress);
1260 }
1261 }
1262 else /* Callback context not found; should never happen! */
1263 AssertMsg(it != mCallbackMap.end(), ("Callback context with ID %u not found!", uContextID));
1264 }
1265 else /* HGCM related error codes .*/
1266 {
1267 if (vrc == VERR_INVALID_VM_HANDLE)
1268 rc = setError(VBOX_E_VM_ERROR,
1269 tr("VMM device is not available (is the VM running?)"));
1270 else if (vrc == VERR_TIMEOUT)
1271 rc = setError(VBOX_E_VM_ERROR,
1272 tr("The guest execution service is not ready"));
1273 else if (vrc == VERR_HGCM_SERVICE_NOT_FOUND)
1274 rc = setError(VBOX_E_VM_ERROR,
1275 tr("The guest execution service is not available"));
1276 else /* HGCM call went wrong. */
1277 rc = setError(E_UNEXPECTED,
1278 tr("The HGCM call failed with error %Rrc"), vrc);
1279 }
1280
1281 for (unsigned i = 0; i < uNumArgs; i++)
1282 RTMemFree(papszArgv[i]);
1283 RTMemFree(papszArgv);
1284 }
1285
1286 if (RT_FAILURE(vrc))
1287 LogRel(("Executing guest process \"%s\" as user \"%s\" failed with %Rrc\n",
1288 Utf8Command.c_str(), Utf8UserName.c_str(), vrc));
1289 }
1290 catch (std::bad_alloc &)
1291 {
1292 rc = E_OUTOFMEMORY;
1293 }
1294 return rc;
1295#endif /* VBOX_WITH_GUEST_CONTROL */
1296}
1297
1298STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
1299{
1300/** @todo r=bird: Eventually we should clean up all the timeout parameters
1301 * in the API and have the same way of specifying infinite waits! */
1302#ifndef VBOX_WITH_GUEST_CONTROL
1303 ReturnComNotImplemented();
1304#else /* VBOX_WITH_GUEST_CONTROL */
1305 using namespace guestControl;
1306
1307 CheckComArgExpr(aPID, aPID > 0);
1308 if (aSize < 0)
1309 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
1310 if (aFlags != 0) /* Flags are not supported at the moment. */
1311 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1312
1313 AutoCaller autoCaller(this);
1314 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1315
1316 HRESULT rc = S_OK;
1317
1318 try
1319 {
1320 /*
1321 * Create progress object.
1322 * This progress object, compared to the one in executeProgress() above
1323 * is only local and is used to determine whether the operation finished
1324 * or got canceled.
1325 */
1326 ComObjPtr <Progress> progress;
1327 rc = progress.createObject();
1328 if (SUCCEEDED(rc))
1329 {
1330 rc = progress->init(static_cast<IGuest*>(this),
1331 Bstr(tr("Getting output of process")).raw(),
1332 TRUE);
1333 }
1334 if (FAILED(rc)) return rc;
1335
1336 /* Adjust timeout */
1337 if (aTimeoutMS == 0)
1338 aTimeoutMS = UINT32_MAX;
1339
1340 /* Search for existing PID. */
1341 PCALLBACKDATAEXECOUT pData = (CALLBACKDATAEXECOUT*)RTMemAlloc(sizeof(CALLBACKDATAEXECOUT));
1342 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1343 RT_ZERO(*pData);
1344 /* Save PID + output flags for later use. */
1345 pData->u32PID = aPID;
1346 pData->u32Flags = aFlags;
1347 /* Add job to callback contexts. */
1348 uint32_t uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT,
1349 pData, sizeof(CALLBACKDATAEXECOUT), progress);
1350 Assert(uContextID > 0);
1351
1352 size_t cbData = (size_t)RT_MIN(aSize, _64K);
1353 com::SafeArray<BYTE> outputData(cbData);
1354
1355 VBOXHGCMSVCPARM paParms[5];
1356 int i = 0;
1357 paParms[i++].setUInt32(uContextID);
1358 paParms[i++].setUInt32(aPID);
1359 paParms[i++].setUInt32(aFlags); /** @todo Should represent stdout and/or stderr. */
1360
1361 int vrc = VINF_SUCCESS;
1362
1363 {
1364 VMMDev *vmmDev;
1365 {
1366 /* Make sure mParent is valid, so set the read lock while using.
1367 * Do not keep this lock while doing the actual call, because in the meanwhile
1368 * another thread could request a write lock which would be a bad idea ... */
1369 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1370
1371 /* Forward the information to the VMM device. */
1372 AssertPtr(mParent);
1373 vmmDev = mParent->getVMMDev();
1374 }
1375
1376 if (vmmDev)
1377 {
1378 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1379 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
1380 i, paParms);
1381 }
1382 }
1383
1384 if (RT_SUCCESS(vrc))
1385 {
1386 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1387
1388 /*
1389 * Wait for the HGCM low level callback until the process
1390 * has been started (or something went wrong). This is necessary to
1391 * get the PID.
1392 */
1393 CallbackMapIter it = getCtrlCallbackContextByID(uContextID);
1394 BOOL fCanceled = FALSE;
1395 if (it != mCallbackMap.end())
1396 {
1397 ComAssert(!it->second.pProgress.isNull());
1398
1399 /* Wait until operation completed. */
1400 rc = it->second.pProgress->WaitForCompletion(aTimeoutMS);
1401 if (FAILED(rc)) throw rc;
1402
1403 /* Was the operation canceled by one of the parties? */
1404 rc = it->second.pProgress->COMGETTER(Canceled)(&fCanceled);
1405 if (FAILED(rc)) throw rc;
1406
1407 if (!fCanceled)
1408 {
1409 BOOL fCompleted;
1410 if ( SUCCEEDED(it->second.pProgress->COMGETTER(Completed)(&fCompleted))
1411 && fCompleted)
1412 {
1413 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1414
1415 /* Did we get some output? */
1416 pData = (PCALLBACKDATAEXECOUT)it->second.pvData;
1417 Assert(it->second.cbData == sizeof(CALLBACKDATAEXECOUT));
1418 AssertPtr(pData);
1419
1420 if (pData->cbData)
1421 {
1422 /* Do we need to resize the array? */
1423 if (pData->cbData > cbData)
1424 outputData.resize(pData->cbData);
1425
1426 /* Fill output in supplied out buffer. */
1427 memcpy(outputData.raw(), pData->pvData, pData->cbData);
1428 outputData.resize(pData->cbData); /* Shrink to fit actual buffer size. */
1429 }
1430 else
1431 vrc = VERR_NO_DATA; /* This is not an error we want to report to COM. */
1432 }
1433 else /* If callback not called within time ... well, that's a timeout! */
1434 vrc = VERR_TIMEOUT;
1435 }
1436 else /* Operation was canceled. */
1437 {
1438 vrc = VERR_CANCELLED;
1439 }
1440
1441 if (RT_FAILURE(vrc))
1442 {
1443 if (vrc == VERR_NO_DATA)
1444 {
1445 /* This is not an error we want to report to COM. */
1446 rc = S_OK;
1447 }
1448 else if (vrc == VERR_TIMEOUT)
1449 {
1450 rc = setError(VBOX_E_IPRT_ERROR,
1451 tr("The guest did not output within time (%ums)"), aTimeoutMS);
1452 }
1453 else if (vrc == VERR_CANCELLED)
1454 {
1455 rc = setError(VBOX_E_IPRT_ERROR,
1456 tr("The output operation was canceled"));
1457 }
1458 else
1459 {
1460 rc = setError(E_UNEXPECTED,
1461 tr("The service call failed with error %Rrc"), vrc);
1462 }
1463 }
1464
1465 {
1466 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1467 /*
1468 * Destroy locally used progress object.
1469 */
1470 destroyCtrlCallbackContext(it);
1471 }
1472
1473 /* Remove callback context (not used anymore). */
1474 mCallbackMap.erase(it);
1475 }
1476 else /* PID lookup failed. */
1477 rc = setError(VBOX_E_IPRT_ERROR,
1478 tr("Process (PID %u) not found!"), aPID);
1479 }
1480 else /* HGCM operation failed. */
1481 rc = setError(E_UNEXPECTED,
1482 tr("The HGCM call failed with error %Rrc"), vrc);
1483
1484 /* Cleanup. */
1485 progress->uninit();
1486 progress.setNull();
1487
1488 /* If something failed (or there simply was no data, indicated by VERR_NO_DATA,
1489 * we return an empty array so that the frontend knows when to give up. */
1490 if (RT_FAILURE(vrc) || FAILED(rc))
1491 outputData.resize(0);
1492 outputData.detachTo(ComSafeArrayOutArg(aData));
1493 }
1494 catch (std::bad_alloc &)
1495 {
1496 rc = E_OUTOFMEMORY;
1497 }
1498 return rc;
1499#endif
1500}
1501
1502STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ULONG *aStatus)
1503{
1504#ifndef VBOX_WITH_GUEST_CONTROL
1505 ReturnComNotImplemented();
1506#else /* VBOX_WITH_GUEST_CONTROL */
1507 using namespace guestControl;
1508
1509 AutoCaller autoCaller(this);
1510 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1511
1512 HRESULT rc = S_OK;
1513
1514 try
1515 {
1516 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1517
1518 GuestProcessMapIterConst it = getProcessByPID(aPID);
1519 if (it != mGuestProcessMap.end())
1520 {
1521 *aExitCode = it->second.mExitCode;
1522 *aFlags = it->second.mFlags;
1523 *aStatus = it->second.mStatus;
1524 }
1525 else
1526 rc = setError(VBOX_E_IPRT_ERROR,
1527 tr("Process (PID %u) not found!"), aPID);
1528 }
1529 catch (std::bad_alloc &)
1530 {
1531 rc = E_OUTOFMEMORY;
1532 }
1533 return rc;
1534#endif
1535}
1536
1537// public methods only for internal purposes
1538/////////////////////////////////////////////////////////////////////////////
1539
1540/**
1541 * Sets the general Guest Additions information like
1542 * API (interface) version and OS type. Gets called by
1543 * vmmdevUpdateGuestInfo.
1544 *
1545 * @param aInterfaceVersion
1546 * @param aOsType
1547 */
1548void Guest::setAdditionsInfo(Bstr aInterfaceVersion, VBOXOSTYPE aOsType)
1549{
1550 AutoCaller autoCaller(this);
1551 AssertComRCReturnVoid (autoCaller.rc());
1552
1553 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1554
1555 /*
1556 * Note: The Guest Additions API (interface) version is deprecated
1557 * and will not be used anymore! We might need it to at least report
1558 * something as version number if *really* ancient Guest Additions are
1559 * installed (without the guest version + revision properties having set).
1560 */
1561 mData.mInterfaceVersion = aInterfaceVersion;
1562
1563 /*
1564 * Older Additions rely on the Additions API version whether they
1565 * are assumed to be active or not. Since newer Additions do report
1566 * the Additions version *before* calling this function (by calling
1567 * VMMDevReportGuestInfo2, VMMDevReportGuestStatus, VMMDevReportGuestInfo,
1568 * in that order) we can tell apart old and new Additions here. Old
1569 * Additions never would set VMMDevReportGuestInfo2 (which set mData.mAdditionsVersion)
1570 * so they just rely on the aInterfaceVersion string (which gets set by
1571 * VMMDevReportGuestInfo).
1572 *
1573 * So only mark the Additions as being active (run level = system) when we
1574 * don't have the Additions version set.
1575 */
1576 if (mData.mAdditionsVersion.isEmpty())
1577 {
1578 if (aInterfaceVersion.isEmpty())
1579 mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
1580 else
1581 mData.mAdditionsRunLevel = AdditionsRunLevelType_System;
1582 }
1583
1584 /*
1585 * Older Additions didn't have this finer grained capability bit,
1586 * so enable it by default. Newer Additions will not enable this here
1587 * and use the setSupportedFeatures function instead.
1588 */
1589 mData.mSupportsGraphics = mData.mAdditionsRunLevel > AdditionsRunLevelType_None;
1590
1591 /*
1592 * Note! There is a race going on between setting mAdditionsRunLevel and
1593 * mSupportsGraphics here and disabling/enabling it later according to
1594 * its real status when using new(er) Guest Additions.
1595 */
1596 mData.mOSTypeId = Global::OSTypeId (aOsType);
1597}
1598
1599/**
1600 * Sets the Guest Additions version information details.
1601 * Gets called by vmmdevUpdateGuestInfo2.
1602 *
1603 * @param aAdditionsVersion
1604 * @param aVersionName
1605 */
1606void Guest::setAdditionsInfo2(Bstr aAdditionsVersion, Bstr aVersionName, Bstr aRevision)
1607{
1608 AutoCaller autoCaller(this);
1609 AssertComRCReturnVoid (autoCaller.rc());
1610
1611 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1612
1613 if (!aVersionName.isEmpty())
1614 /*
1615 * aVersionName could be "x.y.z_BETA1_FOOBAR", so append revision manually to
1616 * become "x.y.z_BETA1_FOOBARr12345".
1617 */
1618 mData.mAdditionsVersion = BstrFmt("%ls r%ls", aVersionName.raw(), aRevision.raw());
1619 else /* aAdditionsVersion is in x.y.zr12345 format. */
1620 mData.mAdditionsVersion = aAdditionsVersion;
1621}
1622
1623/**
1624 * Sets the status of a certain Guest Additions facility.
1625 * Gets called by vmmdevUpdateGuestStatus.
1626 *
1627 * @param Facility
1628 * @param Status
1629 * @param ulFlags
1630 */
1631void Guest::setAdditionsStatus(VBoxGuestStatusFacility Facility, VBoxGuestStatusCurrent Status, ULONG ulFlags)
1632{
1633 AutoCaller autoCaller(this);
1634 AssertComRCReturnVoid (autoCaller.rc());
1635
1636 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1637
1638 uint32_t uCurFacility = Facility + (Status == VBoxGuestStatusCurrent_Active ? 0 : -1);
1639
1640 /* First check for disabled status. */
1641 if ( Facility < VBoxGuestStatusFacility_VBoxGuestDriver
1642 || ( Facility == VBoxGuestStatusFacility_All
1643 && ( Status == VBoxGuestStatusCurrent_Inactive
1644 || Status == VBoxGuestStatusCurrent_Disabled
1645 )
1646 )
1647 )
1648 {
1649 mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
1650 }
1651 else if (uCurFacility >= VBoxGuestStatusFacility_VBoxTray)
1652 {
1653 mData.mAdditionsRunLevel = AdditionsRunLevelType_Desktop;
1654 }
1655 else if (uCurFacility >= VBoxGuestStatusFacility_VBoxService)
1656 {
1657 mData.mAdditionsRunLevel = AdditionsRunLevelType_Userland;
1658 }
1659 else if (uCurFacility >= VBoxGuestStatusFacility_VBoxGuestDriver)
1660 {
1661 mData.mAdditionsRunLevel = AdditionsRunLevelType_System;
1662 }
1663 else /* Should never happen! */
1664 AssertMsgFailed(("Invalid facility status/run level detected! uCurFacility=%ld\n", uCurFacility));
1665}
1666
1667/**
1668 * Sets the supported features (and whether they are active or not).
1669 *
1670 * @param fCaps Guest capability bit mask (VMMDEV_GUEST_SUPPORTS_XXX).
1671 * @param fActive No idea what this is supposed to be, it's always 0 and
1672 * not references by this method.
1673 */
1674void Guest::setSupportedFeatures(uint32_t fCaps, uint32_t fActive)
1675{
1676 AutoCaller autoCaller(this);
1677 AssertComRCReturnVoid (autoCaller.rc());
1678
1679 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1680
1681 mData.mSupportsSeamless = (fCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS);
1682 /** @todo Add VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING */
1683 mData.mSupportsGraphics = (fCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS);
1684}
1685/* 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