summaryrefslogtreecommitdiff
path: root/src/VBox/Frontends/VBoxManage/VBoxManageGuestCtrl.cpp
blob: ced18c1b0fe526e97acdde5ebc03f2962b5e8f1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
/* $Id: VBoxManageGuestCtrl.cpp $ */
/** @file
 * VBoxManage - Implementation of guestcontrol command.
 */

/*
 * Copyright (C) 2010-2013 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */


/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include "VBoxManage.h"
#include "VBoxManageGuestCtrl.h"

#ifndef VBOX_ONLY_DOCS

#include <VBox/com/array.h>
#include <VBox/com/com.h>
#include <VBox/com/ErrorInfo.h>
#include <VBox/com/errorprint.h>
#include <VBox/com/listeners.h>
#include <VBox/com/NativeEventQueue.h>
#include <VBox/com/string.h>
#include <VBox/com/VirtualBox.h>

#include <VBox/err.h>
#include <VBox/log.h>

#include <iprt/asm.h>
#include <iprt/dir.h>
#include <iprt/file.h>
#include <iprt/isofs.h>
#include <iprt/getopt.h>
#include <iprt/list.h>
#include <iprt/path.h>
#include <iprt/process.h> /* For RTProcSelf(). */
#include <iprt/thread.h>

#include <map>
#include <vector>

#ifdef USE_XPCOM_QUEUE
# include <sys/select.h>
# include <errno.h>
#endif

#include <signal.h>

#ifdef RT_OS_DARWIN
# include <CoreFoundation/CFRunLoop.h>
#endif

using namespace com;

/** Set by the signal handler when current guest control
 *  action shall be aborted. */
static volatile bool g_fGuestCtrlCanceled = false;

/**
 * Listener declarations.
 */
VBOX_LISTENER_DECLARE(GuestFileEventListenerImpl)
VBOX_LISTENER_DECLARE(GuestProcessEventListenerImpl)
VBOX_LISTENER_DECLARE(GuestSessionEventListenerImpl)
VBOX_LISTENER_DECLARE(GuestEventListenerImpl)

/**
 * Command context flags.
 */
/** No flags set. */
#define CTLCMDCTX_FLAGS_NONE                0
/** Don't install a signal handler (CTRL+C trap). */
#define CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER   RT_BIT(0)
/** No guest session needed. */
#define CTLCMDCTX_FLAGS_SESSION_ANONYMOUS   RT_BIT(1)
/** Detach the guest session. That is, don't close the
 *  guest session automatically on exit. */
#define CTLCMDCTX_FLAGS_SESSION_DETACH      RT_BIT(2)

/**
 * Context for handling a specific command.
 */
typedef struct GCTLCMDCTX
{
    HandlerArg handlerArg;
    /** Command-specific argument count. */
    int iArgc;
    /** Command-specific argument vector. */
    char **ppaArgv;
    /** First argv to start parsing with. */
    int iFirstArgc;
    /** Command context flags. */
    uint32_t uFlags;
    /** Verbose flag. */
    bool fVerbose;
    /** User name. */
    Utf8Str strUsername;
    /** Password. */
    Utf8Str strPassword;
    /** Domain. */
    Utf8Str strDomain;
    /** Pointer to the IGuest interface. */
    ComPtr<IGuest> pGuest;
    /** Pointer to the to be used guest session. */
    ComPtr<IGuestSession> pGuestSession;
    /** The guest session ID. */
    ULONG uSessionID;

} GCTLCMDCTX, *PGCTLCMDCTX;

typedef struct GCTLCMD
{
    /**
     * Actual command handler callback.
     *
     * @param   pCtx            Pointer to command context to use.
     */
    DECLR3CALLBACKMEMBER(RTEXITCODE, pfnHandler, (PGCTLCMDCTX pCtx));

} GCTLCMD, *PGCTLCMD;

typedef struct COPYCONTEXT
{
    COPYCONTEXT()
        : fDryRun(false),
          fHostToGuest(false)
    {
    }

    PGCTLCMDCTX pCmdCtx;
    bool fDryRun;
    bool fHostToGuest;

} COPYCONTEXT, *PCOPYCONTEXT;

/**
 * An entry for a source element, including an optional DOS-like wildcard (*,?).
 */
class SOURCEFILEENTRY
{
    public:

        SOURCEFILEENTRY(const char *pszSource, const char *pszFilter)
                        : mSource(pszSource),
                          mFilter(pszFilter) {}

        SOURCEFILEENTRY(const char *pszSource)
                        : mSource(pszSource)
        {
            Parse(pszSource);
        }

        const char* GetSource() const
        {
            return mSource.c_str();
        }

        const char* GetFilter() const
        {
            return mFilter.c_str();
        }

    private:

        int Parse(const char *pszPath)
        {
            AssertPtrReturn(pszPath, VERR_INVALID_POINTER);

            if (   !RTFileExists(pszPath)
                && !RTDirExists(pszPath))
            {
                /* No file and no directory -- maybe a filter? */
                char *pszFilename = RTPathFilename(pszPath);
                if (   pszFilename
                    && strpbrk(pszFilename, "*?"))
                {
                    /* Yep, get the actual filter part. */
                    mFilter = RTPathFilename(pszPath);
                    /* Remove the filter from actual sourcec directory name. */
                    RTPathStripFilename(mSource.mutableRaw());
                    mSource.jolt();
                }
            }

            return VINF_SUCCESS; /* @todo */
        }

    private:

        Utf8Str mSource;
        Utf8Str mFilter;
};
typedef std::vector<SOURCEFILEENTRY> SOURCEVEC, *PSOURCEVEC;

/**
 * An entry for an element which needs to be copied/created to/on the guest.
 */
typedef struct DESTFILEENTRY
{
    DESTFILEENTRY(Utf8Str strFileName) : mFileName(strFileName) {}
    Utf8Str mFileName;
} DESTFILEENTRY, *PDESTFILEENTRY;
/*
 * Map for holding destination entires, whereas the key is the destination
 * directory and the mapped value is a vector holding all elements for this directoy.
 */
typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> > DESTDIRMAP, *PDESTDIRMAP;
typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> >::iterator DESTDIRMAPITER, *PDESTDIRMAPITER;

/**
 * Special exit codes for returning errors/information of a
 * started guest process to the command line VBoxManage was started from.
 * Useful for e.g. scripting.
 *
 * @note    These are frozen as of 4.1.0.
 */
enum EXITCODEEXEC
{
    EXITCODEEXEC_SUCCESS        = RTEXITCODE_SUCCESS,
    /* Process exited normally but with an exit code <> 0. */
    EXITCODEEXEC_CODE           = 16,
    EXITCODEEXEC_FAILED         = 17,
    EXITCODEEXEC_TERM_SIGNAL    = 18,
    EXITCODEEXEC_TERM_ABEND     = 19,
    EXITCODEEXEC_TIMEOUT        = 20,
    EXITCODEEXEC_DOWN           = 21,
    EXITCODEEXEC_CANCELED       = 22
};

/*
 * Common getopt definitions, starting at 1000.
 * Specific command definitions will start all at 2000.
 */
enum GETOPTDEF_COMMON
{
    GETOPTDEF_COMMON_PASSWORD = 1000
};

/**
 * RTGetOpt-IDs for the guest execution control command line.
 */
enum GETOPTDEF_EXEC
{
    GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES = 1000,
    GETOPTDEF_EXEC_NO_PROFILE,
    GETOPTDEF_EXEC_OUTPUTFORMAT,
    GETOPTDEF_EXEC_DOS2UNIX,
    GETOPTDEF_EXEC_UNIX2DOS,
    GETOPTDEF_EXEC_WAITFOREXIT,
    GETOPTDEF_EXEC_WAITFORSTDOUT,
    GETOPTDEF_EXEC_WAITFORSTDERR
};

enum GETOPTDEF_COPY
{
    GETOPTDEF_COPY_DRYRUN = 1000,
    GETOPTDEF_COPY_FOLLOW,
    GETOPTDEF_COPY_TARGETDIR
};

enum GETOPTDEF_MKDIR
{
};

enum GETOPTDEF_RM
{
};

enum GETOPTDEF_RMDIR
{
};

enum GETOPTDEF_SESSIONCLOSE
{
    GETOPTDEF_SESSIONCLOSE_ALL = 2000
};

enum GETOPTDEF_STAT
{
};

enum OUTPUTTYPE
{
    OUTPUTTYPE_UNDEFINED = 0,
    OUTPUTTYPE_DOS2UNIX  = 10,
    OUTPUTTYPE_UNIX2DOS  = 20
};

static int ctrlCopyDirExists(PCOPYCONTEXT pContext, bool bGuest, const char *pszDir, bool *fExists);

#endif /* VBOX_ONLY_DOCS */

void usageGuestControl(PRTSTREAM pStrm, const char *pcszSep1, const char *pcszSep2, uint32_t uSubCmd)
{
    RTStrmPrintf(pStrm,
                       "%s guestcontrol %s    <uuid|vmname>\n%s",
                 pcszSep1, pcszSep2,
                 uSubCmd == ~0U ? "\n" : "");
    if (uSubCmd & USAGE_GSTCTRL_EXEC)
        RTStrmPrintf(pStrm,
                 "                              exec[ute]\n"
                 "                              --image <path to program> --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose] [--timeout <msec>]\n"
                 "                              [--environment \"<NAME>=<VALUE> [<NAME>=<VALUE>]\"]\n"
                 "                              [--wait-exit] [--wait-stdout] [--wait-stderr]\n"
                 "                              [--dos2unix] [--unix2dos]\n"
                 "                              [-- [<argument1>] ... [<argumentN>]]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_COPYFROM)
        RTStrmPrintf(pStrm,
                 "                              copyfrom\n"
                 "                              <guest source> <host dest> --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "                              [--dryrun] [--follow] [--recursive]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_COPYTO)
        RTStrmPrintf(pStrm,
                 "                              copyto|cp\n"
                 "                              <host source> <guest dest> --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "                              [--dryrun] [--follow] [--recursive]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_CREATEDIR)
        RTStrmPrintf(pStrm,
                 "                              createdir[ectory]|mkdir|md\n"
                 "                              <guest directory>... --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "                              [--parents] [--mode <mode>]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_REMOVEDIR)
        RTStrmPrintf(pStrm,
                 "                              removedir[ectory]|rmdir\n"
                 "                              <guest directory>... --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "                              [--recursive|-R|-r]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_REMOVEFILE)
        RTStrmPrintf(pStrm,
                 "                              removefile|rm\n"
                 "                              <guest file>... --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_RENAME)
        RTStrmPrintf(pStrm,
                 "                              ren[ame]|mv\n"
                 "                              <source>... <dest> --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_CREATETEMP)
        RTStrmPrintf(pStrm,
                 "                              createtemp[orary]|mktemp\n"
                 "                              <template> --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--directory] [--secure] [--tmpdir <directory>]\n"
                 "                              [--domain <domain>] [--mode <mode>] [--verbose]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_LIST)
        RTStrmPrintf(pStrm,
                 "                              list <all|sessions|processes|files> [--verbose]\n"
                 "\n");
    /** @todo Add an own help group for "session" and "process" sub commands. */
    if (uSubCmd & USAGE_GSTCTRL_PROCESS)
         RTStrmPrintf(pStrm,
                 "                              process kill --session-id <ID>\n"
                 "                                           | --session-name <name or pattern>\n"
                 "                                           [--verbose]\n"
                 "                                           <PID> ... <PID n>\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_KILL)
        RTStrmPrintf(pStrm,
                 "                              [p[s]]kill --session-id <ID>\n"
                 "                                         | --session-name <name or pattern>\n"
                 "                                         [--verbose]\n"
                 "                                         <PID> ... <PID n>\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_SESSION)
        RTStrmPrintf(pStrm,
                 "                              session close  --session-id <ID>\n"
                 "                                           | --session-name <name or pattern>\n"
                 "                                           | --all\n"
                 "                                           [--verbose]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_STAT)
        RTStrmPrintf(pStrm,
                 "                              stat\n"
                 "                              <file>... --username <name>\n"
                 "                              [--passwordfile <file> | --password <password>]\n"
                 "                              [--domain <domain>] [--verbose]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_UPDATEADDS)
        RTStrmPrintf(pStrm,
                 "                              updateadditions\n"
                 "                              [--source <guest additions .ISO>] [--verbose]\n"
                 "                              [--wait-start]\n"
                 "                              [-- [<argument1>] ... [<argumentN>]]\n"
                 "\n");
    if (uSubCmd & USAGE_GSTCTRL_WATCH)
        RTStrmPrintf(pStrm,
                 "                              watch [--verbose]\n"
                 "\n");
}

#ifndef VBOX_ONLY_DOCS

#ifdef RT_OS_WINDOWS
static BOOL WINAPI guestCtrlSignalHandler(DWORD dwCtrlType)
{
    bool fEventHandled = FALSE;
    switch (dwCtrlType)
    {
        /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
         * via GenerateConsoleCtrlEvent(). */
        case CTRL_BREAK_EVENT:
        case CTRL_CLOSE_EVENT:
        case CTRL_C_EVENT:
            ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
            fEventHandled = TRUE;
            break;
        default:
            break;
        /** @todo Add other events here. */
    }

    return fEventHandled;
}
#else /* !RT_OS_WINDOWS */
/**
 * Signal handler that sets g_fGuestCtrlCanceled.
 *
 * This can be executed on any thread in the process, on Windows it may even be
 * a thread dedicated to delivering this signal.  Don't do anything
 * unnecessary here.
 */
static void guestCtrlSignalHandler(int iSignal)
{
    NOREF(iSignal);
    ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
}
#endif

/**
 * Installs a custom signal handler to get notified
 * whenever the user wants to intercept the program.
 *
 ** @todo Make this handler available for all VBoxManage modules?
 */
static int ctrlSignalHandlerInstall(void)
{
    int rc = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
    if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)guestCtrlSignalHandler, TRUE /* Add handler */))
    {
        rc = RTErrConvertFromWin32(GetLastError());
        RTMsgError("Unable to install console control handler, rc=%Rrc\n", rc);
    }
#else
    signal(SIGINT,   guestCtrlSignalHandler);
# ifdef SIGBREAK
    signal(SIGBREAK, guestCtrlSignalHandler);
# endif
#endif
    return rc;
}

/**
 * Uninstalls a previously installed signal handler.
 */
static int ctrlSignalHandlerUninstall(void)
{
    int rc = VINF_SUCCESS;
#ifdef RT_OS_WINDOWS
    if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
    {
        rc = RTErrConvertFromWin32(GetLastError());
        RTMsgError("Unable to uninstall console control handler, rc=%Rrc\n", rc);
    }
#else
    signal(SIGINT,   SIG_DFL);
# ifdef SIGBREAK
    signal(SIGBREAK, SIG_DFL);
# endif
#endif
    return rc;
}

/**
 * Translates a process status to a human readable
 * string.
 */
const char *ctrlProcessStatusToText(ProcessStatus_T enmStatus)
{
    switch (enmStatus)
    {
        case ProcessStatus_Starting:
            return "starting";
        case ProcessStatus_Started:
            return "started";
        case ProcessStatus_Paused:
            return "paused";
        case ProcessStatus_Terminating:
            return "terminating";
        case ProcessStatus_TerminatedNormally:
            return "successfully terminated";
        case ProcessStatus_TerminatedSignal:
            return "terminated by signal";
        case ProcessStatus_TerminatedAbnormally:
            return "abnormally aborted";
        case ProcessStatus_TimedOutKilled:
            return "timed out";
        case ProcessStatus_TimedOutAbnormally:
            return "timed out, hanging";
        case ProcessStatus_Down:
            return "killed";
        case ProcessStatus_Error:
            return "error";
        default:
            break;
    }
    return "unknown";
}

static int ctrlExecProcessStatusToExitCode(ProcessStatus_T enmStatus, ULONG uExitCode)
{
    int vrc = EXITCODEEXEC_SUCCESS;
    switch (enmStatus)
    {
        case ProcessStatus_Starting:
            vrc = EXITCODEEXEC_SUCCESS;
            break;
        case ProcessStatus_Started:
            vrc = EXITCODEEXEC_SUCCESS;
            break;
        case ProcessStatus_Paused:
            vrc = EXITCODEEXEC_SUCCESS;
            break;
        case ProcessStatus_Terminating:
            vrc = EXITCODEEXEC_SUCCESS;
            break;
        case ProcessStatus_TerminatedNormally:
            vrc = !uExitCode ? EXITCODEEXEC_SUCCESS : EXITCODEEXEC_CODE;
            break;
        case ProcessStatus_TerminatedSignal:
            vrc = EXITCODEEXEC_TERM_SIGNAL;
            break;
        case ProcessStatus_TerminatedAbnormally:
            vrc = EXITCODEEXEC_TERM_ABEND;
            break;
        case ProcessStatus_TimedOutKilled:
            vrc = EXITCODEEXEC_TIMEOUT;
            break;
        case ProcessStatus_TimedOutAbnormally:
            vrc = EXITCODEEXEC_TIMEOUT;
            break;
        case ProcessStatus_Down:
            /* Service/OS is stopping, process was killed, so
             * not exactly an error of the started process ... */
            vrc = EXITCODEEXEC_DOWN;
            break;
        case ProcessStatus_Error:
            vrc = EXITCODEEXEC_FAILED;
            break;
        default:
            AssertMsgFailed(("Unknown exit code (%u) from guest process returned!\n", enmStatus));
            break;
    }
    return vrc;
}

const char *ctrlProcessWaitResultToText(ProcessWaitResult_T enmWaitResult)
{
    switch (enmWaitResult)
    {
        case ProcessWaitResult_Start:
            return "started";
        case ProcessWaitResult_Terminate:
            return "terminated";
        case ProcessWaitResult_Status:
            return "status changed";
        case ProcessWaitResult_Error:
            return "error";
        case ProcessWaitResult_Timeout:
            return "timed out";
        case ProcessWaitResult_StdIn:
            return "stdin ready";
        case ProcessWaitResult_StdOut:
            return "data on stdout";
        case ProcessWaitResult_StdErr:
            return "data on stderr";
        case ProcessWaitResult_WaitFlagNotSupported:
            return "waiting flag not supported";
        default:
            break;
    }
    return "unknown";
}

/**
 * Translates a guest session status to a human readable
 * string.
 */
const char *ctrlSessionStatusToText(GuestSessionStatus_T enmStatus)
{
    switch (enmStatus)
    {
        case GuestSessionStatus_Starting:
            return "starting";
        case GuestSessionStatus_Started:
            return "started";
        case GuestSessionStatus_Terminating:
            return "terminating";
        case GuestSessionStatus_Terminated:
            return "terminated";
        case GuestSessionStatus_TimedOutKilled:
            return "timed out";
        case GuestSessionStatus_TimedOutAbnormally:
            return "timed out, hanging";
        case GuestSessionStatus_Down:
            return "killed";
        case GuestSessionStatus_Error:
            return "error";
        default:
            break;
    }
    return "unknown";
}

/**
 * Translates a guest file status to a human readable
 * string.
 */
const char *ctrlFileStatusToText(FileStatus_T enmStatus)
{
    switch (enmStatus)
    {
        case FileStatus_Opening:
            return "opening";
        case FileStatus_Open:
            return "open";
        case FileStatus_Closing:
            return "closing";
        case FileStatus_Closed:
            return "closed";
        case FileStatus_Down:
            return "killed";
        case FileStatus_Error:
            return "error";
        default:
            break;
    }
    return "unknown";
}

static int ctrlPrintError(com::ErrorInfo &errorInfo)
{
    if (   errorInfo.isFullAvailable()
        || errorInfo.isBasicAvailable())
    {
        /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
         * because it contains more accurate info about what went wrong. */
        if (errorInfo.getResultCode() == VBOX_E_IPRT_ERROR)
            RTMsgError("%ls.", errorInfo.getText().raw());
        else
        {
            RTMsgError("Error details:");
            GluePrintErrorInfo(errorInfo);
        }
        return VERR_GENERAL_FAILURE; /** @todo */
    }
    AssertMsgFailedReturn(("Object has indicated no error (%Rhrc)!?\n", errorInfo.getResultCode()),
                          VERR_INVALID_PARAMETER);
}

static int ctrlPrintError(IUnknown *pObj, const GUID &aIID)
{
    com::ErrorInfo ErrInfo(pObj, aIID);
    return ctrlPrintError(ErrInfo);
}

static int ctrlPrintProgressError(ComPtr<IProgress> pProgress)
{
    int vrc = VINF_SUCCESS;
    HRESULT rc;

    do
    {
        BOOL fCanceled;
        CHECK_ERROR_BREAK(pProgress, COMGETTER(Canceled)(&fCanceled));
        if (!fCanceled)
        {
            LONG rcProc;
            CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&rcProc));
            if (FAILED(rcProc))
            {
                com::ProgressErrorInfo ErrInfo(pProgress);
                vrc = ctrlPrintError(ErrInfo);
            }
        }

    } while(0);

    AssertMsgStmt(SUCCEEDED(rc), ("Could not lookup progress information\n"), vrc = VERR_COM_UNEXPECTED);

    return vrc;
}

/**
 * Un-initializes the VM after guest control usage.
 * @param   pCmdCtx                 Pointer to command context.
 * @param   uFlags                  Command context flags.
 */
static void ctrlUninitVM(PGCTLCMDCTX pCtx, uint32_t uFlags)
{
    AssertPtrReturnVoid(pCtx);

    if (!(pCtx->uFlags & CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER))
        ctrlSignalHandlerUninstall();

    HRESULT rc;

    do
    {
        if (!pCtx->pGuestSession.isNull())
        {
            if (   !(pCtx->uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS)
                && !(pCtx->uFlags & CTLCMDCTX_FLAGS_SESSION_DETACH))
            {
                if (pCtx->fVerbose)
                    RTPrintf("Closing guest session ...\n");

                CHECK_ERROR(pCtx->pGuestSession, Close());
                /* Keep going - don't break here. Try to unlock the
                 * machine down below. */
            }
            else if (   (pCtx->uFlags & CTLCMDCTX_FLAGS_SESSION_DETACH)
                     && pCtx->fVerbose)
                RTPrintf("Guest session detached\n");

            pCtx->pGuestSession.setNull();
        }

        if (pCtx->handlerArg.session)
            CHECK_ERROR(pCtx->handlerArg.session, UnlockMachine());

    } while (0);

    for (int i = 0; i < pCtx->iArgc; i++)
        RTStrFree(pCtx->ppaArgv[i]);
    RTMemFree(pCtx->ppaArgv);
    pCtx->iArgc = 0;
}

/**
 * Initializes the VM for IGuest operations.
 *
 * That is, checks whether it's up and running, if it can be locked (shared
 * only) and returns a valid IGuest pointer on success. Also, it does some
 * basic command line processing and opens a guest session, if required.
 *
 * @return  RTEXITCODE status code.
 * @param   pArg                    Pointer to command line argument structure.
 * @param   pCmdCtx                 Pointer to command context.
 * @param   uFlags                  Command context flags.
 */
static RTEXITCODE ctrlInitVM(HandlerArg *pArg,
                             PGCTLCMDCTX pCtx, uint32_t uFlags, uint32_t uUsage)
{
    AssertPtrReturn(pArg, RTEXITCODE_FAILURE);
    AssertReturn(pArg->argc > 1, RTEXITCODE_FAILURE);
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

#ifdef DEBUG_andy
    RTPrintf("Original argv:\n");
    for (int i=0; i<pArg->argc;i++)
        RTPrintf("\targv[%d]=%s\n", i, pArg->argv[i]);
#endif

    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;

    const char *pszNameOrId = pArg->argv[0];
    const char *pszCmd = pArg->argv[1];

    /* Lookup VM. */
    ComPtr<IMachine> machine;
    /* Assume it's an UUID. */
    HRESULT rc;
    CHECK_ERROR(pArg->virtualBox, FindMachine(Bstr(pszNameOrId).raw(),
                                              machine.asOutParam()));
    if (SUCCEEDED(rc))
    {
        /* Machine is running? */
        MachineState_T machineState;
        CHECK_ERROR(machine, COMGETTER(State)(&machineState));
        if (   SUCCEEDED(rc)
            && (machineState != MachineState_Running))
            rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Machine \"%s\" is not running (currently %s)!\n",
                                    pszNameOrId, machineStateToName(machineState, false));
    }
    else
        rcExit = RTEXITCODE_FAILURE;

    if (rcExit == RTEXITCODE_SUCCESS)
    {
        /*
         * Process standard options which are served by all commands.
         */
        static const RTGETOPTDEF s_aOptions[] =
        {
            { "--username",            'u',                             RTGETOPT_REQ_STRING  },
            { "--passwordfile",        'p',                             RTGETOPT_REQ_STRING  },
            { "--password",            GETOPTDEF_COMMON_PASSWORD,       RTGETOPT_REQ_STRING  },
            { "--domain",              'd',                             RTGETOPT_REQ_STRING  },
            { "--verbose",             'v',                             RTGETOPT_REQ_NOTHING }
        };

        /*
         * Allocate per-command argv. This then only contains the specific arguments
         * the command needs.
         */
        pCtx->ppaArgv = (char**)RTMemAlloc(pArg->argc * sizeof(char*) + 1);
        if (!pCtx->ppaArgv)
        {
            rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Not enough memory for per-command argv\n");
        }
        else
        {
            pCtx->iArgc = 0;

            int iArgIdx = 2; /* Skip VM name and guest control command */
            int ch;
            RTGETOPTUNION ValueUnion;
            RTGETOPTSTATE GetState;
            RTGetOptInit(&GetState, pArg->argc, pArg->argv,
                         s_aOptions, RT_ELEMENTS(s_aOptions),
                         iArgIdx, 0);

            while (   (ch = RTGetOpt(&GetState, &ValueUnion))
                   && (rcExit == RTEXITCODE_SUCCESS))
            {
                /* For options that require an argument, ValueUnion has received the value. */
                switch (ch)
                {
                    case 'u': /* User name */
                        if (!(uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS))
                            pCtx->strUsername = ValueUnion.psz;
                        iArgIdx = GetState.iNext;
                        break;

                    case GETOPTDEF_COMMON_PASSWORD: /* Password */
                        if (!(uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS))
                        {
                            if (pCtx->strPassword.isEmpty())
                                pCtx->strPassword = ValueUnion.psz;
                        }
                        iArgIdx = GetState.iNext;
                        break;

                    case 'p': /* Password file */
                    {
                        if (!(uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS))
                            rcExit = readPasswordFile(ValueUnion.psz, &pCtx->strPassword);
                        iArgIdx = GetState.iNext;
                        break;
                    }

                    case 'd': /* domain */
                        if (!(uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS))
                            pCtx->strDomain = ValueUnion.psz;
                        iArgIdx = GetState.iNext;
                        break;

                    case 'v': /* Verbose */
                        pCtx->fVerbose = true;
                        iArgIdx = GetState.iNext;
                        break;

                    case 'h': /* Help */
                        errorGetOptEx(USAGE_GUESTCONTROL, uUsage, ch, &ValueUnion);
                        return RTEXITCODE_SYNTAX;

                    default:
                        /* Simply skip; might be handled in a specific command
                         * handler later. */
                        break;

                } /* switch */

                int iArgDiff = GetState.iNext - iArgIdx;
                if (iArgDiff)
                {
#ifdef DEBUG_andy
                    RTPrintf("Not handled (iNext=%d, iArgsCur=%d):\n", GetState.iNext, iArgIdx);
#endif
                    for (int i = iArgIdx; i < GetState.iNext; i++)
                    {
                        char *pszArg = RTStrDup(pArg->argv[i]);
                        if (!pszArg)
                        {
                            rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE,
                                                    "Not enough memory for command line handling\n");
                            break;
                        }
                        pCtx->ppaArgv[pCtx->iArgc] = pszArg;
                        pCtx->iArgc++;
#ifdef DEBUG_andy
                        RTPrintf("\targv[%d]=%s\n", i, pArg->argv[i]);
#endif
                    }

                    iArgIdx = GetState.iNext;
                }

            } /* while RTGetOpt */
        }
    }

    /*
     * Check for mandatory stuff.
     */
    if (rcExit == RTEXITCODE_SUCCESS)
    {
#if 0
        RTPrintf("argc=%d\n", pCtx->iArgc);
        for (int i = 0; i < pCtx->iArgc; i++)
            RTPrintf("argv[%d]=%s\n", i, pCtx->ppaArgv[i]);
#endif
        if (!(uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS))
        {
            if (pCtx->strUsername.isEmpty())
                rcExit = errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No user name specified!");
        }
    }

    if (rcExit == RTEXITCODE_SUCCESS)
    {
        /*
         * Build up a reasonable guest session name. Useful for identifying
         * a specific session when listing / searching for them.
         */
        char *pszSessionName;
        if (0 >= RTStrAPrintf(&pszSessionName,
                              "[%RU32] VBoxManage Guest Control [%s] - %s",
                              RTProcSelf(), pszNameOrId, pszCmd))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "No enough memory for session name\n");

        do
        {
            /* Open a session for the VM. */
            CHECK_ERROR_BREAK(machine, LockMachine(pArg->session, LockType_Shared));
            /* Get the associated console. */
            ComPtr<IConsole> console;
            CHECK_ERROR_BREAK(pArg->session, COMGETTER(Console)(console.asOutParam()));
            /* ... and session machine. */
            ComPtr<IMachine> sessionMachine;
            CHECK_ERROR_BREAK(pArg->session, COMGETTER(Machine)(sessionMachine.asOutParam()));
            /* Get IGuest interface. */
            CHECK_ERROR_BREAK(console, COMGETTER(Guest)(pCtx->pGuest.asOutParam()));
            if (!(uFlags & CTLCMDCTX_FLAGS_SESSION_ANONYMOUS))
            {
                if (pCtx->fVerbose)
                    RTPrintf("Opening guest session as user '%s' ...\n", pCtx->strUsername.c_str());

                /* Open a guest session. */
                Assert(!pCtx->pGuest.isNull());
                CHECK_ERROR_BREAK(pCtx->pGuest, CreateSession(Bstr(pCtx->strUsername).raw(),
                                                              Bstr(pCtx->strPassword).raw(),
                                                              Bstr(pCtx->strDomain).raw(),
                                                              Bstr(pszSessionName).raw(),
                                                              pCtx->pGuestSession.asOutParam()));

                /*
                 * Wait for guest session to start.
                 */
                if (pCtx->fVerbose)
                    RTPrintf("Waiting for guest session to start ...\n");

                com::SafeArray<GuestSessionWaitForFlag_T> aSessionWaitFlags;
                aSessionWaitFlags.push_back(GuestSessionWaitForFlag_Start);
                GuestSessionWaitResult_T sessionWaitResult;
                CHECK_ERROR_BREAK(pCtx->pGuestSession, WaitForArray(ComSafeArrayAsInParam(aSessionWaitFlags),
                                                                    /** @todo Make session handling timeouts configurable. */
                                                                    30 * 1000, &sessionWaitResult));

                if (   sessionWaitResult == GuestSessionWaitResult_Start
                    /* Note: This might happen when Guest Additions < 4.3 are installed which don't
                     *       support dedicated guest sessions. */
                    || sessionWaitResult == GuestSessionWaitResult_WaitFlagNotSupported)
                {
                    CHECK_ERROR_BREAK(pCtx->pGuestSession, COMGETTER(Id)(&pCtx->uSessionID));
                    if (pCtx->fVerbose)
                        RTPrintf("Guest session (ID %RU32) has been started\n", pCtx->uSessionID);
                }
                else
                {
                    GuestSessionStatus_T sessionStatus;
                    CHECK_ERROR_BREAK(pCtx->pGuestSession, COMGETTER(Status)(&sessionStatus));
                    rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Error starting guest session (current status is: %s)\n",
                                            ctrlSessionStatusToText(sessionStatus));
                    break;
                }
            }

            if (   SUCCEEDED(rc)
                && !(uFlags & CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER))
            {
                ctrlSignalHandlerInstall();
            }

        } while (0);

        if (FAILED(rc))
            rcExit = RTEXITCODE_FAILURE;

        RTStrFree(pszSessionName);
    }

    if (rcExit == RTEXITCODE_SUCCESS)
    {
        pCtx->handlerArg = *pArg;
        pCtx->uFlags = uFlags;
    }
    else /* Clean up on failure. */
        ctrlUninitVM(pCtx, uFlags);

    return rcExit;
}

/**
 * Prints the desired guest output to a stream.
 *
 * @return  IPRT status code.
 * @param   pProcess        Pointer to appropriate process object.
 * @param   pStrmOutput     Where to write the data.
 * @param   uHandle         Handle where to read the data from.
 * @param   uTimeoutMS      Timeout (in ms) to wait for the operation to complete.
 */
static int ctrlExecPrintOutput(IProcess *pProcess, PRTSTREAM pStrmOutput,
                               ULONG uHandle, ULONG uTimeoutMS)
{
    AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
    AssertPtrReturn(pStrmOutput, VERR_INVALID_POINTER);

    int vrc = VINF_SUCCESS;

    SafeArray<BYTE> aOutputData;
    HRESULT rc = pProcess->Read(uHandle, _64K, uTimeoutMS,
                                ComSafeArrayAsOutParam(aOutputData));
    if (FAILED(rc))
        vrc = ctrlPrintError(pProcess, COM_IIDOF(IProcess));
    else
    {
        size_t cbOutputData = aOutputData.size();
        if (cbOutputData > 0)
        {
            BYTE *pBuf = aOutputData.raw();
            AssertPtr(pBuf);
            pBuf[cbOutputData - 1] = 0; /* Properly terminate buffer. */

            /** @todo implement the dos2unix/unix2dos conversions */

            /*
             * If aOutputData is text data from the guest process' stdout or stderr,
             * it has a platform dependent line ending. So standardize on
             * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
             * Windows. Otherwise we end up with CR/CR/LF on Windows.
             */

            char *pszBufUTF8;
            vrc = RTStrCurrentCPToUtf8(&pszBufUTF8, (const char*)aOutputData.raw());
            if (RT_SUCCESS(vrc))
            {
                cbOutputData = strlen(pszBufUTF8);

                ULONG cbOutputDataPrint = cbOutputData;
                for (char *s = pszBufUTF8, *d = s;
                     s - pszBufUTF8 < (ssize_t)cbOutputData;
                     s++, d++)
                {
                    if (*s == '\r')
                    {
                        /* skip over CR, adjust destination */
                        d--;
                        cbOutputDataPrint--;
                    }
                    else if (s != d)
                        *d = *s;
                }

                vrc = RTStrmWrite(pStrmOutput, pszBufUTF8, cbOutputDataPrint);
                if (RT_FAILURE(vrc))
                    RTMsgError("Unable to write output, rc=%Rrc\n", vrc);

                RTStrFree(pszBufUTF8);
            }
            else
                RTMsgError("Unable to convert output, rc=%Rrc\n", vrc);
        }
    }

    return vrc;
}

/**
 * Returns the remaining time (in ms) based on the start time and a set
 * timeout value. Returns RT_INDEFINITE_WAIT if no timeout was specified.
 *
 * @return  RTMSINTERVAL    Time left (in ms).
 * @param   u64StartMs      Start time (in ms).
 * @param   cMsTimeout      Timeout value (in ms).
 */
inline RTMSINTERVAL ctrlExecGetRemainingTime(uint64_t u64StartMs, RTMSINTERVAL cMsTimeout)
{
    if (!cMsTimeout || cMsTimeout == RT_INDEFINITE_WAIT) /* If no timeout specified, wait forever. */
        return RT_INDEFINITE_WAIT;

    uint64_t u64ElapsedMs = RTTimeMilliTS() - u64StartMs;
    if (u64ElapsedMs >= cMsTimeout)
        return 0;

    return cMsTimeout - (RTMSINTERVAL)u64ElapsedMs;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlProcessExec(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    /*
     * Parse arguments.
     */
    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--dos2unix",                     GETOPTDEF_EXEC_DOS2UNIX,                  RTGETOPT_REQ_NOTHING },
        { "--environment",                  'e',                                      RTGETOPT_REQ_STRING  },
        { "--flags",                        'f',                                      RTGETOPT_REQ_STRING  },
        { "--ignore-operhaned-processes",   GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES,   RTGETOPT_REQ_NOTHING },
        { "--image",                        'i',                                      RTGETOPT_REQ_STRING  },
        { "--no-profile",                   GETOPTDEF_EXEC_NO_PROFILE,                RTGETOPT_REQ_NOTHING },
        { "--timeout",                      't',                                      RTGETOPT_REQ_UINT32  },
        { "--unix2dos",                     GETOPTDEF_EXEC_UNIX2DOS,                  RTGETOPT_REQ_NOTHING },
        { "--wait-exit",                    GETOPTDEF_EXEC_WAITFOREXIT,               RTGETOPT_REQ_NOTHING },
        { "--wait-stdout",                  GETOPTDEF_EXEC_WAITFORSTDOUT,             RTGETOPT_REQ_NOTHING },
        { "--wait-stderr",                  GETOPTDEF_EXEC_WAITFORSTDERR,             RTGETOPT_REQ_NOTHING }
    };

#ifdef DEBUG_andy
    RTPrintf("first=%d\n", pCtx->iFirstArgc);
    for (int i=0; i<pCtx->iArgc;i++)
        RTPrintf("\targv[%d]=%s\n", i, pCtx->ppaArgv[i]);
#endif

    int                     ch;
    RTGETOPTUNION           ValueUnion;
    RTGETOPTSTATE           GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv, s_aOptions, RT_ELEMENTS(s_aOptions),
                 pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    Utf8Str                              strCmd;
    com::SafeArray<ProcessCreateFlag_T>  aCreateFlags;
    com::SafeArray<ProcessWaitForFlag_T> aWaitFlags;
    com::SafeArray<IN_BSTR>              aArgs;
    com::SafeArray<IN_BSTR>              aEnv;
    RTMSINTERVAL                         cMsTimeout      = 0;
    OUTPUTTYPE                           eOutputType     = OUTPUTTYPE_UNDEFINED;
    bool                                 fDetached       = true;
    int                                  vrc             = VINF_SUCCESS;

    try
    {
        /* Wait for process start in any case. This is useful for scripting VBoxManage
         * when relying on its overall exit code. */
        aWaitFlags.push_back(ProcessWaitForFlag_Start);

        while (   (ch = RTGetOpt(&GetState, &ValueUnion))
               && RT_SUCCESS(vrc))
        {
            /* For options that require an argument, ValueUnion has received the value. */
            switch (ch)
            {
                case GETOPTDEF_EXEC_DOS2UNIX:
                    if (eOutputType != OUTPUTTYPE_UNDEFINED)
                        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_EXEC,
                                             "More than one output type (dos2unix/unix2dos) specified!");
                    eOutputType = OUTPUTTYPE_DOS2UNIX;
                    break;

                case 'e': /* Environment */
                {
                    char **papszArg;
                    int cArgs;

                    vrc = RTGetOptArgvFromString(&papszArg, &cArgs, ValueUnion.psz, NULL);
                    if (RT_FAILURE(vrc))
                        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_EXEC,
                                             "Failed to parse environment value, rc=%Rrc", vrc);
                    for (int j = 0; j < cArgs; j++)
                        aEnv.push_back(Bstr(papszArg[j]).raw());

                    RTGetOptArgvFree(papszArg);
                    break;
                }

                case GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES:
                    aCreateFlags.push_back(ProcessCreateFlag_IgnoreOrphanedProcesses);
                    break;

                case GETOPTDEF_EXEC_NO_PROFILE:
                    aCreateFlags.push_back(ProcessCreateFlag_NoProfile);
                    break;

                case 'i':
                    strCmd = ValueUnion.psz;
                    break;

                /** @todo Add a hidden flag. */

                case 't': /* Timeout */
                    cMsTimeout = ValueUnion.u32;
                    break;

                case GETOPTDEF_EXEC_UNIX2DOS:
                    if (eOutputType != OUTPUTTYPE_UNDEFINED)
                        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_EXEC,
                                             "More than one output type (dos2unix/unix2dos) specified!");
                    eOutputType = OUTPUTTYPE_UNIX2DOS;
                    break;

                case GETOPTDEF_EXEC_WAITFOREXIT:
                    aWaitFlags.push_back(ProcessWaitForFlag_Terminate);
                    fDetached = false;
                    break;

                case GETOPTDEF_EXEC_WAITFORSTDOUT:
                    aCreateFlags.push_back(ProcessCreateFlag_WaitForStdOut);
                    aWaitFlags.push_back(ProcessWaitForFlag_StdOut);
                    fDetached = false;
                    break;

                case GETOPTDEF_EXEC_WAITFORSTDERR:
                    aCreateFlags.push_back(ProcessCreateFlag_WaitForStdErr);
                    aWaitFlags.push_back(ProcessWaitForFlag_StdErr);
                    fDetached = false;
                    break;

                case VINF_GETOPT_NOT_OPTION:
                    if (aArgs.size() == 0 && strCmd.isEmpty())
                        strCmd = ValueUnion.psz;
                    else
                        aArgs.push_back(Bstr(ValueUnion.psz).raw());
                    break;

                default:
                    /* Note: Necessary for handling non-options (after --) which
                     *       contain a single dash, e.g. "-- foo.exe -s". */
                    if (GetState.argc == GetState.iNext)
                        aArgs.push_back(Bstr(ValueUnion.psz).raw());
                    else
                        return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_EXEC, ch, &ValueUnion);
                    break;

            } /* switch */
        } /* while RTGetOpt */
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }

    if (RT_FAILURE(vrc))
        return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize, rc=%Rrc\n", vrc);

    if (strCmd.isEmpty())
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_EXEC,
                             "No command to execute specified!");

    /** @todo Any output conversion not supported yet! */
    if (eOutputType != OUTPUTTYPE_UNDEFINED)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_EXEC,
                             "Output conversion not implemented yet!");

    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
    HRESULT rc;

    try
    {
        do
        {
            /* Adjust process creation flags if we don't want to wait for process termination. */
            if (fDetached)
                aCreateFlags.push_back(ProcessCreateFlag_WaitForProcessStartOnly);

            /* Get current time stamp to later calculate rest of timeout left. */
            uint64_t u64StartMS = RTTimeMilliTS();

            if (pCtx->fVerbose)
            {
                if (cMsTimeout == 0)
                    RTPrintf("Starting guest process ...\n");
                else
                    RTPrintf("Starting guest process (within %ums)\n", cMsTimeout);
            }

            /*
             * Execute the process.
             */
            ComPtr<IGuestProcess> pProcess;
            CHECK_ERROR_BREAK(pCtx->pGuestSession, ProcessCreate(Bstr(strCmd).raw(),
                                                                 ComSafeArrayAsInParam(aArgs),
                                                                 ComSafeArrayAsInParam(aEnv),
                                                                 ComSafeArrayAsInParam(aCreateFlags),
                                                                 ctrlExecGetRemainingTime(u64StartMS, cMsTimeout),
                                                                 pProcess.asOutParam()));

            /*
             * Explicitly wait for the guest process to be in a started
             * state.
             */
            com::SafeArray<ProcessWaitForFlag_T> aWaitStartFlags;
            aWaitStartFlags.push_back(ProcessWaitForFlag_Start);
            ProcessWaitResult_T waitResult;
            CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitStartFlags),
                                                     ctrlExecGetRemainingTime(u64StartMS, cMsTimeout), &waitResult));
            bool fCompleted = false;

            ULONG uPID = 0;
            CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
            if (!fDetached && pCtx->fVerbose)
            {
                RTPrintf("Process '%s' (PID %RU32) started\n",
                         strCmd.c_str(), uPID);
            }
            else if (fDetached) /** @todo Introduce a --quiet option for not printing this. */
            {
                /* Just print plain PID to make it easier for scripts
                 * invoking VBoxManage. */
                RTPrintf("[%RU32 - Session %RU32]\n", uPID, pCtx->uSessionID);
            }

            vrc = RTStrmSetMode(g_pStdOut, 1 /* Binary mode */, -1 /* Code set, unchanged */);
            if (RT_FAILURE(vrc))
                RTMsgError("Unable to set stdout's binary mode, rc=%Rrc\n", vrc);
            vrc = RTStrmSetMode(g_pStdErr, 1 /* Binary mode */, -1 /* Code set, unchanged */);
            if (RT_FAILURE(vrc))
                RTMsgError("Unable to set stderr's binary mode, rc=%Rrc\n", vrc);

            /* Wait for process to exit ... */
            RTMSINTERVAL cMsTimeLeft = 1; /* Will be calculated. */
            bool fReadStdOut, fReadStdErr;
            fReadStdOut = fReadStdErr = false;

            while (   !fCompleted
                   && !fDetached
                   && cMsTimeLeft != 0)
            {
                cMsTimeLeft = ctrlExecGetRemainingTime(u64StartMS, cMsTimeout);
                CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitFlags),
                                                         500 /* ms */, &waitResult));
                switch (waitResult)
                {
                    case ProcessWaitResult_Start:
                    {
                        /* We're done here if we don't want to wait for termination. */
                        if (fDetached)
                            fCompleted = true;

                        break;
                    }
                    case ProcessWaitResult_StdOut:
                        fReadStdOut = true;
                        break;
                    case ProcessWaitResult_StdErr:
                        fReadStdErr = true;
                        break;
                    case ProcessWaitResult_Terminate:
                        if (pCtx->fVerbose)
                            RTPrintf("Process terminated\n");
                        /* Process terminated, we're done. */
                        fCompleted = true;
                        break;
                    case ProcessWaitResult_WaitFlagNotSupported:
                    {
                        /* The guest does not support waiting for stdout/err, so
                         * yield to reduce the CPU load due to busy waiting. */
                        RTThreadYield(); /* Optional, don't check rc. */

                        /* Try both, stdout + stderr. */
                        fReadStdOut = fReadStdErr = true;
                        break;
                    }
                    case ProcessWaitResult_Timeout:
                        /* Fall through is intentional. */
                    default:
                        /* Ignore all other results, let the timeout expire */
                        break;
                }

                if (g_fGuestCtrlCanceled)
                    break;

                if (fReadStdOut) /* Do we need to fetch stdout data? */
                {
                    cMsTimeLeft = ctrlExecGetRemainingTime(u64StartMS, cMsTimeout);
                    vrc = ctrlExecPrintOutput(pProcess, g_pStdOut,
                                              1 /* StdOut */, cMsTimeLeft);
                    fReadStdOut = false;
                }

                if (fReadStdErr) /* Do we need to fetch stdout data? */
                {
                    cMsTimeLeft = ctrlExecGetRemainingTime(u64StartMS, cMsTimeout);
                    vrc = ctrlExecPrintOutput(pProcess, g_pStdErr,
                                              2 /* StdErr */, cMsTimeLeft);
                    fReadStdErr = false;
                }

                if (   RT_FAILURE(vrc)
                    || g_fGuestCtrlCanceled)
                    break;

                /* Did we run out of time? */
                if (   cMsTimeout
                    && RTTimeMilliTS() - u64StartMS > cMsTimeout)
                    break;

                NativeEventQueue::getMainEventQueue()->processEventQueue(0);

            } /* while */

            if (!fDetached)
            {
                /* Report status back to the user. */
                if (   fCompleted
                    && !g_fGuestCtrlCanceled)
                {

                    {
                        ProcessStatus_T procStatus;
                        CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&procStatus));
                        if (   procStatus == ProcessStatus_TerminatedNormally
                            || procStatus == ProcessStatus_TerminatedAbnormally
                            || procStatus == ProcessStatus_TerminatedSignal)
                        {
                            LONG exitCode;
                            CHECK_ERROR_BREAK(pProcess, COMGETTER(ExitCode)(&exitCode));
                            if (pCtx->fVerbose)
                                RTPrintf("Exit code=%u (Status=%u [%s])\n",
                                         exitCode, procStatus, ctrlProcessStatusToText(procStatus));

                            rcExit = (RTEXITCODE)ctrlExecProcessStatusToExitCode(procStatus, exitCode);
                        }
                        else if (pCtx->fVerbose)
                            RTPrintf("Process now is in status [%s]\n", ctrlProcessStatusToText(procStatus));
                    }
                }
                else
                {
                    if (pCtx->fVerbose)
                        RTPrintf("Process execution aborted!\n");

                    rcExit = (RTEXITCODE)EXITCODEEXEC_TERM_ABEND;
                }
            }

        } while (0);
    }
    catch (std::bad_alloc)
    {
        rc = E_OUTOFMEMORY;
    }

    /*
     * Decide what to do with the guest session. If we started a
     * detached guest process (that is, without waiting for it to exit),
     * don't close the guest session it is part of.
     */
    bool fCloseSession = false;
    if (SUCCEEDED(rc))
    {
        /*
         * Only close the guest session if we waited for the guest
         * process to exit. Otherwise we wouldn't have any chance to
         * access and/or kill detached guest process lateron.
         */
        fCloseSession = !fDetached;

        /*
         * If execution was aborted from the host side (signal handler),
         * close the guest session in any case.
         */
        if (g_fGuestCtrlCanceled)
            fCloseSession = true;
    }
    else /* Close session on error. */
        fCloseSession = true;

    if (!fCloseSession)
        pCtx->uFlags |= CTLCMDCTX_FLAGS_SESSION_DETACH;

    if (   rcExit == RTEXITCODE_SUCCESS
        && FAILED(rc))
    {
        /* Make sure an appropriate exit code is set on error. */
        rcExit = RTEXITCODE_FAILURE;
    }

    return rcExit;
}

/**
 * Creates a copy context structure which then can be used with various
 * guest control copy functions. Needs to be free'd with ctrlCopyContextFree().
 *
 * @return  IPRT status code.
 * @param   pCtx                    Pointer to command context.
 * @param   fDryRun                 Flag indicating if we want to run a dry run only.
 * @param   fHostToGuest            Flag indicating if we want to copy from host to guest
 *                                  or vice versa.
 * @param   strSessionName          Session name (only for identification purposes).
 * @param   ppContext               Pointer which receives the allocated copy context.
 */
static int ctrlCopyContextCreate(PGCTLCMDCTX pCtx, bool fDryRun, bool fHostToGuest,
                                 const Utf8Str &strSessionName,
                                 PCOPYCONTEXT *ppContext)
{
    AssertPtrReturn(pCtx, VERR_INVALID_POINTER);

    int vrc = VINF_SUCCESS;
    try
    {
        PCOPYCONTEXT pContext = new COPYCONTEXT();

        pContext->pCmdCtx = pCtx;
        pContext->fDryRun = fDryRun;
        pContext->fHostToGuest = fHostToGuest;

        *ppContext = pContext;
    }
    catch (std::bad_alloc)
    {
        vrc = VERR_NO_MEMORY;
    }

    return vrc;
}

/**
 * Frees are previously allocated copy context structure.
 *
 * @param   pContext                Pointer to copy context to free.
 */
static void ctrlCopyContextFree(PCOPYCONTEXT pContext)
{
    if (pContext)
        delete pContext;
}

/**
 * Translates a source path to a destination path (can be both sides,
 * either host or guest). The source root is needed to determine the start
 * of the relative source path which also needs to present in the destination
 * path.
 *
 * @return  IPRT status code.
 * @param   pszSourceRoot           Source root path. No trailing directory slash!
 * @param   pszSource               Actual source to transform. Must begin with
 *                                  the source root path!
 * @param   pszDest                 Destination path.
 * @param   ppszTranslated          Pointer to the allocated, translated destination
 *                                  path. Must be free'd with RTStrFree().
 */
static int ctrlCopyTranslatePath(const char *pszSourceRoot, const char *pszSource,
                                 const char *pszDest, char **ppszTranslated)
{
    AssertPtrReturn(pszSourceRoot, VERR_INVALID_POINTER);
    AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
    AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
    AssertPtrReturn(ppszTranslated, VERR_INVALID_POINTER);
#if 0 /** @todo r=bird: It does not make sense to apply host path parsing semantics onto guest paths. I hope this code isn't mixing host/guest paths in the same way anywhere else... @bugref{6344} */
    AssertReturn(RTPathStartsWith(pszSource, pszSourceRoot), VERR_INVALID_PARAMETER);
#endif

    /* Construct the relative dest destination path by "subtracting" the
     * source from the source root, e.g.
     *
     * source root path = "e:\foo\", source = "e:\foo\bar"
     * dest = "d:\baz\"
     * translated = "d:\baz\bar\"
     */
    char szTranslated[RTPATH_MAX];
    size_t srcOff = strlen(pszSourceRoot);
    AssertReturn(srcOff, VERR_INVALID_PARAMETER);

    char *pszDestPath = RTStrDup(pszDest);
    AssertPtrReturn(pszDestPath, VERR_NO_MEMORY);

    int vrc;
    if (!RTPathFilename(pszDestPath))
    {
        vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
                         pszDestPath, &pszSource[srcOff]);
    }
    else
    {
        char *pszDestFileName = RTStrDup(RTPathFilename(pszDestPath));
        if (pszDestFileName)
        {
            RTPathStripFilename(pszDestPath);
            vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
                            pszDestPath, pszDestFileName);
            RTStrFree(pszDestFileName);
        }
        else
            vrc = VERR_NO_MEMORY;
    }
    RTStrFree(pszDestPath);

    if (RT_SUCCESS(vrc))
    {
        *ppszTranslated = RTStrDup(szTranslated);
#if 0
        RTPrintf("Root: %s, Source: %s, Dest: %s, Translated: %s\n",
                 pszSourceRoot, pszSource, pszDest, *ppszTranslated);
#endif
    }
    return vrc;
}

#ifdef DEBUG_andy
static int tstTranslatePath()
{
    RTAssertSetMayPanic(false /* Do not freak out, please. */);

    static struct
    {
        const char *pszSourceRoot;
        const char *pszSource;
        const char *pszDest;
        const char *pszTranslated;
        int         iResult;
    } aTests[] =
    {
        /* Invalid stuff. */
        { NULL, NULL, NULL, NULL, VERR_INVALID_POINTER },
#ifdef RT_OS_WINDOWS
        /* Windows paths. */
        { "c:\\foo", "c:\\foo\\bar.txt", "c:\\test", "c:\\test\\bar.txt", VINF_SUCCESS },
        { "c:\\foo", "c:\\foo\\baz\\bar.txt", "c:\\test", "c:\\test\\baz\\bar.txt", VINF_SUCCESS },
#else /* RT_OS_WINDOWS */
        { "/home/test/foo", "/home/test/foo/bar.txt", "/opt/test", "/opt/test/bar.txt", VINF_SUCCESS },
        { "/home/test/foo", "/home/test/foo/baz/bar.txt", "/opt/test", "/opt/test/baz/bar.txt", VINF_SUCCESS },
#endif /* !RT_OS_WINDOWS */
        /* Mixed paths*/
        /** @todo */
        { NULL }
    };

    size_t iTest = 0;
    for (iTest; iTest < RT_ELEMENTS(aTests); iTest++)
    {
        RTPrintf("=> Test %d\n", iTest);
        RTPrintf("\tSourceRoot=%s, Source=%s, Dest=%s\n",
                 aTests[iTest].pszSourceRoot, aTests[iTest].pszSource, aTests[iTest].pszDest);

        char *pszTranslated = NULL;
        int iResult =  ctrlCopyTranslatePath(aTests[iTest].pszSourceRoot, aTests[iTest].pszSource,
                                             aTests[iTest].pszDest, &pszTranslated);
        if (iResult != aTests[iTest].iResult)
        {
            RTPrintf("\tReturned %Rrc, expected %Rrc\n",
                     iResult, aTests[iTest].iResult);
        }
        else if (   pszTranslated
                 && strcmp(pszTranslated, aTests[iTest].pszTranslated))
        {
            RTPrintf("\tReturned translated path %s, expected %s\n",
                     pszTranslated, aTests[iTest].pszTranslated);
        }

        if (pszTranslated)
        {
            RTPrintf("\tTranslated=%s\n", pszTranslated);
            RTStrFree(pszTranslated);
        }
    }

    return VINF_SUCCESS; /* @todo */
}
#endif

/**
 * Creates a directory on the destination, based on the current copy
 * context.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszDir                  Directory to create.
 */
static int ctrlCopyDirCreate(PCOPYCONTEXT pContext, const char *pszDir)
{
    AssertPtrReturn(pContext, VERR_INVALID_POINTER);
    AssertPtrReturn(pszDir, VERR_INVALID_POINTER);

    bool fDirExists;
    int vrc = ctrlCopyDirExists(pContext, pContext->fHostToGuest, pszDir, &fDirExists);
    if (   RT_SUCCESS(vrc)
        && fDirExists)
    {
        if (pContext->pCmdCtx->fVerbose)
            RTPrintf("Directory \"%s\" already exists\n", pszDir);
        return VINF_SUCCESS;
    }

    /* If querying for a directory existence fails there's no point of even trying
     * to create such a directory. */
    if (RT_FAILURE(vrc))
        return vrc;

    if (pContext->pCmdCtx->fVerbose)
        RTPrintf("Creating directory \"%s\" ...\n", pszDir);

    if (pContext->fDryRun)
        return VINF_SUCCESS;

    if (pContext->fHostToGuest) /* We want to create directories on the guest. */
    {
        SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
        dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
        HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryCreate(Bstr(pszDir).raw(),
                                                                       0700, ComSafeArrayAsInParam(dirCreateFlags));
        if (FAILED(rc))
            vrc = ctrlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
    }
    else /* ... or on the host. */
    {
        vrc = RTDirCreateFullPath(pszDir, 0700);
        if (vrc == VERR_ALREADY_EXISTS)
            vrc = VINF_SUCCESS;
    }
    return vrc;
}

/**
 * Checks whether a specific host/guest directory exists.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   fOnGuest                true if directory needs to be checked on the guest
 *                                  or false if on the host.
 * @param   pszDir                  Actual directory to check.
 * @param   fExists                 Pointer which receives the result if the
 *                                  given directory exists or not.
 */
static int ctrlCopyDirExists(PCOPYCONTEXT pContext, bool fOnGuest,
                             const char *pszDir, bool *fExists)
{
    AssertPtrReturn(pContext, false);
    AssertPtrReturn(pszDir, false);
    AssertPtrReturn(fExists, false);

    int vrc = VINF_SUCCESS;
    if (fOnGuest)
    {
        BOOL fDirExists = FALSE;
        HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryExists(Bstr(pszDir).raw(), &fDirExists);
        if (FAILED(rc))
            vrc = ctrlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
        else
            *fExists = fDirExists ? true : false;
    }
    else
        *fExists = RTDirExists(pszDir);
    return vrc;
}

/**
 * Checks whether a specific directory exists on the destination, based
 * on the current copy context.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszDir                  Actual directory to check.
 * @param   fExists                 Pointer which receives the result if the
 *                                  given directory exists or not.
 */
static int ctrlCopyDirExistsOnDest(PCOPYCONTEXT pContext, const char *pszDir,
                                   bool *fExists)
{
    return ctrlCopyDirExists(pContext, pContext->fHostToGuest,
                             pszDir, fExists);
}

/**
 * Checks whether a specific directory exists on the source, based
 * on the current copy context.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszDir                  Actual directory to check.
 * @param   fExists                 Pointer which receives the result if the
 *                                  given directory exists or not.
 */
static int ctrlCopyDirExistsOnSource(PCOPYCONTEXT pContext, const char *pszDir,
                                     bool *fExists)
{
    return ctrlCopyDirExists(pContext, !pContext->fHostToGuest,
                             pszDir, fExists);
}

/**
 * Checks whether a specific host/guest file exists.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   bGuest                  true if file needs to be checked on the guest
 *                                  or false if on the host.
 * @param   pszFile                 Actual file to check.
 * @param   fExists                 Pointer which receives the result if the
 *                                  given file exists or not.
 */
static int ctrlCopyFileExists(PCOPYCONTEXT pContext, bool bOnGuest,
                              const char *pszFile, bool *fExists)
{
    AssertPtrReturn(pContext, false);
    AssertPtrReturn(pszFile, false);
    AssertPtrReturn(fExists, false);

    int vrc = VINF_SUCCESS;
    if (bOnGuest)
    {
        BOOL fFileExists = FALSE;
        HRESULT rc = pContext->pCmdCtx->pGuestSession->FileExists(Bstr(pszFile).raw(), &fFileExists);
        if (FAILED(rc))
            vrc = ctrlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
        else
            *fExists = fFileExists ? true : false;
    }
    else
        *fExists = RTFileExists(pszFile);
    return vrc;
}

/**
 * Checks whether a specific file exists on the destination, based on the
 * current copy context.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszFile                 Actual file to check.
 * @param   fExists                 Pointer which receives the result if the
 *                                  given file exists or not.
 */
static int ctrlCopyFileExistsOnDest(PCOPYCONTEXT pContext, const char *pszFile,
                                    bool *fExists)
{
    return ctrlCopyFileExists(pContext, pContext->fHostToGuest,
                              pszFile, fExists);
}

/**
 * Checks whether a specific file exists on the source, based on the
 * current copy context.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszFile                 Actual file to check.
 * @param   fExists                 Pointer which receives the result if the
 *                                  given file exists or not.
 */
static int ctrlCopyFileExistsOnSource(PCOPYCONTEXT pContext, const char *pszFile,
                                      bool *fExists)
{
    return ctrlCopyFileExists(pContext, !pContext->fHostToGuest,
                              pszFile, fExists);
}

/**
 * Copies a source file to the destination.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszFileSource           Source file to copy to the destination.
 * @param   pszFileDest             Name of copied file on the destination.
 * @param   fFlags                  Copy flags. No supported at the moment and needs
 *                                  to be set to 0.
 */
static int ctrlCopyFileToDest(PCOPYCONTEXT pContext, const char *pszFileSource,
                              const char *pszFileDest, uint32_t fFlags)
{
    AssertPtrReturn(pContext, VERR_INVALID_POINTER);
    AssertPtrReturn(pszFileSource, VERR_INVALID_POINTER);
    AssertPtrReturn(pszFileDest, VERR_INVALID_POINTER);
    AssertReturn(!fFlags, VERR_INVALID_POINTER); /* No flags supported yet. */

    if (pContext->pCmdCtx->fVerbose)
        RTPrintf("Copying \"%s\" to \"%s\" ...\n",
                 pszFileSource, pszFileDest);

    if (pContext->fDryRun)
        return VINF_SUCCESS;

    int vrc = VINF_SUCCESS;
    ComPtr<IProgress> pProgress;
    HRESULT rc;
    if (pContext->fHostToGuest)
    {
        SafeArray<CopyFileFlag_T> copyFlags;
        rc = pContext->pCmdCtx->pGuestSession->CopyTo(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
                                               ComSafeArrayAsInParam(copyFlags),
                                               pProgress.asOutParam());
    }
    else
    {
        SafeArray<CopyFileFlag_T> copyFlags;
        rc = pContext->pCmdCtx->pGuestSession->CopyFrom(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
                                               ComSafeArrayAsInParam(copyFlags),
                                               pProgress.asOutParam());
    }

    if (FAILED(rc))
    {
        vrc = ctrlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
    }
    else
    {
        if (pContext->pCmdCtx->fVerbose)
            rc = showProgress(pProgress);
        else
            rc = pProgress->WaitForCompletion(-1 /* No timeout */);
        if (SUCCEEDED(rc))
            CHECK_PROGRESS_ERROR(pProgress, ("File copy failed"));
        vrc = ctrlPrintProgressError(pProgress);
    }

    return vrc;
}

/**
 * Copys a directory (tree) from host to the guest.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszSource               Source directory on the host to copy to the guest.
 * @param   pszFilter               DOS-style wildcard filter (?, *).  Optional.
 * @param   pszDest                 Destination directory on the guest.
 * @param   fFlags                  Copy flags, such as recursive copying.
 * @param   pszSubDir               Current sub directory to handle. Needs to NULL and only
 *                                  is needed for recursion.
 */
static int ctrlCopyDirToGuest(PCOPYCONTEXT pContext,
                              const char *pszSource, const char *pszFilter,
                              const char *pszDest, uint32_t fFlags,
                              const char *pszSubDir /* For recursion. */)
{
    AssertPtrReturn(pContext, VERR_INVALID_POINTER);
    AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
    /* Filter is optional. */
    AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
    /* Sub directory is optional. */

    /*
     * Construct current path.
     */
    char szCurDir[RTPATH_MAX];
    int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
    if (RT_SUCCESS(vrc) && pszSubDir)
        vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);

    if (pContext->pCmdCtx->fVerbose)
        RTPrintf("Processing host directory: %s\n", szCurDir);

    /* Flag indicating whether the current directory was created on the
     * target or not. */
    bool fDirCreated = false;

    /*
     * Open directory without a filter - RTDirOpenFiltered unfortunately
     * cannot handle sub directories so we have to do the filtering ourselves.
     */
    PRTDIR pDir = NULL;
    if (RT_SUCCESS(vrc))
    {
        vrc = RTDirOpen(&pDir, szCurDir);
        if (RT_FAILURE(vrc))
            pDir = NULL;
    }
    if (RT_SUCCESS(vrc))
    {
        /*
         * Enumerate the directory tree.
         */
        while (RT_SUCCESS(vrc))
        {
            RTDIRENTRY DirEntry;
            vrc = RTDirRead(pDir, &DirEntry, NULL);
            if (RT_FAILURE(vrc))
            {
                if (vrc == VERR_NO_MORE_FILES)
                    vrc = VINF_SUCCESS;
                break;
            }
            /** @todo r=bird: This ain't gonna work on most UNIX file systems because
             *        enmType is RTDIRENTRYTYPE_UNKNOWN.  This is clearly documented in
             *        RTDIRENTRY::enmType. For trunk, RTDirQueryUnknownType can be used. */
            switch (DirEntry.enmType)
            {
                case RTDIRENTRYTYPE_DIRECTORY:
                {
                    /* Skip "." and ".." entries. */
                    if (   !strcmp(DirEntry.szName, ".")
                        || !strcmp(DirEntry.szName, ".."))
                        break;

                    if (pContext->pCmdCtx->fVerbose)
                        RTPrintf("Directory: %s\n", DirEntry.szName);

                    if (fFlags & CopyFileFlag_Recursive)
                    {
                        char *pszNewSub = NULL;
                        if (pszSubDir)
                            pszNewSub = RTPathJoinA(pszSubDir, DirEntry.szName);
                        else
                        {
                            pszNewSub = RTStrDup(DirEntry.szName);
                            RTPathStripTrailingSlash(pszNewSub);
                        }

                        if (pszNewSub)
                        {
                            vrc = ctrlCopyDirToGuest(pContext,
                                                     pszSource, pszFilter,
                                                     pszDest, fFlags, pszNewSub);
                            RTStrFree(pszNewSub);
                        }
                        else
                            vrc = VERR_NO_MEMORY;
                    }
                    break;
                }

                case RTDIRENTRYTYPE_SYMLINK:
                    if (   (fFlags & CopyFileFlag_Recursive)
                        && (fFlags & CopyFileFlag_FollowLinks))
                    {
                        /* Fall through to next case is intentional. */
                    }
                    else
                        break;

                case RTDIRENTRYTYPE_FILE:
                {
                    if (   pszFilter
                        && !RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
                    {
                        break; /* Filter does not match. */
                    }

                    if (pContext->pCmdCtx->fVerbose)
                        RTPrintf("File: %s\n", DirEntry.szName);

                    if (!fDirCreated)
                    {
                        char *pszDestDir;
                        vrc = ctrlCopyTranslatePath(pszSource, szCurDir,
                                                    pszDest, &pszDestDir);
                        if (RT_SUCCESS(vrc))
                        {
                            vrc = ctrlCopyDirCreate(pContext, pszDestDir);
                            RTStrFree(pszDestDir);

                            fDirCreated = true;
                        }
                    }

                    if (RT_SUCCESS(vrc))
                    {
                        char *pszFileSource = RTPathJoinA(szCurDir, DirEntry.szName);
                        if (pszFileSource)
                        {
                            char *pszFileDest;
                            vrc = ctrlCopyTranslatePath(pszSource, pszFileSource,
                                                       pszDest, &pszFileDest);
                            if (RT_SUCCESS(vrc))
                            {
                                vrc = ctrlCopyFileToDest(pContext, pszFileSource,
                                                        pszFileDest, 0 /* Flags */);
                                RTStrFree(pszFileDest);
                            }
                            RTStrFree(pszFileSource);
                        }
                    }
                    break;
                }

                default:
                    break;
            }
            if (RT_FAILURE(vrc))
                break;
        }

        RTDirClose(pDir);
    }
    return vrc;
}

/**
 * Copys a directory (tree) from guest to the host.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszSource               Source directory on the guest to copy to the host.
 * @param   pszFilter               DOS-style wildcard filter (?, *).  Optional.
 * @param   pszDest                 Destination directory on the host.
 * @param   fFlags                  Copy flags, such as recursive copying.
 * @param   pszSubDir               Current sub directory to handle. Needs to NULL and only
 *                                  is needed for recursion.
 */
static int ctrlCopyDirToHost(PCOPYCONTEXT pContext,
                             const char *pszSource, const char *pszFilter,
                             const char *pszDest, uint32_t fFlags,
                             const char *pszSubDir /* For recursion. */)
{
    AssertPtrReturn(pContext, VERR_INVALID_POINTER);
    AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
    /* Filter is optional. */
    AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
    /* Sub directory is optional. */

    /*
     * Construct current path.
     */
    char szCurDir[RTPATH_MAX];
    int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
    if (RT_SUCCESS(vrc) && pszSubDir)
        vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);

    if (RT_FAILURE(vrc))
        return vrc;

    if (pContext->pCmdCtx->fVerbose)
        RTPrintf("Processing guest directory: %s\n", szCurDir);

    /* Flag indicating whether the current directory was created on the
     * target or not. */
    bool fDirCreated = false;
    SafeArray<DirectoryOpenFlag_T> dirOpenFlags; /* No flags supported yet. */
    ComPtr<IGuestDirectory> pDirectory;
    HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(),
                                                        ComSafeArrayAsInParam(dirOpenFlags),
                                                        pDirectory.asOutParam());
    if (FAILED(rc))
        return ctrlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
    ComPtr<IFsObjInfo> dirEntry;
    while (true)
    {
        rc = pDirectory->Read(dirEntry.asOutParam());
        if (FAILED(rc))
            break;

        FsObjType_T enmType;
        dirEntry->COMGETTER(Type)(&enmType);

        Bstr strName;
        dirEntry->COMGETTER(Name)(strName.asOutParam());

        switch (enmType)
        {
            case FsObjType_Directory:
            {
                Assert(!strName.isEmpty());

                /* Skip "." and ".." entries. */
                if (   !strName.compare(Bstr("."))
                    || !strName.compare(Bstr("..")))
                    break;

                if (pContext->pCmdCtx->fVerbose)
                {
                    Utf8Str strDir(strName);
                    RTPrintf("Directory: %s\n", strDir.c_str());
                }

                if (fFlags & CopyFileFlag_Recursive)
                {
                    Utf8Str strDir(strName);
                    char *pszNewSub = NULL;
                    if (pszSubDir)
                        pszNewSub = RTPathJoinA(pszSubDir, strDir.c_str());
                    else
                    {
                        pszNewSub = RTStrDup(strDir.c_str());
                        RTPathStripTrailingSlash(pszNewSub);
                    }
                    if (pszNewSub)
                    {
                        vrc = ctrlCopyDirToHost(pContext,
                                                pszSource, pszFilter,
                                                pszDest, fFlags, pszNewSub);
                        RTStrFree(pszNewSub);
                    }
                    else
                        vrc = VERR_NO_MEMORY;
                }
                break;
            }

            case FsObjType_Symlink:
                if (   (fFlags & CopyFileFlag_Recursive)
                    && (fFlags & CopyFileFlag_FollowLinks))
                {
                    /* Fall through to next case is intentional. */
                }
                else
                    break;

            case FsObjType_File:
            {
                Assert(!strName.isEmpty());

                Utf8Str strFile(strName);
                if (   pszFilter
                    && !RTStrSimplePatternMatch(pszFilter, strFile.c_str()))
                {
                    break; /* Filter does not match. */
                }

                if (pContext->pCmdCtx->fVerbose)
                    RTPrintf("File: %s\n", strFile.c_str());

                if (!fDirCreated)
                {
                    char *pszDestDir;
                    vrc = ctrlCopyTranslatePath(pszSource, szCurDir,
                                                pszDest, &pszDestDir);
                    if (RT_SUCCESS(vrc))
                    {
                        vrc = ctrlCopyDirCreate(pContext, pszDestDir);
                        RTStrFree(pszDestDir);

                        fDirCreated = true;
                    }
                }

                if (RT_SUCCESS(vrc))
                {
                    char *pszFileSource = RTPathJoinA(szCurDir, strFile.c_str());
                    if (pszFileSource)
                    {
                        char *pszFileDest;
                        vrc = ctrlCopyTranslatePath(pszSource, pszFileSource,
                                                   pszDest, &pszFileDest);
                        if (RT_SUCCESS(vrc))
                        {
                            vrc = ctrlCopyFileToDest(pContext, pszFileSource,
                                                    pszFileDest, 0 /* Flags */);
                            RTStrFree(pszFileDest);
                        }
                        RTStrFree(pszFileSource);
                    }
                    else
                        vrc = VERR_NO_MEMORY;
                }
                break;
            }

            default:
                RTPrintf("Warning: Directory entry of type %ld not handled, skipping ...\n",
                         enmType);
                break;
        }

        if (RT_FAILURE(vrc))
            break;
    }

    if (RT_UNLIKELY(FAILED(rc)))
    {
        switch (rc)
        {
            case E_ABORT: /* No more directory entries left to process. */
                break;

            case VBOX_E_FILE_ERROR: /* Current entry cannot be accessed to
                                       to missing rights. */
            {
                RTPrintf("Warning: Cannot access \"%s\", skipping ...\n",
                         szCurDir);
                break;
            }

            default:
                vrc = ctrlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
                break;
        }
    }

    HRESULT rc2 = pDirectory->Close();
    if (FAILED(rc2))
    {
        int vrc2 = ctrlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
        if (RT_SUCCESS(vrc))
            vrc = vrc2;
    }
    else if (SUCCEEDED(rc))
        rc = rc2;

    return vrc;
}

/**
 * Copys a directory (tree) to the destination, based on the current copy
 * context.
 *
 * @return  IPRT status code.
 * @param   pContext                Pointer to current copy control context.
 * @param   pszSource               Source directory to copy to the destination.
 * @param   pszFilter               DOS-style wildcard filter (?, *).  Optional.
 * @param   pszDest                 Destination directory where to copy in the source
 *                                  source directory.
 * @param   fFlags                  Copy flags, such as recursive copying.
 */
static int ctrlCopyDirToDest(PCOPYCONTEXT pContext,
                             const char *pszSource, const char *pszFilter,
                             const char *pszDest, uint32_t fFlags)
{
    if (pContext->fHostToGuest)
        return ctrlCopyDirToGuest(pContext, pszSource, pszFilter,
                                  pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
    return ctrlCopyDirToHost(pContext, pszSource, pszFilter,
                             pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
}

/**
 * Creates a source root by stripping file names or filters of the specified source.
 *
 * @return  IPRT status code.
 * @param   pszSource               Source to create source root for.
 * @param   ppszSourceRoot          Pointer that receives the allocated source root. Needs
 *                                  to be free'd with ctrlCopyFreeSourceRoot().
 */
static int ctrlCopyCreateSourceRoot(const char *pszSource, char **ppszSourceRoot)
{
    AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
    AssertPtrReturn(ppszSourceRoot, VERR_INVALID_POINTER);

    char *pszNewRoot = RTStrDup(pszSource);
    AssertPtrReturn(pszNewRoot, VERR_NO_MEMORY);

    size_t lenRoot = strlen(pszNewRoot);
    if (   lenRoot
        && pszNewRoot[lenRoot - 1] == '/'
        && pszNewRoot[lenRoot - 1] == '\\'
        && lenRoot > 1
        && pszNewRoot[lenRoot - 2] == '/'
        && pszNewRoot[lenRoot - 2] == '\\')
    {
        *ppszSourceRoot = pszNewRoot;
        if (lenRoot > 1)
            *ppszSourceRoot[lenRoot - 2] = '\0';
        *ppszSourceRoot[lenRoot - 1] = '\0';
    }
    else
    {
        /* If there's anything (like a file name or a filter),
         * strip it! */
        RTPathStripFilename(pszNewRoot);
        *ppszSourceRoot = pszNewRoot;
    }

    return VINF_SUCCESS;
}

/**
 * Frees a previously allocated source root.
 *
 * @return  IPRT status code.
 * @param   pszSourceRoot           Source root to free.
 */
static void ctrlCopyFreeSourceRoot(char *pszSourceRoot)
{
    RTStrFree(pszSourceRoot);
}

static RTEXITCODE handleCtrlCopy(PGCTLCMDCTX pCtx, bool fHostToGuest)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    /** @todo r=bird: This command isn't very unix friendly in general. mkdir
     * is much better (partly because it is much simpler of course).  The main
     * arguments against this is that (1) all but two options conflicts with
     * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
     * done windows CMD style (though not in a 100% compatible way), and (3)
     * that only one source is allowed - efficiently sabotaging default
     * wildcard expansion by a unix shell.  The best solution here would be
     * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */

    /*
     * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
     * what and how to implement the file enumeration/recursive lookup, like VBoxManage
     * does in here.
     */
    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--dryrun",              GETOPTDEF_COPY_DRYRUN,           RTGETOPT_REQ_NOTHING },
        { "--follow",              GETOPTDEF_COPY_FOLLOW,           RTGETOPT_REQ_NOTHING },
        { "--recursive",           'R',                             RTGETOPT_REQ_NOTHING },
        { "--target-directory",    GETOPTDEF_COPY_TARGETDIR,        RTGETOPT_REQ_STRING  }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    Utf8Str strSource;
    Utf8Str strDest;
    uint32_t fFlags = CopyFileFlag_None;
    bool fCopyRecursive = false;
    bool fDryRun = false;
    uint32_t uUsage = fHostToGuest ? USAGE_GSTCTRL_COPYTO : USAGE_GSTCTRL_COPYFROM;

    SOURCEVEC vecSources;

    int vrc = VINF_SUCCESS;
    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case GETOPTDEF_COPY_DRYRUN:
                fDryRun = true;
                break;

            case GETOPTDEF_COPY_FOLLOW:
                fFlags |= CopyFileFlag_FollowLinks;
                break;

            case 'R': /* Recursive processing */
                fFlags |= CopyFileFlag_Recursive;
                break;

            case GETOPTDEF_COPY_TARGETDIR:
                strDest = ValueUnion.psz;
                break;

            case VINF_GETOPT_NOT_OPTION:
            {
                /* Last argument and no destination specified with
                 * --target-directory yet? Then use the current
                 * (= last) argument as destination. */
                if (  pCtx->iArgc == GetState.iNext
                    && strDest.isEmpty())
                {
                    strDest = ValueUnion.psz;
                }
                else
                {
                    /* Save the source directory. */
                    vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
                }
                break;
            }

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, uUsage, ch, &ValueUnion);
        }
    }

    if (!vecSources.size())
        return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage,
                             "No source(s) specified!");

    if (strDest.isEmpty())
        return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage,
                             "No destination specified!");

    /*
     * Done parsing arguments, do some more preparations.
     */
    if (pCtx->fVerbose)
    {
        if (fHostToGuest)
            RTPrintf("Copying from host to guest ...\n");
        else
            RTPrintf("Copying from guest to host ...\n");
        if (fDryRun)
            RTPrintf("Dry run - no files copied!\n");
    }

    /* Create the copy context -- it contains all information
     * the routines need to know when handling the actual copying. */
    PCOPYCONTEXT pContext = NULL;
    vrc = ctrlCopyContextCreate(pCtx, fDryRun, fHostToGuest,
                                  fHostToGuest
                                ? "VBoxManage Guest Control - Copy to guest"
                                : "VBoxManage Guest Control - Copy from guest", &pContext);
    if (RT_FAILURE(vrc))
    {
        RTMsgError("Unable to create copy context, rc=%Rrc\n", vrc);
        return RTEXITCODE_FAILURE;
    }

    /* If the destination is a path, (try to) create it. */
    const char *pszDest = strDest.c_str();
/** @todo r=bird: RTPathFilename and RTPathStripFilename won't work
 * correctly on non-windows hosts when the guest is from the DOS world (Windows,
 * OS/2, DOS).  The host doesn't know about DOS slashes, only UNIX slashes and
 * will get the wrong idea if some dilligent user does:
 *
 *      copyto myfile.txt 'C:\guestfile.txt'
 * or
 *      copyto myfile.txt 'D:guestfile.txt'
 *
 * @bugref{6344}
 */
    if (!RTPathFilename(pszDest))
    {
        vrc = ctrlCopyDirCreate(pContext, pszDest);
    }
    else
    {
        /* We assume we got a file name as destination -- so strip
         * the actual file name and make sure the appropriate
         * directories get created. */
        char *pszDestDir = RTStrDup(pszDest);
        AssertPtr(pszDestDir);
        RTPathStripFilename(pszDestDir);
        vrc = ctrlCopyDirCreate(pContext, pszDestDir);
        RTStrFree(pszDestDir);
    }

    if (RT_SUCCESS(vrc))
    {
        /*
         * Here starts the actual fun!
         * Handle all given sources one by one.
         */
        for (unsigned long s = 0; s < vecSources.size(); s++)
        {
            char *pszSource = RTStrDup(vecSources[s].GetSource());
            AssertPtrBreakStmt(pszSource, vrc = VERR_NO_MEMORY);
            const char *pszFilter = vecSources[s].GetFilter();
            if (!strlen(pszFilter))
                pszFilter = NULL; /* If empty filter then there's no filter :-) */

            char *pszSourceRoot;
            vrc = ctrlCopyCreateSourceRoot(pszSource, &pszSourceRoot);
            if (RT_FAILURE(vrc))
            {
                RTMsgError("Unable to create source root, rc=%Rrc\n", vrc);
                break;
            }

            if (pCtx->fVerbose)
                RTPrintf("Source: %s\n", pszSource);

            /** @todo Files with filter?? */
            bool fSourceIsFile = false;
            bool fSourceExists;

            size_t cchSource = strlen(pszSource);
            if (   cchSource > 1
                && RTPATH_IS_SLASH(pszSource[cchSource - 1]))
            {
                if (pszFilter) /* Directory with filter (so use source root w/o the actual filter). */
                    vrc = ctrlCopyDirExistsOnSource(pContext, pszSourceRoot, &fSourceExists);
                else /* Regular directory without filter. */
                    vrc = ctrlCopyDirExistsOnSource(pContext, pszSource, &fSourceExists);

                if (fSourceExists)
                {
                    /* Strip trailing slash from our source element so that other functions
                     * can use this stuff properly (like RTPathStartsWith). */
                    RTPathStripTrailingSlash(pszSource);
                }
            }
            else
            {
                vrc = ctrlCopyFileExistsOnSource(pContext, pszSource, &fSourceExists);
                if (   RT_SUCCESS(vrc)
                    && fSourceExists)
                {
                    fSourceIsFile = true;
                }
            }

            if (   RT_SUCCESS(vrc)
                && fSourceExists)
            {
                if (fSourceIsFile)
                {
                    /* Single file. */
                    char *pszDestFile;
                    vrc = ctrlCopyTranslatePath(pszSourceRoot, pszSource,
                                                strDest.c_str(), &pszDestFile);
                    if (RT_SUCCESS(vrc))
                    {
                        vrc = ctrlCopyFileToDest(pContext, pszSource,
                                                 pszDestFile, 0 /* Flags */);
                        RTStrFree(pszDestFile);
                    }
                    else
                        RTMsgError("Unable to translate path for \"%s\", rc=%Rrc\n",
                                   pszSource, vrc);
                }
                else
                {
                    /* Directory (with filter?). */
                    vrc = ctrlCopyDirToDest(pContext, pszSource, pszFilter,
                                            strDest.c_str(), fFlags);
                }
            }

            ctrlCopyFreeSourceRoot(pszSourceRoot);

            if (   RT_SUCCESS(vrc)
                && !fSourceExists)
            {
                RTMsgError("Warning: Source \"%s\" does not exist, skipping!\n",
                           pszSource);
                RTStrFree(pszSource);
                continue;
            }
            else if (RT_FAILURE(vrc))
            {
                RTMsgError("Error processing \"%s\", rc=%Rrc\n",
                           pszSource, vrc);
                RTStrFree(pszSource);
                break;
            }

            RTStrFree(pszSource);
        }
    }

    ctrlCopyContextFree(pContext);

    return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlCopyFrom(PGCTLCMDCTX pCtx)
{
    return handleCtrlCopy(pCtx, false /* Guest to host */);
}

static DECLCALLBACK(RTEXITCODE) handleCtrlCopyTo(PGCTLCMDCTX pCtx)
{
    return handleCtrlCopy(pCtx, true /* Host to guest */);
}

static DECLCALLBACK(RTEXITCODE) handleCtrlCreateDirectory(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--mode",                'm',                             RTGETOPT_REQ_UINT32  },
        { "--parents",             'P',                             RTGETOPT_REQ_NOTHING }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
    uint32_t fDirMode = 0; /* Default mode. */
    DESTDIRMAP mapDirs;

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case 'm': /* Mode */
                fDirMode = ValueUnion.u32;
                break;

            case 'P': /* Create parents */
                dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
                break;

            case VINF_GETOPT_NOT_OPTION:
                mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CREATEDIR, ch, &ValueUnion);
        }
    }

    uint32_t cDirs = mapDirs.size();
    if (!cDirs)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CREATEDIR,
                             "No directory to create specified!");

    /*
     * Create the directories.
     */
    HRESULT rc = S_OK;
    if (pCtx->fVerbose && cDirs)
        RTPrintf("Creating %RU32 directories ...\n", cDirs);

    DESTDIRMAPITER it = mapDirs.begin();
    while (   (it != mapDirs.end())
           && !g_fGuestCtrlCanceled)
    {
        if (pCtx->fVerbose)
            RTPrintf("Creating directory \"%s\" ...\n", it->first.c_str());

        CHECK_ERROR_BREAK(pCtx->pGuestSession, DirectoryCreate(Bstr(it->first).raw(),
                                               fDirMode, ComSafeArrayAsInParam(dirCreateFlags)));
        it++;
    }

    return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlRemoveDirectory(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--recursive",           'R',                             RTGETOPT_REQ_NOTHING }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    bool fRecursive = false;
    DESTDIRMAP mapDirs;

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case 'R':
                fRecursive = true;
                break;

            case VINF_GETOPT_NOT_OPTION:
                mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_REMOVEDIR, ch, &ValueUnion);
        }
    }

    uint32_t cDirs = mapDirs.size();
    if (!cDirs)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_REMOVEDIR,
                             "No directory to remove specified!");

    /*
     * Remove the directories.
     */
    HRESULT rc = S_OK;
    if (pCtx->fVerbose && cDirs)
        RTPrintf("Removing %RU32 directories ...\n", cDirs);

    DESTDIRMAPITER it = mapDirs.begin();
    while (   (it != mapDirs.end())
           && !g_fGuestCtrlCanceled)
    {
        if (pCtx->fVerbose)
            RTPrintf("%s directory \"%s\" ...\n",
                     fRecursive ? "Recursively removing" : "Removing",
                     it->first.c_str());
        try
        {
            if (fRecursive)
            {
                com::SafeArray<DirectoryRemoveRecFlag_T> aRemRecFlags;
                /** @todo Make flags configurable. */
                aRemRecFlags.push_back(DirectoryRemoveRecFlag_ContentAndDir);

                ComPtr<IProgress> pProgress;
                CHECK_ERROR_BREAK(pCtx->pGuestSession, DirectoryRemoveRecursive(Bstr(it->first).raw(),
                                                                                ComSafeArrayAsInParam(aRemRecFlags),
                                                                                pProgress.asOutParam()));
                if (pCtx->fVerbose)
                    rc = showProgress(pProgress);
                else
                    rc = pProgress->WaitForCompletion(-1 /* No timeout */);
                if (SUCCEEDED(rc))
                    CHECK_PROGRESS_ERROR(pProgress, ("Directory deletion failed"));

                pProgress.setNull();
            }
            else
                CHECK_ERROR_BREAK(pCtx->pGuestSession, DirectoryRemove(Bstr(it->first).raw()));
        }
        catch (std::bad_alloc)
        {
            rc = E_OUTOFMEMORY;
            break;
        }

        it++;
    }

    return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlRemoveFile(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 NULL /* s_aOptions */, 0 /* RT_ELEMENTS(s_aOptions) */,
                 pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    DESTDIRMAP mapDirs;

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case VINF_GETOPT_NOT_OPTION:
                mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_REMOVEFILE, ch, &ValueUnion);
        }
    }

    uint32_t cFiles = mapDirs.size();
    if (!cFiles)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_REMOVEFILE,
                             "No file to remove specified!");

    /*
     * Create the directories.
     */
    HRESULT rc = S_OK;
    if (pCtx->fVerbose && cFiles)
        RTPrintf("Removing %RU32 file(s) ...\n", cFiles);

    DESTDIRMAPITER it = mapDirs.begin();
    while (   (it != mapDirs.end())
           && !g_fGuestCtrlCanceled)
    {
        if (pCtx->fVerbose)
            RTPrintf("Removing file \"%s\" ...\n", it->first.c_str());

        CHECK_ERROR_BREAK(pCtx->pGuestSession, FileRemove(Bstr(it->first).raw()));

        it++;
    }

    return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlRename(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    static const RTGETOPTDEF s_aOptions[] = { 0 };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 NULL /*s_aOptions*/, 0 /*RT_ELEMENTS(s_aOptions)*/, pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    int vrc = VINF_SUCCESS;

    bool fDryrun = false;
    std::vector< Utf8Str > vecSources;
    Utf8Str strDest;
    com::SafeArray<PathRenameFlag_T> aRenameFlags;

    try
    {
        /** @todo Make flags configurable. */
        aRenameFlags.push_back(PathRenameFlag_NoReplace);

        while (   (ch = RTGetOpt(&GetState, &ValueUnion))
               && RT_SUCCESS(vrc))
        {
            /* For options that require an argument, ValueUnion has received the value. */
            switch (ch)
            {
                /** @todo Implement a --dryrun command. */
                /** @todo Implement rename flags. */

                case VINF_GETOPT_NOT_OPTION:
                    vecSources.push_back(Utf8Str(ValueUnion.psz));
                    strDest = ValueUnion.psz;
                    break;

                default:
                    return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RENAME, ch, &ValueUnion);
            }
        }
    }
    catch (std::bad_alloc)
    {
        vrc = VERR_NO_MEMORY;
    }

    if (RT_FAILURE(vrc))
        return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize, rc=%Rrc\n", vrc);

    uint32_t cSources = vecSources.size();
    if (!cSources)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RENAME,
                             "No source(s) to move specified!");
    if (cSources < 2)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RENAME,
                             "No destination specified!");

    /* Delete last element, which now is the destination. */
    vecSources.pop_back();
    cSources = vecSources.size();

    HRESULT rc = S_OK;

    if (cSources > 1)
    {
        ComPtr<IGuestFsObjInfo> pFsObjInfo;
        rc = pCtx->pGuestSession->DirectoryQueryInfo(Bstr(strDest).raw(), pFsObjInfo.asOutParam());
        if (FAILED(rc))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "Destination must be a directory when specifying multiple sources\n");
    }

    /*
     * Rename (move) the entries.
     */
    if (pCtx->fVerbose && cSources)
        RTPrintf("Renaming %RU32 %s ...\n", cSources,
                   cSources > 1
                 ? "entries" : "entry");

    std::vector< Utf8Str >::iterator it = vecSources.begin();
    while (   (it != vecSources.end())
           && !g_fGuestCtrlCanceled)
    {
        bool fSourceIsDirectory = false;
        Utf8Str strCurSource = (*it);
        Utf8Str strCurDest = strDest;

        /** @todo Slooooow, but works for now. */
        ComPtr<IGuestFsObjInfo> pFsObjInfo;
        rc = pCtx->pGuestSession->FileQueryInfo(Bstr(strCurSource).raw(), pFsObjInfo.asOutParam());
        if (FAILED(rc))
        {
            rc = pCtx->pGuestSession->DirectoryQueryInfo(Bstr(strCurSource).raw(), pFsObjInfo.asOutParam());
            fSourceIsDirectory = SUCCEEDED(rc);
        }
        if (FAILED(rc))
        {
            if (pCtx->fVerbose)
                RTPrintf("Warning: Cannot stat for element \"%s\": No such element\n",
                         strCurSource.c_str());
            it++;
            continue; /* Skip. */
        }

        if (pCtx->fVerbose)
            RTPrintf("Renaming %s \"%s\" to \"%s\" ...\n",
                     fSourceIsDirectory ? "directory" : "file",
                     strCurSource.c_str(), strCurDest.c_str());

        if (!fDryrun)
        {
            if (fSourceIsDirectory)
            {
                CHECK_ERROR_BREAK(pCtx->pGuestSession, DirectoryRename(Bstr(strCurSource).raw(),
                                                                       Bstr(strCurDest).raw(),
                                                                       ComSafeArrayAsInParam(aRenameFlags)));

                /* Break here, since it makes no sense to rename mroe than one source to
                 * the same directory. */
                it = vecSources.end();
                break;
            }
            else
                CHECK_ERROR_BREAK(pCtx->pGuestSession, FileRename(Bstr(strCurSource).raw(),
                                                                  Bstr(strCurDest).raw(),
                                                                  ComSafeArrayAsInParam(aRenameFlags)));
        }

        it++;
    }

    if (   (it != vecSources.end())
        && pCtx->fVerbose)
    {
        RTPrintf("Warning: Not all sources were renamed\n");
    }

    return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlCreateTemp(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--mode",                'm',                             RTGETOPT_REQ_UINT32  },
        { "--directory",           'D',                             RTGETOPT_REQ_NOTHING },
        { "--secure",              's',                             RTGETOPT_REQ_NOTHING },
        { "--tmpdir",              't',                             RTGETOPT_REQ_STRING  }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    Utf8Str strTemplate;
    uint32_t fMode = 0; /* Default mode. */
    bool fDirectory = false;
    bool fSecure = false;
    Utf8Str strTempDir;

    DESTDIRMAP mapDirs;

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case 'm': /* Mode */
                fMode = ValueUnion.u32;
                break;

            case 'D': /* Create directory */
                fDirectory = true;
                break;

            case 's': /* Secure */
                fSecure = true;
                break;

            case 't': /* Temp directory */
                strTempDir = ValueUnion.psz;
                break;

            case VINF_GETOPT_NOT_OPTION:
            {
                if (strTemplate.isEmpty())
                    strTemplate = ValueUnion.psz;
                else
                    return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CREATETEMP,
                                         "More than one template specified!\n");
                break;
            }

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CREATETEMP, ch, &ValueUnion);
        }
    }

    if (strTemplate.isEmpty())
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CREATETEMP,
                             "No template specified!");

    if (!fDirectory)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CREATETEMP,
                             "Creating temporary files is currently not supported!");

    /*
     * Create the directories.
     */
    if (pCtx->fVerbose)
    {
        if (fDirectory && !strTempDir.isEmpty())
            RTPrintf("Creating temporary directory from template '%s' in directory '%s' ...\n",
                     strTemplate.c_str(), strTempDir.c_str());
        else if (fDirectory)
            RTPrintf("Creating temporary directory from template '%s' in default temporary directory ...\n",
                     strTemplate.c_str());
        else if (!fDirectory && !strTempDir.isEmpty())
            RTPrintf("Creating temporary file from template '%s' in directory '%s' ...\n",
                     strTemplate.c_str(), strTempDir.c_str());
        else if (!fDirectory)
            RTPrintf("Creating temporary file from template '%s' in default temporary directory ...\n",
                     strTemplate.c_str());
    }

    HRESULT rc = S_OK;
    if (fDirectory)
    {
        Bstr directory;
        CHECK_ERROR(pCtx->pGuestSession, DirectoryCreateTemp(Bstr(strTemplate).raw(),
                                                             fMode, Bstr(strTempDir).raw(),
                                                             fSecure,
                                                             directory.asOutParam()));
        if (SUCCEEDED(rc))
            RTPrintf("Directory name: %ls\n", directory.raw());
    }
    // else - temporary file not yet implemented

    return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlStat(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--dereference",         'L',                             RTGETOPT_REQ_NOTHING },
        { "--file-system",         'f',                             RTGETOPT_REQ_NOTHING },
        { "--format",              'c',                             RTGETOPT_REQ_STRING },
        { "--terse",               't',                             RTGETOPT_REQ_NOTHING }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    DESTDIRMAP mapObjs;

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case 'L': /* Dereference */
            case 'f': /* File-system */
            case 'c': /* Format */
            case 't': /* Terse */
                return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
                                     "Command \"%s\" not implemented yet!", ValueUnion.psz);

            case VINF_GETOPT_NOT_OPTION:
                mapObjs[ValueUnion.psz]; /* Add element to check to map. */
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT, ch, &ValueUnion);
        }
    }

    uint32_t cObjs = mapObjs.size();
    if (!cObjs)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
                             "No element(s) to check specified!");

    HRESULT rc;

    /*
     * Doing the checks.
     */
    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
    DESTDIRMAPITER it = mapObjs.begin();
    while (it != mapObjs.end())
    {
        if (pCtx->fVerbose)
            RTPrintf("Checking for element \"%s\" ...\n", it->first.c_str());

        ComPtr<IGuestFsObjInfo> pFsObjInfo;
        rc = pCtx->pGuestSession->FileQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
        if (FAILED(rc))
            rc = pCtx->pGuestSession->DirectoryQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());

        if (FAILED(rc))
        {
            /* If there's at least one element which does not exist on the guest,
             * drop out with exitcode 1. */
            if (pCtx->fVerbose)
                RTPrintf("Cannot stat for element \"%s\": No such element\n",
                         it->first.c_str());
            rcExit = RTEXITCODE_FAILURE;
        }
        else
        {
            FsObjType_T objType;
            pFsObjInfo->COMGETTER(Type)(&objType);
            switch (objType)
            {
                case FsObjType_File:
                    RTPrintf("Element \"%s\" found: Is a file\n", it->first.c_str());
                    break;

                case FsObjType_Directory:
                    RTPrintf("Element \"%s\" found: Is a directory\n", it->first.c_str());
                    break;

                case FsObjType_Symlink:
                    RTPrintf("Element \"%s\" found: Is a symlink\n", it->first.c_str());
                    break;

                default:
                    RTPrintf("Element \"%s\" found, type unknown (%ld)\n", it->first.c_str(), objType);
                    break;
            }

            /** @todo: Show more information about this element. */
        }

        it++;
    }

    return rcExit;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlUpdateAdditions(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    /*
     * Check the syntax.  We can deduce the correct syntax from the number of
     * arguments.
     */
    Utf8Str strSource;
    com::SafeArray<IN_BSTR> aArgs;
    bool fWaitStartOnly = false;

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--source",              's',         RTGETOPT_REQ_STRING  },
        { "--wait-start",          'w',         RTGETOPT_REQ_NOTHING }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv, s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, 0);

    int vrc = VINF_SUCCESS;
    while (   (ch = RTGetOpt(&GetState, &ValueUnion))
           && RT_SUCCESS(vrc))
    {
        switch (ch)
        {
            case 's':
                strSource = ValueUnion.psz;
                break;

            case 'w':
                fWaitStartOnly = true;
                break;

            case VINF_GETOPT_NOT_OPTION:
                if (aArgs.size() == 0 && strSource.isEmpty())
                    strSource = ValueUnion.psz;
                else
                    aArgs.push_back(Bstr(ValueUnion.psz).raw());
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEADDS, ch, &ValueUnion);
        }
    }

    if (pCtx->fVerbose)
        RTPrintf("Updating Guest Additions ...\n");

    HRESULT rc = S_OK;
    while (strSource.isEmpty())
    {
        ComPtr<ISystemProperties> pProperties;
        CHECK_ERROR_BREAK(pCtx->handlerArg.virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
        Bstr strISO;
        CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
        strSource = strISO;
        break;
    }

    /* Determine source if not set yet. */
    if (strSource.isEmpty())
    {
        RTMsgError("No Guest Additions source found or specified, aborting\n");
        vrc = VERR_FILE_NOT_FOUND;
    }
    else if (!RTFileExists(strSource.c_str()))
    {
        RTMsgError("Source \"%s\" does not exist!\n", strSource.c_str());
        vrc = VERR_FILE_NOT_FOUND;
    }

    if (RT_SUCCESS(vrc))
    {
        if (pCtx->fVerbose)
            RTPrintf("Using source: %s\n", strSource.c_str());

        com::SafeArray<AdditionsUpdateFlag_T> aUpdateFlags;
        if (fWaitStartOnly)
        {
            aUpdateFlags.push_back(AdditionsUpdateFlag_WaitForUpdateStartOnly);
            if (pCtx->fVerbose)
                RTPrintf("Preparing and waiting for Guest Additions installer to start ...\n");
        }

        ComPtr<IProgress> pProgress;
        CHECK_ERROR(pCtx->pGuest, UpdateGuestAdditions(Bstr(strSource).raw(),
                                                ComSafeArrayAsInParam(aArgs),
                                                /* Wait for whole update process to complete. */
                                                ComSafeArrayAsInParam(aUpdateFlags),
                                                pProgress.asOutParam()));
        if (FAILED(rc))
            vrc = ctrlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
        else
        {
            if (pCtx->fVerbose)
                rc = showProgress(pProgress);
            else
                rc = pProgress->WaitForCompletion(-1 /* No timeout */);

            if (SUCCEEDED(rc))
                CHECK_PROGRESS_ERROR(pProgress, ("Guest additions update failed"));
            vrc = ctrlPrintProgressError(pProgress);
            if (   RT_SUCCESS(vrc)
                && pCtx->fVerbose)
            {
                RTPrintf("Guest Additions update successful\n");
            }
        }
    }

    return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlList(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    if (pCtx->iArgc < 1)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST,
                             "Must specify a listing category");

    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;

    /** Use RTGetOpt here when handling command line args gets more complex. */

    bool fListAll = false;
    bool fListSessions = false;
    bool fListProcesses = false;
    bool fListFiles = false;
    if (   !RTStrICmp(pCtx->ppaArgv[0], "sessions")
        || !RTStrICmp(pCtx->ppaArgv[0], "sess"))
        fListSessions = true;
    else if (   !RTStrICmp(pCtx->ppaArgv[0], "processes")
             || !RTStrICmp(pCtx->ppaArgv[0], "procs"))
        fListSessions = fListProcesses = true; /* Showing processes implies showing sessions. */
    else if (   !RTStrICmp(pCtx->ppaArgv[0], "files"))
        fListSessions = fListFiles = true;     /* Showing files implies showing sessions. */
    else if (!RTStrICmp(pCtx->ppaArgv[0], "all"))
        fListAll = true;

    /** @todo Handle "--verbose" using RTGetOpt. */
    /** @todo Do we need a machine-readable output here as well? */

    if (   fListAll
        || fListSessions)
    {
        HRESULT rc;
        do
        {
            size_t cTotalProcs = 0;
            size_t cTotalFiles = 0;

            SafeIfaceArray <IGuestSession> collSessions;
            CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
            size_t cSessions = collSessions.size();

            if (cSessions)
            {
                RTPrintf("Active guest sessions:\n");

                /** @todo Make this output a bit prettier. No time now. */

                for (size_t i = 0; i < cSessions; i++)
                {
                    ComPtr<IGuestSession> pCurSession = collSessions[i];
                    if (!pCurSession.isNull())
                    {
                        ULONG uID;
                        CHECK_ERROR_BREAK(pCurSession, COMGETTER(Id)(&uID));
                        Bstr strName;
                        CHECK_ERROR_BREAK(pCurSession, COMGETTER(Name)(strName.asOutParam()));
                        Bstr strUser;
                        CHECK_ERROR_BREAK(pCurSession, COMGETTER(User)(strUser.asOutParam()));
                        GuestSessionStatus_T sessionStatus;
                        CHECK_ERROR_BREAK(pCurSession, COMGETTER(Status)(&sessionStatus));
                        RTPrintf("\n\tSession #%-3zu ID=%-3RU32 User=%-16ls Status=[%s] Name=%ls",
                                 i, uID, strUser.raw(), ctrlSessionStatusToText(sessionStatus), strName.raw());

                        if (   fListAll
                            || fListProcesses)
                        {
                            SafeIfaceArray <IGuestProcess> collProcesses;
                            CHECK_ERROR_BREAK(pCurSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcesses)));
                            for (size_t a = 0; a < collProcesses.size(); a++)
                            {
                                ComPtr<IGuestProcess> pCurProcess = collProcesses[a];
                                if (!pCurProcess.isNull())
                                {
                                    ULONG uPID;
                                    CHECK_ERROR_BREAK(pCurProcess, COMGETTER(PID)(&uPID));
                                    Bstr strExecPath;
                                    CHECK_ERROR_BREAK(pCurProcess, COMGETTER(ExecutablePath)(strExecPath.asOutParam()));
                                    ProcessStatus_T procStatus;
                                    CHECK_ERROR_BREAK(pCurProcess, COMGETTER(Status)(&procStatus));

                                    RTPrintf("\n\t\tProcess #%-03zu PID=%-6RU32 Status=[%s] Command=%ls",
                                             a, uPID, ctrlProcessStatusToText(procStatus), strExecPath.raw());
                                }
                            }

                            cTotalProcs += collProcesses.size();
                        }

                        if (   fListAll
                            || fListFiles)
                        {
                            SafeIfaceArray <IGuestFile> collFiles;
                            CHECK_ERROR_BREAK(pCurSession, COMGETTER(Files)(ComSafeArrayAsOutParam(collFiles)));
                            for (size_t a = 0; a < collFiles.size(); a++)
                            {
                                ComPtr<IGuestFile> pCurFile = collFiles[a];
                                if (!pCurFile.isNull())
                                {
                                    CHECK_ERROR_BREAK(pCurFile, COMGETTER(Id)(&uID));
                                    CHECK_ERROR_BREAK(pCurFile, COMGETTER(FileName)(strName.asOutParam()));
                                    FileStatus_T fileStatus;
                                    CHECK_ERROR_BREAK(pCurFile, COMGETTER(Status)(&fileStatus));

                                    RTPrintf("\n\t\tFile #%-03zu ID=%-6RU32 Status=[%s] Name=%ls",
                                             a, uID, ctrlFileStatusToText(fileStatus), strName.raw());
                                }
                            }

                            cTotalFiles += collFiles.size();
                        }
                    }
                }

                RTPrintf("\n\nTotal guest sessions: %zu\n", collSessions.size());
                if (fListAll || fListProcesses)
                    RTPrintf("Total guest processes: %zu\n", cTotalProcs);
                if (fListAll || fListFiles)
                    RTPrintf("Total guest files: %zu\n", cTotalFiles);
            }
            else
                RTPrintf("No active guest sessions found\n");

        } while (0);

        if (FAILED(rc))
            rcExit = RTEXITCODE_FAILURE;
    }
    else
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST,
                             "Invalid listing category '%s", pCtx->ppaArgv[0]);

    return rcExit;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlProcessClose(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    if (pCtx->iArgc < 1)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                             "Must specify at least a PID to close");

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--session-id",          'i',                             RTGETOPT_REQ_UINT32  },
        { "--session-name",        'n',                             RTGETOPT_REQ_STRING  }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    std::vector < uint32_t > vecPID;
    ULONG ulSessionID = UINT32_MAX;
    Utf8Str strSessionName;

    int vrc = VINF_SUCCESS;

    while (   (ch = RTGetOpt(&GetState, &ValueUnion))
           && RT_SUCCESS(vrc))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case 'n': /* Session name (or pattern) */
                strSessionName = ValueUnion.psz;
                break;

            case 'i': /* Session ID */
                ulSessionID = ValueUnion.u32;
                break;

            case VINF_GETOPT_NOT_OPTION:
                if (pCtx->iArgc == GetState.iNext)
                {
                    /* Treat every else specified as a PID to kill. */
                    try
                    {
                        uint32_t uPID = RTStrToUInt32(ValueUnion.psz);
                        if (uPID) /** @todo Is this what we want? If specifying PID 0
                                            this is not going to work on most systems anyway. */
                            vecPID.push_back(uPID);
                        else
                            vrc = VERR_INVALID_PARAMETER;
                    }
                    catch(std::bad_alloc &)
                    {
                        vrc = VERR_NO_MEMORY;
                    }
                }
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS, ch, &ValueUnion);
        }
    }

    if (vecPID.empty())
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                             "At least one PID must be specified to kill!");

    if (   strSessionName.isEmpty()
        && ulSessionID == UINT32_MAX)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                             "No session ID specified!");

    if (   !strSessionName.isEmpty()
        && ulSessionID != UINT32_MAX)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                             "Either session ID or name (pattern) must be specified");

    if (RT_FAILURE(vrc))
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                             "Invalid parameters specified");

    HRESULT rc = S_OK;

    ComPtr<IGuestSession> pSession;
    ComPtr<IGuestProcess> pProcess;
    do
    {
        uint32_t uProcsTerminated = 0;
        bool fSessionFound = false;

        SafeIfaceArray <IGuestSession> collSessions;
        CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
        size_t cSessions = collSessions.size();

        uint32_t uSessionsHandled = 0;
        for (size_t i = 0; i < cSessions; i++)
        {
            pSession = collSessions[i];
            Assert(!pSession.isNull());

            ULONG uID; /* Session ID */
            CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
            Bstr strName;
            CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
            Utf8Str strNameUtf8(strName); /* Session name */
            if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
            {
                fSessionFound = uID == ulSessionID;
            }
            else /* ... or by naming pattern. */
            {
                if (RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str()))
                    fSessionFound = true;
            }

            if (fSessionFound)
            {
                AssertStmt(!pSession.isNull(), break);
                uSessionsHandled++;

                SafeIfaceArray <IGuestProcess> collProcs;
                CHECK_ERROR_BREAK(pSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcs)));

                size_t cProcs = collProcs.size();
                for (size_t p = 0; p < cProcs; p++)
                {
                    pProcess = collProcs[p];
                    Assert(!pProcess.isNull());

                    ULONG uPID; /* Process ID */
                    CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));

                    bool fProcFound = false;
                    for (size_t a = 0; a < vecPID.size(); a++) /* Slow, but works. */
                    {
                        fProcFound = vecPID[a] == uPID;
                        if (fProcFound)
                            break;
                    }

                    if (fProcFound)
                    {
                        if (pCtx->fVerbose)
                            RTPrintf("Terminating process (PID %RU32) (session ID %RU32) ...\n",
                                     uPID, uID);
                        CHECK_ERROR_BREAK(pProcess, Terminate());
                        uProcsTerminated++;
                    }
                    else
                    {
                        if (ulSessionID != UINT32_MAX)
                            RTPrintf("No matching process(es) for session ID %RU32 found\n",
                                     ulSessionID);
                    }

                    pProcess.setNull();
                }

                pSession.setNull();
            }
        }

        if (!uSessionsHandled)
            RTPrintf("No matching session(s) found\n");

        if (uProcsTerminated)
            RTPrintf("%RU32 %s terminated\n",
                     uProcsTerminated, uProcsTerminated == 1 ? "process" : "processes");

    } while (0);

    pProcess.setNull();
    pSession.setNull();

    return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlProcess(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    if (pCtx->iArgc < 1)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                             "Must specify an action");

    /** Use RTGetOpt here when handling command line args gets more complex. */

    if (   !RTStrICmp(pCtx->ppaArgv[0], "close")
        || !RTStrICmp(pCtx->ppaArgv[0], "kill")
        || !RTStrICmp(pCtx->ppaArgv[0], "terminate"))
    {
        pCtx->iFirstArgc++; /* Skip process action. */
        return handleCtrlProcessClose(pCtx);
    }

    return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_PROCESS,
                         "Invalid process action '%s'", pCtx->ppaArgv[0]);
}

static DECLCALLBACK(RTEXITCODE) handleCtrlSessionClose(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    if (pCtx->iArgc < 1)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_SESSION,
                             "Must specify at least a session to close");

    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--all",                 GETOPTDEF_SESSIONCLOSE_ALL,      RTGETOPT_REQ_NOTHING  },
        { "--session-id",          'i',                             RTGETOPT_REQ_UINT32  },
        { "--session-name",        'n',                             RTGETOPT_REQ_STRING  }
    };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 s_aOptions, RT_ELEMENTS(s_aOptions), pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    ULONG ulSessionID = UINT32_MAX;
    Utf8Str strSessionName;

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case 'n': /* Session name pattern */
                strSessionName = ValueUnion.psz;
                break;

            case 'i': /* Session ID */
                ulSessionID = ValueUnion.u32;
                break;

            case GETOPTDEF_SESSIONCLOSE_ALL:
                strSessionName = "*";
                break;

            case VINF_GETOPT_NOT_OPTION:
                /** @todo Supply a CSV list of IDs or patterns to close? */
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_SESSION, ch, &ValueUnion);
        }
    }

    if (   strSessionName.isEmpty()
        && ulSessionID == UINT32_MAX)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_SESSION,
                             "No session ID specified!");

    if (   !strSessionName.isEmpty()
        && ulSessionID != UINT32_MAX)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_SESSION,
                             "Either session ID or name (pattern) must be specified");

    HRESULT rc = S_OK;

    do
    {
        bool fSessionFound = false;
        size_t cSessionsHandled = 0;

        SafeIfaceArray <IGuestSession> collSessions;
        CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
        size_t cSessions = collSessions.size();

        for (size_t i = 0; i < cSessions; i++)
        {
            ComPtr<IGuestSession> pSession = collSessions[i];
            Assert(!pSession.isNull());

            ULONG uID; /* Session ID */
            CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
            Bstr strName;
            CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
            Utf8Str strNameUtf8(strName); /* Session name */

            if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
            {
                fSessionFound = uID == ulSessionID;
            }
            else /* ... or by naming pattern. */
            {
                if (RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str()))
                    fSessionFound = true;
            }

            if (fSessionFound)
            {
                cSessionsHandled++;

                Assert(!pSession.isNull());
                if (pCtx->fVerbose)
                    RTPrintf("Closing guest session ID=#%RU32 \"%s\" ...\n",
                             uID, strNameUtf8.c_str());
                CHECK_ERROR_BREAK(pSession, Close());
                if (pCtx->fVerbose)
                    RTPrintf("Guest session successfully closed\n");

                pSession.setNull();
            }
        }

        if (!cSessionsHandled)
        {
            RTPrintf("No guest session(s) found\n");
            rc = E_ABORT; /* To set exit code accordingly. */
        }

    } while (0);

    return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}

static DECLCALLBACK(RTEXITCODE) handleCtrlSession(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    if (pCtx->iArgc < 1)
        return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_SESSION,
                             "Must specify an action");

    /** Use RTGetOpt here when handling command line args gets more complex. */

    if (   !RTStrICmp(pCtx->ppaArgv[0], "close")
        || !RTStrICmp(pCtx->ppaArgv[0], "kill")
        || !RTStrICmp(pCtx->ppaArgv[0], "terminate"))
    {
        pCtx->iFirstArgc++; /* Skip session action. */
        return handleCtrlSessionClose(pCtx);
    }

    return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_SESSION,
                         "Invalid session action '%s'", pCtx->ppaArgv[0]);
}

static DECLCALLBACK(RTEXITCODE) handleCtrlWatch(PGCTLCMDCTX pCtx)
{
    AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);

    /*
     * Parse arguments.
     */
    static const RTGETOPTDEF s_aOptions[] = { 0 };

    int ch;
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, pCtx->iArgc, pCtx->ppaArgv,
                 NULL /*s_aOptions*/, 0 /*RT_ELEMENTS(s_aOptions)*/, pCtx->iFirstArgc, RTGETOPTINIT_FLAGS_OPTS_FIRST);

    while ((ch = RTGetOpt(&GetState, &ValueUnion)))
    {
        /* For options that require an argument, ValueUnion has received the value. */
        switch (ch)
        {
            case VINF_GETOPT_NOT_OPTION:
                break;

            default:
                return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_WATCH, ch, &ValueUnion);
        }
    }

    /** @todo Specify categories to watch for. */
    /** @todo Specify a --timeout for waiting only for a certain amount of time? */

    HRESULT rc;

    try
    {
        ComObjPtr<GuestEventListenerImpl> pGuestListener;
        do
        {
            /* Listener creation. */
            pGuestListener.createObject();
            pGuestListener->init(new GuestEventListener());

            /* Register for IGuest events. */
            ComPtr<IEventSource> es;
            CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
            com::SafeArray<VBoxEventType_T> eventTypes;
            eventTypes.push_back(VBoxEventType_OnGuestSessionRegistered);
            /** @todo Also register for VBoxEventType_OnGuestUserStateChanged on demand? */
            CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
                                                   true /* Active listener */));
            /* Note: All other guest control events have to be registered
             *       as their corresponding objects appear. */

        } while (0);

        if (pCtx->fVerbose)
            RTPrintf("Waiting for events ...\n");

        while (!g_fGuestCtrlCanceled)
        {
            /** @todo Timeout handling (see above)? */
            RTThreadSleep(10);
        }

        if (pCtx->fVerbose)
            RTPrintf("Signal caught, exiting ...\n");

        if (!pGuestListener.isNull())
        {
            /* Guest callback unregistration. */
            ComPtr<IEventSource> pES;
            CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
            if (!pES.isNull())
                CHECK_ERROR(pES, UnregisterListener(pGuestListener));
            pGuestListener.setNull();
        }
    }
    catch (std::bad_alloc &)
    {
        rc = E_OUTOFMEMORY;
    }

    return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
}

/**
 * Access the guest control store.
 *
 * @returns program exit code.
 * @note see the command line API description for parameters
 */
int handleGuestControl(HandlerArg *pArg)
{
    AssertPtrReturn(pArg, VERR_INVALID_POINTER);

#ifdef DEBUG_andy_disabled
    if (RT_FAILURE(tstTranslatePath()))
        return RTEXITCODE_FAILURE;
#endif

    /* pArg->argv[0] contains the VM name. */
    /* pArg->argv[1] contains the guest control command. */
    if (pArg->argc < 2)
        return errorSyntax(USAGE_GUESTCONTROL, "No sub command specified!");

    uint32_t uCmdCtxFlags = 0;
    uint32_t uUsage;
    GCTLCMD gctlCmd;
    if (   !RTStrICmp(pArg->argv[1], "exec")
        || !RTStrICmp(pArg->argv[1], "execute"))
    {
        gctlCmd.pfnHandler = handleCtrlProcessExec;
        uUsage = USAGE_GSTCTRL_EXEC;
    }
    else if (!RTStrICmp(pArg->argv[1], "copyfrom"))
    {
        gctlCmd.pfnHandler = handleCtrlCopyFrom;
        uUsage = USAGE_GSTCTRL_COPYFROM;
    }
    else if (   !RTStrICmp(pArg->argv[1], "copyto")
             || !RTStrICmp(pArg->argv[1], "cp"))
    {
        gctlCmd.pfnHandler = handleCtrlCopyTo;
        uUsage = USAGE_GSTCTRL_COPYTO;
    }
    else if (   !RTStrICmp(pArg->argv[1], "createdirectory")
             || !RTStrICmp(pArg->argv[1], "createdir")
             || !RTStrICmp(pArg->argv[1], "mkdir")
             || !RTStrICmp(pArg->argv[1], "md"))
    {
        gctlCmd.pfnHandler = handleCtrlCreateDirectory;
        uUsage = USAGE_GSTCTRL_CREATEDIR;
    }
    else if (   !RTStrICmp(pArg->argv[1], "removedirectory")
             || !RTStrICmp(pArg->argv[1], "removedir")
             || !RTStrICmp(pArg->argv[1], "rmdir"))
    {
        gctlCmd.pfnHandler = handleCtrlRemoveDirectory;
        uUsage = USAGE_GSTCTRL_REMOVEDIR;
    }
    else if (   !RTStrICmp(pArg->argv[1], "rm")
             || !RTStrICmp(pArg->argv[1], "removefile"))
    {
        gctlCmd.pfnHandler = handleCtrlRemoveFile;
        uUsage = USAGE_GSTCTRL_REMOVEFILE;
    }
    else if (   !RTStrICmp(pArg->argv[1], "ren")
             || !RTStrICmp(pArg->argv[1], "rename")
             || !RTStrICmp(pArg->argv[1], "mv"))
    {
        gctlCmd.pfnHandler = handleCtrlRename;
        uUsage = USAGE_GSTCTRL_RENAME;
    }
    else if (   !RTStrICmp(pArg->argv[1], "createtemporary")
             || !RTStrICmp(pArg->argv[1], "createtemp")
             || !RTStrICmp(pArg->argv[1], "mktemp"))
    {
        gctlCmd.pfnHandler = handleCtrlCreateTemp;
        uUsage = USAGE_GSTCTRL_CREATETEMP;
    }
    else if (   !RTStrICmp(pArg->argv[1], "kill")    /* Linux. */
             || !RTStrICmp(pArg->argv[1], "pkill")   /* Solaris / *BSD. */
             || !RTStrICmp(pArg->argv[1], "pskill")) /* SysInternals version. */
    {
        /** @todo What about "taskkill" on Windows? */
        uCmdCtxFlags = CTLCMDCTX_FLAGS_SESSION_ANONYMOUS
                     | CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER;
        gctlCmd.pfnHandler = handleCtrlProcessClose;
        uUsage = USAGE_GSTCTRL_KILL;
    }
    /** @todo Implement "killall"? */
    else if (   !RTStrICmp(pArg->argv[1], "stat"))
    {
        gctlCmd.pfnHandler = handleCtrlStat;
        uUsage = USAGE_GSTCTRL_STAT;
    }
    else if (   !RTStrICmp(pArg->argv[1], "updateadditions")
             || !RTStrICmp(pArg->argv[1], "updateadds"))
    {
        uCmdCtxFlags = CTLCMDCTX_FLAGS_SESSION_ANONYMOUS
                     | CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER;
        gctlCmd.pfnHandler = handleCtrlUpdateAdditions;
        uUsage = USAGE_GSTCTRL_UPDATEADDS;
    }
    else if (   !RTStrICmp(pArg->argv[1], "list"))
    {
        uCmdCtxFlags = CTLCMDCTX_FLAGS_SESSION_ANONYMOUS
                     | CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER;
        gctlCmd.pfnHandler = handleCtrlList;
        uUsage = USAGE_GSTCTRL_LIST;
    }
    else if (   !RTStrICmp(pArg->argv[1], "session"))
    {
        uCmdCtxFlags = CTLCMDCTX_FLAGS_SESSION_ANONYMOUS
                     | CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER;
        gctlCmd.pfnHandler = handleCtrlSession;
        uUsage = USAGE_GSTCTRL_SESSION;
    }
    else if (   !RTStrICmp(pArg->argv[1], "process"))
    {
        uCmdCtxFlags = CTLCMDCTX_FLAGS_SESSION_ANONYMOUS
                     | CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER;
        gctlCmd.pfnHandler = handleCtrlProcess;
        uUsage = USAGE_GSTCTRL_PROCESS;
    }
    else if (   !RTStrICmp(pArg->argv[1], "watch"))
    {
        uCmdCtxFlags = CTLCMDCTX_FLAGS_SESSION_ANONYMOUS
                     | CTLCMDCTX_FLAGS_NO_SIGNAL_HANDLER;
        gctlCmd.pfnHandler = handleCtrlWatch;
        uUsage = USAGE_GSTCTRL_WATCH;
    }
    else
        return errorSyntax(USAGE_GUESTCONTROL, "Unknown sub command '%s' specified!", pArg->argv[1]);

    GCTLCMDCTX cmdCtx;
    RT_ZERO(cmdCtx);

    RTEXITCODE rcExit = ctrlInitVM(pArg, &cmdCtx, uCmdCtxFlags, uUsage);
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        /* Kick off the actual command handler. */
        rcExit = gctlCmd.pfnHandler(&cmdCtx);

        ctrlUninitVM(&cmdCtx, cmdCtx.uFlags);
        return rcExit;
    }

    return rcExit;
}
#endif /* !VBOX_ONLY_DOCS */