VirtualBox

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

Last change on this file since 18754 was 18265, checked in by vboxsync, 16 years ago

config file cleanup + small copyright year update

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