VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxControl/VBoxControl.cpp@ 78393

Last change on this file since 78393 was 76553, checked in by vboxsync, 6 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 70.1 KB
Line 
1/* $Id: VBoxControl.cpp 76553 2019-01-01 01:45:53Z vboxsync $ */
2/** @file
3 * VBoxControl - Guest Additions Command Line Management Interface.
4 */
5
6/*
7 * Copyright (C) 2008-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#include <iprt/alloca.h>
23#include <iprt/cpp/autores.h>
24#include <iprt/buildconfig.h>
25#include <iprt/ctype.h>
26#include <iprt/errcore.h>
27#include <iprt/getopt.h>
28#include <iprt/initterm.h>
29#include <iprt/mem.h>
30#include <iprt/message.h>
31#include <iprt/path.h>
32#include <iprt/string.h>
33#include <iprt/stream.h>
34#include <iprt/zip.h>
35#include <VBox/log.h>
36#include <VBox/version.h>
37#include <VBox/VBoxGuestLib.h>
38#ifdef RT_OS_WINDOWS
39# include <iprt/win/windows.h>
40#endif
41#ifdef VBOX_WITH_GUEST_PROPS
42# include <VBox/HostServices/GuestPropertySvc.h>
43#endif
44#ifdef VBOX_WITH_SHARED_FOLDERS
45# include <VBox/shflsvc.h>
46# ifdef RT_OS_OS2
47# define OS2EMX_PLAIN_CHAR
48# define INCL_ERRORS
49# define INCL_DOSFILEMGR
50# include <os2emx.h>
51# endif
52#endif
53#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
54# include <VBox/VBoxGuest.h>
55# include "../VBoxGuest/lib/VBoxGuestR3LibInternal.h" /* HACK ALERT! Using vbglR3DoIOCtl directly!! */
56#endif
57
58
59/*********************************************************************************************************************************
60* Global Variables *
61*********************************************************************************************************************************/
62/** The program name (derived from argv[0]). */
63char const *g_pszProgName = "";
64/** The current verbosity level. */
65int g_cVerbosity = 0;
66
67
68/** @name Displays the program usage message.
69 * @{
70 */
71
72/**
73 * Helper function that does indentation.
74 *
75 * @param pszLine Text.
76 * @param pszName Program name.
77 * @param pszCommand Command/option syntax.
78 */
79static void doUsage(char const *pszLine, char const *pszName = "", char const *pszCommand = "")
80{
81 /* Allow for up to 15 characters command name length (VBoxControl.exe) with
82 * perfect column alignment. Beyond that there's at least one space between
83 * the command if there are command line parameters. */
84 RTPrintf("%s %-*s%s%s\n",
85 pszName,
86 *pszLine ? 35 - strlen(pszName) : 1, pszCommand,
87 *pszLine ? " " : "", pszLine);
88}
89
90/** Enumerate the different parts of the usage we might want to print out */
91enum VBoxControlUsage
92{
93#ifdef RT_OS_WINDOWS
94 GET_VIDEO_ACCEL,
95 SET_VIDEO_ACCEL,
96 VIDEO_FLAGS,
97 LIST_CUST_MODES,
98 ADD_CUST_MODE,
99 REMOVE_CUST_MODE,
100 SET_VIDEO_MODE,
101#endif
102#ifdef VBOX_WITH_GUEST_PROPS
103 GUEST_PROP,
104#endif
105#ifdef VBOX_WITH_SHARED_FOLDERS
106 GUEST_SHAREDFOLDERS,
107#endif
108#if !defined(VBOX_CONTROL_TEST)
109 WRITE_CORE_DUMP,
110#endif
111 WRITE_LOG,
112 TAKE_SNAPSHOT,
113 SAVE_STATE,
114 SUSPEND,
115 POWER_OFF,
116 VERSION,
117 HELP,
118 USAGE_ALL = UINT32_MAX
119};
120
121static RTEXITCODE usage(enum VBoxControlUsage eWhich = USAGE_ALL)
122{
123 RTPrintf("Usage:\n\n");
124 doUsage("print version number and exit", g_pszProgName, "[-V|--version]");
125 doUsage("suppress the logo", g_pszProgName, "--nologo ...");
126 RTPrintf("\n");
127
128 /* Exclude the Windows bits from the test version. Anyone who needs to
129 test them can fix this. */
130#if defined(RT_OS_WINDOWS) && !defined(VBOX_CONTROL_TEST)
131 if (eWhich == GET_VIDEO_ACCEL || eWhich == USAGE_ALL)
132 doUsage("", g_pszProgName, "getvideoacceleration");
133 if (eWhich == SET_VIDEO_ACCEL || eWhich == USAGE_ALL)
134 doUsage("<on|off>", g_pszProgName, "setvideoacceleration");
135 if (eWhich == VIDEO_FLAGS || eWhich == USAGE_ALL)
136 doUsage("<get|set|clear|delete> [hex mask]", g_pszProgName, "videoflags");
137 if (eWhich == LIST_CUST_MODES || eWhich == USAGE_ALL)
138 doUsage("", g_pszProgName, "listcustommodes");
139 if (eWhich == ADD_CUST_MODE || eWhich == USAGE_ALL)
140 doUsage("<width> <height> <bpp>", g_pszProgName, "addcustommode");
141 if (eWhich == REMOVE_CUST_MODE || eWhich == USAGE_ALL)
142 doUsage("<width> <height> <bpp>", g_pszProgName, "removecustommode");
143 if (eWhich == SET_VIDEO_MODE || eWhich == USAGE_ALL)
144 doUsage("<width> <height> <bpp> <screen>", g_pszProgName, "setvideomode");
145#endif
146#ifdef VBOX_WITH_GUEST_PROPS
147 if (eWhich == GUEST_PROP || eWhich == USAGE_ALL)
148 {
149 doUsage("get <property> [--verbose]", g_pszProgName, "guestproperty");
150 doUsage("set <property> [<value> [--flags <flags>]]", g_pszProgName, "guestproperty");
151 doUsage("delete|unset <property>", g_pszProgName, "guestproperty");
152 doUsage("enumerate [--patterns <patterns>]", g_pszProgName, "guestproperty");
153 doUsage("wait <patterns>", g_pszProgName, "guestproperty");
154 doUsage("[--timestamp <last timestamp>]");
155 doUsage("[--timeout <timeout in ms>");
156 }
157#endif
158#ifdef VBOX_WITH_SHARED_FOLDERS
159 if (eWhich == GUEST_SHAREDFOLDERS || eWhich == USAGE_ALL)
160 {
161 doUsage("list [--automount]", g_pszProgName, "sharedfolder");
162# ifdef RT_OS_OS2
163 doUsage("use <drive> <folder>", g_pszProgName, "sharedfolder");
164 doUsage("unuse <drive>", g_pszProgName, "sharedfolder");
165# endif
166 }
167#endif
168
169#if !defined(VBOX_CONTROL_TEST)
170 if (eWhich == WRITE_CORE_DUMP || eWhich == USAGE_ALL)
171 doUsage("", g_pszProgName, "writecoredump");
172#endif
173 if (eWhich == WRITE_LOG || eWhich == USAGE_ALL)
174 doUsage("", g_pszProgName, "writelog [-n|--no-newline] [--] <msg>");
175 if (eWhich == TAKE_SNAPSHOT || eWhich == USAGE_ALL)
176 doUsage("", g_pszProgName, "takesnapshot");
177 if (eWhich == SAVE_STATE || eWhich == USAGE_ALL)
178 doUsage("", g_pszProgName, "savestate");
179 if (eWhich == SUSPEND || eWhich == USAGE_ALL)
180 doUsage("", g_pszProgName, "suspend");
181 if (eWhich == POWER_OFF || eWhich == USAGE_ALL)
182 doUsage("", g_pszProgName, "poweroff");
183 if (eWhich == HELP || eWhich == USAGE_ALL)
184 doUsage("[command]", g_pszProgName, "help");
185 if (eWhich == VERSION || eWhich == USAGE_ALL)
186 doUsage("", g_pszProgName, "version");
187
188 return RTEXITCODE_SUCCESS;
189}
190
191/** @} */
192
193
194/**
195 * Implementation of the '--version' option.
196 *
197 * @returns RTEXITCODE_SUCCESS
198 */
199static RTEXITCODE printVersion(void)
200{
201 RTPrintf("%sr%u\n", VBOX_VERSION_STRING, RTBldCfgRevision());
202 return RTEXITCODE_SUCCESS;
203}
204
205
206/**
207 * Displays an error message.
208 *
209 * @returns RTEXITCODE_FAILURE.
210 * @param pszFormat The message text. No newline.
211 * @param ... Format arguments.
212 */
213static RTEXITCODE VBoxControlError(const char *pszFormat, ...)
214{
215 /** @todo prefix with current command. */
216 va_list va;
217 va_start(va, pszFormat);
218 RTMsgErrorV(pszFormat, va);
219 va_end(va);
220 return RTEXITCODE_FAILURE;
221}
222
223
224/**
225 * Displays a getopt error.
226 *
227 * @returns RTEXITCODE_FAILURE.
228 * @param ch The RTGetOpt return value.
229 * @param pValueUnion The RTGetOpt return data.
230 */
231static RTEXITCODE VBoxCtrlGetOptError(int ch, PCRTGETOPTUNION pValueUnion)
232{
233 /** @todo prefix with current command. */
234 return RTGetOptPrintError(ch, pValueUnion);
235}
236
237
238/**
239 * Displays an syntax error message.
240 *
241 * @returns RTEXITCODE_FAILURE.
242 * @param pszFormat The message text. No newline.
243 * @param ... Format arguments.
244 */
245static RTEXITCODE VBoxControlSyntaxError(const char *pszFormat, ...)
246{
247 /** @todo prefix with current command. */
248 va_list va;
249 va_start(va, pszFormat);
250 RTMsgErrorV(pszFormat, va);
251 va_end(va);
252 return RTEXITCODE_SYNTAX;
253}
254
255#if defined(RT_OS_WINDOWS) && !defined(VBOX_CONTROL_TEST)
256
257decltype(ChangeDisplaySettingsExA) *g_pfnChangeDisplaySettingsExA;
258decltype(ChangeDisplaySettings) *g_pfnChangeDisplaySettingsA;
259decltype(EnumDisplaySettingsA) *g_pfnEnumDisplaySettingsA;
260
261static unsigned nextAdjacentRectXP(RECTL const *paRects, unsigned cRects, unsigned iRect)
262{
263 for (unsigned i = 0; i < cRects; i++)
264 if (paRects[iRect].right == paRects[i].left)
265 return i;
266 return ~0U;
267}
268
269static unsigned nextAdjacentRectXN(RECTL const *paRects, unsigned cRects, unsigned iRect)
270{
271 for (unsigned i = 0; i < cRects; i++)
272 if (paRects[iRect].left == paRects[i].right)
273 return i;
274 return ~0U;
275}
276
277static unsigned nextAdjacentRectYP(RECTL const *paRects, unsigned cRects, unsigned iRect)
278{
279 for (unsigned i = 0; i < cRects; i++)
280 if (paRects[iRect].bottom == paRects[i].top)
281 return i;
282 return ~0U;
283}
284
285unsigned nextAdjacentRectYN(RECTL const *paRects, unsigned cRects, unsigned iRect)
286{
287 for (unsigned i = 0; i < cRects; i++)
288 if (paRects[iRect].top == paRects[i].bottom)
289 return i;
290 return ~0U;
291}
292
293void resizeRect(RECTL *paRects, unsigned cRects, unsigned iPrimary, unsigned iResized, int NewWidth, int NewHeight)
294{
295 RECTL *paNewRects = (RECTL *)alloca(sizeof (RECTL) * cRects);
296 memcpy (paNewRects, paRects, sizeof(RECTL) * cRects);
297 paNewRects[iResized].right += NewWidth - (paNewRects[iResized].right - paNewRects[iResized].left);
298 paNewRects[iResized].bottom += NewHeight - (paNewRects[iResized].bottom - paNewRects[iResized].top);
299
300 /* Verify all pairs of originally adjacent rectangles for all 4 directions.
301 * If the pair has a "good" delta (that is the first rectangle intersects the second)
302 * at a direction and the second rectangle is not primary one (which can not be moved),
303 * move the second rectangle to make it adjacent to the first one.
304 */
305
306 /* X positive. */
307 unsigned iRect;
308 for (iRect = 0; iRect < cRects; iRect++)
309 {
310 /* Find the next adjacent original rect in x positive direction. */
311 unsigned iNextRect = nextAdjacentRectXP (paRects, cRects, iRect);
312 Log(("next %d -> %d\n", iRect, iNextRect));
313
314 if (iNextRect == ~0 || iNextRect == iPrimary)
315 {
316 continue;
317 }
318
319 /* Check whether there is an X intersection between these adjacent rects in the new rectangles
320 * and fix the intersection if delta is "good".
321 */
322 int delta = paNewRects[iRect].right - paNewRects[iNextRect].left;
323
324 if (delta > 0)
325 {
326 Log(("XP intersection right %d left %d, diff %d\n",
327 paNewRects[iRect].right, paNewRects[iNextRect].left,
328 delta));
329
330 paNewRects[iNextRect].left += delta;
331 paNewRects[iNextRect].right += delta;
332 }
333 }
334
335 /* X negative. */
336 for (iRect = 0; iRect < cRects; iRect++)
337 {
338 /* Find the next adjacent original rect in x negative direction. */
339 unsigned iNextRect = nextAdjacentRectXN (paRects, cRects, iRect);
340 Log(("next %d -> %d\n", iRect, iNextRect));
341
342 if (iNextRect == ~0 || iNextRect == iPrimary)
343 {
344 continue;
345 }
346
347 /* Check whether there is an X intersection between these adjacent rects in the new rectangles
348 * and fix the intersection if delta is "good".
349 */
350 int delta = paNewRects[iRect].left - paNewRects[iNextRect].right;
351
352 if (delta < 0)
353 {
354 Log(("XN intersection left %d right %d, diff %d\n",
355 paNewRects[iRect].left, paNewRects[iNextRect].right,
356 delta));
357
358 paNewRects[iNextRect].left += delta;
359 paNewRects[iNextRect].right += delta;
360 }
361 }
362
363 /* Y positive (in the computer sense, top->down). */
364 for (iRect = 0; iRect < cRects; iRect++)
365 {
366 /* Find the next adjacent original rect in y positive direction. */
367 unsigned iNextRect = nextAdjacentRectYP (paRects, cRects, iRect);
368 Log(("next %d -> %d\n", iRect, iNextRect));
369
370 if (iNextRect == ~0 || iNextRect == iPrimary)
371 {
372 continue;
373 }
374
375 /* Check whether there is an Y intersection between these adjacent rects in the new rectangles
376 * and fix the intersection if delta is "good".
377 */
378 int delta = paNewRects[iRect].bottom - paNewRects[iNextRect].top;
379
380 if (delta > 0)
381 {
382 Log(("YP intersection bottom %d top %d, diff %d\n",
383 paNewRects[iRect].bottom, paNewRects[iNextRect].top,
384 delta));
385
386 paNewRects[iNextRect].top += delta;
387 paNewRects[iNextRect].bottom += delta;
388 }
389 }
390
391 /* Y negative (in the computer sense, down->top). */
392 for (iRect = 0; iRect < cRects; iRect++)
393 {
394 /* Find the next adjacent original rect in x negative direction. */
395 unsigned iNextRect = nextAdjacentRectYN (paRects, cRects, iRect);
396 Log(("next %d -> %d\n", iRect, iNextRect));
397
398 if (iNextRect == ~0 || iNextRect == iPrimary)
399 {
400 continue;
401 }
402
403 /* Check whether there is an Y intersection between these adjacent rects in the new rectangles
404 * and fix the intersection if delta is "good".
405 */
406 int delta = paNewRects[iRect].top - paNewRects[iNextRect].bottom;
407
408 if (delta < 0)
409 {
410 Log(("YN intersection top %d bottom %d, diff %d\n",
411 paNewRects[iRect].top, paNewRects[iNextRect].bottom,
412 delta));
413
414 paNewRects[iNextRect].top += delta;
415 paNewRects[iNextRect].bottom += delta;
416 }
417 }
418
419 memcpy (paRects, paNewRects, sizeof (RECTL) * cRects);
420 return;
421}
422
423/* Returns TRUE to try again. */
424static BOOL ResizeDisplayDevice(ULONG Id, DWORD Width, DWORD Height, DWORD BitsPerPixel)
425{
426 BOOL fModeReset = (Width == 0 && Height == 0 && BitsPerPixel == 0);
427
428 DISPLAY_DEVICE DisplayDevice;
429 RT_ZERO(DisplayDevice);
430 DisplayDevice.cb = sizeof(DisplayDevice);
431
432 /* Find out how many display devices the system has */
433 DWORD NumDevices = 0;
434 DWORD i = 0;
435 while (EnumDisplayDevices(NULL, i, &DisplayDevice, 0))
436 {
437 Log(("[%d] %s\n", i, DisplayDevice.DeviceName));
438
439 if (DisplayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
440 {
441 Log(("Found primary device. err %d\n", GetLastError()));
442 NumDevices++;
443 }
444 else if (!(DisplayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
445 {
446
447 Log(("Found secondary device. err %d\n", GetLastError()));
448 NumDevices++;
449 }
450
451 RT_ZERO(DisplayDevice);
452 DisplayDevice.cb = sizeof(DisplayDevice);
453 i++;
454 }
455
456 Log(("Found total %d devices. err %d\n", NumDevices, GetLastError()));
457
458 if (NumDevices == 0 || Id >= NumDevices)
459 {
460 Log(("Requested identifier %d is invalid. err %d\n", Id, GetLastError()));
461 return FALSE;
462 }
463
464 DISPLAY_DEVICE *paDisplayDevices = (DISPLAY_DEVICE *)alloca(sizeof (DISPLAY_DEVICE) * NumDevices);
465 DEVMODE *paDeviceModes = (DEVMODE *)alloca(sizeof (DEVMODE) * NumDevices);
466 RECTL *paRects = (RECTL *)alloca(sizeof (RECTL) * NumDevices);
467
468 /* Fetch information about current devices and modes. */
469 DWORD DevNum = 0;
470 DWORD DevPrimaryNum = 0;
471
472 RT_ZERO(DisplayDevice);
473 DisplayDevice.cb = sizeof(DISPLAY_DEVICE);
474
475 i = 0;
476 while (EnumDisplayDevices (NULL, i, &DisplayDevice, 0))
477 {
478 Log(("[%d(%d)] %s\n", i, DevNum, DisplayDevice.DeviceName));
479
480 BOOL fFetchDevice = FALSE;
481
482 if (DisplayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE)
483 {
484 Log(("Found primary device. err %d\n", GetLastError()));
485 DevPrimaryNum = DevNum;
486 fFetchDevice = TRUE;
487 }
488 else if (!(DisplayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER))
489 {
490
491 Log(("Found secondary device. err %d\n", GetLastError()));
492 fFetchDevice = TRUE;
493 }
494
495 if (fFetchDevice)
496 {
497 if (DevNum >= NumDevices)
498 {
499 Log(("%d >= %d\n", NumDevices, DevNum));
500 return FALSE;
501 }
502
503 paDisplayDevices[DevNum] = DisplayDevice;
504
505 RT_BZERO(&paDeviceModes[DevNum], sizeof(DEVMODE));
506 paDeviceModes[DevNum].dmSize = sizeof(DEVMODE);
507 if (!g_pfnEnumDisplaySettingsA((LPSTR)DisplayDevice.DeviceName, ENUM_REGISTRY_SETTINGS, &paDeviceModes[DevNum]))
508 {
509 Log(("EnumDisplaySettings err %d\n", GetLastError()));
510 return FALSE;
511 }
512
513 Log(("%dx%d at %d,%d\n",
514 paDeviceModes[DevNum].dmPelsWidth,
515 paDeviceModes[DevNum].dmPelsHeight,
516 paDeviceModes[DevNum].dmPosition.x,
517 paDeviceModes[DevNum].dmPosition.y));
518
519 paRects[DevNum].left = paDeviceModes[DevNum].dmPosition.x;
520 paRects[DevNum].top = paDeviceModes[DevNum].dmPosition.y;
521 paRects[DevNum].right = paDeviceModes[DevNum].dmPosition.x + paDeviceModes[DevNum].dmPelsWidth;
522 paRects[DevNum].bottom = paDeviceModes[DevNum].dmPosition.y + paDeviceModes[DevNum].dmPelsHeight;
523 DevNum++;
524 }
525
526 RT_ZERO(DisplayDevice);
527 DisplayDevice.cb = sizeof(DISPLAY_DEVICE);
528 i++;
529 }
530
531 if (Width == 0)
532 Width = paRects[Id].right - paRects[Id].left;
533
534 if (Height == 0)
535 Height = paRects[Id].bottom - paRects[Id].top;
536
537 /* Check whether a mode reset or a change is requested. */
538 if ( !fModeReset
539 && paRects[Id].right - paRects[Id].left == (LONG)Width
540 && paRects[Id].bottom - paRects[Id].top == (LONG)Height
541 && paDeviceModes[Id].dmBitsPerPel == BitsPerPixel)
542 {
543 Log(("VBoxDisplayThread : already at desired resolution.\n"));
544 return FALSE;
545 }
546
547 resizeRect(paRects, NumDevices, DevPrimaryNum, Id, Width, Height);
548#ifdef LOG_ENABLED
549 for (i = 0; i < NumDevices; i++)
550 Log(("[%d]: %d,%d %dx%d\n",
551 i, paRects[i].left, paRects[i].top,
552 paRects[i].right - paRects[i].left,
553 paRects[i].bottom - paRects[i].top));
554#endif /* Log */
555
556 /* Without this, Windows will not ask the miniport for its
557 * mode table but uses an internal cache instead.
558 */
559 DEVMODE tempDevMode;
560 RT_ZERO(tempDevMode);
561 tempDevMode.dmSize = sizeof(DEVMODE);
562 g_pfnEnumDisplaySettingsA(NULL, 0xffffff, &tempDevMode);
563
564 /* Assign the new rectangles to displays. */
565 for (i = 0; i < NumDevices; i++)
566 {
567 paDeviceModes[i].dmPosition.x = paRects[i].left;
568 paDeviceModes[i].dmPosition.y = paRects[i].top;
569 paDeviceModes[i].dmPelsWidth = paRects[i].right - paRects[i].left;
570 paDeviceModes[i].dmPelsHeight = paRects[i].bottom - paRects[i].top;
571
572 paDeviceModes[i].dmFields = DM_POSITION | DM_PELSHEIGHT | DM_PELSWIDTH;
573
574 if ( i == Id
575 && BitsPerPixel != 0)
576 {
577 paDeviceModes[i].dmFields |= DM_BITSPERPEL;
578 paDeviceModes[i].dmBitsPerPel = BitsPerPixel;
579 }
580 Log(("calling pfnChangeDisplaySettingsEx %p\n", g_pfnChangeDisplaySettingsExA));
581 g_pfnChangeDisplaySettingsExA((LPSTR)paDisplayDevices[i].DeviceName,
582 &paDeviceModes[i], NULL, CDS_NORESET | CDS_UPDATEREGISTRY, NULL);
583 Log(("ChangeDisplaySettingsEx position err %d\n", GetLastError()));
584 }
585
586 /* A second call to ChangeDisplaySettings updates the monitor. */
587 LONG status = g_pfnChangeDisplaySettingsA(NULL, 0);
588 Log(("ChangeDisplaySettings update status %d\n", status));
589 if (status == DISP_CHANGE_SUCCESSFUL || status == DISP_CHANGE_BADMODE)
590 {
591 /* Successfully set new video mode or our driver can not set the requested mode. Stop trying. */
592 return FALSE;
593 }
594
595 /* Retry the request. */
596 return TRUE;
597}
598
599static DECLCALLBACK(RTEXITCODE) handleSetVideoMode(int argc, char *argv[])
600{
601 if (argc != 3 && argc != 4)
602 {
603 usage(SET_VIDEO_MODE);
604 return RTEXITCODE_FAILURE;
605 }
606
607 DWORD xres = atoi(argv[0]);
608 DWORD yres = atoi(argv[1]);
609 DWORD bpp = atoi(argv[2]);
610 DWORD scr = 0;
611 if (argc == 4)
612 scr = atoi(argv[3]);
613
614 HMODULE hmodUser = GetModuleHandle("user32.dll");
615 if (hmodUser)
616 {
617 /* ChangeDisplaySettingsExA was probably added in W2K, whereas ChangeDisplaySettingsA
618 and EnumDisplaySettingsA was added in NT 3.51. */
619 g_pfnChangeDisplaySettingsExA = (decltype(g_pfnChangeDisplaySettingsExA))GetProcAddress(hmodUser, "ChangeDisplaySettingsExA");
620 g_pfnChangeDisplaySettingsA = (decltype(g_pfnChangeDisplaySettingsA)) GetProcAddress(hmodUser, "ChangeDisplaySettingsA");
621 g_pfnEnumDisplaySettingsA = (decltype(g_pfnEnumDisplaySettingsA)) GetProcAddress(hmodUser, "EnumDisplaySettingsA");
622
623 Log(("VBoxService: g_pfnChangeDisplaySettingsExA=%p g_pfnChangeDisplaySettingsA=%p g_pfnEnumDisplaySettingsA=%p\n",
624 g_pfnChangeDisplaySettingsExA, g_pfnChangeDisplaySettingsA, g_pfnEnumDisplaySettingsA));
625
626 if ( g_pfnChangeDisplaySettingsExA
627 && g_pfnChangeDisplaySettingsA
628 && g_pfnEnumDisplaySettingsA)
629 {
630 /* The screen index is 0 based in the ResizeDisplayDevice call. */
631 scr = scr > 0 ? scr - 1 : 0;
632
633 /* Horizontal resolution must be a multiple of 8, round down. */
634 xres &= ~0x7;
635
636 RTPrintf("Setting resolution of display %d to %dx%dx%d ...", scr, xres, yres, bpp);
637 ResizeDisplayDevice(scr, xres, yres, bpp);
638 RTPrintf("done.\n");
639 }
640 else
641 VBoxControlError("Error retrieving API for display change!");
642 }
643 else
644 VBoxControlError("Error retrieving handle to user32.dll!");
645
646 return RTEXITCODE_SUCCESS;
647}
648
649static int checkVBoxVideoKey(HKEY hkeyVideo)
650{
651 RTUTF16 wszValue[128];
652 DWORD cbValue = sizeof(wszValue);
653 DWORD dwKeyType;
654 LONG status = RegQueryValueExW(hkeyVideo, L"Device Description", NULL, &dwKeyType, (LPBYTE)wszValue, &cbValue);
655 if (status == ERROR_SUCCESS)
656 {
657 /* WDDM has additional chars after "Adapter" */
658 static char s_szDeviceDescription[] = "VirtualBox Graphics Adapter";
659 wszValue[sizeof(s_szDeviceDescription) - 1] = '\0';
660 if (RTUtf16ICmpAscii(wszValue, s_szDeviceDescription) == 0)
661 return VINF_SUCCESS;
662 }
663
664 return VERR_NOT_FOUND;
665}
666
667static HKEY getVideoKey(bool writable)
668{
669 HKEY hkeyDeviceMap = 0;
670 LONG status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\VIDEO", 0, KEY_READ, &hkeyDeviceMap);
671 if (status != ERROR_SUCCESS || !hkeyDeviceMap)
672 {
673 VBoxControlError("Error opening video device map registry key!\n");
674 return 0;
675 }
676
677 HKEY hkeyVideo = 0;
678 ULONG iDevice;
679 DWORD dwKeyType;
680
681 /*
682 * Scan all '\Device\VideoX' REG_SZ keys to find VBox video driver entry.
683 * 'ObjectNumberList' REG_BINARY is an array of 32 bit device indexes (X).
684 */
685
686 /* Get the 'ObjectNumberList' */
687 ULONG cDevices = 0;
688 DWORD adwObjectNumberList[256];
689 DWORD cbValue = sizeof(adwObjectNumberList);
690 status = RegQueryValueExA(hkeyDeviceMap, "ObjectNumberList", NULL, &dwKeyType, (LPBYTE)&adwObjectNumberList[0], &cbValue);
691
692 if ( status == ERROR_SUCCESS
693 && dwKeyType == REG_BINARY)
694 cDevices = cbValue / sizeof(DWORD);
695 else
696 {
697 /* The list might not exists. Use 'MaxObjectNumber' REG_DWORD and build a list. */
698 DWORD dwMaxObjectNumber = 0;
699 cbValue = sizeof(dwMaxObjectNumber);
700 status = RegQueryValueExA(hkeyDeviceMap, "MaxObjectNumber", NULL, &dwKeyType, (LPBYTE)&dwMaxObjectNumber, &cbValue);
701 if ( status == ERROR_SUCCESS
702 && dwKeyType == REG_DWORD)
703 {
704 /* 'MaxObjectNumber' is inclusive. */
705 cDevices = RT_MIN(dwMaxObjectNumber + 1, RT_ELEMENTS(adwObjectNumberList));
706 for (iDevice = 0; iDevice < cDevices; iDevice++)
707 adwObjectNumberList[iDevice] = iDevice;
708 }
709 }
710
711 if (cDevices == 0)
712 {
713 /* Always try '\Device\Video0' as the old code did. Enum can be used in this case in principle. */
714 adwObjectNumberList[0] = 0;
715 cDevices = 1;
716 }
717
718 /* Scan device entries */
719 for (iDevice = 0; iDevice < cDevices; iDevice++)
720 {
721 char szValueName[64];
722 RTStrPrintf(szValueName, sizeof(szValueName), "\\Device\\Video%u", adwObjectNumberList[iDevice]);
723
724 char szVideoLocation[256];
725 cbValue = sizeof(szVideoLocation);
726 status = RegQueryValueExA(hkeyDeviceMap, szValueName, NULL, &dwKeyType, (LPBYTE)&szVideoLocation[0], &cbValue);
727
728 /* This value starts with '\REGISTRY\Machine' */
729 if ( status == ERROR_SUCCESS
730 && dwKeyType == REG_SZ
731 && _strnicmp(szVideoLocation, "\\REGISTRY\\Machine", 17) == 0)
732 {
733 status = RegOpenKeyExA(HKEY_LOCAL_MACHINE, &szVideoLocation[18], 0,
734 KEY_READ | (writable ? KEY_WRITE : 0), &hkeyVideo);
735 if (status == ERROR_SUCCESS)
736 {
737 int rc = checkVBoxVideoKey(hkeyVideo);
738 if (RT_SUCCESS(rc))
739 {
740 /* Found, return hkeyVideo to the caller. */
741 break;
742 }
743
744 RegCloseKey(hkeyVideo);
745 hkeyVideo = 0;
746 }
747 }
748 }
749
750 if (hkeyVideo == 0)
751 {
752 VBoxControlError("Error opening video registry key!\n");
753 }
754
755 RegCloseKey(hkeyDeviceMap);
756 return hkeyVideo;
757}
758
759static DECLCALLBACK(RTEXITCODE) handleGetVideoAcceleration(int argc, char *argv[])
760{
761 RT_NOREF2(argc, argv);
762 ULONG status;
763 HKEY hkeyVideo = getVideoKey(false);
764
765 if (hkeyVideo)
766 {
767 /* query the actual value */
768 DWORD fAcceleration = 1;
769 DWORD cbValue = sizeof(fAcceleration);
770 DWORD dwKeyType;
771 status = RegQueryValueExA(hkeyVideo, "EnableVideoAccel", NULL, &dwKeyType, (LPBYTE)&fAcceleration, &cbValue);
772 if (status != ERROR_SUCCESS)
773 RTPrintf("Video acceleration: default\n");
774 else
775 RTPrintf("Video acceleration: %s\n", fAcceleration ? "on" : "off");
776 RegCloseKey(hkeyVideo);
777 }
778 return RTEXITCODE_SUCCESS;
779}
780
781static DECLCALLBACK(RTEXITCODE) handleSetVideoAcceleration(int argc, char *argv[])
782{
783 ULONG status;
784 HKEY hkeyVideo;
785
786 /* must have exactly one argument: the new offset */
787 if ( (argc != 1)
788 || ( RTStrICmp(argv[0], "on")
789 && RTStrICmp(argv[0], "off")))
790 {
791 usage(SET_VIDEO_ACCEL);
792 return RTEXITCODE_FAILURE;
793 }
794
795 hkeyVideo = getVideoKey(true);
796
797 if (hkeyVideo)
798 {
799 int fAccel = 0;
800 if (RTStrICmp(argv[0], "on") == 0)
801 fAccel = 1;
802 /* set a new value */
803 status = RegSetValueExA(hkeyVideo, "EnableVideoAccel", 0, REG_DWORD, (LPBYTE)&fAccel, sizeof(fAccel));
804 if (status != ERROR_SUCCESS)
805 {
806 VBoxControlError("Error %d writing video acceleration status!\n", status);
807 }
808 RegCloseKey(hkeyVideo);
809 }
810 return RTEXITCODE_SUCCESS;
811}
812
813static DECLCALLBACK(RTEXITCODE) videoFlagsGet(void)
814{
815 HKEY hkeyVideo = getVideoKey(false);
816
817 if (hkeyVideo)
818 {
819 DWORD dwFlags = 0;
820 DWORD cbValue = sizeof(dwFlags);
821 DWORD dwKeyType;
822 ULONG status = RegQueryValueExA(hkeyVideo, "VBoxVideoFlags", NULL, &dwKeyType, (LPBYTE)&dwFlags, &cbValue);
823 if (status != ERROR_SUCCESS)
824 RTPrintf("Video flags: default\n");
825 else
826 RTPrintf("Video flags: 0x%08X\n", dwFlags);
827 RegCloseKey(hkeyVideo);
828 return RTEXITCODE_SUCCESS;
829 }
830
831 return RTEXITCODE_FAILURE;
832}
833
834static DECLCALLBACK(RTEXITCODE) videoFlagsDelete(void)
835{
836 HKEY hkeyVideo = getVideoKey(true);
837
838 if (hkeyVideo)
839 {
840 ULONG status = RegDeleteValueA(hkeyVideo, "VBoxVideoFlags");
841 if (status != ERROR_SUCCESS)
842 VBoxControlError("Error %d deleting video flags.\n", status);
843 RegCloseKey(hkeyVideo);
844 return RTEXITCODE_SUCCESS;
845 }
846
847 return RTEXITCODE_FAILURE;
848}
849
850static DECLCALLBACK(RTEXITCODE) videoFlagsModify(bool fSet, int argc, char *argv[])
851{
852 if (argc != 1)
853 {
854 VBoxControlError("Mask required.\n");
855 return RTEXITCODE_FAILURE;
856 }
857
858 uint32_t u32Mask = 0;
859 int rc = RTStrToUInt32Full(argv[0], 16, &u32Mask);
860 if (RT_FAILURE(rc))
861 {
862 VBoxControlError("Invalid video flags mask.\n");
863 return RTEXITCODE_FAILURE;
864 }
865
866 RTEXITCODE exitCode = RTEXITCODE_SUCCESS;
867
868 HKEY hkeyVideo = getVideoKey(true);
869 if (hkeyVideo)
870 {
871 DWORD dwFlags = 0;
872 DWORD cbValue = sizeof(dwFlags);
873 DWORD dwKeyType;
874 ULONG status = RegQueryValueExA(hkeyVideo, "VBoxVideoFlags", NULL, &dwKeyType, (LPBYTE)&dwFlags, &cbValue);
875 if (status != ERROR_SUCCESS)
876 dwFlags = 0;
877
878 dwFlags = fSet ? dwFlags | u32Mask : dwFlags & ~u32Mask;
879
880 status = RegSetValueExA(hkeyVideo, "VBoxVideoFlags", 0, REG_DWORD, (LPBYTE)&dwFlags, sizeof(dwFlags));
881 if (status != ERROR_SUCCESS)
882 {
883 VBoxControlError("Error %d writing video flags.\n", status);
884 exitCode = RTEXITCODE_FAILURE;
885 }
886
887 RegCloseKey(hkeyVideo);
888 }
889 else
890 {
891 exitCode = RTEXITCODE_FAILURE;
892 }
893
894 return exitCode;
895}
896
897static DECLCALLBACK(RTEXITCODE) handleVideoFlags(int argc, char *argv[])
898{
899 /* Must have a keyword and optional value (32 bit hex string). */
900 if (argc != 1 && argc != 2)
901 {
902 VBoxControlError("Invalid number of arguments.\n");
903 usage(VIDEO_FLAGS);
904 return RTEXITCODE_FAILURE;
905 }
906
907 RTEXITCODE exitCode = RTEXITCODE_SUCCESS;
908
909 if (RTStrICmp(argv[0], "get") == 0)
910 {
911 exitCode = videoFlagsGet();
912 }
913 else if (RTStrICmp(argv[0], "delete") == 0)
914 {
915 exitCode = videoFlagsDelete();
916 }
917 else if (RTStrICmp(argv[0], "set") == 0)
918 {
919 exitCode = videoFlagsModify(true, argc - 1, &argv[1]);
920 }
921 else if (RTStrICmp(argv[0], "clear") == 0)
922 {
923 exitCode = videoFlagsModify(false, argc - 1, &argv[1]);
924 }
925 else
926 {
927 VBoxControlError("Invalid command.\n");
928 exitCode = RTEXITCODE_FAILURE;
929 }
930
931 if (exitCode != RTEXITCODE_SUCCESS)
932 {
933 usage(VIDEO_FLAGS);
934 }
935
936 return exitCode;
937}
938
939#define MAX_CUSTOM_MODES 128
940
941/* the table of custom modes */
942struct
943{
944 DWORD xres;
945 DWORD yres;
946 DWORD bpp;
947} customModes[MAX_CUSTOM_MODES] = {0};
948
949void getCustomModes(HKEY hkeyVideo)
950{
951 ULONG status;
952 int curMode = 0;
953
954 /* null out the table */
955 RT_ZERO(customModes);
956
957 do
958 {
959 char valueName[20];
960 DWORD xres, yres, bpp = 0;
961 DWORD dwType;
962 DWORD dwLen = sizeof(DWORD);
963
964 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dWidth", curMode);
965 status = RegQueryValueExA(hkeyVideo, valueName, NULL, &dwType, (LPBYTE)&xres, &dwLen);
966 if (status != ERROR_SUCCESS)
967 break;
968 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dHeight", curMode);
969 status = RegQueryValueExA(hkeyVideo, valueName, NULL, &dwType, (LPBYTE)&yres, &dwLen);
970 if (status != ERROR_SUCCESS)
971 break;
972 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dBPP", curMode);
973 status = RegQueryValueExA(hkeyVideo, valueName, NULL, &dwType, (LPBYTE)&bpp, &dwLen);
974 if (status != ERROR_SUCCESS)
975 break;
976
977 /* check if the mode is OK */
978 if ( (xres > (1 << 16))
979 || (yres > (1 << 16))
980 || ( (bpp != 16)
981 && (bpp != 24)
982 && (bpp != 32)))
983 break;
984
985 /* add mode to table */
986 customModes[curMode].xres = xres;
987 customModes[curMode].yres = yres;
988 customModes[curMode].bpp = bpp;
989
990 ++curMode;
991
992 if (curMode >= MAX_CUSTOM_MODES)
993 break;
994 } while(1);
995}
996
997void writeCustomModes(HKEY hkeyVideo)
998{
999 ULONG status;
1000 int tableIndex = 0;
1001 int modeIndex = 0;
1002
1003 /* first remove all values */
1004 for (int i = 0; i < MAX_CUSTOM_MODES; i++)
1005 {
1006 char valueName[20];
1007 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dWidth", i);
1008 RegDeleteValueA(hkeyVideo, valueName);
1009 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dHeight", i);
1010 RegDeleteValueA(hkeyVideo, valueName);
1011 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dBPP", i);
1012 RegDeleteValueA(hkeyVideo, valueName);
1013 }
1014
1015 do
1016 {
1017 if (tableIndex >= MAX_CUSTOM_MODES)
1018 break;
1019
1020 /* is the table entry present? */
1021 if ( (!customModes[tableIndex].xres)
1022 || (!customModes[tableIndex].yres)
1023 || (!customModes[tableIndex].bpp))
1024 {
1025 tableIndex++;
1026 continue;
1027 }
1028
1029 RTPrintf("writing mode %d (%dx%dx%d)\n", modeIndex, customModes[tableIndex].xres, customModes[tableIndex].yres, customModes[tableIndex].bpp);
1030 char valueName[20];
1031 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dWidth", modeIndex);
1032 status = RegSetValueExA(hkeyVideo, valueName, 0, REG_DWORD, (LPBYTE)&customModes[tableIndex].xres,
1033 sizeof(customModes[tableIndex].xres));
1034 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dHeight", modeIndex);
1035 RegSetValueExA(hkeyVideo, valueName, 0, REG_DWORD, (LPBYTE)&customModes[tableIndex].yres,
1036 sizeof(customModes[tableIndex].yres));
1037 RTStrPrintf(valueName, sizeof(valueName), "CustomMode%dBPP", modeIndex);
1038 RegSetValueExA(hkeyVideo, valueName, 0, REG_DWORD, (LPBYTE)&customModes[tableIndex].bpp,
1039 sizeof(customModes[tableIndex].bpp));
1040
1041 modeIndex++;
1042 tableIndex++;
1043
1044 } while(1);
1045
1046}
1047
1048static DECLCALLBACK(RTEXITCODE) handleListCustomModes(int argc, char *argv[])
1049{
1050 RT_NOREF1(argv);
1051 if (argc != 0)
1052 {
1053 usage(LIST_CUST_MODES);
1054 return RTEXITCODE_FAILURE;
1055 }
1056
1057 HKEY hkeyVideo = getVideoKey(false);
1058
1059 if (hkeyVideo)
1060 {
1061 getCustomModes(hkeyVideo);
1062 for (int i = 0; i < (sizeof(customModes) / sizeof(customModes[0])); i++)
1063 {
1064 if ( !customModes[i].xres
1065 || !customModes[i].yres
1066 || !customModes[i].bpp)
1067 continue;
1068
1069 RTPrintf("Mode: %d x %d x %d\n",
1070 customModes[i].xres, customModes[i].yres, customModes[i].bpp);
1071 }
1072 RegCloseKey(hkeyVideo);
1073 }
1074 return RTEXITCODE_SUCCESS;
1075}
1076
1077static DECLCALLBACK(RTEXITCODE) handleAddCustomMode(int argc, char *argv[])
1078{
1079 if (argc != 3)
1080 {
1081 usage(ADD_CUST_MODE);
1082 return RTEXITCODE_FAILURE;
1083 }
1084
1085 DWORD xres = atoi(argv[0]);
1086 DWORD yres = atoi(argv[1]);
1087 DWORD bpp = atoi(argv[2]);
1088
1089 /** @todo better check including xres mod 8 = 0! */
1090 if ( (xres > (1 << 16))
1091 || (yres > (1 << 16))
1092 || ( (bpp != 16)
1093 && (bpp != 24)
1094 && (bpp != 32)))
1095 {
1096 VBoxControlError("invalid mode specified!\n");
1097 return RTEXITCODE_FAILURE;
1098 }
1099
1100 HKEY hkeyVideo = getVideoKey(true);
1101
1102 if (hkeyVideo)
1103 {
1104 int i;
1105 int fModeExists = 0;
1106 getCustomModes(hkeyVideo);
1107 for (i = 0; i < MAX_CUSTOM_MODES; i++)
1108 {
1109 /* mode exists? */
1110 if ( customModes[i].xres == xres
1111 && customModes[i].yres == yres
1112 && customModes[i].bpp == bpp
1113 )
1114 {
1115 fModeExists = 1;
1116 }
1117 }
1118 if (!fModeExists)
1119 {
1120 for (i = 0; i < MAX_CUSTOM_MODES; i++)
1121 {
1122 /* item free? */
1123 if (!customModes[i].xres)
1124 {
1125 customModes[i].xres = xres;
1126 customModes[i].yres = yres;
1127 customModes[i].bpp = bpp;
1128 break;
1129 }
1130 }
1131 writeCustomModes(hkeyVideo);
1132 }
1133 RegCloseKey(hkeyVideo);
1134 }
1135 return RTEXITCODE_SUCCESS;
1136}
1137
1138static DECLCALLBACK(RTEXITCODE) handleRemoveCustomMode(int argc, char *argv[])
1139{
1140 if (argc != 3)
1141 {
1142 usage(REMOVE_CUST_MODE);
1143 return RTEXITCODE_FAILURE;
1144 }
1145
1146 DWORD xres = atoi(argv[0]);
1147 DWORD yres = atoi(argv[1]);
1148 DWORD bpp = atoi(argv[2]);
1149
1150 HKEY hkeyVideo = getVideoKey(true);
1151
1152 if (hkeyVideo)
1153 {
1154 getCustomModes(hkeyVideo);
1155 for (int i = 0; i < MAX_CUSTOM_MODES; i++)
1156 {
1157 /* correct item? */
1158 if ( (customModes[i].xres == xres)
1159 && (customModes[i].yres == yres)
1160 && (customModes[i].bpp == bpp))
1161 {
1162 RTPrintf("found mode at index %d\n", i);
1163 RT_ZERO(customModes[i]);
1164 break;
1165 }
1166 }
1167 writeCustomModes(hkeyVideo);
1168 RegCloseKey(hkeyVideo);
1169 }
1170
1171 return RTEXITCODE_SUCCESS;
1172}
1173
1174#endif /* RT_OS_WINDOWS */
1175
1176#ifdef VBOX_WITH_GUEST_PROPS
1177/**
1178 * Retrieves a value from the guest property store.
1179 * This is accessed through the "VBoxGuestPropSvc" HGCM service.
1180 *
1181 * @returns Command exit code.
1182 * @note see the command line API description for parameters
1183 */
1184static RTEXITCODE getGuestProperty(int argc, char **argv)
1185{
1186 bool fVerbose = false;
1187 if ( argc == 2
1188 && ( strcmp(argv[1], "-verbose") == 0
1189 || strcmp(argv[1], "--verbose") == 0)
1190 )
1191 fVerbose = true;
1192 else if (argc != 1)
1193 {
1194 usage(GUEST_PROP);
1195 return RTEXITCODE_FAILURE;
1196 }
1197
1198 uint32_t u32ClientId = 0;
1199 int rc = VINF_SUCCESS;
1200
1201 rc = VbglR3GuestPropConnect(&u32ClientId);
1202 if (RT_FAILURE(rc))
1203 VBoxControlError("Failed to connect to the guest property service, error %Rrc\n", rc);
1204
1205 /*
1206 * Here we actually retrieve the value from the host.
1207 */
1208 const char *pszName = argv[0];
1209 char *pszValue = NULL;
1210 uint64_t u64Timestamp = 0;
1211 char *pszFlags = NULL;
1212 /* The buffer for storing the data and its initial size. We leave a bit
1213 * of space here in case the maximum values are raised. */
1214 void *pvBuf = NULL;
1215 uint32_t cbBuf = GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN + 1024;
1216 if (RT_SUCCESS(rc))
1217 {
1218 /* Because there is a race condition between our reading the size of a
1219 * property and the guest updating it, we loop a few times here and
1220 * hope. Actually this should never go wrong, as we are generous
1221 * enough with buffer space. */
1222 bool fFinished = false;
1223 for (unsigned i = 0; i < 10 && !fFinished; ++i)
1224 {
1225 void *pvTmpBuf = RTMemRealloc(pvBuf, cbBuf);
1226 if (NULL == pvTmpBuf)
1227 {
1228 rc = VERR_NO_MEMORY;
1229 VBoxControlError("Out of memory\n");
1230 }
1231 else
1232 {
1233 pvBuf = pvTmpBuf;
1234 rc = VbglR3GuestPropRead(u32ClientId, pszName, pvBuf, cbBuf,
1235 &pszValue, &u64Timestamp, &pszFlags,
1236 &cbBuf);
1237 }
1238 if (VERR_BUFFER_OVERFLOW == rc)
1239 /* Leave a bit of extra space to be safe */
1240 cbBuf += 1024;
1241 else
1242 fFinished = true;
1243 }
1244 if (VERR_TOO_MUCH_DATA == rc)
1245 VBoxControlError("Temporarily unable to retrieve the property\n");
1246 else if (RT_FAILURE(rc) && rc != VERR_NOT_FOUND)
1247 VBoxControlError("Failed to retrieve the property value, error %Rrc\n", rc);
1248 }
1249
1250 /*
1251 * And display it on the guest console.
1252 */
1253 if (VERR_NOT_FOUND == rc)
1254 RTPrintf("No value set!\n");
1255 else if (RT_SUCCESS(rc))
1256 {
1257 RTPrintf("Value: %s\n", pszValue);
1258 if (fVerbose)
1259 {
1260 RTPrintf("Timestamp: %lld ns\n", u64Timestamp);
1261 RTPrintf("Flags: %s\n", pszFlags);
1262 }
1263 }
1264
1265 if (u32ClientId != 0)
1266 VbglR3GuestPropDisconnect(u32ClientId);
1267 RTMemFree(pvBuf);
1268 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1269}
1270
1271
1272/**
1273 * Writes a value to the guest property store.
1274 * This is accessed through the "VBoxGuestPropSvc" HGCM service.
1275 *
1276 * @returns Command exit code.
1277 * @note see the command line API description for parameters
1278 */
1279static RTEXITCODE setGuestProperty(int argc, char *argv[])
1280{
1281 /*
1282 * Check the syntax. We can deduce the correct syntax from the number of
1283 * arguments.
1284 */
1285 bool fUsageOK = true;
1286 const char *pszName = NULL;
1287 const char *pszValue = NULL;
1288 const char *pszFlags = NULL;
1289 if (2 == argc)
1290 {
1291 pszValue = argv[1];
1292 }
1293 else if (3 == argc)
1294 fUsageOK = false;
1295 else if (4 == argc)
1296 {
1297 pszValue = argv[1];
1298 if ( strcmp(argv[2], "-flags") != 0
1299 && strcmp(argv[2], "--flags") != 0)
1300 fUsageOK = false;
1301 pszFlags = argv[3];
1302 }
1303 else if (argc != 1)
1304 fUsageOK = false;
1305 if (!fUsageOK)
1306 {
1307 usage(GUEST_PROP);
1308 return RTEXITCODE_FAILURE;
1309 }
1310 /* This is always needed. */
1311 pszName = argv[0];
1312
1313 /*
1314 * Do the actual setting.
1315 */
1316 uint32_t u32ClientId = 0;
1317 int rc = VINF_SUCCESS;
1318 rc = VbglR3GuestPropConnect(&u32ClientId);
1319 if (RT_FAILURE(rc))
1320 VBoxControlError("Failed to connect to the guest property service, error %Rrc\n", rc);
1321 else
1322 {
1323 if (pszFlags != NULL)
1324 rc = VbglR3GuestPropWrite(u32ClientId, pszName, pszValue, pszFlags);
1325 else
1326 rc = VbglR3GuestPropWriteValue(u32ClientId, pszName, pszValue);
1327 if (RT_FAILURE(rc))
1328 VBoxControlError("Failed to store the property value, error %Rrc\n", rc);
1329 }
1330
1331 if (u32ClientId != 0)
1332 VbglR3GuestPropDisconnect(u32ClientId);
1333 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1334}
1335
1336
1337/**
1338 * Deletes a guest property from the guest property store.
1339 * This is accessed through the "VBoxGuestPropSvc" HGCM service.
1340 *
1341 * @returns Command exit code.
1342 * @note see the command line API description for parameters
1343 */
1344static RTEXITCODE deleteGuestProperty(int argc, char *argv[])
1345{
1346 /*
1347 * Check the syntax. We can deduce the correct syntax from the number of
1348 * arguments.
1349 */
1350 bool fUsageOK = true;
1351 const char *pszName = NULL;
1352 if (argc < 1)
1353 fUsageOK = false;
1354 if (!fUsageOK)
1355 {
1356 usage(GUEST_PROP);
1357 return RTEXITCODE_FAILURE;
1358 }
1359 /* This is always needed. */
1360 pszName = argv[0];
1361
1362 /*
1363 * Do the actual setting.
1364 */
1365 uint32_t u32ClientId = 0;
1366 int rc = VbglR3GuestPropConnect(&u32ClientId);
1367 if (RT_FAILURE(rc))
1368 VBoxControlError("Failed to connect to the guest property service, error %Rrc\n", rc);
1369 else
1370 {
1371 rc = VbglR3GuestPropDelete(u32ClientId, pszName);
1372 if (RT_FAILURE(rc))
1373 VBoxControlError("Failed to delete the property value, error %Rrc\n", rc);
1374 }
1375
1376 if (u32ClientId != 0)
1377 VbglR3GuestPropDisconnect(u32ClientId);
1378 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1379}
1380
1381
1382/**
1383 * Enumerates the properties in the guest property store.
1384 * This is accessed through the "VBoxGuestPropSvc" HGCM service.
1385 *
1386 * @returns Command exit code.
1387 * @note see the command line API description for parameters
1388 */
1389static RTEXITCODE enumGuestProperty(int argc, char *argv[])
1390{
1391 /*
1392 * Check the syntax. We can deduce the correct syntax from the number of
1393 * arguments.
1394 */
1395 char const * const *papszPatterns = NULL;
1396 uint32_t cPatterns = 0;
1397 if ( argc > 1
1398 && ( strcmp(argv[0], "-patterns") == 0
1399 || strcmp(argv[0], "--patterns") == 0))
1400 {
1401 papszPatterns = (char const * const *)&argv[1];
1402 cPatterns = argc - 1;
1403 }
1404 else if (argc != 0)
1405 {
1406 usage(GUEST_PROP);
1407 return RTEXITCODE_FAILURE;
1408 }
1409
1410 /*
1411 * Do the actual enumeration.
1412 */
1413 uint32_t u32ClientId = 0;
1414 int rc = VbglR3GuestPropConnect(&u32ClientId);
1415 if (RT_SUCCESS(rc))
1416 {
1417 PVBGLR3GUESTPROPENUM pHandle;
1418 const char *pszName, *pszValue, *pszFlags;
1419 uint64_t u64Timestamp;
1420
1421 rc = VbglR3GuestPropEnum(u32ClientId, papszPatterns, cPatterns, &pHandle,
1422 &pszName, &pszValue, &u64Timestamp, &pszFlags);
1423 if (RT_SUCCESS(rc))
1424 {
1425 while (RT_SUCCESS(rc) && pszName)
1426 {
1427 RTPrintf("Name: %s, value: %s, timestamp: %lld, flags: %s\n",
1428 pszName, pszValue ? pszValue : "", u64Timestamp, pszFlags);
1429
1430 rc = VbglR3GuestPropEnumNext(pHandle, &pszName, &pszValue, &u64Timestamp, &pszFlags);
1431 if (RT_FAILURE(rc))
1432 VBoxControlError("Error while enumerating guest properties: %Rrc\n", rc);
1433 }
1434
1435 VbglR3GuestPropEnumFree(pHandle);
1436 }
1437 else if (VERR_NOT_FOUND == rc)
1438 RTPrintf("No properties found.\n");
1439 else
1440 VBoxControlError("Failed to enumerate the guest properties! Error: %Rrc\n", rc);
1441 VbglR3GuestPropDisconnect(u32ClientId);
1442 }
1443 else
1444 VBoxControlError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
1445 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1446}
1447
1448
1449/**
1450 * Waits for notifications of changes to guest properties.
1451 * This is accessed through the "VBoxGuestPropSvc" HGCM service.
1452 *
1453 * @returns Command exit code.
1454 * @note see the command line API description for parameters
1455 */
1456static RTEXITCODE waitGuestProperty(int argc, char **argv)
1457{
1458 /*
1459 * Handle arguments
1460 */
1461 const char *pszPatterns = NULL;
1462 uint64_t u64TimestampIn = 0;
1463 uint32_t u32Timeout = RT_INDEFINITE_WAIT;
1464 bool fUsageOK = true;
1465 if (argc < 1)
1466 fUsageOK = false;
1467 pszPatterns = argv[0];
1468 for (int i = 1; fUsageOK && i < argc; ++i)
1469 {
1470 if ( strcmp(argv[i], "-timeout") == 0
1471 || strcmp(argv[i], "--timeout") == 0)
1472 {
1473 if ( i + 1 >= argc
1474 || RTStrToUInt32Full(argv[i + 1], 10, &u32Timeout)
1475 != VINF_SUCCESS
1476 )
1477 fUsageOK = false;
1478 else
1479 ++i;
1480 }
1481 else if ( strcmp(argv[i], "-timestamp") == 0
1482 || strcmp(argv[i], "--timestamp") == 0)
1483 {
1484 if ( i + 1 >= argc
1485 || RTStrToUInt64Full(argv[i + 1], 10, &u64TimestampIn)
1486 != VINF_SUCCESS
1487 )
1488 fUsageOK = false;
1489 else
1490 ++i;
1491 }
1492 else
1493 fUsageOK = false;
1494 }
1495 if (!fUsageOK)
1496 {
1497 usage(GUEST_PROP);
1498 return RTEXITCODE_FAILURE;
1499 }
1500
1501 /*
1502 * Connect to the service
1503 */
1504 uint32_t u32ClientId = 0;
1505 int rc = VbglR3GuestPropConnect(&u32ClientId);
1506 if (RT_FAILURE(rc))
1507 VBoxControlError("Failed to connect to the guest property service, error %Rrc\n", rc);
1508
1509 /*
1510 * Retrieve the notification from the host
1511 */
1512 char *pszName = NULL;
1513 char *pszValue = NULL;
1514 uint64_t u64TimestampOut = 0;
1515 char *pszFlags = NULL;
1516 /* The buffer for storing the data and its initial size. We leave a bit
1517 * of space here in case the maximum values are raised. */
1518 void *pvBuf = NULL;
1519 uint32_t cbBuf = GUEST_PROP_MAX_NAME_LEN + GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN + 1024;
1520 /* Because there is a race condition between our reading the size of a
1521 * property and the guest updating it, we loop a few times here and
1522 * hope. Actually this should never go wrong, as we are generous
1523 * enough with buffer space. */
1524 bool fFinished = false;
1525 for (unsigned i = 0; (RT_SUCCESS(rc) || rc == VERR_BUFFER_OVERFLOW) && !fFinished && i < 10; i++)
1526 {
1527 void *pvTmpBuf = RTMemRealloc(pvBuf, cbBuf);
1528 if (NULL == pvTmpBuf)
1529 {
1530 rc = VERR_NO_MEMORY;
1531 VBoxControlError("Out of memory\n");
1532 }
1533 else
1534 {
1535 pvBuf = pvTmpBuf;
1536 rc = VbglR3GuestPropWait(u32ClientId, pszPatterns, pvBuf, cbBuf,
1537 u64TimestampIn, u32Timeout,
1538 &pszName, &pszValue, &u64TimestampOut,
1539 &pszFlags, &cbBuf);
1540 }
1541 if (VERR_BUFFER_OVERFLOW == rc)
1542 /* Leave a bit of extra space to be safe */
1543 cbBuf += 1024;
1544 else
1545 fFinished = true;
1546 if (rc == VERR_TOO_MUCH_DATA)
1547 VBoxControlError("Temporarily unable to get a notification\n");
1548 else if (rc == VERR_INTERRUPTED)
1549 VBoxControlError("The request timed out or was interrupted\n");
1550 else if (RT_FAILURE(rc) && rc != VERR_NOT_FOUND)
1551 VBoxControlError("Failed to get a notification, error %Rrc\n", rc);
1552 }
1553
1554 /*
1555 * And display it on the guest console.
1556 */
1557 if (VERR_NOT_FOUND == rc)
1558 RTPrintf("No value set!\n");
1559 else if (rc == VERR_BUFFER_OVERFLOW)
1560 RTPrintf("Internal error: unable to determine the size of the data!\n");
1561 else if (RT_SUCCESS(rc))
1562 {
1563 RTPrintf("Name: %s\n", pszName);
1564 RTPrintf("Value: %s\n", pszValue);
1565 RTPrintf("Timestamp: %lld ns\n", u64TimestampOut);
1566 RTPrintf("Flags: %s\n", pszFlags);
1567 }
1568
1569 if (u32ClientId != 0)
1570 VbglR3GuestPropDisconnect(u32ClientId);
1571 RTMemFree(pvBuf);
1572 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1573}
1574
1575
1576/**
1577 * Access the guest property store through the "VBoxGuestPropSvc" HGCM
1578 * service.
1579 *
1580 * @returns 0 on success, 1 on failure
1581 * @note see the command line API description for parameters
1582 */
1583static DECLCALLBACK(RTEXITCODE) handleGuestProperty(int argc, char *argv[])
1584{
1585 if (argc == 0)
1586 {
1587 usage(GUEST_PROP);
1588 return RTEXITCODE_FAILURE;
1589 }
1590 if (!strcmp(argv[0], "get"))
1591 return getGuestProperty(argc - 1, argv + 1);
1592 if (!strcmp(argv[0], "set"))
1593 return setGuestProperty(argc - 1, argv + 1);
1594 if (!strcmp(argv[0], "delete") || !strcmp(argv[0], "unset"))
1595 return deleteGuestProperty(argc - 1, argv + 1);
1596 if (!strcmp(argv[0], "enumerate"))
1597 return enumGuestProperty(argc - 1, argv + 1);
1598 if (!strcmp(argv[0], "wait"))
1599 return waitGuestProperty(argc - 1, argv + 1);
1600 /* unknown cmd */
1601 usage(GUEST_PROP);
1602 return RTEXITCODE_FAILURE;
1603}
1604
1605#endif
1606#ifdef VBOX_WITH_SHARED_FOLDERS
1607
1608/**
1609 * Lists the Shared Folders provided by the host.
1610 */
1611static RTEXITCODE sharedFolder_list(int argc, char **argv)
1612{
1613 bool fUsageOK = true;
1614 bool fOnlyShowAutoMount = false;
1615 if (argc == 1)
1616 {
1617 if (!strcmp(argv[0], "--automount"))
1618 fOnlyShowAutoMount = true;
1619 else
1620 fUsageOK = false;
1621 }
1622 else if (argc > 1)
1623 fUsageOK = false;
1624 if (!fUsageOK)
1625 {
1626 usage(GUEST_SHAREDFOLDERS);
1627 return RTEXITCODE_SYNTAX;
1628 }
1629
1630 uint32_t u32ClientId;
1631 int rc = VbglR3SharedFolderConnect(&u32ClientId);
1632 if (RT_FAILURE(rc))
1633 VBoxControlError("Failed to connect to the shared folder service, error %Rrc\n", rc);
1634 else
1635 {
1636 PVBGLR3SHAREDFOLDERMAPPING paMappings;
1637 uint32_t cMappings;
1638 rc = VbglR3SharedFolderGetMappings(u32ClientId, fOnlyShowAutoMount, &paMappings, &cMappings);
1639 if (RT_SUCCESS(rc))
1640 {
1641 if (fOnlyShowAutoMount)
1642 RTPrintf("Auto-mounted Shared Folder mappings (%u):\n\n", cMappings);
1643 else
1644 RTPrintf("Shared Folder mappings (%u):\n\n", cMappings);
1645
1646 for (uint32_t i = 0; i < cMappings; i++)
1647 {
1648 char *pszName;
1649 char *pszMntPt;
1650 uint64_t fFlags;
1651 uint32_t uRootIdVer;
1652 rc = VbglR3SharedFolderQueryFolderInfo(u32ClientId, paMappings[i].u32Root, 0,
1653 &pszName, &pszMntPt, &fFlags, &uRootIdVer);
1654 if (RT_SUCCESS(rc))
1655 {
1656 RTPrintf("%02u - %s [idRoot=%u", i + 1, pszName, paMappings[i].u32Root);
1657 if (fFlags & SHFL_MIF_WRITABLE)
1658 RTPrintf(" writable");
1659 else
1660 RTPrintf(" readonly");
1661 if (fFlags & SHFL_MIF_AUTO_MOUNT)
1662 RTPrintf(" auto-mount");
1663 if (fFlags & SHFL_MIF_SYMLINK_CREATION)
1664 RTPrintf(" create-symlink");
1665 if (fFlags & SHFL_MIF_HOST_ICASE)
1666 RTPrintf(" host-icase");
1667 if (fFlags & SHFL_MIF_GUEST_ICASE)
1668 RTPrintf(" guest-icase");
1669 if (*pszMntPt)
1670 RTPrintf(" mnt-pt=%s", pszMntPt);
1671 RTPrintf("]");
1672# ifdef RT_OS_OS2
1673 /* Show drive letters: */
1674 const char *pszOn = " on";
1675 for (char chDrive = 'A'; chDrive <= 'Z'; chDrive++)
1676 {
1677 char szDrive[4] = { chDrive, ':', '\0', '\0' };
1678 union
1679 {
1680 FSQBUFFER2 FsQueryBuf;
1681 char achPadding[512];
1682 } uBuf;
1683 RT_ZERO(uBuf);
1684 ULONG cbBuf = sizeof(uBuf) - 2;
1685 APIRET rcOs2 = DosQueryFSAttach(szDrive, 0, FSAIL_QUERYNAME, &uBuf.FsQueryBuf, &cbBuf);
1686 if (rcOs2 == NO_ERROR)
1687 {
1688 const char *pszFsdName = (const char *)&uBuf.FsQueryBuf.szName[uBuf.FsQueryBuf.cbName + 1];
1689 if ( uBuf.FsQueryBuf.iType == FSAT_REMOTEDRV
1690 && RTStrICmpAscii(pszFsdName, "VBOXSF") == 0)
1691 {
1692 const char *pszMountedName = (const char *)&pszFsdName[uBuf.FsQueryBuf.cbFSDName + 1];
1693 if (RTStrICmp(pszMountedName, pszName) == 0)
1694 {
1695 const char *pszTag = pszMountedName + strlen(pszMountedName) + 1; /* safe */
1696 if (*pszTag != '\0')
1697 RTPrintf("%s %s (%s)", pszOn, szDrive, pszTag);
1698 else
1699 RTPrintf("%s %s", pszOn, szDrive);
1700 pszOn = ",";
1701 }
1702 }
1703 }
1704 }
1705# endif
1706 RTPrintf("\n");
1707
1708 RTStrFree(pszName);
1709 RTStrFree(pszMntPt);
1710 }
1711 else
1712 VBoxControlError("Error while getting the shared folder name for root node = %u, rc = %Rrc\n",
1713 paMappings[i].u32Root, rc);
1714 }
1715 if (!cMappings)
1716 RTPrintf("No Shared Folders available.\n");
1717 VbglR3SharedFolderFreeMappings(paMappings);
1718 }
1719 else
1720 VBoxControlError("Error while getting the shared folder mappings, rc = %Rrc\n", rc);
1721 VbglR3SharedFolderDisconnect(u32ClientId);
1722 }
1723 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1724}
1725
1726# ifdef RT_OS_OS2
1727/**
1728 * Attaches a shared folder to a drive letter.
1729 */
1730static RTEXITCODE sharedFolder_use(int argc, char **argv)
1731{
1732 /*
1733 * Takes a drive letter and a share name as arguments.
1734 */
1735 if (argc != 2)
1736 return VBoxControlSyntaxError("sharedfolder use: expected a drive letter and a shared folder name\n");
1737
1738 const char *pszDrive = argv[0];
1739 if (!RT_C_IS_ALPHA(pszDrive[0]) || pszDrive[1] != ':' || pszDrive[2] != '\0')
1740 return VBoxControlSyntaxError("sharedfolder use: not a drive letter: %s\n", pszDrive);
1741
1742 static const char s_szTag[] = "VBoxControl";
1743 char szzNameAndTag[256];
1744 const char *pszName = argv[1];
1745 size_t cchName = strlen(pszName);
1746 if (cchName < 1)
1747 return VBoxControlSyntaxError("sharedfolder use: shared folder name cannot be empty!\n");
1748 if (cchName + 1 + sizeof(s_szTag) >= sizeof(szzNameAndTag))
1749 return VBoxControlSyntaxError("sharedfolder use: shared folder name is too long! (%s)\n", pszName);
1750
1751 /*
1752 * Do the attaching.
1753 */
1754 memcpy(szzNameAndTag, pszName, cchName);
1755 szzNameAndTag[cchName] = '\0';
1756 memcpy(&szzNameAndTag[cchName + 1], s_szTag, sizeof(s_szTag));
1757
1758 APIRET rcOs2 = DosFSAttach(pszDrive, "VBOXSF", szzNameAndTag, cchName + 1 + sizeof(s_szTag), FS_ATTACH);
1759 if (rcOs2 == NO_ERROR)
1760 return RTEXITCODE_SUCCESS;
1761 if (rcOs2 == ERROR_INVALID_FSD_NAME)
1762 return VBoxControlError("Shared folders IFS not installed?\n");
1763 return VBoxControlError("DosFSAttach/FS_ATTACH failed to attach '%s' to '%s': %u\n", pszName, pszDrive, rcOs2);
1764}
1765
1766/**
1767 * Detaches a shared folder from a drive letter.
1768 */
1769static RTEXITCODE sharedFolder_unuse(int argc, char **argv)
1770{
1771 /*
1772 * Only takes a drive letter as argument.
1773 */
1774 if (argc != 1)
1775 return VBoxControlSyntaxError("sharedfolder unuse: expected drive letter\n");
1776 const char *pszDrive = argv[0];
1777 if (!RT_C_IS_ALPHA(pszDrive[0]) || pszDrive[1] != ':' || pszDrive[2] != '\0')
1778 return VBoxControlSyntaxError("sharedfolder unuse: not a drive letter: %s\n", pszDrive);
1779
1780 /*
1781 * Do the detaching.
1782 */
1783 APIRET rcOs2 = DosFSAttach(pszDrive, "VBOXSF", NULL, 0, FS_DETACH);
1784 if (rcOs2 == NO_ERROR)
1785 return RTEXITCODE_SUCCESS;
1786 return VBoxControlError("DosFSAttach/FS_DETACH failed on '%s': %u\n", pszDrive, rcOs2);
1787}
1788
1789# endif /* RT_OS_OS2 */
1790
1791
1792/**
1793 * Handles Shared Folders control.
1794 *
1795 * @returns 0 on success, 1 on failure
1796 * @note see the command line API description for parameters
1797 * (r=bird: yeah, right. The API description contains nil about params)
1798 */
1799static DECLCALLBACK(RTEXITCODE) handleSharedFolder(int argc, char *argv[])
1800{
1801 if (argc == 0)
1802 {
1803 usage(GUEST_SHAREDFOLDERS);
1804 return RTEXITCODE_FAILURE;
1805 }
1806 if (!strcmp(argv[0], "list"))
1807 return sharedFolder_list(argc - 1, argv + 1);
1808# ifdef RT_OS_OS2
1809 if (!strcmp(argv[0], "use"))
1810 return sharedFolder_use(argc - 1, argv + 1);
1811 if (!strcmp(argv[0], "unuse"))
1812 return sharedFolder_unuse(argc - 1, argv + 1);
1813# endif
1814
1815 usage(GUEST_SHAREDFOLDERS);
1816 return RTEXITCODE_FAILURE;
1817}
1818
1819#endif
1820#if !defined(VBOX_CONTROL_TEST)
1821
1822/**
1823 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: writecoredump}
1824 */
1825static DECLCALLBACK(RTEXITCODE) handleWriteCoreDump(int argc, char *argv[])
1826{
1827 RT_NOREF2(argc, argv);
1828 int rc = VbglR3WriteCoreDump();
1829 if (RT_SUCCESS(rc))
1830 {
1831 RTPrintf("Guest core dump successful.\n");
1832 return RTEXITCODE_SUCCESS;
1833 }
1834 else
1835 {
1836 VBoxControlError("Error while taking guest core dump. rc=%Rrc\n", rc);
1837 return RTEXITCODE_FAILURE;
1838 }
1839}
1840
1841#endif
1842#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
1843
1844/**
1845 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: help}
1846 */
1847static DECLCALLBACK(RTEXITCODE) handleDpc(int argc, char *argv[])
1848{
1849 RT_NOREF(argc, argv);
1850 int rc = VERR_NOT_IMPLEMENTED;
1851# ifndef VBOX_CONTROL_TEST
1852 for (int i = 0; i < 30; i++)
1853 {
1854 VBGLREQHDR Req;
1855 VBGLREQHDR_INIT(&Req, DPC_LATENCY_CHECKER);
1856 rc = vbglR3DoIOCtl(VBGL_IOCTL_DPC_LATENCY_CHECKER, &Req, sizeof(Req));
1857 if (RT_SUCCESS(rc))
1858 RTPrintf("%d\n", i);
1859 else
1860 break;
1861 }
1862# endif
1863 if (RT_FAILURE(rc))
1864 return VBoxControlError("Error. rc=%Rrc\n", rc);
1865 RTPrintf("Samples collection completed.\n");
1866 return RTEXITCODE_SUCCESS;
1867}
1868#endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
1869
1870
1871/**
1872 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: writelog}
1873 */
1874static DECLCALLBACK(RTEXITCODE) handleWriteLog(int argc, char *argv[])
1875{
1876 static const RTGETOPTDEF s_aOptions[] =
1877 {
1878 { "--no-newline", 'n', RTGETOPT_REQ_NOTHING },
1879 };
1880 bool fNoNewline = false;
1881
1882 RTGETOPTSTATE GetOptState;
1883 int rc = RTGetOptInit(&GetOptState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions),
1884 0 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1885 if (RT_SUCCESS(rc))
1886 {
1887 RTGETOPTUNION ValueUnion;
1888 int ch;
1889 while ((ch = RTGetOpt(&GetOptState, &ValueUnion)) != 0)
1890 {
1891 switch (ch)
1892 {
1893 case VINF_GETOPT_NOT_OPTION:
1894 {
1895 size_t cch = strlen(ValueUnion.psz);
1896 if ( fNoNewline
1897 || (cch > 0 && ValueUnion.psz[cch - 1] == '\n') )
1898 rc = VbglR3WriteLog(ValueUnion.psz, cch);
1899 else
1900 {
1901 char *pszDup = (char *)RTMemDupEx(ValueUnion.psz, cch, 2);
1902 if (RT_SUCCESS(rc))
1903 {
1904 pszDup[cch++] = '\n';
1905 pszDup[cch] = '\0';
1906 rc = VbglR3WriteLog(pszDup, cch);
1907 RTMemFree(pszDup);
1908 }
1909 else
1910 rc = VERR_NO_MEMORY;
1911 }
1912 if (RT_FAILURE(rc))
1913 return VBoxControlError("VbglR3WriteLog: %Rrc", rc);
1914 break;
1915 }
1916
1917 case 'n':
1918 fNoNewline = true;
1919 break;
1920
1921 case 'h': return usage(WRITE_LOG);
1922 case 'V': return printVersion();
1923 default:
1924 return VBoxCtrlGetOptError(ch, &ValueUnion);
1925 }
1926 }
1927 }
1928 else
1929 return VBoxControlError("RTGetOptInit: %Rrc", rc);
1930 return RTEXITCODE_SUCCESS;
1931}
1932
1933
1934/**
1935 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: takesnapshot}
1936 */
1937static DECLCALLBACK(RTEXITCODE) handleTakeSnapshot(int argc, char *argv[])
1938{
1939 RT_NOREF2(argc, argv); //VbglR3VmTakeSnapshot(argv[0], argv[1]);
1940 return VBoxControlError("not implemented");
1941}
1942
1943/**
1944 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: savestate}
1945 */
1946static DECLCALLBACK(RTEXITCODE) handleSaveState(int argc, char *argv[])
1947{
1948 RT_NOREF2(argc, argv); //VbglR3VmSaveState();
1949 return VBoxControlError("not implemented");
1950}
1951
1952/**
1953 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: suspend|pause}
1954 */
1955static DECLCALLBACK(RTEXITCODE) handleSuspend(int argc, char *argv[])
1956{
1957 RT_NOREF2(argc, argv); //VbglR3VmSuspend();
1958 return VBoxControlError("not implemented");
1959}
1960
1961/**
1962 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: poweroff|powerdown}
1963 */
1964static DECLCALLBACK(RTEXITCODE) handlePowerOff(int argc, char *argv[])
1965{
1966 RT_NOREF2(argc, argv); //VbglR3VmPowerOff();
1967 return VBoxControlError("not implemented");
1968}
1969
1970/**
1971 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: version}
1972 */
1973static DECLCALLBACK(RTEXITCODE) handleVersion(int argc, char *argv[])
1974{
1975 RT_NOREF1(argv);
1976 if (argc)
1977 return VBoxControlSyntaxError("getversion does not take any arguments");
1978 return printVersion();
1979}
1980
1981/**
1982 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: help}
1983 */
1984static DECLCALLBACK(RTEXITCODE) handleHelp(int argc, char *argv[])
1985{
1986 RT_NOREF2(argc, argv); /* ignore arguments for now. */
1987 usage();
1988 return RTEXITCODE_SUCCESS;
1989}
1990
1991/**
1992 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: ls}
1993 */
1994static DECLCALLBACK(RTEXITCODE) handleLs(int argc, char *argv[])
1995{
1996 return RTFsCmdLs(argc + 1, argv - 1);
1997}
1998
1999/**
2000 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: tar}
2001 */
2002static DECLCALLBACK(RTEXITCODE) handleTar(int argc, char *argv[])
2003{
2004 return RTZipTarCmd(argc + 1, argv - 1);
2005}
2006
2007/**
2008 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: tar}
2009 */
2010static DECLCALLBACK(RTEXITCODE) handleGzip(int argc, char *argv[])
2011{
2012 return RTZipGzipCmd(argc + 1, argv - 1);
2013}
2014
2015/**
2016 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: unzip}
2017 */
2018static DECLCALLBACK(RTEXITCODE) handleUnzip(int argc, char *argv[])
2019{
2020 return RTZipUnzipCmd(argc + 1, argv - 1);
2021}
2022
2023
2024/** command handler type */
2025typedef DECLCALLBACK(RTEXITCODE) FNVBOXCTRLCMDHANDLER(int argc, char *argv[]);
2026typedef FNVBOXCTRLCMDHANDLER *PFNVBOXCTRLCMDHANDLER;
2027
2028/** The table of all registered command handlers. */
2029struct COMMANDHANDLER
2030{
2031 const char *pszCommand;
2032 PFNVBOXCTRLCMDHANDLER pfnHandler;
2033 bool fNeedDevice;
2034} g_aCommandHandlers[] =
2035{
2036#if defined(RT_OS_WINDOWS) && !defined(VBOX_CONTROL_TEST)
2037 { "getvideoacceleration", handleGetVideoAcceleration, true },
2038 { "setvideoacceleration", handleSetVideoAcceleration, true },
2039 { "videoflags", handleVideoFlags, true },
2040 { "listcustommodes", handleListCustomModes, true },
2041 { "addcustommode", handleAddCustomMode, true },
2042 { "removecustommode", handleRemoveCustomMode, true },
2043 { "setvideomode", handleSetVideoMode, true },
2044#endif
2045#ifdef VBOX_WITH_GUEST_PROPS
2046 { "guestproperty", handleGuestProperty, true },
2047#endif
2048#ifdef VBOX_WITH_SHARED_FOLDERS
2049 { "sharedfolder", handleSharedFolder, true },
2050#endif
2051#if !defined(VBOX_CONTROL_TEST)
2052 { "writecoredump", handleWriteCoreDump, true },
2053#endif
2054#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
2055 { "dpc", handleDpc, true },
2056#endif
2057 { "writelog", handleWriteLog, true },
2058 { "takesnapshot", handleTakeSnapshot, true },
2059 { "savestate", handleSaveState, true },
2060 { "suspend", handleSuspend, true },
2061 { "pause", handleSuspend, true },
2062 { "poweroff", handlePowerOff, true },
2063 { "powerdown", handlePowerOff, true },
2064 { "getversion", handleVersion, false },
2065 { "version", handleVersion, false },
2066 { "help", handleHelp, false },
2067 /* Hany tricks that doesn't cost much space: */
2068 { "gzip", handleGzip, false },
2069 { "ls", handleLs, false },
2070 { "tar", handleTar, false },
2071 { "unzip", handleUnzip, false },
2072};
2073
2074/** Main function */
2075int main(int argc, char **argv)
2076{
2077 /** The application's global return code */
2078 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2079 /** An IPRT return code for local use */
2080 int rrc = VINF_SUCCESS;
2081 /** The index of the command line argument we are currently processing */
2082 int iArg = 1;
2083 /** Should we show the logo text? */
2084 bool fShowLogo = true;
2085 /** Should we print the usage after the logo? For the -help switch. */
2086 bool fDoHelp = false;
2087 /** Will we be executing a command or just printing information? */
2088 bool fOnlyInfo = false;
2089
2090 rrc = RTR3InitExe(argc, &argv, 0);
2091 if (RT_FAILURE(rrc))
2092 return RTMsgInitFailure(rrc);
2093
2094 /*
2095 * Start by handling command line switches
2096 */
2097 /** @todo RTGetOpt conversion of the whole file. */
2098 bool done = false; /**< Are we finished with handling switches? */
2099 while (!done && (iArg < argc))
2100 {
2101 if ( !strcmp(argv[iArg], "-V")
2102 || !strcmp(argv[iArg], "-v")
2103 || !strcmp(argv[iArg], "--version")
2104 || !strcmp(argv[iArg], "-version")
2105 )
2106 {
2107 /* Print version number, and do nothing else. */
2108 printVersion();
2109 fOnlyInfo = true;
2110 fShowLogo = false;
2111 done = true;
2112 }
2113 else if ( !strcmp(argv[iArg], "-nologo")
2114 || !strcmp(argv[iArg], "--nologo"))
2115 fShowLogo = false;
2116 else if ( !strcmp(argv[iArg], "-help")
2117 || !strcmp(argv[iArg], "--help"))
2118 {
2119 fOnlyInfo = true;
2120 fDoHelp = true;
2121 done = true;
2122 }
2123 else
2124 /* We have found an argument which isn't a switch. Exit to the
2125 * command processing bit. */
2126 done = true;
2127 if (!done)
2128 ++iArg;
2129 }
2130
2131 /*
2132 * Find the application name, show our logo if the user hasn't suppressed it,
2133 * and show the usage if the user asked us to
2134 */
2135 g_pszProgName = RTPathFilename(argv[0]);
2136 if (fShowLogo)
2137 RTPrintf(VBOX_PRODUCT " Guest Additions Command Line Management Interface Version "
2138 VBOX_VERSION_STRING "\n"
2139 "(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
2140 "All rights reserved.\n\n");
2141 if (fDoHelp)
2142 usage();
2143
2144 /*
2145 * Now look for an actual command in the argument list and handle it.
2146 */
2147 if (!fOnlyInfo && rcExit == RTEXITCODE_SUCCESS)
2148 {
2149 if (argc > iArg)
2150 {
2151 /*
2152 * Try locate the command and execute it, complain if not found.
2153 */
2154 unsigned i;
2155 for (i = 0; i < RT_ELEMENTS(g_aCommandHandlers); i++)
2156 if (!strcmp(argv[iArg], g_aCommandHandlers[i].pszCommand))
2157 {
2158 if (g_aCommandHandlers[i].fNeedDevice)
2159 {
2160 rrc = VbglR3Init();
2161 if (RT_FAILURE(rrc))
2162 {
2163 VBoxControlError("Could not contact the host system. Make sure that you are running this\n"
2164 "application inside a VirtualBox guest system, and that you have sufficient\n"
2165 "user permissions.\n");
2166 rcExit = RTEXITCODE_FAILURE;
2167 }
2168 }
2169 if (rcExit == RTEXITCODE_SUCCESS)
2170 rcExit = g_aCommandHandlers[i].pfnHandler(argc - iArg - 1, argv + iArg + 1);
2171 break;
2172 }
2173 if (i >= RT_ELEMENTS(g_aCommandHandlers))
2174 {
2175 usage();
2176 rcExit = RTEXITCODE_SYNTAX;
2177 }
2178 }
2179 else
2180 {
2181 /* The user didn't specify a command. */
2182 usage();
2183 rcExit = RTEXITCODE_SYNTAX;
2184 }
2185 }
2186
2187 /*
2188 * And exit, returning the status
2189 */
2190 return rcExit;
2191}
2192
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