VirtualBox

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

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

this is how we setup a one-shot timer. (code still disabled)

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