VirtualBox

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

Last change on this file since 84373 was 84261, checked in by vboxsync, 5 years ago

Guest Control: Partly reverted r137851 and r137880 to remove the paranoia checks whether the cmd/args/env lengths are supported; the GA should handle that in turn as it was decided. ​​​bugref:9320

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