VirtualBox

source: vbox/trunk/src/VBox/Main/testcase/tstVBoxAPILinux.cpp@ 7449

Last change on this file since 7449 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: 23.3 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-2007 innotek GmbH
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 signle 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#include <errno.h>
66
67/*
68 * Include the XPCOM headers
69 */
70
71#if defined(XPCOM_GLUE)
72#include <nsXPCOMGlue.h>
73#endif
74
75#include <nsMemory.h>
76#include <nsString.h>
77#include <nsIServiceManager.h>
78#include <nsEventQueueUtils.h>
79
80#include <nsIExceptionService.h>
81
82/*
83 * VirtualBox XPCOM interface. This header is generated
84 * from IDL which in turn is generated from a custom XML format.
85 */
86#include "VirtualBox_XPCOM.h"
87
88/*
89 * Prototypes
90 */
91
92char *nsIDToString(nsID *guid);
93void printErrorInfo();
94
95
96/**
97 * Display all registered VMs on the screen with some information about each
98 *
99 * @param virtualBox VirtualBox instance object.
100 */
101void listVMs(IVirtualBox *virtualBox)
102{
103 nsresult rc;
104
105 printf("----------------------------------------------------\n");
106 printf("VM List:\n\n");
107
108 /*
109 * Get the list of all registered VMs
110 */
111 IMachineCollection *collection = nsnull;
112 IMachineEnumerator *enumerator = nsnull;
113 rc = virtualBox->GetMachines(&collection);
114 if (NS_SUCCEEDED(rc))
115 rc = collection->Enumerate(&enumerator);
116 if (NS_SUCCEEDED(rc))
117 {
118 /*
119 * Iterate through the collection
120 */
121 PRBool hasMore = false;
122 while (enumerator->HasMore(&hasMore), hasMore)
123 {
124 IMachine *machine = nsnull;
125 rc = enumerator->GetNext(&machine);
126 if ((NS_SUCCEEDED(rc)) && machine)
127 {
128 PRBool isAccessible = PR_FALSE;
129 machine->GetAccessible (&isAccessible);
130
131 if (isAccessible)
132 {
133 nsXPIDLString machineName;
134 machine->GetName(getter_Copies(machineName));
135 char *machineNameAscii = ToNewCString(machineName);
136 printf("\tName: %s\n", machineNameAscii);
137 free(machineNameAscii);
138 }
139 else
140 {
141 printf("\tName: <inaccessible>\n");
142 }
143
144 nsID *iid = nsnull;
145 machine->GetId(&iid);
146 const char *uuidString = nsIDToString(iid);
147 printf("\tUUID: %s\n", uuidString);
148 free((void*)uuidString);
149 nsMemory::Free(iid);
150
151 if (isAccessible)
152 {
153 nsXPIDLString configFile;
154 machine->GetSettingsFilePath(getter_Copies(configFile));
155 char *configFileAscii = ToNewCString(configFile);
156 printf("\tConfig file: %s\n", configFileAscii);
157 free(configFileAscii);
158
159 PRUint32 memorySize;
160 machine->GetMemorySize(&memorySize);
161 printf("\tMemory size: %uMB\n", memorySize);
162
163 nsXPIDLString typeId;
164 machine->GetOSTypeId(getter_Copies(typeId));
165 IGuestOSType *osType = nsnull;
166 virtualBox->GetGuestOSType (typeId.get(), &osType);
167 nsXPIDLString osName;
168 osType->GetDescription(getter_Copies(osName));
169 char *osNameAscii = ToNewCString(osName);
170 printf("\tGuest OS: %s\n\n", osNameAscii);
171 free(osNameAscii);
172 osType->Release();
173 }
174
175 machine->Release();
176 }
177 }
178 }
179 printf("----------------------------------------------------\n\n");
180 /* don't forget to release the objects... */
181 if (enumerator)
182 enumerator->Release();
183 if (collection)
184 collection->Release();
185}
186
187/**
188 * Create a sample VM
189 *
190 * @param virtualBox VirtualBox instance object.
191 */
192void createVM(IVirtualBox *virtualBox)
193{
194 nsresult rc;
195 /*
196 * First create a unnamed new VM. It will be unconfigured and not be saved
197 * in the configuration until we explicitely choose to do so.
198 */
199 nsID VMuuid = {0};
200 nsCOMPtr <IMachine> machine;
201 rc = virtualBox->CreateMachine(nsnull, NS_LITERAL_STRING("A brand new name").get(),
202 VMuuid, getter_AddRefs(machine));
203 if (NS_FAILED(rc))
204 {
205 printf("Error: could not create machine! rc=%08X\n", rc);
206 return;
207 }
208
209 /*
210 * Set some properties
211 */
212 /* alternative to illustrate the use of string classes */
213 rc = machine->SetName(NS_ConvertUTF8toUTF16("A new name").get());
214 rc = machine->SetMemorySize(128);
215
216 /*
217 * Now a more advanced property -- the guest OS type. This is
218 * an object by itself which has to be found first. Note that we
219 * use the ID of the guest OS type here which is an internal
220 * representation (you can find that by configuring the OS type of
221 * a machine in the GUI and then looking at the <Guest ostype=""/>
222 * setting in the XML file. It is also possible to get the OS type from
223 * its description (win2k would be "Windows 2000") by getting the
224 * guest OS type collection and enumerating it.
225 */
226 nsCOMPtr <IGuestOSType> osType;
227 rc = virtualBox->GetGuestOSType(NS_LITERAL_STRING("win2k").get(),
228 getter_AddRefs(osType));
229 if (NS_FAILED(rc))
230 {
231 printf("Error: could not find guest OS type! rc=%08X\n", rc);
232 }
233 else
234 {
235 machine->SetOSTypeId (NS_LITERAL_STRING("win2k").get());
236 }
237
238 /*
239 * Register the VM. Note that this call also saves the VM config
240 * to disk. It is also possible to save the VM settings but not
241 * register the VM.
242 *
243 * Also note that due to current VirtualBox limitations, the machine
244 * must be registered *before* we can attach hard disks to it.
245 */
246 rc = virtualBox->RegisterMachine(machine);
247 if (NS_FAILED(rc))
248 {
249 printf("Error: could not register machine! rc=%08X\n", rc);
250 printErrorInfo();
251 return;
252 }
253
254 /*
255 * In order to manipulate the registered machine, we must open a session
256 * for that machine. Do it now.
257 */
258 nsCOMPtr<ISession> session;
259 {
260 nsCOMPtr<nsIComponentManager> manager;
261 rc = NS_GetComponentManager (getter_AddRefs (manager));
262 if (NS_FAILED(rc))
263 {
264 printf("Error: could not get component manager! rc=%08X\n", rc);
265 return;
266 }
267 rc = manager->CreateInstanceByContractID (NS_SESSION_CONTRACTID,
268 nsnull,
269 NS_GET_IID(ISession),
270 getter_AddRefs(session));
271 if (NS_FAILED(rc))
272 {
273 printf("Error, could not instantiate Session object! rc=0x%x\n", rc);
274 return;
275 }
276
277 nsID *machineUUID = nsnull;
278 machine->GetId(&machineUUID);
279 rc = virtualBox->OpenSession(session, *machineUUID);
280 nsMemory::Free(machineUUID);
281 if (NS_FAILED(rc))
282 {
283 printf("Error, could not open session! rc=0x%x\n", rc);
284 return;
285 }
286
287 /*
288 * After the machine is registered, the initial machine object becomes
289 * immutable. In order to get a mutable machine object, we must query
290 * it from the opened session object.
291 */
292 rc = session->GetMachine(getter_AddRefs(machine));
293 if (NS_FAILED(rc))
294 {
295 printf("Error, could not get sessioned machine! rc=0x%x\n", rc);
296 return;
297 }
298 }
299
300 /*
301 * Create a virtual harddisk
302 */
303 nsCOMPtr<IHardDisk> hardDisk = 0;
304 nsCOMPtr<IVirtualDiskImage> vdi = 0;
305 rc = virtualBox->CreateHardDisk(HardDiskStorageType::VirtualDiskImage,
306 getter_AddRefs(hardDisk));
307 if (NS_SUCCEEDED (rc))
308 {
309 rc = hardDisk->QueryInterface(NS_GET_IID(IVirtualDiskImage),
310 (void **)(getter_AddRefs(vdi)));
311 if (NS_SUCCEEDED (rc))
312 rc = vdi->SetFilePath(NS_LITERAL_STRING("TestHardDisk.vdi").get());
313 }
314
315 if (NS_FAILED(rc))
316 {
317 printf("Failed creating a hard disk object! rc=%08X\n", rc);
318 }
319 else
320 {
321 /*
322 * We have only created an object so far. No on disk representation exists
323 * because none of its properties has been set so far. Let's continue creating
324 * a dynamically expanding image.
325 */
326 nsCOMPtr <IProgress> progress;
327 rc = vdi->CreateDynamicImage(100, // size in megabytes
328 getter_AddRefs(progress)); // optional progress object
329 if (NS_FAILED(rc))
330 {
331 printf("Failed creating hard disk image! rc=%08X\n", rc);
332 }
333 else
334 {
335 /*
336 * Creating the image is done in the background because it can take quite
337 * some time (at least fixed size images). We have to wait for its completion.
338 * Here we wait forever (timeout -1) which is potentially dangerous.
339 */
340 rc = progress->WaitForCompletion(-1);
341 nsresult resultCode;
342 progress->GetResultCode(&resultCode);
343 if (NS_FAILED(rc) || NS_FAILED(resultCode))
344 {
345 printf("Error: could not create hard disk! rc=%08X\n",
346 NS_FAILED(rc) ? rc : resultCode);
347 }
348 else
349 {
350 /*
351 * Now we have to register the new hard disk with VirtualBox.
352 */
353 rc = virtualBox->RegisterHardDisk(hardDisk);
354 if (NS_FAILED(rc))
355 {
356 printf("Error: could not register hard disk! rc=%08X\n", rc);
357 }
358 else
359 {
360 /*
361 * Now that it's registered, we can assign it to the VM. This is done
362 * by UUID, so query that one fist. The UUID has been assigned automatically
363 * when we've created the image.
364 */
365 nsID *vdiUUID = nsnull;
366 hardDisk->GetId(&vdiUUID);
367 rc = machine->AttachHardDisk(*vdiUUID,
368 StorageBus::IDE, // controler identifier
369 0, // channel number on the controller
370 0); // device number on the controller
371 nsMemory::Free(vdiUUID);
372 if (NS_FAILED(rc))
373 {
374 printf("Error: could not attach hard disk! rc=%08X\n", rc);
375 }
376 }
377 }
378 }
379 }
380
381 /*
382 * It's got a hard disk but that one is new and thus not bootable. Make it
383 * boot from an ISO file. This requires some processing. First the ISO file
384 * has to be registered and then mounted to the VM's DVD drive and selected
385 * as the boot device.
386 */
387 nsID uuid = {0};
388 nsCOMPtr<IDVDImage> dvdImage;
389
390 rc = virtualBox->OpenDVDImage(NS_LITERAL_STRING("/home/achimha/isoimages/winnt4ger.iso").get(),
391 uuid, /* NULL UUID, i.e. a new one will be created */
392 getter_AddRefs(dvdImage));
393 if (NS_FAILED(rc))
394 {
395 printf("Error: could not open CD image! rc=%08X\n", rc);
396 }
397 else
398 {
399 /*
400 * Register it with VBox
401 */
402 rc = virtualBox->RegisterDVDImage(dvdImage);
403 if (NS_FAILED(rc))
404 {
405 printf("Error: could not register CD image! rc=%08X\n", rc);
406 }
407 else
408 {
409 /*
410 * Now assign it to our VM
411 */
412 nsID *isoUUID = nsnull;
413 dvdImage->GetId(&isoUUID);
414 nsCOMPtr<IDVDDrive> dvdDrive;
415 machine->GetDVDDrive(getter_AddRefs(dvdDrive));
416 rc = dvdDrive->MountImage(*isoUUID);
417 nsMemory::Free(isoUUID);
418 if (NS_FAILED(rc))
419 {
420 printf("Error: could not mount ISO image! rc=%08X\n", rc);
421 }
422 else
423 {
424 /*
425 * Last step: tell the VM to boot from the CD.
426 */
427 rc = machine->SetBootOrder (1, DeviceType::DVD);
428 if (NS_FAILED(rc))
429 {
430 printf("Could not set boot device! rc=%08X\n", rc);
431 }
432 }
433 }
434 }
435
436 /*
437 * Save all changes we've just made.
438 */
439 rc = machine->SaveSettings();
440 if (NS_FAILED(rc))
441 {
442 printf("Could not save machine settings! rc=%08X\n", rc);
443 }
444
445 /*
446 * It is always important to close the open session when it becomes not
447 * necessary any more.
448 */
449 session->Close();
450}
451
452// main
453///////////////////////////////////////////////////////////////////////////////
454
455int main(int argc, char *argv[])
456{
457 /*
458 * Check that PRUnichar is equal in size to what compiler composes L""
459 * strings from; otherwise NS_LITERAL_STRING macros won't work correctly
460 * and we will get a meaningless SIGSEGV. This, of course, must be checked
461 * at compile time in xpcom/string/nsTDependentString.h, but XPCOM lacks
462 * compile-time assert macros and I'm not going to add them now.
463 */
464 if (sizeof(PRUnichar) != sizeof(wchar_t))
465 {
466 printf("Error: sizeof(PRUnichar) {%d} != sizeof(wchar_t) {%d}!\n"
467 "Probably, you forgot the -fshort-wchar compiler option.\n",
468 sizeof(PRUnichar), sizeof(wchar_t));
469 return -1;
470 }
471
472 nsresult rc;
473
474 /*
475 * This is the standard XPCOM init procedure.
476 * What we do is just follow the required steps to get an instance
477 * of our main interface, which is IVirtualBox.
478 */
479#if defined(XPCOM_GLUE)
480 XPCOMGlueStartup(nsnull);
481#endif
482
483 /*
484 * Note that we scope all nsCOMPtr variables in order to have all XPCOM
485 * objects automatically released before we call NS_ShutdownXPCOM at the
486 * end. This is an XPCOM requirement.
487 */
488 {
489 nsCOMPtr<nsIServiceManager> serviceManager;
490 rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
491 if (NS_FAILED(rc))
492 {
493 printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc);
494 return -1;
495 }
496
497#if 0
498 /*
499 * Register our components. This step is only necessary if this executable
500 * implements XPCOM components itself which is not the case for this
501 * simple example.
502 */
503 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
504 if (!registrar)
505 {
506 printf("Error: could not query nsIComponentRegistrar interface!\n");
507 return -1;
508 }
509 registrar->AutoRegister(nsnull);
510#endif
511
512 /*
513 * Make sure the main event queue is created. This event queue is
514 * responsible for dispatching incoming XPCOM IPC messages. The main
515 * thread should run this event queue's loop during lengthy non-XPCOM
516 * operations to ensure messages from the VirtualBox server and other
517 * XPCOM IPC clients are processed. This use case doesn't perform such
518 * operations so it doesn't run the event loop.
519 */
520 nsCOMPtr<nsIEventQueue> eventQ;
521 rc = NS_GetMainEventQ(getter_AddRefs (eventQ));
522 if (NS_FAILED(rc))
523 {
524 printf("Error: could not get main event queue! rc=%08X\n", rc);
525 return -1;
526 }
527
528 /*
529 * Now XPCOM is ready and we can start to do real work.
530 * IVirtualBox is the root interface of VirtualBox and will be
531 * retrieved from the XPCOM component manager. We use the
532 * XPCOM provided smart pointer nsCOMPtr for all objects because
533 * that's very convenient and removes the need deal with reference
534 * counting and freeing.
535 */
536 nsCOMPtr<nsIComponentManager> manager;
537 rc = NS_GetComponentManager (getter_AddRefs (manager));
538 if (NS_FAILED(rc))
539 {
540 printf("Error: could not get component manager! rc=%08X\n", rc);
541 return -1;
542 }
543
544 nsCOMPtr<IVirtualBox> virtualBox;
545 rc = manager->CreateInstanceByContractID (NS_VIRTUALBOX_CONTRACTID,
546 nsnull,
547 NS_GET_IID(IVirtualBox),
548 getter_AddRefs(virtualBox));
549 if (NS_FAILED(rc))
550 {
551 printf("Error, could not instantiate VirtualBox object! rc=0x%x\n", rc);
552 return -1;
553 }
554 printf("VirtualBox object created\n");
555
556 ////////////////////////////////////////////////////////////////////////////////
557 ////////////////////////////////////////////////////////////////////////////////
558 ////////////////////////////////////////////////////////////////////////////////
559
560
561 listVMs(virtualBox);
562
563 createVM(virtualBox);
564
565
566 ////////////////////////////////////////////////////////////////////////////////
567 ////////////////////////////////////////////////////////////////////////////////
568 ////////////////////////////////////////////////////////////////////////////////
569
570 /* this is enough to free the IVirtualBox instance -- smart pointers rule! */
571 virtualBox = nsnull;
572
573 /*
574 * Process events that might have queued up in the XPCOM event
575 * queue. If we don't process them, the server might hang.
576 */
577 eventQ->ProcessPendingEvents();
578 }
579
580 /*
581 * Perform the standard XPCOM shutdown procedure.
582 */
583 NS_ShutdownXPCOM(nsnull);
584#if defined(XPCOM_GLUE)
585 XPCOMGlueShutdown();
586#endif
587 printf("Done!\n");
588 return 0;
589}
590
591
592//////////////////////////////////////////////////////////////////////////////////////////////////////
593//// Helpers
594//////////////////////////////////////////////////////////////////////////////////////////////////////
595
596/**
597 * Helper function to convert an nsID into a human readable string
598 *
599 * @returns result string, allocated. Has to be freed using free()
600 * @param guid Pointer to nsID that will be converted.
601 */
602char *nsIDToString(nsID *guid)
603{
604 char *res = (char*)malloc(39);
605
606 if (res != NULL)
607 {
608 snprintf(res, 39, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
609 guid->m0, (PRUint32)guid->m1, (PRUint32)guid->m2,
610 (PRUint32)guid->m3[0], (PRUint32)guid->m3[1], (PRUint32)guid->m3[2],
611 (PRUint32)guid->m3[3], (PRUint32)guid->m3[4], (PRUint32)guid->m3[5],
612 (PRUint32)guid->m3[6], (PRUint32)guid->m3[7]);
613 }
614 return res;
615}
616
617/**
618 * Helper function to print XPCOM exception information set on the current
619 * thread after a failed XPCOM method call. This function will also print
620 * extended VirtualBox error info if it is available.
621 */
622void printErrorInfo()
623{
624 nsresult rc;
625
626 nsCOMPtr <nsIExceptionService> es;
627 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
628 if (NS_SUCCEEDED (rc))
629 {
630 nsCOMPtr <nsIExceptionManager> em;
631 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
632 if (NS_SUCCEEDED (rc))
633 {
634 nsCOMPtr<nsIException> ex;
635 rc = em->GetCurrentException (getter_AddRefs (ex));
636 if (NS_SUCCEEDED (rc) && ex)
637 {
638 nsCOMPtr <IVirtualBoxErrorInfo> info;
639 info = do_QueryInterface(ex, &rc);
640 if (NS_SUCCEEDED(rc) && info)
641 {
642 /* got extended error info */
643 printf ("Extended error info (IVirtualBoxErrorInfo):\n");
644 nsresult resultCode = NS_OK;
645 info->GetResultCode (&resultCode);
646 printf (" resultCode=%08X\n", resultCode);
647 nsXPIDLString component;
648 info->GetComponent (getter_Copies (component));
649 printf (" component=%s\n", NS_ConvertUTF16toUTF8(component).get());
650 nsXPIDLString text;
651 info->GetText (getter_Copies (text));
652 printf (" text=%s\n", NS_ConvertUTF16toUTF8(text).get());
653 }
654 else
655 {
656 /* got basic error info */
657 printf ("Basic error info (nsIException):\n");
658 nsresult resultCode = NS_OK;
659 ex->GetResult (&resultCode);
660 printf (" resultCode=%08X\n", resultCode);
661 nsXPIDLCString message;
662 ex->GetMessage (getter_Copies (message));
663 printf (" message=%s\n", message.get());
664 }
665
666 /* reset the exception to NULL to indicate we've processed it */
667 em->SetCurrentException (NULL);
668
669 rc = NS_OK;
670 }
671 }
672 }
673}
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