VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/xpcom/server.cpp@ 56587

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

Main/Performance: convert to API wrapper usage, and quite a bit of cleanup

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 32.3 KB
 
1/* $Id: server.cpp 56587 2015-06-22 19:31:59Z vboxsync $ */
2/** @file
3 * XPCOM server process (VBoxSVC) start point.
4 */
5
6/*
7 * Copyright (C) 2004-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include <ipcIService.h>
19#include <ipcCID.h>
20
21#include <nsIComponentRegistrar.h>
22
23#include <nsEventQueueUtils.h>
24#include <nsGenericFactory.h>
25
26#include "prio.h"
27#include "prproces.h"
28
29#include "server.h"
30
31#include "Logging.h"
32
33#include <VBox/param.h>
34
35#include <iprt/buildconfig.h>
36#include <iprt/initterm.h>
37#include <iprt/critsect.h>
38#include <iprt/getopt.h>
39#include <iprt/message.h>
40#include <iprt/string.h>
41#include <iprt/stream.h>
42#include <iprt/path.h>
43#include <iprt/timer.h>
44#include <iprt/env.h>
45
46#include <signal.h> // for the signal handler
47#include <stdlib.h>
48#include <unistd.h>
49#include <errno.h>
50#include <fcntl.h>
51#include <sys/stat.h>
52#include <sys/resource.h>
53
54/////////////////////////////////////////////////////////////////////////////
55// VirtualBox component instantiation
56/////////////////////////////////////////////////////////////////////////////
57
58#include <nsIGenericFactory.h>
59#include <VirtualBox_XPCOM.h>
60
61#include "ApplianceImpl.h"
62#include "AudioAdapterImpl.h"
63#include "BandwidthControlImpl.h"
64#include "BandwidthGroupImpl.h"
65#include "NetworkServiceRunner.h"
66#include "DHCPServerImpl.h"
67#include "GuestOSTypeImpl.h"
68#include "HostImpl.h"
69#include "HostNetworkInterfaceImpl.h"
70#include "MachineImpl.h"
71#include "MediumFormatImpl.h"
72#include "MediumImpl.h"
73#include "NATEngineImpl.h"
74#include "NetworkAdapterImpl.h"
75#include "ParallelPortImpl.h"
76#include "ProgressProxyImpl.h"
77#include "SerialPortImpl.h"
78#include "SharedFolderImpl.h"
79#include "SnapshotImpl.h"
80#include "StorageControllerImpl.h"
81#include "SystemPropertiesImpl.h"
82#include "USBControllerImpl.h"
83#include "USBDeviceFiltersImpl.h"
84#include "VFSExplorerImpl.h"
85#include "VirtualBoxImpl.h"
86#include "VRDEServerImpl.h"
87#ifdef VBOX_WITH_USB
88# include "HostUSBDeviceImpl.h"
89# include "USBDeviceFilterImpl.h"
90# include "USBDeviceImpl.h"
91#endif
92#ifdef VBOX_WITH_EXTPACK
93# include "ExtPackManagerImpl.h"
94#endif
95# include "NATNetworkImpl.h"
96
97// This needs to stay - it is needed by the service registration below, and
98// is defined in the automatically generated VirtualBoxWrap.cpp
99extern nsIClassInfo *NS_CLASSINFO_NAME(VirtualBoxWrap);
100NS_DECL_CI_INTERFACE_GETTER(VirtualBoxWrap)
101
102// The declarations/implementations of the various XPCOM helper data structures
103// and functions have to be removed bit by bit, as the conversion to the
104// automatically generated wrappers makes them obsolete.
105
106/* implement nsISupports parts of our objects with support for nsIClassInfo */
107NS_DECL_CLASSINFO(SessionMachine)
108NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
109
110NS_DECL_CLASSINFO(SnapshotMachine)
111NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
112
113NS_DECL_CLASSINFO(ProgressProxy)
114NS_IMPL_THREADSAFE_ISUPPORTS1_CI(ProgressProxy, IProgress)
115
116////////////////////////////////////////////////////////////////////////////////
117
118static bool gAutoShutdown = false;
119/** Delay before shutting down the VirtualBox server after the last
120 * VirtualBox instance is released, in ms */
121static uint32_t gShutdownDelayMs = 5000;
122
123static nsCOMPtr<nsIEventQueue> gEventQ = nsnull;
124static PRBool volatile gKeepRunning = PR_TRUE;
125static PRBool volatile gAllowSigUsrQuit = PR_TRUE;
126
127/////////////////////////////////////////////////////////////////////////////
128
129/**
130 * Simple but smart PLEvent wrapper.
131 *
132 * @note Instances must be always created with <tt>operator new</tt>!
133 */
134class MyEvent
135{
136public:
137
138 MyEvent()
139 {
140 mEv.that = NULL;
141 };
142
143 /**
144 * Posts this event to the given message queue. This method may only be
145 * called once. @note On success, the event will be deleted automatically
146 * after it is delivered and handled. On failure, the event will delete
147 * itself before this method returns! The caller must not delete it in
148 * either case.
149 */
150 nsresult postTo(nsIEventQueue *aEventQ)
151 {
152 AssertReturn(mEv.that == NULL, NS_ERROR_FAILURE);
153 AssertReturn(aEventQ, NS_ERROR_FAILURE);
154 nsresult rv = aEventQ->InitEvent(&mEv.e, NULL,
155 eventHandler, eventDestructor);
156 if (NS_SUCCEEDED(rv))
157 {
158 mEv.that = this;
159 rv = aEventQ->PostEvent(&mEv.e);
160 if (NS_SUCCEEDED(rv))
161 return rv;
162 }
163 delete this;
164 return rv;
165 }
166
167 virtual void *handler() = 0;
168
169private:
170
171 struct Ev
172 {
173 PLEvent e;
174 MyEvent *that;
175 } mEv;
176
177 static void *PR_CALLBACK eventHandler(PLEvent *self)
178 {
179 return reinterpret_cast<Ev *>(self)->that->handler();
180 }
181
182 static void PR_CALLBACK eventDestructor(PLEvent *self)
183 {
184 delete reinterpret_cast<Ev *>(self)->that;
185 }
186};
187
188////////////////////////////////////////////////////////////////////////////////
189
190/**
191 * VirtualBox class factory that destroys the created instance right after
192 * the last reference to it is released by the client, and recreates it again
193 * when necessary (so VirtualBox acts like a singleton object).
194 */
195class VirtualBoxClassFactory : public VirtualBox
196{
197public:
198
199 virtual ~VirtualBoxClassFactory()
200 {
201 LogFlowFunc(("Deleting VirtualBox...\n"));
202
203 FinalRelease();
204 sInstance = NULL;
205
206 LogFlowFunc(("VirtualBox object deleted.\n"));
207 RTPrintf("Informational: VirtualBox object deleted.\n");
208 }
209
210 NS_IMETHOD_(nsrefcnt) Release()
211 {
212 /* we overload Release() to guarantee the VirtualBox destructor is
213 * always called on the main thread */
214
215 nsrefcnt count = VirtualBox::Release();
216
217 if (count == 1)
218 {
219 /* the last reference held by clients is being released
220 * (see GetInstance()) */
221
222 PRBool onMainThread = PR_TRUE;
223 nsCOMPtr<nsIEventQueue> q(gEventQ);
224 if (q)
225 {
226 q->IsOnCurrentThread(&onMainThread);
227 q = nsnull;
228 }
229
230 PRBool timerStarted = PR_FALSE;
231
232 /* sTimer is null if this call originates from FactoryDestructor()*/
233 if (sTimer != NULL)
234 {
235 LogFlowFunc(("Last VirtualBox instance was released.\n"));
236 LogFlowFunc(("Scheduling server shutdown in %u ms...\n",
237 gShutdownDelayMs));
238
239 /* make sure the previous timer (if any) is stopped;
240 * otherwise RTTimerStart() will definitely fail. */
241 RTTimerLRStop(sTimer);
242
243 int vrc = RTTimerLRStart(sTimer, gShutdownDelayMs * RT_NS_1MS_64);
244 AssertRC(vrc);
245 timerStarted = SUCCEEDED(vrc);
246 }
247 else
248 {
249 LogFlowFunc(("Last VirtualBox instance was released "
250 "on XPCOM shutdown.\n"));
251 Assert(onMainThread);
252 }
253
254 gAllowSigUsrQuit = PR_TRUE;
255
256 if (!timerStarted)
257 {
258 if (!onMainThread)
259 {
260 /* Failed to start the timer, post the shutdown event
261 * manually if not on the main thread already. */
262 ShutdownTimer(NULL, NULL, 0);
263 }
264 else
265 {
266 /* Here we come if:
267 *
268 * a) gEventQ is 0 which means either FactoryDestructor() is called
269 * or the IPC/DCONNECT shutdown sequence is initiated by the
270 * XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
271 * happens on the main thread.
272 *
273 * b) gEventQ has reported we're on the main thread. This means
274 * that DestructEventHandler() has been called, but another
275 * client was faster and requested VirtualBox again.
276 *
277 * In either case, there is nothing to do.
278 *
279 * Note: case b) is actually no more valid since we don't
280 * call Release() from DestructEventHandler() in this case
281 * any more. Thus, we assert below.
282 */
283
284 Assert(!gEventQ);
285 }
286 }
287 }
288
289 return count;
290 }
291
292 class MaybeQuitEvent : public MyEvent
293 {
294 /* called on the main thread */
295 void *handler()
296 {
297 LogFlowFuncEnter();
298
299 Assert(RTCritSectIsInitialized(&sLock));
300
301 /* stop accepting GetInstance() requests on other threads during
302 * possible destruction */
303 RTCritSectEnter(&sLock);
304
305 nsrefcnt count = 0;
306
307 /* sInstance is NULL here if it was deleted immediately after
308 * creation due to initialization error. See GetInstance(). */
309 if (sInstance != NULL)
310 {
311 /* Release the guard reference added in GetInstance() */
312 count = sInstance->Release();
313 }
314
315 if (count == 0)
316 {
317 if (gAutoShutdown)
318 {
319 Assert(sInstance == NULL);
320 LogFlowFunc(("Terminating the server process...\n"));
321 /* make it leave the event loop */
322 gKeepRunning = PR_FALSE;
323 }
324 else
325 LogFlowFunc(("No automatic shutdown.\n"));
326 }
327 else
328 {
329 /* This condition is quite rare: a new client happened to
330 * connect after this event has been posted to the main queue
331 * but before it started to process it. */
332 LogFlowFunc(("Destruction is canceled (refcnt=%d).\n", count));
333 }
334
335 RTCritSectLeave(&sLock);
336
337 LogFlowFuncLeave();
338 return NULL;
339 }
340 };
341
342 static void ShutdownTimer(RTTIMERLR hTimerLR, void *pvUser, uint64_t /*iTick*/)
343 {
344 NOREF(hTimerLR);
345 NOREF(pvUser);
346
347 /* A "too late" event is theoretically possible if somebody
348 * manually ended the server after a destruction has been scheduled
349 * and this method was so lucky that it got a chance to run before
350 * the timer was killed. */
351 nsCOMPtr<nsIEventQueue> q(gEventQ);
352 AssertReturnVoid(q);
353
354 /* post a quit event to the main queue */
355 MaybeQuitEvent *ev = new MaybeQuitEvent();
356 nsresult rv = ev->postTo(q);
357 NOREF(rv);
358
359 /* A failure above means we've been already stopped (for example
360 * by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
361 * will do the job. Nothing to do. */
362 }
363
364 static NS_IMETHODIMP FactoryConstructor()
365 {
366 LogFlowFunc(("\n"));
367
368 /* create a critsect to protect object construction */
369 if (RT_FAILURE(RTCritSectInit(&sLock)))
370 return NS_ERROR_OUT_OF_MEMORY;
371
372 int vrc = RTTimerLRCreateEx(&sTimer, 0, 0, ShutdownTimer, NULL);
373 if (RT_FAILURE(vrc))
374 {
375 LogFlowFunc(("Failed to create a timer! (vrc=%Rrc)\n", vrc));
376 return NS_ERROR_FAILURE;
377 }
378
379 return NS_OK;
380 }
381
382 static NS_IMETHODIMP FactoryDestructor()
383 {
384 LogFlowFunc(("\n"));
385
386 RTTimerLRDestroy(sTimer);
387 sTimer = NULL;
388
389 if (sInstance != NULL)
390 {
391 /* Either posting a destruction event failed for some reason (most
392 * likely, the quit event has been received before the last release),
393 * or the client has terminated abnormally w/o releasing its
394 * VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
395 * Release the guard reference we added in GetInstance(). */
396 sInstance->Release();
397 }
398
399 /* Destroy lock after releasing the VirtualBox instance, otherwise
400 * there are races with cleanup. */
401 RTCritSectDelete(&sLock);
402
403 return NS_OK;
404 }
405
406 static nsresult GetInstance(VirtualBox **inst)
407 {
408 LogFlowFunc(("Getting VirtualBox object...\n"));
409
410 RTCritSectEnter(&sLock);
411
412 if (!gKeepRunning)
413 {
414 LogFlowFunc(("Process termination requested first. Refusing.\n"));
415
416 RTCritSectLeave(&sLock);
417
418 /* this rv is what CreateInstance() on the client side returns
419 * when the server process stops accepting events. Do the same
420 * here. The client wrapper should attempt to start a new process in
421 * response to a failure from us. */
422 return NS_ERROR_ABORT;
423 }
424
425 nsresult rv = NS_OK;
426
427 if (sInstance == NULL)
428 {
429 LogFlowFunc(("Creating new VirtualBox object...\n"));
430 sInstance = new VirtualBoxClassFactory();
431 if (sInstance != NULL)
432 {
433 /* make an extra AddRef to take the full control
434 * on the VirtualBox destruction (see FinalRelease()) */
435 sInstance->AddRef();
436
437 sInstance->AddRef(); /* protect FinalConstruct() */
438 rv = sInstance->FinalConstruct();
439 RTPrintf("Informational: VirtualBox object created (rc=%Rhrc).\n", rv);
440 if (NS_FAILED(rv))
441 {
442 /* On failure diring VirtualBox initialization, delete it
443 * immediately on the current thread by releasing all
444 * references in order to properly schedule the server
445 * shutdown. Since the object is fully deleted here, there
446 * is a chance to fix the error and request a new
447 * instantiation before the server terminates. However,
448 * the main reason to maintain the shutdown delay on
449 * failure is to let the front-end completely fetch error
450 * info from a server-side IVirtualBoxErrorInfo object. */
451 sInstance->Release();
452 sInstance->Release();
453 Assert(sInstance == NULL);
454 }
455 else
456 {
457 /* On success, make sure the previous timer is stopped to
458 * cancel a scheduled server termination (if any). */
459 gAllowSigUsrQuit = PR_FALSE;
460 RTTimerLRStop(sTimer);
461 }
462 }
463 else
464 {
465 rv = NS_ERROR_OUT_OF_MEMORY;
466 }
467 }
468 else
469 {
470 LogFlowFunc(("Using existing VirtualBox object...\n"));
471 nsrefcnt count = sInstance->AddRef();
472 Assert(count > 1);
473
474 if (count == 2)
475 {
476 LogFlowFunc(("Another client has requested a reference to VirtualBox, canceling destruction...\n"));
477
478 /* make sure the previous timer is stopped */
479 gAllowSigUsrQuit = PR_FALSE;
480 RTTimerLRStop(sTimer);
481 }
482 }
483
484 *inst = sInstance;
485
486 RTCritSectLeave(&sLock);
487
488 return rv;
489 }
490
491private:
492
493 /* Don't be confused that sInstance is of the *ClassFactory type. This is
494 * actually a singleton instance (*ClassFactory inherits the singleton
495 * class; we combined them just for "simplicity" and used "static" for
496 * factory methods. *ClassFactory here is necessary for a couple of extra
497 * methods. */
498
499 static VirtualBoxClassFactory *sInstance;
500 static RTCRITSECT sLock;
501
502 static RTTIMERLR sTimer;
503};
504
505VirtualBoxClassFactory *VirtualBoxClassFactory::sInstance = NULL;
506RTCRITSECT VirtualBoxClassFactory::sLock;
507
508RTTIMERLR VirtualBoxClassFactory::sTimer = NIL_RTTIMERLR;
509
510NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR_WITH_RC(VirtualBox, VirtualBoxClassFactory::GetInstance)
511
512////////////////////////////////////////////////////////////////////////////////
513
514typedef NSFactoryDestructorProcPtr NSFactoryConstructorProcPtr;
515
516/**
517 * Enhanced module component information structure.
518 *
519 * nsModuleComponentInfo lacks the factory construction callback, here we add
520 * it. This callback is called straight after a nsGenericFactory instance is
521 * successfully created in RegisterSelfComponents.
522 */
523struct nsModuleComponentInfoPlusFactoryConstructor
524{
525 /** standard module component information */
526 const nsModuleComponentInfo *mpModuleComponentInfo;
527 /** (optional) Factory Construction Callback */
528 NSFactoryConstructorProcPtr mFactoryConstructor;
529};
530
531/////////////////////////////////////////////////////////////////////////////
532
533/**
534 * Helper function to register self components upon start-up
535 * of the out-of-proc server.
536 */
537static nsresult
538RegisterSelfComponents(nsIComponentRegistrar *registrar,
539 const nsModuleComponentInfoPlusFactoryConstructor *aComponents,
540 PRUint32 count)
541{
542 nsresult rc = NS_OK;
543 const nsModuleComponentInfoPlusFactoryConstructor *info = aComponents;
544 for (PRUint32 i = 0; i < count && NS_SUCCEEDED(rc); i++, info++)
545 {
546 /* skip components w/o a constructor */
547 if (!info->mpModuleComponentInfo->mConstructor)
548 continue;
549 /* create a new generic factory for a component and register it */
550 nsIGenericFactory *factory;
551 rc = NS_NewGenericFactory(&factory, info->mpModuleComponentInfo);
552 if (NS_SUCCEEDED(rc) && info->mFactoryConstructor)
553 {
554 rc = info->mFactoryConstructor();
555 if (NS_FAILED(rc))
556 NS_RELEASE(factory);
557 }
558 if (NS_SUCCEEDED(rc))
559 {
560 rc = registrar->RegisterFactory(info->mpModuleComponentInfo->mCID,
561 info->mpModuleComponentInfo->mDescription,
562 info->mpModuleComponentInfo->mContractID,
563 factory);
564 NS_RELEASE(factory);
565 }
566 }
567 return rc;
568}
569
570/////////////////////////////////////////////////////////////////////////////
571
572static ipcIService *gIpcServ = nsnull;
573static const char *g_pszPidFile = NULL;
574
575class ForceQuitEvent : public MyEvent
576{
577 void *handler()
578 {
579 LogFlowFunc(("\n"));
580
581 gKeepRunning = PR_FALSE;
582
583 if (g_pszPidFile)
584 RTFileDelete(g_pszPidFile);
585
586 return NULL;
587 }
588};
589
590static void signal_handler(int sig)
591{
592 nsCOMPtr<nsIEventQueue> q(gEventQ);
593 if (q && gKeepRunning)
594 {
595 if (sig == SIGUSR1)
596 {
597 if (gAllowSigUsrQuit)
598 {
599 VirtualBoxClassFactory::MaybeQuitEvent *ev = new VirtualBoxClassFactory::MaybeQuitEvent();
600 ev->postTo(q);
601 }
602 /* else do nothing */
603 }
604 else
605 {
606 /* post a force quit event to the queue */
607 ForceQuitEvent *ev = new ForceQuitEvent();
608 ev->postTo(q);
609 }
610 }
611}
612
613static nsresult vboxsvcSpawnDaemonByReExec(const char *pszPath, bool fAutoShutdown, const char *pszPidFile)
614{
615 PRFileDesc *readable = nsnull, *writable = nsnull;
616 PRProcessAttr *attr = nsnull;
617 nsresult rv = NS_ERROR_FAILURE;
618 PRFileDesc *devNull;
619 unsigned args_index = 0;
620 // The ugly casts are necessary because the PR_CreateProcessDetached has
621 // a const array of writable strings as a parameter. It won't write. */
622 char * args[1 + 1 + 2 + 1];
623 args[args_index++] = (char *)pszPath;
624 if (fAutoShutdown)
625 args[args_index++] = (char *)"--auto-shutdown";
626 if (pszPidFile)
627 {
628 args[args_index++] = (char *)"--pidfile";
629 args[args_index++] = (char *)pszPidFile;
630 }
631 args[args_index++] = 0;
632
633 // Use a pipe to determine when the daemon process is in the position
634 // to actually process requests. The daemon will write "READY" to the pipe.
635 if (PR_CreatePipe(&readable, &writable) != PR_SUCCESS)
636 goto end;
637 PR_SetFDInheritable(writable, PR_TRUE);
638
639 attr = PR_NewProcessAttr();
640 if (!attr)
641 goto end;
642
643 if (PR_ProcessAttrSetInheritableFD(attr, writable, VBOXSVC_STARTUP_PIPE_NAME) != PR_SUCCESS)
644 goto end;
645
646 devNull = PR_Open("/dev/null", PR_RDWR, 0);
647 if (!devNull)
648 goto end;
649
650 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardInput, devNull);
651 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardOutput, devNull);
652 PR_ProcessAttrSetStdioRedirect(attr, PR_StandardError, devNull);
653
654 if (PR_CreateProcessDetached(pszPath, (char * const *)args, nsnull, attr) != PR_SUCCESS)
655 goto end;
656
657 // Close /dev/null
658 PR_Close(devNull);
659 // Close the child end of the pipe to make it the only owner of the
660 // file descriptor, so that unexpected closing can be detected.
661 PR_Close(writable);
662 writable = nsnull;
663
664 char msg[10];
665 memset(msg, '\0', sizeof(msg));
666 if ( PR_Read(readable, msg, sizeof(msg)-1) != 5
667 || strcmp(msg, "READY"))
668 goto end;
669
670 rv = NS_OK;
671
672end:
673 if (readable)
674 PR_Close(readable);
675 if (writable)
676 PR_Close(writable);
677 if (attr)
678 PR_DestroyProcessAttr(attr);
679 return rv;
680}
681
682int main(int argc, char **argv)
683{
684 /*
685 * Initialize the VBox runtime without loading
686 * the support driver
687 */
688 int vrc = RTR3InitExe(argc, &argv, 0);
689 if (RT_FAILURE(vrc))
690 return RTMsgInitFailure(vrc);
691
692 static const RTGETOPTDEF s_aOptions[] =
693 {
694 { "--automate", 'a', RTGETOPT_REQ_NOTHING },
695 { "--auto-shutdown", 'A', RTGETOPT_REQ_NOTHING },
696 { "--daemonize", 'd', RTGETOPT_REQ_NOTHING },
697 { "--shutdown-delay", 'D', RTGETOPT_REQ_UINT32 },
698 { "--pidfile", 'p', RTGETOPT_REQ_STRING },
699 { "--logfile", 'F', RTGETOPT_REQ_STRING },
700 { "--logrotate", 'R', RTGETOPT_REQ_UINT32 },
701 { "--logsize", 'S', RTGETOPT_REQ_UINT64 },
702 { "--loginterval", 'I', RTGETOPT_REQ_UINT32 }
703 };
704
705 const char *pszLogFile = NULL;
706 uint32_t cHistory = 10; // enable log rotation, 10 files
707 uint32_t uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
708 uint64_t uHistoryFileSize = 100 * _1M; // max 100MB per file
709 bool fDaemonize = false;
710 PRFileDesc *daemon_pipe_wr = nsnull;
711
712 RTGETOPTSTATE GetOptState;
713 vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
714 AssertRC(vrc);
715
716 RTGETOPTUNION ValueUnion;
717 while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
718 {
719 switch (vrc)
720 {
721 case 'a':
722 /* --automate mode means we are started by XPCOM on
723 * demand. Daemonize ourselves and activate
724 * auto-shutdown. */
725 gAutoShutdown = true;
726 fDaemonize = true;
727 break;
728
729 case 'A':
730 /* --auto-shutdown mode means we're already daemonized. */
731 gAutoShutdown = true;
732 break;
733
734 case 'd':
735 fDaemonize = true;
736 break;
737
738 case 'D':
739 gShutdownDelayMs = ValueUnion.u32;
740 break;
741
742 case 'p':
743 g_pszPidFile = ValueUnion.psz;
744 break;
745
746 case 'F':
747 pszLogFile = ValueUnion.psz;
748 break;
749
750 case 'R':
751 cHistory = ValueUnion.u32;
752 break;
753
754 case 'S':
755 uHistoryFileSize = ValueUnion.u64;
756 break;
757
758 case 'I':
759 uHistoryFileTime = ValueUnion.u32;
760 break;
761
762 case 'h':
763 RTPrintf("no help\n");
764 return 1;
765
766 case 'V':
767 RTPrintf("%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
768 return 0;
769
770 default:
771 return RTGetOptPrintError(vrc, &ValueUnion);
772 }
773 }
774
775 if (fDaemonize)
776 {
777 vboxsvcSpawnDaemonByReExec(argv[0], gAutoShutdown, g_pszPidFile);
778 exit(126);
779 }
780
781 nsresult rc;
782
783 /** @todo Merge this code with svcmain.cpp (use Logging.cpp?). */
784 char szLogFile[RTPATH_MAX];
785 if (!pszLogFile)
786 {
787 vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
788 if (RT_SUCCESS(vrc))
789 vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
790 }
791 else
792 {
793 if (!RTStrPrintf(szLogFile, sizeof(szLogFile), "%s", pszLogFile))
794 vrc = VERR_NO_MEMORY;
795 }
796 if (RT_FAILURE(vrc))
797 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create logging file name, rc=%Rrc", vrc);
798
799 char szError[RTPATH_MAX + 128];
800 vrc = com::VBoxLogRelCreate("XPCOM Server", szLogFile,
801 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
802 VBOXSVC_LOG_DEFAULT, "VBOXSVC_RELEASE_LOG",
803 RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
804 cHistory, uHistoryFileTime, uHistoryFileSize,
805 szError, sizeof(szError));
806 if (RT_FAILURE(vrc))
807 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, vrc);
808
809 daemon_pipe_wr = PR_GetInheritedFD(VBOXSVC_STARTUP_PIPE_NAME);
810 RTEnvUnset("NSPR_INHERIT_FDS");
811
812 const nsModuleComponentInfo VirtualBoxInfo = {
813 "VirtualBox component",
814 NS_VIRTUALBOX_CID,
815 NS_VIRTUALBOX_CONTRACTID,
816 VirtualBoxConstructor, // constructor function
817 NULL, // registration function
818 NULL, // deregistration function
819 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
820 NS_CI_INTERFACE_GETTER_NAME(VirtualBoxWrap),
821 NULL, // language helper
822 &NS_CLASSINFO_NAME(VirtualBoxWrap),
823 0 // flags
824 };
825
826 const nsModuleComponentInfoPlusFactoryConstructor components[] = {
827 {
828 &VirtualBoxInfo,
829 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
830 }
831 };
832
833 do
834 {
835 rc = com::Initialize();
836 if (NS_FAILED(rc))
837 {
838 RTMsgError("Failed to initialize XPCOM! (rc=%Rhrc)\n", rc);
839 break;
840 }
841
842 nsCOMPtr<nsIComponentRegistrar> registrar;
843 rc = NS_GetComponentRegistrar(getter_AddRefs(registrar));
844 if (NS_FAILED(rc))
845 {
846 RTMsgError("Failed to get component registrar! (rc=%Rhrc)", rc);
847 break;
848 }
849
850 registrar->AutoRegister(nsnull);
851 rc = RegisterSelfComponents(registrar, components,
852 NS_ARRAY_LENGTH(components));
853 if (NS_FAILED(rc))
854 {
855 RTMsgError("Failed to register server components! (rc=%Rhrc)", rc);
856 break;
857 }
858
859 /* get the main thread's event queue (afaik, the dconnect service always
860 * gets created upon XPCOM startup, so it will use the main (this)
861 * thread's event queue to receive IPC events) */
862 rc = NS_GetMainEventQ(getter_AddRefs(gEventQ));
863 if (NS_FAILED(rc))
864 {
865 RTMsgError("Failed to get the main event queue! (rc=%Rhrc)", rc);
866 break;
867 }
868
869 nsCOMPtr<ipcIService> ipcServ(do_GetService(IPC_SERVICE_CONTRACTID, &rc));
870 if (NS_FAILED(rc))
871 {
872 RTMsgError("Failed to get IPC service! (rc=%Rhrc)", rc);
873 break;
874 }
875
876 NS_ADDREF(gIpcServ = ipcServ);
877
878 LogFlowFunc(("Will use \"%s\" as server name.\n", VBOXSVC_IPC_NAME));
879
880 rc = gIpcServ->AddName(VBOXSVC_IPC_NAME);
881 if (NS_FAILED(rc))
882 {
883 LogFlowFunc(("Failed to register the server name (rc=%Rhrc (%08X))!\n"
884 "Is another server already running?\n", rc, rc));
885
886 RTMsgError("Failed to register the server name \"%s\" (rc=%Rhrc)!\n"
887 "Is another server already running?\n",
888 VBOXSVC_IPC_NAME, rc);
889 NS_RELEASE(gIpcServ);
890 break;
891 }
892
893 {
894 /* setup signal handling to convert some signals to a quit event */
895 struct sigaction sa;
896 sa.sa_handler = signal_handler;
897 sigemptyset(&sa.sa_mask);
898 sa.sa_flags = 0;
899 sigaction(SIGINT, &sa, NULL);
900 sigaction(SIGQUIT, &sa, NULL);
901 sigaction(SIGTERM, &sa, NULL);
902 sigaction(SIGTRAP, &sa, NULL);
903 sigaction(SIGUSR1, &sa, NULL);
904 }
905
906 {
907 char szBuf[80];
908 int iSize;
909
910 iSize = RTStrPrintf(szBuf, sizeof(szBuf),
911 VBOX_PRODUCT" XPCOM Server Version "
912 VBOX_VERSION_STRING);
913 for (int i = iSize; i > 0; i--)
914 putchar('*');
915 RTPrintf("\n%s\n", szBuf);
916 RTPrintf("(C) 2004-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
917 "All rights reserved.\n");
918#ifdef DEBUG
919 RTPrintf("Debug version.\n");
920#endif
921 }
922
923 if (daemon_pipe_wr != nsnull)
924 {
925 RTPrintf("\nStarting event loop....\n[send TERM signal to quit]\n");
926 /* now we're ready, signal the parent process */
927 PR_Write(daemon_pipe_wr, "READY", strlen("READY"));
928 /* close writing end of the pipe, its job is done */
929 PR_Close(daemon_pipe_wr);
930 }
931 else
932 RTPrintf("\nStarting event loop....\n[press Ctrl-C to quit]\n");
933
934 if (g_pszPidFile)
935 {
936 RTFILE hPidFile = NIL_RTFILE;
937 vrc = RTFileOpen(&hPidFile, g_pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_NONE);
938 if (RT_SUCCESS(vrc))
939 {
940 char szBuf[32];
941 const char *lf = "\n";
942 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
943 RTFileWrite(hPidFile, szBuf, strlen(szBuf), NULL);
944 RTFileWrite(hPidFile, lf, strlen(lf), NULL);
945 RTFileClose(hPidFile);
946 }
947 }
948
949 // Increase the file table size to 10240 or as high as possible.
950 struct rlimit lim;
951 if (getrlimit(RLIMIT_NOFILE, &lim) == 0)
952 {
953 if ( lim.rlim_cur < 10240
954 && lim.rlim_cur < lim.rlim_max)
955 {
956 lim.rlim_cur = RT_MIN(lim.rlim_max, 10240);
957 if (setrlimit(RLIMIT_NOFILE, &lim) == -1)
958 RTPrintf("WARNING: failed to increase file descriptor limit. (%d)\n", errno);
959 }
960 }
961 else
962 RTPrintf("WARNING: failed to obtain per-process file-descriptor limit (%d).\n", errno);
963
964 PLEvent *ev;
965 while (gKeepRunning)
966 {
967 gEventQ->WaitForEvent(&ev);
968 gEventQ->HandleEvent(ev);
969 }
970
971 /* stop accepting new events. Clients that happen to resolve our
972 * name and issue a CreateInstance() request after this point will
973 * get NS_ERROR_ABORT once we handle the remaining messages. As a
974 * result, they should try to start a new server process. */
975 gEventQ->StopAcceptingEvents();
976
977 /* unregister ourselves. After this point, clients will start a new
978 * process because they won't be able to resolve the server name.*/
979 gIpcServ->RemoveName(VBOXSVC_IPC_NAME);
980
981 /* process any remaining events. These events may include
982 * CreateInstance() requests received right before we called
983 * StopAcceptingEvents() above, and those will fail. */
984 gEventQ->ProcessPendingEvents();
985
986 RTPrintf("Terminated event loop.\n");
987 }
988 while (0); // this scopes the nsCOMPtrs
989
990 NS_IF_RELEASE(gIpcServ);
991 gEventQ = nsnull;
992
993 /* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
994
995 LogFlowFunc(("Calling com::Shutdown()...\n"));
996 rc = com::Shutdown();
997 LogFlowFunc(("Finished com::Shutdown() (rc=%Rhrc)\n", rc));
998
999 if (NS_FAILED(rc))
1000 RTMsgError("Failed to shutdown XPCOM! (rc=%Rhrc)", rc);
1001
1002 RTPrintf("XPCOM server has shutdown.\n");
1003
1004 if (g_pszPidFile)
1005 RTFileDelete(g_pszPidFile);
1006
1007 return 0;
1008}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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