VirtualBox

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

Last change on this file since 1084 was 953, checked in by vboxsync, 18 years ago

Main: Prototyped IVMDKImage.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.7 KB
Line 
1/** @file
2 *
3 * XPCOM server module implementation
4 */
5
6/*
7 * Copyright (C) 2006 InnoTek Systemberatung 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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22#include <ipcIService.h>
23#include <ipcCID.h>
24
25#include <nsIServiceManager.h>
26#include <nsIComponentRegistrar.h>
27
28#include <nsXPCOMGlue.h>
29#include <nsEventQueueUtils.h>
30
31// for NS_InitXPCOM2 with bin dir parameter
32#include <nsEmbedString.h>
33#include <nsIFile.h>
34#include <nsILocalFile.h>
35
36#include "Logging.h"
37
38#include <iprt/runtime.h>
39#include <iprt/path.h>
40#include <iprt/critsect.h>
41#include <VBox/param.h>
42#include <VBox/version.h>
43
44// for nsMyFactory
45#include "nsIGenericFactory.h"
46#include "nsIClassInfo.h"
47
48#include <stdio.h>
49
50// for the signal handler
51#include <signal.h>
52#include <stdlib.h>
53#include <unistd.h>
54#include <errno.h>
55#include <getopt.h>
56
57// for the backtrace signal handler
58#if defined(DEBUG) && defined(__LINUX__)
59# define USE_BACKTRACE
60#endif
61#if defined(USE_BACKTRACE)
62# include <execinfo.h>
63// get REG_EIP/RIP from ucontext.h
64# ifndef __USE_GNU
65# define __USE_GNU
66# endif
67# include <ucontext.h>
68# ifdef __AMD64__
69# define REG_PC REG_RIP
70# else
71# define REG_PC REG_EIP
72# endif
73#endif
74
75/////////////////////////////////////////////////////////////////////////////
76// VirtualBox component instantiation
77/////////////////////////////////////////////////////////////////////////////
78
79#include <nsIGenericFactory.h>
80
81#include <VirtualBox_XPCOM.h>
82#include <VirtualBoxImpl.h>
83#include <MachineImpl.h>
84#include <SnapshotImpl.h>
85#include <HardDiskImpl.h>
86#include <ProgressImpl.h>
87#include <DVDDriveImpl.h>
88#include <FloppyDriveImpl.h>
89#include <VRDPServerImpl.h>
90#include <DVDImageImpl.h>
91#include <FloppyImageImpl.h>
92#include <SharedFolderImpl.h>
93#include <HostImpl.h>
94#include <HostDVDDriveImpl.h>
95#include <HostFloppyDriveImpl.h>
96#include <HostUSBDeviceImpl.h>
97#include <GuestOSTypeImpl.h>
98#include <NetworkAdapterImpl.h>
99#include <USBControllerImpl.h>
100#include <USBDeviceImpl.h>
101#include <AudioAdapterImpl.h>
102#include <SystemPropertiesImpl.h>
103#include <Collection.h>
104
105// implement nsISupports parts of our objects with support for nsIClassInfo
106NS_DECL_CLASSINFO(VirtualBox)
107NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VirtualBox, IVirtualBox)
108NS_DECL_CLASSINFO(Machine)
109NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Machine, IMachine)
110NS_DECL_CLASSINFO(SessionMachine)
111NS_IMPL_THREADSAFE_ISUPPORTS2_CI(SessionMachine, IMachine, IInternalMachineControl)
112NS_DECL_CLASSINFO(SnapshotMachine)
113NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SnapshotMachine, IMachine)
114NS_DECL_CLASSINFO(Snapshot)
115NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Snapshot, ISnapshot)
116NS_DECL_CLASSINFO(HardDisk)
117NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HardDisk, IHardDisk)
118NS_DECL_CLASSINFO(HVirtualDiskImage)
119NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HVirtualDiskImage, IHardDisk, IVirtualDiskImage)
120NS_DECL_CLASSINFO(HISCSIHardDisk)
121NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HISCSIHardDisk, IHardDisk, IISCSIHardDisk)
122NS_DECL_CLASSINFO(HVMDKImage)
123NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HVMDKImage, IHardDisk, IVMDKImage)
124NS_DECL_CLASSINFO(HardDiskAttachment)
125NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HardDiskAttachment, IHardDiskAttachment)
126NS_DECL_CLASSINFO(Progress)
127NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Progress, IProgress)
128NS_DECL_CLASSINFO(CombinedProgress)
129NS_IMPL_THREADSAFE_ISUPPORTS1_CI(CombinedProgress, IProgress)
130NS_DECL_CLASSINFO(DVDDrive)
131NS_IMPL_THREADSAFE_ISUPPORTS1_CI(DVDDrive, IDVDDrive)
132NS_DECL_CLASSINFO(FloppyDrive)
133NS_IMPL_THREADSAFE_ISUPPORTS1_CI(FloppyDrive, IFloppyDrive)
134NS_DECL_CLASSINFO(SharedFolder)
135NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SharedFolder, ISharedFolder)
136#ifdef VBOX_VRDP
137NS_DECL_CLASSINFO(VRDPServer)
138NS_IMPL_THREADSAFE_ISUPPORTS1_CI(VRDPServer, IVRDPServer)
139#endif
140NS_DECL_CLASSINFO(DVDImage)
141NS_IMPL_THREADSAFE_ISUPPORTS1_CI(DVDImage, IDVDImage)
142NS_DECL_CLASSINFO(FloppyImage)
143NS_IMPL_THREADSAFE_ISUPPORTS1_CI(FloppyImage, IFloppyImage)
144NS_DECL_CLASSINFO(Host)
145NS_IMPL_THREADSAFE_ISUPPORTS1_CI(Host, IHost)
146NS_DECL_CLASSINFO(HostDVDDrive)
147NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostDVDDrive, IHostDVDDrive)
148NS_DECL_CLASSINFO(HostFloppyDrive)
149NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostFloppyDrive, IHostFloppyDrive)
150NS_DECL_CLASSINFO(GuestOSType)
151NS_IMPL_THREADSAFE_ISUPPORTS1_CI(GuestOSType, IGuestOSType)
152NS_DECL_CLASSINFO(NetworkAdapter)
153NS_IMPL_THREADSAFE_ISUPPORTS1_CI(NetworkAdapter, INetworkAdapter)
154NS_DECL_CLASSINFO(USBController)
155NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBController, IUSBController)
156NS_DECL_CLASSINFO(USBDeviceFilter)
157NS_IMPL_THREADSAFE_ISUPPORTS1_CI(USBDeviceFilter, IUSBDeviceFilter)
158NS_DECL_CLASSINFO(HostUSBDevice)
159NS_IMPL_THREADSAFE_ISUPPORTS2_CI(HostUSBDevice, IUSBDevice, IHostUSBDevice)
160NS_DECL_CLASSINFO(HostUSBDeviceFilter)
161NS_IMPL_THREADSAFE_ISUPPORTS1_CI(HostUSBDeviceFilter, IHostUSBDeviceFilter)
162NS_DECL_CLASSINFO(AudioAdapter)
163NS_IMPL_THREADSAFE_ISUPPORTS1_CI(AudioAdapter, IAudioAdapter)
164NS_DECL_CLASSINFO(SystemProperties)
165NS_IMPL_THREADSAFE_ISUPPORTS1_CI(SystemProperties, ISystemProperties)
166NS_DECL_CLASSINFO(BIOSSettings)
167NS_IMPL_THREADSAFE_ISUPPORTS1_CI(BIOSSettings, IBIOSSettings)
168
169// collections and enumerators
170COM_IMPL_READONLY_ENUM_AND_COLLECTION(Machine)
171COM_IMPL_READONLY_ENUM_AND_COLLECTION(Snapshot)
172COM_IMPL_READONLY_ENUM_AND_COLLECTION(HardDiskAttachment)
173COM_IMPL_READONLY_ENUM_AND_COLLECTION(GuestOSType)
174COM_IMPL_READONLY_ENUM_AND_COLLECTION(USBDeviceFilter)
175COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostDVDDrive)
176COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostFloppyDrive)
177COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostUSBDevice)
178COM_IMPL_READONLY_ENUM_AND_COLLECTION(HostUSBDeviceFilter)
179COM_IMPL_READONLY_ENUM_AND_COLLECTION(HardDisk)
180COM_IMPL_READONLY_ENUM_AND_COLLECTION(DVDImage)
181COM_IMPL_READONLY_ENUM_AND_COLLECTION(FloppyImage)
182COM_IMPL_READONLY_ENUM_AND_COLLECTION(SharedFolder)
183
184COM_IMPL_READONLY_ENUM_AND_COLLECTION_AS(Progress, IProgress)
185COM_IMPL_READONLY_ENUM_AND_COLLECTION_AS(IfaceUSBDevice, IUSBDevice)
186
187////////////////////////////////////////////////////////////////////////////////
188
189static nsIEventQueue* gEventQ = nsnull;
190static PRBool volatile gKeepRunning = PR_TRUE;
191
192////////////////////////////////////////////////////////////////////////////////
193
194/**
195 * VirtualBox class factory that destroys the created instance right after
196 * the last reference to it is released by the client, and recreates it again
197 * when necessary (so VirtualBox acts like a singleton object).
198 */
199class VirtualBoxClassFactory : public VirtualBox
200{
201public:
202
203 virtual ~VirtualBoxClassFactory()
204 {
205 Log (("VirtualBoxClassFactory: deleting VirtualBox...\n"));
206
207 FinalRelease();
208 sInstance = 0;
209
210 Log (("VirtualBoxClassFactory: VirtualBox object deleted.\n"));
211 printf ("Informational: VirtualBox object deleted.\n");
212 }
213
214 NS_IMETHOD_(nsrefcnt) Release()
215 {
216 // we overload Release() to guarantee the VirtualBox destructor is
217 // always called on the main thread
218
219 nsrefcnt count = VirtualBox::Release();
220
221 if (count == 1)
222 {
223 // the last reference held by clients is being released
224 // (see GetInstance())
225
226 PRBool onMainThread = PR_TRUE;
227 if (gEventQ)
228 gEventQ->IsOnCurrentThread (&onMainThread);
229
230 if (!onMainThread)
231 {
232 // post a destruction event to the main thread to release the
233 // extra reference added in GetInstance()
234
235 LogFlow (("VirtualBoxClassFactory: the last VirtualBox reference "
236 "is being released, scheduling the destruction...\n"));
237
238 PLEvent *ev = new PLEvent;
239 gEventQ->InitEvent (ev, NULL, DestructEventHandler,
240 DestructEventDestructor);
241 nsresult rv = gEventQ->PostEvent (ev);
242 if (NS_FAILED (rv))
243 {
244 // this means we've been already stopped (for example
245 // by Ctrl-C). FactoryDestructor() (NS_ShutdownXPCOM())
246 // will do the job.
247 PL_DestroyEvent (ev);
248 }
249 }
250 else
251 {
252 // Here we come if:
253 //
254 // a) gEventQ is 0 which means either FactoryDestructor() is called
255 // or the IPC/DCONNECT shutdown sequence is initiated by the
256 // XPCOM shutdown routine (NS_ShutdownXPCOM()), which always
257 // happens on the main thread.
258 //
259 // b) gEventQ has reported we're on the main thread. This means
260 // that DestructEventHandler() has been called, but another
261 // client was faster and requested VirtualBox again.
262 //
263 // We have nothing to do in these cases.
264 }
265 }
266
267 return count;
268 }
269
270 static void *PR_CALLBACK DestructEventHandler (PLEvent* self)
271 {
272 Assert (RTCritSectIsInitialized (&sLock));
273
274 // stop accepting GetInstance() requests during possible destruction
275 RTCritSectEnter (&sLock);
276
277 Assert (sInstance);
278
279 // release the reference we added in GetInstance()
280 // (will call the destructor if nobody referenced us again)
281 nsrefcnt count = sInstance->Release();
282 if (count != 0)
283 {
284 LogFlow (("VirtualBoxClassFactory: destruciton is canceled\n"));
285 }
286
287 RTCritSectLeave (&sLock);
288
289 return 0;
290 }
291
292 static void PR_CALLBACK DestructEventDestructor (PLEvent* self)
293 {
294 delete self;
295 }
296
297 static NS_IMETHODIMP FactoryConstructor()
298 {
299 LogFlow (("VirtualBoxClassFactory::FactoryConstructor()\n"));
300
301 // create a critsect to protect object construction
302 if (VBOX_FAILURE (RTCritSectInit (&sLock)))
303 return NS_ERROR_OUT_OF_MEMORY;
304
305 return NS_OK;
306 }
307
308 static NS_IMETHODIMP FactoryDestructor()
309 {
310 LogFlow (("VirtualBoxClassFactory::FactoryDestructor()\n"));
311
312 RTCritSectDelete (&sLock);
313
314 if (sInstance)
315 {
316 // Either posting a destruction event falied for some reason (most
317 // likely, the quit event has been received before the last release),
318 // or the client has terminated abnormally w/o releasing its
319 // VirtualBox instance (so NS_ShutdownXPCOM() is doing a cleanup).
320 // Release the extra reference we added in GetInstance().
321 sInstance->Release();
322 }
323
324 return NS_OK;
325 }
326
327 static nsresult GetInstance (VirtualBox **inst)
328 {
329 Log (("VirtualBoxClassFactory: getting VirtualBox object...\n"));
330
331 RTCritSectEnter (&sLock);
332
333 int rv = NS_OK;
334
335 if (sInstance == 0)
336 {
337 Log (("VirtualBoxClassFactory: creating new VirtualBox object...\n"));
338 sInstance = new VirtualBoxClassFactory();
339 if (sInstance)
340 {
341 // make an extra AddRef to take the full control
342 // on the VirtualBox destruction (see FinalRelease())
343 sInstance->AddRef();
344
345 sInstance->AddRef(); // protect FinalConstruct()
346 rv = sInstance->FinalConstruct();
347 printf ("Informational: VirtualBox object created (rc=%08X).\n", rv);
348 if (NS_FAILED (rv))
349 {
350 // on failure diring VirtualBox initialization, delete it
351 // immediately on the current thread, ignoring the reference
352 // count (VirtualBox should be aware of that meaning that it
353 // has already completely unintialized itself in this case)
354 Log (("VirtualBoxClassFactory: VirtualBox creation failed "
355 "(rc=%08X), deleting immediately...\n", rv));
356 delete sInstance;
357 sInstance = 0;
358 }
359 }
360 else
361 {
362 rv = NS_ERROR_OUT_OF_MEMORY;
363 }
364 }
365 else
366 {
367 Log (("VirtualBoxClassFactory: using existing VirtualBox object...\n"));
368 nsrefcnt count = sInstance->AddRef();
369 Assert (count > 1);
370
371 if (count == 2)
372 {
373 LogFlow (("VirtualBoxClassFactory: another client has requested "
374 "a reference of VirtualBox scheduled for destruction, "
375 "canceling detruction...\n"));
376
377 // add a reference to compensate one that DestructEventHandler()
378 // will release
379 sInstance->AddRef();
380 }
381 }
382
383 *inst = sInstance;
384
385 RTCritSectLeave (&sLock);
386
387 return rv;
388 }
389
390private:
391
392 static VirtualBox *sInstance;
393 static RTCRITSECT sLock;
394};
395
396VirtualBox *VirtualBoxClassFactory::sInstance = 0;
397RTCRITSECT VirtualBoxClassFactory::sLock = {0};
398
399NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR_WITH_RC (
400 VirtualBox, VirtualBoxClassFactory::GetInstance
401)
402
403////////////////////////////////////////////////////////////////////////////////
404
405typedef NSFactoryDestructorProcPtr NSFactoryConsructorProcPtr;
406
407/**
408 * Enhanced module component information structure.
409 * nsModuleComponentInfo lacks the factory construction callback,
410 * here we add it. This callback is called by NS_NewMyFactory() after
411 * a nsMyFactory instance is successfully created.
412 */
413struct nsMyModuleComponentInfo : nsModuleComponentInfo
414{
415 nsMyModuleComponentInfo () {}
416 nsMyModuleComponentInfo (int) {}
417
418 nsMyModuleComponentInfo (
419 const char* aDescription,
420 const nsCID& aCID,
421 const char* aContractID,
422 NSConstructorProcPtr aConstructor,
423 NSRegisterSelfProcPtr aRegisterSelfProc,
424 NSUnregisterSelfProcPtr aUnregisterSelfProc,
425 NSFactoryDestructorProcPtr aFactoryDestructor,
426 NSGetInterfacesProcPtr aGetInterfacesProc,
427 NSGetLanguageHelperProcPtr aGetLanguageHelperProc,
428 nsIClassInfo ** aClassInfoGlobal,
429 PRUint32 aFlags,
430 NSFactoryConsructorProcPtr aFactoryConstructor)
431 {
432 mDescription = aDescription;
433 mCID = aCID;
434 mContractID = aContractID;
435 mConstructor = aConstructor;
436 mRegisterSelfProc = aRegisterSelfProc;
437 mUnregisterSelfProc = aUnregisterSelfProc;
438 mFactoryDestructor = aFactoryDestructor;
439 mGetInterfacesProc = aGetInterfacesProc;
440 mGetLanguageHelperProc = aGetLanguageHelperProc;
441 mClassInfoGlobal = aClassInfoGlobal;
442 mFlags = aFlags;
443 mFactoryConstructor = aFactoryConstructor;
444 }
445
446 /** (optional) Factory Construction Callback */
447 NSFactoryConsructorProcPtr mFactoryConstructor;
448};
449
450////////////////////////////////////////////////////////////////////////////////
451
452static const nsMyModuleComponentInfo components[] =
453{
454 nsMyModuleComponentInfo (
455 "VirtualBox component",
456 (nsCID) NS_VIRTUALBOX_CID,
457 NS_VIRTUALBOX_CONTRACTID,
458 VirtualBoxConstructor, // constructor funcion
459 NULL, // registration function
460 NULL, // deregistration function
461 VirtualBoxClassFactory::FactoryDestructor, // factory destructor function
462 NS_CI_INTERFACE_GETTER_NAME(VirtualBox),
463 NULL, // language helper
464 &NS_CLASSINFO_NAME(VirtualBox),
465 0, // flags
466 VirtualBoxClassFactory::FactoryConstructor // factory constructor function
467 )
468};
469
470/////////////////////////////////////////////////////////////////////////////
471
472/**
473 * Generic component factory.
474 *
475 * The code below is stolen from nsGenericFactory.h / nsGenericFactory.cpp,
476 * because we get a segmentation fault for some unknown reason when VBoxSVC
477 * starts up (somewhere during the initialization of the libipcdc.so module)
478 * when we just reference XPCOM's NS_NewGenericFactory() from here (i.e. even
479 * before actually calling it) and run VBoxSVC using the debug XPCOM libraries.
480 */
481class nsMyFactory : public nsIGenericFactory, public nsIClassInfo {
482public:
483 NS_DEFINE_STATIC_CID_ACCESSOR(NS_GENERICFACTORY_CID);
484
485 nsMyFactory(const nsModuleComponentInfo *info = NULL);
486
487 NS_DECL_ISUPPORTS
488 NS_DECL_NSICLASSINFO
489
490 /* nsIGenericFactory methods */
491 NS_IMETHOD SetComponentInfo(const nsModuleComponentInfo *info);
492 NS_IMETHOD GetComponentInfo(const nsModuleComponentInfo **infop);
493
494 NS_IMETHOD CreateInstance(nsISupports *aOuter, REFNSIID aIID, void **aResult);
495
496 NS_IMETHOD LockFactory(PRBool aLock);
497
498 static NS_METHOD Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr);
499private:
500 ~nsMyFactory();
501
502 const nsModuleComponentInfo *mInfo;
503};
504
505nsMyFactory::nsMyFactory(const nsModuleComponentInfo *info)
506 : mInfo(info)
507{
508 if (mInfo && mInfo->mClassInfoGlobal)
509 *mInfo->mClassInfoGlobal = NS_STATIC_CAST(nsIClassInfo *, this);
510}
511
512nsMyFactory::~nsMyFactory()
513{
514 if (mInfo) {
515 if (mInfo->mFactoryDestructor)
516 mInfo->mFactoryDestructor();
517 if (mInfo->mClassInfoGlobal)
518 *mInfo->mClassInfoGlobal = 0;
519 }
520}
521
522NS_IMPL_THREADSAFE_ISUPPORTS3(nsMyFactory,
523 nsIGenericFactory,
524 nsIFactory,
525 nsIClassInfo)
526
527NS_IMETHODIMP nsMyFactory::CreateInstance(nsISupports *aOuter,
528 REFNSIID aIID, void **aResult)
529{
530 if (mInfo->mConstructor)
531 return mInfo->mConstructor(aOuter, aIID, aResult);
532
533 return NS_ERROR_FACTORY_NOT_REGISTERED;
534}
535
536NS_IMETHODIMP nsMyFactory::LockFactory(PRBool aLock)
537{
538 // XXX do we care if (mInfo->mFlags & THREADSAFE)?
539 return NS_OK;
540}
541
542NS_IMETHODIMP nsMyFactory::GetInterfaces(PRUint32 *countp,
543 nsIID* **array)
544{
545 if (!mInfo->mGetInterfacesProc) {
546 *countp = 0;
547 *array = nsnull;
548 return NS_OK;
549 }
550 return mInfo->mGetInterfacesProc(countp, array);
551}
552
553NS_IMETHODIMP nsMyFactory::GetHelperForLanguage(PRUint32 language,
554 nsISupports **helper)
555{
556 if (mInfo->mGetLanguageHelperProc)
557 return mInfo->mGetLanguageHelperProc(language, helper);
558 *helper = nsnull;
559 return NS_OK;
560}
561
562NS_IMETHODIMP nsMyFactory::GetContractID(char **aContractID)
563{
564 if (mInfo->mContractID) {
565 *aContractID = (char *)nsMemory::Alloc(strlen(mInfo->mContractID) + 1);
566 if (!*aContractID)
567 return NS_ERROR_OUT_OF_MEMORY;
568 strcpy(*aContractID, mInfo->mContractID);
569 } else {
570 *aContractID = nsnull;
571 }
572 return NS_OK;
573}
574
575NS_IMETHODIMP nsMyFactory::GetClassDescription(char * *aClassDescription)
576{
577 if (mInfo->mDescription) {
578 *aClassDescription = (char *)
579 nsMemory::Alloc(strlen(mInfo->mDescription) + 1);
580 if (!*aClassDescription)
581 return NS_ERROR_OUT_OF_MEMORY;
582 strcpy(*aClassDescription, mInfo->mDescription);
583 } else {
584 *aClassDescription = nsnull;
585 }
586 return NS_OK;
587}
588
589NS_IMETHODIMP nsMyFactory::GetClassID(nsCID * *aClassID)
590{
591 *aClassID =
592 NS_REINTERPRET_CAST(nsCID*,
593 nsMemory::Clone(&mInfo->mCID, sizeof mInfo->mCID));
594 if (! *aClassID)
595 return NS_ERROR_OUT_OF_MEMORY;
596 return NS_OK;
597}
598
599NS_IMETHODIMP nsMyFactory::GetClassIDNoAlloc(nsCID *aClassID)
600{
601 *aClassID = mInfo->mCID;
602 return NS_OK;
603}
604
605NS_IMETHODIMP nsMyFactory::GetImplementationLanguage(PRUint32 *langp)
606{
607 *langp = nsIProgrammingLanguage::CPLUSPLUS;
608 return NS_OK;
609}
610
611NS_IMETHODIMP nsMyFactory::GetFlags(PRUint32 *flagsp)
612{
613 *flagsp = mInfo->mFlags;
614 return NS_OK;
615}
616
617// nsIGenericFactory: component-info accessors
618NS_IMETHODIMP nsMyFactory::SetComponentInfo(const nsModuleComponentInfo *info)
619{
620 if (mInfo && mInfo->mClassInfoGlobal)
621 *mInfo->mClassInfoGlobal = 0;
622 mInfo = info;
623 if (mInfo && mInfo->mClassInfoGlobal)
624 *mInfo->mClassInfoGlobal = NS_STATIC_CAST(nsIClassInfo *, this);
625 return NS_OK;
626}
627
628NS_IMETHODIMP nsMyFactory::GetComponentInfo(const nsModuleComponentInfo **infop)
629{
630 *infop = mInfo;
631 return NS_OK;
632}
633
634NS_METHOD nsMyFactory::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr)
635{
636 // sorry, aggregation not spoken here.
637 nsresult res = NS_ERROR_NO_AGGREGATION;
638 if (outer == NULL) {
639 nsMyFactory* factory = new nsMyFactory;
640 if (factory != NULL) {
641 res = factory->QueryInterface(aIID, aInstancePtr);
642 if (res != NS_OK)
643 delete factory;
644 } else {
645 res = NS_ERROR_OUT_OF_MEMORY;
646 }
647 }
648 return res;
649}
650
651/**
652 * Instantiates a new factory and calls
653 * nsMyModuleComponentInfo::mFactoryConstructor.
654 */
655NS_COM nsresult
656NS_NewMyFactory(nsIGenericFactory* *result,
657 const nsMyModuleComponentInfo *info)
658{
659 nsresult rv;
660 nsMyFactory* fact;
661 rv = nsMyFactory::Create(NULL, NS_GET_IID(nsIGenericFactory), (void**)&fact);
662 if (NS_FAILED(rv)) return rv;
663 rv = fact->SetComponentInfo(info);
664 if (NS_FAILED(rv)) goto error;
665 if (info && info->mFactoryConstructor) {
666 rv = info->mFactoryConstructor();
667 if (NS_FAILED(rv)) goto error;
668 }
669 *result = fact;
670 return rv;
671
672 error:
673 NS_RELEASE(fact);
674 return rv;
675}
676
677/////////////////////////////////////////////////////////////////////////////
678
679// a helper function to register self components upon start-up
680// of the out-of-proc server
681static nsresult RegisterSelfComponents (
682 nsIComponentRegistrar *registrar,
683 const nsMyModuleComponentInfo *components, PRUint32 count)
684{
685 nsresult rc = NS_OK;
686 const nsMyModuleComponentInfo *info = components;
687 for (PRUint32 i = 0; i < count && NS_SUCCEEDED( rc ); i++, info++) {
688 // skip components w/o a constructor
689 if (!info->mConstructor) continue;
690 // create a new generic factory for a component and register it
691 nsIGenericFactory *factory;
692// rc = NS_NewGenericFactory (&factory, info);
693 rc = NS_NewMyFactory (&factory, info);
694 if (NS_SUCCEEDED( rc )) {
695 rc = registrar->RegisterFactory (
696 info->mCID,
697 info->mDescription,
698 info->mContractID,
699 factory
700 );
701 factory->Release();
702 }
703 }
704 return rc;
705}
706
707/////////////////////////////////////////////////////////////////////////////
708
709#define VIRTUALBOXSERVER_IPCNAME "VirtualBoxServer"
710
711static ipcIService *gIpcServ = nsnull;
712static char *pszPidFile = NULL;
713
714void* PR_CALLBACK quitEventHandler (PLEvent* self) { gKeepRunning = PR_FALSE; return 0; }
715void PR_CALLBACK quitEventDestructor (PLEvent* self) { delete self; }
716
717void signal_handler (int sig)
718{
719 if (gEventQ && gKeepRunning)
720 {
721 // post a quit event to the queue
722 PLEvent *ev = new PLEvent;
723 gEventQ->InitEvent (ev, NULL, quitEventHandler, quitEventDestructor);
724 gEventQ->PostEvent (ev);
725 }
726 if (pszPidFile)
727 {
728 RTFileDelete(pszPidFile);
729 }
730};
731
732#if defined(USE_BACKTRACE)
733/**
734 * the signal handler that prints out a backtrace of the call stack.
735 * the code is taken from http://www.linuxjournal.com/article/6391.
736 */
737void bt_sighandler (int sig, siginfo_t *info, void *secret)
738{
739
740 void *trace[16];
741 char **messages = (char **)NULL;
742 int i, trace_size = 0;
743 ucontext_t *uc = (ucontext_t *)secret;
744
745 // Do something useful with siginfo_t
746 if (sig == SIGSEGV)
747 Log (("Got signal %d, faulty address is %p, from %p\n",
748 sig, info->si_addr, uc->uc_mcontext.gregs[REG_PC]));
749 else
750 Log (("Got signal %d\n", sig));
751
752 trace_size = backtrace (trace, 16);
753 // overwrite sigaction with caller's address
754 trace[1] = (void *) uc->uc_mcontext.gregs [REG_PC];
755
756 messages = backtrace_symbols (trace, trace_size);
757 // skip first stack frame (points here)
758 Log (("[bt] Execution path:\n"));
759 for (i = 1; i < trace_size; ++i)
760 Log (("[bt] %s\n", messages[i]));
761
762 exit (0);
763}
764#endif
765
766int main (int argc, char **argv)
767{
768 const struct option options[] =
769 {
770 { "daemonize", no_argument, NULL, 'd' },
771 { "pidfile", required_argument, NULL, 'p' },
772 { NULL, 0, NULL, 0 }
773 };
774 int c;
775
776 bool fDaemonize = false;
777
778 for (;;)
779 {
780 c = getopt_long(argc, argv, "", options, NULL);
781 if (c == -1)
782 break;
783 switch (c)
784 {
785 case 'd':
786 {
787 fDaemonize = true;
788 break;
789 }
790
791 case 'p':
792 {
793 pszPidFile = optarg;
794 break;
795 }
796
797 default:
798 break;
799 }
800 }
801
802 static int daemon_pipe_fds[2];
803 static RTFILE pidFile = NIL_RTFILE;
804
805 if (fDaemonize)
806 {
807 /* create a pipe for communication between child and parent */
808 if (pipe(daemon_pipe_fds) < 0)
809 {
810 printf("Error creating pipe! errno = %d\n", errno);
811 return 1;
812 }
813
814 pid_t childpid = fork();
815 if (childpid == -1)
816 {
817 printf("Error failed to fork!\n");
818 return 1;
819 }
820
821 if (childpid != 0)
822 {
823 /* we're the parent process */
824 bool fSuccess = false;
825
826 /* close the writing end of the pipe */
827 close(daemon_pipe_fds[1]);
828
829 /* try to read a message from the pipe */
830 char msg[10] = {0}; /* initialize so it's NULL terminated */
831 if (read(daemon_pipe_fds[0], msg, sizeof(msg)) > 0)
832 {
833 if (strcmp(msg, "READY") == 0)
834 {
835 Log (("child process signalled ready\n"));
836 fSuccess = true;
837 }
838 else
839 {
840 Log (("unknown message from child\n"));
841 }
842 }
843 else
844 {
845 Log (("0 bytes read from child process\n"));
846 }
847 /* close the reading end of the pipe as well and exit */
848 close(daemon_pipe_fds[0]);
849 return fSuccess ? 0 : 1;
850 }
851 /* we're the child process */
852
853 /* close the reading end of the pipe */
854 close(daemon_pipe_fds[0]);
855 }
856
857#if defined(USE_BACKTRACE)
858 {
859 // install our signal handler to backtrace the call stack
860 struct sigaction sa;
861 sa.sa_sigaction = bt_sighandler;
862 sigemptyset (&sa.sa_mask);
863 sa.sa_flags = SA_RESTART | SA_SIGINFO;
864 sigaction (SIGSEGV, &sa, NULL);
865 sigaction (SIGBUS, &sa, NULL);
866 sigaction (SIGUSR1, &sa, NULL);
867 }
868#endif
869
870 /*
871 * Initialize the VBox runtime without loading
872 * the support driver
873 */
874 RTR3Init(false);
875
876 nsresult rc;
877
878 do
879 {
880 XPCOMGlueStartup (nsnull);
881
882 // get the path to the executable
883 char buf [RTPATH_MAX];
884 char *appPath = NULL;
885#if defined(DEBUG)
886 appPath = getenv ("VIRTUALBOX_APP_HOME");
887 if (appPath)
888 RTPathReal (appPath, buf, RTPATH_MAX);
889 else
890#endif
891 RTPathProgram (buf, RTPATH_MAX);
892 appPath = buf;
893
894 nsCOMPtr<nsIFile> nsAppPath;
895 {
896 nsCOMPtr<nsILocalFile> file;
897 rc = NS_NewNativeLocalFile (nsEmbedCString (appPath),
898 PR_FALSE, getter_AddRefs (file));
899 if (NS_SUCCEEDED (rc))
900 nsAppPath = do_QueryInterface (file, &rc);
901 }
902 if (NS_FAILED( rc ))
903 {
904 printf ("ERROR: failed to create file object! (rc=%08X)\n", rc);
905 break;
906 }
907
908 nsCOMPtr<nsIServiceManager> servMan;
909 NS_InitXPCOM2 (getter_AddRefs (servMan), nsAppPath, nsnull);
910 if (!servMan)
911 {
912 printf ("ERROR: failed to get service manager!\n");
913 break;
914 }
915
916 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface (servMan);
917 if (!registrar)
918 {
919 printf ("ERROR: failed to get component registrar!\n");
920 break;
921 }
922
923 registrar->AutoRegister (nsnull);
924 rc = RegisterSelfComponents (registrar, components,
925 NS_ARRAY_LENGTH (components));
926 if (NS_FAILED (rc))
927 {
928 printf ("ERROR: failed to register server components! (rc=%08X)\n", rc);
929 break;
930 }
931
932 // get the main thread's event queue (afaik, the dconnect service always
933 // gets created upon XPCOM startup, so it will use the main (this)
934 // thread's event queue to receive IPC events)
935 rc = NS_GetMainEventQ (&gEventQ);
936 if (NS_FAILED (rc))
937 {
938 printf ("ERROR: failed to get the main event queue! (rc=%08X)\n", rc);
939 break;
940 }
941
942 nsCOMPtr<ipcIService> ipcServ (do_GetService(IPC_SERVICE_CONTRACTID, &rc));
943 if (NS_FAILED (rc))
944 {
945 printf ("ERROR: failed to get IPC service! (rc=%08X)\n", rc);
946 break;
947 }
948
949 NS_ADDREF (gIpcServ = ipcServ);
950
951 rc = gIpcServ->AddName (VIRTUALBOXSERVER_IPCNAME);
952 if (NS_FAILED (rc))
953 {
954 printf ("ERROR: failed to register VirtualBoxServer! (rc=%08X)\n", rc);
955 NS_RELEASE (gIpcServ);
956 break;
957 }
958
959 {
960 // setup signal handling to convert some signals to a quit event
961 struct sigaction sa;
962 sa.sa_handler = signal_handler;
963 sigemptyset (&sa.sa_mask);
964 sa.sa_flags = 0;
965 sigaction (SIGINT, &sa, NULL);
966 sigaction (SIGQUIT, &sa, NULL);
967 sigaction (SIGTERM, &sa, NULL);
968 sigaction (SIGTRAP, &sa, NULL);
969 }
970
971 {
972 char szBuf[64];
973 int iSize;
974
975 iSize = snprintf (szBuf, sizeof(szBuf),
976 "InnoTek VirtualBox XPCOM Server Version %d.%d.%d",
977 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD);
978 for (int i=iSize; i>0; i--)
979 putchar('*');
980 printf ("\n%s\n", szBuf);
981 printf ("(C) 2004-2007 InnoTek Systemberatung GmbH\n");
982 printf ("All rights reserved.\n");
983#ifdef DEBUG
984 printf ("Debug version.\n");
985#endif
986#if 0
987 /* in my opinion two lines enclosing the text look better */
988 for (int i=iSize; i>0; i--)
989 putchar('*');
990 putchar('\n');
991#endif
992 }
993
994 if (fDaemonize)
995 {
996 printf ("\nStarting event loop....\n[send TERM signal to quit]\n");
997 /* now we're ready, signal the parent process */
998 write(daemon_pipe_fds[1], "READY", strlen("READY"));
999 }
1000 else
1001 {
1002 printf ("\nStarting event loop....\n[press Ctrl-C to quit]\n");
1003 }
1004
1005 if (pszPidFile)
1006 {
1007 char szBuf[32];
1008 char *lf = "\n";
1009 RTFileOpen(&pidFile, pszPidFile, RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE);
1010 RTStrFormatNumber(szBuf, getpid(), 10, 0, 0, 0);
1011 RTFileWrite(pidFile, szBuf, strlen(szBuf), NULL);
1012 RTFileWrite(pidFile, lf, strlen(lf), NULL);
1013 RTFileClose(pidFile);
1014 }
1015
1016 PLEvent *ev;
1017 while (gKeepRunning)
1018 {
1019 gEventQ->WaitForEvent (&ev);
1020 gEventQ->HandleEvent (ev);
1021 }
1022
1023 gIpcServ->RemoveName (VIRTUALBOXSERVER_IPCNAME);
1024
1025 // stop accepting new events
1026 gEventQ->StopAcceptingEvents();
1027 // process any remaining events
1028 gEventQ->ProcessPendingEvents();
1029
1030 printf ("Terminated event loop.\n");
1031
1032 }
1033 while (0); // this scopes the nsCOMPtrs
1034
1035 NS_IF_RELEASE (gIpcServ);
1036 NS_IF_RELEASE (gEventQ);
1037
1038 // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
1039 LogFlow (("VBoxSVC::main(): calling NS_ShutdownXPCOM()...\n"));
1040 rc = NS_ShutdownXPCOM (nsnull);
1041 LogFlow (("VBoxSVC::main(): finished NS_ShutdownXPCOM() (rc=%08X).\n", rc));
1042
1043 if (NS_FAILED( rc ))
1044 printf ("ERROR: failed to shutdown XPCOM! (rc=%08X)\n", rc);
1045
1046 XPCOMGlueShutdown();
1047
1048 printf ("XPCOM server has shutdown.\n");
1049
1050 if (pszPidFile)
1051 {
1052 RTFileDelete(pszPidFile);
1053 }
1054
1055 if (fDaemonize)
1056 {
1057 /* close writing end of the pipe as well */
1058 close(daemon_pipe_fds[1]);
1059 }
1060
1061 return 0;
1062}
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