VirtualBox

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

Last change on this file since 55540 was 55540, checked in by vboxsync, 10 years ago

Tab.

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