VirtualBox

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

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

Automated rebranding to Oracle copyright/license strings via filemuncher

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