VirtualBox

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

Last change on this file since 16684 was 16382, checked in by vboxsync, 16 years ago

ipcdUnix.cpp, xpcom/server.cpp: Fixed wrong loop. Changed my mind about trial error approach.

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