VirtualBox

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

Last change on this file since 2988 was 2980, checked in by vboxsync, 17 years ago

InnoTek -> innotek: actual code changes (headers follow).

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