VirtualBox

source: vbox/trunk/src/VBox/Main/testcase/tstVBoxAPIXPCOM.cpp@ 49803

Last change on this file since 49803 was 49452, checked in by vboxsync, 11 years ago

whitespace cleanup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 23.5 KB
Line 
1/** @file
2 *
3 * tstVBoxAPILinux - sample program to illustrate the VirtualBox
4 * XPCOM API for machine management on Linux.
5 * It only uses standard C/C++ and XPCOM semantics,
6 * no additional VBox classes/macros/helpers.
7 */
8
9/*
10 * Copyright (C) 2006-2013 Oracle Corporation
11 *
12 * This file is part of VirtualBox Open Source Edition (OSE), as
13 * available from http://www.virtualbox.org. This file is free software;
14 * you can redistribute it and/or modify it under the terms of the GNU
15 * General Public License (GPL) as published by the Free Software
16 * Foundation, in version 2 as it comes in the "COPYING" file of the
17 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
18 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
19 */
20
21/*
22 * PURPOSE OF THIS SAMPLE PROGRAM
23 * ------------------------------
24 *
25 * This sample program is intended to demonstrate the minimal code necessary
26 * to use VirtualBox XPCOM API for learning puroses only. The program uses
27 * pure XPCOM and doesn't have any extra dependencies to let you better
28 * understand what is going on when a client talks to the VirtualBox core
29 * using the XPCOM framework.
30 *
31 * However, if you want to write a real application, it is highly recommended
32 * to use our MS COM XPCOM Glue library and helper C++ classes. This way, you
33 * will get at least the following benefits:
34 *
35 * a) better portability: both the MS COM (used on Windows) and XPCOM (used
36 * everywhere else) VirtualBox client application from the same source code
37 * (including common smart C++ templates for automatic interface pointer
38 * reference counter and string data management);
39 * b) simpler XPCOM initialization and shutdown (only a single method call
40 * that does everything right).
41 *
42 * Currently, there is no separate sample program that uses the VirtualBox MS
43 * COM XPCOM Glue library. Please refer to the sources of stock VirtualBox
44 * applications such as the VirtualBox GUI frontend or the VBoxManage command
45 * line frontend.
46 *
47 *
48 * RUNNING THIS SAMPLE PROGRAM
49 * ---------------------------
50 *
51 * This sample program needs to know where the VirtualBox core files reside
52 * and where to search for VirtualBox shared libraries. Therefore, you need to
53 * use the following (or similar) command to execute it:
54 *
55 * $ env VBOX_XPCOM_HOME=../../.. LD_LIBRARY_PATH=../../.. ./tstVBoxAPILinux
56 *
57 * The above command assumes that VBoxRT.so, VBoxXPCOM.so and others reside in
58 * the directory ../../..
59 */
60
61
62#include <stdio.h>
63#include <stdlib.h>
64#include <iconv.h>
65
66/*
67 * Include the XPCOM headers
68 */
69#include <nsMemory.h>
70#include <nsString.h>
71#include <nsIServiceManager.h>
72#include <nsEventQueueUtils.h>
73
74#include <nsIExceptionService.h>
75
76#include <VBox/com/com.h>
77#include <VBox/com/string.h>
78#include <VBox/com/array.h>
79#include <VBox/com/Guid.h>
80#include <VBox/com/ErrorInfo.h>
81#include <VBox/com/errorprint.h>
82#include <VBox/com/EventQueue.h>
83
84#include <VBox/com/VirtualBox.h>
85
86#include <iprt/stream.h>
87
88
89/*
90 * VirtualBox XPCOM interface. This header is generated
91 * from IDL which in turn is generated from a custom XML format.
92 */
93#include "VirtualBox_XPCOM.h"
94
95/*
96 * Prototypes
97 */
98
99char *nsIDToString(nsID *guid);
100void printErrorInfo();
101
102
103/**
104 * Display all registered VMs on the screen with some information about each
105 *
106 * @param virtualBox VirtualBox instance object.
107 */
108void listVMs(IVirtualBox *virtualBox)
109{
110 nsresult rc;
111
112 RTPrintf("----------------------------------------------------\n");
113 RTPrintf("VM List:\n\n");
114
115 /*
116 * Get the list of all registered VMs
117 */
118 IMachine **machines = NULL;
119 PRUint32 machineCnt = 0;
120
121 rc = virtualBox->GetMachines(&machineCnt, &machines);
122 if (NS_SUCCEEDED(rc))
123 {
124 /*
125 * Iterate through the collection
126 */
127 for (PRUint32 i = 0; i < machineCnt; ++ i)
128 {
129 IMachine *machine = machines[i];
130 if (machine)
131 {
132 PRBool isAccessible = PR_FALSE;
133 machine->GetAccessible(&isAccessible);
134
135 if (isAccessible)
136 {
137 nsXPIDLString machineName;
138 machine->GetName(getter_Copies(machineName));
139 char *machineNameAscii = ToNewCString(machineName);
140 RTPrintf("\tName: %s\n", machineNameAscii);
141 free(machineNameAscii);
142 }
143 else
144 {
145 RTPrintf("\tName: <inaccessible>\n");
146 }
147
148 nsXPIDLString iid;
149 machine->GetId(getter_Copies(iid));
150 const char *uuidString = ToNewCString(iid);
151 RTPrintf("\tUUID: %s\n", uuidString);
152 free((void*)uuidString);
153
154 if (isAccessible)
155 {
156 nsXPIDLString configFile;
157 machine->GetSettingsFilePath(getter_Copies(configFile));
158 char *configFileAscii = ToNewCString(configFile);
159 RTPrintf("\tConfig file: %s\n", configFileAscii);
160 free(configFileAscii);
161
162 PRUint32 memorySize;
163 machine->GetMemorySize(&memorySize);
164 RTPrintf("\tMemory size: %uMB\n", memorySize);
165
166 nsXPIDLString typeId;
167 machine->GetOSTypeId(getter_Copies(typeId));
168 IGuestOSType *osType = nsnull;
169 virtualBox->GetGuestOSType(typeId.get(), &osType);
170 nsXPIDLString osName;
171 osType->GetDescription(getter_Copies(osName));
172 char *osNameAscii = ToNewCString(osName);
173 RTPrintf("\tGuest OS: %s\n\n", osNameAscii);
174 free(osNameAscii);
175 osType->Release();
176 }
177
178 /* don't forget to release the objects in the array... */
179 machine->Release();
180 }
181 }
182 }
183 RTPrintf("----------------------------------------------------\n\n");
184}
185
186/**
187 * Create a sample VM
188 *
189 * @param virtualBox VirtualBox instance object.
190 */
191void createVM(IVirtualBox *virtualBox)
192{
193 nsresult rc;
194 /*
195 * First create a unnamed new VM. It will be unconfigured and not be saved
196 * in the configuration until we explicitely choose to do so.
197 */
198 nsCOMPtr<IMachine> machine;
199 rc = virtualBox->CreateMachine(NULL, /* settings file */
200 NS_LITERAL_STRING("A brand new name").get(),
201 0, nsnull, /* groups (safearray)*/
202 nsnull, /* ostype */
203 nsnull, /* create flags */
204 getter_AddRefs(machine));
205 if (NS_FAILED(rc))
206 {
207 RTPrintf("Error: could not create machine! rc=%Rhrc\n", rc);
208 return;
209 }
210
211 /*
212 * Set some properties
213 */
214 /* alternative to illustrate the use of string classes */
215 rc = machine->SetName(NS_ConvertUTF8toUTF16("A new name").get());
216 rc = machine->SetMemorySize(128);
217
218 /*
219 * Now a more advanced property -- the guest OS type. This is
220 * an object by itself which has to be found first. Note that we
221 * use the ID of the guest OS type here which is an internal
222 * representation (you can find that by configuring the OS type of
223 * a machine in the GUI and then looking at the <Guest ostype=""/>
224 * setting in the XML file. It is also possible to get the OS type from
225 * its description (win2k would be "Windows 2000") by getting the
226 * guest OS type collection and enumerating it.
227 */
228 nsCOMPtr<IGuestOSType> osType;
229 rc = virtualBox->GetGuestOSType(NS_LITERAL_STRING("Windows2000").get(),
230 getter_AddRefs(osType));
231 if (NS_FAILED(rc))
232 {
233 RTPrintf("Error: could not find guest OS type! rc=%Rhrc\n", rc);
234 }
235 else
236 {
237 machine->SetOSTypeId(NS_LITERAL_STRING("Windows2000").get());
238 }
239
240 /*
241 * Register the VM. Note that this call also saves the VM config
242 * to disk. It is also possible to save the VM settings but not
243 * register the VM.
244 *
245 * Also note that due to current VirtualBox limitations, the machine
246 * must be registered *before* we can attach hard disks to it.
247 */
248 rc = virtualBox->RegisterMachine(machine);
249 if (NS_FAILED(rc))
250 {
251 RTPrintf("Error: could not register machine! rc=%Rhrc\n", rc);
252 printErrorInfo();
253 return;
254 }
255
256 nsCOMPtr<IMachine> origMachine = machine;
257
258 /*
259 * In order to manipulate the registered machine, we must open a session
260 * for that machine. Do it now.
261 */
262 nsCOMPtr<ISession> session;
263 nsCOMPtr<IMachine> sessionMachine;
264 {
265 nsCOMPtr<nsIComponentManager> manager;
266 rc = NS_GetComponentManager(getter_AddRefs(manager));
267 if (NS_FAILED(rc))
268 {
269 RTPrintf("Error: could not get component manager! rc=%Rhrc\n", rc);
270 return;
271 }
272 rc = manager->CreateInstanceByContractID(NS_SESSION_CONTRACTID,
273 nsnull,
274 NS_GET_IID(ISession),
275 getter_AddRefs(session));
276 if (NS_FAILED(rc))
277 {
278 RTPrintf("Error, could not instantiate session object! rc=%Rhrc\n", rc);
279 return;
280 }
281
282 rc = machine->LockMachine(session, LockType_Write);
283 if (NS_FAILED(rc))
284 {
285 RTPrintf("Error, could not lock the machine for the session! rc=%Rhrc\n", rc);
286 return;
287 }
288
289 /*
290 * After the machine is registered, the initial machine object becomes
291 * immutable. In order to get a mutable machine object, we must query
292 * it from the opened session object.
293 */
294 rc = session->GetMachine(getter_AddRefs(sessionMachine));
295 if (NS_FAILED(rc))
296 {
297 RTPrintf("Error, could not get machine session! rc=%Rhrc\n", rc);
298 return;
299 }
300 }
301
302 /*
303 * Create a virtual harddisk
304 */
305 nsCOMPtr<IMedium> hardDisk = 0;
306 rc = virtualBox->CreateHardDisk(NS_LITERAL_STRING("VDI").get(),
307 NS_LITERAL_STRING("TestHardDisk.vdi").get(),
308 getter_AddRefs(hardDisk));
309 if (NS_FAILED(rc))
310 {
311 RTPrintf("Failed creating a hard disk object! rc=%Rhrc\n", rc);
312 }
313 else
314 {
315 /*
316 * We have only created an object so far. No on disk representation exists
317 * because none of its properties has been set so far. Let's continue creating
318 * a dynamically expanding image.
319 */
320 nsCOMPtr<IProgress> progress;
321 com::SafeArray<MediumVariant_T> mediumVariant;
322 mediumVariant.push_back(MediumVariant_Standard);
323 rc = hardDisk->CreateBaseStorage(100, // size in megabytes
324 ComSafeArrayAsInParam(mediumVariant),
325 getter_AddRefs(progress)); // optional progress object
326 if (NS_FAILED(rc))
327 {
328 RTPrintf("Failed creating hard disk image! rc=%Rhrc\n", rc);
329 }
330 else
331 {
332 /*
333 * Creating the image is done in the background because it can take quite
334 * some time (at least fixed size images). We have to wait for its completion.
335 * Here we wait forever (timeout -1) which is potentially dangerous.
336 */
337 rc = progress->WaitForCompletion(-1);
338 PRInt32 resultCode;
339 progress->GetResultCode(&resultCode);
340 if (NS_FAILED(rc) || NS_FAILED(resultCode))
341 {
342 RTPrintf("Error: could not create hard disk! rc=%Rhrc\n",
343 NS_FAILED(rc) ? rc : resultCode);
344 }
345 else
346 {
347 /*
348 * Now that it's created, we can assign it to the VM.
349 */
350 rc = sessionMachine->AttachDevice(
351 NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
352 0, // channel number on the controller
353 0, // device number on the controller
354 DeviceType_HardDisk,
355 hardDisk);
356 if (NS_FAILED(rc))
357 {
358 RTPrintf("Error: could not attach hard disk! rc=%Rhrc\n", rc);
359 }
360 }
361 }
362 }
363
364 /*
365 * It's got a hard disk but that one is new and thus not bootable. Make it
366 * boot from an ISO file. This requires some processing. First the ISO file
367 * has to be registered and then mounted to the VM's DVD drive and selected
368 * as the boot device.
369 */
370 nsCOMPtr<IMedium> dvdImage;
371 rc = virtualBox->OpenMedium(NS_LITERAL_STRING("/home/vbox/isos/winnt4ger.iso").get(),
372 DeviceType_DVD,
373 AccessMode_ReadOnly,
374 false /* fForceNewUuid */,
375 getter_AddRefs(dvdImage));
376 if (NS_FAILED(rc))
377 RTPrintf("Error: could not open CD image! rc=%Rhrc\n", rc);
378 else
379 {
380 /*
381 * Now assign it to our VM
382 */
383 rc = sessionMachine->MountMedium(
384 NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
385 2, // channel number on the controller
386 0, // device number on the controller
387 dvdImage,
388 PR_FALSE); // aForce
389 if (NS_FAILED(rc))
390 {
391 RTPrintf("Error: could not mount ISO image! rc=%Rhrc\n", rc);
392 }
393 else
394 {
395 /*
396 * Last step: tell the VM to boot from the CD.
397 */
398 rc = sessionMachine->SetBootOrder(1, DeviceType::DVD);
399 if (NS_FAILED(rc))
400 {
401 RTPrintf("Could not set boot device! rc=%Rhrc\n", rc);
402 }
403 }
404 }
405
406 /*
407 * Save all changes we've just made.
408 */
409 rc = sessionMachine->SaveSettings();
410 if (NS_FAILED(rc))
411 RTPrintf("Could not save machine settings! rc=%Rhrc\n", rc);
412
413 /*
414 * It is always important to close the open session when it becomes not
415 * necessary any more.
416 */
417 session->UnlockMachine();
418
419 com::SafeIfaceArray<IMedium> aMedia;
420 rc = machine->Unregister((CleanupMode_T)CleanupMode_DetachAllReturnHardDisksOnly,
421 ComSafeArrayAsOutParam(aMedia));
422 if (NS_FAILED(rc))
423 RTPrintf("Unregistering the machine failed! rc=%Rhrc\n", rc);
424 else
425 {
426 ComPtr<IProgress> pProgress;
427 rc = machine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress.asOutParam());
428 if (NS_FAILED(rc))
429 RTPrintf("Deleting of machine failed! rc=%Rhrc\n", rc);
430 else
431 {
432 rc = pProgress->WaitForCompletion(-1);
433 PRInt32 resultCode;
434 pProgress->GetResultCode(&resultCode);
435 if (NS_FAILED(rc) || NS_FAILED(resultCode))
436 RTPrintf("Failed to delete the machine! rc=%Rhrc\n",
437 NS_FAILED(rc) ? rc : resultCode);
438 }
439 }
440}
441
442// main
443///////////////////////////////////////////////////////////////////////////////
444
445int main(int argc, char *argv[])
446{
447 /*
448 * Check that PRUnichar is equal in size to what compiler composes L""
449 * strings from; otherwise NS_LITERAL_STRING macros won't work correctly
450 * and we will get a meaningless SIGSEGV. This, of course, must be checked
451 * at compile time in xpcom/string/nsTDependentString.h, but XPCOM lacks
452 * compile-time assert macros and I'm not going to add them now.
453 */
454 if (sizeof(PRUnichar) != sizeof(wchar_t))
455 {
456 RTPrintf("Error: sizeof(PRUnichar) {%lu} != sizeof(wchar_t) {%lu}!\n"
457 "Probably, you forgot the -fshort-wchar compiler option.\n",
458 (unsigned long) sizeof(PRUnichar),
459 (unsigned long) sizeof(wchar_t));
460 return -1;
461 }
462
463 nsresult rc;
464
465 /*
466 * This is the standard XPCOM init procedure.
467 * What we do is just follow the required steps to get an instance
468 * of our main interface, which is IVirtualBox.
469 *
470 * Note that we scope all nsCOMPtr variables in order to have all XPCOM
471 * objects automatically released before we call NS_ShutdownXPCOM at the
472 * end. This is an XPCOM requirement.
473 */
474 {
475 nsCOMPtr<nsIServiceManager> serviceManager;
476 rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
477 if (NS_FAILED(rc))
478 {
479 RTPrintf("Error: XPCOM could not be initialized! rc=%Rhrc\n", rc);
480 return -1;
481 }
482
483#if 0
484 /*
485 * Register our components. This step is only necessary if this executable
486 * implements XPCOM components itself which is not the case for this
487 * simple example.
488 */
489 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
490 if (!registrar)
491 {
492 RTPrintf("Error: could not query nsIComponentRegistrar interface!\n");
493 return -1;
494 }
495 registrar->AutoRegister(nsnull);
496#endif
497
498 /*
499 * Make sure the main event queue is created. This event queue is
500 * responsible for dispatching incoming XPCOM IPC messages. The main
501 * thread should run this event queue's loop during lengthy non-XPCOM
502 * operations to ensure messages from the VirtualBox server and other
503 * XPCOM IPC clients are processed. This use case doesn't perform such
504 * operations so it doesn't run the event loop.
505 */
506 nsCOMPtr<nsIEventQueue> eventQ;
507 rc = NS_GetMainEventQ(getter_AddRefs(eventQ));
508 if (NS_FAILED(rc))
509 {
510 RTPrintf("Error: could not get main event queue! rc=%Rhrc\n", rc);
511 return -1;
512 }
513
514 /*
515 * Now XPCOM is ready and we can start to do real work.
516 * IVirtualBox is the root interface of VirtualBox and will be
517 * retrieved from the XPCOM component manager. We use the
518 * XPCOM provided smart pointer nsCOMPtr for all objects because
519 * that's very convenient and removes the need deal with reference
520 * counting and freeing.
521 */
522 nsCOMPtr<nsIComponentManager> manager;
523 rc = NS_GetComponentManager(getter_AddRefs(manager));
524 if (NS_FAILED(rc))
525 {
526 RTPrintf("Error: could not get component manager! rc=%Rhrc\n", rc);
527 return -1;
528 }
529
530 nsCOMPtr<IVirtualBox> virtualBox;
531 rc = manager->CreateInstanceByContractID(NS_VIRTUALBOX_CONTRACTID,
532 nsnull,
533 NS_GET_IID(IVirtualBox),
534 getter_AddRefs(virtualBox));
535 if (NS_FAILED(rc))
536 {
537 RTPrintf("Error, could not instantiate VirtualBox object! rc=%Rhrc\n", rc);
538 return -1;
539 }
540 RTPrintf("VirtualBox object created\n");
541
542 ////////////////////////////////////////////////////////////////////////////////
543 ////////////////////////////////////////////////////////////////////////////////
544 ////////////////////////////////////////////////////////////////////////////////
545
546
547 listVMs(virtualBox);
548
549 createVM(virtualBox);
550
551
552 ////////////////////////////////////////////////////////////////////////////////
553 ////////////////////////////////////////////////////////////////////////////////
554 ////////////////////////////////////////////////////////////////////////////////
555
556 /* this is enough to free the IVirtualBox instance -- smart pointers rule! */
557 virtualBox = nsnull;
558
559 /*
560 * Process events that might have queued up in the XPCOM event
561 * queue. If we don't process them, the server might hang.
562 */
563 eventQ->ProcessPendingEvents();
564 }
565
566 /*
567 * Perform the standard XPCOM shutdown procedure.
568 */
569 NS_ShutdownXPCOM(nsnull);
570 RTPrintf("Done!\n");
571 return 0;
572}
573
574
575//////////////////////////////////////////////////////////////////////////////////////////////////////
576//// Helpers
577//////////////////////////////////////////////////////////////////////////////////////////////////////
578
579/**
580 * Helper function to convert an nsID into a human readable string
581 *
582 * @returns result string, allocated. Has to be freed using free()
583 * @param guid Pointer to nsID that will be converted.
584 */
585char *nsIDToString(nsID *guid)
586{
587 char *res = (char*)malloc(39);
588
589 if (res != NULL)
590 {
591 RTStrPrintf(res, 39, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
592 guid->m0, (PRUint32)guid->m1, (PRUint32)guid->m2,
593 (PRUint32)guid->m3[0], (PRUint32)guid->m3[1], (PRUint32)guid->m3[2],
594 (PRUint32)guid->m3[3], (PRUint32)guid->m3[4], (PRUint32)guid->m3[5],
595 (PRUint32)guid->m3[6], (PRUint32)guid->m3[7]);
596 }
597 return res;
598}
599
600/**
601 * Helper function to print XPCOM exception information set on the current
602 * thread after a failed XPCOM method call. This function will also print
603 * extended VirtualBox error info if it is available.
604 */
605void printErrorInfo()
606{
607 nsresult rc;
608
609 nsCOMPtr<nsIExceptionService> es;
610 es = do_GetService(NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
611 if (NS_SUCCEEDED(rc))
612 {
613 nsCOMPtr<nsIExceptionManager> em;
614 rc = es->GetCurrentExceptionManager(getter_AddRefs(em));
615 if (NS_SUCCEEDED(rc))
616 {
617 nsCOMPtr<nsIException> ex;
618 rc = em->GetCurrentException(getter_AddRefs(ex));
619 if (NS_SUCCEEDED(rc) && ex)
620 {
621 nsCOMPtr<IVirtualBoxErrorInfo> info;
622 info = do_QueryInterface(ex, &rc);
623 if (NS_SUCCEEDED(rc) && info)
624 {
625 /* got extended error info */
626 RTPrintf("Extended error info (IVirtualBoxErrorInfo):\n");
627 PRInt32 resultCode = NS_OK;
628 info->GetResultCode(&resultCode);
629 RTPrintf(" resultCode=%08X\n", resultCode);
630 nsXPIDLString component;
631 info->GetComponent(getter_Copies(component));
632 RTPrintf(" component=%s\n", NS_ConvertUTF16toUTF8(component).get());
633 nsXPIDLString text;
634 info->GetText(getter_Copies(text));
635 RTPrintf(" text=%s\n", NS_ConvertUTF16toUTF8(text).get());
636 }
637 else
638 {
639 /* got basic error info */
640 RTPrintf("Basic error info (nsIException):\n");
641 nsresult resultCode = NS_OK;
642 ex->GetResult(&resultCode);
643 RTPrintf(" resultCode=%08X\n", resultCode);
644 nsXPIDLCString message;
645 ex->GetMessage(getter_Copies(message));
646 RTPrintf(" message=%s\n", message.get());
647 }
648
649 /* reset the exception to NULL to indicate we've processed it */
650 em->SetCurrentException(NULL);
651
652 rc = NS_OK;
653 }
654 }
655 }
656}
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