VirtualBox

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

Last change on this file since 16776 was 16707, checked in by vboxsync, 16 years ago

#3551: “Main: Replace remaining collections with safe arrays”

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