VirtualBox

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

Last change on this file since 69734 was 69734, checked in by vboxsync, 7 years ago

Main: SDS plan B proof of concept.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.9 KB
Line 
1/* $Id: svcmain.cpp 69734 2017-11-18 02:06:23Z vboxsync $ */
2/** @file
3 * SVCMAIN - COM out-of-proc server main entry
4 */
5
6/*
7 * Copyright (C) 2004-2017 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 RTMEM_WRAP_SOME_NEW_AND_DELETE_TO_EF // DONT COMMIT
23#define RTMEM_WRAP_TO_EF_APIS
24#include <iprt/mem.h>
25#include <iprt/win/windows.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <tchar.h>
29
30#include "VBox/com/defs.h"
31#include "VBox/com/com.h"
32#include "VBox/com/VirtualBox.h"
33
34#include "VirtualBoxImpl.h"
35//#ifdef VBOX_WITH_SDS_PLAN_B
36//# include "VBoxSVCWrap.h"
37//#endif
38#include "Logging.h"
39
40#include "svchlp.h"
41
42#include <VBox/err.h>
43#include <iprt/buildconfig.h>
44#include <iprt/initterm.h>
45#include <iprt/string.h>
46#include <iprt/uni.h>
47#include <iprt/path.h>
48#include <iprt/getopt.h>
49#include <iprt/message.h>
50#include <iprt/asm.h>
51
52
53/*********************************************************************************************************************************
54* Defined Constants And Macros *
55*********************************************************************************************************************************/
56#define MAIN_WND_CLASS L"VirtualBox Interface"
57
58
59/*********************************************************************************************************************************
60* Structures and Typedefs *
61*********************************************************************************************************************************/
62class CExeModule : public ATL::CComModule
63{
64public:
65 LONG Unlock();
66 DWORD dwThreadID;
67 HANDLE hEventShutdown;
68 void MonitorShutdown();
69 bool StartMonitor();
70 bool HasActiveConnection();
71 bool bActivity;
72 static bool isIdleLockCount(LONG cLocks);
73};
74
75
76/*********************************************************************************************************************************
77* Global Variables *
78*********************************************************************************************************************************/
79BEGIN_OBJECT_MAP(ObjectMap)
80 OBJECT_ENTRY(CLSID_VirtualBox, VirtualBox)
81END_OBJECT_MAP()
82
83CExeModule *g_pModule = NULL;
84HWND g_hMainWindow = NULL;
85HINSTANCE g_hInstance = NULL;
86#ifdef VBOX_WITH_SDS_PLAN_B
87/** This is set if we're connected to SDS and should discount a server lock
88 * that it is holding when deciding whether we're idle or not. */
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_PLAN_B
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_PLAN_B
194class VBoxSVC;
195
196/**
197 * Custom class factory for the VirtualBox singleton.
198 *
199 * The implementation of CreateInstance is found in win/svcmain.cpp.
200 */
201class VirtualBoxClassFactory : public ATL::CComClassFactory
202{
203private:
204 /** Tri state: 0=uninitialized or initializing; 1=success; -1=failure.
205 * This will be updated after both m_hrcCreate and m_pObj have been set. */
206 volatile int32_t m_iState;
207 /** The result of the instantiation attempt. */
208 HRESULT m_hrcCreate;
209 /** The IUnknown of the VirtualBox object/interface we're working with. */
210 IUnknown *m_pObj;
211 /** Pointer to the IVBoxSVC implementation that VBoxSDS works with. */
212 VBoxSVC *m_pVBoxSVC;
213 /** The VBoxSDS interface. */
214 ComPtr<IVirtualBoxSDS> m_ptrVirtualBoxSDS;
215
216public:
217 VirtualBoxClassFactory() : m_iState(0), m_hrcCreate(S_OK), m_pObj(NULL), m_pVBoxSVC(NULL)
218 { }
219
220 virtual ~VirtualBoxClassFactory()
221 {
222 if (m_pObj)
223 {
224 m_pObj->Release();
225 m_pObj = NULL;
226 }
227
228 /** @todo Need to check if this is okay wrt COM termination. */
229 i_deregisterWithSds();
230 }
231
232 // IClassFactory
233 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void **ppvObj);
234
235 /** Worker for VBoxSVC::getVirtualBox. */
236 HRESULT i_getVirtualBox(IUnknown **ppResult);
237
238private:
239 HRESULT VirtualBoxClassFactory::i_registerWithSds(IUnknown **ppOtherVirtualBox);
240 void VirtualBoxClassFactory::i_deregisterWithSds(void);
241
242 friend VBoxSVC;
243};
244
245
246/**
247 * The VBoxSVC class is handed to VBoxSDS so it can call us back and ask for the
248 * VirtualBox object when the next VBoxSVC for this user registers itself.
249 */
250class VBoxSVC : public IVBoxSVC
251{
252private:
253 /** Number of references. */
254 uint32_t volatile m_cRefs;
255
256public:
257 /** Pointer to the factory. */
258 VirtualBoxClassFactory *m_pFactory;
259
260public:
261 VBoxSVC(VirtualBoxClassFactory *pFactory)
262 : m_cRefs(1), m_pFactory(pFactory)
263 { }
264 virtual ~VBoxSVC()
265 {
266 if (m_pFactory)
267 {
268 if (m_pFactory->m_pVBoxSVC)
269 m_pFactory->m_pVBoxSVC = NULL;
270 m_pFactory = NULL;
271 }
272 }
273 RTMEMEF_NEW_AND_DELETE_OPERATORS();
274
275 // IUnknown
276 STDMETHOD(QueryInterface)(REFIID riid, void **ppvObject)
277 {
278 if (riid == __uuidof(IUnknown))
279 *ppvObject = (void *)(IUnknown *)this;
280 else if (riid == __uuidof(IVBoxSVC))
281 *ppvObject = (void *)(IVBoxSVC *)this;
282 else
283 {
284 return E_NOINTERFACE;
285 }
286 AddRef();
287 return S_OK;
288
289 }
290
291 STDMETHOD_(ULONG,AddRef)(void)
292 {
293 uint32_t cRefs = ASMAtomicIncU32(&m_cRefs);
294 return cRefs;
295 }
296
297 STDMETHOD_(ULONG,Release)(void)
298 {
299 uint32_t cRefs = ASMAtomicDecU32(&m_cRefs);
300 if (cRefs == 0)
301 delete this;
302 return cRefs;
303 }
304
305 // IVBoxSVC
306 STDMETHOD(GetVirtualBox)(IUnknown **ppResult)
307 {
308 if (m_pFactory)
309 return m_pFactory->i_getVirtualBox(ppResult);
310 return E_FAIL;
311 }
312};
313
314
315HRESULT VirtualBoxClassFactory::i_registerWithSds(IUnknown **ppOtherVirtualBox)
316{
317 /*
318 * Connect to VBoxSDS.
319 */
320 HRESULT hrc = CoCreateInstance(CLSID_VirtualBoxSDS, NULL, CLSCTX_LOCAL_SERVER, IID_IVirtualBoxSDS,
321 (void **)m_ptrVirtualBoxSDS.asOutParam());
322 if (SUCCEEDED(hrc))
323 {
324 /*
325 * Create VBoxSVC object and hand that to VBoxSDS.
326 */
327 m_pVBoxSVC = new VBoxSVC(this);
328 hrc = m_ptrVirtualBoxSDS->RegisterVBoxSVC(m_pVBoxSVC, GetCurrentProcessId(), ppOtherVirtualBox);
329 if (SUCCEEDED(hrc))
330 {
331 g_fRegisteredWithVBoxSDS = true;
332 return hrc;
333 }
334 m_pVBoxSVC->Release();
335 }
336 m_ptrVirtualBoxSDS.setNull();
337 m_pVBoxSVC = NULL;
338 *ppOtherVirtualBox = NULL;
339 return hrc;
340}
341
342
343void VirtualBoxClassFactory::i_deregisterWithSds(void)
344{
345 Log(("VirtualBoxClassFactory::i_deregisterWithSds\n"));
346
347 if (m_ptrVirtualBoxSDS.isNotNull())
348 {
349 if (m_pVBoxSVC)
350 {
351 HRESULT hrc = m_ptrVirtualBoxSDS->DeregisterVBoxSVC(m_pVBoxSVC, GetCurrentProcessId());
352 NOREF(hrc);
353 }
354 m_ptrVirtualBoxSDS.setNull();
355 g_fRegisteredWithVBoxSDS = false;
356 }
357 if (m_pVBoxSVC)
358 {
359 m_pVBoxSVC->m_pFactory = NULL;
360 m_pVBoxSVC->Release();
361 m_pVBoxSVC = NULL;
362 }
363}
364
365
366HRESULT VirtualBoxClassFactory::i_getVirtualBox(IUnknown **ppResult)
367{
368 IUnknown *pObj = m_pObj;
369 if (pObj)
370 {
371 /** @todo Do we need to do something regarding server locking? Hopefully COM
372 * deals with that........... */
373 pObj->AddRef();
374 *ppResult = pObj;
375 Log(("VirtualBoxClassFactory::GetVirtualBox: S_OK - %p\n", pObj));
376 return S_OK;
377 }
378 *ppResult = NULL;
379 Log(("VirtualBoxClassFactory::GetVirtualBox: E_FAIL\n"));
380 return E_FAIL;
381}
382
383
384/**
385 * Custom class factory impl for the VirtualBox singleton.
386 *
387 * This will consult with VBoxSDS on whether this VBoxSVC instance should
388 * provide the actual VirtualBox instance or just forward the instance from
389 * some other SVC instance.
390 *
391 * @param pUnkOuter This must be NULL.
392 * @param riid Reference to the interface ID to provide.
393 * @param ppvObj Where to return the pointer to the riid instance.
394 *
395 * @return COM status code.
396 */
397STDMETHODIMP VirtualBoxClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, void **ppvObj)
398{
399 HRESULT hrc = E_POINTER;
400 if (ppvObj != NULL)
401 {
402 *ppvObj = NULL;
403 // no aggregation for singletons
404 AssertReturn(pUnkOuter == NULL, CLASS_E_NOAGGREGATION);
405
406 /*
407 * We must make sure there is only one instance around.
408 * So, we check without locking and then again after locking.
409 */
410 if (ASMAtomicReadS32(&m_iState) == 0)
411 {
412 Lock();
413 __try
414 {
415 if (ASMAtomicReadS32(&m_iState) == 0)
416 {
417 /*
418 * lock the module to indicate activity
419 * (necessary for the monitor shutdown thread to correctly
420 * terminate the module in case when CreateInstance() fails)
421 */
422 ATL::_pAtlModule->Lock();
423 __try
424 {
425 /*
426 * Now we need to connect to VBoxSDS to register ourselves.
427 */
428 IUnknown *pOtherVirtualBox = NULL;
429 m_hrcCreate = hrc = i_registerWithSds(&pOtherVirtualBox);
430 if (SUCCEEDED(hrc) && pOtherVirtualBox)
431 m_pObj = pOtherVirtualBox;
432 else if (SUCCEEDED(hrc))
433 {
434 ATL::_pAtlModule->Lock();
435 ATL::CComObjectCached<VirtualBox> *p;
436 m_hrcCreate = hrc = ATL::CComObjectCached<VirtualBox>::CreateInstance(&p);
437 if (SUCCEEDED(hrc))
438 {
439 m_hrcCreate = hrc = p->QueryInterface(IID_IUnknown, (void **)&m_pObj);
440 if (FAILED(hrc))
441 {
442 delete p;
443 i_deregisterWithSds();
444 m_pObj = NULL;
445 }
446 }
447 }
448 ASMAtomicWriteS32(&m_iState, SUCCEEDED(hrc) ? 1 : -1);
449 }
450 __finally
451 {
452 ATL::_pAtlModule->Unlock();
453 }
454 }
455 }
456 __finally
457 {
458 if (ASMAtomicReadS32(&m_iState) == 0)
459 {
460 ASMAtomicWriteS32(&m_iState, -1);
461 if (SUCCEEDED(m_hrcCreate))
462 m_hrcCreate = E_FAIL;
463 }
464 Unlock();
465 }
466 }
467
468 /*
469 * Query the requested interface from the IUnknown one we're keeping around.
470 */
471 if (m_hrcCreate == S_OK)
472 hrc = m_pObj->QueryInterface(riid, ppvObj);
473 else
474 hrc = m_hrcCreate;
475 }
476 return hrc;
477}
478
479#endif /* VBOX_WITH_SDS_PLAN_B */
480
481
482/*
483* Wrapper for Win API function ShutdownBlockReasonCreate
484* This function defined starting from Vista only.
485*/
486static BOOL ShutdownBlockReasonCreateAPI(HWND hWnd, LPCWSTR pwszReason)
487{
488 BOOL fResult = FALSE;
489 typedef BOOL(WINAPI *PFNSHUTDOWNBLOCKREASONCREATE)(HWND hWnd, LPCWSTR pwszReason);
490
491 PFNSHUTDOWNBLOCKREASONCREATE pfn = (PFNSHUTDOWNBLOCKREASONCREATE)GetProcAddress(
492 GetModuleHandle(L"User32.dll"), "ShutdownBlockReasonCreate");
493 AssertPtr(pfn);
494 if (pfn)
495 fResult = pfn(hWnd, pwszReason);
496 return fResult;
497}
498
499/*
500* Wrapper for Win API function ShutdownBlockReasonDestroy
501* This function defined starting from Vista only.
502*/
503static BOOL ShutdownBlockReasonDestroyAPI(HWND hWnd)
504{
505 BOOL fResult = FALSE;
506 typedef BOOL(WINAPI *PFNSHUTDOWNBLOCKREASONDESTROY)(HWND hWnd);
507
508 PFNSHUTDOWNBLOCKREASONDESTROY pfn = (PFNSHUTDOWNBLOCKREASONDESTROY)GetProcAddress(
509 GetModuleHandle(L"User32.dll"), "ShutdownBlockReasonDestroy");
510 AssertPtr(pfn);
511 if (pfn)
512 fResult = pfn(hWnd);
513 return fResult;
514}
515
516static LRESULT CALLBACK WinMainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
517{
518 LRESULT rc = 0;
519 switch (msg)
520 {
521 case WM_QUERYENDSESSION:
522 {
523 if (g_pModule)
524 {
525 bool fActiveConnection = g_pModule->HasActiveConnection();
526 if (fActiveConnection)
527 {
528 /* place the VBoxSVC into system shutdown list */
529 ShutdownBlockReasonCreateAPI(hwnd, L"Has active connections.");
530 /* decrease a latency of MonitorShutdown loop */
531 ASMAtomicXchgU32(&dwTimeOut, 100);
532 Log(("VBoxSVCWinMain: WM_QUERYENDSESSION: VBoxSvc has active connections. bActivity = %d. Loc count = %d\n",
533 g_pModule->bActivity, g_pModule->GetLockCount()));
534 }
535 rc = !fActiveConnection;
536 }
537 else
538 AssertMsgFailed(("VBoxSVCWinMain: WM_QUERYENDSESSION: Error: g_pModule is NULL"));
539 break;
540 }
541 case WM_ENDSESSION:
542 {
543 /* Restore timeout of Monitor Shutdown if user canceled system shutdown */
544 if (wParam == FALSE)
545 {
546 ASMAtomicXchgU32(&dwTimeOut, dwNormalTimeout);
547 Log(("VBoxSVCWinMain: user canceled system shutdown.\n"));
548 }
549 break;
550 }
551 case WM_DESTROY:
552 {
553 ShutdownBlockReasonDestroyAPI(hwnd);
554 PostQuitMessage(0);
555 break;
556 }
557 default:
558 {
559 rc = DefWindowProc(hwnd, msg, wParam, lParam);
560 }
561 }
562 return rc;
563}
564
565static int CreateMainWindow()
566{
567 int rc = VINF_SUCCESS;
568 Assert(g_hMainWindow == NULL);
569
570 LogFlow(("CreateMainWindow\n"));
571
572 g_hInstance = (HINSTANCE)GetModuleHandle(NULL);
573
574 /* Register the Window Class. */
575 WNDCLASS wc;
576 RT_ZERO(wc);
577
578 wc.style = CS_NOCLOSE;
579 wc.lpfnWndProc = WinMainWndProc;
580 wc.hInstance = g_hInstance;
581 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
582 wc.lpszClassName = MAIN_WND_CLASS;
583
584 ATOM atomWindowClass = RegisterClass(&wc);
585 if (atomWindowClass == 0)
586 {
587 Log(("Failed to register main window class\n"));
588 rc = VERR_NOT_SUPPORTED;
589 }
590 else
591 {
592 /* Create the window. */
593 g_hMainWindow = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
594 MAIN_WND_CLASS, MAIN_WND_CLASS,
595 WS_POPUPWINDOW,
596 0, 0, 1, 1, NULL, NULL, g_hInstance, NULL);
597 if (g_hMainWindow == NULL)
598 {
599 Log(("Failed to create main window\n"));
600 rc = VERR_NOT_SUPPORTED;
601 }
602 else
603 {
604 SetWindowPos(g_hMainWindow, HWND_TOPMOST, -200, -200, 0, 0,
605 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
606
607 }
608 }
609 return 0;
610}
611
612
613static void DestroyMainWindow()
614{
615 Assert(g_hMainWindow != NULL);
616 Log(("SVCMain: DestroyMainWindow \n"));
617 if (g_hMainWindow != NULL)
618 {
619 DestroyWindow(g_hMainWindow);
620 g_hMainWindow = NULL;
621 if (g_hInstance != NULL)
622 {
623 UnregisterClass(MAIN_WND_CLASS, g_hInstance);
624 g_hInstance = NULL;
625 }
626 }
627}
628
629
630/////////////////////////////////////////////////////////////////////////////
631//
632int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int /*nShowCmd*/)
633{
634 int argc = __argc;
635 char **argv = __argv;
636
637 /*
638 * Need to parse the command line before initializing the VBox runtime so we can
639 * change to the user home directory before logs are being created.
640 */
641 for (int i = 1; i < argc; i++)
642 if ( (argv[i][0] == '/' || argv[i][0] == '-')
643 && stricmp(&argv[i][1], "embedding") == 0) /* ANSI */
644 {
645 /* %HOMEDRIVE%%HOMEPATH% */
646 wchar_t wszHome[RTPATH_MAX];
647 DWORD cEnv = GetEnvironmentVariable(L"HOMEDRIVE", &wszHome[0], RTPATH_MAX);
648 if (cEnv && cEnv < RTPATH_MAX)
649 {
650 DWORD cwc = cEnv; /* doesn't include NUL */
651 cEnv = GetEnvironmentVariable(L"HOMEPATH", &wszHome[cEnv], RTPATH_MAX - cwc);
652 if (cEnv && cEnv < RTPATH_MAX - cwc)
653 {
654 /* If this fails there is nothing we can do. Ignore. */
655 SetCurrentDirectory(wszHome);
656 }
657 }
658 }
659
660 /*
661 * Initialize the VBox runtime without loading
662 * the support driver.
663 */
664 RTR3InitExe(argc, &argv, 0);
665
666 static const RTGETOPTDEF s_aOptions[] =
667 {
668 { "--embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
669 { "-embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
670 { "/embedding", 'e', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
671 { "--unregserver", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
672 { "-unregserver", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
673 { "/unregserver", 'u', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
674 { "--regserver", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
675 { "-regserver", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
676 { "/regserver", 'r', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
677 { "--reregserver", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
678 { "-reregserver", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
679 { "/reregserver", 'f', RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
680 { "--helper", 'H', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
681 { "-helper", 'H', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
682 { "/helper", 'H', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
683 { "--logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
684 { "-logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
685 { "/logfile", 'F', RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
686 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
687 { "-logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
688 { "/logrotate", 'R', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
689 { "--logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
690 { "-logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
691 { "/logsize", 'S', RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
692 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
693 { "-loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
694 { "/loginterval", 'I', RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
695 };
696
697 bool fRun = true;
698 bool fRegister = false;
699 bool fUnregister = false;
700 const char *pszPipeName = NULL;
701 const char *pszLogFile = NULL;
702 uint32_t cHistory = 10; // enable log rotation, 10 files
703 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
704 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
705
706 RTGETOPTSTATE GetOptState;
707 int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
708 AssertRC(vrc);
709
710 RTGETOPTUNION ValueUnion;
711 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
712 {
713 switch (vrc)
714 {
715 case 'e':
716 /* already handled above */
717 break;
718
719 case 'u':
720 fUnregister = true;
721 fRun = false;
722 break;
723
724 case 'r':
725 fRegister = true;
726 fRun = false;
727 break;
728
729 case 'f':
730 fUnregister = true;
731 fRegister = true;
732 fRun = false;
733 break;
734
735 case 'H':
736 pszPipeName = ValueUnion.psz;
737 if (!pszPipeName)
738 pszPipeName = "";
739 fRun = false;
740 break;
741
742 case 'F':
743 pszLogFile = ValueUnion.psz;
744 break;
745
746 case 'R':
747 cHistory = ValueUnion.u32;
748 break;
749
750 case 'S':
751 uHistoryFileSize = ValueUnion.u64;
752 break;
753
754 case 'I':
755 uHistoryFileTime = ValueUnion.u32;
756 break;
757
758 case 'h':
759 {
760 TCHAR txt[]= L"Options:\n\n"
761 L"/RegServer:\tregister COM out-of-proc server\n"
762 L"/UnregServer:\tunregister COM out-of-proc server\n"
763 L"/ReregServer:\tunregister and register COM server\n"
764 L"no options:\trun the server";
765 TCHAR title[]=_T("Usage");
766 fRun = false;
767 MessageBox(NULL, txt, title, MB_OK);
768 return 0;
769 }
770
771 case 'V':
772 {
773 char *psz = NULL;
774 RTStrAPrintf(&psz, "%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
775 PRTUTF16 txt = NULL;
776 RTStrToUtf16(psz, &txt);
777 TCHAR title[]=_T("Version");
778 fRun = false;
779 MessageBox(NULL, txt, title, MB_OK);
780 RTStrFree(psz);
781 RTUtf16Free(txt);
782 return 0;
783 }
784
785 default:
786 /** @todo this assumes that stderr is visible, which is not
787 * true for standard Windows applications. */
788 /* continue on command line errors... */
789 RTGetOptPrintError(vrc, &ValueUnion);
790 }
791 }
792
793 /* Only create the log file when running VBoxSVC normally, but not when
794 * registering/unregistering or calling the helper functionality. */
795 if (fRun)
796 {
797 /** @todo Merge this code with server.cpp (use Logging.cpp?). */
798 char szLogFile[RTPATH_MAX];
799 if (!pszLogFile)
800 {
801 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
802 if (RT_SUCCESS(vrc))
803 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
804 }
805 else
806 {
807 if (!RTStrPrintf(szLogFile, sizeof(szLogFile), "%s", pszLogFile))
808 vrc = VERR_NO_MEMORY;
809 }
810 if (RT_FAILURE(vrc))
811 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create logging file name, rc=%Rrc", vrc);
812
813 char szError[RTPATH_MAX + 128];
814 vrc = com::VBoxLogRelCreate("COM Server", szLogFile,
815 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
816 VBOXSVC_LOG_DEFAULT, "VBOXSVC_RELEASE_LOG",
817 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
818 cHistory, uHistoryFileTime, uHistoryFileSize,
819 szError, sizeof(szError));
820 if (RT_FAILURE(vrc))
821 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, vrc);
822 }
823
824 /* Set up a build identifier so that it can be seen from core dumps what
825 * exact build was used to produce the core. Same as in Console::i_powerUpThread(). */
826 static char saBuildID[48];
827 RTStrPrintf(saBuildID, sizeof(saBuildID), "%s%s%s%s VirtualBox %s r%u %s%s%s%s",
828 "BU", "IL", "DI", "D", RTBldCfgVersion(), RTBldCfgRevision(), "BU", "IL", "DI", "D");
829
830 int nRet = 0;
831 HRESULT hRes = com::Initialize(false /*fGui*/, fRun /*fAutoRegUpdate*/);
832 AssertLogRelMsg(SUCCEEDED(hRes), ("SVCMAIN: init failed: %Rhrc\n", hRes));
833
834 g_pModule = new CExeModule();
835 if(g_pModule == NULL)
836 return RTMsgErrorExit(RTEXITCODE_FAILURE, "not enough memory to create ExeModule.");
837 g_pModule->Init(ObjectMap, hInstance, &LIBID_VirtualBox);
838 g_pModule->dwThreadID = GetCurrentThreadId();
839
840 if (!fRun)
841 {
842#ifndef VBOX_WITH_MIDL_PROXY_STUB /* VBoxProxyStub.dll does all the registration work. */
843 if (fUnregister)
844 {
845 g_pModule->UpdateRegistryFromResource(IDR_VIRTUALBOX, FALSE);
846 nRet = g_pModule->UnregisterServer(TRUE);
847 }
848 if (fRegister)
849 {
850 g_pModule->UpdateRegistryFromResource(IDR_VIRTUALBOX, TRUE);
851 nRet = g_pModule->RegisterServer(TRUE);
852 }
853#endif
854 if (pszPipeName)
855 {
856 Log(("SVCMAIN: Processing Helper request (cmdline=\"%s\")...\n", pszPipeName));
857
858 if (!*pszPipeName)
859 vrc = VERR_INVALID_PARAMETER;
860
861 if (RT_SUCCESS(vrc))
862 {
863 /* do the helper job */
864 SVCHlpServer server;
865 vrc = server.open(pszPipeName);
866 if (RT_SUCCESS(vrc))
867 vrc = server.run();
868 }
869 if (RT_FAILURE(vrc))
870 {
871 Log(("SVCMAIN: Failed to process Helper request (%Rrc).", vrc));
872 nRet = 1;
873 }
874 }
875 }
876 else
877 {
878 g_pModule->StartMonitor();
879#if _WIN32_WINNT >= 0x0400
880 hRes = g_pModule->RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
881 _ASSERTE(SUCCEEDED(hRes));
882 hRes = CoResumeClassObjects();
883#else
884 hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
885#endif
886 _ASSERTE(SUCCEEDED(hRes));
887
888 if (RT_SUCCESS(CreateMainWindow()))
889 Log(("SVCMain: Main window succesfully created\n"));
890 else
891 Log(("SVCMain: Failed to create main window\n"));
892
893 MSG msg;
894 while (GetMessage(&msg, 0, 0, 0) > 0)
895 {
896 DispatchMessage(&msg);
897 TranslateMessage(&msg);
898 }
899
900 DestroyMainWindow();
901
902 g_pModule->RevokeClassObjects();
903 }
904
905 g_pModule->Term();
906
907 com::Shutdown();
908
909 if(g_pModule)
910 delete g_pModule;
911 g_pModule = NULL;
912
913 Log(("SVCMAIN: Returning, COM server process ends.\n"));
914 return nRet;
915}
Note: See TracBrowser for help on using the repository browser.

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