VirtualBox

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

Last change on this file since 30760 was 30760, checked in by vboxsync, 15 years ago

Main: separate internal machine data structs into MachineImplPrivate.h to significantly speed up compilation and for better interface separation; remove obsolete ConsoleEvents.h file

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

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