VirtualBox

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

Last change on this file since 75780 was 75702, checked in by vboxsync, 6 years ago

VBoxControl guestproperty enumerate: Don't print NULL values as <NULL> but rather like empty strings. (Don't ask me why VbglR3GuestPropEnumNext returns NULL values, though it is more efficient.)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 70.1 KB
Line 
1/* $Id: VBoxControl.cpp 75702 2018-11-25 01:40:54Z vboxsync $ */
2/** @file
3 * VBoxControl - Guest Additions Command Line Management Interface.
4 */
5
6/*
7 * Copyright (C) 2008-2017 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/err.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 = VINF_SUCCESS;
1506
1507 rc = VbglR3GuestPropConnect(&u32ClientId);
1508 if (RT_FAILURE(rc))
1509 VBoxControlError("Failed to connect to the guest property service, error %Rrc\n", rc);
1510
1511 /*
1512 * Retrieve the notification from the host
1513 */
1514 char *pszName = NULL;
1515 char *pszValue = NULL;
1516 uint64_t u64TimestampOut = 0;
1517 char *pszFlags = NULL;
1518 /* The buffer for storing the data and its initial size. We leave a bit
1519 * of space here in case the maximum values are raised. */
1520 void *pvBuf = NULL;
1521 uint32_t cbBuf = GUEST_PROP_MAX_NAME_LEN + GUEST_PROP_MAX_VALUE_LEN + GUEST_PROP_MAX_FLAGS_LEN + 1024;
1522 /* Because there is a race condition between our reading the size of a
1523 * property and the guest updating it, we loop a few times here and
1524 * hope. Actually this should never go wrong, as we are generous
1525 * enough with buffer space. */
1526 bool fFinished = false;
1527 for (unsigned i = 0; (RT_SUCCESS(rc) || rc == VERR_BUFFER_OVERFLOW) && !fFinished && i < 10; i++)
1528 {
1529 void *pvTmpBuf = RTMemRealloc(pvBuf, cbBuf);
1530 if (NULL == pvTmpBuf)
1531 {
1532 rc = VERR_NO_MEMORY;
1533 VBoxControlError("Out of memory\n");
1534 }
1535 else
1536 {
1537 pvBuf = pvTmpBuf;
1538 rc = VbglR3GuestPropWait(u32ClientId, pszPatterns, pvBuf, cbBuf,
1539 u64TimestampIn, u32Timeout,
1540 &pszName, &pszValue, &u64TimestampOut,
1541 &pszFlags, &cbBuf);
1542 }
1543 if (VERR_BUFFER_OVERFLOW == rc)
1544 /* Leave a bit of extra space to be safe */
1545 cbBuf += 1024;
1546 else
1547 fFinished = true;
1548 if (rc == VERR_TOO_MUCH_DATA)
1549 VBoxControlError("Temporarily unable to get a notification\n");
1550 else if (rc == VERR_INTERRUPTED)
1551 VBoxControlError("The request timed out or was interrupted\n");
1552#ifndef RT_OS_WINDOWS /* Windows guests do not do this right */
1553 else if (RT_FAILURE(rc) && rc != VERR_NOT_FOUND)
1554 VBoxControlError("Failed to get a notification, error %Rrc\n", rc);
1555#endif
1556 }
1557
1558 /*
1559 * And display it on the guest console.
1560 */
1561 if (VERR_NOT_FOUND == rc)
1562 RTPrintf("No value set!\n");
1563 else if (rc == VERR_BUFFER_OVERFLOW)
1564 RTPrintf("Internal error: unable to determine the size of the data!\n");
1565 else if (RT_SUCCESS(rc))
1566 {
1567 RTPrintf("Name: %s\n", pszName);
1568 RTPrintf("Value: %s\n", pszValue);
1569 RTPrintf("Timestamp: %lld ns\n", u64TimestampOut);
1570 RTPrintf("Flags: %s\n", pszFlags);
1571 }
1572
1573 if (u32ClientId != 0)
1574 VbglR3GuestPropDisconnect(u32ClientId);
1575 RTMemFree(pvBuf);
1576 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1577}
1578
1579
1580/**
1581 * Access the guest property store through the "VBoxGuestPropSvc" HGCM
1582 * service.
1583 *
1584 * @returns 0 on success, 1 on failure
1585 * @note see the command line API description for parameters
1586 */
1587static DECLCALLBACK(RTEXITCODE) handleGuestProperty(int argc, char *argv[])
1588{
1589 if (argc == 0)
1590 {
1591 usage(GUEST_PROP);
1592 return RTEXITCODE_FAILURE;
1593 }
1594 if (!strcmp(argv[0], "get"))
1595 return getGuestProperty(argc - 1, argv + 1);
1596 if (!strcmp(argv[0], "set"))
1597 return setGuestProperty(argc - 1, argv + 1);
1598 if (!strcmp(argv[0], "delete") || !strcmp(argv[0], "unset"))
1599 return deleteGuestProperty(argc - 1, argv + 1);
1600 if (!strcmp(argv[0], "enumerate"))
1601 return enumGuestProperty(argc - 1, argv + 1);
1602 if (!strcmp(argv[0], "wait"))
1603 return waitGuestProperty(argc - 1, argv + 1);
1604 /* unknown cmd */
1605 usage(GUEST_PROP);
1606 return RTEXITCODE_FAILURE;
1607}
1608
1609#endif
1610#ifdef VBOX_WITH_SHARED_FOLDERS
1611
1612/**
1613 * Lists the Shared Folders provided by the host.
1614 */
1615static RTEXITCODE sharedFolder_list(int argc, char **argv)
1616{
1617 bool fUsageOK = true;
1618 bool fOnlyShowAutoMount = false;
1619 if (argc == 1)
1620 {
1621 if (!strcmp(argv[0], "--automount"))
1622 fOnlyShowAutoMount = true;
1623 else
1624 fUsageOK = false;
1625 }
1626 else if (argc > 1)
1627 fUsageOK = false;
1628 if (!fUsageOK)
1629 {
1630 usage(GUEST_SHAREDFOLDERS);
1631 return RTEXITCODE_SYNTAX;
1632 }
1633
1634 uint32_t u32ClientId;
1635 int rc = VbglR3SharedFolderConnect(&u32ClientId);
1636 if (RT_FAILURE(rc))
1637 VBoxControlError("Failed to connect to the shared folder service, error %Rrc\n", rc);
1638 else
1639 {
1640 PVBGLR3SHAREDFOLDERMAPPING paMappings;
1641 uint32_t cMappings;
1642 rc = VbglR3SharedFolderGetMappings(u32ClientId, fOnlyShowAutoMount, &paMappings, &cMappings);
1643 if (RT_SUCCESS(rc))
1644 {
1645 if (fOnlyShowAutoMount)
1646 RTPrintf("Auto-mounted Shared Folder mappings (%u):\n\n", cMappings);
1647 else
1648 RTPrintf("Shared Folder mappings (%u):\n\n", cMappings);
1649
1650 for (uint32_t i = 0; i < cMappings; i++)
1651 {
1652 char *pszName;
1653 char *pszMntPt;
1654 uint64_t fFlags;
1655 uint32_t uRootIdVer;
1656 rc = VbglR3SharedFolderQueryFolderInfo(u32ClientId, paMappings[i].u32Root, 0,
1657 &pszName, &pszMntPt, &fFlags, &uRootIdVer);
1658 if (RT_SUCCESS(rc))
1659 {
1660 RTPrintf("%02u - %s [idRoot=%u", i + 1, pszName, paMappings[i].u32Root);
1661 if (fFlags & SHFL_MIF_WRITABLE)
1662 RTPrintf(" writable");
1663 else
1664 RTPrintf(" readonly");
1665 if (fFlags & SHFL_MIF_AUTO_MOUNT)
1666 RTPrintf(" auto-mount");
1667 if (fFlags & SHFL_MIF_SYMLINK_CREATION)
1668 RTPrintf(" create-symlink");
1669 if (fFlags & SHFL_MIF_HOST_ICASE)
1670 RTPrintf(" host-icase");
1671 if (fFlags & SHFL_MIF_GUEST_ICASE)
1672 RTPrintf(" guest-icase");
1673 if (*pszMntPt)
1674 RTPrintf(" mnt-pt=%s", pszMntPt);
1675 RTPrintf("]");
1676# ifdef RT_OS_OS2
1677 /* Show drive letters: */
1678 const char *pszOn = " on";
1679 for (char chDrive = 'A'; chDrive <= 'Z'; chDrive++)
1680 {
1681 char szDrive[4] = { chDrive, ':', '\0', '\0' };
1682 union
1683 {
1684 FSQBUFFER2 FsQueryBuf;
1685 char achPadding[512];
1686 } uBuf;
1687 RT_ZERO(uBuf);
1688 ULONG cbBuf = sizeof(uBuf) - 2;
1689 APIRET rcOs2 = DosQueryFSAttach(szDrive, 0, FSAIL_QUERYNAME, &uBuf.FsQueryBuf, &cbBuf);
1690 if (rcOs2 == NO_ERROR)
1691 {
1692 const char *pszFsdName = (const char *)&uBuf.FsQueryBuf.szName[uBuf.FsQueryBuf.cbName + 1];
1693 if ( uBuf.FsQueryBuf.iType == FSAT_REMOTEDRV
1694 && RTStrICmpAscii(pszFsdName, "VBOXSF") == 0)
1695 {
1696 const char *pszMountedName = (const char *)&pszFsdName[uBuf.FsQueryBuf.cbFSDName + 1];
1697 if (RTStrICmp(pszMountedName, pszName) == 0)
1698 {
1699 const char *pszTag = pszMountedName + strlen(pszMountedName) + 1; /* safe */
1700 if (*pszTag != '\0')
1701 RTPrintf("%s %s (%s)", pszOn, szDrive, pszTag);
1702 else
1703 RTPrintf("%s %s", pszOn, szDrive);
1704 pszOn = ",";
1705 }
1706 }
1707 }
1708 }
1709# endif
1710 RTPrintf("\n");
1711
1712 RTStrFree(pszName);
1713 RTStrFree(pszMntPt);
1714 }
1715 else
1716 VBoxControlError("Error while getting the shared folder name for root node = %u, rc = %Rrc\n",
1717 paMappings[i].u32Root, rc);
1718 }
1719 if (!cMappings)
1720 RTPrintf("No Shared Folders available.\n");
1721 VbglR3SharedFolderFreeMappings(paMappings);
1722 }
1723 else
1724 VBoxControlError("Error while getting the shared folder mappings, rc = %Rrc\n", rc);
1725 VbglR3SharedFolderDisconnect(u32ClientId);
1726 }
1727 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1728}
1729
1730# ifdef RT_OS_OS2
1731/**
1732 * Attaches a shared folder to a drive letter.
1733 */
1734static RTEXITCODE sharedFolder_use(int argc, char **argv)
1735{
1736 /*
1737 * Takes a drive letter and a share name as arguments.
1738 */
1739 if (argc != 2)
1740 return VBoxControlSyntaxError("sharedfolder use: expected a drive letter and a shared folder name\n");
1741
1742 const char *pszDrive = argv[0];
1743 if (!RT_C_IS_ALPHA(pszDrive[0]) || pszDrive[1] != ':' || pszDrive[2] != '\0')
1744 return VBoxControlSyntaxError("sharedfolder use: not a drive letter: %s\n", pszDrive);
1745
1746 static const char s_szTag[] = "VBoxControl";
1747 char szzNameAndTag[256];
1748 const char *pszName = argv[1];
1749 size_t cchName = strlen(pszName);
1750 if (cchName < 1)
1751 return VBoxControlSyntaxError("sharedfolder use: shared folder name cannot be empty!\n");
1752 if (cchName + 1 + sizeof(s_szTag) >= sizeof(szzNameAndTag))
1753 return VBoxControlSyntaxError("sharedfolder use: shared folder name is too long! (%s)\n", pszName);
1754
1755 /*
1756 * Do the attaching.
1757 */
1758 memcpy(szzNameAndTag, pszName, cchName);
1759 szzNameAndTag[cchName] = '\0';
1760 memcpy(&szzNameAndTag[cchName + 1], s_szTag, sizeof(s_szTag));
1761
1762 APIRET rcOs2 = DosFSAttach(pszDrive, "VBOXSF", szzNameAndTag, cchName + 1 + sizeof(s_szTag), FS_ATTACH);
1763 if (rcOs2 == NO_ERROR)
1764 return RTEXITCODE_SUCCESS;
1765 if (rcOs2 == ERROR_INVALID_FSD_NAME)
1766 return VBoxControlError("Shared folders IFS not installed?\n");
1767 return VBoxControlError("DosFSAttach/FS_ATTACH failed to attach '%s' to '%s': %u\n", pszName, pszDrive, rcOs2);
1768}
1769
1770/**
1771 * Detaches a shared folder from a drive letter.
1772 */
1773static RTEXITCODE sharedFolder_unuse(int argc, char **argv)
1774{
1775 /*
1776 * Only takes a drive letter as argument.
1777 */
1778 if (argc != 1)
1779 return VBoxControlSyntaxError("sharedfolder unuse: expected drive letter\n");
1780 const char *pszDrive = argv[0];
1781 if (!RT_C_IS_ALPHA(pszDrive[0]) || pszDrive[1] != ':' || pszDrive[2] != '\0')
1782 return VBoxControlSyntaxError("sharedfolder unuse: not a drive letter: %s\n", pszDrive);
1783
1784 /*
1785 * Do the detaching.
1786 */
1787 APIRET rcOs2 = DosFSAttach(pszDrive, "VBOXSF", NULL, 0, FS_DETACH);
1788 if (rcOs2 == NO_ERROR)
1789 return RTEXITCODE_SUCCESS;
1790 return VBoxControlError("DosFSAttach/FS_DETACH failed on '%s': %u\n", pszDrive, rcOs2);
1791}
1792
1793# endif /* RT_OS_OS2 */
1794
1795
1796/**
1797 * Handles Shared Folders control.
1798 *
1799 * @returns 0 on success, 1 on failure
1800 * @note see the command line API description for parameters
1801 * (r=bird: yeah, right. The API description contains nil about params)
1802 */
1803static DECLCALLBACK(RTEXITCODE) handleSharedFolder(int argc, char *argv[])
1804{
1805 if (argc == 0)
1806 {
1807 usage(GUEST_SHAREDFOLDERS);
1808 return RTEXITCODE_FAILURE;
1809 }
1810 if (!strcmp(argv[0], "list"))
1811 return sharedFolder_list(argc - 1, argv + 1);
1812# ifdef RT_OS_OS2
1813 if (!strcmp(argv[0], "use"))
1814 return sharedFolder_use(argc - 1, argv + 1);
1815 if (!strcmp(argv[0], "unuse"))
1816 return sharedFolder_unuse(argc - 1, argv + 1);
1817# endif
1818
1819 usage(GUEST_SHAREDFOLDERS);
1820 return RTEXITCODE_FAILURE;
1821}
1822
1823#endif
1824#if !defined(VBOX_CONTROL_TEST)
1825
1826/**
1827 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: writecoredump}
1828 */
1829static DECLCALLBACK(RTEXITCODE) handleWriteCoreDump(int argc, char *argv[])
1830{
1831 RT_NOREF2(argc, argv);
1832 int rc = VbglR3WriteCoreDump();
1833 if (RT_SUCCESS(rc))
1834 {
1835 RTPrintf("Guest core dump successful.\n");
1836 return RTEXITCODE_SUCCESS;
1837 }
1838 else
1839 {
1840 VBoxControlError("Error while taking guest core dump. rc=%Rrc\n", rc);
1841 return RTEXITCODE_FAILURE;
1842 }
1843}
1844
1845#endif
1846#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
1847
1848/**
1849 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: help}
1850 */
1851static DECLCALLBACK(RTEXITCODE) handleDpc(int argc, char *argv[])
1852{
1853 RT_NOREF(argc, argv);
1854 int rc = VERR_NOT_IMPLEMENTED;
1855# ifndef VBOX_CONTROL_TEST
1856 for (int i = 0; i < 30; i++)
1857 {
1858 VBGLREQHDR Req;
1859 VBGLREQHDR_INIT(&Req, DPC_LATENCY_CHECKER);
1860 rc = vbglR3DoIOCtl(VBGL_IOCTL_DPC_LATENCY_CHECKER, &Req, sizeof(Req));
1861 if (RT_SUCCESS(rc))
1862 RTPrintf("%d\n", i);
1863 else
1864 break;
1865 }
1866# endif
1867 if (RT_FAILURE(rc))
1868 return VBoxControlError("Error. rc=%Rrc\n", rc);
1869 RTPrintf("Samples collection completed.\n");
1870 return RTEXITCODE_SUCCESS;
1871}
1872#endif /* VBOX_WITH_DPC_LATENCY_CHECKER */
1873
1874
1875/**
1876 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: writelog}
1877 */
1878static DECLCALLBACK(RTEXITCODE) handleWriteLog(int argc, char *argv[])
1879{
1880 static const RTGETOPTDEF s_aOptions[] =
1881 {
1882 { "--no-newline", 'n', RTGETOPT_REQ_NOTHING },
1883 };
1884 bool fNoNewline = false;
1885
1886 RTGETOPTSTATE GetOptState;
1887 int rc = RTGetOptInit(&GetOptState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions),
1888 0 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1889 if (RT_SUCCESS(rc))
1890 {
1891 RTGETOPTUNION ValueUnion;
1892 int ch;
1893 while ((ch = RTGetOpt(&GetOptState, &ValueUnion)) != 0)
1894 {
1895 switch (ch)
1896 {
1897 case VINF_GETOPT_NOT_OPTION:
1898 {
1899 size_t cch = strlen(ValueUnion.psz);
1900 if ( fNoNewline
1901 || (cch > 0 && ValueUnion.psz[cch - 1] == '\n') )
1902 rc = VbglR3WriteLog(ValueUnion.psz, cch);
1903 else
1904 {
1905 char *pszDup = (char *)RTMemDupEx(ValueUnion.psz, cch, 2);
1906 if (RT_SUCCESS(rc))
1907 {
1908 pszDup[cch++] = '\n';
1909 pszDup[cch] = '\0';
1910 rc = VbglR3WriteLog(pszDup, cch);
1911 RTMemFree(pszDup);
1912 }
1913 else
1914 rc = VERR_NO_MEMORY;
1915 }
1916 if (RT_FAILURE(rc))
1917 return VBoxControlError("VbglR3WriteLog: %Rrc", rc);
1918 break;
1919 }
1920
1921 case 'n':
1922 fNoNewline = true;
1923 break;
1924
1925 case 'h': return usage(WRITE_LOG);
1926 case 'V': return printVersion();
1927 default:
1928 return VBoxCtrlGetOptError(ch, &ValueUnion);
1929 }
1930 }
1931 }
1932 else
1933 return VBoxControlError("RTGetOptInit: %Rrc", rc);
1934 return RTEXITCODE_SUCCESS;
1935}
1936
1937
1938/**
1939 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: takesnapshot}
1940 */
1941static DECLCALLBACK(RTEXITCODE) handleTakeSnapshot(int argc, char *argv[])
1942{
1943 RT_NOREF2(argc, argv); //VbglR3VmTakeSnapshot(argv[0], argv[1]);
1944 return VBoxControlError("not implemented");
1945}
1946
1947/**
1948 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: savestate}
1949 */
1950static DECLCALLBACK(RTEXITCODE) handleSaveState(int argc, char *argv[])
1951{
1952 RT_NOREF2(argc, argv); //VbglR3VmSaveState();
1953 return VBoxControlError("not implemented");
1954}
1955
1956/**
1957 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: suspend|pause}
1958 */
1959static DECLCALLBACK(RTEXITCODE) handleSuspend(int argc, char *argv[])
1960{
1961 RT_NOREF2(argc, argv); //VbglR3VmSuspend();
1962 return VBoxControlError("not implemented");
1963}
1964
1965/**
1966 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: poweroff|powerdown}
1967 */
1968static DECLCALLBACK(RTEXITCODE) handlePowerOff(int argc, char *argv[])
1969{
1970 RT_NOREF2(argc, argv); //VbglR3VmPowerOff();
1971 return VBoxControlError("not implemented");
1972}
1973
1974/**
1975 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: version}
1976 */
1977static DECLCALLBACK(RTEXITCODE) handleVersion(int argc, char *argv[])
1978{
1979 RT_NOREF1(argv);
1980 if (argc)
1981 return VBoxControlSyntaxError("getversion does not take any arguments");
1982 return printVersion();
1983}
1984
1985/**
1986 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: help}
1987 */
1988static DECLCALLBACK(RTEXITCODE) handleHelp(int argc, char *argv[])
1989{
1990 RT_NOREF2(argc, argv); /* ignore arguments for now. */
1991 usage();
1992 return RTEXITCODE_SUCCESS;
1993}
1994
1995/**
1996 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: ls}
1997 */
1998static DECLCALLBACK(RTEXITCODE) handleLs(int argc, char *argv[])
1999{
2000 return RTFsCmdLs(argc + 1, argv - 1);
2001}
2002
2003/**
2004 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: tar}
2005 */
2006static DECLCALLBACK(RTEXITCODE) handleTar(int argc, char *argv[])
2007{
2008 return RTZipTarCmd(argc + 1, argv - 1);
2009}
2010
2011/**
2012 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: tar}
2013 */
2014static DECLCALLBACK(RTEXITCODE) handleGzip(int argc, char *argv[])
2015{
2016 return RTZipGzipCmd(argc + 1, argv - 1);
2017}
2018
2019/**
2020 * @callback_method_impl{FNVBOXCTRLCMDHANDLER, Command: unzip}
2021 */
2022static DECLCALLBACK(RTEXITCODE) handleUnzip(int argc, char *argv[])
2023{
2024 return RTZipUnzipCmd(argc + 1, argv - 1);
2025}
2026
2027
2028/** command handler type */
2029typedef DECLCALLBACK(RTEXITCODE) FNVBOXCTRLCMDHANDLER(int argc, char *argv[]);
2030typedef FNVBOXCTRLCMDHANDLER *PFNVBOXCTRLCMDHANDLER;
2031
2032/** The table of all registered command handlers. */
2033struct COMMANDHANDLER
2034{
2035 const char *pszCommand;
2036 PFNVBOXCTRLCMDHANDLER pfnHandler;
2037 bool fNeedDevice;
2038} g_aCommandHandlers[] =
2039{
2040#if defined(RT_OS_WINDOWS) && !defined(VBOX_CONTROL_TEST)
2041 { "getvideoacceleration", handleGetVideoAcceleration, true },
2042 { "setvideoacceleration", handleSetVideoAcceleration, true },
2043 { "videoflags", handleVideoFlags, true },
2044 { "listcustommodes", handleListCustomModes, true },
2045 { "addcustommode", handleAddCustomMode, true },
2046 { "removecustommode", handleRemoveCustomMode, true },
2047 { "setvideomode", handleSetVideoMode, true },
2048#endif
2049#ifdef VBOX_WITH_GUEST_PROPS
2050 { "guestproperty", handleGuestProperty, true },
2051#endif
2052#ifdef VBOX_WITH_SHARED_FOLDERS
2053 { "sharedfolder", handleSharedFolder, true },
2054#endif
2055#if !defined(VBOX_CONTROL_TEST)
2056 { "writecoredump", handleWriteCoreDump, true },
2057#endif
2058#ifdef VBOX_WITH_DPC_LATENCY_CHECKER
2059 { "dpc", handleDpc, true },
2060#endif
2061 { "writelog", handleWriteLog, true },
2062 { "takesnapshot", handleTakeSnapshot, true },
2063 { "savestate", handleSaveState, true },
2064 { "suspend", handleSuspend, true },
2065 { "pause", handleSuspend, true },
2066 { "poweroff", handlePowerOff, true },
2067 { "powerdown", handlePowerOff, true },
2068 { "getversion", handleVersion, false },
2069 { "version", handleVersion, false },
2070 { "help", handleHelp, false },
2071 /* Hany tricks that doesn't cost much space: */
2072 { "gzip", handleGzip, false },
2073 { "ls", handleLs, false },
2074 { "tar", handleTar, false },
2075 { "unzip", handleUnzip, false },
2076};
2077
2078/** Main function */
2079int main(int argc, char **argv)
2080{
2081 /** The application's global return code */
2082 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2083 /** An IPRT return code for local use */
2084 int rrc = VINF_SUCCESS;
2085 /** The index of the command line argument we are currently processing */
2086 int iArg = 1;
2087 /** Should we show the logo text? */
2088 bool fShowLogo = true;
2089 /** Should we print the usage after the logo? For the -help switch. */
2090 bool fDoHelp = false;
2091 /** Will we be executing a command or just printing information? */
2092 bool fOnlyInfo = false;
2093
2094 rrc = RTR3InitExe(argc, &argv, 0);
2095 if (RT_FAILURE(rrc))
2096 return RTMsgInitFailure(rrc);
2097
2098 /*
2099 * Start by handling command line switches
2100 */
2101 /** @todo RTGetOpt conversion of the whole file. */
2102 bool done = false; /**< Are we finished with handling switches? */
2103 while (!done && (iArg < argc))
2104 {
2105 if ( !strcmp(argv[iArg], "-V")
2106 || !strcmp(argv[iArg], "-v")
2107 || !strcmp(argv[iArg], "--version")
2108 || !strcmp(argv[iArg], "-version")
2109 )
2110 {
2111 /* Print version number, and do nothing else. */
2112 printVersion();
2113 fOnlyInfo = true;
2114 fShowLogo = false;
2115 done = true;
2116 }
2117 else if ( !strcmp(argv[iArg], "-nologo")
2118 || !strcmp(argv[iArg], "--nologo"))
2119 fShowLogo = false;
2120 else if ( !strcmp(argv[iArg], "-help")
2121 || !strcmp(argv[iArg], "--help"))
2122 {
2123 fOnlyInfo = true;
2124 fDoHelp = true;
2125 done = true;
2126 }
2127 else
2128 /* We have found an argument which isn't a switch. Exit to the
2129 * command processing bit. */
2130 done = true;
2131 if (!done)
2132 ++iArg;
2133 }
2134
2135 /*
2136 * Find the application name, show our logo if the user hasn't suppressed it,
2137 * and show the usage if the user asked us to
2138 */
2139 g_pszProgName = RTPathFilename(argv[0]);
2140 if (fShowLogo)
2141 RTPrintf(VBOX_PRODUCT " Guest Additions Command Line Management Interface Version "
2142 VBOX_VERSION_STRING "\n"
2143 "(C) 2008-" VBOX_C_YEAR " " VBOX_VENDOR "\n"
2144 "All rights reserved.\n\n");
2145 if (fDoHelp)
2146 usage();
2147
2148 /*
2149 * Now look for an actual command in the argument list and handle it.
2150 */
2151 if (!fOnlyInfo && rcExit == RTEXITCODE_SUCCESS)
2152 {
2153 if (argc > iArg)
2154 {
2155 /*
2156 * Try locate the command and execute it, complain if not found.
2157 */
2158 unsigned i;
2159 for (i = 0; i < RT_ELEMENTS(g_aCommandHandlers); i++)
2160 if (!strcmp(argv[iArg], g_aCommandHandlers[i].pszCommand))
2161 {
2162 if (g_aCommandHandlers[i].fNeedDevice)
2163 {
2164 rrc = VbglR3Init();
2165 if (RT_FAILURE(rrc))
2166 {
2167 VBoxControlError("Could not contact the host system. Make sure that you are running this\n"
2168 "application inside a VirtualBox guest system, and that you have sufficient\n"
2169 "user permissions.\n");
2170 rcExit = RTEXITCODE_FAILURE;
2171 }
2172 }
2173 if (rcExit == RTEXITCODE_SUCCESS)
2174 rcExit = g_aCommandHandlers[i].pfnHandler(argc - iArg - 1, argv + iArg + 1);
2175 break;
2176 }
2177 if (i >= RT_ELEMENTS(g_aCommandHandlers))
2178 {
2179 usage();
2180 rcExit = RTEXITCODE_SYNTAX;
2181 }
2182 }
2183 else
2184 {
2185 /* The user didn't specify a command. */
2186 usage();
2187 rcExit = RTEXITCODE_SYNTAX;
2188 }
2189 }
2190
2191 /*
2192 * And exit, returning the status
2193 */
2194 return rcExit;
2195}
2196
Note: See TracBrowser for help on using the repository browser.

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