server.cpp revision b8a3aa00d3e073034b15b22a6b04b1a9604f32d6
/** @file
*
* XPCOM server process start point
*/
/*
* Copyright (C) 2006-2007 innotek GmbH
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License as published by the Free Software Foundation,
* in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
* distribution. VirtualBox OSE is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY of any kind.
*
* If you received this file as part of a commercial VirtualBox
* distribution, then only the terms of your commercial VirtualBox
* license agreement apply instead of the previous paragraph.
*/
#include <ipcIService.h>
#include <ipcCID.h>
#include <nsIComponentRegistrar.h>
#include <nsXPCOMGlue.h>
#include <nsEventQueueUtils.h>
// for nsMyFactory
#include <nsIGenericFactory.h>
#include <nsIClassInfo.h>
#include "Logging.h"
#include <iprt/critsect.h>
#include <stdio.h>
// for the signal handler
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <getopt.h>
// for the backtrace signal handler
# define USE_BACKTRACE
#endif
#if defined(USE_BACKTRACE)
# include <execinfo.h>
// get REG_EIP/RIP from ucontext.h
# ifndef __USE_GNU
# define __USE_GNU
# endif
# include <ucontext.h>
# ifdef __AMD64__
# else
# endif
#endif
/////////////////////////////////////////////////////////////////////////////
// VirtualBox component instantiation
/////////////////////////////////////////////////////////////////////////////
#include <nsIGenericFactory.h>
#include <VirtualBox_XPCOM.h>
#include <VirtualBoxImpl.h>
#include <MachineImpl.h>
#include <SnapshotImpl.h>
#include <HardDiskImpl.h>
#include <ProgressImpl.h>
#include <DVDDriveImpl.h>
#include <FloppyDriveImpl.h>
#include <VRDPServerImpl.h>
#include <DVDImageImpl.h>
#include <FloppyImageImpl.h>
#include <SharedFolderImpl.h>
#include <HostImpl.h>
#include <HostDVDDriveImpl.h>
#include <HostFloppyDriveImpl.h>
#include <HostUSBDeviceImpl.h>
#include <GuestOSTypeImpl.h>
#include <NetworkAdapterImpl.h>
#include <USBControllerImpl.h>
#include <USBDeviceImpl.h>
#include <AudioAdapterImpl.h>
#include <SystemPropertiesImpl.h>
#include <Collection.h>
// implement nsISupports parts of our objects with support for nsIClassInfo
#ifdef VBOX_VRDP
#endif
// collections and enumerators
////////////////////////////////////////////////////////////////////////////////
enum
{
/* Delay before shutting down the VirtualBox server after the last
* VirtualBox instance is released, in ms */
VBoxSVC_ShutdownDelay = 5000,
};
static bool gAutoShutdown = false;
/////////////////////////////////////////////////////////////////////////////
/**
* Simple but smart PLEvent wrapper.
*
* @note Instances must be always created with <tt>operator new</tt>!
*/
class MyEvent
{
public:
MyEvent()
{
};
/**
* Posts this event to the given message queue. This method may only be
* called once. @note On success, the event will be deleted automatically
* after it is delivered and handled. On failure, the event will delete
* itself before this method returns! The caller must not delete it in
* either case.
*/
{
if (NS_SUCCEEDED (rv))
{
if (NS_SUCCEEDED (rv))
return rv;
}
delete this;
return rv;
}
virtual void *handler() = 0;
private:
struct Ev
{
PLEvent e;
} mEv;
{
}
{
}
};
////////////////////////////////////////////////////////////////////////////////
/**
* VirtualBox class factory that destroys the created instance right after
* the last reference to it is released by the client, and recreates it again
* when necessary (so VirtualBox acts like a singleton object).
*/
class VirtualBoxClassFactory : public VirtualBox
{
public:
virtual ~VirtualBoxClassFactory()
{
LogFlowFunc (("Deleting VirtualBox...\n"));
FinalRelease();
sInstance = 0;
LogFlowFunc (("VirtualBox object deleted.\n"));
printf ("Informational: VirtualBox object deleted.\n");
}
{
/* we overload Release() to guarantee the VirtualBox destructor is
* always called on the main thread */
if (count == 1)
{
/* the last reference held by clients is being released
* (see GetInstance()) */
if (gEventQ)
/* sTimes is null if this call originates from
* FactoryDestructor() */
{
LogFlowFunc (("Last VirtualBox instance was released.\n"));
LogFlowFunc (("Scheduling server shutdown in %d ms...\n",
/* make sure the previous timer (if any) is stopped;
* otherwise RTTimerStart() will definitely fail. */
}
else
{
LogFlowFunc (("Last VirtualBox instance was released "
"on XPCOM shutdown.\n"));
}
if (!timerStarted)
{
if (!onMainThread)
{
/* Failed to start the timer, post the shutdown event
* manually if not on the main thread alreay. */
}
else
{
/* Here we come if:
*
* a) gEventQ is 0 which means either FactoryDestructor() is called
* XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
* happens on the main thread.
*
* b) gEventQ has reported we're on the main thread. This means
* that DestructEventHandler() has been called, but another
* client was faster and requested VirtualBox again.
*
* In either case, there is nothing to do.
*
* Note: case b) is actually no more valid since we don't
* call Release() from DestructEventHandler() in this case
* any more. Thus, we assert below.
*/
}
}
}
return count;
}
class MaybeQuitEvent : public MyEvent
{
/* called on the main thread */
void *handler()
{
LogFlowFunc (("\n"));
/* stop accepting GetInstance() requests on other threads during
* possible destruction */
RTCritSectEnter (&sLock);
/* sInstance is NULL here if it was deleted immediately after
* creation due to initialization error. See GetInstance(). */
{
/* Release the guard reference added in GetInstance() */
}
if (count == 0)
{
if (gAutoShutdown)
{
LogFlowFunc (("Terminating the server process...\n"));
/* make it leave the event loop */
}
}
else
{
/* This condition is quite rare: a new client will have to
* connect after this event has been posted to the main queue
* but before it started to process it. */
}
RTCritSectLeave (&sLock);
return NULL;
}
};
{
/* A "too late" event is theoretically possible if somebody
* manually ended the server after a destruction has been scheduled
* and this method was so lucky that it got a chance to run before
* the timer was killed. */
/* post a quit event to the main queue */
/* A failure above means we've been already stopped (for example
* by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
* will do the job. Nothing to do. */
}
static NS_IMETHODIMP FactoryConstructor()
{
LogFlowFunc (("\n"));
/* create a critsect to protect object construction */
return NS_ERROR_OUT_OF_MEMORY;
if (VBOX_FAILURE (vrc))
{
return NS_ERROR_FAILURE;
}
return NS_OK;
}
static NS_IMETHODIMP FactoryDestructor()
{
LogFlowFunc (("\n"));
if (sInstance)
{
/* Either posting a destruction event falied for some reason (most
* likely, the quit event has been received before the last release),
* or the client has terminated abnormally w/o releasing its
* VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
* Release the guard reference we added in GetInstance(). */
}
return NS_OK;
}
{
LogFlowFunc (("Getting VirtualBox object...\n"));
RTCritSectEnter (&sLock);
if (sInstance == 0)
{
LogFlowFunc (("Creating new VirtualBox object...\n"));
sInstance = new VirtualBoxClassFactory();
if (sInstance)
{
/* make an extra AddRef to take the full control
* on the VirtualBox destruction (see FinalRelease()) */
{
/* On failure diring VirtualBox initialization, delete it
* immediately on the current thread by releasing all
* references in order to properly schedule the server
* shutdown. Since the object is fully deleted here, there
* is a chance to fix the error and request a new
* instantiation before the server terminates. However,
* the main reason to maintain the shoutdown delay on
* failure is to let the front-end completely fetch error
* info from a server-side IVirtualBoxErrorInfo object. */
}
else
{
/* On success, make sure the previous timer is stopped to
* cancel a scheduled server termination (if any). */
}
}
else
{
}
}
else
{
LogFlowFunc (("Using existing VirtualBox object...\n"));
if (count == 2)
{
LogFlowFunc (("Another client has requested a reference to VirtualBox, "
"canceling detruction...\n"));
/* make sure the previous timer is stopped */
}
}
RTCritSectLeave (&sLock);
return rv;
}
private:
/* Don't be confused that sInstance is of the *ClassFactory type. This is
* actually a singleton instance (*ClassFactory inherits the singleton
* class; we combined them just for "simplicity" and used "static" for
* factory methods. *ClassFactory here is necessary for a couple of extra
* methods. */
static VirtualBoxClassFactory *sInstance;
static RTCRITSECT sLock;
};
////////////////////////////////////////////////////////////////////////////////
/**
* Enhanced module component information structure.
* nsModuleComponentInfo lacks the factory construction callback,
* here we add it. This callback is called by NS_NewMyFactory() after
* a nsMyFactory instance is successfully created.
*/
{
nsMyModuleComponentInfo () {}
nsMyModuleComponentInfo (int) {}
const char* aDescription,
const char* aContractID,
{
}
/** (optional) Factory Construction Callback */
};
////////////////////////////////////////////////////////////////////////////////
static const nsMyModuleComponentInfo components[] =
{
"VirtualBox component",
VirtualBoxConstructor, // constructor funcion
NULL, // registration function
NULL, // deregistration function
NULL, // language helper
0, // flags
)
};
/////////////////////////////////////////////////////////////////////////////
/**
* Generic component factory.
*
* The code below is stolen from nsGenericFactory.h / nsGenericFactory.cpp,
* because we get a segmentation fault for some unknown reason when VBoxSVC
* starts up (somewhere during the initialization of the libipcdc.so module)
* when we just reference XPCOM's NS_NewGenericFactory() from here (i.e. even
* before actually calling it) and run VBoxSVC using the debug XPCOM
* libraries.
*
* Actually, I know why, but I find it too stupid even to discuss.
*/
public:
/* nsIGenericFactory methods */
private:
~nsMyFactory();
const nsModuleComponentInfo *mInfo;
};
{
}
{
if (mInfo) {
if (mInfo->mFactoryDestructor)
if (mInfo->mClassInfoGlobal)
*mInfo->mClassInfoGlobal = 0;
}
}
{
if (mInfo->mConstructor)
return NS_ERROR_FACTORY_NOT_REGISTERED;
}
{
// XXX do we care if (mInfo->mFlags & THREADSAFE)?
return NS_OK;
}
{
if (!mInfo->mGetInterfacesProc) {
*countp = 0;
return NS_OK;
}
}
{
if (mInfo->mGetLanguageHelperProc)
return NS_OK;
}
{
if (mInfo->mContractID) {
if (!*aContractID)
return NS_ERROR_OUT_OF_MEMORY;
} else {
*aContractID = nsnull;
}
return NS_OK;
}
{
if (mInfo->mDescription) {
*aClassDescription = (char *)
if (!*aClassDescription)
return NS_ERROR_OUT_OF_MEMORY;
} else {
}
return NS_OK;
}
{
*aClassID =
if (! *aClassID)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
{
return NS_OK;
}
{
return NS_OK;
}
{
return NS_OK;
}
// nsIGenericFactory: component-info accessors
{
*mInfo->mClassInfoGlobal = 0;
return NS_OK;
}
{
return NS_OK;
}
{
// sorry, aggregation not spoken here.
delete factory;
} else {
}
}
return res;
}
/**
* Instantiates a new factory and calls
* nsMyModuleComponentInfo::mFactoryConstructor.
*/
const nsMyModuleComponentInfo *info)
{
}
return rv;
return rv;
}
/////////////////////////////////////////////////////////////////////////////
/**
* Hhelper function to register self components upon start-up
* of the out-of-proc server.
*/
static nsresult
const nsMyModuleComponentInfo *components,
{
{
/* skip components w/o a constructor */
if (!info->mConstructor) continue;
/* create a new generic factory for a component and register it */
if (NS_SUCCEEDED (rc))
{
factory);
}
}
return rc;
}
/////////////////////////////////////////////////////////////////////////////
static char *pszPidFile = NULL;
class ForceQuitEvent : public MyEvent
{
void *handler()
{
LogFlowFunc (("\n"));
if (pszPidFile)
return NULL;
}
};
static void signal_handler (int sig)
{
if (gEventQ && gKeepRunning)
{
/* post a quit event to the queue */
}
}
#if defined(USE_BACKTRACE)
/**
* the signal handler that prints out a backtrace of the call stack.
* the code is taken from http://www.linuxjournal.com/article/6391.
*/
{
void *trace[16];
int i, trace_size = 0;
// Do something useful with siginfo_t
Log (("Got signal %d, faulty address is %p, from %p\n",
else
// overwrite sigaction with caller's address
// skip first stack frame (points here)
Log (("[bt] Execution path:\n"));
for (i = 1; i < trace_size; ++i)
exit (0);
}
#endif
{
{
};
int c;
bool fDaemonize = false;
for (;;)
{
if (c == -1)
break;
switch (c)
{
case 'a':
{
/* --automate mode means we are started by XPCOM on
* demand. Daemonize ourselves and activate
* auto-shutdown. */
gAutoShutdown = true;
fDaemonize = true;
break;
}
case 'd':
{
fDaemonize = true;
break;
}
case 'p':
{
pszPidFile = optarg;
break;
}
default:
{
/* exit on invalid options */
return 1;
}
}
}
static int daemon_pipe_fds[2];
if (fDaemonize)
{
/* create a pipe for communication between child and parent */
if (pipe(daemon_pipe_fds) < 0)
{
return 1;
}
if (childpid == -1)
{
return 1;
}
if (childpid != 0)
{
/* we're the parent process */
bool fSuccess = false;
/* close the writing end of the pipe */
/* try to read a message from the pipe */
{
fSuccess = true;
else
printf ("ERROR: Unknown message from child "
"process (%s)\n", msg);
}
else
printf ("ERROR: 0 bytes read from child process\n");
/* close the reading end of the pipe as well and exit */
close(daemon_pipe_fds[0]);
return fSuccess ? 0 : 1;
}
/* we're the child process */
/* Create a new SID for the child process */
if (sid < 0)
{
return 1;
}
/* close the reading end of the pipe */
close(daemon_pipe_fds[0]);
}
#if defined(USE_BACKTRACE)
{
/* install our signal handler to backtrace the call stack */
}
#endif
/*
* Initialize the VBox runtime without loading
* the support driver
*/
RTR3Init(false);
do
{
{
break;
}
{
break;
}
{
break;
}
/* get the main thread's event queue (afaik, the dconnect service always
* gets created upon XPCOM startup, so it will use the main (this)
* thread's event queue to receive IPC events) */
{
break;
}
{
break;
}
{
break;
}
{
/* setup signal handling to convert some signals to a quit event */
}
{
char szBuf[80];
int iSize;
"innotek VirtualBox XPCOM Server Version "
for (int i=iSize; i>0; i--)
putchar('*');
printf ("(C) 2004-2007 innotek GmbH\n");
printf ("All rights reserved.\n");
#ifdef DEBUG
printf ("Debug version.\n");
#endif
#if 0
/* in my opinion two lines enclosing the text look better */
for (int i=iSize; i>0; i--)
putchar('*');
putchar('\n');
#endif
}
if (fDaemonize)
{
printf ("\nStarting event loop....\n[send TERM signal to quit]\n");
/* now we're ready, signal the parent process */
}
else
{
printf ("\nStarting event loop....\n[press Ctrl-C to quit]\n");
}
if (pszPidFile)
{
char szBuf[32];
const char *lf = "\n";
}
while (gKeepRunning)
{
}
/* stop accepting new events */
/* process any remaining events */
printf ("Terminated event loop.\n");
}
while (0); // this scopes the nsCOMPtrs
/* no nsCOMPtrs are allowed to be alive when you call com::Shutdown(). */
LogFlowFunc (("Calling com::Shutdown()...\n"));
printf ("XPCOM server has shutdown.\n");
if (pszPidFile)
{
}
if (fDaemonize)
{
/* close writing end of the pipe as well */
}
return 0;
}