VirtualBox

source: vbox/trunk/src/VBox/Main/src-client/GuestProcessImpl.cpp@ 47874

Last change on this file since 47874 was 47874, checked in by vboxsync, 11 years ago

Warnings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 70.2 KB
Line 
1
2/* $Id: GuestProcessImpl.cpp 47874 2013-08-20 07:33:42Z vboxsync $ */
3/** @file
4 * VirtualBox Main - Guest process handling.
5 */
6
7/*
8 * Copyright (C) 2012-2013 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19/**
20 * Locking rules:
21 * - When the main dispatcher (callbackDispatcher) is called it takes the
22 * WriteLock while dispatching to the various on* methods.
23 * - All other outer functions (accessible by Main) must not own a lock
24 * while waiting for a callback or for an event.
25 * - Only keep Read/WriteLocks as short as possible and only when necessary.
26 */
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include "GuestProcessImpl.h"
32#include "GuestSessionImpl.h"
33#include "GuestCtrlImplPrivate.h"
34#include "ConsoleImpl.h"
35#include "VirtualBoxErrorInfoImpl.h"
36
37#include "Global.h"
38#include "AutoCaller.h"
39#include "VBoxEvents.h"
40
41#include <memory> /* For auto_ptr. */
42
43#include <iprt/asm.h>
44#include <iprt/cpp/utils.h> /* For unconst(). */
45#include <iprt/getopt.h>
46
47#include <VBox/com/listeners.h>
48
49#include <VBox/com/array.h>
50
51#ifdef LOG_GROUP
52 #undef LOG_GROUP
53#endif
54#define LOG_GROUP LOG_GROUP_GUEST_CONTROL
55#include <VBox/log.h>
56
57
58class GuestProcessTask
59{
60public:
61
62 GuestProcessTask(GuestProcess *pProcess)
63 : mProcess(pProcess),
64 mRC(VINF_SUCCESS) { }
65
66 virtual ~GuestProcessTask(void) { }
67
68 int rc(void) const { return mRC; }
69 bool isOk(void) const { return RT_SUCCESS(mRC); }
70 const ComObjPtr<GuestProcess> &Process(void) const { return mProcess; }
71
72protected:
73
74 const ComObjPtr<GuestProcess> mProcess;
75 int mRC;
76};
77
78class GuestProcessStartTask : public GuestProcessTask
79{
80public:
81
82 GuestProcessStartTask(GuestProcess *pProcess)
83 : GuestProcessTask(pProcess) { }
84};
85
86/**
87 * Internal listener class to serve events in an
88 * active manner, e.g. without polling delays.
89 */
90class GuestProcessListener
91{
92public:
93
94 GuestProcessListener(void)
95 {
96 }
97
98 HRESULT init(GuestProcess *pProcess)
99 {
100 mProcess = pProcess;
101 return S_OK;
102 }
103
104 void uninit(void)
105 {
106 mProcess.setNull();
107 }
108
109 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
110 {
111 switch (aType)
112 {
113 case VBoxEventType_OnGuestProcessStateChanged:
114 case VBoxEventType_OnGuestProcessInputNotify:
115 case VBoxEventType_OnGuestProcessOutput:
116 {
117 Assert(!mProcess.isNull());
118 int rc2 = mProcess->signalWaitEvents(aType, aEvent);
119#ifdef DEBUG_andy
120 LogFlowThisFunc(("Signalling events of type=%ld, process=%p resulted in rc=%Rrc\n",
121 aType, mProcess, rc2));
122#endif
123 break;
124 }
125
126 default:
127 AssertMsgFailed(("Unhandled event %ld\n", aType));
128 break;
129 }
130
131 return S_OK;
132 }
133
134private:
135
136 ComObjPtr<GuestProcess> mProcess;
137};
138typedef ListenerImpl<GuestProcessListener, GuestProcess*> GuestProcessListenerImpl;
139
140VBOX_LISTENER_DECLARE(GuestProcessListenerImpl)
141
142// constructor / destructor
143/////////////////////////////////////////////////////////////////////////////
144
145DEFINE_EMPTY_CTOR_DTOR(GuestProcess)
146
147HRESULT GuestProcess::FinalConstruct(void)
148{
149 LogFlowThisFuncEnter();
150 return BaseFinalConstruct();
151}
152
153void GuestProcess::FinalRelease(void)
154{
155 LogFlowThisFuncEnter();
156 uninit();
157 BaseFinalRelease();
158 LogFlowThisFuncLeave();
159}
160
161// public initializer/uninitializer for internal purposes only
162/////////////////////////////////////////////////////////////////////////////
163
164int GuestProcess::init(Console *aConsole, GuestSession *aSession,
165 ULONG aProcessID, const GuestProcessStartupInfo &aProcInfo)
166{
167 LogFlowThisFunc(("aConsole=%p, aSession=%p, aProcessID=%RU32\n",
168 aConsole, aSession, aProcessID));
169
170 AssertPtrReturn(aConsole, VERR_INVALID_POINTER);
171 AssertPtrReturn(aSession, VERR_INVALID_POINTER);
172
173 /* Enclose the state transition NotReady->InInit->Ready. */
174 AutoInitSpan autoInitSpan(this);
175 AssertReturn(autoInitSpan.isOk(), VERR_OBJECT_DESTROYED);
176
177#ifndef VBOX_WITH_GUEST_CONTROL
178 autoInitSpan.setSucceeded();
179 return VINF_SUCCESS;
180#else
181 HRESULT hr;
182
183 int vrc = bindToSession(aConsole, aSession, aProcessID /* Object ID */);
184 if (RT_SUCCESS(vrc))
185 {
186 hr = unconst(mEventSource).createObject();
187 if (FAILED(hr))
188 vrc = VERR_NO_MEMORY;
189 else
190 {
191 hr = mEventSource->init(static_cast<IGuestProcess*>(this));
192 if (FAILED(hr))
193 vrc = VERR_COM_UNEXPECTED;
194 }
195 }
196
197 if (RT_SUCCESS(vrc))
198 {
199 try
200 {
201 GuestProcessListener *pListener = new GuestProcessListener();
202 ComObjPtr<GuestProcessListenerImpl> thisListener;
203 hr = thisListener.createObject();
204 if (SUCCEEDED(hr))
205 hr = thisListener->init(pListener, this);
206
207 if (SUCCEEDED(hr))
208 {
209 com::SafeArray <VBoxEventType_T> eventTypes;
210 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
211 eventTypes.push_back(VBoxEventType_OnGuestProcessInputNotify);
212 eventTypes.push_back(VBoxEventType_OnGuestProcessOutput);
213 hr = mEventSource->RegisterListener(thisListener,
214 ComSafeArrayAsInParam(eventTypes),
215 TRUE /* Active listener */);
216 if (SUCCEEDED(hr))
217 {
218 vrc = baseInit();
219 if (RT_SUCCESS(vrc))
220 {
221 mLocalListener = thisListener;
222 }
223 }
224 else
225 vrc = VERR_COM_UNEXPECTED;
226 }
227 else
228 vrc = VERR_COM_UNEXPECTED;
229 }
230 catch(std::bad_alloc &)
231 {
232 vrc = VERR_NO_MEMORY;
233 }
234 }
235
236 if (RT_SUCCESS(vrc))
237 {
238 mData.mProcess = aProcInfo;
239 mData.mExitCode = 0;
240 mData.mPID = 0;
241 mData.mLastError = VINF_SUCCESS;
242 mData.mStatus = ProcessStatus_Undefined;
243 /* Everything else will be set by the actual starting routine. */
244
245 /* Confirm a successful initialization when it's the case. */
246 autoInitSpan.setSucceeded();
247
248 return vrc;
249 }
250
251 autoInitSpan.setFailed();
252 return vrc;
253#endif
254}
255
256/**
257 * Uninitializes the instance.
258 * Called from FinalRelease().
259 */
260void GuestProcess::uninit(void)
261{
262 LogFlowThisFuncEnter();
263
264 /* Enclose the state transition Ready->InUninit->NotReady. */
265 AutoUninitSpan autoUninitSpan(this);
266 if (autoUninitSpan.uninitDone())
267 return;
268
269 LogFlowThisFunc(("mCmd=%s, PID=%RU32\n",
270 mData.mProcess.mCommand.c_str(), mData.mPID));
271
272 /* Terminate process if not already done yet. */
273 int guestRc = VINF_SUCCESS;
274 int vrc = terminateProcess(30 * 1000, &guestRc); /** @todo Make timeouts configurable. */
275 /* Note: Don't return here yet; first uninit all other stuff in
276 * case of failure. */
277
278#ifdef VBOX_WITH_GUEST_CONTROL
279 baseUninit();
280
281 mEventSource->UnregisterListener(mLocalListener);
282
283 mLocalListener.setNull();
284 unconst(mEventSource).setNull();
285#endif
286
287 LogFlowThisFunc(("Returning rc=%Rrc, guestRc=%Rrc\n",
288 vrc, guestRc));
289}
290
291// implementation of public getters/setters for attributes
292/////////////////////////////////////////////////////////////////////////////
293
294STDMETHODIMP GuestProcess::COMGETTER(Arguments)(ComSafeArrayOut(BSTR, aArguments))
295{
296#ifndef VBOX_WITH_GUEST_CONTROL
297 ReturnComNotImplemented();
298#else
299 LogFlowThisFuncEnter();
300
301 CheckComArgOutSafeArrayPointerValid(aArguments);
302
303 AutoCaller autoCaller(this);
304 if (FAILED(autoCaller.rc())) return autoCaller.rc();
305
306 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
307
308 com::SafeArray<BSTR> collection(mData.mProcess.mArguments.size());
309 size_t s = 0;
310 for (ProcessArguments::const_iterator it = mData.mProcess.mArguments.begin();
311 it != mData.mProcess.mArguments.end();
312 it++, s++)
313 {
314 Bstr tmp = *it;
315 tmp.cloneTo(&collection[s]);
316 }
317
318 collection.detachTo(ComSafeArrayOutArg(aArguments));
319
320 return S_OK;
321#endif /* VBOX_WITH_GUEST_CONTROL */
322}
323
324STDMETHODIMP GuestProcess::COMGETTER(Environment)(ComSafeArrayOut(BSTR, aEnvironment))
325{
326#ifndef VBOX_WITH_GUEST_CONTROL
327 ReturnComNotImplemented();
328#else
329 LogFlowThisFuncEnter();
330
331 CheckComArgOutSafeArrayPointerValid(aEnvironment);
332
333 AutoCaller autoCaller(this);
334 if (FAILED(autoCaller.rc())) return autoCaller.rc();
335
336 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
337
338 com::SafeArray<BSTR> arguments(mData.mProcess.mEnvironment.Size());
339 for (size_t i = 0; i < arguments.size(); i++)
340 {
341 Bstr tmp = mData.mProcess.mEnvironment.Get(i);
342 tmp.cloneTo(&arguments[i]);
343 }
344 arguments.detachTo(ComSafeArrayOutArg(aEnvironment));
345
346 return S_OK;
347#endif /* VBOX_WITH_GUEST_CONTROL */
348}
349
350STDMETHODIMP GuestProcess::COMGETTER(EventSource)(IEventSource ** aEventSource)
351{
352#ifndef VBOX_WITH_GUEST_CONTROL
353 ReturnComNotImplemented();
354#else
355 LogFlowThisFuncEnter();
356
357 CheckComArgOutPointerValid(aEventSource);
358
359 AutoCaller autoCaller(this);
360 if (FAILED(autoCaller.rc())) return autoCaller.rc();
361
362 // no need to lock - lifetime constant
363 mEventSource.queryInterfaceTo(aEventSource);
364
365 LogFlowThisFuncLeave();
366 return S_OK;
367#endif /* VBOX_WITH_GUEST_CONTROL */
368}
369
370STDMETHODIMP GuestProcess::COMGETTER(ExecutablePath)(BSTR *aExecutablePath)
371{
372#ifndef VBOX_WITH_GUEST_CONTROL
373 ReturnComNotImplemented();
374#else
375 LogFlowThisFuncEnter();
376
377 CheckComArgOutPointerValid(aExecutablePath);
378
379 AutoCaller autoCaller(this);
380 if (FAILED(autoCaller.rc())) return autoCaller.rc();
381
382 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
383
384 mData.mProcess.mCommand.cloneTo(aExecutablePath);
385
386 return S_OK;
387#endif /* VBOX_WITH_GUEST_CONTROL */
388}
389
390STDMETHODIMP GuestProcess::COMGETTER(ExitCode)(LONG *aExitCode)
391{
392#ifndef VBOX_WITH_GUEST_CONTROL
393 ReturnComNotImplemented();
394#else
395 LogFlowThisFuncEnter();
396
397 CheckComArgOutPointerValid(aExitCode);
398
399 AutoCaller autoCaller(this);
400 if (FAILED(autoCaller.rc())) return autoCaller.rc();
401
402 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
403
404 *aExitCode = mData.mExitCode;
405
406 return S_OK;
407#endif /* VBOX_WITH_GUEST_CONTROL */
408}
409
410STDMETHODIMP GuestProcess::COMGETTER(Name)(BSTR *aName)
411{
412#ifndef VBOX_WITH_GUEST_CONTROL
413 ReturnComNotImplemented();
414#else
415 LogFlowThisFuncEnter();
416
417 CheckComArgOutPointerValid(aName);
418
419 AutoCaller autoCaller(this);
420 if (FAILED(autoCaller.rc())) return autoCaller.rc();
421
422 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
423
424 mData.mProcess.mName.cloneTo(aName);
425
426 return S_OK;
427#endif /* VBOX_WITH_GUEST_CONTROL */
428}
429
430STDMETHODIMP GuestProcess::COMGETTER(PID)(ULONG *aPID)
431{
432#ifndef VBOX_WITH_GUEST_CONTROL
433 ReturnComNotImplemented();
434#else
435 LogFlowThisFuncEnter();
436
437 CheckComArgOutPointerValid(aPID);
438
439 AutoCaller autoCaller(this);
440 if (FAILED(autoCaller.rc())) return autoCaller.rc();
441
442 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
443
444 *aPID = mData.mPID;
445
446 return S_OK;
447#endif /* VBOX_WITH_GUEST_CONTROL */
448}
449
450STDMETHODIMP GuestProcess::COMGETTER(Status)(ProcessStatus_T *aStatus)
451{
452#ifndef VBOX_WITH_GUEST_CONTROL
453 ReturnComNotImplemented();
454#else
455 LogFlowThisFuncEnter();
456
457 AutoCaller autoCaller(this);
458 if (FAILED(autoCaller.rc())) return autoCaller.rc();
459
460 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
461
462 *aStatus = mData.mStatus;
463
464 return S_OK;
465#endif /* VBOX_WITH_GUEST_CONTROL */
466}
467
468// private methods
469/////////////////////////////////////////////////////////////////////////////
470
471int GuestProcess::callbackDispatcher(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
472{
473 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
474 AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);
475#ifdef DEBUG
476 LogFlowThisFunc(("uPID=%RU32, uContextID=%RU32, uFunction=%RU32, pSvcCb=%p\n",
477 mData.mPID, pCbCtx->uContextID, pCbCtx->uFunction, pSvcCb));
478#endif
479
480 int vrc;
481 switch (pCbCtx->uFunction)
482 {
483 case GUEST_DISCONNECTED:
484 {
485 vrc = onGuestDisconnected(pCbCtx, pSvcCb);
486 break;
487 }
488
489 case GUEST_EXEC_STATUS:
490 {
491 vrc = onProcessStatusChange(pCbCtx, pSvcCb);
492 break;
493 }
494
495 case GUEST_EXEC_OUTPUT:
496 {
497 vrc = onProcessOutput(pCbCtx, pSvcCb);
498 break;
499 }
500
501 case GUEST_EXEC_INPUT_STATUS:
502 {
503 vrc = onProcessInputStatus(pCbCtx, pSvcCb);
504 break;
505 }
506
507 default:
508 /* Silently ignore not implemented functions. */
509 vrc = VERR_NOT_SUPPORTED;
510 break;
511 }
512
513#ifdef DEBUG
514 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
515#endif
516 return vrc;
517}
518
519/**
520 * Checks if the current assigned PID matches another PID (from a callback).
521 *
522 * In protocol v1 we don't have the possibility to terminate/kill
523 * processes so it can happen that a formerly started process A
524 * (which has the context ID 0 (session=0, process=0, count=0) will
525 * send a delayed message to the host if this process has already
526 * been discarded there and the same context ID was reused by
527 * a process B. Process B in turn then has a different guest PID.
528 *
529 * @return IPRT status code.
530 * @param uPID PID to check.
531 */
532inline int GuestProcess::checkPID(uint32_t uPID)
533{
534 /* Was there a PID assigned yet? */
535 if (mData.mPID)
536 {
537 /*
538
539 */
540 if (mSession->getProtocolVersion() < 2)
541 {
542 /* Simply ignore the stale requests. */
543 return (mData.mPID == uPID)
544 ? VINF_SUCCESS : VERR_NOT_FOUND;
545 }
546#ifndef DEBUG_andy
547 /* This should never happen! */
548 AssertReleaseMsg(mData.mPID == uPID, ("Unterminated guest process (guest PID %RU32) sent data to a newly started process (host PID %RU32)\n",
549 uPID, mData.mPID));
550#endif
551 }
552
553 return VINF_SUCCESS;
554}
555
556/* static */
557Utf8Str GuestProcess::guestErrorToString(int guestRc)
558{
559 Utf8Str strError;
560
561 /** @todo pData->u32Flags: int vs. uint32 -- IPRT errors are *negative* !!! */
562 switch (guestRc)
563 {
564 case VERR_FILE_NOT_FOUND: /* This is the most likely error. */
565 strError += Utf8StrFmt(tr("The specified file was not found on guest"));
566 break;
567
568 case VERR_INVALID_VM_HANDLE:
569 strError += Utf8StrFmt(tr("VMM device is not available (is the VM running?)"));
570 break;
571
572 case VERR_HGCM_SERVICE_NOT_FOUND:
573 strError += Utf8StrFmt(tr("The guest execution service is not available"));
574 break;
575
576 case VERR_PATH_NOT_FOUND:
577 strError += Utf8StrFmt(tr("Could not resolve path to specified file was not found on guest"));
578 break;
579
580 case VERR_BAD_EXE_FORMAT:
581 strError += Utf8StrFmt(tr("The specified file is not an executable format on guest"));
582 break;
583
584 case VERR_AUTHENTICATION_FAILURE:
585 strError += Utf8StrFmt(tr("The specified user was not able to logon on guest"));
586 break;
587
588 case VERR_INVALID_NAME:
589 strError += Utf8StrFmt(tr("The specified file is an invalid name"));
590 break;
591
592 case VERR_TIMEOUT:
593 strError += Utf8StrFmt(tr("The guest did not respond within time"));
594 break;
595
596 case VERR_CANCELLED:
597 strError += Utf8StrFmt(tr("The execution operation was canceled"));
598 break;
599
600 case VERR_PERMISSION_DENIED:
601 strError += Utf8StrFmt(tr("Invalid user/password credentials"));
602 break;
603
604 case VERR_MAX_PROCS_REACHED:
605 strError += Utf8StrFmt(tr("Maximum number of concurrent guest processes has been reached"));
606 break;
607
608 case VERR_NOT_EQUAL: /** @todo Imprecise to the user; can mean anything and all. */
609 strError += Utf8StrFmt(tr("Unable to retrieve requested information"));
610 break;
611
612 case VERR_NOT_FOUND:
613 strError += Utf8StrFmt(tr("The guest execution service is not ready (yet)"));
614 break;
615
616 default:
617 strError += Utf8StrFmt("%Rrc", guestRc);
618 break;
619 }
620
621 return strError;
622}
623
624inline bool GuestProcess::isAlive(void)
625{
626 return ( mData.mStatus == ProcessStatus_Started
627 || mData.mStatus == ProcessStatus_Paused
628 || mData.mStatus == ProcessStatus_Terminating);
629}
630
631inline bool GuestProcess::hasEnded(void)
632{
633 return ( mData.mStatus == ProcessStatus_TerminatedNormally
634 || mData.mStatus == ProcessStatus_TerminatedSignal
635 || mData.mStatus == ProcessStatus_TerminatedAbnormally
636 || mData.mStatus == ProcessStatus_TimedOutKilled
637 || mData.mStatus == ProcessStatus_TimedOutAbnormally
638 || mData.mStatus == ProcessStatus_Down
639 || mData.mStatus == ProcessStatus_Error);
640}
641
642int GuestProcess::onGuestDisconnected(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
643{
644 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
645 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
646
647 int vrc = setProcessStatus(ProcessStatus_Down, VINF_SUCCESS);
648
649 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
650 return vrc;
651}
652
653int GuestProcess::onProcessInputStatus(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
654{
655 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
656 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
657 /* pCallback is optional. */
658
659 if (pSvcCbData->mParms < 5)
660 return VERR_INVALID_PARAMETER;
661
662 CALLBACKDATA_PROC_INPUT dataCb;
663 /* pSvcCb->mpaParms[0] always contains the context ID. */
664 int vrc = pSvcCbData->mpaParms[1].getUInt32(&dataCb.uPID);
665 AssertRCReturn(vrc, vrc);
666 vrc = pSvcCbData->mpaParms[2].getUInt32(&dataCb.uStatus);
667 AssertRCReturn(vrc, vrc);
668 vrc = pSvcCbData->mpaParms[3].getUInt32(&dataCb.uFlags);
669 AssertRCReturn(vrc, vrc);
670 vrc = pSvcCbData->mpaParms[4].getUInt32(&dataCb.uProcessed);
671 AssertRCReturn(vrc, vrc);
672
673 LogFlowThisFunc(("uPID=%RU32, uStatus=%RU32, uFlags=%RI32, cbProcessed=%RU32\n",
674 dataCb.uPID, dataCb.uStatus, dataCb.uFlags, dataCb.uProcessed));
675
676 vrc = checkPID(dataCb.uPID);
677 if (RT_SUCCESS(vrc))
678 {
679 ProcessInputStatus_T inputStatus = ProcessInputStatus_Undefined;
680 switch (dataCb.uStatus)
681 {
682 case INPUT_STS_WRITTEN:
683 inputStatus = ProcessInputStatus_Written;
684 break;
685 case INPUT_STS_ERROR:
686 inputStatus = ProcessInputStatus_Broken;
687 break;
688 case INPUT_STS_TERMINATED:
689 inputStatus = ProcessInputStatus_Broken;
690 break;
691 case INPUT_STS_OVERFLOW:
692 inputStatus = ProcessInputStatus_Overflow;
693 break;
694 case INPUT_STS_UNDEFINED:
695 /* Fall through is intentional. */
696 default:
697 AssertMsg(!dataCb.uProcessed, ("Processed data is not 0 in undefined input state\n"));
698 break;
699 }
700
701 if (inputStatus != ProcessInputStatus_Undefined)
702 {
703 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
704
705 /* Copy over necessary data before releasing lock again. */
706 uint32_t uPID = mData.mPID;
707 /** @todo Also handle mSession? */
708
709 alock.release(); /* Release lock before firing off event. */
710
711 fireGuestProcessInputNotifyEvent(mEventSource, mSession, this,
712 uPID, 0 /* StdIn */, dataCb.uProcessed, inputStatus);
713 }
714 }
715
716 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
717 return vrc;
718}
719
720int GuestProcess::onProcessNotifyIO(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
721{
722 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
723 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
724
725 return VERR_NOT_IMPLEMENTED;
726}
727
728int GuestProcess::onProcessStatusChange(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
729{
730 AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
731 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
732
733 if (pSvcCbData->mParms < 5)
734 return VERR_INVALID_PARAMETER;
735
736 CALLBACKDATA_PROC_STATUS dataCb;
737 /* pSvcCb->mpaParms[0] always contains the context ID. */
738 int vrc = pSvcCbData->mpaParms[1].getUInt32(&dataCb.uPID);
739 AssertRCReturn(vrc, vrc);
740 vrc = pSvcCbData->mpaParms[2].getUInt32(&dataCb.uStatus);
741 AssertRCReturn(vrc, vrc);
742 vrc = pSvcCbData->mpaParms[3].getUInt32(&dataCb.uFlags);
743 AssertRCReturn(vrc, vrc);
744 vrc = pSvcCbData->mpaParms[4].getPointer(&dataCb.pvData, &dataCb.cbData);
745 AssertRCReturn(vrc, vrc);
746
747 LogFlowThisFunc(("uPID=%RU32, uStatus=%RU32, uFlags=%RU32\n",
748 dataCb.uPID, dataCb.uStatus, dataCb.uFlags));
749
750 vrc = checkPID(dataCb.uPID);
751 if (RT_SUCCESS(vrc))
752 {
753 ProcessStatus_T procStatus = ProcessStatus_Undefined;
754 int procRc = VINF_SUCCESS;
755
756 switch (dataCb.uStatus)
757 {
758 case PROC_STS_STARTED:
759 {
760 procStatus = ProcessStatus_Started;
761
762 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
763 mData.mPID = dataCb.uPID; /* Set the process PID. */
764 break;
765 }
766
767 case PROC_STS_TEN:
768 {
769 procStatus = ProcessStatus_TerminatedNormally;
770
771 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
772 mData.mExitCode = dataCb.uFlags; /* Contains the exit code. */
773 break;
774 }
775
776 case PROC_STS_TES:
777 {
778 procStatus = ProcessStatus_TerminatedSignal;
779
780 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
781 mData.mExitCode = dataCb.uFlags; /* Contains the signal. */
782 break;
783 }
784
785 case PROC_STS_TEA:
786 {
787 procStatus = ProcessStatus_TerminatedAbnormally;
788 break;
789 }
790
791 case PROC_STS_TOK:
792 {
793 procStatus = ProcessStatus_TimedOutKilled;
794 break;
795 }
796
797 case PROC_STS_TOA:
798 {
799 procStatus = ProcessStatus_TimedOutAbnormally;
800 break;
801 }
802
803 case PROC_STS_DWN:
804 {
805 procStatus = ProcessStatus_Down;
806 break;
807 }
808
809 case PROC_STS_ERROR:
810 {
811 procRc = dataCb.uFlags; /* mFlags contains the IPRT error sent from the guest. */
812 procStatus = ProcessStatus_Error;
813 break;
814 }
815
816 case PROC_STS_UNDEFINED:
817 default:
818 {
819 /* Silently skip this request. */
820 procStatus = ProcessStatus_Undefined;
821 break;
822 }
823 }
824
825 LogFlowThisFunc(("Got rc=%Rrc, procSts=%ld, procRc=%Rrc\n",
826 vrc, procStatus, procRc));
827
828 /* Set the process status. */
829 int rc2 = setProcessStatus(procStatus, procRc);
830 if (RT_SUCCESS(vrc))
831 vrc = rc2;
832 }
833
834 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
835 return vrc;
836}
837
838int GuestProcess::onProcessOutput(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
839{
840 AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);
841
842 if (pSvcCbData->mParms < 5)
843 return VERR_INVALID_PARAMETER;
844
845 CALLBACKDATA_PROC_OUTPUT dataCb;
846 /* pSvcCb->mpaParms[0] always contains the context ID. */
847 int vrc = pSvcCbData->mpaParms[1].getUInt32(&dataCb.uPID);
848 AssertRCReturn(vrc, vrc);
849 vrc = pSvcCbData->mpaParms[2].getUInt32(&dataCb.uHandle);
850 AssertRCReturn(vrc, vrc);
851 vrc = pSvcCbData->mpaParms[3].getUInt32(&dataCb.uFlags);
852 AssertRCReturn(vrc, vrc);
853 vrc = pSvcCbData->mpaParms[4].getPointer(&dataCb.pvData, &dataCb.cbData);
854 AssertRCReturn(vrc, vrc);
855
856 LogFlowThisFunc(("uPID=%RU32, uHandle=%RU32, uFlags=%RI32, pvData=%p, cbData=%RU32\n",
857 dataCb.uPID, dataCb.uHandle, dataCb.uFlags, dataCb.pvData, dataCb.cbData));
858
859 vrc = checkPID(dataCb.uPID);
860 if (RT_SUCCESS(vrc))
861 {
862 com::SafeArray<BYTE> data((size_t)dataCb.cbData);
863 if (dataCb.cbData)
864 data.initFrom((BYTE*)dataCb.pvData, dataCb.cbData);
865
866 fireGuestProcessOutputEvent(mEventSource, mSession, this,
867 mData.mPID, dataCb.uHandle, dataCb.cbData, ComSafeArrayAsInParam(data));
868 }
869
870 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
871 return vrc;
872}
873
874int GuestProcess::readData(uint32_t uHandle, uint32_t uSize, uint32_t uTimeoutMS,
875 void *pvData, size_t cbData, uint32_t *pcbRead, int *pGuestRc)
876{
877 LogFlowThisFunc(("uPID=%RU32, uHandle=%RU32, uSize=%RU32, uTimeoutMS=%RU32, pvData=%p, cbData=%RU32, pGuestRc=%p\n",
878 mData.mPID, uHandle, uSize, uTimeoutMS, pvData, cbData, pGuestRc));
879 AssertReturn(uSize, VERR_INVALID_PARAMETER);
880 AssertPtrReturn(pvData, VERR_INVALID_POINTER);
881 AssertReturn(cbData >= uSize, VERR_INVALID_PARAMETER);
882 /* pcbRead is optional. */
883
884 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
885
886 if ( mData.mStatus != ProcessStatus_Started
887 /* Skip reading if the process wasn't started with the appropriate
888 * flags. */
889 || ( ( uHandle == OUTPUT_HANDLE_ID_STDOUT
890 || uHandle == OUTPUT_HANDLE_ID_STDOUT_DEPRECATED)
891 && !(mData.mProcess.mFlags & ProcessCreateFlag_WaitForStdOut))
892 || ( uHandle == OUTPUT_HANDLE_ID_STDERR
893 && !(mData.mProcess.mFlags & ProcessCreateFlag_WaitForStdErr))
894 )
895 {
896 if (pcbRead)
897 *pcbRead = 0;
898 if (pGuestRc)
899 *pGuestRc = VINF_SUCCESS;
900 return VINF_SUCCESS; /* Nothing to read anymore. */
901 }
902
903 int vrc;
904
905 GuestWaitEvent *pEvent = NULL;
906 std::list < VBoxEventType_T > eventTypes;
907 try
908 {
909 /*
910 * On Guest Additions < 4.3 there is no guarantee that the process status
911 * change arrives *after* the output event, e.g. if this was the last output
912 * block being read and the process will report status "terminate".
913 * So just skip checking for process status change and only wait for the
914 * output event.
915 */
916 if (mSession->getProtocolVersion() >= 2)
917 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
918 eventTypes.push_back(VBoxEventType_OnGuestProcessOutput);
919
920 vrc = registerWaitEvent(eventTypes, &pEvent);
921 }
922 catch (std::bad_alloc)
923 {
924 vrc = VERR_NO_MEMORY;
925 }
926
927 if (RT_FAILURE(vrc))
928 return vrc;
929
930 if (RT_SUCCESS(vrc))
931 {
932 VBOXHGCMSVCPARM paParms[8];
933 int i = 0;
934 paParms[i++].setUInt32(pEvent->ContextID());
935 paParms[i++].setUInt32(mData.mPID);
936 paParms[i++].setUInt32(uHandle);
937 paParms[i++].setUInt32(0 /* Flags, none set yet. */);
938
939 alock.release(); /* Drop the write lock before sending. */
940
941 vrc = sendCommand(HOST_EXEC_GET_OUTPUT, i, paParms);
942 }
943
944 if (RT_SUCCESS(vrc))
945 vrc = waitForOutput(pEvent, uHandle, uTimeoutMS,
946 pvData, cbData, pcbRead);
947
948 unregisterWaitEvent(pEvent);
949
950 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
951 return vrc;
952}
953
954/* Does not do locking; caller is responsible for that! */
955int GuestProcess::setProcessStatus(ProcessStatus_T procStatus, int procRc)
956{
957 LogFlowThisFuncEnter();
958
959 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
960
961 LogFlowThisFunc(("oldStatus=%ld, newStatus=%ld, procRc=%Rrc\n",
962 mData.mStatus, procStatus, procRc));
963
964 if (procStatus == ProcessStatus_Error)
965 {
966 AssertMsg(RT_FAILURE(procRc), ("Guest rc must be an error (%Rrc)\n", procRc));
967 /* Do not allow overwriting an already set error. If this happens
968 * this means we forgot some error checking/locking somewhere. */
969 AssertMsg(RT_SUCCESS(mData.mLastError), ("Guest rc already set (to %Rrc)\n", mData.mLastError));
970 }
971 else
972 AssertMsg(RT_SUCCESS(procRc), ("Guest rc must not be an error (%Rrc)\n", procRc));
973
974 int rc = VINF_SUCCESS;
975
976 if (mData.mStatus != procStatus) /* Was there a process status change? */
977 {
978 mData.mStatus = procStatus;
979 mData.mLastError = procRc;
980
981 ComObjPtr<VirtualBoxErrorInfo> errorInfo;
982 HRESULT hr = errorInfo.createObject();
983 ComAssertComRC(hr);
984 if (RT_FAILURE(mData.mLastError))
985 {
986 hr = errorInfo->initEx(VBOX_E_IPRT_ERROR, mData.mLastError,
987 COM_IIDOF(IGuestProcess), getComponentName(),
988 guestErrorToString(mData.mLastError));
989 ComAssertComRC(hr);
990 }
991
992 /* Copy over necessary data before releasing lock again. */
993 uint32_t uPID = mData.mPID;
994 /** @todo Also handle mSession? */
995
996 alock.release(); /* Release lock before firing off event. */
997
998 fireGuestProcessStateChangedEvent(mEventSource, mSession, this,
999 uPID, procStatus, errorInfo);
1000#if 0
1001 /*
1002 * On Guest Additions < 4.3 there is no guarantee that outstanding
1003 * requests will be delivered to the host after the process has ended,
1004 * so just cancel all waiting events here to not let clients run
1005 * into timeouts.
1006 */
1007 if ( mSession->getProtocolVersion() < 2
1008 && hasEnded())
1009 {
1010 LogFlowThisFunc(("Process ended, canceling outstanding wait events ...\n"));
1011 rc = cancelWaitEvents();
1012 }
1013#endif
1014 }
1015
1016 return rc;
1017}
1018
1019/* static */
1020HRESULT GuestProcess::setErrorExternal(VirtualBoxBase *pInterface, int guestRc)
1021{
1022 AssertPtr(pInterface);
1023 AssertMsg(RT_FAILURE(guestRc), ("Guest rc does not indicate a failure when setting error\n"));
1024
1025 return pInterface->setError(VBOX_E_IPRT_ERROR, GuestProcess::guestErrorToString(guestRc).c_str());
1026}
1027
1028int GuestProcess::startProcess(uint32_t uTimeoutMS, int *pGuestRc)
1029{
1030 LogFlowThisFunc(("uTimeoutMS=%RU32, procCmd=%s, procTimeoutMS=%RU32, procFlags=%x, sessionID=%RU32\n",
1031 uTimeoutMS, mData.mProcess.mCommand.c_str(), mData.mProcess.mTimeoutMS, mData.mProcess.mFlags,
1032 mSession->getId()));
1033
1034 /* Wait until the caller function (if kicked off by a thread)
1035 * has returned and continue operation. */
1036 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1037
1038 mData.mStatus = ProcessStatus_Starting;
1039
1040 int vrc;
1041
1042 GuestWaitEvent *pEvent = NULL;
1043 std::list < VBoxEventType_T > eventTypes;
1044 try
1045 {
1046 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1047
1048 vrc = registerWaitEvent(eventTypes, &pEvent);
1049 }
1050 catch (std::bad_alloc)
1051 {
1052 vrc = VERR_NO_MEMORY;
1053 }
1054
1055 if (RT_FAILURE(vrc))
1056 return vrc;
1057
1058 GuestSession *pSession = mSession;
1059 AssertPtr(pSession);
1060
1061 const GuestCredentials &sessionCreds = pSession->getCredentials();
1062
1063 /* Prepare arguments. */
1064 char *pszArgs = NULL;
1065 size_t cArgs = mData.mProcess.mArguments.size();
1066 if (cArgs >= UINT32_MAX)
1067 vrc = VERR_BUFFER_OVERFLOW;
1068
1069 if ( RT_SUCCESS(vrc)
1070 && cArgs)
1071 {
1072 char **papszArgv = (char**)RTMemAlloc((cArgs + 1) * sizeof(char*));
1073 AssertReturn(papszArgv, VERR_NO_MEMORY);
1074
1075 for (size_t i = 0; i < cArgs && RT_SUCCESS(vrc); i++)
1076 {
1077 const char *pszCurArg = mData.mProcess.mArguments[i].c_str();
1078 AssertPtr(pszCurArg);
1079 vrc = RTStrDupEx(&papszArgv[i], pszCurArg);
1080 }
1081 papszArgv[cArgs] = NULL;
1082
1083 if (RT_SUCCESS(vrc))
1084 vrc = RTGetOptArgvToString(&pszArgs, papszArgv, RTGETOPTARGV_CNV_QUOTE_MS_CRT);
1085
1086 if (papszArgv)
1087 {
1088 size_t i = 0;
1089 while (papszArgv[i])
1090 RTStrFree(papszArgv[i++]);
1091 RTMemFree(papszArgv);
1092 }
1093 }
1094
1095 /* Calculate arguments size (in bytes). */
1096 size_t cbArgs = 0;
1097 if (RT_SUCCESS(vrc))
1098 cbArgs = pszArgs ? strlen(pszArgs) + 1 : 0; /* Include terminating zero. */
1099
1100 /* Prepare environment. */
1101 void *pvEnv = NULL;
1102 size_t cbEnv = 0;
1103 if (RT_SUCCESS(vrc))
1104 vrc = mData.mProcess.mEnvironment.BuildEnvironmentBlock(&pvEnv, &cbEnv, NULL /* cEnv */);
1105
1106 if (RT_SUCCESS(vrc))
1107 {
1108 AssertPtr(mSession);
1109 uint32_t uProtocol = mSession->getProtocolVersion();
1110
1111 /* Prepare HGCM call. */
1112 VBOXHGCMSVCPARM paParms[16];
1113 int i = 0;
1114 paParms[i++].setUInt32(pEvent->ContextID());
1115 paParms[i++].setPointer((void*)mData.mProcess.mCommand.c_str(),
1116 (ULONG)mData.mProcess.mCommand.length() + 1);
1117 paParms[i++].setUInt32(mData.mProcess.mFlags);
1118 paParms[i++].setUInt32((uint32_t)mData.mProcess.mArguments.size());
1119 paParms[i++].setPointer((void*)pszArgs, (uint32_t)cbArgs);
1120 paParms[i++].setUInt32((uint32_t)mData.mProcess.mEnvironment.Size());
1121 paParms[i++].setUInt32((uint32_t)cbEnv);
1122 paParms[i++].setPointer((void*)pvEnv, (uint32_t)cbEnv);
1123 if (uProtocol < 2)
1124 {
1125 /* In protocol v1 (VBox < 4.3) the credentials were part of the execution
1126 * call. In newer protocols these credentials are part of the opened guest
1127 * session, so not needed anymore here. */
1128 paParms[i++].setPointer((void*)sessionCreds.mUser.c_str(), (ULONG)sessionCreds.mUser.length() + 1);
1129 paParms[i++].setPointer((void*)sessionCreds.mPassword.c_str(), (ULONG)sessionCreds.mPassword.length() + 1);
1130 }
1131 /*
1132 * If the WaitForProcessStartOnly flag is set, we only want to define and wait for a timeout
1133 * until the process was started - the process itself then gets an infinite timeout for execution.
1134 * This is handy when we want to start a process inside a worker thread within a certain timeout
1135 * but let the started process perform lengthly operations then.
1136 */
1137 if (mData.mProcess.mFlags & ProcessCreateFlag_WaitForProcessStartOnly)
1138 paParms[i++].setUInt32(UINT32_MAX /* Infinite timeout */);
1139 else
1140 paParms[i++].setUInt32(mData.mProcess.mTimeoutMS);
1141 if (uProtocol >= 2)
1142 {
1143 paParms[i++].setUInt32(mData.mProcess.mPriority);
1144 /* CPU affinity: We only support one CPU affinity block at the moment,
1145 * so that makes up to 64 CPUs total. This can be more in the future. */
1146 paParms[i++].setUInt32(1);
1147 /* The actual CPU affinity blocks. */
1148 paParms[i++].setPointer((void*)&mData.mProcess.mAffinity, sizeof(mData.mProcess.mAffinity));
1149 }
1150
1151 alock.release(); /* Drop the write lock before sending. */
1152
1153 vrc = sendCommand(HOST_EXEC_CMD, i, paParms);
1154 if (RT_FAILURE(vrc))
1155 {
1156 int rc2 = setProcessStatus(ProcessStatus_Error, vrc);
1157 AssertRC(rc2);
1158 }
1159 }
1160
1161 GuestEnvironment::FreeEnvironmentBlock(pvEnv);
1162 if (pszArgs)
1163 RTStrFree(pszArgs);
1164
1165 if (RT_SUCCESS(vrc))
1166 vrc = waitForStatusChange(pEvent, uTimeoutMS,
1167 NULL /* Process status */, pGuestRc);
1168 unregisterWaitEvent(pEvent);
1169
1170 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1171 return vrc;
1172}
1173
1174int GuestProcess::startProcessAsync(void)
1175{
1176 LogFlowThisFuncEnter();
1177
1178 int vrc;
1179
1180 try
1181 {
1182 /* Asynchronously start the process on the guest by kicking off a
1183 * worker thread. */
1184 std::auto_ptr<GuestProcessStartTask> pTask(new GuestProcessStartTask(this));
1185 AssertReturn(pTask->isOk(), pTask->rc());
1186
1187 vrc = RTThreadCreate(NULL, GuestProcess::startProcessThread,
1188 (void *)pTask.get(), 0,
1189 RTTHREADTYPE_MAIN_WORKER, 0,
1190 "gctlPrcStart");
1191 if (RT_SUCCESS(vrc))
1192 {
1193 /* pTask is now owned by startProcessThread(), so release it. */
1194 pTask.release();
1195 }
1196 }
1197 catch(std::bad_alloc &)
1198 {
1199 vrc = VERR_NO_MEMORY;
1200 }
1201
1202 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1203 return vrc;
1204}
1205
1206/* static */
1207DECLCALLBACK(int) GuestProcess::startProcessThread(RTTHREAD Thread, void *pvUser)
1208{
1209 LogFlowFunc(("pvUser=%p\n", pvUser));
1210
1211 std::auto_ptr<GuestProcessStartTask> pTask(static_cast<GuestProcessStartTask*>(pvUser));
1212 AssertPtr(pTask.get());
1213
1214 const ComObjPtr<GuestProcess> pProcess(pTask->Process());
1215 Assert(!pProcess.isNull());
1216
1217 AutoCaller autoCaller(pProcess);
1218 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1219
1220 int vrc = pProcess->startProcess(30 * 1000 /* 30s timeout */,
1221 NULL /* Guest rc, ignored */);
1222 /* Nothing to do here anymore. */
1223
1224 LogFlowFunc(("pProcess=%p returning rc=%Rrc\n", (GuestProcess *)pProcess, vrc));
1225 return vrc;
1226}
1227
1228int GuestProcess::terminateProcess(uint32_t uTimeoutMS, int *pGuestRc)
1229{
1230 /* pGuestRc is optional. */
1231 LogFlowThisFunc(("uTimeoutMS=%RU32\n", uTimeoutMS));
1232
1233 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1234
1235 if (mData.mStatus != ProcessStatus_Started)
1236 {
1237 LogFlowThisFunc(("Process not started (yet), nothing to terminate\n"));
1238 return VINF_SUCCESS; /* Nothing to do (anymore). */
1239 }
1240
1241 int vrc = VINF_SUCCESS;
1242
1243 AssertPtr(mSession);
1244 /* Note: VBox < 4.3 (aka protocol version 1) does not
1245 * support this, so just skip. */
1246 if (mSession->getProtocolVersion() < 2)
1247 vrc = VERR_NOT_SUPPORTED;
1248
1249 if (RT_SUCCESS(vrc))
1250 {
1251 GuestWaitEvent *pEvent = NULL;
1252 std::list < VBoxEventType_T > eventTypes;
1253 try
1254 {
1255 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1256
1257 vrc = registerWaitEvent(eventTypes, &pEvent);
1258 }
1259 catch (std::bad_alloc)
1260 {
1261 vrc = VERR_NO_MEMORY;
1262 }
1263
1264 if (RT_FAILURE(vrc))
1265 return vrc;
1266
1267 VBOXHGCMSVCPARM paParms[4];
1268 int i = 0;
1269 paParms[i++].setUInt32(pEvent->ContextID());
1270 paParms[i++].setUInt32(mData.mPID);
1271
1272 alock.release(); /* Drop the write lock before sending. */
1273
1274 vrc = sendCommand(HOST_EXEC_TERMINATE, i, paParms);
1275 if (RT_SUCCESS(vrc))
1276 vrc = waitForStatusChange(pEvent, uTimeoutMS,
1277 NULL /* ProcessStatus */, pGuestRc);
1278 unregisterWaitEvent(pEvent);
1279 }
1280
1281 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1282 return vrc;
1283}
1284
1285/* static */
1286ProcessWaitResult_T GuestProcess::waitFlagsToResultEx(uint32_t fWaitFlags,
1287 ProcessStatus_T procStatus, uint32_t uProcFlags,
1288 uint32_t uProtocol)
1289{
1290 ProcessWaitResult_T waitResult = ProcessWaitResult_None;
1291
1292 if ( (fWaitFlags & ProcessWaitForFlag_Terminate)
1293 || (fWaitFlags & ProcessWaitForFlag_StdIn)
1294 || (fWaitFlags & ProcessWaitForFlag_StdOut)
1295 || (fWaitFlags & ProcessWaitForFlag_StdErr))
1296 {
1297 switch (procStatus)
1298 {
1299 case ProcessStatus_TerminatedNormally:
1300 case ProcessStatus_TerminatedSignal:
1301 case ProcessStatus_TerminatedAbnormally:
1302 case ProcessStatus_Down:
1303 waitResult = ProcessWaitResult_Terminate;
1304 break;
1305
1306 case ProcessStatus_TimedOutKilled:
1307 case ProcessStatus_TimedOutAbnormally:
1308 waitResult = ProcessWaitResult_Timeout;
1309 break;
1310
1311 case ProcessStatus_Error:
1312 /* Handled above. */
1313 break;
1314
1315 case ProcessStatus_Started:
1316 {
1317 /*
1318 * If ProcessCreateFlag_WaitForProcessStartOnly was specified on process creation the
1319 * caller is not interested in getting further process statuses -- so just don't notify
1320 * anything here anymore and return.
1321 */
1322 if (uProcFlags & ProcessCreateFlag_WaitForProcessStartOnly)
1323 waitResult = ProcessWaitResult_Start;
1324 break;
1325 }
1326
1327 case ProcessStatus_Undefined:
1328 case ProcessStatus_Starting:
1329 /* No result available yet. */
1330 break;
1331
1332 default:
1333 AssertMsgFailed(("Unhandled process status %ld\n", procStatus));
1334 break;
1335 }
1336 }
1337 else if (fWaitFlags & ProcessWaitForFlag_Start)
1338 {
1339 switch (procStatus)
1340 {
1341 case ProcessStatus_Started:
1342 case ProcessStatus_Paused:
1343 case ProcessStatus_Terminating:
1344 case ProcessStatus_TerminatedNormally:
1345 case ProcessStatus_TerminatedSignal:
1346 case ProcessStatus_TerminatedAbnormally:
1347 case ProcessStatus_Down:
1348 waitResult = ProcessWaitResult_Start;
1349 break;
1350
1351 case ProcessStatus_Error:
1352 waitResult = ProcessWaitResult_Error;
1353 break;
1354
1355 case ProcessStatus_TimedOutKilled:
1356 case ProcessStatus_TimedOutAbnormally:
1357 waitResult = ProcessWaitResult_Timeout;
1358 break;
1359
1360 case ProcessStatus_Undefined:
1361 case ProcessStatus_Starting:
1362 /* No result available yet. */
1363 break;
1364
1365 default:
1366 AssertMsgFailed(("Unhandled process status %ld\n", procStatus));
1367 break;
1368 }
1369 }
1370
1371 /* Filter out waits which are *not* supported using
1372 * older guest control Guest Additions.
1373 *
1374 ** @todo ProcessWaitForFlag_Std* flags are not implemented yet.
1375 */
1376 if (uProtocol < 99) /* See @todo above. */
1377 {
1378 if ( waitResult == ProcessWaitResult_None
1379 /* We don't support waiting for stdin, out + err,
1380 * just skip waiting then. */
1381 && ( (fWaitFlags & ProcessWaitForFlag_StdIn)
1382 || (fWaitFlags & ProcessWaitForFlag_StdOut)
1383 || (fWaitFlags & ProcessWaitForFlag_StdErr)
1384 )
1385 )
1386 {
1387 /* Use _WaitFlagNotSupported because we don't know what to tell the caller. */
1388 waitResult = ProcessWaitResult_WaitFlagNotSupported;
1389 }
1390 }
1391
1392 return waitResult;
1393}
1394
1395ProcessWaitResult_T GuestProcess::waitFlagsToResult(uint32_t fWaitFlags)
1396{
1397 AssertPtr(mSession);
1398 return GuestProcess::waitFlagsToResultEx(fWaitFlags, mData.mStatus, mData.mProcess.mFlags,
1399 mSession->getProtocolVersion());
1400}
1401
1402int GuestProcess::waitFor(uint32_t fWaitFlags, ULONG uTimeoutMS, ProcessWaitResult_T &waitResult, int *pGuestRc)
1403{
1404 AssertReturn(fWaitFlags, VERR_INVALID_PARAMETER);
1405
1406 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1407
1408 LogFlowThisFunc(("fWaitFlags=0x%x, uTimeoutMS=%RU32, procStatus=%RU32, procRc=%Rrc, pGuestRc=%p\n",
1409 fWaitFlags, uTimeoutMS, mData.mStatus, mData.mLastError, pGuestRc));
1410
1411 /* Did some error occur before? Then skip waiting and return. */
1412 if (mData.mStatus == ProcessStatus_Error)
1413 {
1414 waitResult = ProcessWaitResult_Error;
1415 AssertMsg(RT_FAILURE(mData.mLastError), ("No error rc (%Rrc) set when guest process indicated an error\n", mData.mLastError));
1416 if (pGuestRc)
1417 *pGuestRc = mData.mLastError; /* Return last set error. */
1418 return VERR_GSTCTL_GUEST_ERROR;
1419 }
1420
1421 waitResult = waitFlagsToResult(fWaitFlags);
1422 LogFlowThisFunc(("waitFlagToResult=%ld\n", waitResult));
1423
1424 /* No waiting needed? Return immediately using the last set error. */
1425 if (waitResult != ProcessWaitResult_None)
1426 {
1427 if (pGuestRc)
1428 *pGuestRc = mData.mLastError; /* Return last set error (if any). */
1429 return RT_SUCCESS(mData.mLastError) ? VINF_SUCCESS : VERR_GSTCTL_GUEST_ERROR;
1430 }
1431
1432 alock.release(); /* Release lock before waiting. */
1433
1434 int vrc;
1435
1436 GuestWaitEvent *pEvent = NULL;
1437 std::list < VBoxEventType_T > eventTypes;
1438 try
1439 {
1440 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1441
1442 vrc = registerWaitEvent(eventTypes, &pEvent);
1443 }
1444 catch (std::bad_alloc)
1445 {
1446 vrc = VERR_NO_MEMORY;
1447 }
1448
1449 if (RT_FAILURE(vrc))
1450 return vrc;
1451
1452 /*
1453 * Do the actual waiting.
1454 */
1455 ProcessStatus_T processStatus = ProcessStatus_Undefined;
1456 uint64_t u64StartMS = RTTimeMilliTS();
1457 for (;;)
1458 {
1459 uint64_t u32ElapsedMS = RTTimeMilliTS() - u64StartMS;
1460 if ( uTimeoutMS != RT_INDEFINITE_WAIT
1461 && u32ElapsedMS >= uTimeoutMS)
1462 {
1463 vrc = VERR_TIMEOUT;
1464 break;
1465 }
1466
1467 vrc = waitForStatusChange(pEvent,
1468 uTimeoutMS == RT_INDEFINITE_WAIT
1469 ? RT_INDEFINITE_WAIT : uTimeoutMS - u32ElapsedMS,
1470 &processStatus, pGuestRc);
1471 if (RT_SUCCESS(vrc))
1472 {
1473 alock.acquire();
1474
1475 waitResult = waitFlagsToResultEx(fWaitFlags, processStatus,
1476 mData.mProcess.mFlags, mSession->getProtocolVersion());
1477 LogFlowThisFunc(("Got new status change: waitResult=%ld, processStatus=%ld\n",
1478 waitResult, processStatus));
1479 if (ProcessWaitResult_None != waitResult) /* We got a waiting result. */
1480 break;
1481 }
1482 else /* Waiting failed, bail out. */
1483 break;
1484
1485 alock.release(); /* Don't hold lock in next waiting round. */
1486 }
1487
1488 unregisterWaitEvent(pEvent);
1489
1490 LogFlowThisFunc(("Returned waitResult=%ld, processStatus=%ld, rc=%Rrc\n",
1491 waitResult, processStatus, vrc));
1492 return vrc;
1493}
1494
1495int GuestProcess::waitForInputNotify(GuestWaitEvent *pEvent, uint32_t uHandle, uint32_t uTimeoutMS,
1496 ProcessInputStatus_T *pInputStatus, uint32_t *pcbProcessed)
1497{
1498 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1499
1500 VBoxEventType_T evtType;
1501 ComPtr<IEvent> pIEvent;
1502 int vrc = waitForEvent(pEvent, uTimeoutMS,
1503 &evtType, pIEvent.asOutParam());
1504 if (RT_SUCCESS(vrc))
1505 {
1506 if (evtType == VBoxEventType_OnGuestProcessInputNotify)
1507 {
1508 ComPtr<IGuestProcessInputNotifyEvent> pProcessEvent = pIEvent;
1509 Assert(!pProcessEvent.isNull());
1510
1511 if (pInputStatus)
1512 {
1513 HRESULT hr2 = pProcessEvent->COMGETTER(Status)(pInputStatus);
1514 ComAssertComRC(hr2);
1515 }
1516 if (pcbProcessed)
1517 {
1518 HRESULT hr2 = pProcessEvent->COMGETTER(Processed)((ULONG*)pcbProcessed);
1519 ComAssertComRC(hr2);
1520 }
1521 }
1522 else
1523 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1524 }
1525
1526 LogFlowThisFunc(("Returning pEvent=%p, uHandle=%RU32, rc=%Rrc\n",
1527 pEvent, uHandle, vrc));
1528 return vrc;
1529}
1530
1531int GuestProcess::waitForOutput(GuestWaitEvent *pEvent, uint32_t uHandle, uint32_t uTimeoutMS,
1532 void *pvData, size_t cbData, uint32_t *pcbRead)
1533{
1534 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1535 /* pvData is optional. */
1536 /* cbData is optional. */
1537 /* pcbRead is optional. */
1538
1539 LogFlowThisFunc(("cEventTypes=%zu, pEvent=%p, uHandle=%RU32, uTimeoutMS=%RU32, pvData=%p, cbData=%zu, pcbRead=%p\n",
1540 pEvent->TypeCount(), pEvent, uHandle, uTimeoutMS, pvData, cbData, pcbRead));
1541
1542 int vrc;
1543
1544 VBoxEventType_T evtType;
1545 ComPtr<IEvent> pIEvent;
1546 do
1547 {
1548 vrc = waitForEvent(pEvent, uTimeoutMS,
1549 &evtType, pIEvent.asOutParam());
1550 if (RT_SUCCESS(vrc))
1551 {
1552#ifdef DEBUG_andy
1553 LogFlowThisFunc(("pEvent=%p, evtType=%ld\n", pEvent, evtType));
1554#endif
1555 if (evtType == VBoxEventType_OnGuestProcessOutput)
1556 {
1557 ComPtr<IGuestProcessOutputEvent> pProcessEvent = pIEvent;
1558 Assert(!pProcessEvent.isNull());
1559
1560 ULONG uHandleEvent;
1561 HRESULT hr = pProcessEvent->COMGETTER(Handle)(&uHandleEvent);
1562 LogFlowThisFunc(("Received output, uHandle=%RU32\n", uHandleEvent));
1563 if ( SUCCEEDED(hr)
1564 && uHandleEvent == uHandle)
1565 {
1566 if (pvData)
1567 {
1568 com::SafeArray <BYTE> data;
1569 hr = pProcessEvent->COMGETTER(Data)(ComSafeArrayAsOutParam(data));
1570 ComAssertComRC(hr);
1571 size_t cbRead = data.size();
1572 if (cbRead)
1573 {
1574 if (cbRead <= cbData)
1575 {
1576 /* Copy data from event into our buffer. */
1577 memcpy(pvData, data.raw(), data.size());
1578 }
1579 else
1580 vrc = VERR_BUFFER_OVERFLOW;
1581 }
1582 }
1583
1584 if ( RT_SUCCESS(vrc)
1585 && pcbRead)
1586 {
1587 ULONG cbRead;
1588 hr = pProcessEvent->COMGETTER(Processed)(&cbRead);
1589 ComAssertComRC(hr);
1590 *pcbRead = (uint32_t)cbRead;
1591 }
1592
1593 break;
1594 }
1595 else if (FAILED(hr))
1596 vrc = VERR_COM_UNEXPECTED;
1597 }
1598 else
1599 vrc = VWRN_GSTCTL_OBJECTSTATE_CHANGED;
1600 }
1601
1602 } while (vrc == VINF_SUCCESS);
1603
1604 if ( vrc != VINF_SUCCESS
1605 && pcbRead)
1606 {
1607 *pcbRead = 0;
1608 }
1609
1610 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1611 return vrc;
1612}
1613
1614int GuestProcess::waitForStatusChange(GuestWaitEvent *pEvent, uint32_t uTimeoutMS,
1615 ProcessStatus_T *pProcessStatus, int *pGuestRc)
1616{
1617 AssertPtrReturn(pEvent, VERR_INVALID_POINTER);
1618 /* pProcessStatus is optional. */
1619 /* pGuestRc is optional. */
1620
1621 VBoxEventType_T evtType;
1622 ComPtr<IEvent> pIEvent;
1623 int vrc = waitForEvent(pEvent, uTimeoutMS,
1624 &evtType, pIEvent.asOutParam());
1625 if (RT_SUCCESS(vrc))
1626 {
1627 Assert(evtType == VBoxEventType_OnGuestProcessStateChanged);
1628 ComPtr<IGuestProcessStateChangedEvent> pProcessEvent = pIEvent;
1629 Assert(!pProcessEvent.isNull());
1630
1631 HRESULT hr;
1632 if (pProcessStatus)
1633 {
1634 hr = pProcessEvent->COMGETTER(Status)(pProcessStatus);
1635 ComAssertComRC(hr);
1636 }
1637
1638 ComPtr<IVirtualBoxErrorInfo> errorInfo;
1639 hr = pProcessEvent->COMGETTER(Error)(errorInfo.asOutParam());
1640 ComAssertComRC(hr);
1641
1642 LONG lGuestRc;
1643 hr = errorInfo->COMGETTER(ResultDetail)(&lGuestRc);
1644 ComAssertComRC(hr);
1645
1646 LogFlowThisFunc(("resultDetail=%RI32 (rc=%Rrc)\n",
1647 lGuestRc, lGuestRc));
1648
1649 if (RT_FAILURE((int)lGuestRc))
1650 vrc = VERR_GSTCTL_GUEST_ERROR;
1651
1652 if (pGuestRc)
1653 *pGuestRc = (int)lGuestRc;
1654 }
1655
1656 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1657 return vrc;
1658}
1659
1660/* static */
1661bool GuestProcess::waitResultImpliesEx(ProcessWaitResult_T waitResult,
1662 ProcessStatus_T procStatus, uint32_t uProcFlags,
1663 uint32_t uProtocol)
1664{
1665 bool fImplies;
1666
1667 switch (waitResult)
1668 {
1669 case ProcessWaitResult_Start:
1670 fImplies = procStatus == ProcessStatus_Started;
1671 break;
1672
1673 case ProcessWaitResult_Terminate:
1674 fImplies = ( procStatus == ProcessStatus_TerminatedNormally
1675 || procStatus == ProcessStatus_TerminatedSignal
1676 || procStatus == ProcessStatus_TerminatedAbnormally
1677 || procStatus == ProcessStatus_TimedOutKilled
1678 || procStatus == ProcessStatus_TimedOutAbnormally
1679 || procStatus == ProcessStatus_Down
1680 || procStatus == ProcessStatus_Error);
1681 break;
1682
1683 default:
1684 fImplies = false;
1685 break;
1686 }
1687
1688 return fImplies;
1689}
1690
1691int GuestProcess::writeData(uint32_t uHandle, uint32_t uFlags,
1692 void *pvData, size_t cbData, uint32_t uTimeoutMS, uint32_t *puWritten, int *pGuestRc)
1693{
1694 LogFlowThisFunc(("uPID=%RU32, uHandle=%RU32, uFlags=%RU32, pvData=%p, cbData=%RU32, uTimeoutMS=%RU32, puWritten=%p, pGuestRc=%p\n",
1695 mData.mPID, uHandle, uFlags, pvData, cbData, uTimeoutMS, puWritten, pGuestRc));
1696 /* All is optional. There can be 0 byte writes. */
1697
1698 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1699
1700 if (mData.mStatus != ProcessStatus_Started)
1701 {
1702 if (puWritten)
1703 *puWritten = 0;
1704 if (pGuestRc)
1705 *pGuestRc = VINF_SUCCESS;
1706 return VINF_SUCCESS; /* Not available for writing (anymore). */
1707 }
1708
1709 int vrc;
1710
1711 GuestWaitEvent *pEvent = NULL;
1712 std::list < VBoxEventType_T > eventTypes;
1713 try
1714 {
1715 /*
1716 * On Guest Additions < 4.3 there is no guarantee that the process status
1717 * change arrives *after* the input event, e.g. if this was the last input
1718 * block being written and the process will report status "terminate".
1719 * So just skip checking for process status change and only wait for the
1720 * input event.
1721 */
1722 if (mSession->getProtocolVersion() >= 2)
1723 eventTypes.push_back(VBoxEventType_OnGuestProcessStateChanged);
1724 eventTypes.push_back(VBoxEventType_OnGuestProcessInputNotify);
1725
1726 vrc = registerWaitEvent(eventTypes, &pEvent);
1727 }
1728 catch (std::bad_alloc)
1729 {
1730 vrc = VERR_NO_MEMORY;
1731 }
1732
1733 if (RT_FAILURE(vrc))
1734 return vrc;
1735
1736 VBOXHGCMSVCPARM paParms[5];
1737 int i = 0;
1738 paParms[i++].setUInt32(pEvent->ContextID());
1739 paParms[i++].setUInt32(mData.mPID);
1740 paParms[i++].setUInt32(uFlags);
1741 paParms[i++].setPointer(pvData, (uint32_t)cbData);
1742 paParms[i++].setUInt32((uint32_t)cbData);
1743
1744 alock.release(); /* Drop the write lock before sending. */
1745
1746 uint32_t cbProcessed = 0;
1747 vrc = sendCommand(HOST_EXEC_SET_INPUT, i, paParms);
1748 if (RT_SUCCESS(vrc))
1749 {
1750 ProcessInputStatus_T inputStatus;
1751 vrc = waitForInputNotify(pEvent, uHandle, uTimeoutMS,
1752 &inputStatus, &cbProcessed);
1753 if (RT_SUCCESS(vrc))
1754 {
1755 /** @todo Set guestRc. */
1756
1757 if (puWritten)
1758 *puWritten = cbProcessed;
1759 }
1760 /** @todo Error handling. */
1761 }
1762
1763 unregisterWaitEvent(pEvent);
1764
1765 LogFlowThisFunc(("Returning cbProcessed=%RU32, rc=%Rrc\n",
1766 cbProcessed, vrc));
1767 return vrc;
1768}
1769
1770// implementation of public methods
1771/////////////////////////////////////////////////////////////////////////////
1772
1773STDMETHODIMP GuestProcess::Read(ULONG aHandle, ULONG aToRead, ULONG aTimeoutMS, ComSafeArrayOut(BYTE, aData))
1774{
1775#ifndef VBOX_WITH_GUEST_CONTROL
1776 ReturnComNotImplemented();
1777#else
1778 if (aToRead == 0)
1779 return setError(E_INVALIDARG, tr("The size to read is zero"));
1780 CheckComArgOutSafeArrayPointerValid(aData);
1781
1782 AutoCaller autoCaller(this);
1783 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1784
1785 com::SafeArray<BYTE> data((size_t)aToRead);
1786 Assert(data.size() >= aToRead);
1787
1788 HRESULT hr = S_OK;
1789
1790 uint32_t cbRead; int guestRc;
1791 int vrc = readData(aHandle, aToRead, aTimeoutMS, data.raw(), aToRead, &cbRead, &guestRc);
1792 if (RT_SUCCESS(vrc))
1793 {
1794 if (data.size() != cbRead)
1795 data.resize(cbRead);
1796 data.detachTo(ComSafeArrayOutArg(aData));
1797 }
1798 else
1799 {
1800 switch (vrc)
1801 {
1802 case VERR_GSTCTL_GUEST_ERROR:
1803 hr = GuestProcess::setErrorExternal(this, guestRc);
1804 break;
1805
1806 default:
1807 hr = setError(VBOX_E_IPRT_ERROR,
1808 tr("Reading from process \"%s\" (PID %RU32) failed: %Rrc"),
1809 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1810 break;
1811 }
1812 }
1813
1814 LogFlowThisFunc(("rc=%Rrc, cbRead=%RU32\n", vrc, cbRead));
1815
1816 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1817 return hr;
1818#endif /* VBOX_WITH_GUEST_CONTROL */
1819}
1820
1821STDMETHODIMP GuestProcess::Terminate(void)
1822{
1823#ifndef VBOX_WITH_GUEST_CONTROL
1824 ReturnComNotImplemented();
1825#else
1826 LogFlowThisFuncEnter();
1827
1828 AutoCaller autoCaller(this);
1829 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1830
1831 HRESULT hr = S_OK;
1832
1833 int guestRc;
1834 int vrc = terminateProcess(30 * 1000 /* Timeout in ms */,
1835 &guestRc);
1836 if (RT_FAILURE(vrc))
1837 {
1838 switch (vrc)
1839 {
1840 case VERR_GSTCTL_GUEST_ERROR:
1841 hr = GuestProcess::setErrorExternal(this, guestRc);
1842 break;
1843
1844 case VERR_NOT_SUPPORTED:
1845 hr = setError(VBOX_E_IPRT_ERROR,
1846 tr("Terminating process \"%s\" (PID %RU32) not supported by installed Guest Additions"),
1847 mData.mProcess.mCommand.c_str(), mData.mPID);
1848 break;
1849
1850 default:
1851 hr = setError(VBOX_E_IPRT_ERROR,
1852 tr("Terminating process \"%s\" (PID %RU32) failed: %Rrc"),
1853 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1854 break;
1855 }
1856 }
1857
1858 /* Remove the process from our internal session list. Only an API client
1859 * now may hold references to it. */
1860 AssertPtr(mSession);
1861 mSession->processRemoveFromList(this);
1862
1863 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1864 return hr;
1865#endif /* VBOX_WITH_GUEST_CONTROL */
1866}
1867
1868STDMETHODIMP GuestProcess::WaitFor(ULONG aWaitFlags, ULONG aTimeoutMS, ProcessWaitResult_T *aReason)
1869{
1870#ifndef VBOX_WITH_GUEST_CONTROL
1871 ReturnComNotImplemented();
1872#else
1873 LogFlowThisFuncEnter();
1874
1875 CheckComArgOutPointerValid(aReason);
1876
1877 AutoCaller autoCaller(this);
1878 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1879
1880 /*
1881 * Note: Do not hold any locks here while waiting!
1882 */
1883 HRESULT hr = S_OK;
1884
1885 int guestRc; ProcessWaitResult_T waitResult;
1886 int vrc = waitFor(aWaitFlags, aTimeoutMS, waitResult, &guestRc);
1887 if (RT_SUCCESS(vrc))
1888 {
1889 *aReason = waitResult;
1890 }
1891 else
1892 {
1893 switch (vrc)
1894 {
1895 case VERR_GSTCTL_GUEST_ERROR:
1896 hr = GuestProcess::setErrorExternal(this, guestRc);
1897 break;
1898
1899 case VERR_TIMEOUT:
1900 *aReason = ProcessWaitResult_Timeout;
1901 break;
1902
1903 default:
1904 hr = setError(VBOX_E_IPRT_ERROR,
1905 tr("Waiting for process \"%s\" (PID %RU32) failed: %Rrc"),
1906 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1907 break;
1908 }
1909 }
1910
1911 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1912 return hr;
1913#endif /* VBOX_WITH_GUEST_CONTROL */
1914}
1915
1916STDMETHODIMP GuestProcess::WaitForArray(ComSafeArrayIn(ProcessWaitForFlag_T, aFlags), ULONG aTimeoutMS, ProcessWaitResult_T *aReason)
1917{
1918#ifndef VBOX_WITH_GUEST_CONTROL
1919 ReturnComNotImplemented();
1920#else
1921 LogFlowThisFuncEnter();
1922
1923 CheckComArgOutPointerValid(aReason);
1924
1925 AutoCaller autoCaller(this);
1926 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1927
1928 /*
1929 * Note: Do not hold any locks here while waiting!
1930 */
1931 uint32_t fWaitFor = ProcessWaitForFlag_None;
1932 com::SafeArray<ProcessWaitForFlag_T> flags(ComSafeArrayInArg(aFlags));
1933 for (size_t i = 0; i < flags.size(); i++)
1934 fWaitFor |= flags[i];
1935
1936 return WaitFor(fWaitFor, aTimeoutMS, aReason);
1937#endif /* VBOX_WITH_GUEST_CONTROL */
1938}
1939
1940STDMETHODIMP GuestProcess::Write(ULONG aHandle, ULONG aFlags,
1941 ComSafeArrayIn(BYTE, aData), ULONG aTimeoutMS, ULONG *aWritten)
1942{
1943#ifndef VBOX_WITH_GUEST_CONTROL
1944 ReturnComNotImplemented();
1945#else
1946 LogFlowThisFuncEnter();
1947
1948 CheckComArgOutPointerValid(aWritten);
1949
1950 AutoCaller autoCaller(this);
1951 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1952
1953 com::SafeArray<BYTE> data(ComSafeArrayInArg(aData));
1954
1955 HRESULT hr = S_OK;
1956
1957 uint32_t cbWritten; int guestRc;
1958 int vrc = writeData(aHandle, aFlags, data.raw(), data.size(), aTimeoutMS, &cbWritten, &guestRc);
1959 if (RT_FAILURE(vrc))
1960 {
1961 switch (vrc)
1962 {
1963 case VERR_GSTCTL_GUEST_ERROR:
1964 hr = GuestProcess::setErrorExternal(this, guestRc);
1965 break;
1966
1967 default:
1968 hr = setError(VBOX_E_IPRT_ERROR,
1969 tr("Writing to process \"%s\" (PID %RU32) failed: %Rrc"),
1970 mData.mProcess.mCommand.c_str(), mData.mPID, vrc);
1971 break;
1972 }
1973 }
1974
1975 LogFlowThisFunc(("rc=%Rrc, aWritten=%RU32\n", vrc, cbWritten));
1976
1977 *aWritten = (ULONG)cbWritten;
1978
1979 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
1980 return hr;
1981#endif /* VBOX_WITH_GUEST_CONTROL */
1982}
1983
1984STDMETHODIMP GuestProcess::WriteArray(ULONG aHandle, ComSafeArrayIn(ProcessInputFlag_T, aFlags),
1985 ComSafeArrayIn(BYTE, aData), ULONG aTimeoutMS, ULONG *aWritten)
1986{
1987#ifndef VBOX_WITH_GUEST_CONTROL
1988 ReturnComNotImplemented();
1989#else
1990 LogFlowThisFuncEnter();
1991
1992 CheckComArgOutPointerValid(aWritten);
1993
1994 AutoCaller autoCaller(this);
1995 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1996
1997 /*
1998 * Note: Do not hold any locks here while writing!
1999 */
2000 ULONG fWrite = ProcessInputFlag_None;
2001 com::SafeArray<ProcessInputFlag_T> flags(ComSafeArrayInArg(aFlags));
2002 for (size_t i = 0; i < flags.size(); i++)
2003 fWrite |= flags[i];
2004
2005 return Write(aHandle, fWrite, ComSafeArrayInArg(aData), aTimeoutMS, aWritten);
2006#endif /* VBOX_WITH_GUEST_CONTROL */
2007}
2008
2009///////////////////////////////////////////////////////////////////////////////
2010
2011GuestProcessTool::GuestProcessTool(void)
2012 : pSession(NULL)
2013{
2014}
2015
2016GuestProcessTool::~GuestProcessTool(void)
2017{
2018 Terminate(30 * 1000, NULL /* pGuestRc */);
2019}
2020
2021int GuestProcessTool::Init(GuestSession *pGuestSession, const GuestProcessStartupInfo &startupInfo,
2022 bool fAsync, int *pGuestRc)
2023{
2024 LogFlowThisFunc(("pGuestSession=%p, szCmd=%s, fAsync=%RTbool\n",
2025 pGuestSession, startupInfo.mCommand.c_str(), fAsync));
2026
2027 AssertPtrReturn(pGuestSession, VERR_INVALID_POINTER);
2028
2029 pSession = pGuestSession;
2030 mStartupInfo = startupInfo;
2031
2032 /* Make sure the process is hidden. */
2033 mStartupInfo.mFlags |= ProcessCreateFlag_Hidden;
2034
2035 int vrc = pSession->processCreateExInteral(mStartupInfo, pProcess);
2036 if (RT_SUCCESS(vrc))
2037 vrc = fAsync ? pProcess->startProcessAsync() : pProcess->startProcess(30 * 1000 /* 30s timeout */,
2038 pGuestRc);
2039
2040 if ( RT_SUCCESS(vrc)
2041 && !fAsync
2042 && ( pGuestRc
2043 && RT_FAILURE(*pGuestRc)
2044 )
2045 )
2046 {
2047 vrc = VERR_GSTCTL_GUEST_ERROR;
2048 }
2049
2050 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
2051 return vrc;
2052}
2053
2054int GuestProcessTool::GetCurrentBlock(uint32_t uHandle, GuestProcessStreamBlock &strmBlock)
2055{
2056 const GuestProcessStream *pStream = NULL;
2057 if (uHandle == OUTPUT_HANDLE_ID_STDOUT)
2058 pStream = &mStdOut;
2059 else if (uHandle == OUTPUT_HANDLE_ID_STDERR)
2060 pStream = &mStdErr;
2061
2062 if (!pStream)
2063 return VERR_INVALID_PARAMETER;
2064
2065 int vrc;
2066 do
2067 {
2068 /* Try parsing the data to see if the current block is complete. */
2069 vrc = mStdOut.ParseBlock(strmBlock);
2070 if (strmBlock.GetCount())
2071 break;
2072 } while (RT_SUCCESS(vrc));
2073
2074 LogFlowThisFunc(("rc=%Rrc, %RU64 pairs\n",
2075 vrc, strmBlock.GetCount()));
2076 return vrc;
2077}
2078
2079bool GuestProcessTool::IsRunning(void)
2080{
2081 AssertReturn(!pProcess.isNull(), true);
2082
2083 ProcessStatus_T procStatus = ProcessStatus_Undefined;
2084 HRESULT hr = pProcess->COMGETTER(Status(&procStatus));
2085 Assert(SUCCEEDED(hr));
2086
2087 if ( procStatus != ProcessStatus_Started
2088 && procStatus != ProcessStatus_Paused
2089 && procStatus != ProcessStatus_Terminating)
2090 {
2091 return false;
2092 }
2093
2094 return true;
2095}
2096
2097int GuestProcessTool::TerminatedOk(LONG *pExitCode)
2098{
2099 Assert(!pProcess.isNull());
2100 /* pExitCode is optional. */
2101
2102 if (!IsRunning())
2103 {
2104 LONG exitCode;
2105 HRESULT hr = pProcess->COMGETTER(ExitCode(&exitCode));
2106 Assert(SUCCEEDED(hr));
2107
2108 if (pExitCode)
2109 *pExitCode = exitCode;
2110
2111 if (exitCode != 0)
2112 return VERR_NOT_EQUAL; /** @todo Special guest control rc needed! */
2113 return VINF_SUCCESS;
2114 }
2115
2116 return VERR_INVALID_STATE; /** @todo Special guest control rc needed! */
2117}
2118
2119int GuestProcessTool::Wait(uint32_t fFlags, int *pGuestRc)
2120{
2121 return WaitEx(fFlags, NULL /* pStreamBlock */, pGuestRc);
2122}
2123
2124int GuestProcessTool::WaitEx(uint32_t fFlags, GuestProcessStreamBlock *pStreamBlock, int *pGuestRc)
2125{
2126 LogFlowThisFunc(("pSession=%p, fFlags=0x%x, pStreamBlock=%p, pGuestRc=%p\n",
2127 pSession, fFlags, pStreamBlock, pGuestRc));
2128
2129 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2130 Assert(!pProcess.isNull());
2131 /* Other parameters are optional. */
2132
2133 /* Can we parse the next block without waiting? */
2134 int vrc;
2135 if (fFlags & GUESTPROCESSTOOL_FLAG_STDOUT_BLOCK)
2136 {
2137 AssertPtr(pStreamBlock);
2138 vrc = GetCurrentBlock(OUTPUT_HANDLE_ID_STDOUT, *pStreamBlock);
2139 if (RT_SUCCESS(vrc))
2140 return vrc;
2141 /* else do the the waiting below. */
2142 }
2143
2144 /* Do the waiting. */
2145 uint32_t fWaitFlags = ProcessWaitForFlag_Terminate;
2146 if (mStartupInfo.mFlags & ProcessCreateFlag_WaitForStdOut)
2147 fWaitFlags |= ProcessWaitForFlag_StdOut;
2148 if (mStartupInfo.mFlags & ProcessCreateFlag_WaitForStdErr)
2149 fWaitFlags |= ProcessWaitForFlag_StdErr;
2150
2151 LogFlowThisFunc(("waitFlags=0x%x\n", fWaitFlags));
2152
2153 /** @todo Decrease timeout while running. */
2154 uint32_t uTimeoutMS = mStartupInfo.mTimeoutMS;
2155
2156 int guestRc;
2157 bool fDone = false;
2158
2159 BYTE byBuf[_64K];
2160 uint32_t cbRead;
2161
2162 bool fHandleStdOut = false;
2163 bool fHandleStdErr = false;
2164
2165 ProcessWaitResult_T waitRes;
2166 do
2167 {
2168 vrc = pProcess->waitFor(fWaitFlags,
2169 uTimeoutMS, waitRes, &guestRc);
2170 if (RT_FAILURE(vrc))
2171 break;
2172
2173 switch (waitRes)
2174 {
2175 case ProcessWaitResult_StdIn:
2176 vrc = VERR_NOT_IMPLEMENTED;
2177 break;
2178
2179 case ProcessWaitResult_StdOut:
2180 fHandleStdOut = true;
2181 break;
2182
2183 case ProcessWaitResult_StdErr:
2184 fHandleStdErr = true;
2185 break;
2186
2187 case ProcessWaitResult_WaitFlagNotSupported:
2188 if (fWaitFlags & ProcessWaitForFlag_StdOut)
2189 fHandleStdOut = true;
2190 if (fWaitFlags & ProcessWaitForFlag_StdErr)
2191 fHandleStdErr = true;
2192 /* Since waiting for stdout / stderr is not supported by the guest,
2193 * wait a bit to not hog the CPU too much when polling for data. */
2194 RTThreadSleep(1); /* Optional, don't check rc. */
2195 break;
2196
2197 case ProcessWaitResult_Error:
2198 vrc = VERR_GSTCTL_GUEST_ERROR;
2199 break;
2200
2201 case ProcessWaitResult_Terminate:
2202 fDone = true;
2203 break;
2204
2205 case ProcessWaitResult_Timeout:
2206 vrc = VERR_TIMEOUT;
2207 break;
2208
2209 case ProcessWaitResult_Start:
2210 case ProcessWaitResult_Status:
2211 /* Not used here, just skip. */
2212 break;
2213
2214 default:
2215 AssertReleaseMsgFailed(("Unhandled process wait result %ld\n", waitRes));
2216 break;
2217 }
2218
2219 if (fHandleStdOut)
2220 {
2221 cbRead = 0;
2222 vrc = pProcess->readData(OUTPUT_HANDLE_ID_STDOUT, sizeof(byBuf),
2223 uTimeoutMS, byBuf, sizeof(byBuf),
2224 &cbRead, &guestRc);
2225 if (RT_FAILURE(vrc))
2226 break;
2227
2228 if (cbRead)
2229 {
2230 LogFlowThisFunc(("Received %RU32 bytes from stdout\n", cbRead));
2231 vrc = mStdOut.AddData(byBuf, cbRead);
2232
2233 if ( RT_SUCCESS(vrc)
2234 && (fFlags & GUESTPROCESSTOOL_FLAG_STDOUT_BLOCK))
2235 {
2236 AssertPtr(pStreamBlock);
2237 vrc = GetCurrentBlock(OUTPUT_HANDLE_ID_STDOUT, *pStreamBlock);
2238 if (RT_SUCCESS(vrc))
2239 fDone = true;
2240 }
2241 }
2242
2243 fHandleStdOut = false;
2244 }
2245
2246 if (fHandleStdErr)
2247 {
2248 cbRead = 0;
2249 vrc = pProcess->readData(OUTPUT_HANDLE_ID_STDERR, sizeof(byBuf),
2250 uTimeoutMS, byBuf, sizeof(byBuf),
2251 &cbRead, &guestRc);
2252 if (RT_FAILURE(vrc))
2253 break;
2254
2255 if (cbRead)
2256 {
2257 LogFlowThisFunc(("Received %RU32 bytes from stderr\n", cbRead));
2258 vrc = mStdErr.AddData(byBuf, cbRead);
2259 }
2260
2261 fHandleStdErr = false;
2262 }
2263
2264 } while (!fDone && RT_SUCCESS(vrc));
2265
2266 LogFlowThisFunc(("Loop ended with rc=%Rrc, guestRc=%Rrc, waitRes=%ld\n",
2267 vrc, guestRc, waitRes));
2268 if (pGuestRc)
2269 *pGuestRc = guestRc;
2270
2271 LogFlowThisFunc(("Returning rc=%Rrc\n", vrc));
2272 return vrc;
2273}
2274
2275int GuestProcessTool::Terminate(uint32_t uTimeoutMS, int *pGuestRc)
2276{
2277 LogFlowThisFuncEnter();
2278
2279 int rc = VINF_SUCCESS;
2280 if (!pProcess.isNull())
2281 {
2282 rc = pProcess->terminateProcess(uTimeoutMS, pGuestRc);
2283
2284 Assert(pSession);
2285 int rc2 = pSession->processRemoveFromList(pProcess);
2286 AssertRC(rc2);
2287
2288 pProcess.setNull();
2289 }
2290 else
2291 rc = VERR_NOT_FOUND;
2292
2293 LogFlowFuncLeaveRC(rc);
2294 return rc;
2295}
2296
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