VirtualBox

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

Last change on this file since 17119 was 16971, checked in by vboxsync, 16 years ago

#3551: “Main: Replace remaining collections with safe arrays”
Converted ostype collection. Tested with VBoxManage list ostypes.

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