VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxService.cpp@ 95851

最後變更 在這個檔案從95851是 94624,由 vboxsync 提交於 3 年 前

Runtime/log: Allow setting a custom output interface for the file destination (for encryption), bugref:9955

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 42.4 KB
 
1/* $Id: VBoxService.cpp 94624 2022-04-19 09:20:51Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions Service Skeleton.
4 */
5
6/*
7 * Copyright (C) 2007-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/** @page pg_vgsvc VBoxService
20 *
21 * VBoxService is a root daemon for implementing guest additions features.
22 *
23 * It is structured as one binary that contains many sub-services. The reason
24 * for this is partially historical and partially practical. The practical
25 * reason is that the VBoxService binary is typically statically linked, at
26 * least with IPRT and the guest library, so we save quite a lot of space having
27 * on single binary instead individual binaries for each sub-service and their
28 * helpers (currently up to 9 subservices and 8 helpers). The historical is
29 * simply that it started its life on OS/2 dreaming of conquring Windows next,
30 * so it kind of felt natural to have it all in one binary.
31 *
32 * Even if it's structured as a single binary, it is possible, by using command
33 * line options, to start each subservice as an individual process.
34 *
35 * Subservices:
36 * - @subpage pg_vgsvc_timesync "Time Synchronization"
37 * - @subpage pg_vgsvc_vminfo "VM Information"
38 * - @subpage pg_vgsvc_vmstats "VM Statistics"
39 * - @subpage pg_vgsvc_gstctrl "Guest Control"
40 * - @subpage pg_vgsvc_pagesharing "Page Sharing"
41 * - @subpage pg_vgsvc_memballoon "Memory Balooning"
42 * - @subpage pg_vgsvc_cpuhotplug "CPU Hot-Plugging"
43 * - @subpage pg_vgsvc_automount "Shared Folder Automounting"
44 * - @subpage pg_vgsvc_clipboard "Clipboard (OS/2 only)"
45 *
46 * Now, since the service predates a lot of stuff, including RTGetOpt, we're
47 * currently doing our own version of argument parsing here, which is kind of
48 * stupid. That will hopefully be cleaned up eventually.
49 */
50
51
52/*********************************************************************************************************************************
53* Header Files *
54*********************************************************************************************************************************/
55/** @todo LOG_GROUP*/
56#ifndef _MSC_VER
57# include <unistd.h>
58#endif
59#include <errno.h>
60#ifndef RT_OS_WINDOWS
61# include <signal.h>
62# ifdef RT_OS_OS2
63# define pthread_sigmask sigprocmask
64# endif
65#endif
66#ifdef RT_OS_FREEBSD
67# include <pthread.h>
68#endif
69
70#include <package-generated.h>
71#include "product-generated.h"
72
73#include <iprt/asm.h>
74#include <iprt/buildconfig.h>
75#include <iprt/initterm.h>
76#include <iprt/file.h>
77#ifdef DEBUG
78# include <iprt/memtracker.h>
79#endif
80#include <iprt/env.h>
81#include <iprt/message.h>
82#include <iprt/path.h>
83#include <iprt/process.h>
84#include <iprt/semaphore.h>
85#include <iprt/string.h>
86#include <iprt/stream.h>
87#include <iprt/system.h>
88#include <iprt/thread.h>
89
90#include <VBox/err.h>
91#include <VBox/log.h>
92
93#include "VBoxServiceInternal.h"
94#include "VBoxServiceUtils.h"
95#ifdef VBOX_WITH_VBOXSERVICE_CONTROL
96# include "VBoxServiceControl.h"
97#endif
98#ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
99# include "VBoxServiceToolBox.h"
100#endif
101
102
103/*********************************************************************************************************************************
104* Global Variables *
105*********************************************************************************************************************************/
106/** The program name (derived from argv[0]). */
107char *g_pszProgName = (char *)"";
108/** The current verbosity level. */
109unsigned g_cVerbosity = 0;
110char g_szLogFile[RTPATH_MAX + 128] = "";
111char g_szPidFile[RTPATH_MAX] = "";
112/** Logging parameters. */
113/** @todo Make this configurable later. */
114static PRTLOGGER g_pLoggerRelease = NULL;
115static uint32_t g_cHistory = 10; /* Enable log rotation, 10 files. */
116static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; /* Max 1 day per file. */
117static uint64_t g_uHistoryFileSize = 100 * _1M; /* Max 100MB per file. */
118/** Critical section for (debug) logging. */
119#ifdef DEBUG
120 RTCRITSECT g_csLog;
121#endif
122/** The default service interval (the -i | --interval) option). */
123uint32_t g_DefaultInterval = 0;
124#ifdef RT_OS_WINDOWS
125/** Signal shutdown to the Windows service thread. */
126static bool volatile g_fWindowsServiceShutdown;
127/** Event the Windows service thread waits for shutdown. */
128static RTSEMEVENT g_hEvtWindowsService;
129#endif
130
131/**
132 * The details of the services that has been compiled in.
133 */
134static struct
135{
136 /** Pointer to the service descriptor. */
137 PCVBOXSERVICE pDesc;
138 /** The worker thread. NIL_RTTHREAD if it's the main thread. */
139 RTTHREAD Thread;
140 /** Whether Pre-init was called. */
141 bool fPreInited;
142 /** Shutdown indicator. */
143 bool volatile fShutdown;
144 /** Indicator set by the service thread exiting. */
145 bool volatile fStopped;
146 /** Whether the service was started or not. */
147 bool fStarted;
148 /** Whether the service is enabled or not. */
149 bool fEnabled;
150} g_aServices[] =
151{
152#ifdef VBOX_WITH_VBOXSERVICE_CONTROL
153 { &g_Control, NIL_RTTHREAD, false, false, false, false, true },
154#endif
155#ifdef VBOX_WITH_VBOXSERVICE_TIMESYNC
156 { &g_TimeSync, NIL_RTTHREAD, false, false, false, false, true },
157#endif
158#ifdef VBOX_WITH_VBOXSERVICE_CLIPBOARD
159 { &g_Clipboard, NIL_RTTHREAD, false, false, false, false, true },
160#endif
161#ifdef VBOX_WITH_VBOXSERVICE_VMINFO
162 { &g_VMInfo, NIL_RTTHREAD, false, false, false, false, true },
163#endif
164#ifdef VBOX_WITH_VBOXSERVICE_CPUHOTPLUG
165 { &g_CpuHotPlug, NIL_RTTHREAD, false, false, false, false, true },
166#endif
167#ifdef VBOX_WITH_VBOXSERVICE_MANAGEMENT
168# ifdef VBOX_WITH_MEMBALLOON
169 { &g_MemBalloon, NIL_RTTHREAD, false, false, false, false, true },
170# endif
171 { &g_VMStatistics, NIL_RTTHREAD, false, false, false, false, true },
172#endif
173#if defined(VBOX_WITH_VBOXSERVICE_PAGE_SHARING)
174 { &g_PageSharing, NIL_RTTHREAD, false, false, false, false, true },
175#endif
176#ifdef VBOX_WITH_SHARED_FOLDERS
177 { &g_AutoMount, NIL_RTTHREAD, false, false, false, false, true },
178#endif
179};
180
181
182/*
183 * Default call-backs for services which do not need special behaviour.
184 */
185
186/**
187 * @interface_method_impl{VBOXSERVICE,pfnPreInit, Default Implementation}
188 */
189DECLCALLBACK(int) VGSvcDefaultPreInit(void)
190{
191 return VINF_SUCCESS;
192}
193
194
195/**
196 * @interface_method_impl{VBOXSERVICE,pfnOption, Default Implementation}
197 */
198DECLCALLBACK(int) VGSvcDefaultOption(const char **ppszShort, int argc,
199 char **argv, int *pi)
200{
201 NOREF(ppszShort);
202 NOREF(argc);
203 NOREF(argv);
204 NOREF(pi);
205
206 return -1;
207}
208
209
210/**
211 * @interface_method_impl{VBOXSERVICE,pfnInit, Default Implementation}
212 */
213DECLCALLBACK(int) VGSvcDefaultInit(void)
214{
215 return VINF_SUCCESS;
216}
217
218
219/**
220 * @interface_method_impl{VBOXSERVICE,pfnTerm, Default Implementation}
221 */
222DECLCALLBACK(void) VGSvcDefaultTerm(void)
223{
224 return;
225}
226
227
228/**
229 * @callback_method_impl{FNRTLOGPHASE, Release logger callback}
230 */
231static DECLCALLBACK(void) vgsvcLogHeaderFooter(PRTLOGGER pLoggerRelease, RTLOGPHASE enmPhase, PFNRTLOGPHASEMSG pfnLog)
232{
233 /* Some introductory information. */
234 static RTTIMESPEC s_TimeSpec;
235 char szTmp[256];
236 if (enmPhase == RTLOGPHASE_BEGIN)
237 RTTimeNow(&s_TimeSpec);
238 RTTimeSpecToString(&s_TimeSpec, szTmp, sizeof(szTmp));
239
240 switch (enmPhase)
241 {
242 case RTLOGPHASE_BEGIN:
243 {
244 pfnLog(pLoggerRelease,
245 "VBoxService %s r%s (verbosity: %u) %s (%s %s) release log\n"
246 "Log opened %s\n",
247 RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity, VBOX_BUILD_TARGET,
248 __DATE__, __TIME__, szTmp);
249
250 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
251 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
252 pfnLog(pLoggerRelease, "OS Product: %s\n", szTmp);
253 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
254 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
255 pfnLog(pLoggerRelease, "OS Release: %s\n", szTmp);
256 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
257 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
258 pfnLog(pLoggerRelease, "OS Version: %s\n", szTmp);
259 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
260 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
261 pfnLog(pLoggerRelease, "OS Service Pack: %s\n", szTmp);
262
263 /* the package type is interesting for Linux distributions */
264 char szExecName[RTPATH_MAX];
265 char *pszExecName = RTProcGetExecutablePath(szExecName, sizeof(szExecName));
266 pfnLog(pLoggerRelease,
267 "Executable: %s\n"
268 "Process ID: %u\n"
269 "Package type: %s"
270#ifdef VBOX_OSE
271 " (OSE)"
272#endif
273 "\n",
274 pszExecName ? pszExecName : "unknown",
275 RTProcSelf(),
276 VBOX_PACKAGE_STRING);
277 break;
278 }
279
280 case RTLOGPHASE_PREROTATE:
281 pfnLog(pLoggerRelease, "Log rotated - Log started %s\n", szTmp);
282 break;
283
284 case RTLOGPHASE_POSTROTATE:
285 pfnLog(pLoggerRelease, "Log continuation - Log started %s\n", szTmp);
286 break;
287
288 case RTLOGPHASE_END:
289 pfnLog(pLoggerRelease, "End of log file - Log started %s\n", szTmp);
290 break;
291
292 default:
293 /* nothing */
294 break;
295 }
296}
297
298
299/**
300 * Creates the default release logger outputting to the specified file.
301 *
302 * Pass NULL to disabled logging.
303 *
304 * @return IPRT status code.
305 * @param pszLogFile Filename for log output. NULL disables logging
306 * (r=bird: No, it doesn't!).
307 */
308int VGSvcLogCreate(const char *pszLogFile)
309{
310 /* Create release logger (stdout + file). */
311 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
312 RTUINT fFlags = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME;
313#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
314 fFlags |= RTLOGFLAGS_USECRLF;
315#endif
316 int rc = RTLogCreateEx(&g_pLoggerRelease, "VBOXSERVICE_RELEASE_LOG", fFlags, "all",
317 RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX /*cMaxEntriesPerGroup*/,
318 0 /*cBufDescs*/, NULL /*paBufDescs*/, RTLOGDEST_STDOUT | RTLOGDEST_USER,
319 vgsvcLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
320 NULL /*pOutputIf*/, NULL /*pvOutputIfUser*/,
321 NULL /*pErrInfo*/, "%s", pszLogFile ? pszLogFile : "");
322 if (RT_SUCCESS(rc))
323 {
324 /* register this logger as the release logger */
325 RTLogRelSetDefaultInstance(g_pLoggerRelease);
326
327 /* Explicitly flush the log in case of VBOXSERVICE_RELEASE_LOG=buffered. */
328 RTLogFlush(g_pLoggerRelease);
329 }
330
331 return rc;
332}
333
334
335/**
336 * Logs a verbose message.
337 *
338 * @param pszFormat The message text.
339 * @param va Format arguments.
340 */
341void VGSvcLogV(const char *pszFormat, va_list va)
342{
343#ifdef DEBUG
344 int rc = RTCritSectEnter(&g_csLog);
345 if (RT_SUCCESS(rc))
346 {
347#endif
348 char *psz = NULL;
349 RTStrAPrintfV(&psz, pszFormat, va);
350
351 AssertPtr(psz);
352 LogRel(("%s", psz));
353
354 RTStrFree(psz);
355#ifdef DEBUG
356 RTCritSectLeave(&g_csLog);
357 }
358#endif
359}
360
361
362/**
363 * Destroys the currently active logging instance.
364 */
365void VGSvcLogDestroy(void)
366{
367 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
368}
369
370
371/**
372 * Displays the program usage message.
373 *
374 * @returns 1.
375 */
376static int vgsvcUsage(void)
377{
378 RTPrintf("Usage: %s [-f|--foreground] [-v|--verbose] [-l|--logfile <file>]\n"
379 " [-p|--pidfile <file>] [-i|--interval <seconds>]\n"
380 " [--disable-<service>] [--enable-<service>]\n"
381 " [--only-<service>] [-h|-?|--help]\n", g_pszProgName);
382#ifdef RT_OS_WINDOWS
383 RTPrintf(" [-r|--register] [-u|--unregister]\n");
384#endif
385 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
386 if (g_aServices[j].pDesc->pszUsage)
387 RTPrintf("%s\n", g_aServices[j].pDesc->pszUsage);
388 RTPrintf("\n"
389 "Options:\n"
390 " -i | --interval The default interval.\n"
391 " -f | --foreground Don't daemonize the program. For debugging.\n"
392 " -l | --logfile <file> Enables logging to a file.\n"
393 " -p | --pidfile <file> Write the process ID to a file.\n"
394 " -v | --verbose Increment the verbosity level. For debugging.\n"
395 " -V | --version Show version information.\n"
396 " -h | -? | --help Show this message and exit with status 1.\n"
397 );
398#ifdef RT_OS_WINDOWS
399 RTPrintf(" -r | --register Installs the service.\n"
400 " -u | --unregister Uninstall service.\n");
401#endif
402
403 RTPrintf("\n"
404 "Service-specific options:\n");
405 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
406 {
407 RTPrintf(" --enable-%-14s Enables the %s service. (default)\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
408 RTPrintf(" --disable-%-13s Disables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
409 RTPrintf(" --only-%-16s Only enables the %s service.\n", g_aServices[j].pDesc->pszName, g_aServices[j].pDesc->pszName);
410 if (g_aServices[j].pDesc->pszOptions)
411 RTPrintf("%s", g_aServices[j].pDesc->pszOptions);
412 }
413 RTPrintf("\n"
414 " Copyright (C) 2009-" VBOX_C_YEAR " " VBOX_VENDOR "\n");
415
416 return 1;
417}
418
419
420/**
421 * Displays an error message.
422 *
423 * @returns RTEXITCODE_FAILURE.
424 * @param pszFormat The message text.
425 * @param ... Format arguments.
426 */
427RTEXITCODE VGSvcError(const char *pszFormat, ...)
428{
429 va_list args;
430 va_start(args, pszFormat);
431 char *psz = NULL;
432 RTStrAPrintfV(&psz, pszFormat, args);
433 va_end(args);
434
435 AssertPtr(psz);
436 LogRel(("Error: %s", psz));
437
438 RTStrFree(psz);
439
440 return RTEXITCODE_FAILURE;
441}
442
443
444/**
445 * Displays a verbose message based on the currently
446 * set global verbosity level.
447 *
448 * @param iLevel Minimum log level required to display this message.
449 * @param pszFormat The message text.
450 * @param ... Format arguments.
451 */
452void VGSvcVerbose(unsigned iLevel, const char *pszFormat, ...)
453{
454 if (iLevel <= g_cVerbosity)
455 {
456 va_list va;
457 va_start(va, pszFormat);
458 VGSvcLogV(pszFormat, va);
459 va_end(va);
460 }
461}
462
463
464/**
465 * Reports the current VBoxService status to the host.
466 *
467 * This makes sure that the Failed state is sticky.
468 *
469 * @return IPRT status code.
470 * @param enmStatus Status to report to the host.
471 */
472int VGSvcReportStatus(VBoxGuestFacilityStatus enmStatus)
473{
474 /*
475 * VBoxGuestFacilityStatus_Failed is sticky.
476 */
477 static VBoxGuestFacilityStatus s_enmLastStatus = VBoxGuestFacilityStatus_Inactive;
478 VGSvcVerbose(4, "Setting VBoxService status to %u\n", enmStatus);
479 if (s_enmLastStatus != VBoxGuestFacilityStatus_Failed)
480 {
481 int rc = VbglR3ReportAdditionsStatus(VBoxGuestFacilityType_VBoxService, enmStatus, 0 /* Flags */);
482 if (RT_FAILURE(rc))
483 {
484 VGSvcError("Could not report VBoxService status (%u), rc=%Rrc\n", enmStatus, rc);
485 return rc;
486 }
487 s_enmLastStatus = enmStatus;
488 }
489 return VINF_SUCCESS;
490}
491
492
493/**
494 * Gets a 32-bit value argument.
495 * @todo Get rid of this and VGSvcArgString() as soon as we have RTOpt handling.
496 *
497 * @returns 0 on success, non-zero exit code on error.
498 * @param argc The argument count.
499 * @param argv The argument vector
500 * @param psz Where in *pi to start looking for the value argument.
501 * @param pi Where to find and perhaps update the argument index.
502 * @param pu32 Where to store the 32-bit value.
503 * @param u32Min The minimum value.
504 * @param u32Max The maximum value.
505 */
506int VGSvcArgUInt32(int argc, char **argv, const char *psz, int *pi, uint32_t *pu32, uint32_t u32Min, uint32_t u32Max)
507{
508 if (*psz == ':' || *psz == '=')
509 psz++;
510 if (!*psz)
511 {
512 if (*pi + 1 >= argc)
513 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Missing value for the '%s' argument\n", argv[*pi]);
514 psz = argv[++*pi];
515 }
516
517 char *pszNext;
518 int rc = RTStrToUInt32Ex(psz, &pszNext, 0, pu32);
519 if (RT_FAILURE(rc) || *pszNext)
520 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Failed to convert interval '%s' to a number\n", psz);
521 if (*pu32 < u32Min || *pu32 > u32Max)
522 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "The timesync interval of %RU32 seconds is out of range [%RU32..%RU32]\n",
523 *pu32, u32Min, u32Max);
524 return 0;
525}
526
527
528/** @todo Get rid of this and VGSvcArgUInt32() as soon as we have RTOpt handling. */
529static int vgsvcArgString(int argc, char **argv, const char *psz, int *pi, char *pszBuf, size_t cbBuf)
530{
531 AssertPtrReturn(pszBuf, VERR_INVALID_POINTER);
532 AssertReturn(cbBuf, VERR_INVALID_PARAMETER);
533
534 if (*psz == ':' || *psz == '=')
535 psz++;
536 if (!*psz)
537 {
538 if (*pi + 1 >= argc)
539 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Missing string for the '%s' argument\n", argv[*pi]);
540 psz = argv[++*pi];
541 }
542
543 if (!RTStrPrintf(pszBuf, cbBuf, "%s", psz))
544 return RTMsgErrorExit(RTEXITCODE_FAILURE, "String for '%s' argument too big\n", argv[*pi]);
545 return 0;
546}
547
548
549/**
550 * The service thread.
551 *
552 * @returns Whatever the worker function returns.
553 * @param ThreadSelf My thread handle.
554 * @param pvUser The service index.
555 */
556static DECLCALLBACK(int) vgsvcThread(RTTHREAD ThreadSelf, void *pvUser)
557{
558 const unsigned i = (uintptr_t)pvUser;
559
560#ifndef RT_OS_WINDOWS
561 /*
562 * Block all signals for this thread. Only the main thread will handle signals.
563 */
564 sigset_t signalMask;
565 sigfillset(&signalMask);
566 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
567#endif
568
569 int rc = g_aServices[i].pDesc->pfnWorker(&g_aServices[i].fShutdown);
570 ASMAtomicXchgBool(&g_aServices[i].fShutdown, true);
571 RTThreadUserSignal(ThreadSelf);
572 return rc;
573}
574
575
576/**
577 * Lazily calls the pfnPreInit method on each service.
578 *
579 * @returns VBox status code, error message displayed.
580 */
581static RTEXITCODE vgsvcLazyPreInit(void)
582{
583 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
584 if (!g_aServices[j].fPreInited)
585 {
586 int rc = g_aServices[j].pDesc->pfnPreInit();
587 if (RT_FAILURE(rc))
588 return VGSvcError("Service '%s' failed pre-init: %Rrc\n", g_aServices[j].pDesc->pszName, rc);
589 g_aServices[j].fPreInited = true;
590 }
591 return RTEXITCODE_SUCCESS;
592}
593
594
595/**
596 * Count the number of enabled services.
597 */
598static unsigned vgsvcCountEnabledServices(void)
599{
600 unsigned cEnabled = 0;
601 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
602 cEnabled += g_aServices[i].fEnabled;
603 return cEnabled;
604}
605
606
607#ifdef RT_OS_WINDOWS
608/**
609 * Console control event callback.
610 *
611 * @returns TRUE if handled, FALSE if not.
612 * @param dwCtrlType The control event type.
613 *
614 * @remarks This is generally called on a new thread, so we're racing every
615 * other thread in the process.
616 */
617static BOOL WINAPI vgsvcWinConsoleControlHandler(DWORD dwCtrlType) RT_NOTHROW_DEF
618{
619 int rc = VINF_SUCCESS;
620 bool fEventHandled = FALSE;
621 switch (dwCtrlType)
622 {
623 /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
624 * via GenerateConsoleCtrlEvent(). */
625 case CTRL_BREAK_EVENT:
626 case CTRL_CLOSE_EVENT:
627 case CTRL_C_EVENT:
628 VGSvcVerbose(2, "ControlHandler: Received break/close event\n");
629 rc = VGSvcStopServices();
630 fEventHandled = TRUE;
631 break;
632 default:
633 break;
634 /** @todo Add other events here. */
635 }
636
637 if (RT_FAILURE(rc))
638 VGSvcError("ControlHandler: Event %ld handled with error rc=%Rrc\n",
639 dwCtrlType, rc);
640 return fEventHandled;
641}
642#endif /* RT_OS_WINDOWS */
643
644
645/**
646 * Starts the service.
647 *
648 * @returns VBox status code, errors are fully bitched.
649 *
650 * @remarks Also called from VBoxService-win.cpp, thus not static.
651 */
652int VGSvcStartServices(void)
653{
654 int rc;
655
656 VGSvcReportStatus(VBoxGuestFacilityStatus_Init);
657
658 /*
659 * Initialize the services.
660 */
661 VGSvcVerbose(2, "Initializing services ...\n");
662 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
663 if (g_aServices[j].fEnabled)
664 {
665 rc = g_aServices[j].pDesc->pfnInit();
666 if (RT_FAILURE(rc))
667 {
668 if (rc != VERR_SERVICE_DISABLED)
669 {
670 VGSvcError("Service '%s' failed to initialize: %Rrc\n", g_aServices[j].pDesc->pszName, rc);
671 VGSvcReportStatus(VBoxGuestFacilityStatus_Failed);
672 return rc;
673 }
674
675 g_aServices[j].fEnabled = false;
676 VGSvcVerbose(0, "Service '%s' was disabled because of missing functionality\n", g_aServices[j].pDesc->pszName);
677 }
678 }
679
680 /*
681 * Start the service(s).
682 */
683 VGSvcVerbose(2, "Starting services ...\n");
684 rc = VINF_SUCCESS;
685 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
686 {
687 if (!g_aServices[j].fEnabled)
688 continue;
689
690 VGSvcVerbose(2, "Starting service '%s' ...\n", g_aServices[j].pDesc->pszName);
691 rc = RTThreadCreate(&g_aServices[j].Thread, vgsvcThread, (void *)(uintptr_t)j, 0,
692 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, g_aServices[j].pDesc->pszName);
693 if (RT_FAILURE(rc))
694 {
695 VGSvcError("RTThreadCreate failed, rc=%Rrc\n", rc);
696 break;
697 }
698 g_aServices[j].fStarted = true;
699
700 /* Wait for the thread to initialize. */
701 /** @todo There is a race between waiting and checking
702 * the fShutdown flag of a thread here and processing
703 * the thread's actual worker loop. If the thread decides
704 * to exit the loop before we skipped the fShutdown check
705 * below the service will fail to start! */
706 /** @todo This presumably means either a one-shot service or that
707 * something has gone wrong. In the second case treating it as failure
708 * to start is probably right, so we need a way to signal the first
709 * rather than leaving the idle thread hanging around. A flag in the
710 * service description? */
711 RTThreadUserWait(g_aServices[j].Thread, 60 * 1000);
712 if (g_aServices[j].fShutdown)
713 {
714 VGSvcError("Service '%s' failed to start!\n", g_aServices[j].pDesc->pszName);
715 rc = VERR_GENERAL_FAILURE;
716 }
717 }
718
719 if (RT_SUCCESS(rc))
720 VGSvcVerbose(1, "All services started.\n");
721 else
722 {
723 VGSvcError("An error occcurred while the services!\n");
724 VGSvcReportStatus(VBoxGuestFacilityStatus_Failed);
725 }
726 return rc;
727}
728
729
730/**
731 * Stops and terminates the services.
732 *
733 * This should be called even when VBoxServiceStartServices fails so it can
734 * clean up anything that we succeeded in starting.
735 *
736 * @remarks Also called from VBoxService-win.cpp, thus not static.
737 */
738int VGSvcStopServices(void)
739{
740 VGSvcReportStatus(VBoxGuestFacilityStatus_Terminating);
741
742 /*
743 * Signal all the services.
744 */
745 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
746 ASMAtomicWriteBool(&g_aServices[j].fShutdown, true);
747
748 /*
749 * Do the pfnStop callback on all running services.
750 */
751 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
752 if (g_aServices[j].fStarted)
753 {
754 VGSvcVerbose(3, "Calling stop function for service '%s' ...\n", g_aServices[j].pDesc->pszName);
755 g_aServices[j].pDesc->pfnStop();
756 }
757
758 VGSvcVerbose(3, "All stop functions for services called\n");
759
760 /*
761 * Wait for all the service threads to complete.
762 */
763 int rc = VINF_SUCCESS;
764 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
765 {
766 if (!g_aServices[j].fEnabled) /* Only stop services which were started before. */
767 continue;
768 if (g_aServices[j].Thread != NIL_RTTHREAD)
769 {
770 VGSvcVerbose(2, "Waiting for service '%s' to stop ...\n", g_aServices[j].pDesc->pszName);
771 int rc2 = VINF_SUCCESS;
772 for (int i = 0; i < 30; i++) /* Wait 30 seconds in total */
773 {
774 rc2 = RTThreadWait(g_aServices[j].Thread, 1000 /* Wait 1 second */, NULL);
775 if (RT_SUCCESS(rc2))
776 break;
777#ifdef RT_OS_WINDOWS
778 /* Notify SCM that it takes a bit longer ... */
779 VGSvcWinSetStopPendingStatus(i + j*32);
780#endif
781 }
782 if (RT_FAILURE(rc2))
783 {
784 VGSvcError("Service '%s' failed to stop. (%Rrc)\n", g_aServices[j].pDesc->pszName, rc2);
785 rc = rc2;
786 }
787 }
788 VGSvcVerbose(3, "Terminating service '%s' (%d) ...\n", g_aServices[j].pDesc->pszName, j);
789 g_aServices[j].pDesc->pfnTerm();
790 }
791
792#ifdef RT_OS_WINDOWS
793 /*
794 * Wake up and tell the main() thread that we're shutting down (it's
795 * sleeping in VBoxServiceMainWait).
796 */
797 ASMAtomicWriteBool(&g_fWindowsServiceShutdown, true);
798 if (g_hEvtWindowsService != NIL_RTSEMEVENT)
799 {
800 VGSvcVerbose(3, "Stopping the main thread...\n");
801 int rc2 = RTSemEventSignal(g_hEvtWindowsService);
802 AssertRC(rc2);
803 }
804#endif
805
806 VGSvcVerbose(2, "Stopping services returning: %Rrc\n", rc);
807 VGSvcReportStatus(RT_SUCCESS(rc) ? VBoxGuestFacilityStatus_Paused : VBoxGuestFacilityStatus_Failed);
808 return rc;
809}
810
811
812/**
813 * Block the main thread until the service shuts down.
814 *
815 * @remarks Also called from VBoxService-win.cpp, thus not static.
816 */
817void VGSvcMainWait(void)
818{
819 int rc;
820
821 VGSvcReportStatus(VBoxGuestFacilityStatus_Active);
822
823#ifdef RT_OS_WINDOWS
824 /*
825 * Wait for the semaphore to be signalled.
826 */
827 VGSvcVerbose(1, "Waiting in main thread\n");
828 rc = RTSemEventCreate(&g_hEvtWindowsService);
829 AssertRC(rc);
830 while (!ASMAtomicReadBool(&g_fWindowsServiceShutdown))
831 {
832 rc = RTSemEventWait(g_hEvtWindowsService, RT_INDEFINITE_WAIT);
833 AssertRC(rc);
834 }
835 RTSemEventDestroy(g_hEvtWindowsService);
836 g_hEvtWindowsService = NIL_RTSEMEVENT;
837#else
838 /*
839 * Wait explicitly for a HUP, INT, QUIT, ABRT or TERM signal, blocking
840 * all important signals.
841 *
842 * The annoying EINTR/ERESTART loop is for the benefit of Solaris where
843 * sigwait returns when we receive a SIGCHLD. Kind of makes sense since
844 * the signal has to be delivered... Anyway, darwin (10.9.5) has a much
845 * worse way of dealing with SIGCHLD, apparently it'll just return any
846 * of the signals we're waiting on when SIGCHLD becomes pending on this
847 * thread. So, we wait for SIGCHLD here and ignores it.
848 */
849 sigset_t signalMask;
850 sigemptyset(&signalMask);
851 sigaddset(&signalMask, SIGHUP);
852 sigaddset(&signalMask, SIGINT);
853 sigaddset(&signalMask, SIGQUIT);
854 sigaddset(&signalMask, SIGABRT);
855 sigaddset(&signalMask, SIGTERM);
856 sigaddset(&signalMask, SIGCHLD);
857 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
858
859 int iSignal;
860 do
861 {
862 iSignal = -1;
863 rc = sigwait(&signalMask, &iSignal);
864 }
865 while ( rc == EINTR
866# ifdef ERESTART
867 || rc == ERESTART
868# endif
869 || iSignal == SIGCHLD
870 );
871
872 VGSvcVerbose(3, "VGSvcMainWait: Received signal %d (rc=%d)\n", iSignal, rc);
873#endif /* !RT_OS_WINDOWS */
874}
875
876
877/**
878 * Report VbglR3InitUser / VbglR3Init failure.
879 *
880 * @returns RTEXITCODE_FAILURE
881 * @param rcVbgl The failing status code.
882 */
883static RTEXITCODE vbglInitFailure(int rcVbgl)
884{
885 if (rcVbgl == VERR_ACCESS_DENIED)
886 return RTMsgErrorExit(RTEXITCODE_FAILURE,
887 "Insufficient privileges to start %s! Please start with Administrator/root privileges!\n",
888 g_pszProgName);
889 return RTMsgErrorExit(RTEXITCODE_FAILURE, "VbglR3Init failed with rc=%Rrc\n", rcVbgl);
890}
891
892
893int main(int argc, char **argv)
894{
895 RTEXITCODE rcExit;
896
897 /*
898 * Init globals and such.
899 *
900 * Note! The --utf8-argv stuff is an internal hack to avoid locale configuration
901 * issues preventing us from passing non-ASCII string to child processes.
902 */
903 uint32_t fIprtFlags = 0;
904#ifdef VBOXSERVICE_ARG1_UTF8_ARGV
905 if (argc > 1 && strcmp(argv[1], VBOXSERVICE_ARG1_UTF8_ARGV) == 0)
906 {
907 argv[1] = argv[0];
908 argv++;
909 argc--;
910 fIprtFlags |= RTR3INIT_FLAGS_UTF8_ARGV;
911 }
912#endif
913 int rc = RTR3InitExe(argc, &argv, fIprtFlags);
914 if (RT_FAILURE(rc))
915 return RTMsgInitFailure(rc);
916
917 g_pszProgName = RTPathFilename(argv[0]);
918#ifdef RT_OS_WINDOWS
919 VGSvcWinResolveApis();
920#endif
921#ifdef DEBUG
922 rc = RTCritSectInit(&g_csLog);
923 AssertRC(rc);
924#endif
925
926#ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
927 /*
928 * Run toolbox code before all other stuff since these things are simpler
929 * shell/file/text utility like programs that just happens to be inside
930 * VBoxService and shouldn't be subject to /dev/vboxguest, pid-files and
931 * global mutex restrictions.
932 */
933 if (VGSvcToolboxMain(argc, argv, &rcExit))
934 return rcExit;
935#endif
936
937 bool fUserSession = false;
938#ifdef VBOX_WITH_VBOXSERVICE_CONTROL
939 /*
940 * Check if we're the specially spawned VBoxService.exe process that
941 * handles a guest control session.
942 */
943 if ( argc >= 2
944 && !RTStrICmp(argv[1], VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
945 fUserSession = true;
946#endif
947
948 /*
949 * Connect to the kernel part before daemonizing and *before* we do the sub-service
950 * pre-init just in case one of services needs do to some initial stuff with it.
951 *
952 * However, we do not fail till after we've parsed arguments, because that will
953 * prevent useful stuff like --help, --register, --unregister and --version from
954 * working when the driver hasn't been installed/loaded yet.
955 */
956 int const rcVbgl = fUserSession ? VbglR3InitUser() : VbglR3Init();
957
958#ifdef RT_OS_WINDOWS
959 /*
960 * Check if we're the specially spawned VBoxService.exe process that
961 * handles page fusion. This saves an extra statically linked executable.
962 */
963 if ( argc == 2
964 && !RTStrICmp(argv[1], "pagefusion"))
965 {
966 if (RT_SUCCESS(rcVbgl))
967 return VGSvcPageSharingWorkerChild();
968 return vbglInitFailure(rcVbgl);
969 }
970#endif
971
972#ifdef VBOX_WITH_VBOXSERVICE_CONTROL
973 /*
974 * Check if we're the specially spawned VBoxService.exe process that
975 * handles a guest control session.
976 */
977 if (fUserSession)
978 {
979 if (RT_SUCCESS(rcVbgl))
980 return VGSvcGstCtrlSessionSpawnInit(argc, argv);
981 return vbglInitFailure(rcVbgl);
982 }
983#endif
984
985 /*
986 * Parse the arguments.
987 *
988 * Note! This code predates RTGetOpt, thus the manual parsing.
989 */
990 bool fDaemonize = true;
991 bool fDaemonized = false;
992 for (int i = 1; i < argc; i++)
993 {
994 const char *psz = argv[i];
995 if (*psz != '-')
996 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'\n", psz);
997 psz++;
998
999 /* translate long argument to short */
1000 if (*psz == '-')
1001 {
1002 psz++;
1003 size_t cch = strlen(psz);
1004#define MATCHES(strconst) ( cch == sizeof(strconst) - 1 \
1005 && !memcmp(psz, strconst, sizeof(strconst) - 1) )
1006 if (MATCHES("foreground"))
1007 psz = "f";
1008 else if (MATCHES("verbose"))
1009 psz = "v";
1010 else if (MATCHES("version"))
1011 psz = "V";
1012 else if (MATCHES("help"))
1013 psz = "h";
1014 else if (MATCHES("interval"))
1015 psz = "i";
1016#ifdef RT_OS_WINDOWS
1017 else if (MATCHES("register"))
1018 psz = "r";
1019 else if (MATCHES("unregister"))
1020 psz = "u";
1021#endif
1022 else if (MATCHES("logfile"))
1023 psz = "l";
1024 else if (MATCHES("pidfile"))
1025 psz = "p";
1026 else if (MATCHES("daemonized"))
1027 {
1028 fDaemonized = true;
1029 continue;
1030 }
1031 else
1032 {
1033 bool fFound = false;
1034
1035 if (cch > sizeof("enable-") && !memcmp(psz, RT_STR_TUPLE("enable-")))
1036 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
1037 if ((fFound = !RTStrICmp(psz + sizeof("enable-") - 1, g_aServices[j].pDesc->pszName)))
1038 g_aServices[j].fEnabled = true;
1039
1040 if (cch > sizeof("disable-") && !memcmp(psz, RT_STR_TUPLE("disable-")))
1041 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
1042 if ((fFound = !RTStrICmp(psz + sizeof("disable-") - 1, g_aServices[j].pDesc->pszName)))
1043 g_aServices[j].fEnabled = false;
1044
1045 if (cch > sizeof("only-") && !memcmp(psz, RT_STR_TUPLE("only-")))
1046 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
1047 {
1048 g_aServices[j].fEnabled = !RTStrICmp(psz + sizeof("only-") - 1, g_aServices[j].pDesc->pszName);
1049 if (g_aServices[j].fEnabled)
1050 fFound = true;
1051 }
1052
1053 if (!fFound)
1054 {
1055 rcExit = vgsvcLazyPreInit();
1056 if (rcExit != RTEXITCODE_SUCCESS)
1057 return rcExit;
1058 for (unsigned j = 0; !fFound && j < RT_ELEMENTS(g_aServices); j++)
1059 {
1060 rc = g_aServices[j].pDesc->pfnOption(NULL, argc, argv, &i);
1061 fFound = rc == VINF_SUCCESS;
1062 if (fFound)
1063 break;
1064 if (rc != -1)
1065 return rc;
1066 }
1067 }
1068 if (!fFound)
1069 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown option '%s'\n", argv[i]);
1070 continue;
1071 }
1072#undef MATCHES
1073 }
1074
1075 /* handle the string of short options. */
1076 do
1077 {
1078 switch (*psz)
1079 {
1080 case 'i':
1081 rc = VGSvcArgUInt32(argc, argv, psz + 1, &i, &g_DefaultInterval, 1, (UINT32_MAX / 1000) - 1);
1082 if (rc)
1083 return rc;
1084 psz = NULL;
1085 break;
1086
1087 case 'f':
1088 fDaemonize = false;
1089 break;
1090
1091 case 'v':
1092 g_cVerbosity++;
1093 break;
1094
1095 case 'V':
1096 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
1097 return RTEXITCODE_SUCCESS;
1098
1099 case 'h':
1100 case '?':
1101 return vgsvcUsage();
1102
1103#ifdef RT_OS_WINDOWS
1104 case 'r':
1105 return VGSvcWinInstall();
1106
1107 case 'u':
1108 return VGSvcWinUninstall();
1109#endif
1110
1111 case 'l':
1112 {
1113 rc = vgsvcArgString(argc, argv, psz + 1, &i, g_szLogFile, sizeof(g_szLogFile));
1114 if (rc)
1115 return rc;
1116 psz = NULL;
1117 break;
1118 }
1119
1120 case 'p':
1121 {
1122 rc = vgsvcArgString(argc, argv, psz + 1, &i, g_szPidFile, sizeof(g_szPidFile));
1123 if (rc)
1124 return rc;
1125 psz = NULL;
1126 break;
1127 }
1128
1129 default:
1130 {
1131 rcExit = vgsvcLazyPreInit();
1132 if (rcExit != RTEXITCODE_SUCCESS)
1133 return rcExit;
1134
1135 bool fFound = false;
1136 for (unsigned j = 0; j < RT_ELEMENTS(g_aServices); j++)
1137 {
1138 rc = g_aServices[j].pDesc->pfnOption(&psz, argc, argv, &i);
1139 fFound = rc == VINF_SUCCESS;
1140 if (fFound)
1141 break;
1142 if (rc != -1)
1143 return rc;
1144 }
1145 if (!fFound)
1146 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown option '%c' (%s)\n", *psz, argv[i]);
1147 break;
1148 }
1149 }
1150 } while (psz && *++psz);
1151 }
1152
1153 /* Now we can report the VBGL failure. */
1154 if (RT_FAILURE(rcVbgl))
1155 return vbglInitFailure(rcVbgl);
1156
1157 /* Check that at least one service is enabled. */
1158 if (vgsvcCountEnabledServices() == 0)
1159 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "At least one service must be enabled\n");
1160
1161 rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
1162 if (RT_FAILURE(rc))
1163 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to create release log '%s', rc=%Rrc\n",
1164 g_szLogFile[0] ? g_szLogFile : "<None>", rc);
1165
1166 /* Call pre-init if we didn't do it already. */
1167 rcExit = vgsvcLazyPreInit();
1168 if (rcExit != RTEXITCODE_SUCCESS)
1169 return rcExit;
1170
1171#ifdef VBOX_WITH_VBOXSERVICE_DRMRESIZE
1172# ifdef RT_OS_LINUX
1173 rc = VbglR3DrmClientStart();
1174 if (RT_FAILURE(rc))
1175 VGSvcVerbose(0, "VMSVGA DRM resizing client not started, rc=%Rrc\n", rc);
1176# endif /* RT_OS_LINUX */
1177#endif /* VBOX_WITH_VBOXSERVICE_DRMRESIZE */
1178
1179#ifdef RT_OS_WINDOWS
1180 /*
1181 * Make sure only one instance of VBoxService runs at a time. Create a
1182 * global mutex for that.
1183 *
1184 * Note! The \\Global\ namespace was introduced with Win2K, thus the
1185 * version check.
1186 * Note! If the mutex exists CreateMutex will open it and set last error to
1187 * ERROR_ALREADY_EXISTS.
1188 */
1189 OSVERSIONINFOEX OSInfoEx;
1190 RT_ZERO(OSInfoEx);
1191 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1192
1193 SetLastError(NO_ERROR);
1194 HANDLE hMutexAppRunning;
1195 if ( GetVersionEx((LPOSVERSIONINFO)&OSInfoEx)
1196 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
1197 && OSInfoEx.dwMajorVersion >= 5 /* NT 5.0 a.k.a W2K */)
1198 hMutexAppRunning = CreateMutex(NULL, FALSE, "Global\\" VBOXSERVICE_NAME);
1199 else
1200 hMutexAppRunning = CreateMutex(NULL, FALSE, VBOXSERVICE_NAME);
1201 if (hMutexAppRunning == NULL)
1202 {
1203 DWORD dwErr = GetLastError();
1204 if ( dwErr == ERROR_ALREADY_EXISTS
1205 || dwErr == ERROR_ACCESS_DENIED)
1206 {
1207 VGSvcError("%s is already running! Terminating.\n", g_pszProgName);
1208 return RTEXITCODE_FAILURE;
1209 }
1210
1211 VGSvcError("CreateMutex failed with last error %u! Terminating.\n", GetLastError());
1212 return RTEXITCODE_FAILURE;
1213 }
1214
1215#else /* !RT_OS_WINDOWS */
1216 /* On other OSes we have PID file support provided by the actual service definitions / service wrapper scripts,
1217 * like vboxadd-service.sh on Linux or vboxservice.xml on Solaris. */
1218#endif /* !RT_OS_WINDOWS */
1219
1220 VGSvcVerbose(0, "%s r%s started. Verbose level = %d\n", RTBldCfgVersion(), RTBldCfgRevisionStr(), g_cVerbosity);
1221
1222 /*
1223 * Daemonize if requested.
1224 */
1225 if (fDaemonize && !fDaemonized)
1226 {
1227#ifdef RT_OS_WINDOWS
1228 VGSvcVerbose(2, "Starting service dispatcher ...\n");
1229 rcExit = VGSvcWinEnterCtrlDispatcher();
1230#else
1231 VGSvcVerbose(1, "Daemonizing...\n");
1232 rc = VbglR3Daemonize(false /* fNoChDir */, false /* fNoClose */,
1233 false /* fRespawn */, NULL /* pcRespawn */);
1234 if (RT_FAILURE(rc))
1235 return VGSvcError("Daemon failed: %Rrc\n", rc);
1236 /* in-child */
1237#endif
1238 }
1239#ifdef RT_OS_WINDOWS
1240 else
1241#endif
1242 {
1243 /*
1244 * Windows: We're running the service as a console application now. Start the
1245 * services, enter the main thread's run loop and stop them again
1246 * when it returns.
1247 *
1248 * POSIX: This is used for both daemons and console runs. Start all services
1249 * and return immediately.
1250 */
1251#ifdef RT_OS_WINDOWS
1252 /* Install console control handler. */
1253 if (!SetConsoleCtrlHandler(vgsvcWinConsoleControlHandler, TRUE /* Add handler */))
1254 {
1255 VGSvcError("Unable to add console control handler, error=%ld\n", GetLastError());
1256 /* Just skip this error, not critical. */
1257 }
1258#endif /* RT_OS_WINDOWS */
1259 rc = VGSvcStartServices();
1260 RTFILE hPidFile = NIL_RTFILE;
1261 if (RT_SUCCESS(rc))
1262 if (g_szPidFile[0])
1263 rc = VbglR3PidFile(g_szPidFile, &hPidFile);
1264 rcExit = RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1265 if (RT_SUCCESS(rc))
1266 VGSvcMainWait();
1267 if (g_szPidFile[0] && hPidFile != NIL_RTFILE)
1268 VbglR3ClosePidFile(g_szPidFile, hPidFile);
1269#ifdef RT_OS_WINDOWS
1270 /* Uninstall console control handler. */
1271 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
1272 {
1273 VGSvcError("Unable to remove console control handler, error=%ld\n", GetLastError());
1274 /* Just skip this error, not critical. */
1275 }
1276#else /* !RT_OS_WINDOWS */
1277 /* On Windows - since we're running as a console application - we already stopped all services
1278 * through the console control handler. So only do the stopping of services here on other platforms
1279 * where the break/shutdown/whatever signal was just received. */
1280 VGSvcStopServices();
1281#endif /* RT_OS_WINDOWS */
1282 }
1283 VGSvcReportStatus(VBoxGuestFacilityStatus_Terminated);
1284
1285#ifdef RT_OS_WINDOWS
1286 /*
1287 * Cleanup mutex.
1288 */
1289 CloseHandle(hMutexAppRunning);
1290#endif
1291
1292 VGSvcVerbose(0, "Ended.\n");
1293
1294#ifdef DEBUG
1295 RTCritSectDelete(&g_csLog);
1296 //RTMemTrackerDumpAllToStdOut();
1297#endif
1298
1299 VGSvcLogDestroy();
1300
1301 return rcExit;
1302}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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