VirtualBox

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

Last change on this file since 31649 was 31615, checked in by vboxsync, 14 years ago

Main: Implemenation of per-machine media registries; VirtualBox::openMedium() no longer adds media to the global registry, instead a media are stored in a machine XML registry after Machine::AttachDevice() has been called; Machine::AttachDevice() now takes an IMedium object instead of a UUID; also make Machine::Unregister() work again for inaccessible machines

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