VirtualBox

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

Last change on this file since 17825 was 17825, checked in by vboxsync, 16 years ago

API/HardDIsk: introduce parameter for specifying the image variant to be created.

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