VirtualBox

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

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

*: spelling fixes, thanks Timeless!

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

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