summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-client/GuestSessionImpl.cpp
blob: dd758cacb4fef10e65b985170d2b5da188f4c08d (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
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
/* $Id: GuestSessionImpl.cpp $ */
/** @file
 * VirtualBox Main - Guest session handling.
 */

/*
 * Copyright (C) 2012-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_MAIN_GUESTSESSION
#include "LoggingNew.h"

#include "GuestImpl.h"
#ifndef VBOX_WITH_GUEST_CONTROL
# error "VBOX_WITH_GUEST_CONTROL must defined in this file"
#endif
#include "GuestSessionImpl.h"
#include "GuestSessionImplTasks.h"
#include "GuestCtrlImplPrivate.h"
#include "VirtualBoxErrorInfoImpl.h"

#include "Global.h"
#include "AutoCaller.h"
#include "ProgressImpl.h"
#include "VBoxEvents.h"
#include "VMMDev.h"
#include "ThreadTask.h"

#include <memory> /* For auto_ptr. */

#include <iprt/cpp/utils.h> /* For unconst(). */
#include <iprt/ctype.h>
#include <iprt/env.h>
#include <iprt/file.h> /* For CopyTo/From. */
#include <iprt/path.h>
#include <iprt/rand.h>

#include <VBox/com/array.h>
#include <VBox/com/listeners.h>
#include <VBox/version.h>


/**
 * Base class representing an internal
 * asynchronous session task.
 */
class GuestSessionTaskInternal : public ThreadTask
{
public:

    GuestSessionTaskInternal(GuestSession *pSession)
        : ThreadTask("GenericGuestSessionTaskInternal")
        , mSession(pSession)
        , mVrc(VINF_SUCCESS) { }

    virtual ~GuestSessionTaskInternal(void) { }

    /** Returns the last set result code. */
    int vrc(void) const { return mVrc; }
    /** Returns whether the last set result code indicates success or not. */
    bool isOk(void) const { return RT_SUCCESS(mVrc); }
    /** Returns the task's guest session object. */
    const ComObjPtr<GuestSession> &Session(void) const { return mSession; }

protected:

    /** Guest session the task belongs to. */
    const ComObjPtr<GuestSession>    mSession;
    /** The last set VBox status code. */
    int                              mVrc;
};

/**
 * Class for asynchronously starting a guest session.
 */
class GuestSessionTaskInternalStart : public GuestSessionTaskInternal
{
public:

    GuestSessionTaskInternalStart(GuestSession *pSession)
        : GuestSessionTaskInternal(pSession)
    {
        m_strTaskName = "gctlSesStart";
    }

    void handler()
    {
        /* Ignore return code */
        GuestSession::i_startSessionThreadTask(this);
    }
};

/**
 * Internal listener class to serve events in an
 * active manner, e.g. without polling delays.
 */
class GuestSessionListener
{
public:

    GuestSessionListener(void)
    {
    }

    virtual ~GuestSessionListener(void)
    {
    }

    HRESULT init(GuestSession *pSession)
    {
        AssertPtrReturn(pSession, E_POINTER);
        mSession = pSession;
        return S_OK;
    }

    void uninit(void)
    {
        mSession = NULL;
    }

    STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
    {
        switch (aType)
        {
            case VBoxEventType_OnGuestSessionStateChanged:
            {
                AssertPtrReturn(mSession, E_POINTER);
                int vrc2 = mSession->signalWaitEvent(aType, aEvent);
                RT_NOREF(vrc2);
#ifdef DEBUG_andy
                LogFlowFunc(("Signalling events of type=%RU32, session=%p resulted in vrc2=%Rrc\n", aType, mSession, vrc2));
#endif
                break;
            }

            default:
                AssertMsgFailed(("Unhandled event %RU32\n", aType));
                break;
        }

        return S_OK;
    }

private:

    GuestSession *mSession;
};
typedef ListenerImpl<GuestSessionListener, GuestSession*> GuestSessionListenerImpl;

VBOX_LISTENER_DECLARE(GuestSessionListenerImpl)

// constructor / destructor
/////////////////////////////////////////////////////////////////////////////

DEFINE_EMPTY_CTOR_DTOR(GuestSession)

HRESULT GuestSession::FinalConstruct(void)
{
    LogFlowThisFuncEnter();
    return BaseFinalConstruct();
}

void GuestSession::FinalRelease(void)
{
    LogFlowThisFuncEnter();
    uninit();
    BaseFinalRelease();
    LogFlowThisFuncLeave();
}

// public initializer/uninitializer for internal purposes only
/////////////////////////////////////////////////////////////////////////////

/**
 * Initializes a guest session but does *not* open in on the guest side
 * yet. This needs to be done via the openSession() / openSessionAsync calls.
 *
 * @returns VBox status code.
 * @param   pGuest              Guest object the guest session belongs to.
 * @param   ssInfo              Guest session startup info to use.
 * @param   guestCreds          Guest credentials to use for starting a guest session
 *                              with a specific guest account.
 */
int GuestSession::init(Guest *pGuest, const GuestSessionStartupInfo &ssInfo,
                       const GuestCredentials &guestCreds)
{
    LogFlowThisFunc(("pGuest=%p, ssInfo=%p, guestCreds=%p\n",
                      pGuest, &ssInfo, &guestCreds));

    /* Enclose the state transition NotReady->InInit->Ready. */
    AutoInitSpan autoInitSpan(this);
    AssertReturn(autoInitSpan.isOk(), VERR_OBJECT_DESTROYED);

    AssertPtrReturn(pGuest, VERR_INVALID_POINTER);

    /*
     * Initialize our data members from the input.
     */
    mParent = pGuest;

    /* Copy over startup info. */
    /** @todo Use an overloaded copy operator. Later. */
    mData.mSession.mID = ssInfo.mID;
    mData.mSession.mIsInternal = ssInfo.mIsInternal;
    mData.mSession.mName = ssInfo.mName;
    mData.mSession.mOpenFlags = ssInfo.mOpenFlags;
    mData.mSession.mOpenTimeoutMS = ssInfo.mOpenTimeoutMS;

    /* Copy over session credentials. */
    /** @todo Use an overloaded copy operator. Later. */
    mData.mCredentials.mUser = guestCreds.mUser;
    mData.mCredentials.mPassword = guestCreds.mPassword;
    mData.mCredentials.mDomain = guestCreds.mDomain;

    /* Initialize the remainder of the data. */
    mData.mVrc = VINF_SUCCESS;
    mData.mStatus = GuestSessionStatus_Undefined;
    mData.mpBaseEnvironment = NULL;

    /*
     * Register an object for the session itself to clearly
     * distinguish callbacks which are for this session directly, or for
     * objects (like files, directories, ...) which are bound to this session.
     */
    int vrc = i_objectRegister(NULL /* pObject */, SESSIONOBJECTTYPE_SESSION, &mData.mObjectID);
    if (RT_SUCCESS(vrc))
    {
        vrc = mData.mEnvironmentChanges.initChangeRecord(pGuest->i_isGuestInWindowsNtFamily()
                                                         ? RTENV_CREATE_F_ALLOW_EQUAL_FIRST_IN_VAR : 0);
        if (RT_SUCCESS(vrc))
        {
            vrc = RTCritSectInit(&mWaitEventCritSect);
            AssertRC(vrc);
        }
    }

    if (RT_SUCCESS(vrc))
        vrc = i_determineProtocolVersion();

    if (RT_SUCCESS(vrc))
    {
        /*
         * <Replace this if you figure out what the code is doing.>
         */
        HRESULT hrc = unconst(mEventSource).createObject();
        if (SUCCEEDED(hrc))
            hrc = mEventSource->init();
        if (SUCCEEDED(hrc))
        {
            try
            {
                GuestSessionListener *pListener = new GuestSessionListener();
                ComObjPtr<GuestSessionListenerImpl> thisListener;
                hrc = thisListener.createObject();
                if (SUCCEEDED(hrc))
                    hrc = thisListener->init(pListener, this); /* thisListener takes ownership of pListener. */
                if (SUCCEEDED(hrc))
                {
                    com::SafeArray <VBoxEventType_T> eventTypes;
                    eventTypes.push_back(VBoxEventType_OnGuestSessionStateChanged);
                    hrc = mEventSource->RegisterListener(thisListener,
                                                         ComSafeArrayAsInParam(eventTypes),
                                                         TRUE /* Active listener */);
                    if (SUCCEEDED(hrc))
                    {
                        mLocalListener = thisListener;

                        /*
                         * Mark this object as operational and return success.
                         */
                        autoInitSpan.setSucceeded();
                        LogFlowThisFunc(("mName=%s mID=%RU32 mIsInternal=%RTbool vrc=VINF_SUCCESS\n",
                                         mData.mSession.mName.c_str(), mData.mSession.mID, mData.mSession.mIsInternal));
                        return VINF_SUCCESS;
                    }
                }
            }
            catch (std::bad_alloc &)
            {
                hrc = E_OUTOFMEMORY;
            }
        }
        vrc = Global::vboxStatusCodeFromCOM(hrc);
    }

    autoInitSpan.setFailed();
    LogThisFunc(("Failed! mName=%s mID=%RU32 mIsInternal=%RTbool => vrc=%Rrc\n",
                 mData.mSession.mName.c_str(), mData.mSession.mID, mData.mSession.mIsInternal, vrc));
    return vrc;
}

/**
 * Uninitializes the instance.
 * Called from FinalRelease().
 */
void GuestSession::uninit(void)
{
    /* Enclose the state transition Ready->InUninit->NotReady. */
    AutoUninitSpan autoUninitSpan(this);
    if (autoUninitSpan.uninitDone())
        return;

    LogFlowThisFuncEnter();

    /* Call i_onRemove to take care of the object cleanups. */
    i_onRemove();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Unregister the session's object ID. */
    i_objectUnregister(mData.mObjectID);

    Assert(mData.mObjects.size () == 0);
    mData.mObjects.clear();

    mData.mEnvironmentChanges.reset();

    if (mData.mpBaseEnvironment)
    {
        mData.mpBaseEnvironment->releaseConst();
        mData.mpBaseEnvironment = NULL;
    }

    /* Unitialize our local listener. */
    mLocalListener.setNull();

    baseUninit();

    LogFlowFuncLeave();
}

// implementation of public getters/setters for attributes
/////////////////////////////////////////////////////////////////////////////

HRESULT GuestSession::getUser(com::Utf8Str &aUser)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aUser = mData.mCredentials.mUser;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getDomain(com::Utf8Str &aDomain)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aDomain = mData.mCredentials.mDomain;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getName(com::Utf8Str &aName)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aName = mData.mSession.mName;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getId(ULONG *aId)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    *aId = mData.mSession.mID;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getStatus(GuestSessionStatus_T *aStatus)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    *aStatus = mData.mStatus;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getTimeout(ULONG *aTimeout)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    *aTimeout = mData.mTimeout;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::setTimeout(ULONG aTimeout)
{
    LogFlowThisFuncEnter();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    mData.mTimeout = aTimeout;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getProtocolVersion(ULONG *aProtocolVersion)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    *aProtocolVersion = mData.mProtocolVersion;

    LogFlowThisFuncLeave();
    return S_OK;
}

HRESULT GuestSession::getEnvironmentChanges(std::vector<com::Utf8Str> &aEnvironmentChanges)
{
    LogFlowThisFuncEnter();

    int vrc;
    {
        AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
        vrc = mData.mEnvironmentChanges.queryPutEnvArray(&aEnvironmentChanges);
    }

    LogFlowFuncLeaveRC(vrc);
    return Global::vboxStatusCodeToCOM(vrc);
}

HRESULT GuestSession::setEnvironmentChanges(const std::vector<com::Utf8Str> &aEnvironmentChanges)
{
    LogFlowThisFuncEnter();

    int vrc;
    size_t idxError = ~(size_t)0;
    {
        AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
        mData.mEnvironmentChanges.reset();
        vrc = mData.mEnvironmentChanges.applyPutEnvArray(aEnvironmentChanges, &idxError);
    }

    LogFlowFuncLeaveRC(vrc);
    if (RT_SUCCESS(vrc))
        return S_OK;
    if (vrc == VERR_ENV_INVALID_VAR_NAME)
        return setError(E_INVALIDARG, tr("Invalid environment variable name '%s', index %zu"),
                        aEnvironmentChanges[idxError].c_str(), idxError);
    return setErrorBoth(Global::vboxStatusCodeToCOM(vrc), vrc, tr("Failed to apply '%s', index %zu (%Rrc)"),
                        aEnvironmentChanges[idxError].c_str(), idxError, vrc);
}

HRESULT GuestSession::getEnvironmentBase(std::vector<com::Utf8Str> &aEnvironmentBase)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
    HRESULT hrc;
    if (mData.mpBaseEnvironment)
    {
        int vrc = mData.mpBaseEnvironment->queryPutEnvArray(&aEnvironmentBase);
        hrc = Global::vboxStatusCodeToCOM(vrc);
    }
    else if (mData.mProtocolVersion < 99999)
        hrc = setError(VBOX_E_NOT_SUPPORTED, tr("The base environment feature is not supported by the Guest Additions"));
    else
        hrc = setError(VBOX_E_INVALID_OBJECT_STATE, tr("The base environment has not yet been reported by the guest"));

    LogFlowFuncLeave();
    return hrc;
}

HRESULT GuestSession::getProcesses(std::vector<ComPtr<IGuestProcess> > &aProcesses)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aProcesses.resize(mData.mProcesses.size());
    size_t i = 0;
    for (SessionProcesses::iterator it  = mData.mProcesses.begin();
                                    it != mData.mProcesses.end();
                                    ++it, ++i)
    {
        it->second.queryInterfaceTo(aProcesses[i].asOutParam());
    }

    LogFlowFunc(("mProcesses=%zu\n", aProcesses.size()));
    return S_OK;
}

HRESULT GuestSession::getPathStyle(PathStyle_T *aPathStyle)
{
    *aPathStyle = i_getGuestPathStyle();
    return S_OK;
}

HRESULT GuestSession::getCurrentDirectory(com::Utf8Str &aCurrentDirectory)
{
    RT_NOREF(aCurrentDirectory);
    ReturnComNotImplemented();
}

HRESULT GuestSession::setCurrentDirectory(const com::Utf8Str &aCurrentDirectory)
{
    RT_NOREF(aCurrentDirectory);
    ReturnComNotImplemented();
}

HRESULT GuestSession::getUserHome(com::Utf8Str &aUserHome)
{
    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_pathUserHome(aUserHome, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        switch (vrc)
        {
            case VERR_GSTCTL_GUEST_ERROR:
            {
                switch (vrcGuest)
                {
                    case VERR_NOT_SUPPORTED:
                        hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest,
                                          tr("Getting the user's home path is not supported by installed Guest Additions"));
                        break;

                    default:
                        hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest,
                                          tr("Getting the user's home path failed on the guest: %Rrc"), vrcGuest);
                        break;
                }
                break;
            }

            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Getting the user's home path failed: %Rrc"), vrc);
                break;
        }
    }

    return hrc;
}

HRESULT GuestSession::getUserDocuments(com::Utf8Str &aUserDocuments)
{
    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_pathUserDocuments(aUserDocuments, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        switch (vrc)
        {
            case VERR_GSTCTL_GUEST_ERROR:
            {
                switch (vrcGuest)
                {
                    case VERR_NOT_SUPPORTED:
                        hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest,
                                          tr("Getting the user's documents path is not supported by installed Guest Additions"));
                        break;

                    default:
                        hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest,
                                          tr("Getting the user's documents path failed on the guest: %Rrc"), vrcGuest);
                        break;
                }
                break;
            }

            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Getting the user's documents path failed: %Rrc"), vrc);
                break;
        }
    }

    return hrc;
}

HRESULT GuestSession::getDirectories(std::vector<ComPtr<IGuestDirectory> > &aDirectories)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aDirectories.resize(mData.mDirectories.size());
    size_t i = 0;
    for (SessionDirectories::iterator it = mData.mDirectories.begin(); it != mData.mDirectories.end(); ++it, ++i)
    {
        it->second.queryInterfaceTo(aDirectories[i].asOutParam());
    }

    LogFlowFunc(("mDirectories=%zu\n", aDirectories.size()));
    return S_OK;
}

HRESULT GuestSession::getFiles(std::vector<ComPtr<IGuestFile> > &aFiles)
{
    LogFlowThisFuncEnter();

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    aFiles.resize(mData.mFiles.size());
    size_t i = 0;
    for(SessionFiles::iterator it = mData.mFiles.begin(); it != mData.mFiles.end(); ++it, ++i)
        it->second.queryInterfaceTo(aFiles[i].asOutParam());

    LogFlowFunc(("mDirectories=%zu\n", aFiles.size()));

    return S_OK;
}

HRESULT GuestSession::getEventSource(ComPtr<IEventSource> &aEventSource)
{
    LogFlowThisFuncEnter();

    // no need to lock - lifetime constant
    mEventSource.queryInterfaceTo(aEventSource.asOutParam());

    LogFlowThisFuncLeave();
    return S_OK;
}

// private methods
///////////////////////////////////////////////////////////////////////////////

/**
 * Closes a guest session on the guest.
 *
 * @returns VBox status code.
 * @param   uFlags              Guest session close flags.
 * @param   uTimeoutMS          Timeout (in ms) to wait.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the read lock.
 */
int GuestSession::i_closeSession(uint32_t uFlags, uint32_t uTimeoutMS, int *pvrcGuest)
{
    AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);

    LogFlowThisFunc(("uFlags=%x, uTimeoutMS=%RU32\n", uFlags, uTimeoutMS));

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Guest Additions < 4.3 don't support closing dedicated
       guest sessions, skip. */
    if (mData.mProtocolVersion < 2)
    {
        LogFlowThisFunc(("Installed Guest Additions don't support closing dedicated sessions, skipping\n"));
        return VINF_SUCCESS;
    }

    /** @todo uFlags validation. */

    if (mData.mStatus != GuestSessionStatus_Started)
    {
        LogFlowThisFunc(("Session ID=%RU32 not started (anymore), status now is: %RU32\n",
                         mData.mSession.mID, mData.mStatus));
        return VINF_SUCCESS;
    }

    int vrc;

    GuestWaitEvent *pEvent = NULL;
    GuestEventTypes eventTypes;
    try
    {
        eventTypes.push_back(VBoxEventType_OnGuestSessionStateChanged);

        vrc = registerWaitEventEx(mData.mSession.mID, mData.mObjectID, eventTypes, &pEvent);
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }

    if (RT_FAILURE(vrc))
        return vrc;

    LogFlowThisFunc(("Sending closing request to guest session ID=%RU32, uFlags=%x\n",
                     mData.mSession.mID, uFlags));

    alock.release();

    VBOXHGCMSVCPARM paParms[4];
    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
    HGCMSvcSetU32(&paParms[i++], uFlags);

    vrc = i_sendMessage(HOST_MSG_SESSION_CLOSE, i, paParms, VBOX_GUESTCTRL_DST_BOTH);
    if (RT_SUCCESS(vrc))
        vrc = i_waitForStatusChange(pEvent, GuestSessionWaitForFlag_Terminate, uTimeoutMS,
                                    NULL /* Session status */, pvrcGuest);

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Internal worker function for public APIs that handle copying elements from
 * guest to the host.
 *
 * @return HRESULT
 * @param  SourceSet            Source set specifying what to copy.
 * @param  strDestination       Destination path on the host. Host path style.
 * @param  pProgress            Progress object returned to the caller.
 */
HRESULT GuestSession::i_copyFromGuest(const GuestSessionFsSourceSet &SourceSet,
                                      const com::Utf8Str &strDestination, ComPtr<IProgress> &pProgress)
{
    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    /* Validate stuff. */
    if (RT_UNLIKELY(SourceSet.size() == 0 || *(SourceSet[0].strSource.c_str()) == '\0')) /* At least one source must be present. */
        return setError(E_INVALIDARG, tr("No source(s) specified"));
    if (RT_UNLIKELY((strDestination.c_str()) == NULL || *(strDestination.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No destination specified"));

    GuestSessionFsSourceSet::const_iterator itSrc = SourceSet.begin();
    while (itSrc != SourceSet.end())
    {
        LogRel2(("Guest Control: Copying '%s' from guest to '%s' on the host (type: %s, filter: %s)\n",
                 itSrc->strSource.c_str(), strDestination.c_str(), GuestBase::fsObjTypeToStr(itSrc->enmType), itSrc->strFilter.c_str()));
        ++itSrc;
    }

    /* Create a task and return the progress obejct for it. */
    GuestSessionTaskCopyFrom *pTask = NULL;
    try
    {
        pTask = new GuestSessionTaskCopyFrom(this /* GuestSession */, SourceSet, strDestination);
    }
    catch (std::bad_alloc &)
    {
        return setError(E_OUTOFMEMORY, tr("Failed to create GuestSessionTaskCopyFrom object"));
    }

    try
    {
        hrc = pTask->Init(Utf8StrFmt(tr("Copying to \"%s\" on the host"), strDestination.c_str()));
    }
    catch (std::bad_alloc &)
    {
        hrc = E_OUTOFMEMORY;
    }
    if (SUCCEEDED(hrc))
    {
        ComObjPtr<Progress> ptrProgressObj = pTask->GetProgressObject();

        /* Kick off the worker thread. Note! Consumes pTask. */
        hrc = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
        pTask = NULL;
        if (SUCCEEDED(hrc))
            hrc = ptrProgressObj.queryInterfaceTo(pProgress.asOutParam());
        else
            hrc = setError(hrc, tr("Starting thread for copying from guest to the host failed"));
    }
    else
    {
        hrc = setError(hrc, tr("Initializing GuestSessionTaskCopyFrom object failed"));
        delete pTask;
    }

    LogFlowFunc(("Returning %Rhrc\n", hrc));
    return hrc;
}

/**
 * Internal worker function for public APIs that handle copying elements from
 * host to the guest.
 *
 * @return HRESULT
 * @param  SourceSet            Source set specifying what to copy.
 * @param  strDestination       Destination path on the guest. Guest path style.
 * @param  pProgress            Progress object returned to the caller.
 */
HRESULT GuestSession::i_copyToGuest(const GuestSessionFsSourceSet &SourceSet,
                                    const com::Utf8Str &strDestination, ComPtr<IProgress> &pProgress)
{
    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    GuestSessionFsSourceSet::const_iterator itSrc = SourceSet.begin();
    while (itSrc != SourceSet.end())
    {
        LogRel2(("Guest Control: Copying '%s' from host to '%s' on the guest (type: %s, filter: %s)\n",
                 itSrc->strSource.c_str(), strDestination.c_str(), GuestBase::fsObjTypeToStr(itSrc->enmType), itSrc->strFilter.c_str()));
        ++itSrc;
    }

    /* Create a task and return the progress object for it. */
    GuestSessionTaskCopyTo *pTask = NULL;
    try
    {
        pTask = new GuestSessionTaskCopyTo(this /* GuestSession */, SourceSet, strDestination);
    }
    catch (std::bad_alloc &)
    {
        return setError(E_OUTOFMEMORY, tr("Failed to create GuestSessionTaskCopyTo object"));
    }

    try
    {
        hrc = pTask->Init(Utf8StrFmt(tr("Copying to \"%s\" on the guest"), strDestination.c_str()));
    }
    catch (std::bad_alloc &)
    {
        hrc = E_OUTOFMEMORY;
    }
    if (SUCCEEDED(hrc))
    {
        ComObjPtr<Progress> ptrProgressObj = pTask->GetProgressObject();

        /* Kick off the worker thread. Note! Consumes pTask. */
        hrc = pTask->createThreadWithType(RTTHREADTYPE_MAIN_HEAVY_WORKER);
        pTask = NULL;
        if (SUCCEEDED(hrc))
            hrc = ptrProgressObj.queryInterfaceTo(pProgress.asOutParam());
        else
            hrc = setError(hrc, tr("Starting thread for copying from host to the guest failed"));
    }
    else
    {
        hrc = setError(hrc, tr("Initializing GuestSessionTaskCopyTo object failed"));
        delete pTask;
    }

    LogFlowFunc(("Returning %Rhrc\n", hrc));
    return hrc;
}

/**
 * Validates and extracts directory copy flags from a comma-separated string.
 *
 * @return COM status, error set on failure
 * @param  strFlags             String to extract flags from.
 * @param  fStrict              Whether to set an error when an unknown / invalid flag is detected.
 * @param  pfFlags              Where to store the extracted (and validated) flags.
 */
HRESULT GuestSession::i_directoryCopyFlagFromStr(const com::Utf8Str &strFlags, bool fStrict, DirectoryCopyFlag_T *pfFlags)
{
    unsigned fFlags = DirectoryCopyFlag_None;

    /* Validate and set flags. */
    if (strFlags.isNotEmpty())
    {
        const char *pszNext = strFlags.c_str();
        for (;;)
        {
            /* Find the next keyword, ignoring all whitespace. */
            pszNext = RTStrStripL(pszNext);

            const char * const pszComma = strchr(pszNext, ',');
            size_t cchKeyword = pszComma ? pszComma - pszNext : strlen(pszNext);
            while (cchKeyword > 0 && RT_C_IS_SPACE(pszNext[cchKeyword - 1]))
                cchKeyword--;

            if (cchKeyword > 0)
            {
                /* Convert keyword to flag. */
#define MATCH_KEYWORD(a_szKeyword) (   cchKeyword == sizeof(a_szKeyword) - 1U \
                                    && memcmp(pszNext, a_szKeyword, sizeof(a_szKeyword) - 1U) == 0)
                if (MATCH_KEYWORD("CopyIntoExisting"))
                    fFlags |= (unsigned)DirectoryCopyFlag_CopyIntoExisting;
                else if (MATCH_KEYWORD("Recursive"))
                    fFlags |= (unsigned)DirectoryCopyFlag_Recursive;
                else if (MATCH_KEYWORD("FollowLinks"))
                    fFlags |= (unsigned)DirectoryCopyFlag_FollowLinks;
                else if (fStrict)
                    return setError(E_INVALIDARG, tr("Invalid directory copy flag: %.*s"), (int)cchKeyword, pszNext);
#undef MATCH_KEYWORD
            }
            if (!pszComma)
                break;
            pszNext = pszComma + 1;
        }
    }

    if (pfFlags)
        *pfFlags = (DirectoryCopyFlag_T)fFlags;
    return S_OK;
}

/**
 * Creates a directory on the guest.
 *
 * @returns VBox status code.
 * @param   strPath             Path on guest to directory to create.
 * @param   uMode               Creation mode to use (octal, 0777 max).
 * @param   uFlags              Directory creation flags to use.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 */
int GuestSession::i_directoryCreate(const Utf8Str &strPath, uint32_t uMode, uint32_t uFlags, int *pvrcGuest)
{
    AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);

    LogFlowThisFunc(("strPath=%s, uMode=%x, uFlags=%x\n", strPath.c_str(), uMode, uFlags));

    int vrc = VINF_SUCCESS;

    GuestProcessStartupInfo procInfo;
    procInfo.mFlags      = ProcessCreateFlag_Hidden;
    procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_MKDIR);

    try
    {
        procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */

        /* Construct arguments. */
        if (uFlags)
        {
            if (uFlags & DirectoryCreateFlag_Parents)
                procInfo.mArguments.push_back(Utf8Str("--parents")); /* We also want to create the parent directories. */
            else
                vrc = VERR_INVALID_PARAMETER;
        }

        if (   RT_SUCCESS(vrc)
            && uMode)
        {
            procInfo.mArguments.push_back(Utf8Str("--mode")); /* Set the creation mode. */

            char szMode[16];
            if (RTStrPrintf(szMode, sizeof(szMode), "%o", uMode))
            {
                procInfo.mArguments.push_back(Utf8Str(szMode));
            }
            else
                vrc = VERR_BUFFER_OVERFLOW;
        }

        procInfo.mArguments.push_back("--");    /* '--version' is a valid directory name. */
        procInfo.mArguments.push_back(strPath); /* The directory we want to create. */
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }

    if (RT_SUCCESS(vrc))
        vrc = GuestProcessTool::run(this, procInfo, pvrcGuest);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Checks if a directory on the guest exists.
 *
 * @returns \c true if directory exists on the guest, \c false if not.
 * @param   strPath             Path of directory to check.
 */
bool GuestSession::i_directoryExists(const Utf8Str &strPath)
{
    GuestFsObjData objDataIgnored;
    int vrcGuestIgnored;
    int const vrc = i_directoryQueryInfo(strPath, true /* fFollowSymlinks */, objDataIgnored, &vrcGuestIgnored);
    return RT_SUCCESS(vrc);
}

/**
 * Checks if a directory object exists and optionally returns its object.
 *
 * @returns \c true if directory object exists, or \c false if not.
 * @param   uDirID              ID of directory object to check.
 * @param   pDir                Where to return the found directory object on success.
 */
inline bool GuestSession::i_directoryExists(uint32_t uDirID, ComObjPtr<GuestDirectory> *pDir)
{
    SessionDirectories::const_iterator it = mData.mDirectories.find(uDirID);
    if (it != mData.mDirectories.end())
    {
        if (pDir)
            *pDir = it->second;
        return true;
    }
    return false;
}

/**
 * Queries information about a directory on the guest.
 *
 * @returns VBox status code, or VERR_NOT_A_DIRECTORY if the file system object exists but is not a directory.
 * @param   strPath             Path to directory to query information for.
 * @param   fFollowSymlinks     Whether to follow symlinks or not.
 * @param   objData             Where to store the information returned on success.
 * @param   pvrcGuest           Guest VBox status code, when returning
 *                              VERR_GSTCTL_GUEST_ERROR.
 */
int GuestSession::i_directoryQueryInfo(const Utf8Str &strPath, bool fFollowSymlinks, GuestFsObjData &objData, int *pvrcGuest)
{
    AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);

    LogFlowThisFunc(("strPath=%s, fFollowSymlinks=%RTbool\n", strPath.c_str(), fFollowSymlinks));

    int vrc = i_fsQueryInfo(strPath, fFollowSymlinks, objData, pvrcGuest);
    if (RT_SUCCESS(vrc))
    {
        vrc = objData.mType == FsObjType_Directory
            ? VINF_SUCCESS : VERR_NOT_A_DIRECTORY;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Unregisters a directory object from a guest session.
 *
 * @returns VBox status code. VERR_NOT_FOUND if the directory is not registered (anymore).
 * @param   pDirectory          Directory object to unregister from session.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_directoryUnregister(GuestDirectory *pDirectory)
{
    AssertPtrReturn(pDirectory, VERR_INVALID_POINTER);

    LogFlowThisFunc(("pDirectory=%p\n", pDirectory));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    const uint32_t idObject = pDirectory->getObjectID();

    LogFlowFunc(("Removing directory (objectID=%RU32) ...\n", idObject));

    int vrc = i_objectUnregister(idObject);
    if (RT_FAILURE(vrc))
        return vrc;

    SessionDirectories::iterator itDirs = mData.mDirectories.find(idObject);
    AssertReturn(itDirs != mData.mDirectories.end(), VERR_NOT_FOUND);

    /* Make sure to consume the pointer before the one of the iterator gets released. */
    ComObjPtr<GuestDirectory> pDirConsumed = pDirectory;

    LogFlowFunc(("Removing directory ID=%RU32 (session %RU32, now total %zu directories)\n",
                 idObject, mData.mSession.mID, mData.mDirectories.size()));

    vrc = pDirConsumed->i_onUnregister();
    AssertRCReturn(vrc, vrc);

    mData.mDirectories.erase(itDirs);

    alock.release(); /* Release lock before firing off event. */

//    ::FireGuestDirectoryRegisteredEvent(mEventSource, this /* Session */, pDirConsumed, false /* Process unregistered */);

    pDirConsumed.setNull();

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Removes a directory on the guest.
 *
 * @returns VBox status code.
 * @param   strPath             Path of directory on guest to remove.
 * @param   fFlags              Directory remove flags to use.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the read lock.
 */
int GuestSession::i_directoryRemove(const Utf8Str &strPath, uint32_t fFlags, int *pvrcGuest)
{
    AssertReturn(!(fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK), VERR_INVALID_PARAMETER);
    AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);

    LogFlowThisFunc(("strPath=%s, uFlags=0x%x\n", strPath.c_str(), fFlags));

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    GuestWaitEvent *pEvent = NULL;
    int vrc = registerWaitEvent(mData.mSession.mID, mData.mObjectID, &pEvent);
    if (RT_FAILURE(vrc))
        return vrc;

    /* Prepare HGCM call. */
    VBOXHGCMSVCPARM paParms[8];
    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
    HGCMSvcSetPv(&paParms[i++], (void*)strPath.c_str(),
                            (ULONG)strPath.length() + 1);
    HGCMSvcSetU32(&paParms[i++], fFlags);

    alock.release(); /* Drop lock before sending. */

    vrc = i_sendMessage(HOST_MSG_DIR_REMOVE, i, paParms);
    if (RT_SUCCESS(vrc))
    {
        vrc = pEvent->Wait(30 * 1000);
        if (   vrc == VERR_GSTCTL_GUEST_ERROR
            && pvrcGuest)
            *pvrcGuest = pEvent->GuestResult();
    }

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Creates a temporary directory / file on the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @param   strTemplate         Name template to use.
 *                              \sa RTDirCreateTemp / RTDirCreateTempSecure.
 * @param   strPath             Path where to create the temporary directory / file.
 * @param   fDirectory          Whether to create a temporary directory or file.
 * @param   strName             Where to return the created temporary name on success.
 * @param   fMode               File mode to use for creation (octal, umask-style).
 *                              Ignored when \a fSecure is specified.
 * @param   fSecure             Whether to perform a secure creation or not.
 * @param   pvrcGuest           Guest VBox status code, when returning
 *                              VERR_GSTCTL_GUEST_ERROR.
 */
int GuestSession::i_fsCreateTemp(const Utf8Str &strTemplate, const Utf8Str &strPath, bool fDirectory, Utf8Str &strName,
                                 uint32_t fMode, bool fSecure, int *pvrcGuest)
{
    AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);
    AssertReturn(fSecure || !(fMode & ~07777), VERR_INVALID_PARAMETER);

    LogFlowThisFunc(("strTemplate=%s, strPath=%s, fDirectory=%RTbool, fMode=%o, fSecure=%RTbool\n",
                     strTemplate.c_str(), strPath.c_str(), fDirectory, fMode, fSecure));

    GuestProcessStartupInfo procInfo;
    procInfo.mFlags = ProcessCreateFlag_WaitForStdOut;
    try
    {
        procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_MKTEMP);
        procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
        procInfo.mArguments.push_back(Utf8Str("--machinereadable"));
        if (fDirectory)
            procInfo.mArguments.push_back(Utf8Str("-d"));
        if (strPath.length()) /* Otherwise use /tmp or equivalent. */
        {
            procInfo.mArguments.push_back(Utf8Str("-t"));
            procInfo.mArguments.push_back(strPath);
        }
        /* Note: Secure flag and mode cannot be specified at the same time. */
        if (fSecure)
        {
            procInfo.mArguments.push_back(Utf8Str("--secure"));
        }
        else
        {
            procInfo.mArguments.push_back(Utf8Str("--mode"));

            /* Note: Pass the mode unmodified down to the guest. See @ticketref{21394}. */
            char szMode[16];
            int vrc2 = RTStrPrintf2(szMode, sizeof(szMode), "%d", fMode);
            AssertRCReturn(vrc2, vrc2);
            procInfo.mArguments.push_back(szMode);
        }
        procInfo.mArguments.push_back("--"); /* strTemplate could be '--help'. */
        procInfo.mArguments.push_back(strTemplate);
    }
    catch (std::bad_alloc &)
    {
        Log(("Out of memory!\n"));
        return VERR_NO_MEMORY;
    }

    /** @todo Use an internal HGCM command for this operation, since
     *        we now can run in a user-dedicated session. */
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    GuestCtrlStreamObjects stdOut;
    int vrc = GuestProcessTool::runEx(this, procInfo, &stdOut, 1 /* cStrmOutObjects */, &vrcGuest);
    if (!GuestProcess::i_isGuestError(vrc))
    {
        GuestFsObjData objData;
        if (!stdOut.empty())
        {
            vrc = objData.FromMkTemp(stdOut.at(0));
            if (RT_FAILURE(vrc))
            {
                vrcGuest = vrc;
                if (pvrcGuest)
                    *pvrcGuest = vrcGuest;
                vrc = VERR_GSTCTL_GUEST_ERROR;
            }
        }
        else
            vrc = VERR_BROKEN_PIPE;

        if (RT_SUCCESS(vrc))
            strName = objData.mName;
    }
    else if (pvrcGuest)
        *pvrcGuest = vrcGuest;

    LogFlowThisFunc(("Returning vrc=%Rrc, vrcGuest=%Rrc\n", vrc, vrcGuest));
    return vrc;
}

/**
 * Open a directory on the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @param   openInfo            Open information to use.
 * @param   pDirectory          Where to return the guest directory object on success.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_directoryOpen(const GuestDirectoryOpenInfo &openInfo, ComObjPtr<GuestDirectory> &pDirectory, int *pvrcGuest)
{
    AssertPtrReturn(pvrcGuest, VERR_INVALID_POINTER);

    LogFlowThisFunc(("strPath=%s, strPath=%s, uFlags=%x\n", openInfo.mPath.c_str(), openInfo.mFilter.c_str(), openInfo.mFlags));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Create the directory object. */
    HRESULT hrc = pDirectory.createObject();
    if (FAILED(hrc))
        return Global::vboxStatusCodeFromCOM(hrc);

    /* Register a new object ID. */
    uint32_t idObject;
    int vrc = i_objectRegister(pDirectory, SESSIONOBJECTTYPE_DIRECTORY, &idObject);
    if (RT_FAILURE(vrc))
    {
        pDirectory.setNull();
        return vrc;
    }

    /* We need to release the write lock first before initializing the directory object below,
     * as we're starting a guest process as part of it. This in turn will try to acquire the session's
     * write lock. */
    alock.release();

    Console *pConsole = mParent->i_getConsole();
    AssertPtr(pConsole);

    vrc = pDirectory->init(pConsole, this /* Parent */, idObject, openInfo);
    if (RT_FAILURE(vrc))
    {
        /* Make sure to acquire the write lock again before unregistering the object. */
        alock.acquire();

        int vrc2 = i_objectUnregister(idObject);
        AssertRC(vrc2);

        pDirectory.setNull();
    }
    else
    {
        /* Make sure to acquire the write lock again before continuing. */
        alock.acquire();

        try
        {
            /* Add the created directory to our map. */
            mData.mDirectories[idObject] = pDirectory;

            LogFlowFunc(("Added new guest directory \"%s\" (Session: %RU32) (now total %zu directories)\n",
                         openInfo.mPath.c_str(), mData.mSession.mID, mData.mDirectories.size()));

            alock.release(); /* Release lock before firing off event. */

            /** @todo Fire off a VBoxEventType_OnGuestDirectoryRegistered event? */
        }
        catch (std::bad_alloc &)
        {
            vrc = VERR_NO_MEMORY;
        }
    }

    if (RT_SUCCESS(vrc))
    {
        /* Nothing further to do here yet. */
        if (pvrcGuest)
            *pvrcGuest = VINF_SUCCESS;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Dispatches a host callback to its corresponding object.
 *
 * @return VBox status code. VERR_NOT_FOUND if no corresponding object was found.
 * @param  pCtxCb               Host callback context.
 * @param  pSvcCb               Service callback data.
 *
 * @note   Takes the read lock.
 */
int GuestSession::i_dispatchToObject(PVBOXGUESTCTRLHOSTCBCTX pCtxCb, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
{
    LogFlowFunc(("pCtxCb=%p, pSvcCb=%p\n", pCtxCb, pSvcCb));

    AssertPtrReturn(pCtxCb, VERR_INVALID_POINTER);
    AssertPtrReturn(pSvcCb, VERR_INVALID_POINTER);

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    /*
     * Find the object.
     */
    int vrc = VERR_NOT_FOUND;
    const uint32_t idObject = VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pCtxCb->uContextID);
    SessionObjects::const_iterator itObj = mData.mObjects.find(idObject);
    if (itObj != mData.mObjects.end())
    {
        /* Set protocol version so that pSvcCb can be interpreted right. */
        pCtxCb->uProtocol = mData.mProtocolVersion;

        switch (itObj->second.enmType)
        {
            /* Note: The session object is special, as it does not inherit from GuestObject we could call
             *       its dispatcher for -- so treat this separately and call it directly. */
            case SESSIONOBJECTTYPE_SESSION:
            {
                alock.release();

                vrc = i_dispatchToThis(pCtxCb, pSvcCb);
                break;
            }
            case SESSIONOBJECTTYPE_DIRECTORY:
            {
                ComObjPtr<GuestDirectory> pObj((GuestDirectory *)itObj->second.pObject);
                AssertReturn(!pObj.isNull(), VERR_INVALID_POINTER);

                alock.release();

                vrc = pObj->i_callbackDispatcher(pCtxCb, pSvcCb);
                break;
            }
            case SESSIONOBJECTTYPE_FILE:
            {
                ComObjPtr<GuestFile> pObj((GuestFile *)itObj->second.pObject);
                AssertReturn(!pObj.isNull(), VERR_INVALID_POINTER);

                alock.release();

                vrc = pObj->i_callbackDispatcher(pCtxCb, pSvcCb);
                break;
            }
            case SESSIONOBJECTTYPE_PROCESS:
            {
                ComObjPtr<GuestProcess> pObj((GuestProcess *)itObj->second.pObject);
                AssertReturn(!pObj.isNull(), VERR_INVALID_POINTER);

                alock.release();

                vrc = pObj->i_callbackDispatcher(pCtxCb, pSvcCb);
                break;
            }
            default:
                AssertMsgFailed(("%d\n", itObj->second.enmType));
                vrc = VERR_INTERNAL_ERROR_4;
                break;
        }
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Main handler for guest session messages from the guest.
 *
 * @returns VBox status code.
 * @param   pCbCtx              Host callback context from HGCM service.
 * @param   pSvcCbData          HGCM service callback data.
 *
 * @note    No locking!
 */
int GuestSession::i_dispatchToThis(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
{
    AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
    AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);

    LogFlowThisFunc(("sessionID=%RU32, CID=%RU32, uMessage=%RU32, pSvcCb=%p\n",
                     mData.mSession.mID, pCbCtx->uContextID, pCbCtx->uMessage, pSvcCbData));
    int vrc;
    switch (pCbCtx->uMessage)
    {
        case GUEST_MSG_DISCONNECTED:
            /** @todo Handle closing all guest objects. */
            vrc = VERR_INTERNAL_ERROR;
            break;

        case GUEST_MSG_SESSION_NOTIFY: /* Guest Additions >= 4.3.0. */
            vrc = i_onSessionStatusChange(pCbCtx, pSvcCbData);
            break;

        default:
            vrc = dispatchGeneric(pCbCtx, pSvcCbData);
            break;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Validates and extracts file copy flags from a comma-separated string.
 *
 * @return COM status, error set on failure
 * @param  strFlags             String to extract flags from.
 * @param  fStrict              Whether to set an error when an unknown / invalid flag is detected.
 * @param  pfFlags              Where to store the extracted (and validated) flags.
 */
HRESULT GuestSession::i_fileCopyFlagFromStr(const com::Utf8Str &strFlags, bool fStrict, FileCopyFlag_T *pfFlags)
{
    unsigned fFlags = (unsigned)FileCopyFlag_None;

    /* Validate and set flags. */
    if (strFlags.isNotEmpty())
    {
        const char *pszNext = strFlags.c_str();
        for (;;)
        {
            /* Find the next keyword, ignoring all whitespace. */
            pszNext = RTStrStripL(pszNext);

            const char * const pszComma = strchr(pszNext, ',');
            size_t cchKeyword = pszComma ? pszComma - pszNext : strlen(pszNext);
            while (cchKeyword > 0 && RT_C_IS_SPACE(pszNext[cchKeyword - 1]))
                cchKeyword--;

            if (cchKeyword > 0)
            {
                /* Convert keyword to flag. */
#define MATCH_KEYWORD(a_szKeyword) (   cchKeyword == sizeof(a_szKeyword) - 1U \
                                    && memcmp(pszNext, a_szKeyword, sizeof(a_szKeyword) - 1U) == 0)
                if (MATCH_KEYWORD("NoReplace"))
                    fFlags |= (unsigned)FileCopyFlag_NoReplace;
                else if (MATCH_KEYWORD("FollowLinks"))
                    fFlags |= (unsigned)FileCopyFlag_FollowLinks;
                else if (MATCH_KEYWORD("Update"))
                    fFlags |= (unsigned)FileCopyFlag_Update;
                else if (fStrict)
                    return setError(E_INVALIDARG, tr("Invalid file copy flag: %.*s"), (int)cchKeyword, pszNext);
#undef MATCH_KEYWORD
            }
            if (!pszComma)
                break;
            pszNext = pszComma + 1;
        }
    }

    if (pfFlags)
        *pfFlags = (FileCopyFlag_T)fFlags;
    return S_OK;
}

/**
 * Checks if a file object exists and optionally returns its object.
 *
 * @returns \c true if file object exists, or \c false if not.
 * @param   uFileID             ID of file object to check.
 * @param   pFile               Where to return the found file object on success.
 */
inline bool GuestSession::i_fileExists(uint32_t uFileID, ComObjPtr<GuestFile> *pFile)
{
    SessionFiles::const_iterator it = mData.mFiles.find(uFileID);
    if (it != mData.mFiles.end())
    {
        if (pFile)
            *pFile = it->second;
        return true;
    }
    return false;
}

/**
 * Unregisters a file object from a guest session.
 *
 * @returns VBox status code. VERR_NOT_FOUND if the file is not registered (anymore).
 * @param   pFile               File object to unregister from session.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_fileUnregister(GuestFile *pFile)
{
    AssertPtrReturn(pFile, VERR_INVALID_POINTER);

    LogFlowThisFunc(("pFile=%p\n", pFile));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    const uint32_t idObject = pFile->getObjectID();

    LogFlowFunc(("Removing file (objectID=%RU32) ...\n", idObject));

    int vrc = i_objectUnregister(idObject);
    if (RT_FAILURE(vrc))
        return vrc;

    SessionFiles::iterator itFiles = mData.mFiles.find(idObject);
    AssertReturn(itFiles != mData.mFiles.end(), VERR_NOT_FOUND);

    /* Make sure to consume the pointer before the one of the iterator gets released. */
    ComObjPtr<GuestFile> pFileConsumed = pFile;

    LogFlowFunc(("Removing file ID=%RU32 (session %RU32, now total %zu files)\n",
                 pFileConsumed->getObjectID(), mData.mSession.mID, mData.mFiles.size()));

    vrc = pFileConsumed->i_onUnregister();
    AssertRCReturn(vrc, vrc);

    mData.mFiles.erase(itFiles);

    alock.release(); /* Release lock before firing off event. */

    ::FireGuestFileRegisteredEvent(mEventSource, this, pFileConsumed, false /* Unregistered */);

    pFileConsumed.setNull();

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Removes a file from the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @param   strPath             Path of file on guest to remove.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 */
int GuestSession::i_fileRemove(const Utf8Str &strPath, int *pvrcGuest)
{
    LogFlowThisFunc(("strPath=%s\n", strPath.c_str()));

    GuestProcessStartupInfo procInfo;
    GuestProcessStream      streamOut;

    procInfo.mFlags      = ProcessCreateFlag_WaitForStdOut;
    procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_RM);

    try
    {
        procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
        procInfo.mArguments.push_back(Utf8Str("--machinereadable"));
        procInfo.mArguments.push_back("--"); /* strPath could be '--help', which is a valid filename. */
        procInfo.mArguments.push_back(strPath); /* The file we want to remove. */
    }
    catch (std::bad_alloc &)
    {
        return VERR_NO_MEMORY;
    }

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    GuestCtrlStreamObjects stdOut;
    int vrc = GuestProcessTool::runEx(this, procInfo, &stdOut, 1 /* cStrmOutObjects */, &vrcGuest);
    if (GuestProcess::i_isGuestError(vrc))
    {
        if (!stdOut.empty())
        {
            GuestFsObjData objData;
            vrc = objData.FromRm(stdOut.at(0));
            if (RT_FAILURE(vrc))
            {
                vrcGuest = vrc;
                if (pvrcGuest)
                    *pvrcGuest = vrcGuest;
                vrc = VERR_GSTCTL_GUEST_ERROR;
            }
        }
        else
            vrc = VERR_BROKEN_PIPE;
    }
    else if (pvrcGuest)
        *pvrcGuest = vrcGuest;

    LogFlowThisFunc(("Returning vrc=%Rrc, vrcGuest=%Rrc\n", vrc, vrcGuest));
    return vrc;
}

/**
 * Opens a file on the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @param   aPath               File path on guest to open.
 * @param   aAccessMode         Access mode to use.
 * @param   aOpenAction         Open action to use.
 * @param   aSharingMode        Sharing mode to use.
 * @param   aCreationMode       Creation mode to use.
 * @param   aFlags              Open flags to use.
 * @param   pFile               Where to return the file object on success.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_fileOpenEx(const com::Utf8Str &aPath, FileAccessMode_T aAccessMode, FileOpenAction_T aOpenAction,
                               FileSharingMode_T aSharingMode, ULONG aCreationMode, const std::vector<FileOpenExFlag_T> &aFlags,
                               ComObjPtr<GuestFile> &pFile, int *pvrcGuest)
{
    GuestFileOpenInfo openInfo;
    openInfo.mFilename     = aPath;
    openInfo.mCreationMode = aCreationMode;
    openInfo.mAccessMode   = aAccessMode;
    openInfo.mOpenAction   = aOpenAction;
    openInfo.mSharingMode  = aSharingMode;

    /* Combine and validate flags. */
    for (size_t i = 0; i < aFlags.size(); i++)
        openInfo.mfOpenEx |= aFlags[i];
    /* Validation is done in i_fileOpen(). */

    return i_fileOpen(openInfo, pFile, pvrcGuest);
}

/**
 * Opens a file on the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @param   openInfo            Open information to use for opening the file.
 * @param   pFile               Where to return the file object on success.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_fileOpen(const GuestFileOpenInfo &openInfo, ComObjPtr<GuestFile> &pFile, int *pvrcGuest)
{
    LogFlowThisFunc(("strFile=%s, enmAccessMode=0x%x, enmOpenAction=0x%x, uCreationMode=%RU32, mfOpenEx=%RU32\n",
                     openInfo.mFilename.c_str(), openInfo.mAccessMode, openInfo.mOpenAction, openInfo.mCreationMode,
                     openInfo.mfOpenEx));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Guest Additions < 4.3 don't support handling guest files, skip. */
    if (mData.mProtocolVersion < 2)
    {
        if (pvrcGuest)
            *pvrcGuest = VERR_NOT_SUPPORTED;
        return VERR_GSTCTL_GUEST_ERROR;
    }

    if (!openInfo.IsValid())
        return VERR_INVALID_PARAMETER;

    /* Create the directory object. */
    HRESULT hrc = pFile.createObject();
    if (FAILED(hrc))
        return VERR_COM_UNEXPECTED;

    /* Register a new object ID. */
    uint32_t idObject;
    int vrc = i_objectRegister(pFile, SESSIONOBJECTTYPE_FILE, &idObject);
    if (RT_FAILURE(vrc))
    {
        pFile.setNull();
        return vrc;
    }

    Console *pConsole = mParent->i_getConsole();
    AssertPtr(pConsole);

    vrc = pFile->init(pConsole, this /* GuestSession */, idObject, openInfo);
    if (RT_FAILURE(vrc))
        return vrc;

    /*
     * Since this is a synchronous guest call we have to
     * register the file object first, releasing the session's
     * lock and then proceed with the actual opening command
     * -- otherwise the file's opening callback would hang
     * because the session's lock still is in place.
     */
    try
    {
        /* Add the created file to our vector. */
        mData.mFiles[idObject] = pFile;

        LogFlowFunc(("Added new guest file \"%s\" (Session: %RU32) (now total %zu files)\n",
                     openInfo.mFilename.c_str(), mData.mSession.mID, mData.mFiles.size()));

        alock.release(); /* Release lock before firing off event. */

        ::FireGuestFileRegisteredEvent(mEventSource, this, pFile, true /* Registered */);
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }

    if (RT_SUCCESS(vrc))
    {
        int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
        vrc = pFile->i_openFile(30 * 1000 /* 30s timeout */, &vrcGuest);
        if (   vrc == VERR_GSTCTL_GUEST_ERROR
            && pvrcGuest)
            *pvrcGuest = vrcGuest;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Queries information from a file on the guest.
 *
 * @returns IPRT status code. VERR_NOT_A_FILE if the queried file system object on the guest is not a file,
 *                            or VERR_GSTCTL_GUEST_ERROR if pvrcGuest contains
 *                            more error information from the guest.
 * @param   strPath           Absolute path of file to query information for.
 * @param   fFollowSymlinks   Whether or not to follow symbolic links on the guest.
 * @param   objData           Where to store the acquired information.
 * @param   pvrcGuest         Where to store the guest VBox status code.
 *                            Optional.
 */
int GuestSession::i_fileQueryInfo(const Utf8Str &strPath, bool fFollowSymlinks, GuestFsObjData &objData, int *pvrcGuest)
{
    LogFlowThisFunc(("strPath=%s fFollowSymlinks=%RTbool\n", strPath.c_str(), fFollowSymlinks));

    int vrc = i_fsQueryInfo(strPath, fFollowSymlinks, objData, pvrcGuest);
    if (RT_SUCCESS(vrc))
        vrc = objData.mType == FsObjType_File ? VINF_SUCCESS : VERR_NOT_A_FILE;

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Queries the size of a file on the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @retval  VERR_
 * @param   strPath             Path of file on guest to query size for.
 * @param   fFollowSymlinks     \c true when wanting to follow symbolic links, \c false if not.
 * @param   pllSize             Where to return the queried file size on success.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 */
int GuestSession::i_fileQuerySize(const Utf8Str &strPath, bool fFollowSymlinks, int64_t *pllSize, int *pvrcGuest)
{
    AssertPtrReturn(pllSize, VERR_INVALID_POINTER);

    GuestFsObjData objData;
    int vrc = i_fileQueryInfo(strPath, fFollowSymlinks, objData, pvrcGuest);
    if (RT_SUCCESS(vrc))
        *pllSize = objData.mObjectSize;

    return vrc;
}

/**
 * Queries information of a file system object (file, directory, ...).
 *
 * @return  IPRT status code.
 * @param   strPath             Path to file system object to query information for.
 * @param   fFollowSymlinks     Whether to follow symbolic links or not.
 * @param   objData             Where to return the file system object data, if found.
 * @param   pvrcGuest           Guest VBox status code, when returning
 *                              VERR_GSTCTL_GUEST_ERROR. Any other return code
 *                              indicates some host side error.
 */
int GuestSession::i_fsQueryInfo(const Utf8Str &strPath, bool fFollowSymlinks, GuestFsObjData &objData, int *pvrcGuest)
{
    LogFlowThisFunc(("strPath=%s\n", strPath.c_str()));

    /** @todo Merge this with IGuestFile::queryInfo(). */
    GuestProcessStartupInfo procInfo;
    procInfo.mFlags      = ProcessCreateFlag_WaitForStdOut;
    try
    {
        procInfo.mExecutable = Utf8Str(VBOXSERVICE_TOOL_STAT);
        procInfo.mArguments.push_back(procInfo.mExecutable); /* Set argv0. */
        procInfo.mArguments.push_back(Utf8Str("--machinereadable"));
        if (fFollowSymlinks)
            procInfo.mArguments.push_back(Utf8Str("-L"));
        procInfo.mArguments.push_back("--"); /* strPath could be '--help', which is a valid filename. */
        procInfo.mArguments.push_back(strPath);
    }
    catch (std::bad_alloc &)
    {
        Log(("Out of memory!\n"));
        return VERR_NO_MEMORY;
    }

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    GuestCtrlStreamObjects stdOut;
    int vrc = GuestProcessTool::runEx(this, procInfo,
                                        &stdOut, 1 /* cStrmOutObjects */,
                                        &vrcGuest);
    if (!GuestProcess::i_isGuestError(vrc))
    {
        if (!stdOut.empty())
        {
            vrc = objData.FromStat(stdOut.at(0));
            if (RT_FAILURE(vrc))
            {
                vrcGuest = vrc;
                if (pvrcGuest)
                    *pvrcGuest = vrcGuest;
                vrc = VERR_GSTCTL_GUEST_ERROR;
            }
        }
        else
            vrc = VERR_BROKEN_PIPE;
    }
    else if (pvrcGuest)
        *pvrcGuest = vrcGuest;

    LogFlowThisFunc(("Returning vrc=%Rrc, vrcGuest=%Rrc\n", vrc, vrcGuest));
    return vrc;
}

/**
 * Returns the guest credentials of a guest session.
 *
 * @returns Guest credentials.
 */
const GuestCredentials& GuestSession::i_getCredentials(void)
{
    return mData.mCredentials;
}

/**
 * Returns the guest session (friendly) name.
 *
 * @returns Guest session name.
 */
Utf8Str GuestSession::i_getName(void)
{
    return mData.mSession.mName;
}

/**
 * Returns a stringified error description for a given guest result code.
 *
 * @returns Stringified error description.
 */
/* static */
Utf8Str GuestSession::i_guestErrorToString(int vrcGuest)
{
    Utf8Str strError;

    /** @todo pData->u32Flags: int vs. uint32 -- IPRT errors are *negative* !!! */
    switch (vrcGuest)
    {
        case VERR_INVALID_VM_HANDLE:
            strError.printf(tr("VMM device is not available (is the VM running?)"));
            break;

        case VERR_HGCM_SERVICE_NOT_FOUND:
            strError.printf(tr("The guest execution service is not available"));
            break;

        case VERR_ACCOUNT_RESTRICTED:
            strError.printf(tr("The specified user account on the guest is restricted and can't be used to logon"));
            break;

        case VERR_AUTHENTICATION_FAILURE:
            strError.printf(tr("The specified user was not able to logon on guest"));
            break;

        case VERR_TIMEOUT:
            strError.printf(tr("The guest did not respond within time"));
            break;

        case VERR_CANCELLED:
            strError.printf(tr("The session operation was canceled"));
            break;

        case VERR_GSTCTL_MAX_CID_OBJECTS_REACHED:
            strError.printf(tr("Maximum number of concurrent guest processes has been reached"));
            break;

        case VERR_NOT_FOUND:
            strError.printf(tr("The guest execution service is not ready (yet)"));
            break;

        default:
            strError.printf("%Rrc", vrcGuest);
            break;
    }

    return strError;
}

/**
 * Returns whether the session is in a started state or not.
 *
 * @returns \c true if in a started state, or \c false if not.
 */
bool GuestSession::i_isStarted(void) const
{
    return (mData.mStatus == GuestSessionStatus_Started);
}

/**
 * Checks if this session is ready state where it can handle
 * all session-bound actions (like guest processes, guest files).
 * Only used by official API methods. Will set an external
 * error when not ready.
 */
HRESULT GuestSession::i_isStartedExternal(void)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    /** @todo Be a bit more informative. */
    if (!i_isStarted())
        return setError(E_UNEXPECTED, tr("Session is not in started state"));

    return S_OK;
}

/**
 * Returns whether a guest session status implies a terminated state or not.
 *
 * @returns \c true if it's a terminated state, or \c false if not.
 */
/* static */
bool GuestSession::i_isTerminated(GuestSessionStatus_T enmStatus)
{
    switch (enmStatus)
    {
        case GuestSessionStatus_Terminated:
            RT_FALL_THROUGH();
        case GuestSessionStatus_TimedOutKilled:
            RT_FALL_THROUGH();
        case GuestSessionStatus_TimedOutAbnormally:
            RT_FALL_THROUGH();
        case GuestSessionStatus_Down:
            RT_FALL_THROUGH();
        case GuestSessionStatus_Error:
            return true;

        default:
            break;
    }

    return false;
}

/**
 * Returns whether the session is in a terminated state or not.
 *
 * @returns \c true if in a terminated state, or \c false if not.
 */
bool GuestSession::i_isTerminated(void) const
{
    return GuestSession::i_isTerminated(mData.mStatus);
}

/**
 * Called by IGuest right before this session gets removed from
 * the public session list.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_onRemove(void)
{
    LogFlowThisFuncEnter();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    int vrc = i_objectsUnregister();

    /*
     * Note: The event source stuff holds references to this object,
     *       so make sure that this is cleaned up *before* calling uninit.
     */
    if (!mEventSource.isNull())
    {
        mEventSource->UnregisterListener(mLocalListener);

        mLocalListener.setNull();
        unconst(mEventSource).setNull();
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Handles guest session status changes from the guest.
 *
 * @returns VBox status code.
 * @param   pCbCtx              Host callback context from HGCM service.
 * @param   pSvcCbData          HGCM service callback data.
 *
 * @note    Takes the read lock (for session ID lookup).
 */
int GuestSession::i_onSessionStatusChange(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCbData)
{
    AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
    /* pCallback is optional. */
    AssertPtrReturn(pSvcCbData, VERR_INVALID_POINTER);

    if (pSvcCbData->mParms < 3)
        return VERR_INVALID_PARAMETER;

    CALLBACKDATA_SESSION_NOTIFY dataCb;
    /* pSvcCb->mpaParms[0] always contains the context ID. */
    int vrc = HGCMSvcGetU32(&pSvcCbData->mpaParms[1], &dataCb.uType);
    AssertRCReturn(vrc, vrc);
    vrc = HGCMSvcGetU32(&pSvcCbData->mpaParms[2], &dataCb.uResult);
    AssertRCReturn(vrc, vrc);

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    LogFlowThisFunc(("ID=%RU32, uType=%RU32, vrcGuest=%Rrc\n", mData.mSession.mID, dataCb.uType, dataCb.uResult));

    GuestSessionStatus_T sessionStatus = GuestSessionStatus_Undefined;

    int vrcGuest = dataCb.uResult; /** @todo uint32_t vs. int. */
    switch (dataCb.uType)
    {
        case GUEST_SESSION_NOTIFYTYPE_ERROR:
            sessionStatus = GuestSessionStatus_Error;
            LogRel(("Guest Control: Error starting Session '%s' (%Rrc) \n", mData.mSession.mName.c_str(), vrcGuest));
            break;

        case GUEST_SESSION_NOTIFYTYPE_STARTED:
            sessionStatus = GuestSessionStatus_Started;
#if 0 /** @todo If we get some environment stuff along with this kind notification: */
            const char *pszzEnvBlock = ...;
            uint32_t    cbEnvBlock   = ...;
            if (!mData.mpBaseEnvironment)
            {
                GuestEnvironment *pBaseEnv;
                try { pBaseEnv = new GuestEnvironment(); } catch (std::bad_alloc &) { pBaseEnv = NULL; }
                if (pBaseEnv)
                {
                    int vrc = pBaseEnv->initNormal(Guest.i_isGuestInWindowsNtFamily() ? RTENV_CREATE_F_ALLOW_EQUAL_FIRST_IN_VAR : 0);
                    if (RT_SUCCESS(vrc))
                        vrc = pBaseEnv->copyUtf8Block(pszzEnvBlock, cbEnvBlock);
                    if (RT_SUCCESS(vrc))
                        mData.mpBaseEnvironment = pBaseEnv;
                    else
                        pBaseEnv->release();
                }
            }
#endif
            LogRel(("Guest Control: Session '%s' was successfully started\n", mData.mSession.mName.c_str()));
            break;

        case GUEST_SESSION_NOTIFYTYPE_TEN:
            LogRel(("Guest Control: Session '%s' was terminated normally with exit code %#x\n",
                    mData.mSession.mName.c_str(), dataCb.uResult));
            sessionStatus = GuestSessionStatus_Terminated;
            break;

        case GUEST_SESSION_NOTIFYTYPE_TEA:
            LogRel(("Guest Control: Session '%s' was terminated abnormally\n", mData.mSession.mName.c_str()));
            sessionStatus = GuestSessionStatus_Terminated;
            /* dataCb.uResult is undefined. */
            break;

        case GUEST_SESSION_NOTIFYTYPE_TES:
            LogRel(("Guest Control: Session '%s' was terminated via signal %#x\n", mData.mSession.mName.c_str(), dataCb.uResult));
            sessionStatus = GuestSessionStatus_Terminated;
            break;

        case GUEST_SESSION_NOTIFYTYPE_TOK:
            sessionStatus = GuestSessionStatus_TimedOutKilled;
            LogRel(("Guest Control: Session '%s' timed out and was killed\n", mData.mSession.mName.c_str()));
            break;

        case GUEST_SESSION_NOTIFYTYPE_TOA:
            sessionStatus = GuestSessionStatus_TimedOutAbnormally;
            LogRel(("Guest Control: Session '%s' timed out and was not killed successfully\n", mData.mSession.mName.c_str()));
            break;

        case GUEST_SESSION_NOTIFYTYPE_DWN:
            sessionStatus = GuestSessionStatus_Down;
            LogRel(("Guest Control: Session '%s' got killed as guest service/OS is down\n", mData.mSession.mName.c_str()));
            break;

        case GUEST_SESSION_NOTIFYTYPE_UNDEFINED:
        default:
            vrc = VERR_NOT_SUPPORTED;
            break;
    }

    /* Leave the lock, as i_setSessionStatus() below will require a write lock for actually
     * committing the session state. */
    alock.release();

    if (RT_SUCCESS(vrc))
    {
        if (RT_FAILURE(vrcGuest))
            sessionStatus = GuestSessionStatus_Error;
    }

    /* Set the session status. */
    if (RT_SUCCESS(vrc))
        vrc = i_setSessionStatus(sessionStatus, vrcGuest);

    LogFlowThisFunc(("ID=%RU32, vrcGuest=%Rrc\n", mData.mSession.mID, vrcGuest));

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Returns the path separation style used on the guest.
 *
 * @returns Separation style used on the guest.
 */
PathStyle_T GuestSession::i_getGuestPathStyle(void)
{
    PathStyle_T enmPathStyle;

    VBOXOSTYPE enmOsType = mParent->i_getGuestOSType();
    if (enmOsType < VBOXOSTYPE_DOS)
    {
        LogFlowFunc(("returns PathStyle_Unknown\n"));
        enmPathStyle = PathStyle_Unknown;
    }
    else if (enmOsType < VBOXOSTYPE_Linux)
    {
        LogFlowFunc(("returns PathStyle_DOS\n"));
        enmPathStyle = PathStyle_DOS;
    }
    else
    {
        LogFlowFunc(("returns PathStyle_UNIX\n"));
        enmPathStyle = PathStyle_UNIX;
    }

    return enmPathStyle;
}

/**
 * Returns the path separation style used on the host.
 *
 * @returns Separation style used on the host.
 */
/* static */
PathStyle_T GuestSession::i_getHostPathStyle(void)
{
#if RTPATH_STYLE == RTPATH_STR_F_STYLE_DOS
    return PathStyle_DOS;
#else
    return PathStyle_UNIX;
#endif
}

/**
 * Starts the guest session on the guest.
 *
 * @returns VBox status code.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the read and write locks.
 */
int GuestSession::i_startSession(int *pvrcGuest)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    LogFlowThisFunc(("mID=%RU32, mName=%s, uProtocolVersion=%RU32, openFlags=%x, openTimeoutMS=%RU32\n",
                     mData.mSession.mID, mData.mSession.mName.c_str(), mData.mProtocolVersion,
                     mData.mSession.mOpenFlags, mData.mSession.mOpenTimeoutMS));

    /* Guest Additions < 4.3 don't support opening dedicated
       guest sessions. Simply return success here. */
    if (mData.mProtocolVersion < 2)
    {
        alock.release(); /* Release lock before changing status. */

        i_setSessionStatus(GuestSessionStatus_Started, VINF_SUCCESS); /* ignore return code*/
        LogFlowThisFunc(("Installed Guest Additions don't support opening dedicated sessions, skipping\n"));
        return VINF_SUCCESS;
    }

    if (mData.mStatus != GuestSessionStatus_Undefined)
        return VINF_SUCCESS;

    /** @todo mData.mSession.uFlags validation. */

    alock.release(); /* Release lock before changing status. */

    /* Set current session status. */
    int vrc = i_setSessionStatus(GuestSessionStatus_Starting, VINF_SUCCESS);
    if (RT_FAILURE(vrc))
        return vrc;

    GuestWaitEvent *pEvent = NULL;
    GuestEventTypes eventTypes;
    try
    {
        eventTypes.push_back(VBoxEventType_OnGuestSessionStateChanged);

        vrc = registerWaitEventEx(mData.mSession.mID, mData.mObjectID, eventTypes, &pEvent);
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }

    if (RT_FAILURE(vrc))
        return vrc;

    alock.acquire(); /* Re-acquire lock before accessing session attributes below. */

    VBOXHGCMSVCPARM paParms[8];

    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
    HGCMSvcSetU32(&paParms[i++], mData.mProtocolVersion);
    HGCMSvcSetPv(&paParms[i++], (void*)mData.mCredentials.mUser.c_str(),
                            (ULONG)mData.mCredentials.mUser.length() + 1);
    HGCMSvcSetPv(&paParms[i++], (void*)mData.mCredentials.mPassword.c_str(),
                            (ULONG)mData.mCredentials.mPassword.length() + 1);
    HGCMSvcSetPv(&paParms[i++], (void*)mData.mCredentials.mDomain.c_str(),
                            (ULONG)mData.mCredentials.mDomain.length() + 1);
    HGCMSvcSetU32(&paParms[i++], mData.mSession.mOpenFlags);

    alock.release(); /* Drop lock before sending. */

    vrc = i_sendMessage(HOST_MSG_SESSION_CREATE, i, paParms, VBOX_GUESTCTRL_DST_ROOT_SVC);
    if (RT_SUCCESS(vrc))
    {
        vrc = i_waitForStatusChange(pEvent, GuestSessionWaitForFlag_Start,
                                    30 * 1000 /* 30s timeout */,
                                    NULL /* Session status */, pvrcGuest);
    }
    else
    {
        /*
         * Unable to start guest session - update its current state.
         * Since there is no (official API) way to recover a failed guest session
         * this also marks the end state. Internally just calling this
         * same function again will work though.
         */
        i_setSessionStatus(GuestSessionStatus_Error, vrc); /* ignore return code */
    }

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Starts the guest session asynchronously in a separate worker thread.
 *
 * @returns IPRT status code.
 */
int GuestSession::i_startSessionAsync(void)
{
    LogFlowThisFuncEnter();

    /* Create task: */
    GuestSessionTaskInternalStart *pTask = NULL;
    try
    {
        pTask = new GuestSessionTaskInternalStart(this);
    }
    catch (std::bad_alloc &)
    {
        return VERR_NO_MEMORY;
    }
    if (pTask->isOk())
    {
        /* Kick off the thread: */
        HRESULT hrc = pTask->createThread();
        pTask = NULL; /* Not valid anymore, not even on failure! */
        if (SUCCEEDED(hrc))
        {
            LogFlowFuncLeaveRC(VINF_SUCCESS);
            return VINF_SUCCESS;
        }
        LogFlow(("GuestSession: Failed to create thread for GuestSessionTaskInternalOpen task.\n"));
    }
    else
        LogFlow(("GuestSession: GuestSessionTaskInternalStart creation failed: %Rhrc.\n", pTask->vrc()));
    LogFlowFuncLeaveRC(VERR_GENERAL_FAILURE);
    return VERR_GENERAL_FAILURE;
}

/**
 * Static function to start a guest session asynchronously.
 *
 * @returns IPRT status code.
 * @param   pTask               Task object to use for starting the guest session.
 */
/* static */
int GuestSession::i_startSessionThreadTask(GuestSessionTaskInternalStart *pTask)
{
    LogFlowFunc(("pTask=%p\n", pTask));
    AssertPtr(pTask);

    const ComObjPtr<GuestSession> pSession(pTask->Session());
    Assert(!pSession.isNull());

    AutoCaller autoCaller(pSession);
    if (FAILED(autoCaller.hrc()))
        return VERR_COM_INVALID_OBJECT_STATE;

    int vrc = pSession->i_startSession(NULL /*pvrcGuest*/);
    /* Nothing to do here anymore. */

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Registers an object with the session, i.e. allocates an object ID.
 *
 * @return  VBox status code.
 * @retval  VERR_GSTCTL_MAX_OBJECTS_REACHED if the maximum of concurrent objects
 *          is reached.
 * @param   pObject     Guest object to register (weak pointer). Optional.
 * @param   enmType     Session object type to register.
 * @param   pidObject   Where to return the object ID on success. Optional.
 */
int GuestSession::i_objectRegister(GuestObject *pObject, SESSIONOBJECTTYPE enmType, uint32_t *pidObject)
{
    /* pObject can be NULL. */
    /* pidObject is optional. */

    /*
     * Pick a random bit as starting point.  If it's in use, search forward
     * for a free one, wrapping around.  We've reserved both the zero'th and
     * max-1 IDs (see Data constructor).
     */
    uint32_t idObject = RTRandU32Ex(1, VBOX_GUESTCTRL_MAX_OBJECTS - 2);
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
    if (!ASMBitTestAndSet(&mData.bmObjectIds[0], idObject))
    { /* likely */ }
    else if (mData.mObjects.size() < VBOX_GUESTCTRL_MAX_OBJECTS - 2 /* First and last are not used */)
    {
        /* Forward search. */
        int iHit = ASMBitNextClear(&mData.bmObjectIds[0], VBOX_GUESTCTRL_MAX_OBJECTS, idObject);
        if (iHit < 0)
            iHit = ASMBitFirstClear(&mData.bmObjectIds[0], VBOX_GUESTCTRL_MAX_OBJECTS);
        AssertLogRelMsgReturn(iHit >= 0, ("object count: %#zu\n", mData.mObjects.size()), VERR_GSTCTL_MAX_CID_OBJECTS_REACHED);
        idObject = iHit;
        AssertLogRelMsgReturn(!ASMBitTestAndSet(&mData.bmObjectIds[0], idObject), ("idObject=%#x\n", idObject), VERR_INTERNAL_ERROR_2);
    }
    else
    {
        LogFunc(("Maximum number of objects reached (enmType=%RU32, %zu objects)\n", enmType, mData.mObjects.size()));
        return VERR_GSTCTL_MAX_CID_OBJECTS_REACHED;
    }

    Log2Func(("enmType=%RU32 -> idObject=%RU32 (%zu objects)\n", enmType, idObject, mData.mObjects.size()));

    try
    {
        mData.mObjects[idObject].pObject = pObject; /* Can be NULL. */
        mData.mObjects[idObject].enmType = enmType;
        mData.mObjects[idObject].msBirth = RTTimeMilliTS();
    }
    catch (std::bad_alloc &)
    {
        ASMBitClear(&mData.bmObjectIds[0], idObject);
        return VERR_NO_MEMORY;
    }

    if (pidObject)
        *pidObject = idObject;

    return VINF_SUCCESS;
}

/**
 * Unregisters an object from the session objects list.
 *
 * @retval  VINF_SUCCESS on success.
 * @retval  VERR_NOT_FOUND if the object ID was not found.
 * @param   idObject        Object ID to unregister.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_objectUnregister(uint32_t idObject)
{
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    int vrc = VINF_SUCCESS;
    AssertMsgStmt(ASMBitTestAndClear(&mData.bmObjectIds, idObject), ("idObject=%#x\n", idObject), vrc = VERR_NOT_FOUND);

    SessionObjects::iterator ItObj = mData.mObjects.find(idObject);
    AssertMsgReturn(ItObj != mData.mObjects.end(), ("idObject=%#x\n", idObject), VERR_NOT_FOUND);
    mData.mObjects.erase(ItObj);

    return vrc;
}

/**
 * Unregisters all objects from the session list.
 *
 * @returns VBox status code.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_objectsUnregister(void)
{
    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    LogFlowThisFunc(("Unregistering directories (%zu total)\n", mData.mDirectories.size()));

    SessionDirectories::iterator itDirs;
    while ((itDirs = mData.mDirectories.begin()) != mData.mDirectories.end())
    {
        alock.release();
        i_directoryUnregister(itDirs->second);
        alock.acquire();
    }

    Assert(mData.mDirectories.size() == 0);
    mData.mDirectories.clear();

    LogFlowThisFunc(("Unregistering files (%zu total)\n", mData.mFiles.size()));

    SessionFiles::iterator itFiles;
    while ((itFiles = mData.mFiles.begin()) != mData.mFiles.end())
    {
        alock.release();
        i_fileUnregister(itFiles->second);
        alock.acquire();
    }

    Assert(mData.mFiles.size() == 0);
    mData.mFiles.clear();

    LogFlowThisFunc(("Unregistering processes (%zu total)\n", mData.mProcesses.size()));

    SessionProcesses::iterator itProcs;
    while ((itProcs = mData.mProcesses.begin()) != mData.mProcesses.end())
    {
        alock.release();
        i_processUnregister(itProcs->second);
        alock.acquire();
    }

    Assert(mData.mProcesses.size() == 0);
    mData.mProcesses.clear();

    return VINF_SUCCESS;
}

/**
 * Notifies all registered objects about a guest session status change.
 *
 * @returns VBox status code.
 * @param   enmSessionStatus    Session status to notify objects about.
 */
int GuestSession::i_objectsNotifyAboutStatusChange(GuestSessionStatus_T enmSessionStatus)
{
    LogFlowThisFunc(("enmSessionStatus=%RU32\n", enmSessionStatus));

    int vrc = VINF_SUCCESS;

    SessionObjects::iterator itObjs = mData.mObjects.begin();
    while (itObjs != mData.mObjects.end())
    {
        GuestObject *pObj = itObjs->second.pObject;
        if (pObj) /* pObject can be NULL (weak pointer). */
        {
            int vrc2 = pObj->i_onSessionStatusChange(enmSessionStatus);
            if (RT_SUCCESS(vrc))
                vrc = vrc2;

            /* If the session got terminated, make sure to cancel all wait events for
             * the current object. */
            if (i_isTerminated())
                pObj->cancelWaitEvents();
        }

        ++itObjs;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Renames a path on the guest.
 *
 * @returns VBox status code.
 * @returns VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @param   strSource           Source path on guest to rename.
 * @param   strDest             Destination path on guest to rename \a strSource to.
 * @param   uFlags              Renaming flags.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 * @note    Takes the read lock.
 */
int GuestSession::i_pathRename(const Utf8Str &strSource, const Utf8Str &strDest, uint32_t uFlags, int *pvrcGuest)
{
    AssertReturn(!(uFlags & ~PATHRENAME_FLAG_VALID_MASK), VERR_INVALID_PARAMETER);

    LogFlowThisFunc(("strSource=%s, strDest=%s, uFlags=0x%x\n",
                     strSource.c_str(), strDest.c_str(), uFlags));

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    GuestWaitEvent *pEvent = NULL;
    int vrc = registerWaitEvent(mData.mSession.mID, mData.mObjectID, &pEvent);
    if (RT_FAILURE(vrc))
        return vrc;

    /* Prepare HGCM call. */
    VBOXHGCMSVCPARM paParms[8];
    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
    HGCMSvcSetPv(&paParms[i++], (void*)strSource.c_str(),
                            (ULONG)strSource.length() + 1);
    HGCMSvcSetPv(&paParms[i++], (void*)strDest.c_str(),
                            (ULONG)strDest.length() + 1);
    HGCMSvcSetU32(&paParms[i++], uFlags);

    alock.release(); /* Drop lock before sending. */

    vrc = i_sendMessage(HOST_MSG_PATH_RENAME, i, paParms);
    if (RT_SUCCESS(vrc))
    {
        vrc = pEvent->Wait(30 * 1000);
        if (   vrc == VERR_GSTCTL_GUEST_ERROR
            && pvrcGuest)
            *pvrcGuest = pEvent->GuestResult();
    }

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Returns the user's absolute documents path, if any.
 *
 * @returns VBox status code.
 * @param   strPath     Where to store the user's document path.
 * @param   pvrcGuest   Guest VBox status code, when returning
 *                      VERR_GSTCTL_GUEST_ERROR. Any other return code indicates
 *                      some host side error.
 *
 * @note    Takes the read lock.
 */
int GuestSession::i_pathUserDocuments(Utf8Str &strPath, int *pvrcGuest)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    /** @todo Cache the user's document path? */

    GuestWaitEvent *pEvent = NULL;
    int vrc = registerWaitEvent(mData.mSession.mID, mData.mObjectID, &pEvent);
    if (RT_FAILURE(vrc))
        return vrc;

    /* Prepare HGCM call. */
    VBOXHGCMSVCPARM paParms[2];
    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());

    alock.release(); /* Drop lock before sending. */

    vrc = i_sendMessage(HOST_MSG_PATH_USER_DOCUMENTS, i, paParms);
    if (RT_SUCCESS(vrc))
    {
        vrc = pEvent->Wait(30 * 1000);
        if (RT_SUCCESS(vrc))
        {
            strPath = pEvent->Payload().ToString();
        }
        else
        {
            if (vrc == VERR_GSTCTL_GUEST_ERROR)
            {
                if (pvrcGuest)
                    *pvrcGuest = pEvent->GuestResult();
            }
        }
    }

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Returns the user's absolute home path, if any.
 *
 * @returns VBox status code.
 * @param   strPath     Where to store the user's home path.
 * @param   pvrcGuest   Guest VBox status code, when returning
 *                      VERR_GSTCTL_GUEST_ERROR. Any other return code indicates
 *                      some host side error.
 *
 * @note    Takes the read lock.
 */
int GuestSession::i_pathUserHome(Utf8Str &strPath, int *pvrcGuest)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    /** @todo Cache the user's home path? */

    GuestWaitEvent *pEvent = NULL;
    int vrc = registerWaitEvent(mData.mSession.mID, mData.mObjectID, &pEvent);
    if (RT_FAILURE(vrc))
        return vrc;

    /* Prepare HGCM call. */
    VBOXHGCMSVCPARM paParms[2];
    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());

    alock.release(); /* Drop lock before sending. */

    vrc = i_sendMessage(HOST_MSG_PATH_USER_HOME, i, paParms);
    if (RT_SUCCESS(vrc))
    {
        vrc = pEvent->Wait(30 * 1000);
        if (RT_SUCCESS(vrc))
        {
            strPath = pEvent->Payload().ToString();
        }
        else
        {
            if (vrc == VERR_GSTCTL_GUEST_ERROR)
            {
                if (pvrcGuest)
                    *pvrcGuest = pEvent->GuestResult();
            }
        }
    }

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Unregisters a process object from a guest session.
 *
 * @returns VBox status code. VERR_NOT_FOUND if the process is not registered (anymore).
 * @param   pProcess            Process object to unregister from session.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_processUnregister(GuestProcess *pProcess)
{
    AssertPtrReturn(pProcess, VERR_INVALID_POINTER);

    LogFlowThisFunc(("pProcess=%p\n", pProcess));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    const uint32_t idObject = pProcess->getObjectID();

    LogFlowFunc(("Removing process (objectID=%RU32) ...\n", idObject));

    int vrc = i_objectUnregister(idObject);
    if (RT_FAILURE(vrc))
        return vrc;

    SessionProcesses::iterator itProcs = mData.mProcesses.find(idObject);
    AssertReturn(itProcs != mData.mProcesses.end(), VERR_NOT_FOUND);

    /* Make sure to consume the pointer before the one of the iterator gets released. */
    ComObjPtr<GuestProcess> pProc = pProcess;

    ULONG uPID;
    HRESULT hrc = pProc->COMGETTER(PID)(&uPID);
    ComAssertComRC(hrc);

    LogFlowFunc(("Removing process ID=%RU32 (session %RU32, guest PID %RU32, now total %zu processes)\n",
                 idObject, mData.mSession.mID, uPID, mData.mProcesses.size()));

    vrc = pProcess->i_onUnregister();
    AssertRCReturn(vrc, vrc);

    mData.mProcesses.erase(itProcs);

    alock.release(); /* Release lock before firing off event. */

    ::FireGuestProcessRegisteredEvent(mEventSource, this /* Session */, pProc, uPID, false /* Process unregistered */);

    pProc.setNull();

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Creates but does *not* start the process yet.
 *
 * See GuestProcess::startProcess() or GuestProcess::startProcessAsync() for
 * starting the process.
 *
 * @returns IPRT status code.
 * @param   procInfo            Process startup info to use for starting the process.
 * @param   pProcess            Where to return the created guest process object on success.
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_processCreateEx(GuestProcessStartupInfo &procInfo, ComObjPtr<GuestProcess> &pProcess)
{
    LogFlowFunc(("mExe=%s, mFlags=%x, mTimeoutMS=%RU32\n",
                 procInfo.mExecutable.c_str(), procInfo.mFlags, procInfo.mTimeoutMS));
#ifdef DEBUG
    if (procInfo.mArguments.size())
    {
        LogFlowFunc(("Arguments:"));
        ProcessArguments::const_iterator it = procInfo.mArguments.begin();
        while (it != procInfo.mArguments.end())
        {
            LogFlow((" %s", (*it).c_str()));
            ++it;
        }
        LogFlow(("\n"));
    }
#endif

    /* Validate flags. */
    if (procInfo.mFlags)
    {
        if (   !(procInfo.mFlags & ProcessCreateFlag_IgnoreOrphanedProcesses)
            && !(procInfo.mFlags & ProcessCreateFlag_WaitForProcessStartOnly)
            && !(procInfo.mFlags & ProcessCreateFlag_Hidden)
            && !(procInfo.mFlags & ProcessCreateFlag_Profile)
            && !(procInfo.mFlags & ProcessCreateFlag_WaitForStdOut)
            && !(procInfo.mFlags & ProcessCreateFlag_WaitForStdErr))
        {
            return VERR_INVALID_PARAMETER;
        }
    }

    if (   (procInfo.mFlags & ProcessCreateFlag_WaitForProcessStartOnly)
        && (   (procInfo.mFlags & ProcessCreateFlag_WaitForStdOut)
            || (procInfo.mFlags & ProcessCreateFlag_WaitForStdErr)
           )
       )
    {
        return VERR_INVALID_PARAMETER;
    }

    if (procInfo.mPriority)
    {
        if (!(procInfo.mPriority & ProcessPriority_Default))
            return VERR_INVALID_PARAMETER;
    }

    /* Adjust timeout.
     * If set to 0, we define an infinite timeout (unlimited process run time). */
    if (procInfo.mTimeoutMS == 0)
        procInfo.mTimeoutMS = UINT32_MAX;

    /** @todo Implement process priority + affinity. */

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Create the process object. */
    HRESULT hrc = pProcess.createObject();
    if (FAILED(hrc))
        return VERR_COM_UNEXPECTED;

    /* Register a new object ID. */
    uint32_t idObject;
    int vrc = i_objectRegister(pProcess, SESSIONOBJECTTYPE_PROCESS, &idObject);
    if (RT_FAILURE(vrc))
    {
        pProcess.setNull();
        return vrc;
    }

    vrc = pProcess->init(mParent->i_getConsole() /* Console */, this /* Session */, idObject, procInfo, mData.mpBaseEnvironment);
    if (RT_FAILURE(vrc))
        return vrc;

    /* Add the created process to our map. */
    try
    {
        mData.mProcesses[idObject] = pProcess;

        LogFlowFunc(("Added new process (Session: %RU32) with process ID=%RU32 (now total %zu processes)\n",
                     mData.mSession.mID, idObject, mData.mProcesses.size()));

        alock.release(); /* Release lock before firing off event. */

        ::FireGuestProcessRegisteredEvent(mEventSource, this /* Session */, pProcess, 0 /* PID */, true /* Process registered */);
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }

    return vrc;
}

/**
 * Checks if a process object exists and optionally returns its object.
 *
 * @returns \c true if process object exists, or \c false if not.
 * @param   uProcessID          ID of process object to check.
 * @param   pProcess            Where to return the found process object on success.
 *
 * @note    No locking done!
 */
inline bool GuestSession::i_processExists(uint32_t uProcessID, ComObjPtr<GuestProcess> *pProcess)
{
    SessionProcesses::const_iterator it = mData.mProcesses.find(uProcessID);
    if (it != mData.mProcesses.end())
    {
        if (pProcess)
            *pProcess = it->second;
        return true;
    }
    return false;
}

/**
 * Returns the process object from a guest PID.
 *
 * @returns VBox status code.
 * @param   uPID                Guest PID to get process object for.
 * @param   pProcess            Where to return the process object on success.
 *
 * @note    No locking done!
 */
inline int GuestSession::i_processGetByPID(ULONG uPID, ComObjPtr<GuestProcess> *pProcess)
{
    AssertReturn(uPID, false);
    /* pProcess is optional. */

    SessionProcesses::iterator itProcs = mData.mProcesses.begin();
    for (; itProcs != mData.mProcesses.end(); ++itProcs)
    {
        ComObjPtr<GuestProcess> pCurProc = itProcs->second;
        AutoCaller procCaller(pCurProc);
        if (!procCaller.isOk())
            return VERR_COM_INVALID_OBJECT_STATE;

        ULONG uCurPID;
        HRESULT hrc = pCurProc->COMGETTER(PID)(&uCurPID);
        ComAssertComRC(hrc);

        if (uCurPID == uPID)
        {
            if (pProcess)
                *pProcess = pCurProc;
            return VINF_SUCCESS;
        }
    }

    return VERR_NOT_FOUND;
}

/**
 * Sends a message to the HGCM host service.
 *
 * @returns VBox status code.
 * @param   uMessage            Message ID to send.
 * @param   uParms              Number of parameters in \a paParms to send.
 * @param   paParms             Array of HGCM parameters to send.
 * @param   fDst                Host message destination flags of type VBOX_GUESTCTRL_DST_XXX.
 */
int GuestSession::i_sendMessage(uint32_t uMessage, uint32_t uParms, PVBOXHGCMSVCPARM paParms,
                                uint64_t fDst /*= VBOX_GUESTCTRL_DST_SESSION*/)
{
    LogFlowThisFuncEnter();

#ifndef VBOX_GUESTCTRL_TEST_CASE
    ComObjPtr<Console> pConsole = mParent->i_getConsole();
    Assert(!pConsole.isNull());

    /* Forward the information to the VMM device. */
    VMMDev *pVMMDev = pConsole->i_getVMMDev();
    AssertPtr(pVMMDev);

    LogFlowThisFunc(("uMessage=%RU32 (%s), uParms=%RU32\n", uMessage, GstCtrlHostMsgtoStr((guestControl::eHostMsg)uMessage), uParms));

    /* HACK ALERT! We extend the first parameter to 64-bit and use the
                   two topmost bits for call destination information. */
    Assert(fDst == VBOX_GUESTCTRL_DST_SESSION || fDst == VBOX_GUESTCTRL_DST_ROOT_SVC || fDst == VBOX_GUESTCTRL_DST_BOTH);
    Assert(paParms[0].type == VBOX_HGCM_SVC_PARM_32BIT);
    paParms[0].type = VBOX_HGCM_SVC_PARM_64BIT;
    paParms[0].u.uint64 = (uint64_t)paParms[0].u.uint32 | fDst;

    /* Make the call. */
    int vrc = pVMMDev->hgcmHostCall(HGCMSERVICE_NAME, uMessage, uParms, paParms);
    if (RT_FAILURE(vrc))
    {
        /** @todo What to do here? */
    }
#else
    /* Not needed within testcases. */
    int vrc = VINF_SUCCESS;
#endif
    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Sets the guest session's current status.
 *
 * @returns VBox status code.
 * @param   sessionStatus       Session status to set.
 * @param   vrcSession          Session result to set (for error handling).
 *
 * @note    Takes the write lock.
 */
int GuestSession::i_setSessionStatus(GuestSessionStatus_T sessionStatus, int vrcSession)
{
    LogFlowThisFunc(("oldStatus=%RU32, newStatus=%RU32, vrcSession=%Rrc\n", mData.mStatus, sessionStatus, vrcSession));

    if (sessionStatus == GuestSessionStatus_Error)
    {
        AssertMsg(RT_FAILURE(vrcSession), ("Guest vrcSession must be an error (%Rrc)\n", vrcSession));
        /* Do not allow overwriting an already set error. If this happens
         * this means we forgot some error checking/locking somewhere. */
        AssertMsg(RT_SUCCESS(mData.mVrc), ("Guest mVrc already set (to %Rrc)\n", mData.mVrc));
    }
    else
        AssertMsg(RT_SUCCESS(vrcSession), ("Guest vrcSession must not be an error (%Rrc)\n", vrcSession));

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    int vrc = VINF_SUCCESS;

    if (mData.mStatus != sessionStatus)
    {
        mData.mStatus = sessionStatus;
        mData.mVrc    = vrcSession;

        /* Make sure to notify all underlying objects first. */
        vrc = i_objectsNotifyAboutStatusChange(sessionStatus);

        ComObjPtr<VirtualBoxErrorInfo> errorInfo;
        HRESULT hrc = errorInfo.createObject();
        ComAssertComRC(hrc);
        int vrc2 = errorInfo->initEx(VBOX_E_IPRT_ERROR, vrcSession, COM_IIDOF(IGuestSession), getComponentName(),
                                     i_guestErrorToString(vrcSession));
        AssertRC(vrc2);

        alock.release(); /* Release lock before firing off event. */

        ::FireGuestSessionStateChangedEvent(mEventSource, this, mData.mSession.mID, sessionStatus, errorInfo);
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/** @todo Unused --remove? */
int GuestSession::i_signalWaiters(GuestSessionWaitResult_T enmWaitResult, int vrc /*= VINF_SUCCESS */)
{
    RT_NOREF(enmWaitResult, vrc);

    /*LogFlowThisFunc(("enmWaitResult=%d, vrc=%Rrc, mWaitCount=%RU32, mWaitEvent=%p\n",
                     enmWaitResult, vrc, mData.mWaitCount, mData.mWaitEvent));*/

    /* Note: No write locking here -- already done in the caller. */

    int vrc2 = VINF_SUCCESS;
    /*if (mData.mWaitEvent)
        vrc2 = mData.mWaitEvent->Signal(enmWaitResult, vrc);*/
    LogFlowFuncLeaveRC(vrc2);
    return vrc2;
}

/**
 * Shuts down (and optionally powers off / reboots) the guest.
 * Needs supported Guest Additions installed.
 *
 * @returns VBox status code. VERR_NOT_SUPPORTED if not supported by Guest Additions.
 * @param   fFlags      Guest shutdown flags.
 * @param   pvrcGuest   Guest VBox status code, when returning
 *                      VERR_GSTCTL_GUEST_ERROR. Any other return code indicates
 *                      some host side error.
 *
 * @note    Takes the read lock.
 */
int GuestSession::i_shutdown(uint32_t fFlags, int *pvrcGuest)
{
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    AssertPtrReturn(mParent, VERR_INVALID_POINTER);
    if (!(mParent->i_getGuestControlFeatures0() & VBOX_GUESTCTRL_GF_0_SHUTDOWN))
        return VERR_NOT_SUPPORTED;

    LogRel(("Guest Control: Shutting down guest (flags = %#x) ...\n", fFlags));

    GuestWaitEvent *pEvent = NULL;
    int vrc = registerWaitEvent(mData.mSession.mID, mData.mObjectID, &pEvent);
    if (RT_FAILURE(vrc))
        return vrc;

    /* Prepare HGCM call. */
    VBOXHGCMSVCPARM paParms[2];
    int i = 0;
    HGCMSvcSetU32(&paParms[i++], pEvent->ContextID());
    HGCMSvcSetU32(&paParms[i++], fFlags);

    alock.release(); /* Drop lock before sending. */

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;

    vrc = i_sendMessage(HOST_MSG_SHUTDOWN, i, paParms);
    if (RT_SUCCESS(vrc))
    {
        vrc = pEvent->Wait(30 * 1000);
        if (RT_FAILURE(vrc))
        {
            if (vrc == VERR_GSTCTL_GUEST_ERROR)
                vrcGuest = pEvent->GuestResult();
        }
    }

    if (RT_FAILURE(vrc))
    {
        LogRel(("Guest Control: Shutting down guest failed, vrc=%Rrc\n", vrc == VERR_GSTCTL_GUEST_ERROR ? vrcGuest : vrc));
        if (   vrc == VERR_GSTCTL_GUEST_ERROR
            && pvrcGuest)
            *pvrcGuest = vrcGuest;
    }

    unregisterWaitEvent(pEvent);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Determines the protocol version (sets mData.mProtocolVersion).
 *
 * This is called from the init method prior to to establishing a guest
 * session.
 *
 * @returns VBox status code.
 */
int GuestSession::i_determineProtocolVersion(void)
{
    /*
     * We currently do this based on the reported Guest Additions version,
     * ASSUMING that VBoxService and VBoxDrv are at the same version.
     */
    ComObjPtr<Guest> pGuest = mParent;
    AssertReturn(!pGuest.isNull(), VERR_NOT_SUPPORTED);
    uint32_t uGaVersion = pGuest->i_getAdditionsVersion();

    /* Everyone supports version one, if they support anything at all. */
    mData.mProtocolVersion = 1;

    /* Guest control 2.0 was introduced with 4.3.0. */
    if (uGaVersion >= VBOX_FULL_VERSION_MAKE(4,3,0))
        mData.mProtocolVersion = 2; /* Guest control 2.0. */

    LogFlowThisFunc(("uGaVersion=%u.%u.%u => mProtocolVersion=%u\n",
                     VBOX_FULL_VERSION_GET_MAJOR(uGaVersion), VBOX_FULL_VERSION_GET_MINOR(uGaVersion),
                     VBOX_FULL_VERSION_GET_BUILD(uGaVersion), mData.mProtocolVersion));

    /*
     * Inform the user about outdated Guest Additions (VM release log).
     */
    if (mData.mProtocolVersion < 2)
        LogRelMax(3, ("Warning: Guest Additions v%u.%u.%u only supports the older guest control protocol version %u.\n"
                      "         Please upgrade GAs to the current version to get full guest control capabilities.\n",
                      VBOX_FULL_VERSION_GET_MAJOR(uGaVersion), VBOX_FULL_VERSION_GET_MINOR(uGaVersion),
                      VBOX_FULL_VERSION_GET_BUILD(uGaVersion), mData.mProtocolVersion));

    return VINF_SUCCESS;
}

/**
 * Waits for guest session events.
 *
 * @returns VBox status code.
 * @retval  VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @retval  VERR_TIMEOUT when a timeout has occurred.
 * @param   fWaitFlags          Wait flags to use.
 * @param   uTimeoutMS          Timeout (in ms) to wait.
 * @param   waitResult          Where to return the wait result on success.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 *
 * @note    Takes the read lock.
 */
int GuestSession::i_waitFor(uint32_t fWaitFlags, ULONG uTimeoutMS, GuestSessionWaitResult_T &waitResult, int *pvrcGuest)
{
    LogFlowThisFuncEnter();

    AssertReturn(fWaitFlags, VERR_INVALID_PARAMETER);

    /*LogFlowThisFunc(("fWaitFlags=0x%x, uTimeoutMS=%RU32, mStatus=%RU32, mWaitCount=%RU32, mWaitEvent=%p, pvrcGuest=%p\n",
                     fWaitFlags, uTimeoutMS, mData.mStatus, mData.mWaitCount, mData.mWaitEvent, pvrcGuest));*/

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    /* Did some error occur before? Then skip waiting and return. */
    if (mData.mStatus == GuestSessionStatus_Error)
    {
        waitResult = GuestSessionWaitResult_Error;
        AssertMsg(RT_FAILURE(mData.mVrc), ("No error mVrc (%Rrc) set when guest session indicated an error\n", mData.mVrc));
        if (pvrcGuest)
            *pvrcGuest = mData.mVrc; /* Return last set error. */
        return VERR_GSTCTL_GUEST_ERROR;
    }

    /* Guest Additions < 4.3 don't support session handling, skip. */
    if (mData.mProtocolVersion < 2)
    {
        waitResult = GuestSessionWaitResult_WaitFlagNotSupported;

        LogFlowThisFunc(("Installed Guest Additions don't support waiting for dedicated sessions, skipping\n"));
        return VINF_SUCCESS;
    }

    waitResult = GuestSessionWaitResult_None;
    if (fWaitFlags & GuestSessionWaitForFlag_Terminate)
    {
        switch (mData.mStatus)
        {
            case GuestSessionStatus_Terminated:
            case GuestSessionStatus_Down:
                waitResult = GuestSessionWaitResult_Terminate;
                break;

            case GuestSessionStatus_TimedOutKilled:
            case GuestSessionStatus_TimedOutAbnormally:
                waitResult = GuestSessionWaitResult_Timeout;
                break;

            case GuestSessionStatus_Error:
                /* Handled above. */
                break;

            case GuestSessionStatus_Started:
                waitResult = GuestSessionWaitResult_Start;
                break;

            case GuestSessionStatus_Undefined:
            case GuestSessionStatus_Starting:
                /* Do the waiting below. */
                break;

            default:
                AssertMsgFailed(("Unhandled session status %RU32\n", mData.mStatus));
                return VERR_NOT_IMPLEMENTED;
        }
    }
    else if (fWaitFlags & GuestSessionWaitForFlag_Start)
    {
        switch (mData.mStatus)
        {
            case GuestSessionStatus_Started:
            case GuestSessionStatus_Terminating:
            case GuestSessionStatus_Terminated:
            case GuestSessionStatus_Down:
                waitResult = GuestSessionWaitResult_Start;
                break;

            case GuestSessionStatus_Error:
                waitResult = GuestSessionWaitResult_Error;
                break;

            case GuestSessionStatus_TimedOutKilled:
            case GuestSessionStatus_TimedOutAbnormally:
                waitResult = GuestSessionWaitResult_Timeout;
                break;

            case GuestSessionStatus_Undefined:
            case GuestSessionStatus_Starting:
                /* Do the waiting below. */
                break;

            default:
                AssertMsgFailed(("Unhandled session status %RU32\n", mData.mStatus));
                return VERR_NOT_IMPLEMENTED;
        }
    }

    LogFlowThisFunc(("sessionStatus=%RU32, vrcSession=%Rrc, waitResult=%RU32\n", mData.mStatus, mData.mVrc, waitResult));

    /* No waiting needed? Return immediately using the last set error. */
    if (waitResult != GuestSessionWaitResult_None)
    {
        if (pvrcGuest)
            *pvrcGuest = mData.mVrc; /* Return last set error (if any). */
        return RT_SUCCESS(mData.mVrc) ? VINF_SUCCESS : VERR_GSTCTL_GUEST_ERROR;
    }

    int vrc = VINF_SUCCESS;

    uint64_t const tsStart = RTTimeMilliTS();
    uint64_t       tsNow   = tsStart;

    while (tsNow - tsStart < uTimeoutMS)
    {
        GuestWaitEvent *pEvent = NULL;
        GuestEventTypes eventTypes;
        try
        {
            eventTypes.push_back(VBoxEventType_OnGuestSessionStateChanged);

            vrc = registerWaitEventEx(mData.mSession.mID, mData.mObjectID, eventTypes, &pEvent);
        }
        catch (std::bad_alloc &)
        {
            vrc = VERR_NO_MEMORY;
        }

        if (RT_FAILURE(vrc))
            return vrc;

        alock.release(); /* Release lock before waiting. */

        GuestSessionStatus_T sessionStatus;
        vrc = i_waitForStatusChange(pEvent, fWaitFlags,
                                    uTimeoutMS - (tsNow - tsStart), &sessionStatus, pvrcGuest);
        if (RT_SUCCESS(vrc))
        {
            switch (sessionStatus)
            {
                case GuestSessionStatus_Started:
                    waitResult = GuestSessionWaitResult_Start;
                    break;

                case GuestSessionStatus_Starting:
                    RT_FALL_THROUGH();
                case GuestSessionStatus_Terminating:
                    if (fWaitFlags & GuestSessionWaitForFlag_Status) /* Any status wanted? */
                        waitResult = GuestSessionWaitResult_Status;
                    /* else: Wait another round until we get the event(s) fWaitFlags defines. */
                    break;

                case GuestSessionStatus_Terminated:
                    waitResult = GuestSessionWaitResult_Terminate;
                    break;

                case GuestSessionStatus_TimedOutKilled:
                    RT_FALL_THROUGH();
                case GuestSessionStatus_TimedOutAbnormally:
                    waitResult = GuestSessionWaitResult_Timeout;
                    break;

                case GuestSessionStatus_Down:
                    waitResult = GuestSessionWaitResult_Terminate;
                    break;

                case GuestSessionStatus_Error:
                    waitResult = GuestSessionWaitResult_Error;
                    break;

                default:
                    waitResult = GuestSessionWaitResult_Status;
                    break;
            }
        }

        unregisterWaitEvent(pEvent);

        /* Wait result not None, e.g. some result acquired or a wait error occurred? Bail out. */
        if (   waitResult != GuestSessionWaitResult_None
            || RT_FAILURE(vrc))
            break;

        tsNow = RTTimeMilliTS();

        alock.acquire(); /* Re-acquire lock before waiting for the next event. */
    }

    if (tsNow - tsStart >= uTimeoutMS)
    {
        waitResult = GuestSessionWaitResult_None; /* Paranoia. */
        vrc = VERR_TIMEOUT;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Waits for guest session status changes.
 *
 * @returns VBox status code.
 * @retval  VERR_GSTCTL_GUEST_ERROR on received guest error.
 * @retval  VERR_WRONG_ORDER when an unexpected event type has been received.
 * @param   pEvent              Wait event to use for waiting.
 * @param   fWaitFlags          Wait flags to use.
 * @param   uTimeoutMS          Timeout (in ms) to wait.
 * @param   pSessionStatus      Where to return the guest session status.
 * @param   pvrcGuest           Where to return the guest error when
 *                              VERR_GSTCTL_GUEST_ERROR was returned. Optional.
 */
int GuestSession::i_waitForStatusChange(GuestWaitEvent *pEvent, uint32_t fWaitFlags, uint32_t uTimeoutMS,
                                        GuestSessionStatus_T *pSessionStatus, int *pvrcGuest)
{
    RT_NOREF(fWaitFlags);
    AssertPtrReturn(pEvent, VERR_INVALID_POINTER);

    VBoxEventType_T evtType;
    ComPtr<IEvent> pIEvent;
    int vrc = waitForEvent(pEvent, uTimeoutMS, &evtType, pIEvent.asOutParam());
    if (RT_SUCCESS(vrc))
    {
        if (evtType == VBoxEventType_OnGuestSessionStateChanged)
        {
            ComPtr<IGuestSessionStateChangedEvent> pChangedEvent = pIEvent;
            Assert(!pChangedEvent.isNull());

            GuestSessionStatus_T sessionStatus;
            pChangedEvent->COMGETTER(Status)(&sessionStatus);
            if (pSessionStatus)
                *pSessionStatus = sessionStatus;

            ComPtr<IVirtualBoxErrorInfo> errorInfo;
            HRESULT hrc = pChangedEvent->COMGETTER(Error)(errorInfo.asOutParam());
            ComAssertComRC(hrc);

            LONG lGuestRc;
            hrc = errorInfo->COMGETTER(ResultDetail)(&lGuestRc);
            ComAssertComRC(hrc);
            if (RT_FAILURE((int)lGuestRc))
                vrc = VERR_GSTCTL_GUEST_ERROR;
            if (pvrcGuest)
                *pvrcGuest = (int)lGuestRc;

            LogFlowThisFunc(("Status changed event for session ID=%RU32, new status is: %RU32 (%Rrc)\n",
                             mData.mSession.mID, sessionStatus,
                             RT_SUCCESS((int)lGuestRc) ? VINF_SUCCESS : (int)lGuestRc));
        }
        else /** @todo Re-visit this. Can this happen more frequently? */
            AssertMsgFailedReturn(("Got unexpected event type %#x\n", evtType), VERR_WRONG_ORDER);
    }
    /* waitForEvent may also return VERR_GSTCTL_GUEST_ERROR like we do above, so make pvrcGuest is set. */
    else if (vrc == VERR_GSTCTL_GUEST_ERROR && pvrcGuest)
        *pvrcGuest = pEvent->GuestResult();
    Assert(vrc != VERR_GSTCTL_GUEST_ERROR || !pvrcGuest || *pvrcGuest != (int)0xcccccccc);

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

// implementation of public methods
/////////////////////////////////////////////////////////////////////////////

HRESULT GuestSession::close()
{
    LogFlowThisFuncEnter();

    /* Note: Don't check if the session is ready via i_isStartedExternal() here;
     *       the session (already) could be in a stopped / aborted state. */

    int vrc      = VINF_SUCCESS; /* Shut up MSVC. */
    int vrcGuest = VINF_SUCCESS;

    uint32_t msTimeout = RT_MS_10SEC; /* 10s timeout by default */
    for (int i = 0; i < 3; i++)
    {
        if (i)
        {
            LogRel(("Guest Control: Closing session '%s' timed out (%RU32s timeout, attempt %d/10), retrying ...\n",
                    mData.mSession.mName.c_str(), msTimeout / RT_MS_1SEC, i + 1));
            msTimeout += RT_MS_5SEC; /* Slightly increase the timeout. */
        }

        /* Close session on guest. */
        vrc = i_closeSession(0 /* Flags */, msTimeout, &vrcGuest);
        if (   RT_SUCCESS(vrc)
            || vrc != VERR_TIMEOUT) /* If something else happened there is no point in retrying further. */
            break;
    }

    /* On failure don't return here, instead do all the cleanup
     * work first and then return an error. */

    /* Destroy session + remove ourselves from the session list. */
    AssertPtr(mParent);
    int vrc2 = mParent->i_sessionDestroy(mData.mSession.mID);
    if (vrc2 == VERR_NOT_FOUND) /* Not finding the session anymore isn't critical. */
        vrc2 = VINF_SUCCESS;

    if (RT_SUCCESS(vrc))
        vrc = vrc2;

    LogFlowThisFunc(("Returning vrc=%Rrc, vrcGuest=%Rrc\n", vrc, vrcGuest));

    if (RT_FAILURE(vrc))
    {
        if (vrc == VERR_GSTCTL_GUEST_ERROR)
        {
            GuestErrorInfo ge(GuestErrorInfo::Type_Session, vrcGuest, mData.mSession.mName.c_str());
            return setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Closing guest session failed: %s"),
                                GuestBase::getErrorAsString(ge).c_str());
        }
        return setError(VBOX_E_IPRT_ERROR, tr("Closing guest session \"%s\" failed with %Rrc"),
                        mData.mSession.mName.c_str(), vrc);
    }

    return S_OK;
}

HRESULT GuestSession::fileCopy(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                               const std::vector<FileCopyFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
{
    RT_NOREF(aSource, aDestination, aFlags, aProgress);
    ReturnComNotImplemented();
}

HRESULT GuestSession::fileCopyFromGuest(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                                        const std::vector<FileCopyFlag_T> &aFlags,
                                        ComPtr<IProgress> &aProgress)
{
    uint32_t fFlags = FileCopyFlag_None;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
            fFlags |= aFlags[i];

        const uint32_t fValidFlags = FileCopyFlag_None | FileCopyFlag_NoReplace | FileCopyFlag_FollowLinks | FileCopyFlag_Update;
        if (fFlags & ~fValidFlags)
            return setError(E_INVALIDARG,tr("Unknown flags: flags value %#x, invalid: %#x"), fFlags, fFlags & ~fValidFlags);
    }

    GuestSessionFsSourceSet SourceSet;

    GuestSessionFsSourceSpec source;
    source.strSource      = aSource;
    source.enmType        = FsObjType_File;
    source.enmPathStyle   = i_getGuestPathStyle();
    source.fDryRun        = false; /** @todo Implement support for a dry run. */
    source.fDirCopyFlags  = DirectoryCopyFlag_None;
    source.fFileCopyFlags = (FileCopyFlag_T)fFlags;

    SourceSet.push_back(source);

    return i_copyFromGuest(SourceSet, aDestination, aProgress);
}

HRESULT GuestSession::fileCopyToGuest(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                                      const std::vector<FileCopyFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
{
    uint32_t fFlags = FileCopyFlag_None;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
            fFlags |= aFlags[i];

        const uint32_t fValidFlags = FileCopyFlag_None | FileCopyFlag_NoReplace | FileCopyFlag_FollowLinks | FileCopyFlag_Update;
        if (fFlags & ~fValidFlags)
            return setError(E_INVALIDARG,tr("Unknown flags: flags value %#x, invalid: %#x"), fFlags, fFlags & ~fValidFlags);
    }

    GuestSessionFsSourceSet SourceSet;

    GuestSessionFsSourceSpec source;
    source.strSource      = aSource;
    source.enmType        = FsObjType_File;
    source.enmPathStyle   = GuestSession::i_getHostPathStyle();
    source.fDryRun        = false; /** @todo Implement support for a dry run. */
    source.fDirCopyFlags  = DirectoryCopyFlag_None;
    source.fFileCopyFlags = (FileCopyFlag_T)fFlags;

    SourceSet.push_back(source);

    return i_copyToGuest(SourceSet, aDestination, aProgress);
}

HRESULT GuestSession::copyFromGuest(const std::vector<com::Utf8Str> &aSources, const std::vector<com::Utf8Str> &aFilters,
                                    const std::vector<com::Utf8Str> &aFlags, const com::Utf8Str &aDestination,
                                    ComPtr<IProgress> &aProgress)
{
    const size_t cSources = aSources.size();
    if (   (aFilters.size() && aFilters.size() != cSources)
        || (aFlags.size()   && aFlags.size()   != cSources))
    {
        return setError(E_INVALIDARG, tr("Parameter array sizes don't match to the number of sources specified"));
    }

    GuestSessionFsSourceSet SourceSet;

    std::vector<com::Utf8Str>::const_iterator itSource = aSources.begin();
    std::vector<com::Utf8Str>::const_iterator itFilter = aFilters.begin();
    std::vector<com::Utf8Str>::const_iterator itFlags  = aFlags.begin();

    const bool fContinueOnErrors = false; /** @todo Do we want a flag for that? */
    const bool fFollowSymlinks   = true;  /** @todo Ditto. */

    while (itSource != aSources.end())
    {
        GuestFsObjData objData;
        int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
        int vrc = i_fsQueryInfo(*(itSource), fFollowSymlinks, objData, &vrcGuest);
        if (   RT_FAILURE(vrc)
            && !fContinueOnErrors)
        {
            if (GuestProcess::i_isGuestError(vrc))
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_Process, vrcGuest, (*itSource).c_str());
                return setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying type for guest source failed: %s"),
                                    GuestBase::getErrorAsString(ge).c_str());
            }
            return setError(E_FAIL, tr("Querying type for guest source \"%s\" failed: %Rrc"), (*itSource).c_str(), vrc);
        }

        Utf8Str strFlags;
        if (itFlags != aFlags.end())
        {
            strFlags = *itFlags;
            ++itFlags;
        }

        Utf8Str strFilter;
        if (itFilter != aFilters.end())
        {
            strFilter = *itFilter;
            ++itFilter;
        }

        GuestSessionFsSourceSpec source;
        source.strSource    = *itSource;
        source.strFilter    = strFilter;
        source.enmType      = objData.mType;
        source.enmPathStyle = i_getGuestPathStyle();
        source.fDryRun      = false; /** @todo Implement support for a dry run. */

        /* Check both flag groups here, as copying a directory also could mean to explicitly
         * *not* replacing any existing files (or just copy files which are newer, for instance). */
        GuestSession::i_directoryCopyFlagFromStr(strFlags, false /* fStrict */, &source.fDirCopyFlags);
        GuestSession::i_fileCopyFlagFromStr(strFlags, false /* fStrict */, &source.fFileCopyFlags);

        SourceSet.push_back(source);

        ++itSource;
    }

    return i_copyFromGuest(SourceSet, aDestination, aProgress);
}

HRESULT GuestSession::copyToGuest(const std::vector<com::Utf8Str> &aSources, const std::vector<com::Utf8Str> &aFilters,
                                  const std::vector<com::Utf8Str> &aFlags, const com::Utf8Str &aDestination,
                                  ComPtr<IProgress> &aProgress)
{
    const size_t cSources = aSources.size();
    if (   (aFilters.size() && aFilters.size() != cSources)
        || (aFlags.size()   && aFlags.size()   != cSources))
    {
        return setError(E_INVALIDARG, tr("Parameter array sizes don't match to the number of sources specified"));
    }

    GuestSessionFsSourceSet SourceSet;

    std::vector<com::Utf8Str>::const_iterator itSource = aSources.begin();
    std::vector<com::Utf8Str>::const_iterator itFilter = aFilters.begin();
    std::vector<com::Utf8Str>::const_iterator itFlags  = aFlags.begin();

    const bool fContinueOnErrors = false; /** @todo Do we want a flag for that? */

    while (itSource != aSources.end())
    {
        RTFSOBJINFO objInfo;
        int vrc = RTPathQueryInfo((*itSource).c_str(), &objInfo, RTFSOBJATTRADD_NOTHING);
        if (   RT_FAILURE(vrc)
            && !fContinueOnErrors)
        {
            return setError(E_FAIL, tr("Unable to query type for source '%s' (%Rrc)"), (*itSource).c_str(), vrc);
        }

        Utf8Str strFlags;
        if (itFlags != aFlags.end())
        {
            strFlags = *itFlags;
            ++itFlags;
        }

        Utf8Str strFilter;
        if (itFilter != aFilters.end())
        {
            strFilter = *itFilter;
            ++itFilter;
        }

        GuestSessionFsSourceSpec source;
        source.strSource    = *itSource;
        source.strFilter    = strFilter;
        source.enmType      = GuestBase::fileModeToFsObjType(objInfo.Attr.fMode);
        source.enmPathStyle = GuestSession::i_getHostPathStyle();
        source.fDryRun      = false; /** @todo Implement support for a dry run. */

        GuestSession::i_directoryCopyFlagFromStr(strFlags, false /* fStrict */, &source.fDirCopyFlags);
        GuestSession::i_fileCopyFlagFromStr(strFlags, false /* fStrict */, &source.fFileCopyFlags);

        SourceSet.push_back(source);

        ++itSource;
    }

    /* (Re-)Validate stuff. */
    if (RT_UNLIKELY(SourceSet.size() == 0)) /* At least one source must be present. */
        return setError(E_INVALIDARG, tr("No sources specified"));
    if (RT_UNLIKELY(SourceSet[0].strSource.isEmpty()))
        return setError(E_INVALIDARG, tr("First source entry is empty"));
    if (RT_UNLIKELY(aDestination.isEmpty()))
        return setError(E_INVALIDARG, tr("No destination specified"));

    return i_copyToGuest(SourceSet, aDestination, aProgress);
}

HRESULT GuestSession::directoryCopy(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                                    const std::vector<DirectoryCopyFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
{
    RT_NOREF(aSource, aDestination, aFlags, aProgress);
    ReturnComNotImplemented();
}

HRESULT GuestSession::directoryCopyFromGuest(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                                             const std::vector<DirectoryCopyFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
{
    uint32_t fFlags = DirectoryCopyFlag_None;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
            fFlags |= aFlags[i];

        const uint32_t fValidFlags =   DirectoryCopyFlag_None | DirectoryCopyFlag_CopyIntoExisting | DirectoryCopyFlag_Recursive
                                     | DirectoryCopyFlag_FollowLinks;
        if (fFlags & ~fValidFlags)
            return setError(E_INVALIDARG,tr("Unknown flags: flags value %#x, invalid: %#x"), fFlags, fFlags & ~fValidFlags);
    }

    GuestSessionFsSourceSet SourceSet;

    GuestSessionFsSourceSpec source;
    source.strSource      = aSource;
    source.enmType        = FsObjType_Directory;
    source.enmPathStyle   = i_getGuestPathStyle();
    source.fDryRun        = false; /** @todo Implement support for a dry run. */
    source.fDirCopyFlags  = (DirectoryCopyFlag_T)fFlags;
    source.fFileCopyFlags = FileCopyFlag_None; /* Overwrite existing files. */

    SourceSet.push_back(source);

    return i_copyFromGuest(SourceSet, aDestination, aProgress);
}

HRESULT GuestSession::directoryCopyToGuest(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                                           const std::vector<DirectoryCopyFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
{
    uint32_t fFlags = DirectoryCopyFlag_None;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
            fFlags |= aFlags[i];

        const uint32_t fValidFlags =   DirectoryCopyFlag_None | DirectoryCopyFlag_CopyIntoExisting | DirectoryCopyFlag_Recursive
                                     | DirectoryCopyFlag_FollowLinks;
        if (fFlags & ~fValidFlags)
            return setError(E_INVALIDARG,tr("Unknown flags: flags value %#x, invalid: %#x"), fFlags, fFlags & ~fValidFlags);
    }

    GuestSessionFsSourceSet SourceSet;

    GuestSessionFsSourceSpec source;
    source.strSource      = aSource;
    source.enmType        = FsObjType_Directory;
    source.enmPathStyle   = GuestSession::i_getHostPathStyle();
    source.fDryRun        = false; /** @todo Implement support for a dry run. */
    source.fDirCopyFlags  = (DirectoryCopyFlag_T)fFlags;
    source.fFileCopyFlags = FileCopyFlag_None; /* Overwrite existing files. */

    SourceSet.push_back(source);

    return i_copyToGuest(SourceSet, aDestination, aProgress);
}

HRESULT GuestSession::directoryCreate(const com::Utf8Str &aPath, ULONG aMode,
                                      const std::vector<DirectoryCreateFlag_T> &aFlags)
{
    if (RT_UNLIKELY((aPath.c_str()) == NULL || *(aPath.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No directory to create specified"));

    uint32_t fFlags = DirectoryCreateFlag_None;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
            fFlags |= aFlags[i];

        if (fFlags & ~DirectoryCreateFlag_Parents)
            return setError(E_INVALIDARG, tr("Unknown flags (%#x)"), fFlags);
    }

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    ComObjPtr <GuestDirectory> pDirectory;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_directoryCreate(aPath, (uint32_t)aMode, fFlags, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        if (GuestProcess::i_isGuestError(vrc))
        {
            GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, aPath.c_str());
            return setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Guest directory creation failed: %s"),
                                GuestBase::getErrorAsString(ge).c_str());
        }
        switch (vrc)
        {
            case VERR_INVALID_PARAMETER:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Guest directory creation failed: Invalid parameters given"));
                break;

            case VERR_BROKEN_PIPE:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Guest directory creation failed: Unexpectedly aborted"));
                break;

            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Guest directory creation failed: %Rrc"), vrc);
                break;
        }
    }

    return hrc;
}

HRESULT GuestSession::directoryCreateTemp(const com::Utf8Str &aTemplateName, ULONG aMode, const com::Utf8Str &aPath,
                                          BOOL aSecure, com::Utf8Str &aDirectory)
{
    if (RT_UNLIKELY((aTemplateName.c_str()) == NULL || *(aTemplateName.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No template specified"));
    if (RT_UNLIKELY((aPath.c_str()) == NULL || *(aPath.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No directory name specified"));
    if (!aSecure) /* Ignore what mode is specified when a secure temp thing needs to be created. */
        if (RT_UNLIKELY(aMode & ~07777))
            return setError(E_INVALIDARG, tr("Mode invalid (must be specified in octal mode)"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fsCreateTemp(aTemplateName, aPath, true /* Directory */, aDirectory, aMode, RT_BOOL(aSecure), &vrcGuest);
    if (!RT_SUCCESS(vrc))
    {
        switch (vrc)
        {
            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_ToolMkTemp, vrcGuest, aPath.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Temporary guest directory creation failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            default:
               hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Temporary guest directory creation \"%s\" with template \"%s\" failed: %Rrc"),
                                  aPath.c_str(), aTemplateName.c_str(), vrc);
               break;
        }
    }

    return hrc;
}

HRESULT GuestSession::directoryExists(const com::Utf8Str &aPath, BOOL aFollowSymlinks, BOOL *aExists)
{
    if (RT_UNLIKELY(aPath.isEmpty()))
        return setError(E_INVALIDARG, tr("Empty path"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    GuestFsObjData objData;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;

    int vrc = i_directoryQueryInfo(aPath, aFollowSymlinks != FALSE, objData, &vrcGuest);
    if (RT_SUCCESS(vrc))
        *aExists = TRUE;
    else
    {
        switch (vrc)
        {
            case VERR_GSTCTL_GUEST_ERROR:
            {
                switch (vrcGuest)
                {
                    case VERR_PATH_NOT_FOUND:
                        *aExists = FALSE;
                        break;
                    default:
                    {
                        GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, aPath.c_str());
                        hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying directory existence failed: %s"),
                                           GuestBase::getErrorAsString(ge).c_str());
                        break;
                    }
                }
                break;
            }

            case VERR_NOT_A_DIRECTORY:
            {
                *aExists = FALSE;
                break;
            }

            default:
               hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Querying directory existence \"%s\" failed: %Rrc"),
                                  aPath.c_str(), vrc);
               break;
        }
    }

    return hrc;
}

HRESULT GuestSession::directoryOpen(const com::Utf8Str &aPath, const com::Utf8Str &aFilter,
                                    const std::vector<DirectoryOpenFlag_T> &aFlags, ComPtr<IGuestDirectory> &aDirectory)
{
    if (RT_UNLIKELY((aPath.c_str()) == NULL || *(aPath.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No directory to open specified"));
    if (RT_UNLIKELY((aFilter.c_str()) != NULL && *(aFilter.c_str()) != '\0'))
        return setError(E_INVALIDARG, tr("Directory filters are not implemented yet"));

    uint32_t fFlags = DirectoryOpenFlag_None;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
            fFlags |= aFlags[i];

        if (fFlags)
            return setError(E_INVALIDARG, tr("Open flags (%#x) not implemented yet"), fFlags);
    }

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    GuestDirectoryOpenInfo openInfo;
    openInfo.mPath = aPath;
    openInfo.mFilter = aFilter;
    openInfo.mFlags = fFlags;

    ComObjPtr<GuestDirectory> pDirectory;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_directoryOpen(openInfo, pDirectory, &vrcGuest);
    if (RT_SUCCESS(vrc))
    {
        /* Return directory object to the caller. */
        hrc = pDirectory.queryInterfaceTo(aDirectory.asOutParam());
    }
    else
    {
        switch (vrc)
        {
            case VERR_INVALID_PARAMETER:
               hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Opening guest directory \"%s\" failed; invalid parameters given"),
                                  aPath.c_str());
               break;

            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, aPath.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Opening guest directory failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            default:
               hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Opening guest directory \"%s\" failed: %Rrc"), aPath.c_str(), vrc);
               break;
        }
    }

    return hrc;
}

HRESULT GuestSession::directoryRemove(const com::Utf8Str &aPath)
{
    if (RT_UNLIKELY(aPath.c_str() == NULL || *aPath.c_str() == '\0'))
        return setError(E_INVALIDARG, tr("No directory to remove specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    /* No flags; only remove the directory when empty. */
    uint32_t fFlags = DIRREMOVEREC_FLAG_NONE;

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_directoryRemove(aPath, fFlags, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        switch (vrc)
        {
            case VERR_NOT_SUPPORTED:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                   tr("Handling removing guest directories not supported by installed Guest Additions"));
                break;

            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, aPath.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Removing guest directory failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Removing guest directory \"%s\" failed: %Rrc"), aPath.c_str(), vrc);
                break;
        }
    }

    return hrc;
}

HRESULT GuestSession::directoryRemoveRecursive(const com::Utf8Str &aPath, const std::vector<DirectoryRemoveRecFlag_T> &aFlags,
                                               ComPtr<IProgress> &aProgress)
{
    if (RT_UNLIKELY(aPath.c_str() == NULL || *aPath.c_str() == '\0'))
        return setError(E_INVALIDARG, tr("No directory to remove recursively specified"));

    /* By defautl remove recursively as the function name implies. */
    uint32_t fFlags = DIRREMOVEREC_FLAG_RECURSIVE;
    if (aFlags.size())
    {
        for (size_t i = 0; i < aFlags.size(); i++)
        {
            switch (aFlags[i])
            {
                case DirectoryRemoveRecFlag_None: /* Skip. */
                    continue;

                case DirectoryRemoveRecFlag_ContentAndDir:
                    fFlags |= DIRREMOVEREC_FLAG_CONTENT_AND_DIR;
                    break;

                case DirectoryRemoveRecFlag_ContentOnly:
                    fFlags |= DIRREMOVEREC_FLAG_CONTENT_ONLY;
                    break;

                default:
                    return setError(E_INVALIDARG, tr("Invalid flags specified"));
            }
        }
    }

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    ComObjPtr<Progress> pProgress;
    hrc = pProgress.createObject();
    if (SUCCEEDED(hrc))
        hrc = pProgress->init(static_cast<IGuestSession *>(this),
                              Bstr(tr("Removing guest directory")).raw(),
                              TRUE /*aCancelable*/);
    if (FAILED(hrc))
        return hrc;

    /* Note: At the moment we don't supply progress information while
     *       deleting a guest directory recursively. So just complete
     *       the progress object right now. */
     /** @todo Implement progress reporting on guest directory deletion! */
    hrc = pProgress->i_notifyComplete(S_OK);
    if (FAILED(hrc))
        return hrc;

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_directoryRemove(aPath, fFlags, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        switch (vrc)
        {
            case VERR_NOT_SUPPORTED:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                   tr("Handling removing guest directories recursively not supported by installed Guest Additions"));
                break;

            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_Directory, vrcGuest, aPath.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Recursively removing guest directory failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Recursively removing guest directory \"%s\" failed: %Rrc"),
                                   aPath.c_str(), vrc);
                break;
        }
    }
    else
    {
        pProgress.queryInterfaceTo(aProgress.asOutParam());
    }

    return hrc;
}

HRESULT GuestSession::environmentScheduleSet(const com::Utf8Str &aName, const com::Utf8Str &aValue)
{
    LogFlowThisFuncEnter();
    int vrc;
    {
        AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
        vrc = mData.mEnvironmentChanges.setVariable(aName, aValue);
    }
    HRESULT hrc;
    if (RT_SUCCESS(vrc))
        hrc = S_OK;
    else if (vrc == VERR_ENV_INVALID_VAR_NAME)
        hrc = setError(E_INVALIDARG, tr("Invalid environment variable name '%s'"), aName.c_str());
    else
        hrc = setErrorVrc(vrc, tr("Failed to schedule setting environment variable '%s' to '%s'"), aName.c_str(), aValue.c_str());

    LogFlowThisFuncLeave();
    return hrc;
}

HRESULT GuestSession::environmentScheduleUnset(const com::Utf8Str &aName)
{
    LogFlowThisFuncEnter();
    int vrc;
    {
        AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
        vrc = mData.mEnvironmentChanges.unsetVariable(aName);
    }
    HRESULT hrc;
    if (RT_SUCCESS(vrc))
        hrc = S_OK;
    else if (vrc == VERR_ENV_INVALID_VAR_NAME)
        hrc = setError(E_INVALIDARG, tr("Invalid environment variable name '%s'"), aName.c_str());
    else
        hrc = setErrorVrc(vrc, tr("Failed to schedule unsetting environment variable '%s'"), aName.c_str());

    LogFlowThisFuncLeave();
    return hrc;
}

HRESULT GuestSession::environmentGetBaseVariable(const com::Utf8Str &aName, com::Utf8Str &aValue)
{
    LogFlowThisFuncEnter();
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    HRESULT hrc;
    if (mData.mpBaseEnvironment)
    {
        int vrc = mData.mpBaseEnvironment->getVariable(aName, &aValue);
        if (RT_SUCCESS(vrc))
            hrc = S_OK;
        else if (vrc == VERR_ENV_INVALID_VAR_NAME)
            hrc = setError(E_INVALIDARG, tr("Invalid environment variable name '%s'"), aName.c_str());
        else
            hrc = setErrorVrc(vrc);
    }
    else if (mData.mProtocolVersion < 99999)
        hrc = setError(VBOX_E_NOT_SUPPORTED, tr("The base environment feature is not supported by the Guest Additions"));
    else
        hrc = setError(VBOX_E_INVALID_OBJECT_STATE, tr("The base environment has not yet been reported by the guest"));

    LogFlowThisFuncLeave();
    return hrc;
}

HRESULT GuestSession::environmentDoesBaseVariableExist(const com::Utf8Str &aName, BOOL *aExists)
{
    LogFlowThisFuncEnter();
    *aExists = FALSE;
    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    HRESULT hrc;
    if (mData.mpBaseEnvironment)
    {
        hrc = S_OK;
        *aExists = mData.mpBaseEnvironment->doesVariableExist(aName);
    }
    else if (mData.mProtocolVersion < 99999)
        hrc = setError(VBOX_E_NOT_SUPPORTED, tr("The base environment feature is not supported by the Guest Additions"));
    else
        hrc = setError(VBOX_E_INVALID_OBJECT_STATE, tr("The base environment has not yet been reported by the guest"));

    LogFlowThisFuncLeave();
    return hrc;
}

HRESULT GuestSession::fileCreateTemp(const com::Utf8Str &aTemplateName, ULONG aMode, const com::Utf8Str &aPath, BOOL aSecure,
                                     ComPtr<IGuestFile> &aFile)
{
    RT_NOREF(aTemplateName, aMode, aPath, aSecure, aFile);
    ReturnComNotImplemented();
}

HRESULT GuestSession::fileExists(const com::Utf8Str &aPath, BOOL aFollowSymlinks, BOOL *aExists)
{
    /* By default we return non-existent. */
    *aExists = FALSE;

    if (RT_UNLIKELY((aPath.c_str()) == NULL || *(aPath.c_str()) == '\0'))
        return S_OK;

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    GuestFsObjData objData;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fileQueryInfo(aPath, RT_BOOL(aFollowSymlinks), objData, &vrcGuest);
    if (RT_SUCCESS(vrc))
    {
        *aExists = TRUE;
        return S_OK;
    }

    switch (vrc)
    {
        case VERR_GSTCTL_GUEST_ERROR:
        {
            switch (vrcGuest)
            {
                case VERR_PATH_NOT_FOUND:
                    RT_FALL_THROUGH();
                case VERR_FILE_NOT_FOUND:
                    break;

                default:
                {
                    GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, aPath.c_str());
                    hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying guest file existence failed: %s"),
                                       GuestBase::getErrorAsString(ge).c_str());
                    break;
                }
            }

            break;
        }

        case VERR_NOT_A_FILE:
            break;

        default:
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Querying guest file information for \"%s\" failed: %Rrc"),
                               aPath.c_str(), vrc);
            break;
    }

    return hrc;
}

HRESULT GuestSession::fileOpen(const com::Utf8Str &aPath, FileAccessMode_T aAccessMode, FileOpenAction_T aOpenAction,
                               ULONG aCreationMode, ComPtr<IGuestFile> &aFile)
{
    LogFlowThisFuncEnter();

    const std::vector<FileOpenExFlag_T> EmptyFlags;
    return fileOpenEx(aPath, aAccessMode, aOpenAction, FileSharingMode_All, aCreationMode, EmptyFlags, aFile);
}

HRESULT GuestSession::fileOpenEx(const com::Utf8Str &aPath, FileAccessMode_T aAccessMode, FileOpenAction_T aOpenAction,
                                 FileSharingMode_T aSharingMode, ULONG aCreationMode,
                                 const std::vector<FileOpenExFlag_T> &aFlags, ComPtr<IGuestFile> &aFile)
{
    if (RT_UNLIKELY((aPath.c_str()) == NULL || *(aPath.c_str()) == '\0'))
        return setError(E_INVALIDARG, tr("No file to open specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFuncEnter();

    /* Validate aAccessMode. */
    switch (aAccessMode)
    {
        case FileAccessMode_ReadOnly:
            RT_FALL_THRU();
        case FileAccessMode_WriteOnly:
            RT_FALL_THRU();
        case FileAccessMode_ReadWrite:
            break;
        case FileAccessMode_AppendOnly:
            RT_FALL_THRU();
        case FileAccessMode_AppendRead:
            return setError(E_NOTIMPL, tr("Append access modes are not yet implemented"));
        default:
            return setError(E_INVALIDARG, tr("Unknown FileAccessMode value %u (%#x)"), aAccessMode, aAccessMode);
    }

    /* Validate aOpenAction to the old format. */
    switch (aOpenAction)
    {
        case FileOpenAction_OpenExisting:
            RT_FALL_THRU();
        case FileOpenAction_OpenOrCreate:
            RT_FALL_THRU();
        case FileOpenAction_CreateNew:
            RT_FALL_THRU();
        case FileOpenAction_CreateOrReplace:
            RT_FALL_THRU();
        case FileOpenAction_OpenExistingTruncated:
            RT_FALL_THRU();
        case FileOpenAction_AppendOrCreate:
            break;
        default:
            return setError(E_INVALIDARG, tr("Unknown FileOpenAction value %u (%#x)"), aAccessMode, aAccessMode);
    }

    /* Validate aSharingMode. */
    switch (aSharingMode)
    {
        case FileSharingMode_All:
            break;
        case FileSharingMode_Read:
        case FileSharingMode_Write:
        case FileSharingMode_ReadWrite:
        case FileSharingMode_Delete:
        case FileSharingMode_ReadDelete:
        case FileSharingMode_WriteDelete:
            return setError(E_NOTIMPL, tr("Only FileSharingMode_All is currently implemented"));

        default:
            return setError(E_INVALIDARG, tr("Unknown FileOpenAction value %u (%#x)"), aAccessMode, aAccessMode);
    }

    /* Combine and validate flags. */
    uint32_t fOpenEx = 0;
    for (size_t i = 0; i < aFlags.size(); i++)
        fOpenEx |= aFlags[i];
    if (fOpenEx)
        return setError(E_INVALIDARG, tr("Unsupported FileOpenExFlag value(s) in aFlags (%#x)"), fOpenEx);

    ComObjPtr <GuestFile> pFile;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fileOpenEx(aPath, aAccessMode, aOpenAction, aSharingMode, aCreationMode, aFlags, pFile, &vrcGuest);
    if (RT_SUCCESS(vrc))
        /* Return directory object to the caller. */
        hrc = pFile.queryInterfaceTo(aFile.asOutParam());
    else
    {
        switch (vrc)
        {
            case VERR_NOT_SUPPORTED:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                   tr("Handling guest files not supported by installed Guest Additions"));
                break;

            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_File, vrcGuest, aPath.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Opening guest file failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Opening guest file \"%s\" failed: %Rrc"), aPath.c_str(), vrc);
                break;
        }
    }

    return hrc;
}

HRESULT GuestSession::fileQuerySize(const com::Utf8Str &aPath, BOOL aFollowSymlinks, LONG64 *aSize)
{
    if (aPath.isEmpty())
        return setError(E_INVALIDARG, tr("No path specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    int64_t llSize;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fileQuerySize(aPath, aFollowSymlinks != FALSE,  &llSize, &vrcGuest);
    if (RT_SUCCESS(vrc))
        *aSize = llSize;
    else
    {
        if (GuestProcess::i_isGuestError(vrc))
        {
            GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, aPath.c_str());
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying guest file size failed: %s"),
                               GuestBase::getErrorAsString(ge).c_str());
        }
        else
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Querying guest file size of \"%s\" failed: %Rrc"),
                               vrc, aPath.c_str());
    }

    return hrc;
}

HRESULT GuestSession::fsQueryFreeSpace(const com::Utf8Str &aPath, LONG64 *aFreeSpace)
{
    RT_NOREF(aPath, aFreeSpace);

    return E_NOTIMPL;
}

HRESULT GuestSession::fsQueryInfo(const com::Utf8Str &aPath, ComPtr<IGuestFsInfo> &aInfo)
{
    RT_NOREF(aPath, aInfo);

    return E_NOTIMPL;
}

HRESULT GuestSession::fsObjExists(const com::Utf8Str &aPath, BOOL aFollowSymlinks, BOOL *aExists)
{
    if (aPath.isEmpty())
        return setError(E_INVALIDARG, tr("No path specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFunc(("aPath=%s, aFollowSymlinks=%RTbool\n", aPath.c_str(), RT_BOOL(aFollowSymlinks)));

    *aExists = false;

    GuestFsObjData objData;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fsQueryInfo(aPath, aFollowSymlinks != FALSE, objData, &vrcGuest);
    if (RT_SUCCESS(vrc))
        *aExists = TRUE;
    else
    {
        if (GuestProcess::i_isGuestError(vrc))
        {
            if (   vrcGuest == VERR_NOT_A_FILE
                || vrcGuest == VERR_PATH_NOT_FOUND
                || vrcGuest == VERR_FILE_NOT_FOUND
                || vrcGuest == VERR_INVALID_NAME)
                hrc = S_OK; /* Ignore these vrc values. */
            else
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, aPath.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying guest file existence information failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
            }
        }
        else
            hrc = setErrorVrc(vrc, tr("Querying guest file existence information for \"%s\" failed: %Rrc"), aPath.c_str(), vrc);
    }

    return hrc;
}

HRESULT GuestSession::fsObjQueryInfo(const com::Utf8Str &aPath, BOOL aFollowSymlinks, ComPtr<IGuestFsObjInfo> &aInfo)
{
    if (aPath.isEmpty())
        return setError(E_INVALIDARG, tr("No path specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFunc(("aPath=%s, aFollowSymlinks=%RTbool\n", aPath.c_str(), RT_BOOL(aFollowSymlinks)));

    GuestFsObjData Info;
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fsQueryInfo(aPath, aFollowSymlinks != FALSE, Info, &vrcGuest);
    if (RT_SUCCESS(vrc))
    {
        ComObjPtr<GuestFsObjInfo> ptrFsObjInfo;
        hrc = ptrFsObjInfo.createObject();
        if (SUCCEEDED(hrc))
        {
            vrc = ptrFsObjInfo->init(Info);
            if (RT_SUCCESS(vrc))
                hrc = ptrFsObjInfo.queryInterfaceTo(aInfo.asOutParam());
            else
                hrc = setErrorVrc(vrc);
        }
    }
    else
    {
        if (GuestProcess::i_isGuestError(vrc))
        {
            GuestErrorInfo ge(GuestErrorInfo::Type_ToolStat, vrcGuest, aPath.c_str());
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Querying guest file information failed: %s"),
                               GuestBase::getErrorAsString(ge).c_str());
        }
        else
            hrc = setErrorVrc(vrc, tr("Querying guest file information for \"%s\" failed: %Rrc"), aPath.c_str(), vrc);
    }

    return hrc;
}

HRESULT GuestSession::fsObjRemove(const com::Utf8Str &aPath)
{
    if (RT_UNLIKELY(aPath.isEmpty()))
        return setError(E_INVALIDARG, tr("No path specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    LogFlowThisFunc(("aPath=%s\n", aPath.c_str()));

    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_fileRemove(aPath, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        if (GuestProcess::i_isGuestError(vrc))
        {
            GuestErrorInfo ge(GuestErrorInfo::Type_ToolRm, vrcGuest, aPath.c_str());
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Removing guest file failed: %s"),
                               GuestBase::getErrorAsString(ge).c_str());
        }
        else
            hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Removing guest file \"%s\" failed: %Rrc"), aPath.c_str(), vrc);
    }

    return hrc;
}

HRESULT GuestSession::fsObjRemoveArray(const std::vector<com::Utf8Str> &aPaths, ComPtr<IProgress> &aProgress)
{
    RT_NOREF(aPaths, aProgress);
    return E_NOTIMPL;
}

HRESULT GuestSession::fsObjRename(const com::Utf8Str &aSource,
                                  const com::Utf8Str &aDestination,
                                  const std::vector<FsObjRenameFlag_T> &aFlags)
{
    if (RT_UNLIKELY(aSource.isEmpty()))
        return setError(E_INVALIDARG, tr("No source path specified"));

    if (RT_UNLIKELY(aDestination.isEmpty()))
        return setError(E_INVALIDARG, tr("No destination path specified"));

    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    /* Combine, validate and convert flags. */
    uint32_t fApiFlags = 0;
    for (size_t i = 0; i < aFlags.size(); i++)
        fApiFlags |= aFlags[i];
    if (fApiFlags & ~((uint32_t)FsObjRenameFlag_NoReplace | (uint32_t)FsObjRenameFlag_Replace))
        return setError(E_INVALIDARG, tr("Unknown rename flag: %#x"), fApiFlags);

    LogFlowThisFunc(("aSource=%s, aDestination=%s\n", aSource.c_str(), aDestination.c_str()));

    AssertCompile(FsObjRenameFlag_NoReplace == 0);
    AssertCompile(FsObjRenameFlag_Replace != 0);
    uint32_t fBackend;
    if ((fApiFlags & ((uint32_t)FsObjRenameFlag_NoReplace | (uint32_t)FsObjRenameFlag_Replace)) == FsObjRenameFlag_Replace)
        fBackend = PATHRENAME_FLAG_REPLACE;
    else
        fBackend = PATHRENAME_FLAG_NO_REPLACE;

    /* Call worker to do the job. */
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS;
    int vrc = i_pathRename(aSource, aDestination, fBackend, &vrcGuest);
    if (RT_FAILURE(vrc))
    {
        switch (vrc)
        {
            case VERR_NOT_SUPPORTED:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                   tr("Handling renaming guest paths not supported by installed Guest Additions"));
                break;

            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_Process, vrcGuest, aSource.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Renaming guest path failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            default:
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc, tr("Renaming guest path \"%s\" failed: %Rrc"),
                                   aSource.c_str(), vrc);
                break;
        }
    }

    return hrc;
}

HRESULT GuestSession::fsObjMove(const com::Utf8Str &aSource, const com::Utf8Str &aDestination,
                                const std::vector<FsObjMoveFlag_T> &aFlags, ComPtr<IProgress> &aProgress)
{
    RT_NOREF(aSource, aDestination, aFlags, aProgress);
    ReturnComNotImplemented();
}

HRESULT GuestSession::fsObjMoveArray(const std::vector<com::Utf8Str> &aSource,
                                     const com::Utf8Str &aDestination,
                                     const std::vector<FsObjMoveFlag_T> &aFlags,
                                     ComPtr<IProgress> &aProgress)
{
    RT_NOREF(aSource, aDestination, aFlags, aProgress);
    ReturnComNotImplemented();
}

HRESULT GuestSession::fsObjCopyArray(const std::vector<com::Utf8Str> &aSource,
                                     const com::Utf8Str &aDestination,
                                     const std::vector<FileCopyFlag_T> &aFlags,
                                     ComPtr<IProgress> &aProgress)
{
    RT_NOREF(aSource, aDestination, aFlags, aProgress);
    ReturnComNotImplemented();
}

HRESULT GuestSession::fsObjSetACL(const com::Utf8Str &aPath, BOOL aFollowSymlinks, const com::Utf8Str &aAcl, ULONG aMode)
{
    RT_NOREF(aPath, aFollowSymlinks, aAcl, aMode);
    ReturnComNotImplemented();
}


HRESULT GuestSession::processCreate(const com::Utf8Str &aExecutable, const std::vector<com::Utf8Str> &aArguments,
                                    const std::vector<com::Utf8Str> &aEnvironment,
                                    const std::vector<ProcessCreateFlag_T> &aFlags,
                                    ULONG aTimeoutMS, ComPtr<IGuestProcess> &aGuestProcess)
{
    LogFlowThisFuncEnter();

    std::vector<LONG> affinityIgnored;
    return processCreateEx(aExecutable, aArguments, aEnvironment, aFlags, aTimeoutMS, ProcessPriority_Default,
                           affinityIgnored, aGuestProcess);
}

HRESULT GuestSession::processCreateEx(const com::Utf8Str &aExecutable, const std::vector<com::Utf8Str> &aArguments,
                                      const std::vector<com::Utf8Str> &aEnvironment,
                                      const std::vector<ProcessCreateFlag_T> &aFlags, ULONG aTimeoutMS,
                                      ProcessPriority_T aPriority, const std::vector<LONG> &aAffinity,
                                      ComPtr<IGuestProcess> &aGuestProcess)
{
    HRESULT hrc = i_isStartedExternal();
    if (FAILED(hrc))
        return hrc;

    /*
     * Must have an executable to execute.  If none is given, we try use the
     * zero'th argument.
     */
    const char *pszExecutable = aExecutable.c_str();
    if (RT_UNLIKELY(pszExecutable == NULL || *pszExecutable == '\0'))
    {
        if (aArguments.size() > 0)
            pszExecutable = aArguments[0].c_str();
        if (pszExecutable == NULL || *pszExecutable == '\0')
            return setError(E_INVALIDARG, tr("No command to execute specified"));
    }

    /* The rest of the input is being validated in i_processCreateEx(). */

    LogFlowThisFuncEnter();

    /*
     * Build the process startup info.
     */
    GuestProcessStartupInfo procInfo;

    /* Executable and arguments. */
    procInfo.mExecutable = pszExecutable;
    if (aArguments.size())
    {
        for (size_t i = 0; i < aArguments.size(); i++)
            procInfo.mArguments.push_back(aArguments[i]);
    }
    else /* If no arguments were given, add the executable as argv[0] by default. */
        procInfo.mArguments.push_back(procInfo.mExecutable);

    /* Combine the environment changes associated with the ones passed in by
       the caller, giving priority to the latter.  The changes are putenv style
       and will be applied to the standard environment for the guest user. */
    int vrc = procInfo.mEnvironmentChanges.copy(mData.mEnvironmentChanges);
    if (RT_SUCCESS(vrc))
    {
        size_t idxError = ~(size_t)0;
        vrc = procInfo.mEnvironmentChanges.applyPutEnvArray(aEnvironment, &idxError);
        if (RT_SUCCESS(vrc))
        {
            /* Convert the flag array into a mask. */
            if (aFlags.size())
                for (size_t i = 0; i < aFlags.size(); i++)
                    procInfo.mFlags |= aFlags[i];

            procInfo.mTimeoutMS = aTimeoutMS;

            /** @todo use RTCPUSET instead of archaic 64-bit variables! */
            if (aAffinity.size())
                for (size_t i = 0; i < aAffinity.size(); i++)
                    if (aAffinity[i])
                        procInfo.mAffinity |= (uint64_t)1 << i;

            procInfo.mPriority = aPriority;

            /*
             * Create a guest process object.
             */
            ComObjPtr<GuestProcess> pProcess;
            vrc = i_processCreateEx(procInfo, pProcess);
            if (RT_SUCCESS(vrc))
            {
                ComPtr<IGuestProcess> pIProcess;
                hrc = pProcess.queryInterfaceTo(pIProcess.asOutParam());
                if (SUCCEEDED(hrc))
                {
                    /*
                     * Start the process.
                     */
                    vrc = pProcess->i_startProcessAsync();
                    if (RT_SUCCESS(vrc))
                    {
                        aGuestProcess = pIProcess;

                        LogFlowFuncLeaveRC(vrc);
                        return S_OK;
                    }

                    hrc = setErrorVrc(vrc, tr("Failed to start guest process: %Rrc"), vrc);
                }
            }
            else if (vrc == VERR_GSTCTL_MAX_CID_OBJECTS_REACHED)
                hrc = setErrorVrc(vrc, tr("Maximum number of concurrent guest processes per session (%u) reached"),
                                 VBOX_GUESTCTRL_MAX_OBJECTS);
            else
                hrc = setErrorVrc(vrc, tr("Failed to create guest process object: %Rrc"), vrc);
        }
        else
            hrc = setErrorBoth(vrc == VERR_ENV_INVALID_VAR_NAME ? E_INVALIDARG : Global::vboxStatusCodeToCOM(vrc), vrc,
                              tr("Failed to apply environment variable '%s', index %u (%Rrc)'"),
                              aEnvironment[idxError].c_str(), idxError, vrc);
    }
    else
        hrc = setErrorVrc(vrc, tr("Failed to set up the environment: %Rrc"), vrc);

    LogFlowFuncLeaveRC(vrc);
    return hrc;
}

HRESULT GuestSession::processGet(ULONG aPid, ComPtr<IGuestProcess> &aGuestProcess)

{
    if (aPid == 0)
        return setError(E_INVALIDARG, tr("No valid process ID (PID) specified"));

    LogFlowThisFunc(("PID=%RU32\n", aPid));

    AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);

    HRESULT hrc = S_OK;

    ComObjPtr<GuestProcess> pProcess;
    int vrc = i_processGetByPID(aPid, &pProcess);
    if (RT_FAILURE(vrc))
        hrc = setError(E_INVALIDARG, tr("No process with PID %RU32 found"), aPid);

    /* This will set (*aProcess) to NULL if pProgress is NULL. */
    HRESULT hrc2 = pProcess.queryInterfaceTo(aGuestProcess.asOutParam());
    if (SUCCEEDED(hrc))
        hrc = hrc2;

    LogFlowThisFunc(("aProcess=%p, hrc=%Rhrc\n", (IGuestProcess*)aGuestProcess, hrc));
    return hrc;
}

HRESULT GuestSession::symlinkCreate(const com::Utf8Str &aSource, const com::Utf8Str &aTarget, SymlinkType_T aType)
{
    RT_NOREF(aSource, aTarget, aType);
    ReturnComNotImplemented();
}

HRESULT GuestSession::symlinkExists(const com::Utf8Str &aSymlink, BOOL *aExists)

{
    RT_NOREF(aSymlink, aExists);
    ReturnComNotImplemented();
}

HRESULT GuestSession::symlinkRead(const com::Utf8Str &aSymlink, const std::vector<SymlinkReadFlag_T> &aFlags,
                                  com::Utf8Str &aTarget)
{
    RT_NOREF(aSymlink, aFlags, aTarget);
    ReturnComNotImplemented();
}

HRESULT GuestSession::waitFor(ULONG aWaitFor, ULONG aTimeoutMS, GuestSessionWaitResult_T *aReason)
{
    /* Note: No call to i_isStartedExternal() needed here, as the session might not has been started (yet). */

    LogFlowThisFuncEnter();

    HRESULT hrc = S_OK;

    /*
     * Note: Do not hold any locks here while waiting!
     */
    int vrcGuest = VERR_IPE_UNINITIALIZED_STATUS; GuestSessionWaitResult_T waitResult;
    int vrc = i_waitFor(aWaitFor, aTimeoutMS, waitResult, &vrcGuest);
    if (RT_SUCCESS(vrc))
        *aReason = waitResult;
    else
    {
        switch (vrc)
        {
            case VERR_GSTCTL_GUEST_ERROR:
            {
                GuestErrorInfo ge(GuestErrorInfo::Type_Session, vrcGuest, mData.mSession.mName.c_str());
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrcGuest, tr("Waiting for guest process failed: %s"),
                                   GuestBase::getErrorAsString(ge).c_str());
                break;
            }
            case VERR_TIMEOUT:
                *aReason = GuestSessionWaitResult_Timeout;
                break;

            default:
            {
                const char *pszSessionName = mData.mSession.mName.c_str();
                hrc = setErrorBoth(VBOX_E_IPRT_ERROR, vrc,
                                   tr("Waiting for guest session \"%s\" failed: %Rrc"),
                                   pszSessionName ? pszSessionName : tr("Unnamed"), vrc);
                break;
            }
        }
    }

    LogFlowFuncLeaveRC(vrc);
    return hrc;
}

HRESULT GuestSession::waitForArray(const std::vector<GuestSessionWaitForFlag_T> &aWaitFor, ULONG aTimeoutMS,
                                   GuestSessionWaitResult_T *aReason)
{
    /* Note: No call to i_isStartedExternal() needed here, as the session might not has been started (yet). */

    LogFlowThisFuncEnter();

    /*
     * Note: Do not hold any locks here while waiting!
     */
    uint32_t fWaitFor = GuestSessionWaitForFlag_None;
    for (size_t i = 0; i < aWaitFor.size(); i++)
        fWaitFor |= aWaitFor[i];

    return WaitFor(fWaitFor, aTimeoutMS, aReason);
}