VirtualBox

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

最後變更 在這個檔案從58521是 58521,由 vboxsync 提交於 9 年 前

pr7179. GuestSession, GuestProcess, GuestControl classes have been modified.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette