VirtualBox

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

Last change on this file since 23575 was 23249, checked in by vboxsync, 15 years ago

medium: rename default IDE/FD storage controller names to IDE Controller and Floppy Controller

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