VirtualBox

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

Last change on this file since 31570 was 31568, checked in by vboxsync, 15 years ago

Main: combine IVirtualBox::openHardDisk(), openDVDImage(), openFloppyImage() into new IVirtualBox::openMedium(); add new IMedium::setImageUUIDs() method for a rare use case of the old openHardDisk(); optimize client code now that code is mostly the same

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 22.2 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. This is done
333 * by UUID, so query that one fist. The UUID has been assigned automatically
334 * when we've created the image.
335 */
336 nsXPIDLString vdiUUID;
337 hardDisk->GetId(getter_Copies(vdiUUID));
338 rc = machine->AttachDevice(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
339 0, // channel number on the controller
340 0, // device number on the controller
341 DeviceType_HardDisk,
342 vdiUUID);
343 if (NS_FAILED(rc))
344 {
345 printf("Error: could not attach hard disk! rc=%08X\n", rc);
346 }
347 }
348 }
349 }
350
351 /*
352 * It's got a hard disk but that one is new and thus not bootable. Make it
353 * boot from an ISO file. This requires some processing. First the ISO file
354 * has to be registered and then mounted to the VM's DVD drive and selected
355 * as the boot device.
356 */
357 nsCOMPtr<IMedium> dvdImage;
358 rc = virtualBox->OpenMedium(NS_LITERAL_STRING("/home/vbox/isos/winnt4ger.iso").get(),
359 DeviceType_DVD,
360 AccessMode_ReadOnly,
361 getter_AddRefs(dvdImage));
362 if (NS_FAILED(rc))
363 printf("Error: could not open CD image! rc=%08X\n", rc);
364 else
365 {
366 /*
367 * Now assign it to our VM
368 */
369 nsXPIDLString isoUUID;
370 dvdImage->GetId(getter_Copies(isoUUID));
371 rc = machine->MountMedium(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
372 2, // channel number on the controller
373 0, // device number on the controller
374 isoUUID,
375 PR_FALSE); // aForce
376 if (NS_FAILED(rc))
377 {
378 printf("Error: could not mount ISO image! rc=%08X\n", rc);
379 }
380 else
381 {
382 /*
383 * Last step: tell the VM to boot from the CD.
384 */
385 rc = machine->SetBootOrder (1, DeviceType::DVD);
386 if (NS_FAILED(rc))
387 {
388 printf("Could not set boot device! rc=%08X\n", rc);
389 }
390 }
391 }
392
393 /*
394 * Save all changes we've just made.
395 */
396 rc = machine->SaveSettings();
397 if (NS_FAILED(rc))
398 {
399 printf("Could not save machine settings! rc=%08X\n", rc);
400 }
401
402 /*
403 * It is always important to close the open session when it becomes not
404 * necessary any more.
405 */
406 session->UnlockMachine();
407}
408
409// main
410///////////////////////////////////////////////////////////////////////////////
411
412int main(int argc, char *argv[])
413{
414 /*
415 * Check that PRUnichar is equal in size to what compiler composes L""
416 * strings from; otherwise NS_LITERAL_STRING macros won't work correctly
417 * and we will get a meaningless SIGSEGV. This, of course, must be checked
418 * at compile time in xpcom/string/nsTDependentString.h, but XPCOM lacks
419 * compile-time assert macros and I'm not going to add them now.
420 */
421 if (sizeof(PRUnichar) != sizeof(wchar_t))
422 {
423 printf("Error: sizeof(PRUnichar) {%lu} != sizeof(wchar_t) {%lu}!\n"
424 "Probably, you forgot the -fshort-wchar compiler option.\n",
425 (unsigned long) sizeof(PRUnichar),
426 (unsigned long) sizeof(wchar_t));
427 return -1;
428 }
429
430 nsresult rc;
431
432 /*
433 * This is the standard XPCOM init procedure.
434 * What we do is just follow the required steps to get an instance
435 * of our main interface, which is IVirtualBox.
436 */
437#if defined(XPCOM_GLUE)
438 XPCOMGlueStartup(nsnull);
439#endif
440
441 /*
442 * Note that we scope all nsCOMPtr variables in order to have all XPCOM
443 * objects automatically released before we call NS_ShutdownXPCOM at the
444 * end. This is an XPCOM requirement.
445 */
446 {
447 nsCOMPtr<nsIServiceManager> serviceManager;
448 rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
449 if (NS_FAILED(rc))
450 {
451 printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc);
452 return -1;
453 }
454
455#if 0
456 /*
457 * Register our components. This step is only necessary if this executable
458 * implements XPCOM components itself which is not the case for this
459 * simple example.
460 */
461 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
462 if (!registrar)
463 {
464 printf("Error: could not query nsIComponentRegistrar interface!\n");
465 return -1;
466 }
467 registrar->AutoRegister(nsnull);
468#endif
469
470 /*
471 * Make sure the main event queue is created. This event queue is
472 * responsible for dispatching incoming XPCOM IPC messages. The main
473 * thread should run this event queue's loop during lengthy non-XPCOM
474 * operations to ensure messages from the VirtualBox server and other
475 * XPCOM IPC clients are processed. This use case doesn't perform such
476 * operations so it doesn't run the event loop.
477 */
478 nsCOMPtr<nsIEventQueue> eventQ;
479 rc = NS_GetMainEventQ(getter_AddRefs (eventQ));
480 if (NS_FAILED(rc))
481 {
482 printf("Error: could not get main event queue! rc=%08X\n", rc);
483 return -1;
484 }
485
486 /*
487 * Now XPCOM is ready and we can start to do real work.
488 * IVirtualBox is the root interface of VirtualBox and will be
489 * retrieved from the XPCOM component manager. We use the
490 * XPCOM provided smart pointer nsCOMPtr for all objects because
491 * that's very convenient and removes the need deal with reference
492 * counting and freeing.
493 */
494 nsCOMPtr<nsIComponentManager> manager;
495 rc = NS_GetComponentManager (getter_AddRefs (manager));
496 if (NS_FAILED(rc))
497 {
498 printf("Error: could not get component manager! rc=%08X\n", rc);
499 return -1;
500 }
501
502 nsCOMPtr<IVirtualBox> virtualBox;
503 rc = manager->CreateInstanceByContractID (NS_VIRTUALBOX_CONTRACTID,
504 nsnull,
505 NS_GET_IID(IVirtualBox),
506 getter_AddRefs(virtualBox));
507 if (NS_FAILED(rc))
508 {
509 printf("Error, could not instantiate VirtualBox object! rc=0x%x\n", rc);
510 return -1;
511 }
512 printf("VirtualBox object created\n");
513
514 ////////////////////////////////////////////////////////////////////////////////
515 ////////////////////////////////////////////////////////////////////////////////
516 ////////////////////////////////////////////////////////////////////////////////
517
518
519 listVMs(virtualBox);
520
521 createVM(virtualBox);
522
523
524 ////////////////////////////////////////////////////////////////////////////////
525 ////////////////////////////////////////////////////////////////////////////////
526 ////////////////////////////////////////////////////////////////////////////////
527
528 /* this is enough to free the IVirtualBox instance -- smart pointers rule! */
529 virtualBox = nsnull;
530
531 /*
532 * Process events that might have queued up in the XPCOM event
533 * queue. If we don't process them, the server might hang.
534 */
535 eventQ->ProcessPendingEvents();
536 }
537
538 /*
539 * Perform the standard XPCOM shutdown procedure.
540 */
541 NS_ShutdownXPCOM(nsnull);
542#if defined(XPCOM_GLUE)
543 XPCOMGlueShutdown();
544#endif
545 printf("Done!\n");
546 return 0;
547}
548
549
550//////////////////////////////////////////////////////////////////////////////////////////////////////
551//// Helpers
552//////////////////////////////////////////////////////////////////////////////////////////////////////
553
554/**
555 * Helper function to convert an nsID into a human readable string
556 *
557 * @returns result string, allocated. Has to be freed using free()
558 * @param guid Pointer to nsID that will be converted.
559 */
560char *nsIDToString(nsID *guid)
561{
562 char *res = (char*)malloc(39);
563
564 if (res != NULL)
565 {
566 snprintf(res, 39, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
567 guid->m0, (PRUint32)guid->m1, (PRUint32)guid->m2,
568 (PRUint32)guid->m3[0], (PRUint32)guid->m3[1], (PRUint32)guid->m3[2],
569 (PRUint32)guid->m3[3], (PRUint32)guid->m3[4], (PRUint32)guid->m3[5],
570 (PRUint32)guid->m3[6], (PRUint32)guid->m3[7]);
571 }
572 return res;
573}
574
575/**
576 * Helper function to print XPCOM exception information set on the current
577 * thread after a failed XPCOM method call. This function will also print
578 * extended VirtualBox error info if it is available.
579 */
580void printErrorInfo()
581{
582 nsresult rc;
583
584 nsCOMPtr <nsIExceptionService> es;
585 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
586 if (NS_SUCCEEDED(rc))
587 {
588 nsCOMPtr <nsIExceptionManager> em;
589 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
590 if (NS_SUCCEEDED(rc))
591 {
592 nsCOMPtr<nsIException> ex;
593 rc = em->GetCurrentException (getter_AddRefs (ex));
594 if (NS_SUCCEEDED(rc) && ex)
595 {
596 nsCOMPtr <IVirtualBoxErrorInfo> info;
597 info = do_QueryInterface(ex, &rc);
598 if (NS_SUCCEEDED(rc) && info)
599 {
600 /* got extended error info */
601 printf ("Extended error info (IVirtualBoxErrorInfo):\n");
602 PRInt32 resultCode = NS_OK;
603 info->GetResultCode (&resultCode);
604 printf (" resultCode=%08X\n", resultCode);
605 nsXPIDLString component;
606 info->GetComponent (getter_Copies (component));
607 printf (" component=%s\n", NS_ConvertUTF16toUTF8(component).get());
608 nsXPIDLString text;
609 info->GetText (getter_Copies (text));
610 printf (" text=%s\n", NS_ConvertUTF16toUTF8(text).get());
611 }
612 else
613 {
614 /* got basic error info */
615 printf ("Basic error info (nsIException):\n");
616 nsresult resultCode = NS_OK;
617 ex->GetResult (&resultCode);
618 printf (" resultCode=%08X\n", resultCode);
619 nsXPIDLCString message;
620 ex->GetMessage (getter_Copies (message));
621 printf (" message=%s\n", message.get());
622 }
623
624 /* reset the exception to NULL to indicate we've processed it */
625 em->SetCurrentException (NULL);
626
627 rc = NS_OK;
628 }
629 }
630 }
631}
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette