VirtualBox

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

最後變更 在這個檔案從17200是 17200,由 vboxsync 提交於 16 年 前

#3551: “Main: Replace remaining collections with safe arrays”
Take two. Convert HostDVDDriveCollection. This time for all plattforms.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette