summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-client/GuestCtrlPrivate.cpp
blob: d05a5def3824fca58d2e6b32e7daebc2245c90e8 (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
/* $Id: GuestCtrlPrivate.cpp $ */
/** @file
 * Internal helpers/structures for guest control functionality.
 */

/*
 * Copyright (C) 2011-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_GUEST_CONTROL
#include "LoggingNew.h"

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

#include <iprt/asm.h>
#include <iprt/cpp/utils.h> /* For unconst(). */
#include <iprt/ctype.h>
#ifdef DEBUG
# include <iprt/file.h>
#endif
#include <iprt/fs.h>
#include <iprt/path.h>
#include <iprt/rand.h>
#include <iprt/time.h>
#include <VBox/AssertGuest.h>


/**
 * Extracts the timespec from a given stream block key.
 *
 * @return Pointer to handed-in timespec, or NULL if invalid / not found.
 * @param  strmBlk              Stream block to extract timespec from.
 * @param  strKey               Key to get timespec for.
 * @param  pTimeSpec            Where to store the extracted timespec.
 */
/* static */
PRTTIMESPEC GuestFsObjData::TimeSpecFromKey(const GuestProcessStreamBlock &strmBlk, const Utf8Str &strKey, PRTTIMESPEC pTimeSpec)
{
    AssertPtrReturn(pTimeSpec, NULL);

    Utf8Str strTime = strmBlk.GetString(strKey.c_str());
    if (strTime.isEmpty())
        return NULL;

    if (!RTTimeSpecFromString(pTimeSpec, strTime.c_str()))
        return NULL;

    return pTimeSpec;
}

/**
 * Extracts the nanoseconds relative from Unix epoch for a given stream block key.
 *
 * @return Nanoseconds relative from Unix epoch, or 0 if invalid / not found.
 * @param  strmBlk              Stream block to extract nanoseconds from.
 * @param  strKey               Key to get nanoseconds for.
 */
/* static */
int64_t GuestFsObjData::UnixEpochNsFromKey(const GuestProcessStreamBlock &strmBlk, const Utf8Str &strKey)
{
    RTTIMESPEC TimeSpec;
    if (!GuestFsObjData::TimeSpecFromKey(strmBlk, strKey, &TimeSpec))
        return 0;

    return TimeSpec.i64NanosecondsRelativeToUnixEpoch;
}

/**
 * Initializes this object data with a stream block from VBOXSERVICE_TOOL_LS.
 *
 * This is also used by FromStat since the output should be identical given that
 * they use the same output function on the guest side when fLong is true.
 *
 * @return VBox status code.
 * @param  strmBlk              Stream block to use for initialization.
 * @param  fLong                Whether the stream block contains long (detailed) information or not.
 */
int GuestFsObjData::FromLs(const GuestProcessStreamBlock &strmBlk, bool fLong)
{
    LogFlowFunc(("\n"));
#ifdef DEBUG
    strmBlk.DumpToLog();
#endif

    /* Object name. */
    mName = strmBlk.GetString("name");
    ASSERT_GUEST_RETURN(mName.isNotEmpty(), VERR_NOT_FOUND);

    /* Type & attributes. */
    bool fHaveAttribs = false;
    char szAttribs[32];
    memset(szAttribs, '?', sizeof(szAttribs) - 1);
    mType = FsObjType_Unknown;
    const char *psz = strmBlk.GetString("ftype");
    if (psz)
    {
        fHaveAttribs = true;
        szAttribs[0] = *psz;
        switch (*psz)
        {
            case '-':   mType = FsObjType_File; break;
            case 'd':   mType = FsObjType_Directory; break;
            case 'l':   mType = FsObjType_Symlink; break;
            case 'c':   mType = FsObjType_DevChar; break;
            case 'b':   mType = FsObjType_DevBlock; break;
            case 'f':   mType = FsObjType_Fifo; break;
            case 's':   mType = FsObjType_Socket; break;
            case 'w':   mType = FsObjType_WhiteOut; break;
            default:
                AssertMsgFailed(("%s\n", psz));
                szAttribs[0] = '?';
                fHaveAttribs = false;
                break;
        }
    }
    psz = strmBlk.GetString("owner_mask");
    if (   psz
        && (psz[0] == '-' || psz[0] == 'r')
        && (psz[1] == '-' || psz[1] == 'w')
        && (psz[2] == '-' || psz[2] == 'x'))
    {
        szAttribs[1] = psz[0];
        szAttribs[2] = psz[1];
        szAttribs[3] = psz[2];
        fHaveAttribs = true;
    }
    psz = strmBlk.GetString("group_mask");
    if (   psz
        && (psz[0] == '-' || psz[0] == 'r')
        && (psz[1] == '-' || psz[1] == 'w')
        && (psz[2] == '-' || psz[2] == 'x'))
    {
        szAttribs[4] = psz[0];
        szAttribs[5] = psz[1];
        szAttribs[6] = psz[2];
        fHaveAttribs = true;
    }
    psz = strmBlk.GetString("other_mask");
    if (   psz
        && (psz[0] == '-' || psz[0] == 'r')
        && (psz[1] == '-' || psz[1] == 'w')
        && (psz[2] == '-' || psz[2] == 'x'))
    {
        szAttribs[7] = psz[0];
        szAttribs[8] = psz[1];
        szAttribs[9] = psz[2];
        fHaveAttribs = true;
    }
    szAttribs[10] = ' '; /* Reserve three chars for sticky bits. */
    szAttribs[11] = ' ';
    szAttribs[12] = ' ';
    szAttribs[13] = ' '; /* Separator. */
    psz = strmBlk.GetString("dos_mask");
    if (   psz
        && (psz[ 0] == '-' || psz[ 0] == 'R')
        && (psz[ 1] == '-' || psz[ 1] == 'H')
        && (psz[ 2] == '-' || psz[ 2] == 'S')
        && (psz[ 3] == '-' || psz[ 3] == 'D')
        && (psz[ 4] == '-' || psz[ 4] == 'A')
        && (psz[ 5] == '-' || psz[ 5] == 'd')
        && (psz[ 6] == '-' || psz[ 6] == 'N')
        && (psz[ 7] == '-' || psz[ 7] == 'T')
        && (psz[ 8] == '-' || psz[ 8] == 'P')
        && (psz[ 9] == '-' || psz[ 9] == 'J')
        && (psz[10] == '-' || psz[10] == 'C')
        && (psz[11] == '-' || psz[11] == 'O')
        && (psz[12] == '-' || psz[12] == 'I')
        && (psz[13] == '-' || psz[13] == 'E'))
    {
        memcpy(&szAttribs[14], psz, 14);
        fHaveAttribs = true;
    }
    szAttribs[28] = '\0';
    if (fHaveAttribs)
        mFileAttrs = szAttribs;

    /* Object size. */
    int vrc = strmBlk.GetInt64Ex("st_size", &mObjectSize);
    ASSERT_GUEST_RC_RETURN(vrc, vrc);
    strmBlk.GetInt64Ex("alloc", &mAllocatedSize);

    /* INode number and device. */
    psz = strmBlk.GetString("node_id");
    if (!psz)
        psz = strmBlk.GetString("cnode_id"); /* copy & past error fixed in 6.0 RC1 */
    if (psz)
        mNodeID = RTStrToInt64(psz);
    mNodeIDDevice = strmBlk.GetUInt32("inode_dev"); /* (Produced by GAs prior to 6.0 RC1.) */

    if (fLong)
    {
        /* Dates. */
        mAccessTime       = GuestFsObjData::UnixEpochNsFromKey(strmBlk, "st_atime");
        mBirthTime        = GuestFsObjData::UnixEpochNsFromKey(strmBlk, "st_birthtime");
        mChangeTime       = GuestFsObjData::UnixEpochNsFromKey(strmBlk, "st_ctime");
        mModificationTime = GuestFsObjData::UnixEpochNsFromKey(strmBlk, "st_mtime");

        /* Owner & group. */
        mUID = strmBlk.GetInt32("uid");
        psz = strmBlk.GetString("username");
        if (psz)
            mUserName = psz;
        mGID = strmBlk.GetInt32("gid");
        psz = strmBlk.GetString("groupname");
        if (psz)
            mGroupName = psz;

        /* Misc attributes: */
        mNumHardLinks = strmBlk.GetUInt32("hlinks", 1);
        mDeviceNumber = strmBlk.GetUInt32("st_rdev");
        mGenerationID = strmBlk.GetUInt32("st_gen");
        mUserFlags    = strmBlk.GetUInt32("st_flags");

        /** @todo ACL */
    }

    LogFlowFuncLeave();
    return VINF_SUCCESS;
}

/**
 * Parses stream block output data which came from the 'rm' (vbox_rm)
 * VBoxService toolbox command. The result will be stored in this object.
 *
 * @returns VBox status code.
 * @param   strmBlk             Stream block output data to parse.
 */
int GuestFsObjData::FromRm(const GuestProcessStreamBlock &strmBlk)
{
#ifdef DEBUG
    strmBlk.DumpToLog();
#endif
    /* Object name. */
    mName = strmBlk.GetString("fname"); /* Note: RTPathRmCmd() only sets this on failure. */

    /* Return the stream block's vrc. */
    return strmBlk.GetVrc(true /* fSucceedIfNotFound */);
}

/**
 * Parses stream block output data which came from the 'stat' (vbox_stat)
 * VBoxService toolbox command. The result will be stored in this object.
 *
 * @returns VBox status code.
 * @param   strmBlk             Stream block output data to parse.
 */
int GuestFsObjData::FromStat(const GuestProcessStreamBlock &strmBlk)
{
    /* Should be identical output. */
    return GuestFsObjData::FromLs(strmBlk, true /*fLong*/);
}

/**
 * Parses stream block output data which came from the 'mktemp' (vbox_mktemp)
 * VBoxService toolbox command. The result will be stored in this object.
 *
 * @returns VBox status code.
 * @param   strmBlk             Stream block output data to parse.
 */
int GuestFsObjData::FromMkTemp(const GuestProcessStreamBlock &strmBlk)
{
    LogFlowFunc(("\n"));

#ifdef DEBUG
    strmBlk.DumpToLog();
#endif
    /* Object name. */
    mName = strmBlk.GetString("name");
    ASSERT_GUEST_RETURN(mName.isNotEmpty(), VERR_NOT_FOUND);

    /* Assign the stream block's vrc. */
    int const vrc = strmBlk.GetVrc();
    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Returns the IPRT-compatible file mode.
 * Note: Only handling RTFS_TYPE_ flags are implemented for now.
 *
 * @return IPRT file mode.
 */
RTFMODE GuestFsObjData::GetFileMode(void) const
{
    RTFMODE fMode = 0;

    switch (mType)
    {
        case FsObjType_Directory:
            fMode |= RTFS_TYPE_DIRECTORY;
            break;

        case FsObjType_File:
            fMode |= RTFS_TYPE_FILE;
            break;

        case FsObjType_Symlink:
            fMode |= RTFS_TYPE_SYMLINK;
            break;

        default:
            break;
    }

    /** @todo Implement more stuff. */

    return fMode;
}

///////////////////////////////////////////////////////////////////////////////

/** @todo *NOT* thread safe yet! */
/** @todo Add exception handling for STL stuff! */

GuestProcessStreamBlock::GuestProcessStreamBlock(void)
    : m_fComplete(false) { }

GuestProcessStreamBlock::~GuestProcessStreamBlock()
{
    Clear();
}

/**
 * Clears (destroys) the currently stored stream pairs.
 */
void GuestProcessStreamBlock::Clear(void)
{
    m_fComplete = false;
    m_mapPairs.clear();
}

#ifdef DEBUG
/**
 * Dumps the currently stored stream pairs to the (debug) log.
 */
void GuestProcessStreamBlock::DumpToLog(void) const
{
    LogFlowFunc(("Dumping contents of stream block=0x%p (%ld items, fComplete=%RTbool):\n",
                 this, m_mapPairs.size(), m_fComplete));

    for (GuestCtrlStreamPairMapIterConst it = m_mapPairs.begin();
         it != m_mapPairs.end(); ++it)
    {
        LogFlowFunc(("\t%s=%s\n", it->first.c_str(), it->second.mValue.c_str()));
    }
}
#endif

/**
 * Returns a 64-bit signed integer of a specified key.
 *
 * @return VBox status code. VERR_NOT_FOUND if key was not found.
 * @param  pszKey               Name of key to get the value for.
 * @param  piVal                Pointer to value to return.
 */
int GuestProcessStreamBlock::GetInt64Ex(const char *pszKey, int64_t *piVal) const
{
    AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
    AssertPtrReturn(piVal, VERR_INVALID_POINTER);
    const char *pszValue = GetString(pszKey);
    if (pszValue)
    {
        *piVal = RTStrToInt64(pszValue);
        return VINF_SUCCESS;
    }
    return VERR_NOT_FOUND;
}

/**
 * Returns a 64-bit integer of a specified key.
 *
 * @return  int64_t             Value to return, 0 if not found / on failure.
 * @param   pszKey              Name of key to get the value for.
 */
int64_t GuestProcessStreamBlock::GetInt64(const char *pszKey) const
{
    int64_t iVal;
    if (RT_SUCCESS(GetInt64Ex(pszKey, &iVal)))
        return iVal;
    return 0;
}

/**
 * Returns the current number of stream pairs.
 *
 * @return  uint32_t            Current number of stream pairs.
 */
size_t GuestProcessStreamBlock::GetCount(void) const
{
    return m_mapPairs.size();
}

/**
 * Gets the return code (name = "rc") of this stream block.
 *
 * @return  VBox status code.
 * @retval  VERR_NOT_FOUND if the return code string ("rc") was not found.
 * @param   fSucceedIfNotFound  When set to @c true, this reports back VINF_SUCCESS when the key ("rc") is not found.
 *                              This can happen with some (older) IPRT-provided tools such as RTPathRmCmd(), which only outputs
 *                              rc on failure but not on success. Defaults to @c false.
 */
int GuestProcessStreamBlock::GetVrc(bool fSucceedIfNotFound /* = false */) const
{
    const char *pszValue = GetString("rc");
    if (pszValue)
        return RTStrToInt16(pszValue);
    if (fSucceedIfNotFound)
        return VINF_SUCCESS;
    /** @todo We probably should have a dedicated error for that, VERR_GSTCTL_GUEST_TOOLBOX_whatever. */
    return VERR_NOT_FOUND;
}

/**
 * Returns a string value of a specified key.
 *
 * @return  uint32_t            Pointer to string to return, NULL if not found / on failure.
 * @param   pszKey              Name of key to get the value for.
 */
const char *GuestProcessStreamBlock::GetString(const char *pszKey) const
{
    AssertPtrReturn(pszKey, NULL);

    try
    {
        GuestCtrlStreamPairMapIterConst itPairs = m_mapPairs.find(pszKey);
        if (itPairs != m_mapPairs.end())
            return itPairs->second.mValue.c_str();
    }
    catch (const std::exception &ex)
    {
        RT_NOREF(ex);
    }
    return NULL;
}

/**
 * Returns a 32-bit unsigned integer of a specified key.
 *
 * @return  VBox status code. VERR_NOT_FOUND if key was not found.
 * @param   pszKey              Name of key to get the value for.
 * @param   puVal               Pointer to value to return.
 */
int GuestProcessStreamBlock::GetUInt32Ex(const char *pszKey, uint32_t *puVal) const
{
    const char *pszValue = GetString(pszKey);
    if (pszValue)
    {
        *puVal = RTStrToUInt32(pszValue);
        return VINF_SUCCESS;
    }
    return VERR_NOT_FOUND;
}

/**
 * Returns a 32-bit signed integer of a specified key.
 *
 * @returns 32-bit signed value
 * @param   pszKey              Name of key to get the value for.
 * @param   iDefault            The default to return on error if not found.
 */
int32_t GuestProcessStreamBlock::GetInt32(const char *pszKey, int32_t iDefault) const
{
    const char *pszValue = GetString(pszKey);
    if (pszValue)
    {
        int32_t iRet;
        int vrc = RTStrToInt32Full(pszValue, 0, &iRet);
        if (RT_SUCCESS(vrc))
            return iRet;
        ASSERT_GUEST_MSG_FAILED(("%s=%s\n", pszKey, pszValue));
    }
    return iDefault;
}

/**
 * Returns a 32-bit unsigned integer of a specified key.
 *
 * @return  uint32_t            Value to return, 0 if not found / on failure.
 * @param   pszKey              Name of key to get the value for.
 * @param   uDefault            The default value to return.
 */
uint32_t GuestProcessStreamBlock::GetUInt32(const char *pszKey, uint32_t uDefault /*= 0*/) const
{
    uint32_t uVal;
    if (RT_SUCCESS(GetUInt32Ex(pszKey, &uVal)))
        return uVal;
    return uDefault;
}

/**
 * Sets a value to a key or deletes a key by setting a NULL value. Extended version.
 *
 * @return  VBox status code.
 * @param   pszKey              Key name to process.
 * @param   cwcKey              Maximum characters of \a pszKey to process.
 * @param   pszValue            Value to set. Set NULL for deleting the key.
 * @param   cwcValue            Maximum characters of \a pszValue to process.
 * @param   fOverwrite          Whether a key can be overwritten with a new value if it already exists. Will assert otherwise.
 */
int GuestProcessStreamBlock::SetValueEx(const char *pszKey, size_t cwcKey, const char *pszValue, size_t cwcValue,
                                        bool fOverwrite /* = false */)
{
    AssertPtrReturn(pszKey, VERR_INVALID_POINTER);
    AssertReturn(cwcKey, VERR_INVALID_PARAMETER);

    int vrc = VINF_SUCCESS;
    try
    {
        Utf8Str const strKey(pszKey, cwcKey);

        /* Take a shortcut and prevent crashes on some funny versions
         * of STL if map is empty initially. */
        if (!m_mapPairs.empty())
        {
            GuestCtrlStreamPairMapIter it = m_mapPairs.find(strKey);
            if (it != m_mapPairs.end())
            {
                if (pszValue == NULL)
                    m_mapPairs.erase(it);
                else if (!fOverwrite)
                    AssertMsgFailedReturn(("Key '%*s' already exists! Value is '%s'\n", cwcKey, pszKey, m_mapPairs[strKey].mValue.c_str()),
                                          VERR_ALREADY_EXISTS);
            }
        }

        if (pszValue)
        {
            GuestProcessStreamValue val(pszValue, cwcValue);
            Log3Func(("strKey='%s', strValue='%s'\n", strKey.c_str(), val.mValue.c_str()));
            m_mapPairs[strKey] = val;
        }
    }
    catch (const std::exception &)
    {
        /** @todo set vrc?   */
    }
    return vrc;
}

/**
 * Sets a value to a key or deletes a key by setting a NULL value.
 *
 * @return  VBox status code.
 * @param   pszKey              Key name to process.
 * @param   pszValue            Value to set. Set NULL for deleting the key.
 */
int GuestProcessStreamBlock::SetValue(const char *pszKey, const char *pszValue)
{
    return SetValueEx(pszKey, RTSTR_MAX, pszValue, RTSTR_MAX);
}

///////////////////////////////////////////////////////////////////////////////

GuestProcessStream::GuestProcessStream(void)
    : m_cbMax(_32M)
    , m_cbAllocated(0)
    , m_cbUsed(0)
    , m_offBuf(0)
    , m_pbBuffer(NULL)
    , m_cBlocks(0) { }

GuestProcessStream::~GuestProcessStream(void)
{
    Destroy();
}

/**
 * Adds data to the internal parser buffer. Useful if there
 * are multiple rounds of adding data needed.
 *
 * @return  VBox status code. Will return VERR_TOO_MUCH_DATA if the buffer's maximum (limit) has been reached.
 * @param   pbData              Pointer to data to add.
 * @param   cbData              Size (in bytes) of data to add.
 */
int GuestProcessStream::AddData(const BYTE *pbData, size_t cbData)
{
    AssertPtrReturn(pbData, VERR_INVALID_POINTER);
    AssertReturn(cbData, VERR_INVALID_PARAMETER);

    int vrc = VINF_SUCCESS;

    /* Rewind the buffer if it's empty. */
    size_t     cbInBuf   = m_cbUsed - m_offBuf;
    bool const fAddToSet = cbInBuf == 0;
    if (fAddToSet)
        m_cbUsed = m_offBuf = 0;

    /* Try and see if we can simply append the data. */
    if (cbData + m_cbUsed <= m_cbAllocated)
    {
        memcpy(&m_pbBuffer[m_cbUsed], pbData, cbData);
        m_cbUsed += cbData;
    }
    else
    {
        /* Move any buffered data to the front. */
        cbInBuf = m_cbUsed - m_offBuf;
        if (cbInBuf == 0)
            m_cbUsed = m_offBuf = 0;
        else if (m_offBuf) /* Do we have something to move? */
        {
            memmove(m_pbBuffer, &m_pbBuffer[m_offBuf], cbInBuf);
            m_cbUsed = cbInBuf;
            m_offBuf = 0;
        }

        /* Do we need to grow the buffer? */
        if (cbData + m_cbUsed > m_cbAllocated)
        {
            size_t cbAlloc = m_cbUsed + cbData;
            if (cbAlloc <= m_cbMax)
            {
                cbAlloc = RT_ALIGN_Z(cbAlloc, _64K);
                void *pvNew = RTMemRealloc(m_pbBuffer, cbAlloc);
                if (pvNew)
                {
                    m_pbBuffer = (uint8_t *)pvNew;
                    m_cbAllocated = cbAlloc;
                }
                else
                    vrc = VERR_NO_MEMORY;
            }
            else
                vrc = VERR_TOO_MUCH_DATA;
        }

        /* Finally, copy the data. */
        if (RT_SUCCESS(vrc))
        {
            if (cbData + m_cbUsed <= m_cbAllocated)
            {
                memcpy(&m_pbBuffer[m_cbUsed], pbData, cbData);
                m_cbUsed += cbData;
            }
            else
                vrc = VERR_BUFFER_OVERFLOW;
        }
    }

    return vrc;
}

/**
 * Destroys the internal data buffer.
 */
void GuestProcessStream::Destroy(void)
{
    if (m_pbBuffer)
    {
        RTMemFree(m_pbBuffer);
        m_pbBuffer = NULL;
    }

    m_cbAllocated = 0;
    m_cbUsed = 0;
    m_offBuf = 0;
    m_cBlocks = 0;
}

#ifdef DEBUG
/**
 * Dumps the raw guest process output to a file on the host.
 * If the file on the host already exists, it will be overwritten.
 *
 * @param   pszFile             Absolute path to host file to dump the output to.
 */
void GuestProcessStream::Dump(const char *pszFile)
{
    LogFlowFunc(("Dumping contents of stream=0x%p (cbAlloc=%u, cbSize=%u, cbOff=%u) to %s\n",
                 m_pbBuffer, m_cbAllocated, m_cbUsed, m_offBuf, pszFile));

    RTFILE hFile;
    int vrc = RTFileOpen(&hFile, pszFile, RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
    if (RT_SUCCESS(vrc))
    {
        vrc = RTFileWrite(hFile, m_pbBuffer, m_cbUsed, NULL /* pcbWritten */);
        RTFileClose(hFile);
    }
}
#endif /* DEBUG */

/**
 * Tries to parse the next upcoming pair block within the internal buffer.
 *
 * Parsing behavior:
 * - A stream can contain one or multiple blocks and is terminated by four (4) "\0".
 * - A block (or "object") contains one or multiple key=value pairs and is terminated with two (2) "\0".
 * - Each key=value pair is terminated by a single (1) "\0".
 *
 * As new data can arrive at a later time eventually completing a pair / block / stream,
 * the algorithm needs to be careful not intepreting its current data too early. So only skip termination
 * sequences if we really know that the termination sequence is complete. See comments down below.
 *
 * No locking done.
 *
 * @return VBox status code.
 * @retval VINF_EOF if the stream reached its end.
 * @param  streamBlock              Reference to guest stream block to fill
 */
int GuestProcessStream::ParseBlock(GuestProcessStreamBlock &streamBlock)
{
    AssertMsgReturn(streamBlock.m_fComplete == false, ("Block object already marked as being completed\n"), VERR_WRONG_ORDER);

    if (   !m_pbBuffer
        || !m_cbUsed)
        return VINF_EOF;

    AssertReturn(m_offBuf <= m_cbUsed, VERR_INVALID_PARAMETER);
    if (m_offBuf == m_cbUsed)
        return VINF_EOF;

    char * const  pszStart = (char *)&m_pbBuffer[m_offBuf];

    size_t        cbLeftParsed    = m_offBuf < m_cbUsed ? m_cbUsed - m_offBuf : 0;
    size_t        cbLeftLookAhead = cbLeftParsed;

    char         *pszLookAhead = pszStart; /* Look ahead pointer to count terminators. */
    char         *pszParsed    = pszStart; /* Points to data considered as being parsed already. */

    Log4Func(("Current @ %zu/%zu:\n%.*Rhxd\n", m_offBuf, m_cbUsed, RT_MIN(cbLeftParsed, _1K), pszStart));

    size_t cTerm = 0;

    /*
     * We have to be careful when handling single terminators ('\0') here, as we might not know yet
     * if it's part of a multi-terminator seqeuence.
     *
     * So handle and skip those *only* when we hit a non-terminator char again.
     */
    int vrc = VINF_SUCCESS;
    while (cbLeftLookAhead)
    {
        /* Count consequtive terminators. */
        if (*pszLookAhead == GUESTTOOLBOX_STRM_TERM)
        {
            cTerm++;
            pszLookAhead++;
            cbLeftLookAhead--;
            continue;
        }

        pszParsed    = pszLookAhead;
        cbLeftParsed = cbLeftLookAhead;

        /* We hit a non-terminator (again); now interpret where we are, and
         * bail out if we need to. */
        if (cTerm >= 2)
        {
            Log2Func(("Hit end of termination sequence (%zu)\n", cTerm));
            break;
        }

        cTerm = 0; /* Reset consequtive counter. */

        char * const pszPairEnd = RTStrEnd(pszParsed, cbLeftParsed);
        if (!pszPairEnd) /* No zero terminator found (yet), try next time. */
            break;

        Log3Func(("Pair '%s' (%u)\n", pszParsed, strlen(pszParsed)));

        Assert(pszPairEnd != pszParsed);
        size_t const cbPair = (size_t)(pszPairEnd - pszParsed);
        Assert(cbPair);
        const char  *pszSep = (const char *)memchr(pszParsed, '=', cbPair);
        if (!pszSep) /* No separator found (yet), try next time. */
            break;

        /* Skip the separator so that pszSep points to the actual value. */
        pszSep++;

        char const * const pszKey = pszParsed;
        char const * const pszVal = pszSep;

        vrc = streamBlock.SetValueEx(pszKey, pszSep - pszKey - 1, pszVal, pszPairEnd - pszVal);
        if (RT_FAILURE(vrc))
            return vrc;

        if (cbPair >= cbLeftParsed)
            break;

        /* Accounting for next iteration. */
        pszParsed       = pszPairEnd;
        Assert(cbLeftParsed >= cbPair);
        cbLeftParsed   -= cbPair;

        pszLookAhead    = pszPairEnd;
        cbLeftLookAhead = cbLeftParsed;

        if (cbLeftParsed)
            Log4Func(("Next iteration @ %zu:\n%.*Rhxd\n", pszParsed - pszStart, cbLeftParsed, pszParsed));
    }

    if (cbLeftParsed)
        Log4Func(("Done @ %zu:\n%.*Rhxd\n", pszParsed - pszStart, cbLeftParsed, pszParsed));

    m_offBuf += pszParsed - pszStart; /* Only account really parsed content. */
    Assert(m_offBuf <= m_cbUsed);

    /* Did we hit a block or stream termination sequence? */
    if (cTerm >= GUESTTOOLBOX_STRM_BLK_TERM_CNT)
    {
        if (!streamBlock.IsEmpty()) /* Only account and complete blocks which have values in it. */
        {
            m_cBlocks++;
            streamBlock.m_fComplete = true;
#ifdef DEBUG
            streamBlock.DumpToLog();
#endif
        }

        if (cTerm >= GUESTTOOLBOX_STRM_TERM_CNT)
        {
            m_offBuf = m_cbUsed;
            vrc = VINF_EOF;
        }
    }

    LogFlowThisFunc(("cbLeft=%zu, offBuffer=%zu / cbUsed=%zu, cBlocks=%zu, cTerm=%zu -> current block has %RU64 pairs (complete = %RTbool), rc=%Rrc\n",
                     cbLeftParsed, m_offBuf, m_cbUsed, m_cBlocks, cTerm, streamBlock.GetCount(), streamBlock.IsComplete(), vrc));

    return vrc;
}

GuestBase::GuestBase(void)
    : mConsole(NULL)
    , mNextContextID(RTRandU32() % VBOX_GUESTCTRL_MAX_CONTEXTS)
{
}

GuestBase::~GuestBase(void)
{
}

/**
 * Separate initialization function for the base class.
 *
 * @returns VBox status code.
 */
int GuestBase::baseInit(void)
{
    int const vrc = RTCritSectInit(&mWaitEventCritSect);
    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Separate uninitialization function for the base class.
 */
void GuestBase::baseUninit(void)
{
    LogFlowThisFuncEnter();

    /* Make sure to cancel any outstanding wait events. */
    int vrc2 = cancelWaitEvents();
    AssertRC(vrc2);

    vrc2 = RTCritSectDelete(&mWaitEventCritSect);
    AssertRC(vrc2);

    LogFlowFuncLeaveRC(vrc2);
    /* No return value. */
}

/**
 * Cancels all outstanding wait events.
 *
 * @returns VBox status code.
 */
int GuestBase::cancelWaitEvents(void)
{
    LogFlowThisFuncEnter();

    int vrc = RTCritSectEnter(&mWaitEventCritSect);
    if (RT_SUCCESS(vrc))
    {
        GuestEventGroup::iterator itEventGroups = mWaitEventGroups.begin();
        while (itEventGroups != mWaitEventGroups.end())
        {
            GuestWaitEvents::iterator itEvents = itEventGroups->second.begin();
            while (itEvents != itEventGroups->second.end())
            {
                GuestWaitEvent *pEvent = itEvents->second;
                AssertPtr(pEvent);

                /*
                 * Just cancel the event, but don't remove it from the
                 * wait events map. Don't delete it though, this (hopefully)
                 * is done by the caller using unregisterWaitEvent().
                 */
                int vrc2 = pEvent->Cancel();
                AssertRC(vrc2);

                ++itEvents;
            }

            ++itEventGroups;
        }

        int vrc2 = RTCritSectLeave(&mWaitEventCritSect);
        if (RT_SUCCESS(vrc))
            vrc = vrc2;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Handles generic messages not bound to a specific object type.
 *
 * @return VBox status code. VERR_NOT_FOUND if no handler has been found or VERR_NOT_SUPPORTED
 *         if this class does not support the specified callback.
 * @param  pCtxCb               Host callback context.
 * @param  pSvcCb               Service callback data.
 */
int GuestBase::dispatchGeneric(PVBOXGUESTCTRLHOSTCBCTX pCtxCb, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb)
{
    LogFlowFunc(("pCtxCb=%p, pSvcCb=%p\n", pCtxCb, pSvcCb));

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

    int vrc;

    try
    {
        Log2Func(("uFunc=%RU32, cParms=%RU32\n", pCtxCb->uMessage, pSvcCb->mParms));

        switch (pCtxCb->uMessage)
        {
            case GUEST_MSG_PROGRESS_UPDATE:
                vrc = VINF_SUCCESS;
                break;

            case GUEST_MSG_REPLY:
            {
                if (pSvcCb->mParms >= 4)
                {
                    int idx = 1; /* Current parameter index. */
                    CALLBACKDATA_MSG_REPLY dataCb;
                    /* pSvcCb->mpaParms[0] always contains the context ID. */
                    vrc = HGCMSvcGetU32(&pSvcCb->mpaParms[idx++], &dataCb.uType);
                    AssertRCReturn(vrc, vrc);
                    vrc = HGCMSvcGetU32(&pSvcCb->mpaParms[idx++], &dataCb.rc);
                    AssertRCReturn(vrc, vrc);
                    vrc = HGCMSvcGetPv(&pSvcCb->mpaParms[idx++], &dataCb.pvPayload, &dataCb.cbPayload);
                    AssertRCReturn(vrc, vrc);

                    try
                    {
                        GuestWaitEventPayload evPayload(dataCb.uType, dataCb.pvPayload, dataCb.cbPayload);
                        vrc = signalWaitEventInternal(pCtxCb, dataCb.rc, &evPayload);
                    }
                    catch (int vrcEx) /* Thrown by GuestWaitEventPayload constructor. */
                    {
                        vrc = vrcEx;
                    }
                }
                else
                    vrc = VERR_INVALID_PARAMETER;
                break;
            }

            default:
                vrc = VERR_NOT_SUPPORTED;
                break;
        }
    }
    catch (std::bad_alloc &)
    {
        vrc = VERR_NO_MEMORY;
    }
    catch (int vrcCatch)
    {
        vrc = vrcCatch;
    }

    LogFlowFuncLeaveRC(vrc);
    return vrc;
}

/**
 * Generates a context ID (CID) by incrementing the object's count.
 * A CID consists of a session ID, an object ID and a count.
 *
 * Note: This function does not guarantee that the returned CID is unique;
 *       the caller has to take care of that and eventually retry.
 *
 * @returns VBox status code.
 * @param   uSessionID          Session ID to use for CID generation.
 * @param   uObjectID           Object ID to use for CID generation.
 * @param   puContextID         Where to store the generated CID on success.
 */
int GuestBase::generateContextID(uint32_t uSessionID, uint32_t uObjectID, uint32_t *puContextID)
{
    AssertPtrReturn(puContextID, VERR_INVALID_POINTER);

    if (   uSessionID >= VBOX_GUESTCTRL_MAX_SESSIONS
        || uObjectID  >= VBOX_GUESTCTRL_MAX_OBJECTS)
        return VERR_INVALID_PARAMETER;

    uint32_t uCount = ASMAtomicIncU32(&mNextContextID);
    uCount %= VBOX_GUESTCTRL_MAX_CONTEXTS;

    uint32_t uNewContextID = VBOX_GUESTCTRL_CONTEXTID_MAKE(uSessionID, uObjectID, uCount);

    *puContextID = uNewContextID;

#if 0
    LogFlowThisFunc(("mNextContextID=%RU32, uSessionID=%RU32, uObjectID=%RU32, uCount=%RU32, uNewContextID=%RU32\n",
                     mNextContextID, uSessionID, uObjectID, uCount, uNewContextID));
#endif
    return VINF_SUCCESS;
}

/**
 * Registers (creates) a new wait event based on a given session and object ID.
 *
 * From those IDs an unique context ID (CID) will be built, which only can be
 * around once at a time.
 *
 * @returns VBox status code.
 * @retval  VERR_GSTCTL_MAX_CID_COUNT_REACHED if unable to generate a free context ID (CID, the count part (bits 15:0)).
 * @param   uSessionID              Session ID to register wait event for.
 * @param   uObjectID               Object ID to register wait event for.
 * @param   ppEvent                 Pointer to registered (created) wait event on success.
 *                                  Must be destroyed with unregisterWaitEvent().
 */
int GuestBase::registerWaitEvent(uint32_t uSessionID, uint32_t uObjectID, GuestWaitEvent **ppEvent)
{
    GuestEventTypes eventTypesEmpty;
    return registerWaitEventEx(uSessionID, uObjectID, eventTypesEmpty, ppEvent);
}

/**
 * Creates and registers a new wait event object that waits on a set of events
 * related to a given object within the session.
 *
 * From the session ID and object ID a one-time unique context ID (CID) is built
 * for this wait object.  Normally the CID is then passed to the guest along
 * with a request, and the guest passed the CID back with the reply.  The
 * handler for the reply then emits a signal on the event type associated with
 * the reply, which includes signalling the object returned by this method and
 * the waking up the thread waiting on it.
 *
 * @returns VBox status code.
 * @retval  VERR_GSTCTL_MAX_CID_COUNT_REACHED if unable to generate a free context ID (CID, the count part (bits 15:0)).
 * @param   uSessionID              Session ID to register wait event for.
 * @param   uObjectID               Object ID to register wait event for.
 * @param   lstEvents               List of events to register the wait event for.
 * @param   ppEvent                 Pointer to registered (created) wait event on success.
 *                                  Must be destroyed with unregisterWaitEvent().
 */
int GuestBase::registerWaitEventEx(uint32_t uSessionID, uint32_t uObjectID, const GuestEventTypes &lstEvents,
                                   GuestWaitEvent **ppEvent)
{
    AssertPtrReturn(ppEvent, VERR_INVALID_POINTER);

    uint32_t idContext;
    int vrc = generateContextID(uSessionID, uObjectID, &idContext);
    AssertRCReturn(vrc, vrc);

    GuestWaitEvent *pEvent = new GuestWaitEvent();
    AssertPtrReturn(pEvent, VERR_NO_MEMORY);

    vrc = pEvent->Init(idContext, lstEvents);
    AssertRCReturn(vrc, vrc);

    LogFlowThisFunc(("New event=%p, CID=%RU32\n", pEvent, idContext));

    vrc = RTCritSectEnter(&mWaitEventCritSect);
    if (RT_SUCCESS(vrc))
    {
        /*
         * Check that we don't have any context ID collisions (should be very unlikely).
         *
         * The ASSUMPTION here is that mWaitEvents has all the same events as
         * mWaitEventGroups, so it suffices to check one of the two.
         */
        if (mWaitEvents.find(idContext) != mWaitEvents.end())
        {
            uint32_t cTries = 0;
            do
            {
                vrc = generateContextID(uSessionID, uObjectID, &idContext);
                AssertRCBreak(vrc);
                LogFunc(("Found context ID duplicate; trying a different context ID: %#x\n", idContext));
                if (mWaitEvents.find(idContext) != mWaitEvents.end())
                    vrc = VERR_GSTCTL_MAX_CID_COUNT_REACHED;
            } while (RT_FAILURE_NP(vrc) && cTries++ < 10);
        }
        if (RT_SUCCESS(vrc))
        {
            /*
             * Insert event into matching event group. This is for faster per-group lookup of all events later.
             */
            uint32_t cInserts = 0;
            for (GuestEventTypes::const_iterator ItType = lstEvents.begin(); ItType != lstEvents.end(); ++ItType)
            {
                GuestWaitEvents &eventGroup = mWaitEventGroups[*ItType];
                if (eventGroup.find(idContext) == eventGroup.end())
                {
                    try
                    {
                        eventGroup.insert(std::pair<uint32_t, GuestWaitEvent *>(idContext, pEvent));
                        cInserts++;
                    }
                    catch (std::bad_alloc &)
                    {
                        while (ItType != lstEvents.begin())
                        {
                            --ItType;
                            mWaitEventGroups[*ItType].erase(idContext);
                        }
                        vrc = VERR_NO_MEMORY;
                        break;
                    }
                }
                else
                    Assert(cInserts > 0); /* else: lstEvents has duplicate entries. */
            }
            if (RT_SUCCESS(vrc))
            {
                Assert(cInserts > 0 || lstEvents.size() == 0);
                RT_NOREF(cInserts);

                /*
                 * Register event in the regular event list.
                 */
                try
                {
                    mWaitEvents[idContext] = pEvent;
                }
                catch (std::bad_alloc &)
                {
                    for (GuestEventTypes::const_iterator ItType = lstEvents.begin(); ItType != lstEvents.end(); ++ItType)
                        mWaitEventGroups[*ItType].erase(idContext);
                    vrc = VERR_NO_MEMORY;
                }
            }
        }

        RTCritSectLeave(&mWaitEventCritSect);
    }
    if (RT_SUCCESS(vrc))
    {
        *ppEvent = pEvent;
        return vrc;
    }

    if (pEvent)
        delete pEvent;

    return vrc;
}

/**
 * Signals all wait events of a specific type (if found)
 * and notifies external events accordingly.
 *
 * @returns VBox status code.
 * @param   aType               Event type to signal.
 * @param   aEvent              Which external event to notify.
 */
int GuestBase::signalWaitEvent(VBoxEventType_T aType, IEvent *aEvent)
{
    int vrc = RTCritSectEnter(&mWaitEventCritSect);
#ifdef DEBUG
    uint32_t cEvents = 0;
#endif
    if (RT_SUCCESS(vrc))
    {
        GuestEventGroup::iterator itGroup = mWaitEventGroups.find(aType);
        if (itGroup != mWaitEventGroups.end())
        {
            /* Signal all events in the group, leaving the group empty afterwards. */
            GuestWaitEvents::iterator ItWaitEvt;
            while ((ItWaitEvt = itGroup->second.begin()) != itGroup->second.end())
            {
                LogFlowThisFunc(("Signalling event=%p, type=%ld (CID %#x: Session=%RU32, Object=%RU32, Count=%RU32) ...\n",
                                 ItWaitEvt->second, aType, ItWaitEvt->first, VBOX_GUESTCTRL_CONTEXTID_GET_SESSION(ItWaitEvt->first),
                                 VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(ItWaitEvt->first), VBOX_GUESTCTRL_CONTEXTID_GET_COUNT(ItWaitEvt->first)));

                int vrc2 = ItWaitEvt->second->SignalExternal(aEvent);
                AssertRC(vrc2);

                /* Take down the wait event object details before we erase it from this list and invalid ItGrpEvt. */
                const GuestEventTypes &EvtTypes  = ItWaitEvt->second->Types();
                uint32_t               idContext = ItWaitEvt->first;
                itGroup->second.erase(ItWaitEvt);

                for (GuestEventTypes::const_iterator ItType = EvtTypes.begin(); ItType != EvtTypes.end(); ++ItType)
                {
                    GuestEventGroup::iterator EvtTypeGrp = mWaitEventGroups.find(*ItType);
                    if (EvtTypeGrp != mWaitEventGroups.end())
                    {
                        ItWaitEvt = EvtTypeGrp->second.find(idContext);
                        if (ItWaitEvt != EvtTypeGrp->second.end())
                        {
                            LogFlowThisFunc(("Removing event %p (CID %#x) from type %d group\n", ItWaitEvt->second, idContext, *ItType));
                            EvtTypeGrp->second.erase(ItWaitEvt);
                            LogFlowThisFunc(("%zu events left for type %d\n", EvtTypeGrp->second.size(), *ItType));
                            Assert(EvtTypeGrp->second.find(idContext) == EvtTypeGrp->second.end()); /* no duplicates */
                        }
                    }
                }
            }
        }

        int vrc2 = RTCritSectLeave(&mWaitEventCritSect);
        if (RT_SUCCESS(vrc))
            vrc = vrc2;
    }

#ifdef DEBUG
    LogFlowThisFunc(("Signalled %RU32 events, vrc=%Rrc\n", cEvents, vrc));
#endif
    return vrc;
}

/**
 * Signals a wait event which is registered to a specific callback (bound to a context ID (CID)).
 *
 * @returns VBox status code.
 * @param   pCbCtx      Pointer to host service callback context.
 * @param   vrcGuest    Guest return VBox status code to set.
 * @param   pPayload    Additional wait event payload data set set on return. Optional.
 */
int GuestBase::signalWaitEventInternal(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, int vrcGuest, const GuestWaitEventPayload *pPayload)
{
    if (RT_SUCCESS(vrcGuest))
        return signalWaitEventInternalEx(pCbCtx, VINF_SUCCESS, VINF_SUCCESS /* vrcGuest */, pPayload);

    return signalWaitEventInternalEx(pCbCtx, VERR_GSTCTL_GUEST_ERROR, vrcGuest, pPayload);
}

/**
 * Signals a wait event which is registered to a specific callback (bound to a context ID (CID)).
 * Extended version.
 *
 * @returns VBox status code.
 * @param   pCbCtx      Pointer to host service callback context.
 * @param   vrc         Return VBox status code to set as wait result.
 * @param   vrcGuest    Guest return VBox status code to set additionally, if
 *                      vrc is set to VERR_GSTCTL_GUEST_ERROR.
 * @param   pPayload    Additional wait event payload data set set on return. Optional.
 */
int GuestBase::signalWaitEventInternalEx(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, int vrc, int vrcGuest,
                                         const GuestWaitEventPayload *pPayload)
{
    AssertPtrReturn(pCbCtx, VERR_INVALID_POINTER);
    /* pPayload is optional. */

    int vrc2 = RTCritSectEnter(&mWaitEventCritSect);
    if (RT_SUCCESS(vrc2))
    {
        GuestWaitEvents::iterator itEvent = mWaitEvents.find(pCbCtx->uContextID);
        if (itEvent != mWaitEvents.end())
        {
            LogFlowThisFunc(("Signalling event=%p (CID %RU32, vrc=%Rrc, vrcGuest=%Rrc, pPayload=%p) ...\n",
                             itEvent->second, itEvent->first, vrc, vrcGuest, pPayload));
            GuestWaitEvent *pEvent = itEvent->second;
            AssertPtr(pEvent);
            vrc2 = pEvent->SignalInternal(vrc, vrcGuest, pPayload);
        }
        else
            vrc2 = VERR_NOT_FOUND;

        int vrc3 = RTCritSectLeave(&mWaitEventCritSect);
        if (RT_SUCCESS(vrc2))
            vrc2 = vrc3;
    }

    return vrc2;
}

/**
 * Unregisters (deletes) a wait event.
 *
 * After successful unregistration the event will not be valid anymore.
 *
 * @returns VBox status code.
 * @param   pWaitEvt        Wait event to unregister (delete).
 */
int GuestBase::unregisterWaitEvent(GuestWaitEvent *pWaitEvt)
{
    if (!pWaitEvt) /* Nothing to unregister. */
        return VINF_SUCCESS;

    int vrc = RTCritSectEnter(&mWaitEventCritSect);
    if (RT_SUCCESS(vrc))
    {
        LogFlowThisFunc(("pWaitEvt=%p\n", pWaitEvt));

/** @todo r=bird: One way of optimizing this would be to use the pointer
 * instead of the context ID as index into the groups, i.e. revert the value
 * pair for the GuestWaitEvents type.
 *
 * An even more efficent way, would be to not use sexy std::xxx containers for
 * the types, but iprt/list.h, as that would just be a RTListNodeRemove call for
 * each type w/o needing to iterate much at all.  I.e. add a struct {
 * RTLISTNODE, GuestWaitEvent *pSelf} array to GuestWaitEvent, and change
 * GuestEventGroup to std::map<VBoxEventType_T, RTListAnchorClass>
 * (RTListAnchorClass == RTLISTANCHOR wrapper with a constructor)).
 *
 * P.S. the try/catch is now longer needed after I changed pWaitEvt->Types() to
 * return a const reference rather than a copy of the type list (and it think it
 * is safe to assume iterators are not hitting the heap).  Copy vs reference is
 * an easy mistake to make in C++.
 *
 * P.P.S. The mWaitEventGroups optimization is probably just a lot of extra work
 * with little payoff.
 */
        try
        {
            /* Remove the event from all event type groups. */
            const GuestEventTypes &lstTypes = pWaitEvt->Types();
            for (GuestEventTypes::const_iterator itType = lstTypes.begin();
                 itType != lstTypes.end(); ++itType)
            {
                /** @todo Slow O(n) lookup. Optimize this. */
                GuestWaitEvents::iterator itCurEvent = mWaitEventGroups[(*itType)].begin();
                while (itCurEvent != mWaitEventGroups[(*itType)].end())
                {
                    if (itCurEvent->second == pWaitEvt)
                    {
                        mWaitEventGroups[(*itType)].erase(itCurEvent);
                        break;
                    }
                    ++itCurEvent;
                }
            }

            /* Remove the event from the general event list as well. */
            GuestWaitEvents::iterator itEvent = mWaitEvents.find(pWaitEvt->ContextID());

            Assert(itEvent != mWaitEvents.end());
            Assert(itEvent->second == pWaitEvt);

            mWaitEvents.erase(itEvent);

            delete pWaitEvt;
            pWaitEvt = NULL;
        }
        catch (const std::exception &ex)
        {
            RT_NOREF(ex);
            AssertFailedStmt(vrc = VERR_NOT_FOUND);
        }

        int vrc2 = RTCritSectLeave(&mWaitEventCritSect);
        if (RT_SUCCESS(vrc))
            vrc = vrc2;
    }

    return vrc;
}

/**
 * Waits for an already registered guest wait event.
 *
 * @return  VBox status code.
 * @retval  VERR_GSTCTL_GUEST_ERROR may be returned, call GuestResult() to get
 *          the actual result.
 *
 * @param   pWaitEvt                Pointer to event to wait for.
 * @param   msTimeout               Timeout (in ms) for waiting.
 * @param   pType                   Event type of following IEvent. Optional.
 * @param   ppEvent                 Pointer to IEvent which got triggered for this event. Optional.
 */
int GuestBase::waitForEvent(GuestWaitEvent *pWaitEvt, uint32_t msTimeout, VBoxEventType_T *pType, IEvent **ppEvent)
{
    AssertPtrReturn(pWaitEvt, VERR_INVALID_POINTER);
    /* pType is optional. */
    /* ppEvent is optional. */

    int vrc = pWaitEvt->Wait(msTimeout);
    if (RT_SUCCESS(vrc))
    {
        const ComPtr<IEvent> pThisEvent = pWaitEvt->Event();
        if (pThisEvent.isNotNull()) /* Make sure that we actually have an event associated. */
        {
            if (pType)
            {
                HRESULT hrc = pThisEvent->COMGETTER(Type)(pType);
                if (FAILED(hrc))
                    vrc = VERR_COM_UNEXPECTED;
            }
            if (   RT_SUCCESS(vrc)
                && ppEvent)
                pThisEvent.queryInterfaceTo(ppEvent);

            unconst(pThisEvent).setNull();
        }
    }

    return vrc;
}

#ifndef VBOX_GUESTCTRL_TEST_CASE
/**
 * Convenience function to return a pre-formatted string using an action description and a guest error information.
 *
 * @returns Pre-formatted string with a user-friendly error string.
 * @param   strAction           Action of when the error occurred.
 * @param   guestErrorInfo      Related guest error information to use.
 */
/* static */ Utf8Str GuestBase::getErrorAsString(const Utf8Str& strAction, const GuestErrorInfo& guestErrorInfo)
{
    Assert(strAction.isNotEmpty());
    return Utf8StrFmt("%s: %s", strAction.c_str(), getErrorAsString(guestErrorInfo).c_str());
}

/**
 * Returns a user-friendly error message from a given GuestErrorInfo object.
 *
 * @returns Error message string.
 * @param   guestErrorInfo      Guest error info to return error message for.
 */
/* static */ Utf8Str GuestBase::getErrorAsString(const GuestErrorInfo& guestErrorInfo)
{
    AssertMsg(RT_FAILURE(guestErrorInfo.getVrc()), ("Guest vrc does not indicate a failure\n"));

    Utf8Str strErr;

#define CASE_TOOL_ERROR(a_eType, a_strTool) \
    case a_eType: \
    { \
        strErr = GuestProcessTool::guestErrorToString(a_strTool, guestErrorInfo); \
        break; \
    }

    switch (guestErrorInfo.getType())
    {
        case GuestErrorInfo::Type_Session:
            strErr = GuestSession::i_guestErrorToString(guestErrorInfo.getVrc());
            break;

        case GuestErrorInfo::Type_Process:
            strErr = GuestProcess::i_guestErrorToString(guestErrorInfo.getVrc(), guestErrorInfo.getWhat().c_str());
            break;

        case GuestErrorInfo::Type_File:
            strErr = GuestFile::i_guestErrorToString(guestErrorInfo.getVrc(), guestErrorInfo.getWhat().c_str());
            break;

        case GuestErrorInfo::Type_Directory:
            strErr = GuestDirectory::i_guestErrorToString(guestErrorInfo.getVrc(), guestErrorInfo.getWhat().c_str());
            break;

        CASE_TOOL_ERROR(GuestErrorInfo::Type_ToolCat,    VBOXSERVICE_TOOL_CAT);
        CASE_TOOL_ERROR(GuestErrorInfo::Type_ToolLs,     VBOXSERVICE_TOOL_LS);
        CASE_TOOL_ERROR(GuestErrorInfo::Type_ToolMkDir,  VBOXSERVICE_TOOL_MKDIR);
        CASE_TOOL_ERROR(GuestErrorInfo::Type_ToolMkTemp, VBOXSERVICE_TOOL_MKTEMP);
        CASE_TOOL_ERROR(GuestErrorInfo::Type_ToolRm,     VBOXSERVICE_TOOL_RM);
        CASE_TOOL_ERROR(GuestErrorInfo::Type_ToolStat,   VBOXSERVICE_TOOL_STAT);

        default:
            AssertMsgFailed(("Type not implemented (type=%RU32, vrc=%Rrc)\n", guestErrorInfo.getType(), guestErrorInfo.getVrc()));
            strErr = Utf8StrFmt("Unknown / Not implemented -- Please file a bug report (type=%RU32, vrc=%Rrc)\n",
                                guestErrorInfo.getType(), guestErrorInfo.getVrc());
            break;
    }

    return strErr;
}

#endif /* VBOX_GUESTCTRL_TEST_CASE */

/**
 * Converts RTFMODE to FsObjType_T.
 *
 * @return  Converted FsObjType_T type.
 * @param   fMode               RTFMODE to convert.
 */
/* static */
FsObjType_T GuestBase::fileModeToFsObjType(RTFMODE fMode)
{
    if (RTFS_IS_FILE(fMode))           return FsObjType_File;
    else if (RTFS_IS_DIRECTORY(fMode)) return FsObjType_Directory;
    else if (RTFS_IS_SYMLINK(fMode))   return FsObjType_Symlink;

    return FsObjType_Unknown;
}

/**
 * Converts a FsObjType_T to a human-readable string.
 *
 * @returns Human-readable string of FsObjType_T.
 * @param   enmType             FsObjType_T to convert.
 */
/* static */
const char *GuestBase::fsObjTypeToStr(FsObjType_T enmType)
{
    switch (enmType)
    {
        case FsObjType_Directory: return "directory";
        case FsObjType_Symlink:   return "symbolic link";
        case FsObjType_File:      return "file";
        default:                  break;
    }

    return "unknown";
}

/**
 * Converts a PathStyle_T to a human-readable string.
 *
 * @returns Human-readable string of PathStyle_T.
 * @param   enmPathStyle        PathStyle_T to convert.
 */
/* static */
const char *GuestBase::pathStyleToStr(PathStyle_T enmPathStyle)
{
    switch (enmPathStyle)
    {
        case PathStyle_DOS:     return "DOS";
        case PathStyle_UNIX:    return "UNIX";
        case PathStyle_Unknown: return "Unknown";
        default:                break;
    }

    return "<invalid>";
}

GuestObject::GuestObject(void)
    : mSession(NULL),
      mObjectID(0)
{
}

GuestObject::~GuestObject(void)
{
}

/**
 * Binds this guest (control) object to a specific guest (control) session.
 *
 * @returns VBox status code.
 * @param   pConsole            Pointer to console object to use.
 * @param   pSession            Pointer to session to bind this object to.
 * @param   uObjectID           Object ID for this object to use within that specific session.
 *                              Each object ID must be unique per session.
 */
int GuestObject::bindToSession(Console *pConsole, GuestSession *pSession, uint32_t uObjectID)
{
    AssertPtrReturn(pConsole, VERR_INVALID_POINTER);
    AssertPtrReturn(pSession, VERR_INVALID_POINTER);

    mConsole  = pConsole;
    mSession  = pSession;
    mObjectID = uObjectID;

    return VINF_SUCCESS;
}

/**
 * Registers (creates) a new wait event.
 *
 * @returns VBox status code.
 * @param   lstEvents           List of events which the new wait event gets triggered at.
 * @param   ppEvent             Returns the new wait event on success.
 */
int GuestObject::registerWaitEvent(const GuestEventTypes &lstEvents,
                                   GuestWaitEvent **ppEvent)
{
    AssertPtr(mSession);
    return GuestBase::registerWaitEventEx(mSession->i_getId(), mObjectID, lstEvents, ppEvent);
}

/**
 * Sends a HGCM message to the guest (via the guest control host service).
 *
 * @returns VBox status code.
 * @param   uMessage            Message ID of message to send.
 * @param   cParms              Number of HGCM message parameters to send.
 * @param   paParms             Array of HGCM message parameters to send.
 */
int GuestObject::sendMessage(uint32_t uMessage, uint32_t cParms, PVBOXHGCMSVCPARM paParms)
{
#ifndef VBOX_GUESTCTRL_TEST_CASE
    ComObjPtr<Console> pConsole = mConsole;
    Assert(!pConsole.isNull());

    int vrc = VERR_HGCM_SERVICE_NOT_FOUND;

    /* Forward the information to the VMM device. */
    VMMDev *pVMMDev = pConsole->i_getVMMDev();
    if (pVMMDev)
    {
        /* HACK ALERT! We extend the first parameter to 64-bit and use the
                       two topmost bits for call destination information. */
        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 | VBOX_GUESTCTRL_DST_SESSION;

        /* Make the call. */
        LogFlowThisFunc(("uMessage=%RU32, cParms=%RU32\n", uMessage, cParms));
        vrc = pVMMDev->hgcmHostCall(HGCMSERVICE_NAME, uMessage, cParms, paParms);
        if (RT_FAILURE(vrc))
        {
            /** @todo What to do here? */
        }
    }
#else
    LogFlowThisFuncEnter();

    /* Not needed within testcases. */
    RT_NOREF(uMessage, cParms, paParms);
    int vrc = VINF_SUCCESS;
#endif
    return vrc;
}

GuestWaitEventBase::GuestWaitEventBase(void)
    : mfAborted(false),
      mCID(0),
      mEventSem(NIL_RTSEMEVENT),
      mVrc(VINF_SUCCESS),
      mGuestRc(VINF_SUCCESS)
{
}

GuestWaitEventBase::~GuestWaitEventBase(void)
{
    if (mEventSem != NIL_RTSEMEVENT)
    {
        RTSemEventDestroy(mEventSem);
        mEventSem = NIL_RTSEMEVENT;
    }
}

/**
 * Initializes a wait event with a specific context ID (CID).
 *
 * @returns VBox status code.
 * @param   uCID                Context ID (CID) to initialize wait event with.
 */
int GuestWaitEventBase::Init(uint32_t uCID)
{
    mCID = uCID;

    return RTSemEventCreate(&mEventSem);
}

/**
 * Signals a wait event.
 *
 * @returns VBox status code.
 * @param   vrc         Return VBox status code to set as wait result.
 * @param   vrcGuest    Guest return VBox status code to set additionally, if
 *                      @a vrc is set to VERR_GSTCTL_GUEST_ERROR.
 * @param   pPayload    Additional wait event payload data set set on return. Optional.
 */
int GuestWaitEventBase::SignalInternal(int vrc, int vrcGuest, const GuestWaitEventPayload *pPayload)
{
    if (mfAborted)
        return VERR_CANCELLED;

#ifdef VBOX_STRICT
    if (vrc == VERR_GSTCTL_GUEST_ERROR)
        AssertMsg(RT_FAILURE(vrcGuest), ("Guest error indicated but no actual guest error set (%Rrc)\n", vrcGuest));
    else
        AssertMsg(RT_SUCCESS(vrcGuest), ("No guest error indicated but actual guest error set (%Rrc)\n", vrcGuest));
#endif

    int vrc2;
    if (pPayload)
        vrc2 = mPayload.CopyFromDeep(*pPayload);
    else
        vrc2 = VINF_SUCCESS;
    if (RT_SUCCESS(vrc2))
    {
        mVrc = vrc;
        mGuestRc = vrcGuest;

        vrc2 = RTSemEventSignal(mEventSem);
    }

    return vrc2;
}

/**
 * Waits for the event to get triggered. Will return success if the
 * wait was successufl (e.g. was being triggered), otherwise an error will be returned.
 *
 * @returns VBox status code.
 * @retval  VERR_GSTCTL_GUEST_ERROR may be returned, call GuestResult() to get
 *          the actual result.
 *
 * @param   msTimeout           Timeout (in ms) to wait.
 *                              Specifiy 0 to wait indefinitely.
 */
int GuestWaitEventBase::Wait(RTMSINTERVAL msTimeout)
{
    int vrc;
    if (!mfAborted)
    {
        AssertReturn(mEventSem != NIL_RTSEMEVENT, VERR_CANCELLED);

        vrc = RTSemEventWait(mEventSem, msTimeout ? msTimeout : RT_INDEFINITE_WAIT);
        if (   RT_SUCCESS(vrc)
            && mfAborted)
            vrc = VERR_CANCELLED;

        if (RT_SUCCESS(vrc))
        {
            /* If waiting succeeded, return the overall
             * result code. */
            vrc = mVrc;
        }
    }
    else
        vrc = VERR_CANCELLED;
    return vrc;
}

GuestWaitEvent::GuestWaitEvent(void)
{
}

GuestWaitEvent::~GuestWaitEvent(void)
{

}

/**
 * Cancels the event.
 */
int GuestWaitEvent::Cancel(void)
{
    if (mfAborted) /* Already aborted? */
        return VINF_SUCCESS;

    mfAborted = true;

#ifdef DEBUG_andy
    LogFlowThisFunc(("Cancelling %p ...\n"));
#endif
    return RTSemEventSignal(mEventSem);
}

/**
 * Initializes a wait event with a given context ID (CID).
 *
 * @returns VBox status code.
 * @param   uCID                Context ID to initialize wait event with.
 */
int GuestWaitEvent::Init(uint32_t uCID)
{
    return GuestWaitEventBase::Init(uCID);
}

/**
 * Initializes a wait event with a given context ID (CID) and a list of event types to wait for.
 *
 * @returns VBox status code.
 * @param   uCID                Context ID to initialize wait event with.
 * @param   lstEvents           List of event types to wait for this wait event to get signalled.
 */
int GuestWaitEvent::Init(uint32_t uCID, const GuestEventTypes &lstEvents)
{
    int vrc = GuestWaitEventBase::Init(uCID);
    if (RT_SUCCESS(vrc))
        mEventTypes = lstEvents;

    return vrc;
}

/**
 * Signals the event.
 *
 * @return  VBox status code.
 * @param   pEvent              Public IEvent to associate.
 *                              Optional.
 */
int GuestWaitEvent::SignalExternal(IEvent *pEvent)
{
    if (pEvent)
        mEvent = pEvent;

    return RTSemEventSignal(mEventSem);
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GuestPath
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * Builds a (final) destination path from a given source + destination path.
 *
 * This does not utilize any file system access whatsoever. Used for guest and host paths.
 *
 * @returns VBox status code.
 * @param   strSrcPath          Source path to build destination path for.
 * @param   enmSrcPathStyle     Path style the source path is in.
 * @param   strDstPath          Destination path to use for building the (final) destination path.
 * @param   enmDstPathStyle     Path style the destination path is in.
 *
 * @note    See rules within the function.
 */
/* static */
int GuestPath::BuildDestinationPath(const Utf8Str &strSrcPath, PathStyle_T enmSrcPathStyle,
                                    Utf8Str &strDstPath, PathStyle_T enmDstPathStyle)
{
    /*
     * Rules:
     *
     * #    source       dest             final dest                        remarks
     *
     * 1    /src/path1/  /dst/path2/      /dst/path2/<contents of path1>    Just copies contents of <contents of path1>, not the path1 itself.
     * 2    /src/path1   /dst/path2/      /dst/path2/path1                  Copies path1 into path2.
     * 3    /src/path1   /dst/path2       /dst/path2                        Overwrites stuff from path2 with stuff from path1.
     * 4    Dotdot ("..") directories are forbidden for security reasons.
     */
    const char *pszSrcName = RTPathFilenameEx(strSrcPath.c_str(),
                                                enmSrcPathStyle == PathStyle_DOS
                                              ? RTPATH_STR_F_STYLE_DOS : RTPATH_STR_F_STYLE_UNIX);

    const char *pszDstName = RTPathFilenameEx(strDstPath.c_str(),
                                                enmDstPathStyle == PathStyle_DOS
                                              ? RTPATH_STR_F_STYLE_DOS : RTPATH_STR_F_STYLE_UNIX);

    if (   (!pszSrcName && !pszDstName)  /* #1 */
        || ( pszSrcName &&  pszDstName)) /* #3 */
    {
        /* Note: Must have DirectoryFlag_CopyIntoExisting + FileFlag_NoReplace *not* set. */
    }
    else if (pszSrcName && !pszDstName) /* #2 */
    {
        if (!strDstPath.endsWith(PATH_STYLE_SEP_STR(enmDstPathStyle)))
            strDstPath += PATH_STYLE_SEP_STR(enmDstPathStyle);
        strDstPath += pszSrcName;
    }

    /* Translate the built destination path to a path compatible with the destination. */
    int vrc = GuestPath::Translate(strDstPath, enmSrcPathStyle, enmDstPathStyle);
    if (RT_SUCCESS(vrc))
    {
        union
        {
            RTPATHPARSED    Parsed;
            RTPATHSPLIT     Split;
            uint8_t         ab[4096];
        } u;
        vrc = RTPathParse(strDstPath.c_str(), &u.Parsed, sizeof(u),  enmDstPathStyle == PathStyle_DOS
                                                                   ? RTPATH_STR_F_STYLE_DOS : RTPATH_STR_F_STYLE_UNIX);
        if (RT_SUCCESS(vrc))
        {
            if (u.Parsed.fProps & RTPATH_PROP_DOTDOT_REFS) /* #4 */
                vrc = VERR_INVALID_PARAMETER;
        }
    }

    LogRel2(("Guest Control: Building destination path for '%s' (%s) -> '%s' (%s): %Rrc\n",
             strSrcPath.c_str(), GuestBase::pathStyleToStr(enmSrcPathStyle),
             strDstPath.c_str(), GuestBase::pathStyleToStr(enmDstPathStyle), vrc));

    return vrc;
}

/**
 * Translates a path from a specific path style into another.
 *
 * @returns VBox status code.
 * @retval  VERR_NOT_SUPPORTED if a conversion is not supported.
 * @retval  VERR_NOT_IMPLEMENTED if path style conversion is not implemented yet.
 * @param   strPath             Path to translate. Will contain the translated path on success. UTF-8 only.
 * @param   enmSrcPathStyle     Source path style \a strPath is expected in.
 * @param   enmDstPathStyle     Destination path style to convert to.
 * @param   fForce              Whether to force the translation to the destination path style or not.
 *
 * @note    This does NOT remove any trailing slashes and/or perform file system lookups!
 */
/* static */
int GuestPath::Translate(Utf8Str &strPath, PathStyle_T enmSrcPathStyle, PathStyle_T enmDstPathStyle, bool fForce /* = false */)
{
    if (strPath.isEmpty())
        return VINF_SUCCESS;

    AssertReturn(RTStrIsValidEncoding(strPath.c_str()), VERR_INVALID_PARAMETER);

    int vrc = VINF_SUCCESS;

    Utf8Str strTranslated;

    if (   (   enmSrcPathStyle == PathStyle_DOS
            && enmDstPathStyle == PathStyle_UNIX)
        || (fForce && enmDstPathStyle == PathStyle_UNIX))
    {
        strTranslated = strPath;
        RTPathChangeToUnixSlashes(strTranslated.mutableRaw(), true /* fForce */);
    }
    else if (  (   enmSrcPathStyle == PathStyle_UNIX
                && enmDstPathStyle == PathStyle_DOS)
            || (fForce && enmDstPathStyle == PathStyle_DOS))

    {
        strTranslated = strPath;
        RTPathChangeToDosSlashes(strTranslated.mutableRaw(), true /* fForce */);
    }

    if (   strTranslated.isEmpty() /* Not forced. */
        && enmSrcPathStyle == enmDstPathStyle)
    {
        strTranslated = strPath;
    }

    if (RT_FAILURE(vrc))
    {
        LogRel(("Guest Control: Translating path '%s' (%s) -> '%s' (%s) failed, vrc=%Rrc\n",
                strPath.c_str(), GuestBase::pathStyleToStr(enmSrcPathStyle),
                strTranslated.c_str(), GuestBase::pathStyleToStr(enmDstPathStyle), vrc));
        return vrc;
    }

    /* Cleanup. */
    const char  *psz = strTranslated.mutableRaw();
    size_t const cch = strTranslated.length();
    size_t       off = 0;
    while (off < cch)
    {
        if (off + 1 > cch)
            break;
        /* Remove double back slashes (DOS only). */
        if (   enmDstPathStyle == PathStyle_DOS
            && psz[off]     == '\\'
            && psz[off + 1] == '\\')
        {
            strTranslated.erase(off + 1, 1);
            off++;
        }
        /* Remove double forward slashes (UNIX only). */
        if (   enmDstPathStyle == PathStyle_UNIX
            && psz[off]     == '/'
            && psz[off + 1] == '/')
        {
            strTranslated.erase(off + 1, 1);
            off++;
        }
        off++;
    }

    /* Note: Do not trim() paths here, as technically it's possible to create paths with trailing spaces. */

    strTranslated.jolt();

    LogRel2(("Guest Control: Translating '%s' (%s) -> '%s' (%s): %Rrc\n",
             strPath.c_str(), GuestBase::pathStyleToStr(enmSrcPathStyle),
             strTranslated.c_str(), GuestBase::pathStyleToStr(enmDstPathStyle), vrc));

    if (RT_SUCCESS(vrc))
        strPath = strTranslated;

    return vrc;
}