VirtualBox

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

Last change on this file since 44591 was 44528, checked in by vboxsync, 12 years ago

header (C) fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 22.6 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-2013 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
66/*
67 * Include the XPCOM headers
68 */
69
70#if defined(XPCOM_GLUE)
71#include <nsXPCOMGlue.h>
72#endif
73
74#include <nsMemory.h>
75#include <nsString.h>
76#include <nsIServiceManager.h>
77#include <nsEventQueueUtils.h>
78
79#include <nsIExceptionService.h>
80
81#include <VBox/com/com.h>
82#include <VBox/com/string.h>
83#include <VBox/com/array.h>
84#include <VBox/com/Guid.h>
85#include <VBox/com/ErrorInfo.h>
86#include <VBox/com/errorprint.h>
87#include <VBox/com/EventQueue.h>
88
89#include <VBox/com/VirtualBox.h>
90
91
92/*
93 * VirtualBox XPCOM interface. This header is generated
94 * from IDL which in turn is generated from a custom XML format.
95 */
96#include "VirtualBox_XPCOM.h"
97
98/*
99 * Prototypes
100 */
101
102char *nsIDToString(nsID *guid);
103void printErrorInfo();
104
105
106/**
107 * Display all registered VMs on the screen with some information about each
108 *
109 * @param virtualBox VirtualBox instance object.
110 */
111void listVMs(IVirtualBox *virtualBox)
112{
113 nsresult rc;
114
115 printf("----------------------------------------------------\n");
116 printf("VM List:\n\n");
117
118 /*
119 * Get the list of all registered VMs
120 */
121 IMachine **machines = NULL;
122 PRUint32 machineCnt = 0;
123
124 rc = virtualBox->GetMachines(&machineCnt, &machines);
125 if (NS_SUCCEEDED(rc))
126 {
127 /*
128 * Iterate through the collection
129 */
130 for (PRUint32 i = 0; i < machineCnt; ++ i)
131 {
132 IMachine *machine = machines[i];
133 if (machine)
134 {
135 PRBool isAccessible = PR_FALSE;
136 machine->GetAccessible(&isAccessible);
137
138 if (isAccessible)
139 {
140 nsXPIDLString machineName;
141 machine->GetName(getter_Copies(machineName));
142 char *machineNameAscii = ToNewCString(machineName);
143 printf("\tName: %s\n", machineNameAscii);
144 free(machineNameAscii);
145 }
146 else
147 {
148 printf("\tName: <inaccessible>\n");
149 }
150
151 nsXPIDLString iid;
152 machine->GetId(getter_Copies(iid));
153 const char *uuidString = ToNewCString(iid);
154 printf("\tUUID: %s\n", uuidString);
155 free((void*)uuidString);
156
157 if (isAccessible)
158 {
159 nsXPIDLString configFile;
160 machine->GetSettingsFilePath(getter_Copies(configFile));
161 char *configFileAscii = ToNewCString(configFile);
162 printf("\tConfig file: %s\n", configFileAscii);
163 free(configFileAscii);
164
165 PRUint32 memorySize;
166 machine->GetMemorySize(&memorySize);
167 printf("\tMemory size: %uMB\n", memorySize);
168
169 nsXPIDLString typeId;
170 machine->GetOSTypeId(getter_Copies(typeId));
171 IGuestOSType *osType = nsnull;
172 virtualBox->GetGuestOSType (typeId.get(), &osType);
173 nsXPIDLString osName;
174 osType->GetDescription(getter_Copies(osName));
175 char *osNameAscii = ToNewCString(osName);
176 printf("\tGuest OS: %s\n\n", osNameAscii);
177 free(osNameAscii);
178 osType->Release();
179 }
180
181 /* don't forget to release the objects in the array... */
182 machine->Release();
183 }
184 }
185 }
186 printf("----------------------------------------------------\n\n");
187}
188
189/**
190 * Create a sample VM
191 *
192 * @param virtualBox VirtualBox instance object.
193 */
194void createVM(IVirtualBox *virtualBox)
195{
196 nsresult rc;
197 /*
198 * First create a unnamed new VM. It will be unconfigured and not be saved
199 * in the configuration until we explicitely choose to do so.
200 */
201 nsCOMPtr<IMachine> machine;
202 rc = virtualBox->CreateMachine(NULL, /* settings file */
203 NS_LITERAL_STRING("A brand new name").get(),
204 0, nsnull, /* groups (safearray)*/
205 nsnull, /* ostype */
206 nsnull, /* create flags */
207 getter_AddRefs(machine));
208 if (NS_FAILED(rc))
209 {
210 printf("Error: could not create machine! rc=%08X\n", rc);
211 return;
212 }
213
214 /*
215 * Set some properties
216 */
217 /* alternative to illustrate the use of string classes */
218 rc = machine->SetName(NS_ConvertUTF8toUTF16("A new name").get());
219 rc = machine->SetMemorySize(128);
220
221 /*
222 * Now a more advanced property -- the guest OS type. This is
223 * an object by itself which has to be found first. Note that we
224 * use the ID of the guest OS type here which is an internal
225 * representation (you can find that by configuring the OS type of
226 * a machine in the GUI and then looking at the <Guest ostype=""/>
227 * setting in the XML file. It is also possible to get the OS type from
228 * its description (win2k would be "Windows 2000") by getting the
229 * guest OS type collection and enumerating it.
230 */
231 nsCOMPtr<IGuestOSType> osType;
232 rc = virtualBox->GetGuestOSType(NS_LITERAL_STRING("win2k").get(),
233 getter_AddRefs(osType));
234 if (NS_FAILED(rc))
235 {
236 printf("Error: could not find guest OS type! rc=%08X\n", rc);
237 }
238 else
239 {
240 machine->SetOSTypeId (NS_LITERAL_STRING("win2k").get());
241 }
242
243 /*
244 * Register the VM. Note that this call also saves the VM config
245 * to disk. It is also possible to save the VM settings but not
246 * register the VM.
247 *
248 * Also note that due to current VirtualBox limitations, the machine
249 * must be registered *before* we can attach hard disks to it.
250 */
251 rc = virtualBox->RegisterMachine(machine);
252 if (NS_FAILED(rc))
253 {
254 printf("Error: could not register machine! rc=%08X\n", rc);
255 printErrorInfo();
256 return;
257 }
258
259 /*
260 * In order to manipulate the registered machine, we must open a session
261 * for that machine. Do it now.
262 */
263 nsCOMPtr<ISession> session;
264 {
265 nsCOMPtr<nsIComponentManager> manager;
266 rc = NS_GetComponentManager (getter_AddRefs (manager));
267 if (NS_FAILED(rc))
268 {
269 printf("Error: could not get component manager! rc=%08X\n", rc);
270 return;
271 }
272 rc = manager->CreateInstanceByContractID (NS_SESSION_CONTRACTID,
273 nsnull,
274 NS_GET_IID(ISession),
275 getter_AddRefs(session));
276 if (NS_FAILED(rc))
277 {
278 printf("Error, could not instantiate session object! rc=0x%x\n", rc);
279 return;
280 }
281
282 rc = machine->LockMachine(session, LockType_Write);
283 if (NS_FAILED(rc))
284 {
285 printf("Error, could not lock the machine for the session! rc=0x%x\n", rc);
286 return;
287 }
288
289 /*
290 * After the machine is registered, the initial machine object becomes
291 * immutable. In order to get a mutable machine object, we must query
292 * it from the opened session object.
293 */
294 rc = session->GetMachine(getter_AddRefs(machine));
295 if (NS_FAILED(rc))
296 {
297 printf("Error, could not get machine session! rc=0x%x\n", rc);
298 return;
299 }
300 }
301
302 /*
303 * Create a virtual harddisk
304 */
305 nsCOMPtr<IMedium> hardDisk = 0;
306 rc = virtualBox->CreateHardDisk(NS_LITERAL_STRING("VDI").get(),
307 NS_LITERAL_STRING("TestHardDisk.vdi").get(),
308 getter_AddRefs(hardDisk));
309 if (NS_FAILED(rc))
310 {
311 printf("Failed creating a hard disk object! rc=%08X\n", rc);
312 }
313 else
314 {
315 /*
316 * We have only created an object so far. No on disk representation exists
317 * because none of its properties has been set so far. Let's continue creating
318 * a dynamically expanding image.
319 */
320 nsCOMPtr <IProgress> progress;
321 com::SafeArray<MediumVariant_T> mediumVariant(sizeof(MediumVariant_T)*8);
322 mediumVariant.push_back(MediumVariant_Standard);
323 rc = hardDisk->CreateBaseStorage(100, // size in megabytes
324 ComSafeArrayAsInParam(mediumVariant),
325 getter_AddRefs(progress)); // optional progress object
326 if (NS_FAILED(rc))
327 {
328 printf("Failed creating hard disk image! rc=%08X\n", rc);
329 }
330 else
331 {
332 /*
333 * Creating the image is done in the background because it can take quite
334 * some time (at least fixed size images). We have to wait for its completion.
335 * Here we wait forever (timeout -1) which is potentially dangerous.
336 */
337 rc = progress->WaitForCompletion(-1);
338 PRInt32 resultCode;
339 progress->GetResultCode(&resultCode);
340 if (NS_FAILED(rc) || NS_FAILED(resultCode))
341 {
342 printf("Error: could not create hard disk! rc=%08X\n",
343 NS_FAILED(rc) ? rc : resultCode);
344 }
345 else
346 {
347 /*
348 * Now that it's created, we can assign it to the VM.
349 */
350 rc = machine->AttachDevice(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
351 0, // channel number on the controller
352 0, // device number on the controller
353 DeviceType_HardDisk,
354 hardDisk);
355 if (NS_FAILED(rc))
356 {
357 printf("Error: could not attach hard disk! rc=%08X\n", rc);
358 }
359 }
360 }
361 }
362
363 /*
364 * It's got a hard disk but that one is new and thus not bootable. Make it
365 * boot from an ISO file. This requires some processing. First the ISO file
366 * has to be registered and then mounted to the VM's DVD drive and selected
367 * as the boot device.
368 */
369 nsCOMPtr<IMedium> dvdImage;
370 rc = virtualBox->OpenMedium(NS_LITERAL_STRING("/home/vbox/isos/winnt4ger.iso").get(),
371 DeviceType_DVD,
372 AccessMode_ReadOnly,
373 false /* fForceNewUuid */,
374 getter_AddRefs(dvdImage));
375 if (NS_FAILED(rc))
376 printf("Error: could not open CD image! rc=%08X\n", rc);
377 else
378 {
379 /*
380 * Now assign it to our VM
381 */
382 rc = machine->MountMedium(NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
383 2, // channel number on the controller
384 0, // device number on the controller
385 dvdImage,
386 PR_FALSE); // aForce
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->UnlockMachine();
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 PRInt32 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