VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/win/svcmain.cpp@ 76900

Last change on this file since 76900 was 76592, checked in by vboxsync, 6 years ago

Main: Don't use Logging.h.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.5 KB
Line 
1/* $Id: svcmain.cpp 76592 2019-01-01 20:13:07Z vboxsync $ */
2/** @file
3 * SVCMAIN - COM out-of-proc server main entry
4 */
5
6/*
7 * Copyright (C) 2004-2019 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/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_MAIN_VBOXSVC
23#include <iprt/win/windows.h>
24#ifdef DEBUG_bird
25# include <RpcAsync.h>
26#endif
27
28#include "VBox/com/defs.h"
29#include "VBox/com/com.h"
30#include "VBox/com/VirtualBox.h"
31
32#include "VirtualBoxImpl.h"
33#include "LoggingNew.h"
34
35#include "svchlp.h"
36
37#include <iprt/errcore.h>
38#include <iprt/buildconfig.h>
39#include <iprt/initterm.h>
40#include <iprt/string.h>
41#include <iprt/path.h>
42#include <iprt/getopt.h>
43#include <iprt/message.h>
44#include <iprt/asm.h>
45
46
47/*********************************************************************************************************************************
48* Defined Constants And Macros *
49*********************************************************************************************************************************/
50#define MAIN_WND_CLASS L"VirtualBox Interface"
51
52
53/*********************************************************************************************************************************
54* Structures and Typedefs *
55*********************************************************************************************************************************/
56class CExeModule : public ATL::CComModule
57{
58public:
59 LONG Unlock();
60 DWORD dwThreadID;
61 HANDLE hEventShutdown;
62 void MonitorShutdown();
63 bool StartMonitor();
64 bool HasActiveConnection();
65 bool bActivity;
66 static bool isIdleLockCount(LONG cLocks);
67};
68
69
70/*********************************************************************************************************************************
71* Global Variables *
72*********************************************************************************************************************************/
73BEGIN_OBJECT_MAP(ObjectMap)
74 OBJECT_ENTRY(CLSID_VirtualBox, VirtualBox)
75END_OBJECT_MAP()
76
77CExeModule *g_pModule = NULL;
78HWND g_hMainWindow = NULL;
79HINSTANCE g_hInstance = NULL;
80#ifdef VBOX_WITH_SDS
81/** This is set if we're connected to SDS.
82 *
83 * It means that we should discount a server lock that it is holding when
84 * deciding whether we're idle or not.
85 *
86 * Also, when set we deregister with SDS during class factory destruction. We
87 * exploit this to prevent attempts to deregister during or after COM shutdown.
88 */
89bool g_fRegisteredWithVBoxSDS = false;
90#endif
91
92/* Normal timeout usually used in Shutdown Monitor */
93const DWORD dwNormalTimeout = 5000;
94volatile uint32_t dwTimeOut = dwNormalTimeout; /* time for EXE to be idle before shutting down. Can be decreased at system shutdown phase. */
95
96
97
98/** Passed to CreateThread to monitor the shutdown event. */
99static DWORD WINAPI MonitorProc(void *pv)
100{
101 CExeModule *p = (CExeModule *)pv;
102 p->MonitorShutdown();
103 return 0;
104}
105
106LONG CExeModule::Unlock()
107{
108 LONG cLocks = ATL::CComModule::Unlock();
109 if (isIdleLockCount(cLocks))
110 {
111 bActivity = true;
112 SetEvent(hEventShutdown); /* tell monitor that we transitioned to zero */
113 }
114 return cLocks;
115}
116
117bool CExeModule::HasActiveConnection()
118{
119 return bActivity || !isIdleLockCount(GetLockCount());
120}
121
122/**
123 * Checks if @a cLocks signifies an IDLE server lock load.
124 *
125 * This takes VBoxSDS into account (i.e. ignores it).
126 */
127/*static*/ bool CExeModule::isIdleLockCount(LONG cLocks)
128{
129#ifdef VBOX_WITH_SDS
130 if (g_fRegisteredWithVBoxSDS)
131 return cLocks <= 1;
132#endif
133 return cLocks <= 0;
134}
135
136/* Monitors the shutdown event */
137void CExeModule::MonitorShutdown()
138{
139 while (1)
140 {
141 WaitForSingleObject(hEventShutdown, INFINITE);
142 DWORD dwWait;
143 do
144 {
145 bActivity = false;
146 dwWait = WaitForSingleObject(hEventShutdown, dwTimeOut);
147 } while (dwWait == WAIT_OBJECT_0);
148 /* timed out */
149 if (!HasActiveConnection()) /* if no activity let's really bail */
150 {
151 /* Disable log rotation at this point, worst case a log file
152 * becomes slightly bigger than it should. Avoids quirks with
153 * log rotation: there might be another API service process
154 * running at this point which would rotate the logs concurrently,
155 * creating a mess. */
156 PRTLOGGER pReleaseLogger = RTLogRelGetDefaultInstance();
157 if (pReleaseLogger)
158 {
159 char szDest[1024];
160 int rc = RTLogGetDestinations(pReleaseLogger, szDest, sizeof(szDest));
161 if (RT_SUCCESS(rc))
162 {
163 rc = RTStrCat(szDest, sizeof(szDest), " nohistory");
164 if (RT_SUCCESS(rc))
165 {
166 rc = RTLogDestinations(pReleaseLogger, szDest);
167 AssertRC(rc);
168 }
169 }
170 }
171#if _WIN32_WINNT >= 0x0400
172 CoSuspendClassObjects();
173 if (!HasActiveConnection())
174#endif
175 break;
176 }
177 }
178 CloseHandle(hEventShutdown);
179 PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
180}
181
182bool CExeModule::StartMonitor()
183{
184 hEventShutdown = CreateEvent(NULL, false, false, NULL);
185 if (hEventShutdown == NULL)
186 return false;
187 DWORD dwThreadID;
188 HANDLE h = CreateThread(NULL, 0, MonitorProc, this, 0, &dwThreadID);
189 return (h != NULL);
190}
191
192
193#ifdef VBOX_WITH_SDS
194
195class VBoxSVCRegistration;
196
197/**
198 * Custom class factory for the VirtualBox singleton.
199 *
200 * The implementation of CreateInstance is found in win/svcmain.cpp.
201 */
202class VirtualBoxClassFactory : public ATL::CComClassFactory
203{
204private:
205 /** Tri state: 0=uninitialized or initializing; 1=success; -1=failure.
206 * This will be updated after both m_hrcCreate and m_pObj have been set. */
207 volatile int32_t m_iState;
208 /** The result of the instantiation attempt. */
209 HRESULT m_hrcCreate;
210 /** The IUnknown of the VirtualBox object/interface we're working with. */
211 IUnknown *m_pObj;
212 /** Pointer to the IVBoxSVCRegistration implementation that VBoxSDS works with. */
213 VBoxSVCRegistration *m_pVBoxSVC;
214 /** The VBoxSDS interface. */
215 ComPtr<IVirtualBoxSDS> m_ptrVirtualBoxSDS;
216
217public:
218 VirtualBoxClassFactory() : m_iState(0), m_hrcCreate(S_OK), m_pObj(NULL), m_pVBoxSVC(NULL)
219 { }
220
221 virtual ~VirtualBoxClassFactory()
222 {
223 if (m_pObj)
224 {
225 m_pObj->Release();
226 m_pObj = NULL;
227 }
228
229 /* We usually get here during g_pModule->Term() via CoRevokeClassObjec, so COM
230 probably working well enough to talk to SDS when we get here. */
231 if (g_fRegisteredWithVBoxSDS)
232 i_deregisterWithSds();
233 }
234
235 // IClassFactory
236 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void **ppvObj);
237
238 /** Worker for VBoxSVCRegistration::getVirtualBox. */
239 HRESULT i_getVirtualBox(IUnknown **ppResult);
240
241private:
242 HRESULT VirtualBoxClassFactory::i_registerWithSds(IUnknown **ppOtherVirtualBox);
243 void VirtualBoxClassFactory::i_deregisterWithSds(void);
244
245 friend VBoxSVCRegistration;
246};
247
248
249/**
250 * The VBoxSVC class is handed to VBoxSDS so it can call us back and ask for the
251 * VirtualBox object when the next VBoxSVC for this user registers itself.
252 */
253class VBoxSVCRegistration : public IVBoxSVCRegistration
254{
255private:
256 /** Number of references. */
257 uint32_t volatile m_cRefs;
258
259public:
260 /** Pointer to the factory. */
261 VirtualBoxClassFactory *m_pFactory;
262
263public:
264 VBoxSVCRegistration(VirtualBoxClassFactory *pFactory)
265 : m_cRefs(1), m_pFactory(pFactory)
266 { }
267 virtual ~VBoxSVCRegistration()
268 {
269 if (m_pFactory)
270 {
271 if (m_pFactory->m_pVBoxSVC)
272 m_pFactory->m_pVBoxSVC = NULL;
273 m_pFactory = NULL;
274 }
275 }
276 RTMEMEF_NEW_AND_DELETE_OPERATORS();
277
278 // IUnknown
279 STDMETHOD(QueryInterface)(REFIID riid, void **ppvObject)
280 {
281 if (riid == __uuidof(IUnknown))
282 *ppvObject = (void *)(IUnknown *)this;
283 else if (riid == __uuidof(IVBoxSVCRegistration))
284 *ppvObject = (void *)(IVBoxSVCRegistration *)this;
285 else
286 {
287 return E_NOINTERFACE;
288 }
289 AddRef();
290 return S_OK;
291
292 }
293
294 STDMETHOD_(ULONG,AddRef)(void)
295 {
296 uint32_t cRefs = ASMAtomicIncU32(&m_cRefs);
297 return cRefs;
298 }
299
300 STDMETHOD_(ULONG,Release)(void)
301 {
302 uint32_t cRefs = ASMAtomicDecU32(&m_cRefs);
303 if (cRefs == 0)
304 delete this;
305 return cRefs;
306 }
307
308 // IVBoxSVCRegistration
309 STDMETHOD(GetVirtualBox)(IUnknown **ppResult)
310 {
311 if (m_pFactory)
312 return m_pFactory->i_getVirtualBox(ppResult);
313 return E_FAIL;
314 }
315};
316
317
318HRESULT VirtualBoxClassFactory::i_registerWithSds(IUnknown **ppOtherVirtualBox)
319{
320# ifdef DEBUG_bird
321 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
322 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
323 LogRel(("i_registerWithSds: RpcServerInqCallAttributesW -> %#x ClientPID=%#x IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid\n",
324 rcRpc, CallAttribs.ClientPID, CallAttribs.IsClientLocal, CallAttribs.ProtocolSequence, CallAttribs.CallStatus,
325 CallAttribs.CallType, CallAttribs.OpNum, &CallAttribs.InterfaceUuid));
326# endif
327
328 /*
329 * Connect to VBoxSDS.
330 */
331 HRESULT hrc = CoCreateInstance(CLSID_VirtualBoxSDS, NULL, CLSCTX_LOCAL_SERVER, IID_IVirtualBoxSDS,
332 (void **)m_ptrVirtualBoxSDS.asOutParam());
333 if (SUCCEEDED(hrc))
334 {
335 /*
336 * Create VBoxSVCRegistration object and hand that to VBoxSDS.
337 */
338 m_pVBoxSVC = new VBoxSVCRegistration(this);
339 hrc = m_ptrVirtualBoxSDS->RegisterVBoxSVC(m_pVBoxSVC, GetCurrentProcessId(), ppOtherVirtualBox);
340 if (SUCCEEDED(hrc))
341 {
342 g_fRegisteredWithVBoxSDS = !*ppOtherVirtualBox;
343 return hrc;
344 }
345 m_pVBoxSVC->Release();
346 }
347 m_ptrVirtualBoxSDS.setNull();
348 m_pVBoxSVC = NULL;
349 *ppOtherVirtualBox = NULL;
350 return hrc;
351}
352
353
354void VirtualBoxClassFactory::i_deregisterWithSds(void)
355{
356 Log(("VirtualBoxClassFactory::i_deregisterWithSds\n"));
357
358 if (m_ptrVirtualBoxSDS.isNotNull())
359 {
360 if (m_pVBoxSVC)
361 {
362 HRESULT hrc = m_ptrVirtualBoxSDS->DeregisterVBoxSVC(m_pVBoxSVC, GetCurrentProcessId());
363 NOREF(hrc);
364 }
365 m_ptrVirtualBoxSDS.setNull();
366 g_fRegisteredWithVBoxSDS = false;
367 }
368 if (m_pVBoxSVC)
369 {
370 m_pVBoxSVC->m_pFactory = NULL;
371 m_pVBoxSVC->Release();
372 m_pVBoxSVC = NULL;
373 }
374}
375
376
377HRESULT VirtualBoxClassFactory::i_getVirtualBox(IUnknown **ppResult)
378{
379# ifdef DEBUG_bird
380 RPC_CALL_ATTRIBUTES_V2_W CallAttribs = { RPC_CALL_ATTRIBUTES_VERSION, RPC_QUERY_CLIENT_PID | RPC_QUERY_IS_CLIENT_LOCAL };
381 RPC_STATUS rcRpc = RpcServerInqCallAttributesW(NULL, &CallAttribs);
382 LogRel(("i_getVirtualBox: RpcServerInqCallAttributesW -> %#x ClientPID=%#x IsClientLocal=%d ProtocolSequence=%#x CallStatus=%#x CallType=%#x OpNum=%#x InterfaceUuid=%RTuuid\n",
383 rcRpc, CallAttribs.ClientPID, CallAttribs.IsClientLocal, CallAttribs.ProtocolSequence, CallAttribs.CallStatus,
384 CallAttribs.CallType, CallAttribs.OpNum, &CallAttribs.InterfaceUuid));
385# endif
386 IUnknown *pObj = m_pObj;
387 if (pObj)
388 {
389 /** @todo Do we need to do something regarding server locking? Hopefully COM
390 * deals with that........... */
391 pObj->AddRef();
392 *ppResult = pObj;
393 Log(("VirtualBoxClassFactory::GetVirtualBox: S_OK - %p\n", pObj));
394 return S_OK;
395 }
396 *ppResult = NULL;
397 Log(("VirtualBoxClassFactory::GetVirtualBox: E_FAIL\n"));
398 return E_FAIL;
399}
400
401
402/**
403 * Custom instantiation of CComObjectCached.
404 *
405 * This catches certain QueryInterface callers for the purpose of watching for
406 * abnormal client process termination (@bugref{3300}).
407 *
408 * @todo just merge this into class VirtualBox VirtualBoxImpl.h
409 */
410class VirtualBoxObjectCached : public VirtualBox
411{
412public:
413 VirtualBoxObjectCached(void * = NULL)
414 : VirtualBox()
415 {
416 }
417
418 virtual ~VirtualBoxObjectCached()
419 {
420 m_iRef = LONG_MIN / 2; /* Catch refcount screwups by setting refcount something insane. */
421 FinalRelease();
422 }
423
424 /** @name IUnknown implementation for VirtualBox
425 * @{ */
426
427 STDMETHOD_(ULONG, AddRef)() throw()
428 {
429 ULONG cRefs = InternalAddRef();
430 if (cRefs == 2)
431 {
432 AssertMsg(ATL::_pAtlModule, ("ATL: referring to ATL module without having one declared in this linking namespace\n"));
433 ATL::_pAtlModule->Lock();
434 }
435 return cRefs;
436 }
437
438 STDMETHOD_(ULONG, Release)() throw()
439 {
440 ULONG cRefs = InternalRelease();
441 if (cRefs == 0)
442 delete this;
443 else if (cRefs == 1)
444 {
445 AssertMsg(ATL::_pAtlModule, ("ATL: referring to ATL module without having one declared in this linking namespace\n"));
446 ATL::_pAtlModule->Unlock();
447 }
448 return cRefs;
449 }
450
451 STDMETHOD(QueryInterface)(REFIID iid, void **ppvObj) throw()
452 {
453 HRESULT hrc = _InternalQueryInterface(iid, ppvObj);
454#ifdef VBOXSVC_WITH_CLIENT_WATCHER
455 i_logCaller("QueryInterface %RTuuid -> %Rhrc %p", &iid, hrc, *ppvObj);
456#endif
457 return hrc;
458 }
459
460 /** @} */
461
462 static HRESULT WINAPI CreateInstance(VirtualBoxObjectCached **ppObj) throw()
463 {
464 AssertReturn(ppObj, E_POINTER);
465 *ppObj = NULL;
466
467 HRESULT hrc = E_OUTOFMEMORY;
468 VirtualBoxObjectCached *p = new (std::nothrow) VirtualBoxObjectCached();
469 if (p)
470 {
471 p->SetVoid(NULL);
472 p->InternalFinalConstructAddRef();
473 hrc = p->_AtlInitialConstruct();
474 if (SUCCEEDED(hrc))
475 hrc = p->FinalConstruct();
476 p->InternalFinalConstructRelease();
477 if (FAILED(hrc))
478 delete p;
479 else
480 *ppObj = p;
481 }
482 return hrc;
483 }
484};
485
486
487/**
488 * Custom class factory impl for the VirtualBox singleton.
489 *
490 * This will consult with VBoxSDS on whether this VBoxSVC instance should
491 * provide the actual VirtualBox instance or just forward the instance from
492 * some other SVC instance.
493 *
494 * @param pUnkOuter This must be NULL.
495 * @param riid Reference to the interface ID to provide.
496 * @param ppvObj Where to return the pointer to the riid instance.
497 *
498 * @return COM status code.
499 */
500STDMETHODIMP VirtualBoxClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, void **ppvObj)
501{
502# ifdef VBOXSVC_WITH_CLIENT_WATCHER
503 VirtualBox::i_logCaller("VirtualBoxClassFactory::CreateInstance: %RTuuid", riid);
504# endif
505 HRESULT hrc = E_POINTER;
506 if (ppvObj != NULL)
507 {
508 *ppvObj = NULL;
509 // no aggregation for singletons
510 AssertReturn(pUnkOuter == NULL, CLASS_E_NOAGGREGATION);
511
512 /*
513 * We must make sure there is only one instance around.
514 * So, we check without locking and then again after locking.
515 */
516 if (ASMAtomicReadS32(&m_iState) == 0)
517 {
518 Lock();
519 __try
520 {
521 if (ASMAtomicReadS32(&m_iState) == 0)
522 {
523 /*
524 * lock the module to indicate activity
525 * (necessary for the monitor shutdown thread to correctly
526 * terminate the module in case when CreateInstance() fails)
527 */
528 ATL::_pAtlModule->Lock();
529 __try
530 {
531 /*
532 * Now we need to connect to VBoxSDS to register ourselves.
533 */
534 IUnknown *pOtherVirtualBox = NULL;
535 m_hrcCreate = hrc = i_registerWithSds(&pOtherVirtualBox);
536 if (SUCCEEDED(hrc) && pOtherVirtualBox)
537 m_pObj = pOtherVirtualBox;
538 else if (SUCCEEDED(hrc))
539 {
540 ATL::_pAtlModule->Lock();
541 VirtualBoxObjectCached *p;
542 m_hrcCreate = hrc = VirtualBoxObjectCached::CreateInstance(&p);
543 if (SUCCEEDED(hrc))
544 {
545 m_hrcCreate = hrc = p->QueryInterface(IID_IUnknown, (void **)&m_pObj);
546 if (SUCCEEDED(hrc))
547 RTLogClearFileDelayFlag(RTLogRelGetDefaultInstance(), NULL);
548 else
549 {
550 delete p;
551 i_deregisterWithSds();
552 m_pObj = NULL;
553 }
554 }
555 }
556 ASMAtomicWriteS32(&m_iState, SUCCEEDED(hrc) ? 1 : -1);
557 }
558 __finally
559 {
560 ATL::_pAtlModule->Unlock();
561 }
562 }
563 }
564 __finally
565 {
566 if (ASMAtomicReadS32(&m_iState) == 0)
567 {
568 ASMAtomicWriteS32(&m_iState, -1);
569 if (SUCCEEDED(m_hrcCreate))
570 m_hrcCreate = E_FAIL;
571 }
572 Unlock();
573 }
574 }
575
576 /*
577 * Query the requested interface from the IUnknown one we're keeping around.
578 */
579 if (m_hrcCreate == S_OK)
580 hrc = m_pObj->QueryInterface(riid, ppvObj);
581 else
582 hrc = m_hrcCreate;
583 }
584 return hrc;
585}
586
587#endif // VBOX_WITH_SDS
588
589
590/*
591* Wrapper for Win API function ShutdownBlockReasonCreate
592* This function defined starting from Vista only.
593*/
594static BOOL ShutdownBlockReasonCreateAPI(HWND hWnd, LPCWSTR pwszReason)
595{
596 BOOL fResult = FALSE;
597 typedef BOOL(WINAPI *PFNSHUTDOWNBLOCKREASONCREATE)(HWND hWnd, LPCWSTR pwszReason);
598
599 PFNSHUTDOWNBLOCKREASONCREATE pfn = (PFNSHUTDOWNBLOCKREASONCREATE)GetProcAddress(
600 GetModuleHandle(L"User32.dll"), "ShutdownBlockReasonCreate");
601 AssertPtr(pfn);
602 if (pfn)
603 fResult = pfn(hWnd, pwszReason);
604 return fResult;
605}
606
607/*
608* Wrapper for Win API function ShutdownBlockReasonDestroy
609* This function defined starting from Vista only.
610*/
611static BOOL ShutdownBlockReasonDestroyAPI(HWND hWnd)
612{
613 BOOL fResult = FALSE;
614 typedef BOOL(WINAPI *PFNSHUTDOWNBLOCKREASONDESTROY)(HWND hWnd);
615
616 PFNSHUTDOWNBLOCKREASONDESTROY pfn = (PFNSHUTDOWNBLOCKREASONDESTROY)GetProcAddress(
617 GetModuleHandle(L"User32.dll"), "ShutdownBlockReasonDestroy");
618 AssertPtr(pfn);
619 if (pfn)
620 fResult = pfn(hWnd);
621 return fResult;
622}
623
624static LRESULT CALLBACK WinMainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
625{
626 LRESULT rc = 0;
627 switch (msg)
628 {
629 case WM_QUERYENDSESSION:
630 {
631 if (g_pModule)
632 {
633 bool fActiveConnection = g_pModule->HasActiveConnection();
634 if (fActiveConnection)
635 {
636 /* place the VBoxSVC into system shutdown list */
637 ShutdownBlockReasonCreateAPI(hwnd, L"Has active connections.");
638 /* decrease a latency of MonitorShutdown loop */
639 ASMAtomicXchgU32(&dwTimeOut, 100);
640 Log(("VBoxSVCWinMain: WM_QUERYENDSESSION: VBoxSvc has active connections. bActivity = %d. Loc count = %d\n",
641 g_pModule->bActivity, g_pModule->GetLockCount()));
642 }
643 rc = !fActiveConnection;
644 }
645 else
646 AssertMsgFailed(("VBoxSVCWinMain: WM_QUERYENDSESSION: Error: g_pModule is NULL"));
647 break;
648 }
649 case WM_ENDSESSION:
650 {
651 /* Restore timeout of Monitor Shutdown if user canceled system shutdown */
652 if (wParam == FALSE)
653 {
654 ASMAtomicXchgU32(&dwTimeOut, dwNormalTimeout);
655 Log(("VBoxSVCWinMain: user canceled system shutdown.\n"));
656 }
657 break;
658 }
659 case WM_DESTROY:
660 {
661 ShutdownBlockReasonDestroyAPI(hwnd);
662 PostQuitMessage(0);
663 break;
664 }
665 default:
666 {
667 rc = DefWindowProc(hwnd, msg, wParam, lParam);
668 }
669 }
670 return rc;
671}
672
673static int CreateMainWindow()
674{
675 int rc = VINF_SUCCESS;
676 Assert(g_hMainWindow == NULL);
677
678 LogFlow(("CreateMainWindow\n"));
679
680 g_hInstance = (HINSTANCE)GetModuleHandle(NULL);
681
682 /* Register the Window Class. */
683 WNDCLASS wc;
684 RT_ZERO(wc);
685
686 wc.style = CS_NOCLOSE;
687 wc.lpfnWndProc = WinMainWndProc;
688 wc.hInstance = g_hInstance;
689 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
690 wc.lpszClassName = MAIN_WND_CLASS;
691
692 ATOM atomWindowClass = RegisterClass(&wc);
693 if (atomWindowClass == 0)
694 {
695 Log(("Failed to register main window class\n"));
696 rc = VERR_NOT_SUPPORTED;
697 }
698 else
699 {
700 /* Create the window. */
701 g_hMainWindow = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
702 MAIN_WND_CLASS, MAIN_WND_CLASS,
703 WS_POPUPWINDOW,
704 0, 0, 1, 1, NULL, NULL, g_hInstance, NULL);
705 if (g_hMainWindow == NULL)
706 {
707 Log(("Failed to create main window\n"));
708 rc = VERR_NOT_SUPPORTED;
709 }
710 else
711 {
712 SetWindowPos(g_hMainWindow, HWND_TOPMOST, -200, -200, 0, 0,
713 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
714
715 }
716 }
717 return 0;
718}
719
720
721static void DestroyMainWindow()
722{
723 Assert(g_hMainWindow != NULL);
724 Log(("SVCMain: DestroyMainWindow \n"));
725 if (g_hMainWindow != NULL)
726 {
727 DestroyWindow(g_hMainWindow);
728 g_hMainWindow = NULL;
729 if (g_hInstance != NULL)
730 {
731 UnregisterClass(MAIN_WND_CLASS, g_hInstance);
732 g_hInstance = NULL;
733 }
734 }
735}
736
737
738/** Special export that make VBoxProxyStub not register this process as one that
739 * VBoxSDS should be watching.
740 */
741extern "C" DECLEXPORT(void) VBOXCALL Is_VirtualBox_service_process_like_VBoxSDS_And_VBoxSDS(void)
742{
743 /* never called, just need to be here */
744}
745
746
747/////////////////////////////////////////////////////////////////////////////
748//
749int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int /*nShowCmd*/)
750{
751 int argc = __argc;
752 char **argv = __argv;
753
754 /*
755 * Need to parse the command line before initializing the VBox runtime so we can
756 * change to the user home directory before logs are being created.
757 */
758 for (int i = 1; i < argc; i++)
759 if ( (argv[i][0] == '/' || argv[i][0] == '-')
760 && stricmp(&argv[i][1], "embedding") == 0) /* ANSI */
761 {
762 /* %HOMEDRIVE%%HOMEPATH% */
763 wchar_t wszHome[RTPATH_MAX];
764 DWORD cEnv = GetEnvironmentVariable(L"HOMEDRIVE", &wszHome[0], RTPATH_MAX);
765 if (cEnv && cEnv < RTPATH_MAX)
766 {
767 DWORD cwc = cEnv; /* doesn't include NUL */
768 cEnv = GetEnvironmentVariable(L"HOMEPATH", &wszHome[cEnv], RTPATH_MAX - cwc);
769 if (cEnv && cEnv < RTPATH_MAX - cwc)
770 {
771 /* If this fails there is nothing we can do. Ignore. */
772 SetCurrentDirectory(wszHome);
773 }
774 }
775 }
776
777 /*
778 * Initialize the VBox runtime without loading
779 * the support driver.
780 */
781 RTR3InitExe(argc, &argv, 0);
782
783 static const RTGETOPTDEF s_aOptions[] =
784 {
785 { "--embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
786 { "-embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
787 { "/embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
788 { "--unregserver", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
789 { "-unregserver", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
790 { "/unregserver", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
791 { "--regserver", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
792 { "-regserver", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
793 { "/regserver", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
794 { "--reregserver", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
795 { "-reregserver", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
796 { "/reregserver", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
797 { "--helper", 'H', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
798 { "-helper", 'H', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
799 { "/helper", 'H', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
800 { "--logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
801 { "-logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
802 { "/logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
803 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
804 { "-logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
805 { "/logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
806 { "--logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
807 { "-logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
808 { "/logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
809 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
810 { "-loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
811 { "/loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
812 };
813
814 bool fRun = true;
815 bool fRegister = false;
816 bool fUnregister = false;
817 const char *pszPipeName = NULL;
818 const char *pszLogFile = NULL;
819 uint32_t cHistory = 10; // enable log rotation, 10 files
820 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
821 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
822
823 RTGETOPTSTATE GetOptState;
824 int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
825 AssertRC(vrc);
826
827 RTGETOPTUNION ValueUnion;
828 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
829 {
830 switch (vrc)
831 {
832 case 'e':
833 /* already handled above */
834 break;
835
836 case 'u':
837 fUnregister = true;
838 fRun = false;
839 break;
840
841 case 'r':
842 fRegister = true;
843 fRun = false;
844 break;
845
846 case 'f':
847 fUnregister = true;
848 fRegister = true;
849 fRun = false;
850 break;
851
852 case 'H':
853 pszPipeName = ValueUnion.psz;
854 if (!pszPipeName)
855 pszPipeName = "";
856 fRun = false;
857 break;
858
859 case 'F':
860 pszLogFile = ValueUnion.psz;
861 break;
862
863 case 'R':
864 cHistory = ValueUnion.u32;
865 break;
866
867 case 'S':
868 uHistoryFileSize = ValueUnion.u64;
869 break;
870
871 case 'I':
872 uHistoryFileTime = ValueUnion.u32;
873 break;
874
875 case 'h':
876 {
877 static const WCHAR s_wszText[] = L"Options:\n\n"
878 L"/RegServer:\tregister COM out-of-proc server\n"
879 L"/UnregServer:\tunregister COM out-of-proc server\n"
880 L"/ReregServer:\tunregister and register COM server\n"
881 L"no options:\trun the server";
882 static const WCHAR s_wszTitle[] = L"Usage";
883 fRun = false;
884 MessageBoxW(NULL, s_wszText, s_wszTitle, MB_OK);
885 return 0;
886 }
887
888 case 'V':
889 {
890 static const WCHAR s_wszTitle[] = L"Version";
891 char *pszText = NULL;
892 RTStrAPrintf(&pszText, "%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
893 PRTUTF16 pwszText = NULL;
894 RTStrToUtf16(pszText, &pwszText);
895 RTStrFree(pszText);
896 MessageBoxW(NULL, pwszText, s_wszTitle, MB_OK);
897 RTUtf16Free(pwszText);
898 fRun = false;
899 return 0;
900 }
901
902 default:
903 /** @todo this assumes that stderr is visible, which is not
904 * true for standard Windows applications. */
905 /* continue on command line errors... */
906 RTGetOptPrintError(vrc, &ValueUnion);
907 }
908 }
909
910 /* Only create the log file when running VBoxSVC normally, but not when
911 * registering/unregistering or calling the helper functionality. */
912 if (fRun)
913 {
914 /** @todo Merge this code with server.cpp (use Logging.cpp?). */
915 char szLogFile[RTPATH_MAX];
916 if (!pszLogFile || !*pszLogFile)
917 {
918 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
919 if (RT_SUCCESS(vrc))
920 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
921 if (RT_FAILURE(vrc))
922 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to construct release log filename, rc=%Rrc", vrc);
923 pszLogFile = szLogFile;
924 }
925
926 RTERRINFOSTATIC ErrInfo;
927 vrc = com::VBoxLogRelCreate("COM Server", pszLogFile,
928 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
929 VBOXSVC_LOG_DEFAULT, "VBOXSVC_RELEASE_LOG",
930#ifdef VBOX_WITH_SDS
931 RTLOGDEST_FILE | RTLOGDEST_F_DELAY_FILE,
932#else
933 RTLOGDEST_FILE,
934#endif
935 UINT32_MAX /* cMaxEntriesPerGroup */, cHistory, uHistoryFileTime, uHistoryFileSize,
936 RTErrInfoInitStatic(&ErrInfo));
937 if (RT_FAILURE(vrc))
938 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", ErrInfo.Core.pszMsg, vrc);
939 }
940
941 /* Set up a build identifier so that it can be seen from core dumps what
942 * exact build was used to produce the core. Same as in Console::i_powerUpThread(). */
943 static char saBuildID[48];
944 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
945 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
946
947 int nRet = 0;
948 HRESULT hRes = com::Initialize(false /*fGui*/, fRun /*fAutoRegUpdate*/);
949 AssertLogRelMsg(SUCCEEDED(hRes), ("SVCMAIN: init failed: %Rhrc\n", hRes));
950
951 g_pModule = new CExeModule();
952 if(g_pModule == NULL)
953 return RTMsgErrorExit(RTEXITCODE_FAILURE, "not enough memory to create ExeModule.");
954 g_pModule->Init(ObjectMap, hInstance, &LIBID_VirtualBox);
955 g_pModule->dwThreadID = GetCurrentThreadId();
956
957 if (!fRun)
958 {
959#ifndef VBOX_WITH_MIDL_PROXY_STUB /* VBoxProxyStub.dll does all the registration work. */
960 if (fUnregister)
961 {
962 g_pModule->UpdateRegistryFromResource(IDR_VIRTUALBOX, FALSE);
963 nRet = g_pModule->UnregisterServer(TRUE);
964 }
965 if (fRegister)
966 {
967 g_pModule->UpdateRegistryFromResource(IDR_VIRTUALBOX, TRUE);
968 nRet = g_pModule->RegisterServer(TRUE);
969 }
970#endif
971 if (pszPipeName)
972 {
973 Log(("SVCMAIN: Processing Helper request (cmdline=\"%s\")...\n", pszPipeName));
974
975 if (!*pszPipeName)
976 vrc = VERR_INVALID_PARAMETER;
977
978 if (RT_SUCCESS(vrc))
979 {
980 /* do the helper job */
981 SVCHlpServer server;
982 vrc = server.open(pszPipeName);
983 if (RT_SUCCESS(vrc))
984 vrc = server.run();
985 }
986 if (RT_FAILURE(vrc))
987 {
988 Log(("SVCMAIN: Failed to process Helper request (%Rrc).\n", vrc));
989 nRet = 1;
990 }
991 }
992 }
993 else
994 {
995 g_pModule->StartMonitor();
996#if _WIN32_WINNT >= 0x0400
997 hRes = g_pModule->RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
998 _ASSERTE(SUCCEEDED(hRes));
999 hRes = CoResumeClassObjects();
1000#else
1001 hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
1002#endif
1003 _ASSERTE(SUCCEEDED(hRes));
1004
1005 if (RT_SUCCESS(CreateMainWindow()))
1006 Log(("SVCMain: Main window succesfully created\n"));
1007 else
1008 Log(("SVCMain: Failed to create main window\n"));
1009
1010 MSG msg;
1011 while (GetMessage(&msg, 0, 0, 0) > 0)
1012 {
1013 DispatchMessage(&msg);
1014 TranslateMessage(&msg);
1015 }
1016
1017 DestroyMainWindow();
1018
1019 g_pModule->RevokeClassObjects();
1020 }
1021
1022 g_pModule->Term();
1023
1024#ifdef VBOX_WITH_SDS
1025 g_fRegisteredWithVBoxSDS = false; /* Don't trust COM LPC to work right from now on. */
1026#endif
1027 com::Shutdown();
1028
1029 if(g_pModule)
1030 delete g_pModule;
1031 g_pModule = NULL;
1032
1033 Log(("SVCMAIN: Returning, COM server process ends.\n"));
1034 return nRet;
1035}
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