VirtualBox

source: vbox/trunk/src/VBox/Main/linux/server.cpp@ 1471

Last change on this file since 1471 was 1471, checked in by vboxsync, 18 years ago

Main: XPCOM: Initial implementation of auto-startable "out-of-proc" VirtualBox component (VBoxSVC).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.6 KB
Line 
1/** @file
2 *
3 * XPCOM server process start point
4 */
5
6/*
7 * Copyright (C) 2006 InnoTek Systemberatung GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22#include <ipcIService.h>
23#include <ipcCID.h>
24
25#include <nsIServiceManager.h>
26#include <nsIComponentRegistrar.h>
27
28#include <nsXPCOMGlue.h>
29#include <nsEventQueueUtils.h>
30
31// for NS_InitXPCOM2 with bin dir parameter
32#include <nsEmbedString.h>
33#include <nsIFile.h>
34#include <nsILocalFile.h>
35
36#include "Logging.h"
37
38#include <iprt/runtime.h>
39#include <iprt/path.h>
40#include <iprt/critsect.h>
41#include <iprt/timer.h>
42
43#include <VBox/param.h>
44#include <VBox/version.h>
45
46// for nsMyFactory
47#include "nsIGenericFactory.h"
48#include "nsIClassInfo.h"
49
50#include <stdio.h>
51
52// for the signal handler
53#include <signal.h>
54#include <stdlib.h>
55#include <unistd.h>
56#include <errno.h>
57#include <getopt.h>
58
59// for the backtrace signal handler
60#if defined(DEBUG) && defined(__LINUX__)
61# define USE_BACKTRACE
62#endif
63#if defined(USE_BACKTRACE)
64# include <execinfo.h>
65// get REG_EIP/RIP from ucontext.h
66# ifndef __USE_GNU
67# define __USE_GNU
68# endif
69# include <ucontext.h>
70# ifdef __AMD64__
71# define REG_PC REG_RIP
72# else
73# define REG_PC REG_EIP
74# endif
75#endif
76
77/////////////////////////////////////////////////////////////////////////////
78// VirtualBox component instantiation
79/////////////////////////////////////////////////////////////////////////////
80
81#include <nsIGenericFactory.h>
82
83#include <VirtualBox_XPCOM.h>
84#include <VirtualBoxImpl.h>
85#include <MachineImpl.h>
86#include <SnapshotImpl.h>
87#include <HardDiskImpl.h>
88#include <ProgressImpl.h>
89#include <DVDDriveImpl.h>
90#include <FloppyDriveImpl.h>
91#include <VRDPServerImpl.h>
92#include <DVDImageImpl.h>
93#include <FloppyImageImpl.h>
94#include <SharedFolderImpl.h>
95#include <HostImpl.h>
96#include <HostDVDDriveImpl.h>
97#include <HostFloppyDriveImpl.h>
98#include <HostUSBDeviceImpl.h>
99#include <GuestOSTypeImpl.h>
100#include <NetworkAdapterImpl.h>
101#include <USBControllerImpl.h>
102#include <USBDeviceImpl.h>
103#include <AudioAdapterImpl.h>
104#include <SystemPropertiesImpl.h>
105#include <Collection.h>
106
107// implement nsISupports parts of our objects with support for nsIClassInfo
108NS_DECL_CLASSINFO(VirtualBox)
109NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VirtualBox, IVirtualBox)
110NS_DECL_CLASSINFO(Machine)
111NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Machine, IMachine)
112NS_DECL_CLASSINFO(SessionMachine)
113NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
114NS_DECL_CLASSINFO(SnapshotMachine)
115NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
116NS_DECL_CLASSINFO(Snapshot)
117NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Snapshot, ISnapshot)
118NS_DECL_CLASSINFO(HardDisk)
119NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HardDisk, IHardDisk)
120NS_DECL_CLASSINFO(HVirtualDiskImage)
121NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HVirtualDiskImage, IHardDisk, IVirtualDiskImage)
122NS_DECL_CLASSINFO(HISCSIHardDisk)
123NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HISCSIHardDisk, IHardDisk, IISCSIHardDisk)
124NS_DECL_CLASSINFO(HVMDKImage)
125NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HVMDKImage, IHardDisk, IVMDKImage)
126NS_DECL_CLASSINFO(HardDiskAttachment)
127NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HardDiskAttachment, IHardDiskAttachment)
128NS_DECL_CLASSINFO(Progress)
129NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Progress, IProgress)
130NS_DECL_CLASSINFO(CombinedProgress)
131NS_IMPL_THREADSAFE_ISUPPORTS1_CI(CombinedProgress, IProgress)
132NS_DECL_CLASSINFO(DVDDrive)
133NS_IMPL_THREADSAFE_ISUPPORTS1_CI(DVDDrive, IDVDDrive)
134NS_DECL_CLASSINFO(FloppyDrive)
135NS_IMPL_THREADSAFE_ISUPPORTS1_CI(FloppyDrive, IFloppyDrive)
136NS_DECL_CLASSINFO(SharedFolder)
137NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SharedFolder, ISharedFolder)
138#ifdef VBOX_VRDP
139NS_DECL_CLASSINFO(VRDPServer)
140NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VRDPServer, IVRDPServer)
141#endif
142NS_DECL_CLASSINFO(DVDImage)
143NS_IMPL_THREADSAFE_ISUPPORTS1_CI(DVDImage, IDVDImage)
144NS_DECL_CLASSINFO(FloppyImage)
145NS_IMPL_THREADSAFE_ISUPPORTS1_CI(FloppyImage, IFloppyImage)
146NS_DECL_CLASSINFO(Host)
147NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Host, IHost)
148NS_DECL_CLASSINFO(HostDVDDrive)
149NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostDVDDrive, IHostDVDDrive)
150NS_DECL_CLASSINFO(HostFloppyDrive)
151NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostFloppyDrive, IHostFloppyDrive)
152NS_DECL_CLASSINFO(GuestOSType)
153NS_IMPL_THREADSAFE_ISUPPORTS1_CI(GuestOSType, IGuestOSType)
154NS_DECL_CLASSINFO(NetworkAdapter)
155NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NetworkAdapter, INetworkAdapter)
156NS_DECL_CLASSINFO(USBController)
157NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBController, IUSBController)
158NS_DECL_CLASSINFO(USBDeviceFilter)
159NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBDeviceFilter, IUSBDeviceFilter)
160NS_DECL_CLASSINFO(HostUSBDevice)
161NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDevice, IUSBDevice, IHostUSBDevice)
162NS_DECL_CLASSINFO(HostUSBDeviceFilter)
163NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostUSBDeviceFilter, IHostUSBDeviceFilter)
164NS_DECL_CLASSINFO(AudioAdapter)
165NS_IMPL_THREADSAFE_ISUPPORTS1_CI(AudioAdapter, IAudioAdapter)
166NS_DECL_CLASSINFO(SystemProperties)
167NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SystemProperties, ISystemProperties)
168NS_DECL_CLASSINFO(BIOSSettings)
169NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BIOSSettings, IBIOSSettings)
170
171// collections and enumerators
172COM_IMPL_READONLY_ENUM_AND_COLLECTION(Machine)
173COM_IMPL_READONLY_ENUM_AND_COLLECTION(Snapshot)
174COM_IMPL_READONLY_ENUM_AND_COLLECTION(HardDiskAttachment)
175COM_IMPL_READONLY_ENUM_AND_COLLECTION(GuestOSType)
176COM_IMPL_READONLY_ENUM_AND_COLLECTION(USBDeviceFilter)
177COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostDVDDrive)
178COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostFloppyDrive)
179COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostUSBDevice)
180COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostUSBDeviceFilter)
181COM_IMPL_READONLY_ENUM_AND_COLLECTION(HardDisk)
182COM_IMPL_READONLY_ENUM_AND_COLLECTION(DVDImage)
183COM_IMPL_READONLY_ENUM_AND_COLLECTION(FloppyImage)
184COM_IMPL_READONLY_ENUM_AND_COLLECTION(SharedFolder)
185
186COM_IMPL_READONLY_ENUM_AND_COLLECTION_AS(Progress, IProgress)
187COM_IMPL_READONLY_ENUM_AND_COLLECTION_AS(IfaceUSBDevice, IUSBDevice)
188
189////////////////////////////////////////////////////////////////////////////////
190
191enum
192{
193 /* Delay before shutting down the VirtualBox server after the last
194 * VirtualBox instance is released, in ms */
195 VBoxSVC_ShutdownDelay = 5000,
196};
197
198static bool gAutoShutdown = false;
199
200static nsIEventQueue* gEventQ = nsnull;
201static PRBool volatile gKeepRunning = PR_TRUE;
202
203////////////////////////////////////////////////////////////////////////////////
204
205/**
206 * VirtualBox class factory that destroys the created instance right after
207 * the last reference to it is released by the client, and recreates it again
208 * when necessary (so VirtualBox acts like a singleton object).
209 */
210class VirtualBoxClassFactory : public VirtualBox
211{
212public:
213
214 virtual ~VirtualBoxClassFactory()
215 {
216 LogFlowFunc (("Deleting VirtualBox...\n"));
217
218 FinalRelease();
219 sInstance = 0;
220
221 LogFlowFunc (("VirtualBox object deleted.\n"));
222 printf ("Informational: VirtualBox object deleted.\n");
223
224 /* Instruct the main event loop to terminate. Note that it's enough
225 * to set gKeepRunning to false because we are on the main thread
226 * already (i.e. no need to post events there). */
227 if (gAutoShutdown)
228 gKeepRunning = PR_FALSE;
229 }
230
231 NS_IMETHOD_(nsrefcnt) Release()
232 {
233 /* we overload Release() to guarantee the VirtualBox destructor is
234 * always called on the main thread */
235
236 nsrefcnt count = VirtualBox::Release();
237
238 if (count == 1)
239 {
240 /* the last reference held by clients is being released
241 * (see GetInstance()) */
242
243 PRBool onMainThread = PR_TRUE;
244 if (gEventQ)
245 gEventQ->IsOnCurrentThread (&onMainThread);
246
247 if (!onMainThread)
248 {
249 LogFlowFunc (("Last VirtualBox instance was released, "
250 "scheduling server shutdown in %d ms...\n",
251 VBoxSVC_ShutdownDelay));
252
253 /* Start a shutdown timer to provide some delay */
254 int vrc = RTTimerStart (sTimer, 0);
255/// @todo uncomment when implemented
256// AssertRC (vrc);
257 if (VBOX_FAILURE (vrc))
258 {
259 /* failed to start the timer, post the shutdown event
260 * manually */
261 ShutdownTimer (NULL, NULL);
262 }
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 * We have nothing to do in these cases.
278 */
279 }
280 }
281
282 return count;
283 }
284
285 static void *PR_CALLBACK DestructEventHandler (PLEvent* self)
286 {
287 Assert (RTCritSectIsInitialized (&sLock));
288
289 /* stop accepting GetInstance() requests during possible destruction */
290 RTCritSectEnter (&sLock);
291
292 Assert (sInstance);
293
294 /* release the reference we added in GetInstance()
295 * (will call the destructor if nobody referenced us again) */
296 nsrefcnt count = sInstance->Release();
297 if (count != 0)
298 {
299 LogFlowFunc (("Destruction is canceled.\n"));
300 }
301
302 RTCritSectLeave (&sLock);
303
304 return 0;
305 }
306
307 static void PR_CALLBACK DestructEventDestructor (PLEvent* self)
308 {
309 delete self;
310 }
311
312 static void ShutdownTimer (PRTTIMER pTimer, void *pvUser)
313 {
314 NOREF (pvUser);
315
316 if (pTimer)
317 {
318 /* it's a single shot timer */
319 int vrc = RTTimerStop (pTimer);
320/// @todo uncomment when implemented
321// AssertRC (vrc);
322 NOREF (vrc);
323 }
324
325 /* post a destruction event to the main thread to safely release the
326 * extra reference added in VirtualBoxClassFactory::GetInstance() */
327
328 LogFlowFunc (("Posting VirtualBox destruction & shtutdown event...\n"));
329
330 PLEvent *ev = new PLEvent;
331 gEventQ->InitEvent (ev, NULL, DestructEventHandler,
332 DestructEventDestructor);
333 nsresult rv = gEventQ->PostEvent (ev);
334 if (NS_FAILED (rv))
335 {
336 /* this means we've been already stopped (for example
337 * by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
338 * will do the job. */
339 PL_DestroyEvent (ev);
340 }
341 }
342
343 static NS_IMETHODIMP FactoryConstructor()
344 {
345 LogFlowFunc (("\n"));
346
347 /* create a critsect to protect object construction */
348 if (VBOX_FAILURE (RTCritSectInit (&sLock)))
349 return NS_ERROR_OUT_OF_MEMORY;
350
351 int vrc = RTTimerCreateEx (&sTimer,
352 uint64_t (VBoxSVC_ShutdownDelay) * 1000000,
353 0, ShutdownTimer, NULL);
354 NOREF (vrc);
355/// @todo uncomment when implemented
356// if (VBOX_FAILURE (vrc))
357// {
358// LogFlowFunc (("Failed to create a timer! (vrc=%Vrc)\n", vrc));
359// return NS_ERROR_FAILURE;
360// }
361
362 return NS_OK;
363 }
364
365 static NS_IMETHODIMP FactoryDestructor()
366 {
367 LogFlowFunc (("\n"));
368
369 RTTimerDestroy (sTimer);
370 sTimer = NULL;
371
372 RTCritSectDelete (&sLock);
373
374 if (sInstance)
375 {
376 /* Either posting a destruction event falied for some reason (most
377 * likely, the quit event has been received before the last release),
378 * or the client has terminated abnormally w/o releasing its
379 * VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
380 * Release the extra reference we added in GetInstance(). */
381 sInstance->Release();
382 }
383
384 return NS_OK;
385 }
386
387 static nsresult GetInstance (VirtualBox **inst)
388 {
389 LogFlowFunc (("Getting VirtualBox object...\n"));
390
391 RTCritSectEnter (&sLock);
392
393 int rv = NS_OK;
394
395 if (sInstance == 0)
396 {
397 LogFlowFunc (("Creating new VirtualBox object...\n"));
398 sInstance = new VirtualBoxClassFactory();
399 if (sInstance)
400 {
401 /* make an extra AddRef to take the full control
402 * on the VirtualBox destruction (see FinalRelease()) */
403 sInstance->AddRef();
404
405 sInstance->AddRef(); /* protect FinalConstruct() */
406 rv = sInstance->FinalConstruct();
407 printf ("Informational: VirtualBox object created (rc=%08X).\n", rv);
408 if (NS_FAILED (rv))
409 {
410 /* on failure diring VirtualBox initialization, delete it
411 * immediately on the current thread, ignoring the reference
412 * count (VirtualBox should be aware of that meaning that it
413 * has already completely unintialized itself in this
414 * case) */
415 LogFlowFunc (("VirtualBox creation failed "
416 "(rc=%08X), deleting immediately...\n", rv));
417 delete sInstance;
418 sInstance = 0;
419 }
420 }
421 else
422 {
423 rv = NS_ERROR_OUT_OF_MEMORY;
424 }
425 }
426 else
427 {
428 LogFlowFunc (("Using existing VirtualBox object...\n"));
429 nsrefcnt count = sInstance->AddRef();
430 Assert (count > 1);
431
432 if (count == 2)
433 {
434 LogFlowFunc (("Another client has requested "
435 "a reference of VirtualBox scheduled for destruction, "
436 "canceling detruction...\n"));
437
438 /* add a reference to compensate one that DestructEventHandler()
439 * will release */
440 sInstance->AddRef();
441 }
442 }
443
444 *inst = sInstance;
445
446 RTCritSectLeave (&sLock);
447
448 return rv;
449 }
450
451private:
452
453 static VirtualBox *sInstance;
454 static RTCRITSECT sLock;
455
456 static PRTTIMER sTimer;
457};
458
459VirtualBox *VirtualBoxClassFactory::sInstance = 0;
460RTCRITSECT VirtualBoxClassFactory::sLock = {0};
461
462PRTTIMER VirtualBoxClassFactory::sTimer = NULL;
463
464NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR_WITH_RC
465 (VirtualBox, VirtualBoxClassFactory::GetInstance)
466
467////////////////////////////////////////////////////////////////////////////////
468
469typedef NSFactoryDestructorProcPtr NSFactoryConsructorProcPtr;
470
471/**
472 * Enhanced module component information structure.
473 * nsModuleComponentInfo lacks the factory construction callback,
474 * here we add it. This callback is called by NS_NewMyFactory() after
475 * a nsMyFactory instance is successfully created.
476 */
477struct nsMyModuleComponentInfo : nsModuleComponentInfo
478{
479 nsMyModuleComponentInfo () {}
480 nsMyModuleComponentInfo (int) {}
481
482 nsMyModuleComponentInfo (
483 const char* aDescription,
484 const nsCID& aCID,
485 const char* aContractID,
486 NSConstructorProcPtr aConstructor,
487 NSRegisterSelfProcPtr aRegisterSelfProc,
488 NSUnregisterSelfProcPtr aUnregisterSelfProc,
489 NSFactoryDestructorProcPtr aFactoryDestructor,
490 NSGetInterfacesProcPtr aGetInterfacesProc,
491 NSGetLanguageHelperProcPtr aGetLanguageHelperProc,
492 nsIClassInfo ** aClassInfoGlobal,
493 PRUint32 aFlags,
494 NSFactoryConsructorProcPtr aFactoryConstructor)
495 {
496 mDescription = aDescription;
497 mCID = aCID;
498 mContractID = aContractID;
499 mConstructor = aConstructor;
500 mRegisterSelfProc = aRegisterSelfProc;
501 mUnregisterSelfProc = aUnregisterSelfProc;
502 mFactoryDestructor = aFactoryDestructor;
503 mGetInterfacesProc = aGetInterfacesProc;
504 mGetLanguageHelperProc = aGetLanguageHelperProc;
505 mClassInfoGlobal = aClassInfoGlobal;
506 mFlags = aFlags;
507 mFactoryConstructor = aFactoryConstructor;
508 }
509
510 /** (optional) Factory Construction Callback */
511 NSFactoryConsructorProcPtr mFactoryConstructor;
512};
513
514////////////////////////////////////////////////////////////////////////////////
515
516static const nsMyModuleComponentInfo components[] =
517{
518 nsMyModuleComponentInfo (
519 "VirtualBox component",
520 (nsCID) NS_VIRTUALBOX_CID,
521 NS_VIRTUALBOX_CONTRACTID,
522 VirtualBoxConstructor, // constructor funcion
523 NULL, // registration function
524 NULL, // deregistration function
525 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
526 NS_CI_INTERFACE_GETTER_NAME(VirtualBox),
527 NULL, // language helper
528 &NS_CLASSINFO_NAME(VirtualBox),
529 0, // flags
530 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
531 )
532};
533
534/////////////////////////////////////////////////////////////////////////////
535
536/**
537 * Generic component factory.
538 *
539 * The code below is stolen from nsGenericFactory.h / nsGenericFactory.cpp,
540 * because we get a segmentation fault for some unknown reason when VBoxSVC
541 * starts up (somewhere during the initialization of the libipcdc.so module)
542 * when we just reference XPCOM's NS_NewGenericFactory() from here (i.e. even
543 * before actually calling it) and run VBoxSVC using the debug XPCOM
544 * libraries.
545 *
546 * Actually, I know why, but I find it too stupid even to discuss.
547 */
548class nsMyFactory : public nsIGenericFactory, public nsIClassInfo {
549public:
550 NS_DEFINE_STATIC_CID_ACCESSOR(NS_GENERICFACTORY_CID);
551
552 nsMyFactory(const nsModuleComponentInfo *info = NULL);
553
554 NS_DECL_ISUPPORTS
555 NS_DECL_NSICLASSINFO
556
557 /* nsIGenericFactory methods */
558 NS_IMETHOD SetComponentInfo(const nsModuleComponentInfo *info);
559 NS_IMETHOD GetComponentInfo(const nsModuleComponentInfo **infop);
560
561 NS_IMETHOD CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult);
562
563 NS_IMETHOD LockFactory(PRBool aLock);
564
565 static NS_METHOD Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr);
566private:
567 ~nsMyFactory();
568
569 const nsModuleComponentInfo *mInfo;
570};
571
572nsMyFactory::nsMyFactory(const nsModuleComponentInfo *info)
573 : mInfo(info)
574{
575 if (mInfo && mInfo->mClassInfoGlobal)
576 *mInfo->mClassInfoGlobal = NS_STATIC_CAST(nsIClassInfo *, this);
577}
578
579nsMyFactory::~nsMyFactory()
580{
581 if (mInfo) {
582 if (mInfo->mFactoryDestructor)
583 mInfo->mFactoryDestructor();
584 if (mInfo->mClassInfoGlobal)
585 *mInfo->mClassInfoGlobal = 0;
586 }
587}
588
589NS_IMPL_THREADSAFE_ISUPPORTS3(nsMyFactory,
590 nsIGenericFactory,
591 nsIFactory,
592 nsIClassInfo)
593
594NS_IMETHODIMP nsMyFactory::CreateInstance(nsISupports *aOuter,
595 REFNSIID aIID, void **aResult)
596{
597 if (mInfo->mConstructor)
598 return mInfo->mConstructor(aOuter, aIID, aResult);
599
600 return NS_ERROR_FACTORY_NOT_REGISTERED;
601}
602
603NS_IMETHODIMP nsMyFactory::LockFactory(PRBool aLock)
604{
605 // XXX do we care if (mInfo->mFlags & THREADSAFE)?
606 return NS_OK;
607}
608
609NS_IMETHODIMP nsMyFactory::GetInterfaces(PRUint32 *countp,
610 nsIID* **array)
611{
612 if (!mInfo->mGetInterfacesProc) {
613 *countp = 0;
614 *array = nsnull;
615 return NS_OK;
616 }
617 return mInfo->mGetInterfacesProc(countp, array);
618}
619
620NS_IMETHODIMP nsMyFactory::GetHelperForLanguage(PRUint32 language,
621 nsISupports **helper)
622{
623 if (mInfo->mGetLanguageHelperProc)
624 return mInfo->mGetLanguageHelperProc(language, helper);
625 *helper = nsnull;
626 return NS_OK;
627}
628
629NS_IMETHODIMP nsMyFactory::GetContractID(char **aContractID)
630{
631 if (mInfo->mContractID) {
632 *aContractID = (char *)nsMemory::Alloc(strlen(mInfo->mContractID) + 1);
633 if (!*aContractID)
634 return NS_ERROR_OUT_OF_MEMORY;
635 strcpy(*aContractID, mInfo->mContractID);
636 } else {
637 *aContractID = nsnull;
638 }
639 return NS_OK;
640}
641
642NS_IMETHODIMP nsMyFactory::GetClassDescription(char * *aClassDescription)
643{
644 if (mInfo->mDescription) {
645 *aClassDescription = (char *)
646 nsMemory::Alloc(strlen(mInfo->mDescription) + 1);
647 if (!*aClassDescription)
648 return NS_ERROR_OUT_OF_MEMORY;
649 strcpy(*aClassDescription, mInfo->mDescription);
650 } else {
651 *aClassDescription = nsnull;
652 }
653 return NS_OK;
654}
655
656NS_IMETHODIMP nsMyFactory::GetClassID(nsCID * *aClassID)
657{
658 *aClassID =
659 NS_REINTERPRET_CAST(nsCID*,
660 nsMemory::Clone(&mInfo->mCID, sizeof mInfo->mCID));
661 if (! *aClassID)
662 return NS_ERROR_OUT_OF_MEMORY;
663 return NS_OK;
664}
665
666NS_IMETHODIMP nsMyFactory::GetClassIDNoAlloc(nsCID *aClassID)
667{
668 *aClassID = mInfo->mCID;
669 return NS_OK;
670}
671
672NS_IMETHODIMP nsMyFactory::GetImplementationLanguage(PRUint32 *langp)
673{
674 *langp = nsIProgrammingLanguage::CPLUSPLUS;
675 return NS_OK;
676}
677
678NS_IMETHODIMP nsMyFactory::GetFlags(PRUint32 *flagsp)
679{
680 *flagsp = mInfo->mFlags;
681 return NS_OK;
682}
683
684// nsIGenericFactory: component-info accessors
685NS_IMETHODIMP nsMyFactory::SetComponentInfo(const nsModuleComponentInfo *info)
686{
687 if (mInfo && mInfo->mClassInfoGlobal)
688 *mInfo->mClassInfoGlobal = 0;
689 mInfo = info;
690 if (mInfo && mInfo->mClassInfoGlobal)
691 *mInfo->mClassInfoGlobal = NS_STATIC_CAST(nsIClassInfo *, this);
692 return NS_OK;
693}
694
695NS_IMETHODIMP nsMyFactory::GetComponentInfo(const nsModuleComponentInfo **infop)
696{
697 *infop = mInfo;
698 return NS_OK;
699}
700
701NS_METHOD nsMyFactory::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr)
702{
703 // sorry, aggregation not spoken here.
704 nsresult res = NS_ERROR_NO_AGGREGATION;
705 if (outer == NULL) {
706 nsMyFactory* factory = new nsMyFactory;
707 if (factory != NULL) {
708 res = factory->QueryInterface(aIID, aInstancePtr);
709 if (res != NS_OK)
710 delete factory;
711 } else {
712 res = NS_ERROR_OUT_OF_MEMORY;
713 }
714 }
715 return res;
716}
717
718/**
719 * Instantiates a new factory and calls
720 * nsMyModuleComponentInfo::mFactoryConstructor.
721 */
722NS_COM nsresult
723NS_NewMyFactory(nsIGenericFactory* *result,
724 const nsMyModuleComponentInfo *info)
725{
726 nsresult rv;
727 nsMyFactory* fact;
728 rv = nsMyFactory::Create(NULL, NS_GET_IID(nsIGenericFactory), (void**)&fact);
729 if (NS_FAILED(rv)) return rv;
730 rv = fact->SetComponentInfo(info);
731 if (NS_FAILED(rv)) goto error;
732 if (info && info->mFactoryConstructor) {
733 rv = info->mFactoryConstructor();
734 if (NS_FAILED(rv)) goto error;
735 }
736 *result = fact;
737 return rv;
738
739 error:
740 NS_RELEASE(fact);
741 return rv;
742}
743
744/////////////////////////////////////////////////////////////////////////////
745
746/**
747 * Hhelper function to register self components upon start-up
748 * of the out-of-proc server.
749 */
750static nsresult
751RegisterSelfComponents (nsIComponentRegistrar *registrar,
752 const nsMyModuleComponentInfo *components,
753 PRUint32 count)
754{
755 nsresult rc = NS_OK;
756 const nsMyModuleComponentInfo *info = components;
757 for (PRUint32 i = 0; i < count && NS_SUCCEEDED (rc); i++, info++)
758 {
759 /* skip components w/o a constructor */
760 if (!info->mConstructor) continue;
761 /* create a new generic factory for a component and register it */
762 nsIGenericFactory *factory;
763 rc = NS_NewGenericFactory (&factory, info);
764 rc = NS_NewMyFactory (&factory, info);
765 if (NS_SUCCEEDED (rc))
766 {
767 rc = registrar->RegisterFactory (info->mCID,
768 info->mDescription,
769 info->mContractID,
770 factory);
771 factory->Release();
772 }
773 }
774 return rc;
775}
776
777/////////////////////////////////////////////////////////////////////////////
778
779static ipcIService *gIpcServ = nsnull;
780static char *pszPidFile = NULL;
781
782void* PR_CALLBACK quitEventHandler (PLEvent* self) { gKeepRunning = PR_FALSE; return 0; }
783void PR_CALLBACK quitEventDestructor (PLEvent* self) { delete self; }
784
785static void signal_handler (int sig)
786{
787 if (gEventQ && gKeepRunning)
788 {
789 /* post a quit event to the queue */
790 PLEvent *ev = new PLEvent;
791 gEventQ->InitEvent (ev, NULL, quitEventHandler, quitEventDestructor);
792 gEventQ->PostEvent (ev);
793 }
794 if (pszPidFile)
795 {
796 RTFileDelete(pszPidFile);
797 }
798};
799
800#if defined(USE_BACKTRACE)
801/**
802 * the signal handler that prints out a backtrace of the call stack.
803 * the code is taken from http://www.linuxjournal.com/article/6391.
804 */
805static void bt_sighandler (int sig, siginfo_t *info, void *secret)
806{
807
808 void *trace[16];
809 char **messages = (char **)NULL;
810 int i, trace_size = 0;
811 ucontext_t *uc = (ucontext_t *)secret;
812
813 // Do something useful with siginfo_t
814 if (sig == SIGSEGV)
815 Log (("Got signal %d, faulty address is %p, from %p\n",
816 sig, info->si_addr, uc->uc_mcontext.gregs[REG_PC]));
817 else
818 Log (("Got signal %d\n", sig));
819
820 trace_size = backtrace (trace, 16);
821 // overwrite sigaction with caller's address
822 trace[1] = (void *) uc->uc_mcontext.gregs [REG_PC];
823
824 messages = backtrace_symbols (trace, trace_size);
825 // skip first stack frame (points here)
826 Log (("[bt] Execution path:\n"));
827 for (i = 1; i < trace_size; ++i)
828 Log (("[bt] %s\n", messages[i]));
829
830 exit (0);
831}
832#endif
833
834int main (int argc, char **argv)
835{
836 const struct option options[] =
837 {
838 { "automate", no_argument, NULL, 'a' },
839 { "daemonize", no_argument, NULL, 'd' },
840 { "pidfile", required_argument, NULL, 'p' },
841 { NULL, 0, NULL, 0 }
842 };
843 int c;
844
845 bool fDaemonize = false;
846
847 for (;;)
848 {
849 c = getopt_long(argc, argv, "", options, NULL);
850 if (c == -1)
851 break;
852 switch (c)
853 {
854 case 'a':
855 {
856 /* --automate mode means we are started by XPCOM on
857 * demand. Daemonize ourselves and activate
858 * auto-shutdown. */
859 gAutoShutdown = true;
860 fDaemonize = true;
861 break;
862 }
863
864 case 'd':
865 {
866 fDaemonize = true;
867 break;
868 }
869
870 case 'p':
871 {
872 pszPidFile = optarg;
873 break;
874 }
875
876 default:
877 {
878 /* exit on invalid options */
879 return 1;
880 }
881 }
882 }
883
884 static int daemon_pipe_fds[2];
885 static RTFILE pidFile = NIL_RTFILE;
886
887 if (fDaemonize)
888 {
889 /* create a pipe for communication between child and parent */
890 if (pipe(daemon_pipe_fds) < 0)
891 {
892 printf("ERROR: pipe() failed (errno = %d)\n", errno);
893 return 1;
894 }
895
896 pid_t childpid = fork();
897 if (childpid == -1)
898 {
899 printf("ERROR: fork() failed (errno = %d)\n", errno);
900 return 1;
901 }
902
903 if (childpid != 0)
904 {
905 /* we're the parent process */
906 bool fSuccess = false;
907
908 /* close the writing end of the pipe */
909 close(daemon_pipe_fds[1]);
910
911 /* try to read a message from the pipe */
912 char msg[10] = {0}; /* initialize so it's NULL terminated */
913 if (read(daemon_pipe_fds[0], msg, sizeof(msg)) > 0)
914 {
915 if (strcmp(msg, "READY") == 0)
916 fSuccess = true;
917 else
918 printf ("ERROR: Unknown message from child "
919 "process (%s)\n", msg);
920 }
921 else
922 printf ("ERROR: 0 bytes read from child process\n");
923
924 /* close the reading end of the pipe as well and exit */
925 close(daemon_pipe_fds[0]);
926 return fSuccess ? 0 : 1;
927 }
928 /* we're the child process */
929
930 /* Create a new SID for the child process */
931 pid_t sid = setsid();
932 if (sid < 0)
933 {
934 printf("ERROR: setsid() failed (errno = %d)\n", errno);
935 return 1;
936 }
937
938 /* Redirect standard i/o streams to /dev/null */
939 freopen ("/dev/null", "r", stdin);
940 freopen ("/dev/null", "w", stdout);
941 freopen ("/dev/null", "w", stderr);
942
943 /* close the reading end of the pipe */
944 close(daemon_pipe_fds[0]);
945 }
946
947#if defined(USE_BACKTRACE)
948 {
949 /* install our signal handler to backtrace the call stack */
950 struct sigaction sa;
951 sa.sa_sigaction = bt_sighandler;
952 sigemptyset (&sa.sa_mask);
953 sa.sa_flags = SA_RESTART | SA_SIGINFO;
954 sigaction (SIGSEGV, &sa, NULL);
955 sigaction (SIGBUS, &sa, NULL);
956 sigaction (SIGUSR1, &sa, NULL);
957 }
958#endif
959
960 /*
961 * Initialize the VBox runtime without loading
962 * the support driver
963 */
964 RTR3Init(false);
965
966 nsresult rc;
967
968 do
969 {
970 XPCOMGlueStartup (nsnull);
971
972 char path [RTPATH_MAX];
973 path [0] = '\0';
974
975 nsCOMPtr<nsIFile> nsAppPath;
976 {
977 /* get the path to the executable */
978 char *appPath = NULL;
979#if defined (DEBUG)
980 appPath = getenv ("VIRTUALBOX_APP_HOME");
981 if (appPath)
982 RTPathReal (appPath, path, RTPATH_MAX);
983 else
984#endif
985 RTPathProgram (path, RTPATH_MAX);
986 appPath = path;
987
988 nsCOMPtr<nsILocalFile> file;
989 rc = NS_NewNativeLocalFile (nsEmbedCString (appPath),
990 PR_FALSE, getter_AddRefs (file));
991 if (NS_SUCCEEDED (rc))
992 nsAppPath = do_QueryInterface (file, &rc);
993 }
994 if (NS_FAILED (rc))
995 {
996 printf ("ERROR: Failed to create file object! (rc=%08X)\n", rc);
997 break;
998 }
999
1000 /* get the executable name (will be used below) */
1001 if (!RTProcGetExecutableName (path, sizeof (path)))
1002 {
1003 printf ("ERROR: Failed to get executable name!\n");
1004 break;
1005 }
1006
1007 LogFlowFunc (("Will use \"%s\" as server name.\n", path));
1008
1009 nsCOMPtr<nsIServiceManager> servMan;
1010 NS_InitXPCOM2 (getter_AddRefs (servMan), nsAppPath, nsnull);
1011 if (!servMan)
1012 {
1013 printf ("ERROR: Failed to get service manager!\n");
1014 break;
1015 }
1016
1017 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface (servMan);
1018 if (!registrar)
1019 {
1020 printf ("ERROR: Failed to get component registrar!\n");
1021 break;
1022 }
1023
1024 registrar->AutoRegister (nsnull);
1025 rc = RegisterSelfComponents (registrar, components,
1026 NS_ARRAY_LENGTH (components));
1027 if (NS_FAILED (rc))
1028 {
1029 printf ("ERROR: Failed to register server components! (rc=%08X)\n", rc);
1030 break;
1031 }
1032
1033 /* get the main thread's event queue (afaik, the dconnect service always
1034 * gets created upon XPCOM startup, so it will use the main (this)
1035 * thread's event queue to receive IPC events) */
1036 rc = NS_GetMainEventQ (&gEventQ);
1037 if (NS_FAILED (rc))
1038 {
1039 printf ("ERROR: Failed to get the main event queue! (rc=%08X)\n", rc);
1040 break;
1041 }
1042
1043 nsCOMPtr<ipcIService> ipcServ (do_GetService(IPC_SERVICE_CONTRACTID, &rc));
1044 if (NS_FAILED (rc))
1045 {
1046 printf ("ERROR: Failed to get IPC service! (rc=%08X)\n", rc);
1047 break;
1048 }
1049
1050 NS_ADDREF (gIpcServ = ipcServ);
1051
1052 /* use the executable name as the server name */
1053 rc = gIpcServ->AddName (path);
1054 if (NS_FAILED (rc))
1055 {
1056 printf ("ERROR: Failed to register VirtualBoxServer! (rc=%08X)\n", rc);
1057 NS_RELEASE (gIpcServ);
1058 break;
1059 }
1060
1061 {
1062 /* setup signal handling to convert some signals to a quit event */
1063 struct sigaction sa;
1064 sa.sa_handler = signal_handler;
1065 sigemptyset (&sa.sa_mask);
1066 sa.sa_flags = 0;
1067 sigaction (SIGINT, &sa, NULL);
1068 sigaction (SIGQUIT, &sa, NULL);
1069 sigaction (SIGTERM, &sa, NULL);
1070 sigaction (SIGTRAP, &sa, NULL);
1071 }
1072
1073 {
1074 char szBuf[80];
1075 int iSize;
1076
1077 iSize = snprintf (szBuf, sizeof(szBuf),
1078 "InnoTek VirtualBox XPCOM Server Version %s",
1079 VBOX_VERSION_STRING);
1080 for (int i=iSize; i>0; i--)
1081 putchar('*');
1082 printf ("\n%s\n", szBuf);
1083 printf ("(C) 2004-2007 InnoTek Systemberatung GmbH\n");
1084 printf ("All rights reserved.\n");
1085#ifdef DEBUG
1086 printf ("Debug version.\n");
1087#endif
1088#if 0
1089 /* in my opinion two lines enclosing the text look better */
1090 for (int i=iSize; i>0; i--)
1091 putchar('*');
1092 putchar('\n');
1093#endif
1094 }
1095
1096 if (fDaemonize)
1097 {
1098 printf ("\nStarting event loop....\n[send TERM signal to quit]\n");
1099 /* now we're ready, signal the parent process */
1100 write(daemon_pipe_fds[1], "READY", strlen("READY"));
1101 }
1102 else
1103 {
1104 printf ("\nStarting event loop....\n[press Ctrl-C to quit]\n");
1105 }
1106
1107 if (pszPidFile)
1108 {
1109 char szBuf[32];
1110 char *lf = "\n";
1111 RTFileOpen(&pidFile, pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE);
1112 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
1113 RTFileWrite(pidFile, szBuf, strlen(szBuf), NULL);
1114 RTFileWrite(pidFile, lf, strlen(lf), NULL);
1115 RTFileClose(pidFile);
1116 }
1117
1118 PLEvent *ev;
1119 while (gKeepRunning)
1120 {
1121 gEventQ->WaitForEvent (&ev);
1122 gEventQ->HandleEvent (ev);
1123 }
1124
1125 gIpcServ->RemoveName (path);
1126
1127 // stop accepting new events
1128 gEventQ->StopAcceptingEvents();
1129 // process any remaining events
1130 gEventQ->ProcessPendingEvents();
1131
1132 printf ("Terminated event loop.\n");
1133
1134 }
1135 while (0); // this scopes the nsCOMPtrs
1136
1137 NS_IF_RELEASE (gIpcServ);
1138 NS_IF_RELEASE (gEventQ);
1139
1140 // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
1141 LogFlowFunc (("Calling NS_ShutdownXPCOM()...\n"));
1142 rc = NS_ShutdownXPCOM (nsnull);
1143 LogFlowFunc (("Finished NS_ShutdownXPCOM() (rc=%08X)\n", rc));
1144
1145 if (NS_FAILED (rc))
1146 printf ("ERROR: Failed to shutdown XPCOM! (rc=%08X)\n", rc);
1147
1148 XPCOMGlueShutdown();
1149
1150 printf ("XPCOM server has shutdown.\n");
1151
1152 if (pszPidFile)
1153 {
1154 RTFileDelete(pszPidFile);
1155 }
1156
1157 if (fDaemonize)
1158 {
1159 /* close writing end of the pipe as well */
1160 close(daemon_pipe_fds[1]);
1161 }
1162
1163 return 0;
1164}
Note: See TracBrowser for help on using the repository browser.

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