VirtualBox

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

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

tstVBoxAPILinux.cpp: typos

  • 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 single 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(NULL, /* settings file */
193 NS_LITERAL_STRING("A brand new name").get(),
194 nsnull, /* ostype */
195 nsnull, /* machine uuid */
196 false, /* forceOverwrite */
197 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 rc = machine->LockMachine(session, LockType_Write);
273 if (NS_FAILED(rc))
274 {
275 printf("Error, could not lock the machine for the session! rc=0x%x\n", rc);
276 return;
277 }
278
279 /*
280 * After the machine is registered, the initial machine object becomes
281 * immutable. In order to get a mutable machine object, we must query
282 * it from the opened session object.
283 */
284 rc = session->GetMachine(getter_AddRefs(machine));
285 if (NS_FAILED(rc))
286 {
287 printf("Error, could not get machine session! rc=0x%x\n", rc);
288 return;
289 }
290 }
291
292 /*
293 * Create a virtual harddisk
294 */
295 nsCOMPtr<IMedium> hardDisk = 0;
296 rc = virtualBox->CreateHardDisk(NS_LITERAL_STRING("VDI").get(),
297 NS_LITERAL_STRING("TestHardDisk.vdi").get(),
298 getter_AddRefs(hardDisk));
299 if (NS_FAILED(rc))
300 {
301 printf("Failed creating a hard disk object! rc=%08X\n", rc);
302 }
303 else
304 {
305 /*
306 * We have only created an object so far. No on disk representation exists
307 * because none of its properties has been set so far. Let's continue creating
308 * a dynamically expanding image.
309 */
310 nsCOMPtr <IProgress> progress;
311 rc = hardDisk->CreateBaseStorage(100, // size in megabytes
312 MediumVariant_Standard,
313 getter_AddRefs(progress)); // optional progress object
314 if (NS_FAILED(rc))
315 {
316 printf("Failed creating hard disk image! rc=%08X\n", rc);
317 }
318 else
319 {
320 /*
321 * Creating the image is done in the background because it can take quite
322 * some time (at least fixed size images). We have to wait for its completion.
323 * Here we wait forever (timeout -1) which is potentially dangerous.
324 */
325 rc = progress->WaitForCompletion(-1);
326 PRInt32 resultCode;
327 progress->GetResultCode(&resultCode);
328 if (NS_FAILED(rc) || NS_FAILED(resultCode))
329 {
330 printf("Error: could not create hard disk! rc=%08X\n",
331 NS_FAILED(rc) ? rc : resultCode);
332 }
333 else
334 {
335 /*
336 * Now that it's created, we can assign it to the VM.
337 */
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 hardDisk);
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 rc = machine->MountMedium(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
370 2, // channel number on the controller
371 0, // device number on the controller
372 dvdImage,
373 PR_FALSE); // aForce
374 if (NS_FAILED(rc))
375 {
376 printf("Error: could not mount ISO image! rc=%08X\n", rc);
377 }
378 else
379 {
380 /*
381 * Last step: tell the VM to boot from the CD.
382 */
383 rc = machine->SetBootOrder (1, DeviceType::DVD);
384 if (NS_FAILED(rc))
385 {
386 printf("Could not set boot device! rc=%08X\n", rc);
387 }
388 }
389 }
390
391 /*
392 * Save all changes we've just made.
393 */
394 rc = machine->SaveSettings();
395 if (NS_FAILED(rc))
396 {
397 printf("Could not save machine settings! rc=%08X\n", rc);
398 }
399
400 /*
401 * It is always important to close the open session when it becomes not
402 * necessary any more.
403 */
404 session->UnlockMachine();
405}
406
407// main
408///////////////////////////////////////////////////////////////////////////////
409
410int main(int argc, char *argv[])
411{
412 /*
413 * Check that PRUnichar is equal in size to what compiler composes L""
414 * strings from; otherwise NS_LITERAL_STRING macros won't work correctly
415 * and we will get a meaningless SIGSEGV. This, of course, must be checked
416 * at compile time in xpcom/string/nsTDependentString.h, but XPCOM lacks
417 * compile-time assert macros and I'm not going to add them now.
418 */
419 if (sizeof(PRUnichar) != sizeof(wchar_t))
420 {
421 printf("Error: sizeof(PRUnichar) {%lu} != sizeof(wchar_t) {%lu}!\n"
422 "Probably, you forgot the -fshort-wchar compiler option.\n",
423 (unsigned long) sizeof(PRUnichar),
424 (unsigned long) sizeof(wchar_t));
425 return -1;
426 }
427
428 nsresult rc;
429
430 /*
431 * This is the standard XPCOM init procedure.
432 * What we do is just follow the required steps to get an instance
433 * of our main interface, which is IVirtualBox.
434 */
435#if defined(XPCOM_GLUE)
436 XPCOMGlueStartup(nsnull);
437#endif
438
439 /*
440 * Note that we scope all nsCOMPtr variables in order to have all XPCOM
441 * objects automatically released before we call NS_ShutdownXPCOM at the
442 * end. This is an XPCOM requirement.
443 */
444 {
445 nsCOMPtr<nsIServiceManager> serviceManager;
446 rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
447 if (NS_FAILED(rc))
448 {
449 printf("Error: XPCOM could not be initialized! rc=0x%x\n", rc);
450 return -1;
451 }
452
453#if 0
454 /*
455 * Register our components. This step is only necessary if this executable
456 * implements XPCOM components itself which is not the case for this
457 * simple example.
458 */
459 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
460 if (!registrar)
461 {
462 printf("Error: could not query nsIComponentRegistrar interface!\n");
463 return -1;
464 }
465 registrar->AutoRegister(nsnull);
466#endif
467
468 /*
469 * Make sure the main event queue is created. This event queue is
470 * responsible for dispatching incoming XPCOM IPC messages. The main
471 * thread should run this event queue's loop during lengthy non-XPCOM
472 * operations to ensure messages from the VirtualBox server and other
473 * XPCOM IPC clients are processed. This use case doesn't perform such
474 * operations so it doesn't run the event loop.
475 */
476 nsCOMPtr<nsIEventQueue> eventQ;
477 rc = NS_GetMainEventQ(getter_AddRefs (eventQ));
478 if (NS_FAILED(rc))
479 {
480 printf("Error: could not get main event queue! rc=%08X\n", rc);
481 return -1;
482 }
483
484 /*
485 * Now XPCOM is ready and we can start to do real work.
486 * IVirtualBox is the root interface of VirtualBox and will be
487 * retrieved from the XPCOM component manager. We use the
488 * XPCOM provided smart pointer nsCOMPtr for all objects because
489 * that's very convenient and removes the need deal with reference
490 * counting and freeing.
491 */
492 nsCOMPtr<nsIComponentManager> manager;
493 rc = NS_GetComponentManager (getter_AddRefs (manager));
494 if (NS_FAILED(rc))
495 {
496 printf("Error: could not get component manager! rc=%08X\n", rc);
497 return -1;
498 }
499
500 nsCOMPtr<IVirtualBox> virtualBox;
501 rc = manager->CreateInstanceByContractID (NS_VIRTUALBOX_CONTRACTID,
502 nsnull,
503 NS_GET_IID(IVirtualBox),
504 getter_AddRefs(virtualBox));
505 if (NS_FAILED(rc))
506 {
507 printf("Error, could not instantiate VirtualBox object! rc=0x%x\n", rc);
508 return -1;
509 }
510 printf("VirtualBox object created\n");
511
512 ////////////////////////////////////////////////////////////////////////////////
513 ////////////////////////////////////////////////////////////////////////////////
514 ////////////////////////////////////////////////////////////////////////////////
515
516
517 listVMs(virtualBox);
518
519 createVM(virtualBox);
520
521
522 ////////////////////////////////////////////////////////////////////////////////
523 ////////////////////////////////////////////////////////////////////////////////
524 ////////////////////////////////////////////////////////////////////////////////
525
526 /* this is enough to free the IVirtualBox instance -- smart pointers rule! */
527 virtualBox = nsnull;
528
529 /*
530 * Process events that might have queued up in the XPCOM event
531 * queue. If we don't process them, the server might hang.
532 */
533 eventQ->ProcessPendingEvents();
534 }
535
536 /*
537 * Perform the standard XPCOM shutdown procedure.
538 */
539 NS_ShutdownXPCOM(nsnull);
540#if defined(XPCOM_GLUE)
541 XPCOMGlueShutdown();
542#endif
543 printf("Done!\n");
544 return 0;
545}
546
547
548//////////////////////////////////////////////////////////////////////////////////////////////////////
549//// Helpers
550//////////////////////////////////////////////////////////////////////////////////////////////////////
551
552/**
553 * Helper function to convert an nsID into a human readable string
554 *
555 * @returns result string, allocated. Has to be freed using free()
556 * @param guid Pointer to nsID that will be converted.
557 */
558char *nsIDToString(nsID *guid)
559{
560 char *res = (char*)malloc(39);
561
562 if (res != NULL)
563 {
564 snprintf(res, 39, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
565 guid->m0, (PRUint32)guid->m1, (PRUint32)guid->m2,
566 (PRUint32)guid->m3[0], (PRUint32)guid->m3[1], (PRUint32)guid->m3[2],
567 (PRUint32)guid->m3[3], (PRUint32)guid->m3[4], (PRUint32)guid->m3[5],
568 (PRUint32)guid->m3[6], (PRUint32)guid->m3[7]);
569 }
570 return res;
571}
572
573/**
574 * Helper function to print XPCOM exception information set on the current
575 * thread after a failed XPCOM method call. This function will also print
576 * extended VirtualBox error info if it is available.
577 */
578void printErrorInfo()
579{
580 nsresult rc;
581
582 nsCOMPtr <nsIExceptionService> es;
583 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
584 if (NS_SUCCEEDED(rc))
585 {
586 nsCOMPtr <nsIExceptionManager> em;
587 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
588 if (NS_SUCCEEDED(rc))
589 {
590 nsCOMPtr<nsIException> ex;
591 rc = em->GetCurrentException (getter_AddRefs (ex));
592 if (NS_SUCCEEDED(rc) && ex)
593 {
594 nsCOMPtr <IVirtualBoxErrorInfo> info;
595 info = do_QueryInterface(ex, &rc);
596 if (NS_SUCCEEDED(rc) && info)
597 {
598 /* got extended error info */
599 printf ("Extended error info (IVirtualBoxErrorInfo):\n");
600 PRInt32 resultCode = NS_OK;
601 info->GetResultCode (&resultCode);
602 printf (" resultCode=%08X\n", resultCode);
603 nsXPIDLString component;
604 info->GetComponent (getter_Copies (component));
605 printf (" component=%s\n", NS_ConvertUTF16toUTF8(component).get());
606 nsXPIDLString text;
607 info->GetText (getter_Copies (text));
608 printf (" text=%s\n", NS_ConvertUTF16toUTF8(text).get());
609 }
610 else
611 {
612 /* got basic error info */
613 printf ("Basic error info (nsIException):\n");
614 nsresult resultCode = NS_OK;
615 ex->GetResult (&resultCode);
616 printf (" resultCode=%08X\n", resultCode);
617 nsXPIDLCString message;
618 ex->GetMessage (getter_Copies (message));
619 printf (" message=%s\n", message.get());
620 }
621
622 /* reset the exception to NULL to indicate we've processed it */
623 em->SetCurrentException (NULL);
624
625 rc = NS_OK;
626 }
627 }
628 }
629}
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