VirtualBox

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

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

Main: change VirtualBox::createMachine() to accept arbitrary paths for the XML settings file; remove the override parameter

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette