VirtualBox

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

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

Main/Guest+Console: fix lock ordering issues, and mark code where this still needs to be done

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 60.8 KB
Line 
1/* $Id: GuestImpl.cpp 32827 2010-09-29 18:48:37Z 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 /* MUST release all locks before calling VMM device as its critsect
306 * has higher lock order than anything in Main. */
307 alock.release();
308 /* forward the information to the VMM device */
309 VMMDev *pVMMDev = mParent->getVMMDev();
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 /* MUST release all locks before calling VMM device as its critsect
343 * has higher lock order than anything in Main. */
344 alock.release();
345 /* forward the information to the VMM device */
346 VMMDev *pVMMDev = mParent->getVMMDev();
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) exited because system is shutting down\n", pCBData->u32PID)); /** @todo Add process name */
690 errMsg = Utf8StrFmt(Guest::tr("Process exited because system is shutting down"));
691 break;
692
693 case PROC_STS_ERROR:
694 LogRel(("Guest process (PID %u) could not be started because of rc=%Rrc\n",
695 pCBData->u32PID, pCBData->u32Flags)); /** @todo Add process name */
696 errMsg = Utf8StrFmt(Guest::tr("Process execution failed with rc=%Rrc"), pCBData->u32Flags);
697 break;
698
699 default:
700 vrc = VERR_INVALID_PARAMETER;
701 break;
702 }
703
704 /* Handle process map. */
705 /** @todo What happens on/deal with PID reuse? */
706 /** @todo How to deal with multiple updates at once? */
707 if (pCBData->u32PID > 0)
708 {
709 GuestProcessMapIter it_proc = getProcessByPID(pCBData->u32PID);
710 if (it_proc == mGuestProcessMap.end())
711 {
712 /* Not found, add to map. */
713 GuestProcess newProcess;
714 newProcess.mStatus = pCBData->u32Status;
715 newProcess.mExitCode = pCBData->u32Flags; /* Contains exit code. */
716 newProcess.mFlags = 0;
717
718 mGuestProcessMap[pCBData->u32PID] = newProcess;
719 }
720 else /* Update map. */
721 {
722 it_proc->second.mStatus = pCBData->u32Status;
723 it_proc->second.mExitCode = pCBData->u32Flags; /* Contains exit code. */
724 it_proc->second.mFlags = 0;
725 }
726 }
727 }
728 else
729 errMsg = Utf8StrFmt(Guest::tr("Process execution canceled"));
730
731 if (!it->second.pProgress->getCompleted())
732 {
733 if ( errMsg.length()
734 || fCanceled) /* If canceled we have to report E_FAIL! */
735 {
736 HRESULT hr2 = it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
737 COM_IIDOF(IGuest),
738 Guest::getStaticComponentName(),
739 "%s", errMsg.c_str());
740 AssertComRC(hr2);
741 LogFlowFunc(("Process (context ID=%u, status=%u) reported error: %s\n",
742 pData->hdr.u32ContextID, pData->u32Status, errMsg.c_str()));
743 }
744 }
745 }
746 else
747 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
748 LogFlowFunc(("Returned with rc=%Rrc\n", vrc));
749 return vrc;
750}
751
752/* Function for handling the execution output notification. */
753int Guest::notifyCtrlExecOut(uint32_t u32Function,
754 PCALLBACKDATAEXECOUT pData)
755{
756 int rc = VINF_SUCCESS;
757
758 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
759
760 AssertPtr(pData);
761 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
762 if (it != mCallbackMap.end())
763 {
764 PCALLBACKDATAEXECOUT pCBData = (CALLBACKDATAEXECOUT*)it->second.pvData;
765 AssertPtr(pCBData);
766
767 pCBData->u32PID = pData->u32PID;
768 pCBData->u32HandleId = pData->u32HandleId;
769 pCBData->u32Flags = pData->u32Flags;
770
771 /* Make sure we really got something! */
772 if ( pData->cbData
773 && pData->pvData)
774 {
775 /* Allocate data buffer and copy it */
776 pCBData->pvData = RTMemAlloc(pData->cbData);
777 pCBData->cbData = pData->cbData;
778
779 AssertReturn(pCBData->pvData, VERR_NO_MEMORY);
780 memcpy(pCBData->pvData, pData->pvData, pData->cbData);
781 }
782 else
783 {
784 pCBData->pvData = NULL;
785 pCBData->cbData = 0;
786 }
787
788 /* Was progress canceled before? */
789 BOOL fCanceled;
790 ComAssert(!it->second.pProgress.isNull());
791 if (SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled)) && fCanceled)
792 {
793 it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
794 COM_IIDOF(IGuest),
795 Guest::getStaticComponentName(),
796 Guest::tr("The output operation was canceled"));
797 }
798 else
799 it->second.pProgress->notifyComplete(S_OK);
800 }
801 else
802 LogFlowFunc(("Unexpected callback (magic=%u, context ID=%u) arrived\n", pData->hdr.u32Magic, pData->hdr.u32ContextID));
803 return rc;
804}
805
806int Guest::notifyCtrlClientDisconnected(uint32_t u32Function,
807 PCALLBACKDATACLIENTDISCONNECTED pData)
808{
809 int rc = VINF_SUCCESS;
810
811 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
812 CallbackMapIter it = getCtrlCallbackContextByID(pData->hdr.u32ContextID);
813 if (it != mCallbackMap.end())
814 {
815 LogFlowFunc(("Client with context ID=%u disconnected\n", it->first));
816 destroyCtrlCallbackContext(it);
817 }
818 return rc;
819}
820
821Guest::CallbackMapIter Guest::getCtrlCallbackContextByID(uint32_t u32ContextID)
822{
823 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
824 return mCallbackMap.find(u32ContextID);
825}
826
827Guest::GuestProcessMapIter Guest::getProcessByPID(uint32_t u32PID)
828{
829 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
830 return mGuestProcessMap.find(u32PID);
831}
832
833/* No locking here; */
834void Guest::destroyCtrlCallbackContext(Guest::CallbackMapIter it)
835{
836 LogFlowFunc(("Destroying callback with CID=%u ...\n", it->first));
837
838 if (it->second.pvData)
839 {
840 RTMemFree(it->second.pvData);
841 it->second.pvData = NULL;
842 it->second.cbData = 0;
843 }
844
845 /* Notify outstanding waits for progress ... */
846 if ( it->second.pProgress
847 && !it->second.pProgress.isNull())
848 {
849 LogFlowFunc(("Handling progress for CID=%u ...\n", it->first));
850
851 /*
852 * Assume we didn't complete to make sure we clean up even if the
853 * following call fails.
854 */
855 BOOL fCompleted = FALSE;
856 it->second.pProgress->COMGETTER(Completed)(&fCompleted);
857 if (!fCompleted)
858 {
859 LogFlowFunc(("Progress of CID=%u *not* completed, cancelling ...\n", it->first));
860
861 /* Only cancel if not canceled before! */
862 BOOL fCanceled;
863 if (SUCCEEDED(it->second.pProgress->COMGETTER(Canceled)(&fCanceled)) && !fCanceled)
864 it->second.pProgress->Cancel();
865
866 /*
867 * To get waitForCompletion completed (unblocked) we have to notify it if necessary (only
868 * cancle won't work!). This could happen if the client thread (e.g. VBoxService, thread of a spawned process)
869 * is disconnecting without having the chance to sending a status message before, so we
870 * have to abort here to make sure the host never hangs/gets stuck while waiting for the
871 * progress object to become signalled.
872 */
873 it->second.pProgress->notifyComplete(VBOX_E_IPRT_ERROR,
874 COM_IIDOF(IGuest),
875 Guest::getStaticComponentName(),
876 Guest::tr("The operation was canceled because client is shutting down"));
877 }
878 /*
879 * Do *not* NULL pProgress here, because waiting function like executeProcess()
880 * will still rely on this object for checking whether they have to give up!
881 */
882 }
883}
884
885/* Adds a callback with a user provided data block and an optional progress object
886 * to the callback map. A callback is identified by a unique context ID which is used
887 * to identify a callback from the guest side. */
888uint32_t Guest::addCtrlCallbackContext(eVBoxGuestCtrlCallbackType enmType, void *pvData, uint32_t cbData, Progress *pProgress)
889{
890 AssertPtr(pProgress);
891
892 /** @todo Put this stuff into a constructor! */
893 CallbackContext context;
894 context.mType = enmType;
895 context.pvData = pvData;
896 context.cbData = cbData;
897 context.pProgress = pProgress;
898
899 /* Create a new context ID and assign it. */
900 CallbackMapIter it;
901 uint32_t uNewContext = 0;
902 do
903 {
904 /* Create a new context ID ... */
905 uNewContext = ASMAtomicIncU32(&mNextContextID);
906 if (uNewContext == UINT32_MAX)
907 ASMAtomicUoWriteU32(&mNextContextID, 1000);
908 /* Is the context ID already used? */
909 it = getCtrlCallbackContextByID(uNewContext);
910 } while(it != mCallbackMap.end());
911
912 uint32_t nCallbacks = 0;
913 if ( it == mCallbackMap.end()
914 && uNewContext > 0)
915 {
916 /* We apparently got an unused context ID, let's use it! */
917 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
918 mCallbackMap[uNewContext] = context;
919 nCallbacks = mCallbackMap.size();
920 }
921 else
922 {
923 /* Should never happen ... */
924 {
925 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
926 nCallbacks = mCallbackMap.size();
927 }
928 AssertReleaseMsg(uNewContext, ("No free context ID found! uNewContext=%u, nCallbacks=%u", uNewContext, nCallbacks));
929 }
930
931#if 0
932 if (nCallbacks > 256) /* Don't let the container size get too big! */
933 {
934 Guest::CallbackListIter it = mCallbackList.begin();
935 destroyCtrlCallbackContext(it);
936 {
937 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
938 mCallbackList.erase(it);
939 }
940 }
941#endif
942 return uNewContext;
943}
944#endif /* VBOX_WITH_GUEST_CONTROL */
945
946STDMETHODIMP Guest::ExecuteProcess(IN_BSTR aCommand, ULONG aFlags,
947 ComSafeArrayIn(IN_BSTR, aArguments), ComSafeArrayIn(IN_BSTR, aEnvironment),
948 IN_BSTR aUserName, IN_BSTR aPassword,
949 ULONG aTimeoutMS, ULONG *aPID, IProgress **aProgress)
950{
951/** @todo r=bird: Eventually we should clean up all the timeout parameters
952 * in the API and have the same way of specifying infinite waits! */
953#ifndef VBOX_WITH_GUEST_CONTROL
954 ReturnComNotImplemented();
955#else /* VBOX_WITH_GUEST_CONTROL */
956 using namespace guestControl;
957
958 CheckComArgStrNotEmptyOrNull(aCommand);
959 CheckComArgOutPointerValid(aPID);
960 CheckComArgOutPointerValid(aProgress);
961
962 /* Do not allow anonymous executions (with system rights). */
963 if (RT_UNLIKELY((aUserName) == NULL || *(aUserName) == '\0'))
964 return setError(E_INVALIDARG, tr("No user name specified"));
965
966 AutoCaller autoCaller(this);
967 if (FAILED(autoCaller.rc())) return autoCaller.rc();
968
969 if (aFlags != 0) /* Flags are not supported at the moment. */
970 return E_INVALIDARG;
971
972 HRESULT rc = S_OK;
973
974 try
975 {
976 /*
977 * Create progress object. Note that this is a multi operation
978 * object to perform the following steps:
979 * - Operation 1 (0): Create/start process.
980 * - Operation 2 (1): Wait for process to exit.
981 * If this progress completed successfully (S_OK), the process
982 * started and exited normally. In any other case an error/exception
983 * occured.
984 */
985 ComObjPtr <Progress> progress;
986 rc = progress.createObject();
987 if (SUCCEEDED(rc))
988 {
989 rc = progress->init(static_cast<IGuest*>(this),
990 Bstr(tr("Executing process")).raw(),
991 TRUE,
992 2, /* Number of operations. */
993 Bstr(tr("Starting process ...")).raw()); /* Description of first stage. */
994 }
995 if (FAILED(rc)) return rc;
996
997 /*
998 * Prepare process execution.
999 */
1000 int vrc = VINF_SUCCESS;
1001 Utf8Str Utf8Command(aCommand);
1002
1003 /* Adjust timeout */
1004 if (aTimeoutMS == 0)
1005 aTimeoutMS = UINT32_MAX;
1006
1007 /* Prepare arguments. */
1008 char **papszArgv = NULL;
1009 uint32_t uNumArgs = 0;
1010 if (aArguments > 0)
1011 {
1012 com::SafeArray<IN_BSTR> args(ComSafeArrayInArg(aArguments));
1013 uNumArgs = args.size();
1014 papszArgv = (char**)RTMemAlloc(sizeof(char*) * (uNumArgs + 1));
1015 AssertReturn(papszArgv, E_OUTOFMEMORY);
1016 for (unsigned i = 0; RT_SUCCESS(vrc) && i < uNumArgs; i++)
1017 vrc = RTUtf16ToUtf8(args[i], &papszArgv[i]);
1018 papszArgv[uNumArgs] = NULL;
1019 }
1020
1021 Utf8Str Utf8UserName(aUserName);
1022 Utf8Str Utf8Password(aPassword);
1023 if (RT_SUCCESS(vrc))
1024 {
1025 uint32_t uContextID = 0;
1026
1027 char *pszArgs = NULL;
1028 if (uNumArgs > 0)
1029 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, 0);
1030 if (RT_SUCCESS(vrc))
1031 {
1032 uint32_t cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1033
1034 /* Prepare environment. */
1035 void *pvEnv = NULL;
1036 uint32_t uNumEnv = 0;
1037 uint32_t cbEnv = 0;
1038 if (aEnvironment > 0)
1039 {
1040 com::SafeArray<IN_BSTR> env(ComSafeArrayInArg(aEnvironment));
1041
1042 for (unsigned i = 0; i < env.size(); i++)
1043 {
1044 vrc = prepareExecuteEnv(Utf8Str(env[i]).c_str(), &pvEnv, &cbEnv, &uNumEnv);
1045 if (RT_FAILURE(vrc))
1046 break;
1047 }
1048 }
1049
1050 LogRel(("Executing guest process \"%s\" as user \"%s\" ...\n",
1051 Utf8Command.c_str(), Utf8UserName.c_str()));
1052
1053 if (RT_SUCCESS(vrc))
1054 {
1055 PCALLBACKDATAEXECSTATUS pData = (PCALLBACKDATAEXECSTATUS)RTMemAlloc(sizeof(CALLBACKDATAEXECSTATUS));
1056 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1057 RT_ZERO(*pData);
1058 uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_START,
1059 pData, sizeof(CALLBACKDATAEXECSTATUS), progress);
1060 Assert(uContextID > 0);
1061
1062 VBOXHGCMSVCPARM paParms[15];
1063 int i = 0;
1064 paParms[i++].setUInt32(uContextID);
1065 paParms[i++].setPointer((void*)Utf8Command.c_str(), (uint32_t)Utf8Command.length() + 1);
1066 paParms[i++].setUInt32(aFlags);
1067 paParms[i++].setUInt32(uNumArgs);
1068 paParms[i++].setPointer((void*)pszArgs, cbArgs);
1069 paParms[i++].setUInt32(uNumEnv);
1070 paParms[i++].setUInt32(cbEnv);
1071 paParms[i++].setPointer((void*)pvEnv, cbEnv);
1072 paParms[i++].setPointer((void*)Utf8UserName.c_str(), (uint32_t)Utf8UserName.length() + 1);
1073 paParms[i++].setPointer((void*)Utf8Password.c_str(), (uint32_t)Utf8Password.length() + 1);
1074 paParms[i++].setUInt32(aTimeoutMS);
1075
1076 VMMDev *vmmDev;
1077 {
1078 /* Make sure mParent is valid, so set the read lock while using.
1079 * Do not keep this lock while doing the actual call, because in the meanwhile
1080 * another thread could request a write lock which would be a bad idea ... */
1081 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1082
1083 /* Forward the information to the VMM device. */
1084 AssertPtr(mParent);
1085 vmmDev = mParent->getVMMDev();
1086 }
1087
1088 if (vmmDev)
1089 {
1090 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1091 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_CMD,
1092 i, paParms);
1093 }
1094 else
1095 vrc = VERR_INVALID_VM_HANDLE;
1096 RTMemFree(pvEnv);
1097 }
1098 RTStrFree(pszArgs);
1099 }
1100 if (RT_SUCCESS(vrc))
1101 {
1102 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1103
1104 /*
1105 * Wait for the HGCM low level callback until the process
1106 * has been started (or something went wrong). This is necessary to
1107 * get the PID.
1108 */
1109 CallbackMapIter it = getCtrlCallbackContextByID(uContextID);
1110 BOOL fCanceled = FALSE;
1111 if (it != mCallbackMap.end())
1112 {
1113 ComAssert(!it->second.pProgress.isNull());
1114
1115 /*
1116 * Wait for the first stage (=0) to complete (that is starting the process).
1117 */
1118 PCALLBACKDATAEXECSTATUS pData = NULL;
1119 rc = it->second.pProgress->WaitForOperationCompletion(0, aTimeoutMS);
1120 if (SUCCEEDED(rc))
1121 {
1122 /* Was the operation canceled by one of the parties? */
1123 rc = it->second.pProgress->COMGETTER(Canceled)(&fCanceled);
1124 if (FAILED(rc)) throw rc;
1125
1126 if (!fCanceled)
1127 {
1128 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1129
1130 pData = (PCALLBACKDATAEXECSTATUS)it->second.pvData;
1131 Assert(it->second.cbData == sizeof(CALLBACKDATAEXECSTATUS));
1132 AssertPtr(pData);
1133
1134 /* Did we get some status? */
1135 switch (pData->u32Status)
1136 {
1137 case PROC_STS_STARTED:
1138 /* Process is (still) running; get PID. */
1139 *aPID = pData->u32PID;
1140 break;
1141
1142 /* In any other case the process either already
1143 * terminated or something else went wrong, so no PID ... */
1144 case PROC_STS_TEN: /* Terminated normally. */
1145 case PROC_STS_TEA: /* Terminated abnormally. */
1146 case PROC_STS_TES: /* Terminated through signal. */
1147 case PROC_STS_TOK:
1148 case PROC_STS_TOA:
1149 case PROC_STS_DWN:
1150 /*
1151 * Process (already) ended, but we want to get the
1152 * PID anyway to retrieve the output in a later call.
1153 */
1154 *aPID = pData->u32PID;
1155 break;
1156
1157 case PROC_STS_ERROR:
1158 vrc = pData->u32Flags; /* u32Flags member contains IPRT error code. */
1159 break;
1160
1161 case PROC_STS_UNDEFINED:
1162 vrc = VERR_TIMEOUT; /* Operation did not complete within time. */
1163 break;
1164
1165 default:
1166 vrc = VERR_INVALID_PARAMETER; /* Unknown status, should never happen! */
1167 break;
1168 }
1169 }
1170 else /* Operation was canceled. */
1171 vrc = VERR_CANCELLED;
1172 }
1173 else /* Operation did not complete within time. */
1174 vrc = VERR_TIMEOUT;
1175
1176 /*
1177 * Do *not* remove the callback yet - we might wait with the IProgress object on something
1178 * else (like end of process) ...
1179 */
1180 if (RT_FAILURE(vrc))
1181 {
1182 if (vrc == VERR_FILE_NOT_FOUND) /* This is the most likely error. */
1183 rc = setError(VBOX_E_IPRT_ERROR,
1184 tr("The file '%s' was not found on guest"), Utf8Command.c_str());
1185 else if (vrc == VERR_PATH_NOT_FOUND)
1186 rc = setError(VBOX_E_IPRT_ERROR,
1187 tr("The path to file '%s' was not found on guest"), Utf8Command.c_str());
1188 else if (vrc == VERR_BAD_EXE_FORMAT)
1189 rc = setError(VBOX_E_IPRT_ERROR,
1190 tr("The file '%s' is not an executable format on guest"), Utf8Command.c_str());
1191 else if (vrc == VERR_AUTHENTICATION_FAILURE)
1192 rc = setError(VBOX_E_IPRT_ERROR,
1193 tr("The specified user '%s' was not able to logon on guest"), Utf8UserName.c_str());
1194 else if (vrc == VERR_TIMEOUT)
1195 rc = setError(VBOX_E_IPRT_ERROR,
1196 tr("The guest did not respond within time (%ums)"), aTimeoutMS);
1197 else if (vrc == VERR_CANCELLED)
1198 rc = setError(VBOX_E_IPRT_ERROR,
1199 tr("The execution operation was canceled"));
1200 else if (vrc == VERR_PERMISSION_DENIED)
1201 rc = setError(VBOX_E_IPRT_ERROR,
1202 tr("Invalid user/password credentials"));
1203 else
1204 {
1205 if (pData && pData->u32Status == PROC_STS_ERROR)
1206 rc = setError(VBOX_E_IPRT_ERROR,
1207 tr("Process could not be started: %Rrc"), pData->u32Flags);
1208 else
1209 rc = setError(E_UNEXPECTED,
1210 tr("The service call failed with error %Rrc"), vrc);
1211 }
1212 }
1213 else /* Execution went fine. */
1214 {
1215 /* Return the progress to the caller. */
1216 progress.queryInterfaceTo(aProgress);
1217 }
1218 }
1219 else /* Callback context not found; should never happen! */
1220 AssertMsg(it != mCallbackMap.end(), ("Callback context with ID %u not found!", uContextID));
1221 }
1222 else /* HGCM related error codes .*/
1223 {
1224 if (vrc == VERR_INVALID_VM_HANDLE)
1225 rc = setError(VBOX_E_VM_ERROR,
1226 tr("VMM device is not available (is the VM running?)"));
1227 else if (vrc == VERR_TIMEOUT)
1228 rc = setError(VBOX_E_VM_ERROR,
1229 tr("The guest execution service is not ready"));
1230 else if (vrc == VERR_HGCM_SERVICE_NOT_FOUND)
1231 rc = setError(VBOX_E_VM_ERROR,
1232 tr("The guest execution service is not available"));
1233 else /* HGCM call went wrong. */
1234 rc = setError(E_UNEXPECTED,
1235 tr("The HGCM call failed with error %Rrc"), vrc);
1236 }
1237
1238 for (unsigned i = 0; i < uNumArgs; i++)
1239 RTMemFree(papszArgv[i]);
1240 RTMemFree(papszArgv);
1241 }
1242
1243 if (RT_FAILURE(vrc))
1244 LogRel(("Executing guest process \"%s\" as user \"%s\" failed with %Rrc\n",
1245 Utf8Command.c_str(), Utf8UserName.c_str(), vrc));
1246 }
1247 catch (std::bad_alloc &)
1248 {
1249 rc = E_OUTOFMEMORY;
1250 }
1251 return rc;
1252#endif /* VBOX_WITH_GUEST_CONTROL */
1253}
1254
1255STDMETHODIMP Guest::GetProcessOutput(ULONG aPID, ULONG aFlags, ULONG aTimeoutMS, LONG64 aSize, ComSafeArrayOut(BYTE, aData))
1256{
1257/** @todo r=bird: Eventually we should clean up all the timeout parameters
1258 * in the API and have the same way of specifying infinite waits! */
1259#ifndef VBOX_WITH_GUEST_CONTROL
1260 ReturnComNotImplemented();
1261#else /* VBOX_WITH_GUEST_CONTROL */
1262 using namespace guestControl;
1263
1264 CheckComArgExpr(aPID, aPID > 0);
1265 if (aSize < 0)
1266 return setError(E_INVALIDARG, tr("The size argument (%lld) is negative"), aSize);
1267 if (aFlags != 0) /* Flags are not supported at the moment. */
1268 return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), aFlags);
1269
1270 AutoCaller autoCaller(this);
1271 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1272
1273 HRESULT rc = S_OK;
1274
1275 try
1276 {
1277 /*
1278 * Create progress object.
1279 * This progress object, compared to the one in executeProgress() above,
1280 * is only local and is used to determine whether the operation finished
1281 * or got canceled.
1282 */
1283 ComObjPtr <Progress> progress;
1284 rc = progress.createObject();
1285 if (SUCCEEDED(rc))
1286 {
1287 rc = progress->init(static_cast<IGuest*>(this),
1288 Bstr(tr("Getting output of process")).raw(),
1289 TRUE);
1290 }
1291 if (FAILED(rc)) return rc;
1292
1293 /* Adjust timeout */
1294 if (aTimeoutMS == 0)
1295 aTimeoutMS = UINT32_MAX;
1296
1297 /* Search for existing PID. */
1298 PCALLBACKDATAEXECOUT pData = (CALLBACKDATAEXECOUT*)RTMemAlloc(sizeof(CALLBACKDATAEXECOUT));
1299 AssertReturn(pData, VBOX_E_IPRT_ERROR);
1300 RT_ZERO(*pData);
1301 uint32_t uContextID = addCtrlCallbackContext(VBOXGUESTCTRLCALLBACKTYPE_EXEC_OUTPUT,
1302 pData, sizeof(CALLBACKDATAEXECOUT), progress);
1303 Assert(uContextID > 0);
1304
1305 size_t cbData = (size_t)RT_MIN(aSize, _64K);
1306 com::SafeArray<BYTE> outputData(cbData);
1307
1308 VBOXHGCMSVCPARM paParms[5];
1309 int i = 0;
1310 paParms[i++].setUInt32(uContextID);
1311 paParms[i++].setUInt32(aPID);
1312 paParms[i++].setUInt32(aFlags); /** @todo Should represent stdout and/or stderr. */
1313
1314 int vrc = VINF_SUCCESS;
1315
1316 {
1317 VMMDev *vmmDev;
1318 {
1319 /* Make sure mParent is valid, so set the read lock while using.
1320 * Do not keep this lock while doing the actual call, because in the meanwhile
1321 * another thread could request a write lock which would be a bad idea ... */
1322 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1323
1324 /* Forward the information to the VMM device. */
1325 AssertPtr(mParent);
1326 vmmDev = mParent->getVMMDev();
1327 }
1328
1329 if (vmmDev)
1330 {
1331 LogFlowFunc(("hgcmHostCall numParms=%d\n", i));
1332 vrc = vmmDev->hgcmHostCall("VBoxGuestControlSvc", HOST_EXEC_GET_OUTPUT,
1333 i, paParms);
1334 }
1335 }
1336
1337 if (RT_SUCCESS(vrc))
1338 {
1339 LogFlowFunc(("Waiting for HGCM callback (timeout=%ldms) ...\n", aTimeoutMS));
1340
1341 /*
1342 * Wait for the HGCM low level callback until the process
1343 * has been started (or something went wrong). This is necessary to
1344 * get the PID.
1345 */
1346 CallbackMapIter it = getCtrlCallbackContextByID(uContextID);
1347 BOOL fCanceled = FALSE;
1348 if (it != mCallbackMap.end())
1349 {
1350 ComAssert(!it->second.pProgress.isNull());
1351
1352 /* Wait until operation completed. */
1353 rc = it->second.pProgress->WaitForCompletion(aTimeoutMS);
1354 if (FAILED(rc)) throw rc;
1355
1356 /* Was the operation canceled by one of the parties? */
1357 rc = it->second.pProgress->COMGETTER(Canceled)(&fCanceled);
1358 if (FAILED(rc)) throw rc;
1359
1360 if (!fCanceled)
1361 {
1362 BOOL fCompleted;
1363 if ( SUCCEEDED(it->second.pProgress->COMGETTER(Completed)(&fCompleted))
1364 && fCompleted)
1365 {
1366 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1367
1368 /* Did we get some output? */
1369 pData = (PCALLBACKDATAEXECOUT)it->second.pvData;
1370 Assert(it->second.cbData == sizeof(CALLBACKDATAEXECOUT));
1371 AssertPtr(pData);
1372
1373 if (pData->cbData)
1374 {
1375 /* Do we need to resize the array? */
1376 if (pData->cbData > cbData)
1377 outputData.resize(pData->cbData);
1378
1379 /* Fill output in supplied out buffer. */
1380 memcpy(outputData.raw(), pData->pvData, pData->cbData);
1381 outputData.resize(pData->cbData); /* Shrink to fit actual buffer size. */
1382 }
1383 else
1384 vrc = VERR_NO_DATA; /* This is not an error we want to report to COM. */
1385 }
1386 else /* If callback not called within time ... well, that's a timeout! */
1387 vrc = VERR_TIMEOUT;
1388 }
1389 else /* Operation was canceled. */
1390 {
1391 vrc = VERR_CANCELLED;
1392 }
1393
1394 if (RT_FAILURE(vrc))
1395 {
1396 if (vrc == VERR_NO_DATA)
1397 {
1398 /* This is not an error we want to report to COM. */
1399 rc = S_OK;
1400 }
1401 else if (vrc == VERR_TIMEOUT)
1402 {
1403 rc = setError(VBOX_E_IPRT_ERROR,
1404 tr("The guest did not output within time (%ums)"), aTimeoutMS);
1405 }
1406 else if (vrc == VERR_CANCELLED)
1407 {
1408 rc = setError(VBOX_E_IPRT_ERROR,
1409 tr("The output operation was canceled"));
1410 }
1411 else
1412 {
1413 rc = setError(E_UNEXPECTED,
1414 tr("The service call failed with error %Rrc"), vrc);
1415 }
1416 }
1417
1418 {
1419 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1420 /*
1421 * Destroy locally used progress object.
1422 */
1423 destroyCtrlCallbackContext(it);
1424 }
1425
1426 /* Remove callback context (not used anymore). */
1427 mCallbackMap.erase(it);
1428 }
1429 else /* PID lookup failed. */
1430 rc = setError(VBOX_E_IPRT_ERROR,
1431 tr("Process (PID %u) not found!"), aPID);
1432 }
1433 else /* HGCM operation failed. */
1434 rc = setError(E_UNEXPECTED,
1435 tr("The HGCM call failed with error %Rrc"), vrc);
1436
1437 /* Cleanup. */
1438 progress->uninit();
1439 progress.setNull();
1440
1441 /* If something failed (or there simply was no data, indicated by VERR_NO_DATA,
1442 * we return an empty array so that the frontend knows when to give up. */
1443 if (RT_FAILURE(vrc) || FAILED(rc))
1444 outputData.resize(0);
1445 outputData.detachTo(ComSafeArrayOutArg(aData));
1446 }
1447 catch (std::bad_alloc &)
1448 {
1449 rc = E_OUTOFMEMORY;
1450 }
1451 return rc;
1452#endif
1453}
1454
1455STDMETHODIMP Guest::GetProcessStatus(ULONG aPID, ULONG *aExitCode, ULONG *aFlags, ULONG *aStatus)
1456{
1457#ifndef VBOX_WITH_GUEST_CONTROL
1458 ReturnComNotImplemented();
1459#else /* VBOX_WITH_GUEST_CONTROL */
1460 using namespace guestControl;
1461
1462 AutoCaller autoCaller(this);
1463 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1464
1465 HRESULT rc = S_OK;
1466
1467 try
1468 {
1469 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1470
1471 GuestProcessMapIterConst it = getProcessByPID(aPID);
1472 if (it != mGuestProcessMap.end())
1473 {
1474 *aExitCode = it->second.mExitCode;
1475 *aFlags = it->second.mFlags;
1476 *aStatus = it->second.mStatus;
1477 }
1478 else
1479 rc = setError(VBOX_E_IPRT_ERROR,
1480 tr("Process (PID %u) not found!"), aPID);
1481 }
1482 catch (std::bad_alloc &)
1483 {
1484 rc = E_OUTOFMEMORY;
1485 }
1486 return rc;
1487#endif
1488}
1489
1490// public methods only for internal purposes
1491/////////////////////////////////////////////////////////////////////////////
1492
1493/**
1494 * Sets the general Guest Additions information like
1495 * API (interface) version and OS type. Gets called by
1496 * vmmdevUpdateGuestInfo.
1497 *
1498 * @param aInterfaceVersion
1499 * @param aOsType
1500 */
1501void Guest::setAdditionsInfo(Bstr aInterfaceVersion, VBOXOSTYPE aOsType)
1502{
1503 AutoCaller autoCaller(this);
1504 AssertComRCReturnVoid (autoCaller.rc());
1505
1506 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1507
1508 /*
1509 * Note: The Guest Additions API (interface) version is deprecated
1510 * and will not be used anymore! We might need it to at least report
1511 * something as version number if *really* ancient Guest Additions are
1512 * installed (without the guest version + revision properties having set).
1513 */
1514 mData.mInterfaceVersion = aInterfaceVersion;
1515
1516 /*
1517 * Older Additions rely on the Additions API version whether they
1518 * are assumed to be active or not. Since newer Additions do report
1519 * the Additions version *before* calling this function (by calling
1520 * VMMDevReportGuestInfo2, VMMDevReportGuestStatus, VMMDevReportGuestInfo,
1521 * in that order) we can tell apart old and new Additions here. Old
1522 * Additions never would set VMMDevReportGuestInfo2 (which set mData.mAdditionsVersion)
1523 * so they just rely on the aInterfaceVersion string (which gets set by
1524 * VMMDevReportGuestInfo).
1525 *
1526 * So only mark the Additions as being active (run level = system) when we
1527 * don't have the Additions version set.
1528 */
1529 if (mData.mAdditionsVersion.isEmpty())
1530 {
1531 if (aInterfaceVersion.isEmpty())
1532 mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
1533 else
1534 mData.mAdditionsRunLevel = AdditionsRunLevelType_System;
1535 }
1536
1537 /*
1538 * Older Additions didn't have this finer grained capability bit,
1539 * so enable it by default. Newer Additions will not enable this here
1540 * and use the setSupportedFeatures function instead.
1541 */
1542 mData.mSupportsGraphics = mData.mAdditionsRunLevel > AdditionsRunLevelType_None;
1543
1544 /*
1545 * Note! There is a race going on between setting mAdditionsRunLevel and
1546 * mSupportsGraphics here and disabling/enabling it later according to
1547 * its real status when using new(er) Guest Additions.
1548 */
1549 mData.mOSTypeId = Global::OSTypeId (aOsType);
1550}
1551
1552/**
1553 * Sets the Guest Additions version information details.
1554 * Gets called by vmmdevUpdateGuestInfo2.
1555 *
1556 * @param aAdditionsVersion
1557 * @param aVersionName
1558 */
1559void Guest::setAdditionsInfo2(Bstr aAdditionsVersion, Bstr aVersionName, Bstr aRevision)
1560{
1561 AutoCaller autoCaller(this);
1562 AssertComRCReturnVoid (autoCaller.rc());
1563
1564 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1565
1566 if (!aVersionName.isEmpty())
1567 /*
1568 * aVersionName could be "x.y.z_BETA1_FOOBAR", so append revision manually to
1569 * become "x.y.z_BETA1_FOOBARr12345".
1570 */
1571 mData.mAdditionsVersion = BstrFmt("%ls r%ls", aVersionName.raw(), aRevision.raw());
1572 else /* aAdditionsVersion is in x.y.zr12345 format. */
1573 mData.mAdditionsVersion = aAdditionsVersion;
1574}
1575
1576/**
1577 * Sets the status of a certain Guest Additions facility.
1578 * Gets called by vmmdevUpdateGuestStatus.
1579 *
1580 * @param Facility
1581 * @param Status
1582 * @param ulFlags
1583 */
1584void Guest::setAdditionsStatus(VBoxGuestStatusFacility Facility, VBoxGuestStatusCurrent Status, ULONG ulFlags)
1585{
1586 AutoCaller autoCaller(this);
1587 AssertComRCReturnVoid (autoCaller.rc());
1588
1589 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1590
1591 uint32_t uCurFacility = Facility + (Status == VBoxGuestStatusCurrent_Active ? 0 : -1);
1592
1593 /* First check for disabled status. */
1594 if ( Facility < VBoxGuestStatusFacility_VBoxGuestDriver
1595 || ( Facility == VBoxGuestStatusFacility_All
1596 && ( Status == VBoxGuestStatusCurrent_Inactive
1597 || Status == VBoxGuestStatusCurrent_Disabled
1598 )
1599 )
1600 )
1601 {
1602 mData.mAdditionsRunLevel = AdditionsRunLevelType_None;
1603 }
1604 else if (uCurFacility >= VBoxGuestStatusFacility_VBoxTray)
1605 {
1606 mData.mAdditionsRunLevel = AdditionsRunLevelType_Desktop;
1607 }
1608 else if (uCurFacility >= VBoxGuestStatusFacility_VBoxService)
1609 {
1610 mData.mAdditionsRunLevel = AdditionsRunLevelType_Userland;
1611 }
1612 else if (uCurFacility >= VBoxGuestStatusFacility_VBoxGuestDriver)
1613 {
1614 mData.mAdditionsRunLevel = AdditionsRunLevelType_System;
1615 }
1616 else /* Should never happen! */
1617 AssertMsgFailed(("Invalid facility status/run level detected! uCurFacility=%ld\n", uCurFacility));
1618}
1619
1620/**
1621 * Sets the supported features (and whether they are active or not).
1622 *
1623 * @param fCaps Guest capability bit mask (VMMDEV_GUEST_SUPPORTS_XXX).
1624 * @param fActive No idea what this is supposed to be, it's always 0 and
1625 * not references by this method.
1626 */
1627void Guest::setSupportedFeatures(uint32_t fCaps, uint32_t fActive)
1628{
1629 AutoCaller autoCaller(this);
1630 AssertComRCReturnVoid (autoCaller.rc());
1631
1632 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1633
1634 mData.mSupportsSeamless = (fCaps & VMMDEV_GUEST_SUPPORTS_SEAMLESS);
1635 /** @todo Add VMMDEV_GUEST_SUPPORTS_GUEST_HOST_WINDOW_MAPPING */
1636 mData.mSupportsGraphics = (fCaps & VMMDEV_GUEST_SUPPORTS_GRAPHICS);
1637}
1638/* 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