VirtualBox

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

最後變更 在這個檔案從47813是 47813,由 vboxsync 提交於 12 年 前

tstVBoxAPILinux: a few fixes and make sure to remove the registered VM at the end

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 23.8 KB
 
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.alldomusa.eu.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#include <iprt/stream.h>
92
93
94/*
95 * VirtualBox XPCOM interface. This header is generated
96 * from IDL which in turn is generated from a custom XML format.
97 */
98#include "VirtualBox_XPCOM.h"
99
100/*
101 * Prototypes
102 */
103
104char *nsIDToString(nsID *guid);
105void printErrorInfo();
106
107
108/**
109 * Display all registered VMs on the screen with some information about each
110 *
111 * @param virtualBox VirtualBox instance object.
112 */
113void listVMs(IVirtualBox *virtualBox)
114{
115 nsresult rc;
116
117 RTPrintf("----------------------------------------------------\n");
118 RTPrintf("VM List:\n\n");
119
120 /*
121 * Get the list of all registered VMs
122 */
123 IMachine **machines = NULL;
124 PRUint32 machineCnt = 0;
125
126 rc = virtualBox->GetMachines(&machineCnt, &machines);
127 if (NS_SUCCEEDED(rc))
128 {
129 /*
130 * Iterate through the collection
131 */
132 for (PRUint32 i = 0; i < machineCnt; ++ i)
133 {
134 IMachine *machine = machines[i];
135 if (machine)
136 {
137 PRBool isAccessible = PR_FALSE;
138 machine->GetAccessible(&isAccessible);
139
140 if (isAccessible)
141 {
142 nsXPIDLString machineName;
143 machine->GetName(getter_Copies(machineName));
144 char *machineNameAscii = ToNewCString(machineName);
145 RTPrintf("\tName: %s\n", machineNameAscii);
146 free(machineNameAscii);
147 }
148 else
149 {
150 RTPrintf("\tName: <inaccessible>\n");
151 }
152
153 nsXPIDLString iid;
154 machine->GetId(getter_Copies(iid));
155 const char *uuidString = ToNewCString(iid);
156 RTPrintf("\tUUID: %s\n", uuidString);
157 free((void*)uuidString);
158
159 if (isAccessible)
160 {
161 nsXPIDLString configFile;
162 machine->GetSettingsFilePath(getter_Copies(configFile));
163 char *configFileAscii = ToNewCString(configFile);
164 RTPrintf("\tConfig file: %s\n", configFileAscii);
165 free(configFileAscii);
166
167 PRUint32 memorySize;
168 machine->GetMemorySize(&memorySize);
169 RTPrintf("\tMemory size: %uMB\n", memorySize);
170
171 nsXPIDLString typeId;
172 machine->GetOSTypeId(getter_Copies(typeId));
173 IGuestOSType *osType = nsnull;
174 virtualBox->GetGuestOSType (typeId.get(), &osType);
175 nsXPIDLString osName;
176 osType->GetDescription(getter_Copies(osName));
177 char *osNameAscii = ToNewCString(osName);
178 RTPrintf("\tGuest OS: %s\n\n", osNameAscii);
179 free(osNameAscii);
180 osType->Release();
181 }
182
183 /* don't forget to release the objects in the array... */
184 machine->Release();
185 }
186 }
187 }
188 RTPrintf("----------------------------------------------------\n\n");
189}
190
191/**
192 * Create a sample VM
193 *
194 * @param virtualBox VirtualBox instance object.
195 */
196void createVM(IVirtualBox *virtualBox)
197{
198 nsresult rc;
199 /*
200 * First create a unnamed new VM. It will be unconfigured and not be saved
201 * in the configuration until we explicitely choose to do so.
202 */
203 nsCOMPtr<IMachine> machine;
204 rc = virtualBox->CreateMachine(NULL, /* settings file */
205 NS_LITERAL_STRING("A brand new name").get(),
206 0, nsnull, /* groups (safearray)*/
207 nsnull, /* ostype */
208 nsnull, /* create flags */
209 getter_AddRefs(machine));
210 if (NS_FAILED(rc))
211 {
212 RTPrintf("Error: could not create machine! rc=%Rhrc\n", rc);
213 return;
214 }
215
216 /*
217 * Set some properties
218 */
219 /* alternative to illustrate the use of string classes */
220 rc = machine->SetName(NS_ConvertUTF8toUTF16("A new name").get());
221 rc = machine->SetMemorySize(128);
222
223 /*
224 * Now a more advanced property -- the guest OS type. This is
225 * an object by itself which has to be found first. Note that we
226 * use the ID of the guest OS type here which is an internal
227 * representation (you can find that by configuring the OS type of
228 * a machine in the GUI and then looking at the <Guest ostype=""/>
229 * setting in the XML file. It is also possible to get the OS type from
230 * its description (win2k would be "Windows 2000") by getting the
231 * guest OS type collection and enumerating it.
232 */
233 nsCOMPtr<IGuestOSType> osType;
234 rc = virtualBox->GetGuestOSType(NS_LITERAL_STRING("Windows2000").get(),
235 getter_AddRefs(osType));
236 if (NS_FAILED(rc))
237 {
238 RTPrintf("Error: could not find guest OS type! rc=%Rhrc\n", rc);
239 }
240 else
241 {
242 machine->SetOSTypeId (NS_LITERAL_STRING("Windows2000").get());
243 }
244
245 /*
246 * Register the VM. Note that this call also saves the VM config
247 * to disk. It is also possible to save the VM settings but not
248 * register the VM.
249 *
250 * Also note that due to current VirtualBox limitations, the machine
251 * must be registered *before* we can attach hard disks to it.
252 */
253 rc = virtualBox->RegisterMachine(machine);
254 if (NS_FAILED(rc))
255 {
256 RTPrintf("Error: could not register machine! rc=%Rhrc\n", rc);
257 printErrorInfo();
258 return;
259 }
260
261 nsCOMPtr<IMachine> origMachine = machine;
262
263 /*
264 * In order to manipulate the registered machine, we must open a session
265 * for that machine. Do it now.
266 */
267 nsCOMPtr<ISession> session;
268 nsCOMPtr<IMachine> sessionMachine;
269 {
270 nsCOMPtr<nsIComponentManager> manager;
271 rc = NS_GetComponentManager (getter_AddRefs (manager));
272 if (NS_FAILED(rc))
273 {
274 RTPrintf("Error: could not get component manager! rc=%Rhrc\n", rc);
275 return;
276 }
277 rc = manager->CreateInstanceByContractID (NS_SESSION_CONTRACTID,
278 nsnull,
279 NS_GET_IID(ISession),
280 getter_AddRefs(session));
281 if (NS_FAILED(rc))
282 {
283 RTPrintf("Error, could not instantiate session object! rc=0x%x\n", rc);
284 return;
285 }
286
287 rc = machine->LockMachine(session, LockType_Write);
288 if (NS_FAILED(rc))
289 {
290 RTPrintf("Error, could not lock the machine for the session! rc=0x%x\n", rc);
291 return;
292 }
293
294 /*
295 * After the machine is registered, the initial machine object becomes
296 * immutable. In order to get a mutable machine object, we must query
297 * it from the opened session object.
298 */
299 rc = session->GetMachine(getter_AddRefs(sessionMachine));
300 if (NS_FAILED(rc))
301 {
302 RTPrintf("Error, could not get machine session! rc=0x%x\n", rc);
303 return;
304 }
305 }
306
307 /*
308 * Create a virtual harddisk
309 */
310 nsCOMPtr<IMedium> hardDisk = 0;
311 rc = virtualBox->CreateHardDisk(NS_LITERAL_STRING("VDI").get(),
312 NS_LITERAL_STRING("TestHardDisk.vdi").get(),
313 getter_AddRefs(hardDisk));
314 if (NS_FAILED(rc))
315 {
316 RTPrintf("Failed creating a hard disk object! rc=%Rhrc\n", rc);
317 }
318 else
319 {
320 /*
321 * We have only created an object so far. No on disk representation exists
322 * because none of its properties has been set so far. Let's continue creating
323 * a dynamically expanding image.
324 */
325 nsCOMPtr <IProgress> progress;
326 com::SafeArray<MediumVariant_T> mediumVariant(sizeof(MediumVariant_T)*8);
327 mediumVariant.push_back(MediumVariant_Standard);
328 rc = hardDisk->CreateBaseStorage(100, // size in megabytes
329 ComSafeArrayAsInParam(mediumVariant),
330 getter_AddRefs(progress)); // optional progress object
331 if (NS_FAILED(rc))
332 {
333 RTPrintf("Failed creating hard disk image! rc=%Rhrc\n", rc);
334 }
335 else
336 {
337 /*
338 * Creating the image is done in the background because it can take quite
339 * some time (at least fixed size images). We have to wait for its completion.
340 * Here we wait forever (timeout -1) which is potentially dangerous.
341 */
342 rc = progress->WaitForCompletion(-1);
343 PRInt32 resultCode;
344 progress->GetResultCode(&resultCode);
345 if (NS_FAILED(rc) || NS_FAILED(resultCode))
346 {
347 RTPrintf("Error: could not create hard disk! rc=%Rhrc\n",
348 NS_FAILED(rc) ? rc : resultCode);
349 }
350 else
351 {
352 /*
353 * Now that it's created, we can assign it to the VM.
354 */
355 rc = sessionMachine->AttachDevice(
356 NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
357 0, // channel number on the controller
358 0, // device number on the controller
359 DeviceType_HardDisk,
360 hardDisk);
361 if (NS_FAILED(rc))
362 {
363 RTPrintf("Error: could not attach hard disk! rc=%Rhrc\n", rc);
364 }
365 }
366 }
367 }
368
369 /*
370 * It's got a hard disk but that one is new and thus not bootable. Make it
371 * boot from an ISO file. This requires some processing. First the ISO file
372 * has to be registered and then mounted to the VM's DVD drive and selected
373 * as the boot device.
374 */
375 nsCOMPtr<IMedium> dvdImage;
376 rc = virtualBox->OpenMedium(NS_LITERAL_STRING("/home/vbox/isos/winnt4ger.iso").get(),
377 DeviceType_DVD,
378 AccessMode_ReadOnly,
379 false /* fForceNewUuid */,
380 getter_AddRefs(dvdImage));
381 if (NS_FAILED(rc))
382 RTPrintf("Error: could not open CD image! rc=%Rhrc\n", rc);
383 else
384 {
385 /*
386 * Now assign it to our VM
387 */
388 rc = sessionMachine->MountMedium(
389 NS_LITERAL_STRING("IDE Controller").get(), // controller identifier
390 2, // channel number on the controller
391 0, // device number on the controller
392 dvdImage,
393 PR_FALSE); // aForce
394 if (NS_FAILED(rc))
395 {
396 RTPrintf("Error: could not mount ISO image! rc=%Rhrc\n", rc);
397 }
398 else
399 {
400 /*
401 * Last step: tell the VM to boot from the CD.
402 */
403 rc = sessionMachine->SetBootOrder (1, DeviceType::DVD);
404 if (NS_FAILED(rc))
405 {
406 RTPrintf("Could not set boot device! rc=%Rhrc\n", rc);
407 }
408 }
409 }
410
411 /*
412 * Save all changes we've just made.
413 */
414 rc = sessionMachine->SaveSettings();
415 if (NS_FAILED(rc))
416 RTPrintf("Could not save machine settings! rc=%Rhrc\n", rc);
417
418 /*
419 * It is always important to close the open session when it becomes not
420 * necessary any more.
421 */
422 session->UnlockMachine();
423
424 com::SafeIfaceArray<IMedium> aMedia;
425 rc = machine->Unregister((CleanupMode_T)CleanupMode_DetachAllReturnHardDisksOnly,
426 ComSafeArrayAsOutParam(aMedia));
427 if (NS_FAILED(rc))
428 RTPrintf("Unregistering the machine failed! rc=%Rhrc\n", rc);
429 else
430 {
431 ComPtr<IProgress> pProgress;
432 rc = machine->DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress.asOutParam());
433 if (NS_FAILED(rc))
434 RTPrintf("Deleting of machine failed! rc=%Rhrc\n", rc);
435 else
436 {
437 rc = pProgress->WaitForCompletion(-1);
438 PRInt32 resultCode;
439 pProgress->GetResultCode(&resultCode);
440 if (NS_FAILED(rc) || NS_FAILED(resultCode))
441 RTPrintf("Failed to delete the machine! rc=%Rhrc\n",
442 NS_FAILED(rc) ? rc : resultCode);
443 }
444 }
445}
446
447// main
448///////////////////////////////////////////////////////////////////////////////
449
450int main(int argc, char *argv[])
451{
452 /*
453 * Check that PRUnichar is equal in size to what compiler composes L""
454 * strings from; otherwise NS_LITERAL_STRING macros won't work correctly
455 * and we will get a meaningless SIGSEGV. This, of course, must be checked
456 * at compile time in xpcom/string/nsTDependentString.h, but XPCOM lacks
457 * compile-time assert macros and I'm not going to add them now.
458 */
459 if (sizeof(PRUnichar) != sizeof(wchar_t))
460 {
461 RTPrintf("Error: sizeof(PRUnichar) {%lu} != sizeof(wchar_t) {%lu}!\n"
462 "Probably, you forgot the -fshort-wchar compiler option.\n",
463 (unsigned long) sizeof(PRUnichar),
464 (unsigned long) sizeof(wchar_t));
465 return -1;
466 }
467
468 nsresult rc;
469
470 /*
471 * This is the standard XPCOM init procedure.
472 * What we do is just follow the required steps to get an instance
473 * of our main interface, which is IVirtualBox.
474 */
475#if defined(XPCOM_GLUE)
476 XPCOMGlueStartup(nsnull);
477#endif
478
479 /*
480 * Note that we scope all nsCOMPtr variables in order to have all XPCOM
481 * objects automatically released before we call NS_ShutdownXPCOM at the
482 * end. This is an XPCOM requirement.
483 */
484 {
485 nsCOMPtr<nsIServiceManager> serviceManager;
486 rc = NS_InitXPCOM2(getter_AddRefs(serviceManager), nsnull, nsnull);
487 if (NS_FAILED(rc))
488 {
489 RTPrintf("Error: XPCOM could not be initialized! rc=0x%x\n", rc);
490 return -1;
491 }
492
493#if 0
494 /*
495 * Register our components. This step is only necessary if this executable
496 * implements XPCOM components itself which is not the case for this
497 * simple example.
498 */
499 nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(serviceManager);
500 if (!registrar)
501 {
502 RTPrintf("Error: could not query nsIComponentRegistrar interface!\n");
503 return -1;
504 }
505 registrar->AutoRegister(nsnull);
506#endif
507
508 /*
509 * Make sure the main event queue is created. This event queue is
510 * responsible for dispatching incoming XPCOM IPC messages. The main
511 * thread should run this event queue's loop during lengthy non-XPCOM
512 * operations to ensure messages from the VirtualBox server and other
513 * XPCOM IPC clients are processed. This use case doesn't perform such
514 * operations so it doesn't run the event loop.
515 */
516 nsCOMPtr<nsIEventQueue> eventQ;
517 rc = NS_GetMainEventQ(getter_AddRefs (eventQ));
518 if (NS_FAILED(rc))
519 {
520 RTPrintf("Error: could not get main event queue! rc=%Rhrc\n", rc);
521 return -1;
522 }
523
524 /*
525 * Now XPCOM is ready and we can start to do real work.
526 * IVirtualBox is the root interface of VirtualBox and will be
527 * retrieved from the XPCOM component manager. We use the
528 * XPCOM provided smart pointer nsCOMPtr for all objects because
529 * that's very convenient and removes the need deal with reference
530 * counting and freeing.
531 */
532 nsCOMPtr<nsIComponentManager> manager;
533 rc = NS_GetComponentManager (getter_AddRefs (manager));
534 if (NS_FAILED(rc))
535 {
536 RTPrintf("Error: could not get component manager! rc=%Rhrc\n", rc);
537 return -1;
538 }
539
540 nsCOMPtr<IVirtualBox> virtualBox;
541 rc = manager->CreateInstanceByContractID (NS_VIRTUALBOX_CONTRACTID,
542 nsnull,
543 NS_GET_IID(IVirtualBox),
544 getter_AddRefs(virtualBox));
545 if (NS_FAILED(rc))
546 {
547 RTPrintf("Error, could not instantiate VirtualBox object! rc=0x%x\n", rc);
548 return -1;
549 }
550 RTPrintf("VirtualBox object created\n");
551
552 ////////////////////////////////////////////////////////////////////////////////
553 ////////////////////////////////////////////////////////////////////////////////
554 ////////////////////////////////////////////////////////////////////////////////
555
556
557 listVMs(virtualBox);
558
559 createVM(virtualBox);
560
561
562 ////////////////////////////////////////////////////////////////////////////////
563 ////////////////////////////////////////////////////////////////////////////////
564 ////////////////////////////////////////////////////////////////////////////////
565
566 /* this is enough to free the IVirtualBox instance -- smart pointers rule! */
567 virtualBox = nsnull;
568
569 /*
570 * Process events that might have queued up in the XPCOM event
571 * queue. If we don't process them, the server might hang.
572 */
573 eventQ->ProcessPendingEvents();
574 }
575
576 /*
577 * Perform the standard XPCOM shutdown procedure.
578 */
579 NS_ShutdownXPCOM(nsnull);
580#if defined(XPCOM_GLUE)
581 XPCOMGlueShutdown();
582#endif
583 RTPrintf("Done!\n");
584 return 0;
585}
586
587
588//////////////////////////////////////////////////////////////////////////////////////////////////////
589//// Helpers
590//////////////////////////////////////////////////////////////////////////////////////////////////////
591
592/**
593 * Helper function to convert an nsID into a human readable string
594 *
595 * @returns result string, allocated. Has to be freed using free()
596 * @param guid Pointer to nsID that will be converted.
597 */
598char *nsIDToString(nsID *guid)
599{
600 char *res = (char*)malloc(39);
601
602 if (res != NULL)
603 {
604 RTStrPrintf(res, 39, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
605 guid->m0, (PRUint32)guid->m1, (PRUint32)guid->m2,
606 (PRUint32)guid->m3[0], (PRUint32)guid->m3[1], (PRUint32)guid->m3[2],
607 (PRUint32)guid->m3[3], (PRUint32)guid->m3[4], (PRUint32)guid->m3[5],
608 (PRUint32)guid->m3[6], (PRUint32)guid->m3[7]);
609 }
610 return res;
611}
612
613/**
614 * Helper function to print XPCOM exception information set on the current
615 * thread after a failed XPCOM method call. This function will also print
616 * extended VirtualBox error info if it is available.
617 */
618void printErrorInfo()
619{
620 nsresult rc;
621
622 nsCOMPtr <nsIExceptionService> es;
623 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
624 if (NS_SUCCEEDED(rc))
625 {
626 nsCOMPtr <nsIExceptionManager> em;
627 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
628 if (NS_SUCCEEDED(rc))
629 {
630 nsCOMPtr<nsIException> ex;
631 rc = em->GetCurrentException (getter_AddRefs (ex));
632 if (NS_SUCCEEDED(rc) && ex)
633 {
634 nsCOMPtr <IVirtualBoxErrorInfo> info;
635 info = do_QueryInterface(ex, &rc);
636 if (NS_SUCCEEDED(rc) && info)
637 {
638 /* got extended error info */
639 RTPrintf ("Extended error info (IVirtualBoxErrorInfo):\n");
640 PRInt32 resultCode = NS_OK;
641 info->GetResultCode (&resultCode);
642 RTPrintf (" resultCode=%08X\n", resultCode);
643 nsXPIDLString component;
644 info->GetComponent (getter_Copies (component));
645 RTPrintf (" component=%s\n", NS_ConvertUTF16toUTF8(component).get());
646 nsXPIDLString text;
647 info->GetText (getter_Copies (text));
648 RTPrintf (" text=%s\n", NS_ConvertUTF16toUTF8(text).get());
649 }
650 else
651 {
652 /* got basic error info */
653 RTPrintf ("Basic error info (nsIException):\n");
654 nsresult resultCode = NS_OK;
655 ex->GetResult (&resultCode);
656 RTPrintf (" resultCode=%08X\n", resultCode);
657 nsXPIDLCString message;
658 ex->GetMessage (getter_Copies (message));
659 RTPrintf (" message=%s\n", message.get());
660 }
661
662 /* reset the exception to NULL to indicate we've processed it */
663 em->SetCurrentException (NULL);
664
665 rc = NS_OK;
666 }
667 }
668 }
669}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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