VirtualBox

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

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

Main: reorganize session APIs

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