VirtualBox

source: vbox/trunk/src/VBox/Main/linux/server.cpp@ 7596

Last change on this file since 7596 was 7442, checked in by vboxsync, 17 years ago

Main: Applied SATA changes from #2406. Increased XML settings version format from 1.2 to 1.3.pre.

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