summaryrefslogtreecommitdiff
path: root/src/VBox/Main/src-client/HGCM.cpp
blob: 722333ff2de27836cfcdd32fde7ab866217a39b6 (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
/** @file
 *
 * HGCM (Host-Guest Communication Manager)
 */

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

#define LOG_GROUP_MAIN_OVERRIDE LOG_GROUP_HGCM
#include "Logging.h"

#include "HGCM.h"
#include "HGCMThread.h"

#include <VBox/err.h>
#include <VBox/hgcmsvc.h>
#include <VBox/vmm/ssm.h>
#include <VBox/sup.h>

#include <iprt/alloc.h>
#include <iprt/alloca.h>
#include <iprt/avl.h>
#include <iprt/critsect.h>
#include <iprt/asm.h>
#include <iprt/ldr.h>
#include <iprt/param.h>
#include <iprt/path.h>
#include <iprt/string.h>
#include <iprt/semaphore.h>
#include <iprt/thread.h>

#include <VBox/VMMDev.h>

/**
 * A service gets one thread, which synchronously delivers messages to
 * the service. This is good for serialization.
 *
 * Some services may want to process messages asynchronously, and will want
 * a next message to be delivered, while a previous message is still being
 * processed.
 *
 * The dedicated service thread delivers a next message when service
 * returns after fetching a previous one. The service will call a message
 * completion callback when message is actually processed. So returning
 * from the service call means only that the service is processing message.
 *
 * 'Message processed' condition is indicated by service, which call the
 * callback, even if the callback is called synchronously in the dedicated
 * thread.
 *
 * This message completion callback is only valid for Call requests.
 * Connect and Disconnect are processed synchronously by the service.
 */


/* The maximum allowed size of a service name in bytes. */
#define VBOX_HGCM_SVC_NAME_MAX_BYTES 1024

struct _HGCMSVCEXTHANDLEDATA
{
    char *pszServiceName;
    /* The service name follows. */
};

/** Internal helper service object. HGCM code would use it to
 *  hold information about services and communicate with services.
 *  The HGCMService is an (in future) abstract class that implements
 *  common functionality. There will be derived classes for specific
 *  service types.
 */

class HGCMService
{
    private:
        VBOXHGCMSVCHELPERS m_svcHelpers;

        static HGCMService *sm_pSvcListHead;
        static HGCMService *sm_pSvcListTail;

        static int sm_cServices;

        HGCMTHREADHANDLE m_thread;
        friend DECLCALLBACK(void) hgcmServiceThread (HGCMTHREADHANDLE ThreadHandle, void *pvUser);

        uint32_t volatile m_u32RefCnt;

        HGCMService *m_pSvcNext;
        HGCMService *m_pSvcPrev;

        char *m_pszSvcName;
        char *m_pszSvcLibrary;

        RTLDRMOD m_hLdrMod;
        PFNVBOXHGCMSVCLOAD m_pfnLoad;

        VBOXHGCMSVCFNTABLE m_fntable;

        int m_cClients;
        int m_cClientsAllocated;

        uint32_t *m_paClientIds;

#ifdef VBOX_WITH_CRHGSMI
        uint32_t m_cHandleAcquires;
#endif

        HGCMSVCEXTHANDLE m_hExtension;

        int loadServiceDLL (void);
        void unloadServiceDLL (void);

        /*
         * Main HGCM thread methods.
         */
        int instanceCreate (const char *pszServiceLibrary, const char *pszServiceName);
        void instanceDestroy (void);

        int saveClientState(uint32_t u32ClientId, PSSMHANDLE pSSM);
        int loadClientState(uint32_t u32ClientId, PSSMHANDLE pSSM);

        HGCMService ();
        ~HGCMService () {};

        static DECLCALLBACK(void) svcHlpCallComplete (VBOXHGCMCALLHANDLE callHandle, int32_t rc);
        static DECLCALLBACK(void) svcHlpDisconnectClient (void *pvInstance, uint32_t u32ClientId);

    public:

        /*
         * Main HGCM thread methods.
         */
        static int LoadService (const char *pszServiceLibrary, const char *pszServiceName);
        void UnloadService (void);

        static void UnloadAll (void);

        static int ResolveService (HGCMService **ppsvc, const char *pszServiceName);
        void ReferenceService (void);
        void ReleaseService (void);

        static void Reset (void);

        static int SaveState (PSSMHANDLE pSSM);
        static int LoadState (PSSMHANDLE pSSM);

        int CreateAndConnectClient (uint32_t *pu32ClientIdOut, uint32_t u32ClientIdIn);
        int DisconnectClient (uint32_t u32ClientId, bool fFromService);

        int HostCall (uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM *paParms);

#ifdef VBOX_WITH_CRHGSMI
        int HandleAcquired();
        int HandleReleased();
        int HostFastCallAsync (uint32_t u32Function, VBOXHGCMSVCPARM *pParm, PHGCMHOSTFASTCALLCB pfnCompletion, void *pvCompletion);
#endif

        uint32_t SizeOfClient (void) { return m_fntable.cbClient; };

        int RegisterExtension (HGCMSVCEXTHANDLE handle, PFNHGCMSVCEXT pfnExtension, void *pvExtension);
        void UnregisterExtension (HGCMSVCEXTHANDLE handle);

        /*
         * The service thread methods.
         */

        int GuestCall (PPDMIHGCMPORT pHGCMPort, PVBOXHGCMCMD pCmd, uint32_t u32ClientId, uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM aParms[]);
};


class HGCMClient: public HGCMObject
{
    public:
        HGCMClient () : HGCMObject(HGCMOBJ_CLIENT), pService(NULL),
                        pvData(NULL) {};
        ~HGCMClient ();

        int Init (HGCMService *pSvc);

        /** Service that the client is connected to. */
        HGCMService *pService;

        /** Client specific data. */
        void *pvData;
};

HGCMClient::~HGCMClient ()
{
    if (pService->SizeOfClient () > 0)
        RTMemFree (pvData);
}

int HGCMClient::Init (HGCMService *pSvc)
{
    pService = pSvc;

    if (pService->SizeOfClient () > 0)
    {
        pvData = RTMemAllocZ (pService->SizeOfClient ());

        if (!pvData)
        {
           return VERR_NO_MEMORY;
        }
    }

    return VINF_SUCCESS;
}


#define HGCM_CLIENT_DATA(pService, pClient) (pClient->pvData)



HGCMService *HGCMService::sm_pSvcListHead = NULL;
HGCMService *HGCMService::sm_pSvcListTail = NULL;
int HGCMService::sm_cServices = 0;

HGCMService::HGCMService ()
    :
    m_thread     (0),
    m_u32RefCnt  (0),
    m_pSvcNext   (NULL),
    m_pSvcPrev   (NULL),
    m_pszSvcName (NULL),
    m_pszSvcLibrary (NULL),
    m_hLdrMod    (NIL_RTLDRMOD),
    m_pfnLoad    (NULL),
    m_cClients   (0),
    m_cClientsAllocated (0),
    m_paClientIds (NULL),
#ifdef VBOX_WITH_CRHGSMI
    m_cHandleAcquires (0),
#endif
    m_hExtension (NULL)
{
    RT_ZERO(m_fntable);
}


static bool g_fResetting = false;
static bool g_fSaveState = false;


/** Helper function to load a local service DLL.
 *
 *  @return VBox code
 */
int HGCMService::loadServiceDLL(void)
{
    LogFlowFunc(("m_pszSvcLibrary = %s\n", m_pszSvcLibrary));

    if (m_pszSvcLibrary == NULL)
    {
        return VERR_INVALID_PARAMETER;
    }

    RTERRINFOSTATIC ErrInfo;
    RTErrInfoInitStatic(&ErrInfo);

    int rc;

    if (RTPathHasPath(m_pszSvcLibrary))
        rc = SUPR3HardenedLdrLoadPlugIn(m_pszSvcLibrary, &m_hLdrMod, &ErrInfo.Core);
    else
        rc = SUPR3HardenedLdrLoadAppPriv(m_pszSvcLibrary, &m_hLdrMod, RTLDRLOAD_FLAGS_LOCAL, &ErrInfo.Core);

    if (RT_SUCCESS(rc))
    {
        LogFlowFunc(("successfully loaded the library.\n"));

        m_pfnLoad = NULL;

        rc = RTLdrGetSymbol(m_hLdrMod, VBOX_HGCM_SVCLOAD_NAME, (void**)&m_pfnLoad);

        if (RT_FAILURE(rc) || !m_pfnLoad)
        {
            Log(("HGCMService::loadServiceDLL: Error resolving the service entry point %s, rc = %d, m_pfnLoad = %p\n", VBOX_HGCM_SVCLOAD_NAME, rc, m_pfnLoad));

            if (RT_SUCCESS(rc))
            {
                /* m_pfnLoad was NULL */
                rc = VERR_SYMBOL_NOT_FOUND;
            }
        }

        if (RT_SUCCESS(rc))
        {
            RT_ZERO(m_fntable);

            m_fntable.cbSize     = sizeof(m_fntable);
            m_fntable.u32Version = VBOX_HGCM_SVC_VERSION;
            m_fntable.pHelpers   = &m_svcHelpers;

            rc = m_pfnLoad(&m_fntable);

            LogFlowFunc(("m_pfnLoad rc = %Rrc\n", rc));

            if (RT_SUCCESS(rc))
            {
                if (   m_fntable.pfnUnload == NULL
                    || m_fntable.pfnConnect == NULL
                    || m_fntable.pfnDisconnect == NULL
                    || m_fntable.pfnCall == NULL
                   )
                {
                    Log(("HGCMService::loadServiceDLL: at least one of function pointers is NULL\n"));

                    rc = VERR_INVALID_PARAMETER;

                    if (m_fntable.pfnUnload)
                    {
                        m_fntable.pfnUnload(m_fntable.pvService);
                    }
                }
            }
        }
    }
    else
    {
        LogRel(("HGCM: Failed to load the service library: [%s], rc = %Rrc - %s. The service will be not available.\n",
                m_pszSvcLibrary, rc, ErrInfo.Core.pszMsg));
        m_hLdrMod = NIL_RTLDRMOD;
    }

    if (RT_FAILURE(rc))
    {
        unloadServiceDLL();
    }

    return rc;
}

/** Helper function to free a local service DLL.
 *
 *  @return VBox code
 */
void HGCMService::unloadServiceDLL(void)
{
    if (m_hLdrMod)
    {
        RTLdrClose(m_hLdrMod);
    }

    RT_ZERO(m_fntable);
    m_pfnLoad = NULL;
    m_hLdrMod = NIL_RTLDRMOD;
}

/*
 * Messages processed by service threads. These threads only call the service entry points.
 */

#define SVC_MSG_LOAD       (0)  /* Load the service library and call VBOX_HGCM_SVCLOAD_NAME entry point. */
#define SVC_MSG_UNLOAD     (1)  /* call pfnUnload and unload the service library. */
#define SVC_MSG_CONNECT    (2)  /* pfnConnect */
#define SVC_MSG_DISCONNECT (3)  /* pfnDisconnect */
#define SVC_MSG_GUESTCALL  (4)  /* pfnGuestCall */
#define SVC_MSG_HOSTCALL   (5)  /* pfnHostCall */
#define SVC_MSG_LOADSTATE  (6)  /* pfnLoadState. */
#define SVC_MSG_SAVESTATE  (7)  /* pfnSaveState. */
#define SVC_MSG_QUIT       (8)  /* Terminate the thread. */
#define SVC_MSG_REGEXT     (9)  /* pfnRegisterExtension */
#define SVC_MSG_UNREGEXT   (10) /* pfnRegisterExtension */
#ifdef VBOX_WITH_CRHGSMI
# define SVC_MSG_HOSTFASTCALLASYNC (21) /* pfnHostCall */
#endif

class HGCMMsgSvcLoad: public HGCMMsgCore
{
};

class HGCMMsgSvcUnload: public HGCMMsgCore
{
};

class HGCMMsgSvcConnect: public HGCMMsgCore
{
    public:
        /* client identifier */
        uint32_t u32ClientId;
};

class HGCMMsgSvcDisconnect: public HGCMMsgCore
{
    public:
        /* client identifier */
        uint32_t u32ClientId;
};

class HGCMMsgHeader: public HGCMMsgCore
{
    public:
        HGCMMsgHeader () : pCmd (NULL), pHGCMPort (NULL) {};

        /* Command pointer/identifier. */
        PVBOXHGCMCMD pCmd;

        /* Port to be informed on message completion. */
        PPDMIHGCMPORT pHGCMPort;
};


class HGCMMsgCall: public HGCMMsgHeader
{
    public:
        /* client identifier */
        uint32_t u32ClientId;

        /* function number */
        uint32_t u32Function;

        /* number of parameters */
        uint32_t cParms;

        VBOXHGCMSVCPARM *paParms;
};

class HGCMMsgLoadSaveStateClient: public HGCMMsgCore
{
    public:
        uint32_t    u32ClientId;
        PSSMHANDLE  pSSM;
};

class HGCMMsgHostCallSvc: public HGCMMsgCore
{
    public:
        /* function number */
        uint32_t u32Function;

        /* number of parameters */
        uint32_t cParms;

        VBOXHGCMSVCPARM *paParms;
};

class HGCMMsgSvcRegisterExtension: public HGCMMsgCore
{
    public:
        /* Handle of the extension to be registered. */
        HGCMSVCEXTHANDLE handle;
        /* The extension entry point. */
        PFNHGCMSVCEXT pfnExtension;
        /* The extension pointer. */
        void *pvExtension;
};

class HGCMMsgSvcUnregisterExtension: public HGCMMsgCore
{
    public:
        /* Handle of the registered extension. */
        HGCMSVCEXTHANDLE handle;
};

#ifdef VBOX_WITH_CRHGSMI
class HGCMMsgHostFastCallAsyncSvc: public HGCMMsgCore
{
    public:
        /* function number */
        uint32_t u32Function;
        /* parameter */
        VBOXHGCMSVCPARM Param;
        /* completion info */
        PHGCMHOSTFASTCALLCB pfnCompletion;
        void *pvCompletion;
};
#endif

static HGCMMsgCore *hgcmMessageAllocSvc (uint32_t u32MsgId)
{
    switch (u32MsgId)
    {
#ifdef VBOX_WITH_CRHGSMI
        case SVC_MSG_HOSTFASTCALLASYNC: return new HGCMMsgHostFastCallAsyncSvc ();
#endif
        case SVC_MSG_LOAD:        return new HGCMMsgSvcLoad ();
        case SVC_MSG_UNLOAD:      return new HGCMMsgSvcUnload ();
        case SVC_MSG_CONNECT:     return new HGCMMsgSvcConnect ();
        case SVC_MSG_DISCONNECT:  return new HGCMMsgSvcDisconnect ();
        case SVC_MSG_HOSTCALL:    return new HGCMMsgHostCallSvc ();
        case SVC_MSG_GUESTCALL:   return new HGCMMsgCall ();
        case SVC_MSG_LOADSTATE:
        case SVC_MSG_SAVESTATE:   return new HGCMMsgLoadSaveStateClient ();
        case SVC_MSG_REGEXT:      return new HGCMMsgSvcRegisterExtension ();
        case SVC_MSG_UNREGEXT:    return new HGCMMsgSvcUnregisterExtension ();
        default:
            AssertReleaseMsgFailed(("Msg id = %08X\n", u32MsgId));
    }

    return NULL;
}

/*
 * The service thread. Loads the service library and calls the service entry points.
 */
DECLCALLBACK(void) hgcmServiceThread (HGCMTHREADHANDLE ThreadHandle, void *pvUser)
{
    HGCMService *pSvc = (HGCMService *)pvUser;
    AssertRelease(pSvc != NULL);

    bool fQuit = false;

    while (!fQuit)
    {
        HGCMMsgCore *pMsgCore;
        int rc = hgcmMsgGet (ThreadHandle, &pMsgCore);

        if (RT_FAILURE(rc))
        {
            /* The error means some serious unrecoverable problem in the hgcmMsg/hgcmThread layer. */
            AssertMsgFailed (("%Rrc\n", rc));
            break;
        }

        /* Cache required information to avoid unnecessary pMsgCore access. */
        uint32_t u32MsgId = pMsgCore->MsgId ();

        switch (u32MsgId)
        {
#ifdef VBOX_WITH_CRHGSMI
            case SVC_MSG_HOSTFASTCALLASYNC:
            {
                HGCMMsgHostFastCallAsyncSvc *pMsg = (HGCMMsgHostFastCallAsyncSvc *)pMsgCore;

                LogFlowFunc(("SVC_MSG_HOSTFASTCALLASYNC u32Function = %d, pParm = %p\n", pMsg->u32Function, &pMsg->Param));

                rc = pSvc->m_fntable.pfnHostCall (pSvc->m_fntable.pvService, pMsg->u32Function, 1, &pMsg->Param);
            } break;
#endif
            case SVC_MSG_LOAD:
            {
                LogFlowFunc(("SVC_MSG_LOAD\n"));
                rc = pSvc->loadServiceDLL ();
            } break;

            case SVC_MSG_UNLOAD:
            {
                LogFlowFunc(("SVC_MSG_UNLOAD\n"));
                if (pSvc->m_fntable.pfnUnload)
                {
                    pSvc->m_fntable.pfnUnload (pSvc->m_fntable.pvService);
                }

                pSvc->unloadServiceDLL ();
                fQuit = true;
            } break;

            case SVC_MSG_CONNECT:
            {
                HGCMMsgSvcConnect *pMsg = (HGCMMsgSvcConnect *)pMsgCore;

                LogFlowFunc(("SVC_MSG_CONNECT u32ClientId = %d\n", pMsg->u32ClientId));

                HGCMClient *pClient = (HGCMClient *)hgcmObjReference (pMsg->u32ClientId, HGCMOBJ_CLIENT);

                if (pClient)
                {
                    rc = pSvc->m_fntable.pfnConnect (pSvc->m_fntable.pvService, pMsg->u32ClientId, HGCM_CLIENT_DATA(pSvc, pClient));

                    hgcmObjDereference (pClient);
                }
                else
                {
                    rc = VERR_HGCM_INVALID_CLIENT_ID;
                }
            } break;

            case SVC_MSG_DISCONNECT:
            {
                HGCMMsgSvcDisconnect *pMsg = (HGCMMsgSvcDisconnect *)pMsgCore;

                LogFlowFunc(("SVC_MSG_DISCONNECT u32ClientId = %d\n", pMsg->u32ClientId));

                HGCMClient *pClient = (HGCMClient *)hgcmObjReference (pMsg->u32ClientId, HGCMOBJ_CLIENT);

                if (pClient)
                {
                    rc = pSvc->m_fntable.pfnDisconnect (pSvc->m_fntable.pvService, pMsg->u32ClientId, HGCM_CLIENT_DATA(pSvc, pClient));

                    hgcmObjDereference (pClient);
                }
                else
                {
                    rc = VERR_HGCM_INVALID_CLIENT_ID;
                }
            } break;

            case SVC_MSG_GUESTCALL:
            {
                HGCMMsgCall *pMsg = (HGCMMsgCall *)pMsgCore;

                LogFlowFunc(("SVC_MSG_GUESTCALL u32ClientId = %d, u32Function = %d, cParms = %d, paParms = %p\n",
                             pMsg->u32ClientId, pMsg->u32Function, pMsg->cParms, pMsg->paParms));

                HGCMClient *pClient = (HGCMClient *)hgcmObjReference (pMsg->u32ClientId, HGCMOBJ_CLIENT);

                if (pClient)
                {
                    pSvc->m_fntable.pfnCall (pSvc->m_fntable.pvService, (VBOXHGCMCALLHANDLE)pMsg, pMsg->u32ClientId, HGCM_CLIENT_DATA(pSvc, pClient), pMsg->u32Function, pMsg->cParms, pMsg->paParms);

                    hgcmObjDereference (pClient);
                }
                else
                {
                    rc = VERR_HGCM_INVALID_CLIENT_ID;
                }
            } break;

            case SVC_MSG_HOSTCALL:
            {
                HGCMMsgHostCallSvc *pMsg = (HGCMMsgHostCallSvc *)pMsgCore;

                LogFlowFunc(("SVC_MSG_HOSTCALL u32Function = %d, cParms = %d, paParms = %p\n", pMsg->u32Function, pMsg->cParms, pMsg->paParms));

                rc = pSvc->m_fntable.pfnHostCall (pSvc->m_fntable.pvService, pMsg->u32Function, pMsg->cParms, pMsg->paParms);
            } break;

            case SVC_MSG_LOADSTATE:
            {
                HGCMMsgLoadSaveStateClient *pMsg = (HGCMMsgLoadSaveStateClient *)pMsgCore;

                LogFlowFunc(("SVC_MSG_LOADSTATE\n"));

                HGCMClient *pClient = (HGCMClient *)hgcmObjReference (pMsg->u32ClientId, HGCMOBJ_CLIENT);

                if (pClient)
                {
                    if (pSvc->m_fntable.pfnLoadState)
                    {
                        rc = pSvc->m_fntable.pfnLoadState (pSvc->m_fntable.pvService, pMsg->u32ClientId, HGCM_CLIENT_DATA(pSvc, pClient), pMsg->pSSM);
                    }

                    hgcmObjDereference (pClient);
                }
                else
                {
                    rc = VERR_HGCM_INVALID_CLIENT_ID;
                }
            } break;

            case SVC_MSG_SAVESTATE:
            {
                HGCMMsgLoadSaveStateClient *pMsg = (HGCMMsgLoadSaveStateClient *)pMsgCore;

                LogFlowFunc(("SVC_MSG_SAVESTATE\n"));

                HGCMClient *pClient = (HGCMClient *)hgcmObjReference (pMsg->u32ClientId, HGCMOBJ_CLIENT);

                rc = VINF_SUCCESS;

                if (pClient)
                {
                    if (pSvc->m_fntable.pfnSaveState)
                    {
                        g_fSaveState = true;
                        rc = pSvc->m_fntable.pfnSaveState (pSvc->m_fntable.pvService, pMsg->u32ClientId, HGCM_CLIENT_DATA(pSvc, pClient), pMsg->pSSM);
                        g_fSaveState = false;
                    }

                    hgcmObjDereference (pClient);
                }
                else
                {
                    rc = VERR_HGCM_INVALID_CLIENT_ID;
                }
            } break;

            case SVC_MSG_REGEXT:
            {
                HGCMMsgSvcRegisterExtension *pMsg = (HGCMMsgSvcRegisterExtension *)pMsgCore;

                LogFlowFunc(("SVC_MSG_REGEXT handle = %p, pfn = %p\n", pMsg->handle, pMsg->pfnExtension));

                if (pSvc->m_hExtension)
                {
                    rc = VERR_NOT_SUPPORTED;
                }
                else
                {
                    if (pSvc->m_fntable.pfnRegisterExtension)
                    {
                        rc = pSvc->m_fntable.pfnRegisterExtension (pSvc->m_fntable.pvService, pMsg->pfnExtension, pMsg->pvExtension);
                    }
                    else
                    {
                        rc = VERR_NOT_SUPPORTED;
                    }

                    if (RT_SUCCESS(rc))
                    {
                        pSvc->m_hExtension = pMsg->handle;
                    }
                }
            } break;

            case SVC_MSG_UNREGEXT:
            {
                HGCMMsgSvcUnregisterExtension *pMsg = (HGCMMsgSvcUnregisterExtension *)pMsgCore;

                LogFlowFunc(("SVC_MSG_UNREGEXT handle = %p\n", pMsg->handle));

                if (pSvc->m_hExtension != pMsg->handle)
                {
                    rc = VERR_NOT_SUPPORTED;
                }
                else
                {
                    if (pSvc->m_fntable.pfnRegisterExtension)
                    {
                        rc = pSvc->m_fntable.pfnRegisterExtension (pSvc->m_fntable.pvService, NULL, NULL);
                    }
                    else
                    {
                        rc = VERR_NOT_SUPPORTED;
                    }

                    pSvc->m_hExtension = NULL;
                }
            } break;

            default:
            {
                AssertMsgFailed(("hgcmServiceThread::Unsupported message number %08X\n", u32MsgId));
                rc = VERR_NOT_SUPPORTED;
            } break;
        }

        if (u32MsgId != SVC_MSG_GUESTCALL)
        {
            /* For SVC_MSG_GUESTCALL the service calls the completion helper.
             * Other messages have to be completed here.
             */
            hgcmMsgComplete (pMsgCore, rc);
        }
    }
}

/* static */ DECLCALLBACK(void) HGCMService::svcHlpCallComplete (VBOXHGCMCALLHANDLE callHandle, int32_t rc)
{
   HGCMMsgCore *pMsgCore = (HGCMMsgCore *)callHandle;

   if (pMsgCore->MsgId () == SVC_MSG_GUESTCALL)
   {
       /* Only call the completion for these messages. The helper
        * is called by the service, and the service does not get
        * any other messages.
        */
       hgcmMsgComplete (pMsgCore, rc);
   }
   else
   {
       AssertFailed ();
   }
}

/* static */ DECLCALLBACK(void) HGCMService::svcHlpDisconnectClient (void *pvInstance, uint32_t u32ClientId)
{
     HGCMService *pService = static_cast <HGCMService *> (pvInstance);

     if (pService)
     {
         pService->DisconnectClient (u32ClientId, true);
     }
}

static DECLCALLBACK(void) hgcmMsgCompletionCallback (int32_t result, HGCMMsgCore *pMsgCore)
{
    /* Call the VMMDev port interface to issue IRQ notification. */
    HGCMMsgHeader *pMsgHdr = (HGCMMsgHeader *)pMsgCore;

    LogFlow(("MAIN::hgcmMsgCompletionCallback: message %p\n", pMsgCore));

    if (pMsgHdr->pHGCMPort && !g_fResetting)
    {
        pMsgHdr->pHGCMPort->pfnCompleted (pMsgHdr->pHGCMPort, g_fSaveState? VINF_HGCM_SAVE_STATE: result, pMsgHdr->pCmd);
    }
}

/*
 * The main HGCM methods of the service.
 */

int HGCMService::instanceCreate (const char *pszServiceLibrary, const char *pszServiceName)
{
    LogFlowFunc(("name %s, lib %s\n", pszServiceName, pszServiceLibrary));

    /* The maximum length of the thread name, allowed by the RT is 15. */
    char szThreadName[16];
    if (!strncmp (pszServiceName, RT_STR_TUPLE("VBoxShared")))
        RTStrPrintf (szThreadName, sizeof (szThreadName), "Sh%s", pszServiceName + 10);
    else if (!strncmp (pszServiceName, RT_STR_TUPLE("VBox")))
        RTStrCopy (szThreadName, sizeof (szThreadName), pszServiceName + 4);
    else
        RTStrCopy (szThreadName, sizeof (szThreadName), pszServiceName);

    int rc = hgcmThreadCreate (&m_thread, szThreadName, hgcmServiceThread, this);

    if (RT_SUCCESS(rc))
    {
        m_pszSvcName    = RTStrDup (pszServiceName);
        m_pszSvcLibrary = RTStrDup (pszServiceLibrary);

        if (!m_pszSvcName || !m_pszSvcLibrary)
        {
            RTStrFree (m_pszSvcLibrary);
            m_pszSvcLibrary = NULL;

            RTStrFree (m_pszSvcName);
            m_pszSvcName = NULL;

            rc = VERR_NO_MEMORY;
        }
        else
        {
            /* Initialize service helpers table. */
            m_svcHelpers.pfnCallComplete     = svcHlpCallComplete;
            m_svcHelpers.pvInstance          = this;
            m_svcHelpers.pfnDisconnectClient = svcHlpDisconnectClient;

            /* Execute the load request on the service thread. */
            HGCMMSGHANDLE hMsg;
            rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_LOAD, hgcmMessageAllocSvc);

            if (RT_SUCCESS(rc))
            {
                rc = hgcmMsgSend (hMsg);
            }
        }
    }

    if (RT_FAILURE(rc))
    {
        instanceDestroy ();
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

void HGCMService::instanceDestroy (void)
{
    LogFlowFunc(("%s\n", m_pszSvcName));

    HGCMMSGHANDLE hMsg;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_UNLOAD, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        rc = hgcmMsgSend (hMsg);

        if (RT_SUCCESS(rc))
        {
            hgcmThreadWait (m_thread);
        }
    }

    RTStrFree (m_pszSvcLibrary);
    m_pszSvcLibrary = NULL;

    RTStrFree (m_pszSvcName);
    m_pszSvcName = NULL;
}

int HGCMService::saveClientState(uint32_t u32ClientId, PSSMHANDLE pSSM)
{
    LogFlowFunc(("%s\n", m_pszSvcName));

    HGCMMSGHANDLE hMsg;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_SAVESTATE, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgLoadSaveStateClient *pMsg = (HGCMMsgLoadSaveStateClient *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->u32ClientId = u32ClientId;
        pMsg->pSSM        = pSSM;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

int HGCMService::loadClientState (uint32_t u32ClientId, PSSMHANDLE pSSM)
{
    LogFlowFunc(("%s\n", m_pszSvcName));

    HGCMMSGHANDLE hMsg;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_LOADSTATE, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgLoadSaveStateClient *pMsg = (HGCMMsgLoadSaveStateClient *)hgcmObjReference (hMsg, HGCMOBJ_MSG);

        AssertRelease(pMsg);

        pMsg->u32ClientId = u32ClientId;
        pMsg->pSSM        = pSSM;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}


/** The method creates a service and references it.
 *
 * @param pszServiceLibrary  The library to be loaded.
 * @param pszServiceName     The name of the service.
 * @return VBox rc.
 * @thread main HGCM
 */
/* static */ int HGCMService::LoadService (const char *pszServiceLibrary, const char *pszServiceName)
{
    LogFlowFunc(("lib %s, name = %s\n", pszServiceLibrary, pszServiceName));

    /* Look at already loaded services to avoid double loading. */

    HGCMService *pSvc;
    int rc = HGCMService::ResolveService (&pSvc, pszServiceName);

    if (RT_SUCCESS(rc))
    {
        /* The service is already loaded. */
        pSvc->ReleaseService ();
        rc = VERR_HGCM_SERVICE_EXISTS;
    }
    else
    {
        /* Create the new service. */
        pSvc = new HGCMService ();

        if (!pSvc)
        {
            rc = VERR_NO_MEMORY;
        }
        else
        {
            /* Load the library and call the initialization entry point. */
            rc = pSvc->instanceCreate (pszServiceLibrary, pszServiceName);

            if (RT_SUCCESS(rc))
            {
                /* Insert the just created service to list for future references. */
                pSvc->m_pSvcNext = sm_pSvcListHead;
                pSvc->m_pSvcPrev = NULL;

                if (sm_pSvcListHead)
                {
                    sm_pSvcListHead->m_pSvcPrev = pSvc;
                }
                else
                {
                    sm_pSvcListTail = pSvc;
                }

                sm_pSvcListHead = pSvc;

                sm_cServices++;

                /* Reference the service (for first time) until it is unloaded on HGCM termination. */
                AssertRelease (pSvc->m_u32RefCnt == 0);
                pSvc->ReferenceService ();

                LogFlowFunc(("service %p\n", pSvc));
            }
        }
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/** The method unloads a service.
 *
 * @thread main HGCM
 */
void HGCMService::UnloadService (void)
{
    LogFlowFunc(("name = %s\n", m_pszSvcName));

    /* Remove the service from the list. */
    if (m_pSvcNext)
    {
        m_pSvcNext->m_pSvcPrev = m_pSvcPrev;
    }
    else
    {
        sm_pSvcListTail = m_pSvcPrev;
    }

    if (m_pSvcPrev)
    {
        m_pSvcPrev->m_pSvcNext = m_pSvcNext;
    }
    else
    {
        sm_pSvcListHead = m_pSvcNext;
    }

    sm_cServices--;

    /* The service must be unloaded only if all clients were disconnected. */
    LogFlowFunc(("m_u32RefCnt = %d\n", m_u32RefCnt));
    AssertRelease (m_u32RefCnt == 1);

    /* Now the service can be released. */
    ReleaseService ();
}

/** The method unloads all services.
 *
 * @thread main HGCM
 */
/* static */ void HGCMService::UnloadAll (void)
{
    while (sm_pSvcListHead)
    {
        sm_pSvcListHead->UnloadService ();
    }
}

/** The method obtains a referenced pointer to the service with
 *  specified name. The caller must call ReleaseService when
 *  the pointer is no longer needed.
 *
 * @param ppSvc          Where to store the pointer to the service.
 * @param pszServiceName The name of the service.
 * @return VBox rc.
 * @thread main HGCM
 */
/* static */ int HGCMService::ResolveService (HGCMService **ppSvc, const char *pszServiceName)
{
    LogFlowFunc(("ppSvc = %p name = %s\n",
                 ppSvc, pszServiceName));

    if (!ppSvc || !pszServiceName)
    {
        return VERR_INVALID_PARAMETER;
    }

    HGCMService *pSvc = sm_pSvcListHead;

    while (pSvc)
    {
        if (strcmp (pSvc->m_pszSvcName, pszServiceName) == 0)
        {
            break;
        }

        pSvc = pSvc->m_pSvcNext;
    }

    LogFlowFunc(("lookup in the list is %p\n", pSvc));

    if (pSvc == NULL)
    {
        *ppSvc = NULL;
        return VERR_HGCM_SERVICE_NOT_FOUND;
    }

    pSvc->ReferenceService ();

    *ppSvc = pSvc;

    return VINF_SUCCESS;
}

/** The method increases reference counter.
 *
 * @thread main HGCM
 */
void HGCMService::ReferenceService (void)
{
    ASMAtomicIncU32 (&m_u32RefCnt);
    LogFlowFunc(("[%s] m_u32RefCnt = %d\n", m_pszSvcName, m_u32RefCnt));
}

/** The method dereferences a service and deletes it when no more refs.
 *
 * @thread main HGCM
 */
void HGCMService::ReleaseService (void)
{
    LogFlowFunc(("m_u32RefCnt = %d\n", m_u32RefCnt));
    uint32_t u32RefCnt = ASMAtomicDecU32 (&m_u32RefCnt);
    AssertRelease(u32RefCnt != ~0U);

    LogFlowFunc(("u32RefCnt = %d, name %s\n", u32RefCnt, m_pszSvcName));

    if (u32RefCnt == 0)
    {
        instanceDestroy ();
        delete this;
    }
}

/** The method is called when the VM is being reset or terminated
 *  and disconnects all clients from all services.
 *
 * @thread main HGCM
 */
/* static */ void HGCMService::Reset (void)
{
    g_fResetting = true;

    HGCMService *pSvc = sm_pSvcListHead;

    while (pSvc)
    {
        while (pSvc->m_cClients && pSvc->m_paClientIds)
        {
            LogFlowFunc(("handle %d\n", pSvc->m_paClientIds[0]));
            pSvc->DisconnectClient (pSvc->m_paClientIds[0], false);
        }

#ifdef VBOX_WITH_CRHGSMI
        /* @todo: could this actually happen that the service is destroyed on ReleaseService? */
        HGCMService *pNextSvc = pSvc->m_pSvcNext;
        while (pSvc->m_cHandleAcquires)
        {
            pSvc->HandleReleased ();
            pSvc->ReleaseService ();
        }
        pSvc = pNextSvc;
#else
        pSvc = pSvc->m_pSvcNext;
#endif
    }

    g_fResetting = false;
}

/** The method saves the HGCM state.
 *
 * @param pSSM  The saved state context.
 * @return VBox rc.
 * @thread main HGCM
 */
/* static */ int HGCMService::SaveState (PSSMHANDLE pSSM)
{
    /* Save the current handle count and restore afterwards to avoid client id conflicts. */
    int rc = SSMR3PutU32(pSSM, hgcmObjQueryHandleCount());
    AssertRCReturn(rc, rc);

    LogFlowFunc(("%d services to be saved:\n", sm_cServices));

    /* Save number of services. */
    rc = SSMR3PutU32(pSSM, sm_cServices);
    AssertRCReturn(rc, rc);

    /* Save every service. */
    HGCMService *pSvc = sm_pSvcListHead;

    while (pSvc)
    {
        LogFlowFunc(("Saving service [%s]\n", pSvc->m_pszSvcName));

        /* Save the length of the service name. */
        rc = SSMR3PutU32(pSSM, (uint32_t) strlen(pSvc->m_pszSvcName) + 1);
        AssertRCReturn(rc, rc);

        /* Save the name of the service. */
        rc = SSMR3PutStrZ(pSSM, pSvc->m_pszSvcName);
        AssertRCReturn(rc, rc);

        /* Save the number of clients. */
        rc = SSMR3PutU32(pSSM, pSvc->m_cClients);
        AssertRCReturn(rc, rc);

        /* Call the service for every client. Normally a service must not have
         * a global state to be saved: only per client info is relevant.
         * The global state of a service is configured during VM startup.
         */
        int i;

        for (i = 0; i < pSvc->m_cClients; i++)
        {
            uint32_t u32ClientId = pSvc->m_paClientIds[i];

            Log(("client id 0x%08X\n", u32ClientId));

            /* Save the client id. */
            rc = SSMR3PutU32(pSSM, u32ClientId);
            AssertRCReturn(rc, rc);

            /* Call the service, so the operation is executed by the service thread. */
            rc = pSvc->saveClientState (u32ClientId, pSSM);
            AssertRCReturn(rc, rc);
        }

        pSvc = pSvc->m_pSvcNext;
    }

    return VINF_SUCCESS;
}

/** The method loads saved HGCM state.
 *
 * @param pSSM  The saved state context.
 * @return VBox rc.
 * @thread main HGCM
 */
/* static */ int HGCMService::LoadState (PSSMHANDLE pSSM)
{
    /* Restore handle count to avoid client id conflicts. */
    uint32_t u32;

    int rc = SSMR3GetU32(pSSM, &u32);
    AssertRCReturn(rc, rc);

    hgcmObjSetHandleCount(u32);

    /* Get the number of services. */
    uint32_t cServices;

    rc = SSMR3GetU32(pSSM, &cServices);
    AssertRCReturn(rc, rc);

    LogFlowFunc(("%d services to be restored:\n", cServices));

    while (cServices--)
    {
        /* Get the length of the service name. */
        rc = SSMR3GetU32(pSSM, &u32);
        AssertRCReturn(rc, rc);
        AssertReturn(u32 <= VBOX_HGCM_SVC_NAME_MAX_BYTES, VERR_SSM_UNEXPECTED_DATA);

        char *pszServiceName = (char *)alloca (u32);

        /* Get the service name. */
        rc = SSMR3GetStrZ(pSSM, pszServiceName, u32);
        AssertRCReturn(rc, rc);

        LogRel(("HGCM: restoring [%s]\n", pszServiceName));

        /* Resolve the service instance. */
        HGCMService *pSvc;
        rc = ResolveService (&pSvc, pszServiceName);
        AssertLogRelMsgReturn(pSvc, ("rc=%Rrc, %s\n", rc, pszServiceName), VERR_SSM_UNEXPECTED_DATA);

        /* Get the number of clients. */
        uint32_t cClients;
        rc = SSMR3GetU32(pSSM, &cClients);
        if (RT_FAILURE(rc))
        {
            pSvc->ReleaseService ();
            AssertFailed();
            return rc;
        }

        while (cClients--)
        {
            /* Get the client id. */
            uint32_t u32ClientId;
            rc = SSMR3GetU32(pSSM, &u32ClientId);
            if (RT_FAILURE(rc))
            {
                pSvc->ReleaseService ();
                AssertFailed();
                return rc;
            }

            /* Connect the client. */
            rc = pSvc->CreateAndConnectClient (NULL, u32ClientId);
            if (RT_FAILURE(rc))
            {
                pSvc->ReleaseService ();
                AssertLogRelMsgFailed(("rc=%Rrc %s\n", rc, pszServiceName));
                return rc;
            }

            /* Call the service, so the operation is executed by the service thread. */
            rc = pSvc->loadClientState (u32ClientId, pSSM);
            if (RT_FAILURE(rc))
            {
                pSvc->ReleaseService ();
                AssertLogRelMsgFailed(("rc=%Rrc %s\n", rc, pszServiceName));
                return rc;
            }
        }

        pSvc->ReleaseService ();
    }

    return VINF_SUCCESS;
}

/* Create a new client instance and connect it to the service.
 *
 * @param pu32ClientIdOut If not NULL, then the method must generate a new handle for the client.
 *                        If NULL, use the given 'u32ClientIdIn' handle.
 * @param u32ClientIdIn   The handle for the client, when 'pu32ClientIdOut' is NULL.
 * @return VBox rc.
 */
int HGCMService::CreateAndConnectClient (uint32_t *pu32ClientIdOut, uint32_t u32ClientIdIn)
{
    LogFlowFunc(("pu32ClientIdOut = %p, u32ClientIdIn = %d\n", pu32ClientIdOut, u32ClientIdIn));

    /* Allocate a client information structure. */
    HGCMClient *pClient = new HGCMClient ();

    if (!pClient)
    {
        LogWarningFunc(("Could not allocate HGCMClient!!!\n"));
        return VERR_NO_MEMORY;
    }

    uint32_t handle;

    if (pu32ClientIdOut != NULL)
    {
        handle = hgcmObjGenerateHandle (pClient);
    }
    else
    {
        handle = hgcmObjAssignHandle (pClient, u32ClientIdIn);
    }

    LogFlowFunc(("client id = %d\n", handle));

    AssertRelease(handle);

    /* Initialize the HGCM part of the client. */
    int rc = pClient->Init (this);

    if (RT_SUCCESS(rc))
    {
        /* Call the service. */
        HGCMMSGHANDLE hMsg;

        rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_CONNECT, hgcmMessageAllocSvc);

        if (RT_SUCCESS(rc))
        {
            HGCMMsgSvcConnect *pMsg = (HGCMMsgSvcConnect *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
            AssertRelease(pMsg);

            pMsg->u32ClientId = handle;

            hgcmObjDereference (pMsg);

            rc = hgcmMsgSend (hMsg);

            if (RT_SUCCESS(rc))
            {
                /* Add the client Id to the array. */
                if (m_cClients == m_cClientsAllocated)
                {
                    m_paClientIds = (uint32_t *)RTMemRealloc (m_paClientIds, (m_cClientsAllocated + 64) * sizeof (m_paClientIds[0]));
                    Assert(m_paClientIds);
                    m_cClientsAllocated += 64;
                }

                m_paClientIds[m_cClients] = handle;
                m_cClients++;
            }
        }
    }

    if (RT_FAILURE(rc))
    {
        hgcmObjDeleteHandle (handle);
    }
    else
    {
        if (pu32ClientIdOut != NULL)
        {
            *pu32ClientIdOut = handle;
        }

        ReferenceService ();
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* Disconnect the client from the service and delete the client handle.
 *
 * @param u32ClientId  The handle of the client.
 * @return VBox rc.
 */
int HGCMService::DisconnectClient (uint32_t u32ClientId, bool fFromService)
{
    int rc = VINF_SUCCESS;

    LogFlowFunc(("client id = %d, fFromService = %d\n", u32ClientId, fFromService));

    if (!fFromService)
    {
        /* Call the service. */
        HGCMMSGHANDLE hMsg;

        rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_DISCONNECT, hgcmMessageAllocSvc);

        if (RT_SUCCESS(rc))
        {
            HGCMMsgSvcDisconnect *pMsg = (HGCMMsgSvcDisconnect *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
            AssertRelease(pMsg);

            pMsg->u32ClientId = u32ClientId;

            hgcmObjDereference (pMsg);

            rc = hgcmMsgSend (hMsg);
        }
        else
        {
            LogRel(("(%d, %d) [%s] hgcmMsgAlloc(%p, SVC_MSG_DISCONNECT) failed %Rrc\n",
                    u32ClientId, fFromService, RT_VALID_PTR(m_pszSvcName)? m_pszSvcName: "", m_thread, rc));
        }
    }

    /* Remove the client id from the array in any case, rc does not matter. */
    int i;

    for (i = 0; i < m_cClients; i++)
    {
        if (m_paClientIds[i] == u32ClientId)
        {
            m_cClients--;

            if (m_cClients > i)
            {
                memmove (&m_paClientIds[i], &m_paClientIds[i + 1], sizeof (m_paClientIds[0]) * (m_cClients - i));
            }

            /* Delete the client handle. */
            hgcmObjDeleteHandle (u32ClientId);

            /* The service must be released. */
            ReleaseService ();

            break;
        }
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

int HGCMService::RegisterExtension (HGCMSVCEXTHANDLE handle,
                                    PFNHGCMSVCEXT pfnExtension,
                                    void *pvExtension)
{
    LogFlowFunc(("%s\n", handle->pszServiceName));

    /* Forward the message to the service thread. */
    HGCMMSGHANDLE hMsg = 0;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_REGEXT, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgSvcRegisterExtension *pMsg = (HGCMMsgSvcRegisterExtension *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->handle       = handle;
        pMsg->pfnExtension = pfnExtension;
        pMsg->pvExtension  = pvExtension;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

void HGCMService::UnregisterExtension (HGCMSVCEXTHANDLE handle)
{
    /* Forward the message to the service thread. */
    HGCMMSGHANDLE hMsg = 0;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_UNREGEXT, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgSvcUnregisterExtension *pMsg = (HGCMMsgSvcUnregisterExtension *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->handle = handle;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
}

/* Perform a guest call to the service.
 *
 * @param pHGCMPort      The port to be used for completion confirmation.
 * @param pCmd           The VBox HGCM context.
 * @param u32ClientId    The client handle to be disconnected and deleted.
 * @param u32Function    The function number.
 * @param cParms         Number of parameters.
 * @param paParms        Pointer to array of parameters.
 * @return VBox rc.
 */
int HGCMService::GuestCall (PPDMIHGCMPORT pHGCMPort, PVBOXHGCMCMD pCmd, uint32_t u32ClientId, uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
    HGCMMSGHANDLE hMsg = 0;

    LogFlow(("MAIN::HGCMService::Call\n"));

    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_GUESTCALL, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgCall *pMsg = (HGCMMsgCall *)hgcmObjReference (hMsg, HGCMOBJ_MSG);

        AssertRelease(pMsg);

        pMsg->pCmd      = pCmd;
        pMsg->pHGCMPort = pHGCMPort;

        pMsg->u32ClientId = u32ClientId;
        pMsg->u32Function = u32Function;
        pMsg->cParms      = cParms;
        pMsg->paParms     = paParms;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgPost (hMsg, hgcmMsgCompletionCallback);
    }
    else
    {
        Log(("MAIN::HGCMService::Call: Message allocation failed: %Rrc\n", rc));
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* Perform a host call the service.
 *
 * @param u32Function    The function number.
 * @param cParms         Number of parameters.
 * @param paParms        Pointer to array of parameters.
 * @return VBox rc.
 */
int HGCMService::HostCall (uint32_t u32Function, uint32_t cParms, VBOXHGCMSVCPARM *paParms)
{
    LogFlowFunc(("%s u32Function = %d, cParms = %d, paParms = %p\n",
                 m_pszSvcName, u32Function, cParms, paParms));

    HGCMMSGHANDLE hMsg = 0;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_HOSTCALL, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgHostCallSvc *pMsg = (HGCMMsgHostCallSvc *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->u32Function      = u32Function;
        pMsg->cParms           = cParms;
        pMsg->paParms          = paParms;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

#ifdef VBOX_WITH_CRHGSMI
static DECLCALLBACK(void) hgcmMsgFastCallCompletionCallback (int32_t result, HGCMMsgCore *pMsgCore)
{
    /* Call the VMMDev port interface to issue IRQ notification. */
    LogFlow(("MAIN::hgcmMsgFastCallCompletionCallback: message %p\n", pMsgCore));

    HGCMMsgHostFastCallAsyncSvc *pMsg = (HGCMMsgHostFastCallAsyncSvc *)pMsgCore;
    if (pMsg->pfnCompletion)
    {
        pMsg->pfnCompletion (result, pMsg->u32Function, &pMsg->Param, pMsg->pvCompletion);
    }
}

int HGCMService::HandleAcquired()
{
    ++m_cHandleAcquires;
    return VINF_SUCCESS;
}

int HGCMService::HandleReleased()
{
    Assert(m_cHandleAcquires);
    if (m_cHandleAcquires)
    {
        --m_cHandleAcquires;
        return VINF_SUCCESS;
    }
    return VERR_INVALID_STATE;
}

int HGCMService::HostFastCallAsync (uint32_t u32Function, VBOXHGCMSVCPARM *pParm, PHGCMHOSTFASTCALLCB pfnCompletion, void *pvCompletion)
{
    LogFlowFunc(("%s u32Function = %d, pParm = %p\n",
                 m_pszSvcName, u32Function, pParm));

    HGCMMSGHANDLE hMsg = 0;
    int rc = hgcmMsgAlloc (m_thread, &hMsg, SVC_MSG_HOSTFASTCALLASYNC, hgcmMessageAllocSvc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgHostFastCallAsyncSvc *pMsg = (HGCMMsgHostFastCallAsyncSvc *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->u32Function      = u32Function;
        pMsg->Param = *pParm;
        pMsg->pfnCompletion = pfnCompletion;
        pMsg->pvCompletion = pvCompletion;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgPost(hMsg, hgcmMsgFastCallCompletionCallback);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}
#endif

/*
 * Main HGCM thread that manages services.
 */

/* Messages processed by the main HGCM thread. */
#define HGCM_MSG_CONNECT    (10)  /* Connect a client to a service. */
#define HGCM_MSG_DISCONNECT (11)  /* Disconnect the specified client id. */
#define HGCM_MSG_LOAD       (12)  /* Load the service. */
#define HGCM_MSG_HOSTCALL   (13)  /* Call the service. */
#define HGCM_MSG_LOADSTATE  (14)  /* Load saved state for the specified service. */
#define HGCM_MSG_SAVESTATE  (15)  /* Save state for the specified service. */
#define HGCM_MSG_RESET      (16)  /* Disconnect all clients from the specified service. */
#define HGCM_MSG_QUIT       (17)  /* Unload all services and terminate the thread. */
#define HGCM_MSG_REGEXT     (18)  /* Register a service extension. */
#define HGCM_MSG_UNREGEXT   (19)  /* Unregister a service extension. */
#ifdef VBOX_WITH_CRHGSMI
# define HGCM_MSG_SVCAQUIRE  (30)  /* Acquire a service handle (for fast host calls) */
# define HGCM_MSG_SVCRELEASE (31)  /* Release a service */
#endif

class HGCMMsgMainConnect: public HGCMMsgHeader
{
    public:
        /* Service name. */
        const char *pszServiceName;
        /* Where to store the client handle. */
        uint32_t *pu32ClientId;
};

class HGCMMsgMainDisconnect: public HGCMMsgHeader
{
    public:
        /* Handle of the client to be disconnected. */
        uint32_t u32ClientId;
};

class HGCMMsgMainLoad: public HGCMMsgCore
{
    public:
        /* Name of the library to be loaded. */
        const char *pszServiceLibrary;
        /* Name to be assigned to the service. */
        const char *pszServiceName;
};

class HGCMMsgMainHostCall: public HGCMMsgCore
{
    public:
        /* Which service to call. */
        const char *pszServiceName;
        /* Function number. */
        uint32_t u32Function;
        /* Number of the function parameters. */
        uint32_t cParms;
        /* Pointer to array of the function parameters. */
        VBOXHGCMSVCPARM *paParms;
};

class HGCMMsgMainLoadSaveState: public HGCMMsgCore
{
    public:
        /* SSM context. */
        PSSMHANDLE pSSM;
};

class HGCMMsgMainReset: public HGCMMsgCore
{
};

class HGCMMsgMainQuit: public HGCMMsgCore
{
};

class HGCMMsgMainRegisterExtension: public HGCMMsgCore
{
    public:
        /* Returned handle to be used in HGCMMsgMainUnregisterExtension. */
        HGCMSVCEXTHANDLE *pHandle;
        /* Name of the service. */
        const char *pszServiceName;
        /* The extension entry point. */
        PFNHGCMSVCEXT pfnExtension;
        /* The extension pointer. */
        void *pvExtension;
};

class HGCMMsgMainUnregisterExtension: public HGCMMsgCore
{
    public:
        /* Handle of the registered extension. */
        HGCMSVCEXTHANDLE handle;
};

#ifdef VBOX_WITH_CRHGSMI
class HGCMMsgMainSvcAcquire: public HGCMMsgCore
{
    public:
        /* Which service to call. */
        const char *pszServiceName;
        /* Returned service. */
        HGCMService *pService;
};

class HGCMMsgMainSvcRelease: public HGCMMsgCore
{
    public:
        /* Svc . */
        HGCMService *pService;
};
#endif


static HGCMMsgCore *hgcmMainMessageAlloc (uint32_t u32MsgId)
{
    switch (u32MsgId)
    {
        case HGCM_MSG_CONNECT:    return new HGCMMsgMainConnect ();
        case HGCM_MSG_DISCONNECT: return new HGCMMsgMainDisconnect ();
        case HGCM_MSG_LOAD:       return new HGCMMsgMainLoad ();
        case HGCM_MSG_HOSTCALL:   return new HGCMMsgMainHostCall ();
        case HGCM_MSG_LOADSTATE:
        case HGCM_MSG_SAVESTATE:  return new HGCMMsgMainLoadSaveState ();
        case HGCM_MSG_RESET:      return new HGCMMsgMainReset ();
        case HGCM_MSG_QUIT:       return new HGCMMsgMainQuit ();
        case HGCM_MSG_REGEXT:     return new HGCMMsgMainRegisterExtension ();
        case HGCM_MSG_UNREGEXT:   return new HGCMMsgMainUnregisterExtension ();
#ifdef VBOX_WITH_CRHGSMI
        case HGCM_MSG_SVCAQUIRE: return new HGCMMsgMainSvcAcquire();
        case HGCM_MSG_SVCRELEASE: return new HGCMMsgMainSvcRelease();
#endif

        default:
            AssertReleaseMsgFailed(("Msg id = %08X\n", u32MsgId));
    }

    return NULL;
}


/* The main HGCM thread handler. */
static DECLCALLBACK(void) hgcmThread (HGCMTHREADHANDLE ThreadHandle, void *pvUser)
{
    LogFlowFunc(("ThreadHandle = %p, pvUser = %p\n",
                 ThreadHandle, pvUser));

    NOREF(pvUser);

    bool fQuit = false;

    while (!fQuit)
    {
        HGCMMsgCore *pMsgCore;
        int rc = hgcmMsgGet (ThreadHandle, &pMsgCore);

        if (RT_FAILURE(rc))
        {
            /* The error means some serious unrecoverable problem in the hgcmMsg/hgcmThread layer. */
            AssertMsgFailed (("%Rrc\n", rc));
            break;
        }

        uint32_t u32MsgId = pMsgCore->MsgId ();

        switch (u32MsgId)
        {
            case HGCM_MSG_CONNECT:
            {
                HGCMMsgMainConnect *pMsg = (HGCMMsgMainConnect *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_CONNECT pszServiceName %s, pu32ClientId %p\n",
                             pMsg->pszServiceName, pMsg->pu32ClientId));

                /* Resolve the service name to the pointer to service instance.
                 */
                HGCMService *pService;
                rc = HGCMService::ResolveService (&pService, pMsg->pszServiceName);

                if (RT_SUCCESS(rc))
                {
                    /* Call the service instance method. */
                    rc = pService->CreateAndConnectClient (pMsg->pu32ClientId, 0);

                    /* Release the service after resolve. */
                    pService->ReleaseService ();
                }
            } break;

            case HGCM_MSG_DISCONNECT:
            {
                HGCMMsgMainDisconnect *pMsg = (HGCMMsgMainDisconnect *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_DISCONNECT u32ClientId = %d\n",
                             pMsg->u32ClientId));

                HGCMClient *pClient = (HGCMClient *)hgcmObjReference (pMsg->u32ClientId, HGCMOBJ_CLIENT);

                if (!pClient)
                {
                    rc = VERR_HGCM_INVALID_CLIENT_ID;
                    break;
                }

                /* The service the client belongs to. */
                HGCMService *pService = pClient->pService;

                /* Call the service instance to disconnect the client. */
                rc = pService->DisconnectClient (pMsg->u32ClientId, false);

                hgcmObjDereference (pClient);
            } break;

            case HGCM_MSG_LOAD:
            {
                HGCMMsgMainLoad *pMsg = (HGCMMsgMainLoad *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_LOAD pszServiceName = %s, pMsg->pszServiceLibrary = %s\n",
                             pMsg->pszServiceName, pMsg->pszServiceLibrary));

                rc = HGCMService::LoadService (pMsg->pszServiceLibrary, pMsg->pszServiceName);
            } break;

            case HGCM_MSG_HOSTCALL:
            {
                HGCMMsgMainHostCall *pMsg = (HGCMMsgMainHostCall *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_HOSTCALL pszServiceName %s, u32Function %d, cParms %d, paParms %p\n",
                             pMsg->pszServiceName, pMsg->u32Function, pMsg->cParms, pMsg->paParms));

                /* Resolve the service name to the pointer to service instance. */
                HGCMService *pService;
                rc = HGCMService::ResolveService (&pService, pMsg->pszServiceName);

                if (RT_SUCCESS(rc))
                {
                    rc = pService->HostCall (pMsg->u32Function, pMsg->cParms, pMsg->paParms);

                    pService->ReleaseService ();
                }
            } break;

#ifdef VBOX_WITH_CRHGSMI
            case HGCM_MSG_SVCAQUIRE:
            {
                HGCMMsgMainSvcAcquire *pMsg = (HGCMMsgMainSvcAcquire *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_SVCAQUIRE pszServiceName %s\n", pMsg->pszServiceName));

                /* Resolve the service name to the pointer to service instance. */
                HGCMService *pService;
                rc = HGCMService::ResolveService (&pService, pMsg->pszServiceName);
                if (RT_SUCCESS(rc))
                {
                    rc = pService->HandleAcquired ();
                    if (RT_SUCCESS(rc))
                    {
                        pMsg->pService = pService;
                    }
                    else
                    {
                        pService->ReleaseService ();
                    }
                }
            } break;

            case HGCM_MSG_SVCRELEASE:
            {
                HGCMMsgMainSvcRelease *pMsg = (HGCMMsgMainSvcRelease *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_SVCARELEASE pService %p\n", pMsg->pService));

                /* Resolve the service name to the pointer to service instance. */

                rc = pMsg->pService->HandleReleased ();
                if (RT_SUCCESS(rc))
                {
                    pMsg->pService->ReleaseService ();
                }
            } break;
#endif

            case HGCM_MSG_RESET:
            {
                LogFlowFunc(("HGCM_MSG_RESET\n"));

                HGCMService::Reset ();
            } break;

            case HGCM_MSG_LOADSTATE:
            {
                HGCMMsgMainLoadSaveState *pMsg = (HGCMMsgMainLoadSaveState *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_LOADSTATE\n"));

                rc = HGCMService::LoadState (pMsg->pSSM);
            } break;

            case HGCM_MSG_SAVESTATE:
            {
                HGCMMsgMainLoadSaveState *pMsg = (HGCMMsgMainLoadSaveState *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_SAVESTATE\n"));

                rc = HGCMService::SaveState (pMsg->pSSM);
            } break;

            case HGCM_MSG_QUIT:
            {
                LogFlowFunc(("HGCM_MSG_QUIT\n"));

                HGCMService::UnloadAll ();

                fQuit = true;
            } break;

            case HGCM_MSG_REGEXT:
            {
                HGCMMsgMainRegisterExtension *pMsg = (HGCMMsgMainRegisterExtension *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_REGEXT\n"));

                /* Allocate the handle data. */
                HGCMSVCEXTHANDLE handle = (HGCMSVCEXTHANDLE)RTMemAllocZ (sizeof (struct _HGCMSVCEXTHANDLEDATA)
                                                                         + strlen (pMsg->pszServiceName)
                                                                         + sizeof (char));

                if (handle == NULL)
                {
                    rc = VERR_NO_MEMORY;
                }
                else
                {
                    handle->pszServiceName = (char *)((uint8_t *)handle + sizeof (struct _HGCMSVCEXTHANDLEDATA));
                    strcpy (handle->pszServiceName, pMsg->pszServiceName);

                    HGCMService *pService;
                    rc = HGCMService::ResolveService (&pService, handle->pszServiceName);

                    if (RT_SUCCESS(rc))
                    {
                        pService->RegisterExtension (handle, pMsg->pfnExtension, pMsg->pvExtension);

                        pService->ReleaseService ();
                    }

                    if (RT_FAILURE(rc))
                    {
                        RTMemFree (handle);
                    }
                    else
                    {
                        *pMsg->pHandle = handle;
                    }
                }
            } break;

            case HGCM_MSG_UNREGEXT:
            {
                HGCMMsgMainUnregisterExtension *pMsg = (HGCMMsgMainUnregisterExtension *)pMsgCore;

                LogFlowFunc(("HGCM_MSG_UNREGEXT\n"));

                HGCMService *pService;
                rc = HGCMService::ResolveService (&pService, pMsg->handle->pszServiceName);

                if (RT_SUCCESS(rc))
                {
                    pService->UnregisterExtension (pMsg->handle);

                    pService->ReleaseService ();
                }

                RTMemFree (pMsg->handle);
            } break;

            default:
            {
                AssertMsgFailed(("hgcmThread: Unsupported message number %08X!!!\n", u32MsgId));
                rc = VERR_NOT_SUPPORTED;
            } break;
        }

        /* Complete the message processing. */
        hgcmMsgComplete (pMsgCore, rc);

        LogFlowFunc(("message processed %Rrc\n", rc));
    }
}


/*
 * The HGCM API.
 */

/* The main hgcm thread. */
static HGCMTHREADHANDLE g_hgcmThread = 0;

/*
 * Public HGCM functions.
 *
 * hgcmGuest* - called as a result of the guest HGCM requests.
 * hgcmHost*  - called by the host.
 */

/* Load a HGCM service from the specified library.
 * Assign the specified name to the service.
 *
 * @param pszServiceLibrary  The library to be loaded.
 * @param pszServiceName     The name to be assigned to the service.
 * @return VBox rc.
 */
int HGCMHostLoad (const char *pszServiceLibrary,
                  const char *pszServiceName)
{
    LogFlowFunc(("lib = %s, name = %s\n", pszServiceLibrary, pszServiceName));

    if (!pszServiceLibrary || !pszServiceName)
    {
        return VERR_INVALID_PARAMETER;
    }

    /* Forward the request to the main hgcm thread. */
    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_LOAD, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        /* Initialize the message. Since the message is synchronous, use the supplied pointers. */
        HGCMMsgMainLoad *pMsg = (HGCMMsgMainLoad *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pszServiceLibrary = pszServiceLibrary;
        pMsg->pszServiceName    = pszServiceName;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* Register a HGCM service extension.
 *
 * @param pHandle            Returned handle for the registered extension.
 * @param pszServiceName     The name of the service.
 * @param pfnExtension       The extension entry point (callback).
 * @param pvExtension        The extension pointer.
 * @return VBox rc.
 */
int HGCMHostRegisterServiceExtension (HGCMSVCEXTHANDLE *pHandle,
                                      const char *pszServiceName,
                                      PFNHGCMSVCEXT pfnExtension,
                                      void *pvExtension)
{
    LogFlowFunc(("pHandle = %p, name = %s, pfn = %p, rv = %p\n", pHandle, pszServiceName, pfnExtension, pvExtension));

    if (!pHandle || !pszServiceName || !pfnExtension)
    {
        return VERR_INVALID_PARAMETER;
    }

    /* Forward the request to the main hgcm thread. */
    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_REGEXT, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        /* Initialize the message. Since the message is synchronous, use the supplied pointers. */
        HGCMMsgMainRegisterExtension *pMsg = (HGCMMsgMainRegisterExtension *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pHandle        = pHandle;
        pMsg->pszServiceName = pszServiceName;
        pMsg->pfnExtension   = pfnExtension;
        pMsg->pvExtension    = pvExtension;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("*pHandle = %p, rc = %Rrc\n", *pHandle, rc));
    return rc;
}

void HGCMHostUnregisterServiceExtension (HGCMSVCEXTHANDLE handle)
{
    LogFlowFunc(("handle = %p\n", handle));

    /* Forward the request to the main hgcm thread. */
    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_UNREGEXT, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        /* Initialize the message. */
        HGCMMsgMainUnregisterExtension *pMsg = (HGCMMsgMainUnregisterExtension *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->handle = handle;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return;
}

/* Find a service and inform it about a client connection, create a client handle.
 *
 * @param pHGCMPort      The port to be used for completion confirmation.
 * @param pCmd           The VBox HGCM context.
 * @param pszServiceName The name of the service to be connected to.
 * @param pu32ClientId   Where the store the created client handle.
 * @return VBox rc.
 */
int HGCMGuestConnect (PPDMIHGCMPORT pHGCMPort,
                      PVBOXHGCMCMD pCmd,
                      const char *pszServiceName,
                      uint32_t *pu32ClientId)
{
    LogFlowFunc(("pHGCMPort = %p, pCmd = %p, name = %s, pu32ClientId = %p\n",
                 pHGCMPort, pCmd, pszServiceName, pu32ClientId));

    if (pHGCMPort == NULL || pCmd == NULL || pszServiceName == NULL || pu32ClientId == NULL)
    {
        return VERR_INVALID_PARAMETER;
    }

    /* Forward the request to the main hgcm thread. */
    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_CONNECT, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        /* Initialize the message. Since 'pszServiceName' and 'pu32ClientId'
         * will not be deallocated by the caller until the message is completed,
         * use the supplied pointers.
         */
        HGCMMsgMainConnect *pMsg = (HGCMMsgMainConnect *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pHGCMPort      = pHGCMPort;
        pMsg->pCmd           = pCmd;
        pMsg->pszServiceName = pszServiceName;
        pMsg->pu32ClientId   = pu32ClientId;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgPost (hMsg, hgcmMsgCompletionCallback);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* Tell a service that the client is disconnecting, destroy the client handle.
 *
 * @param pHGCMPort      The port to be used for completion confirmation.
 * @param pCmd           The VBox HGCM context.
 * @param u32ClientId    The client handle to be disconnected and deleted.
 * @return VBox rc.
 */
int HGCMGuestDisconnect (PPDMIHGCMPORT pHGCMPort,
                         PVBOXHGCMCMD pCmd,
                         uint32_t u32ClientId)
{
    LogFlowFunc(("pHGCMPort = %p, pCmd = %p, u32ClientId = %d\n",
                  pHGCMPort, pCmd, u32ClientId));

    if (!pHGCMPort || !pCmd || !u32ClientId)
    {
        return VERR_INVALID_PARAMETER;
    }

    /* Forward the request to the main hgcm thread. */
    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_DISCONNECT, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        /* Initialize the message. */
        HGCMMsgMainDisconnect *pMsg = (HGCMMsgMainDisconnect *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pCmd        = pCmd;
        pMsg->pHGCMPort   = pHGCMPort;
        pMsg->u32ClientId = u32ClientId;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgPost (hMsg, hgcmMsgCompletionCallback);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* Helper to send either HGCM_MSG_SAVESTATE or HGCM_MSG_LOADSTATE messages to the main HGCM thread.
 *
 * @param pSSM     The SSM handle.
 * @param u32MsgId The message to be sent: HGCM_MSG_SAVESTATE or HGCM_MSG_LOADSTATE.
 * @return VBox rc.
 */
static int hgcmHostLoadSaveState (PSSMHANDLE pSSM,
                                  uint32_t u32MsgId)
{
    LogFlowFunc(("pSSM = %p, u32MsgId = %d\n", pSSM, u32MsgId));

    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, u32MsgId, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgMainLoadSaveState *pMsg = (HGCMMsgMainLoadSaveState *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pSSM = pSSM;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* Save the state of services.
 *
 * @param pSSM     The SSM handle.
 * @return VBox rc.
 */
int HGCMHostSaveState (PSSMHANDLE pSSM)
{
    return hgcmHostLoadSaveState (pSSM, HGCM_MSG_SAVESTATE);
}

/* Load the state of services.
 *
 * @param pSSM     The SSM handle.
 * @return VBox rc.
 */
int HGCMHostLoadState (PSSMHANDLE pSSM)
{
    return hgcmHostLoadSaveState (pSSM, HGCM_MSG_LOADSTATE);
}

/* The guest calls the service.
 *
 * @param pHGCMPort      The port to be used for completion confirmation.
 * @param pCmd           The VBox HGCM context.
 * @param u32ClientId    The client handle to be disconnected and deleted.
 * @param u32Function    The function number.
 * @param cParms         Number of parameters.
 * @param paParms        Pointer to array of parameters.
 * @return VBox rc.
 */
int HGCMGuestCall (PPDMIHGCMPORT pHGCMPort,
                   PVBOXHGCMCMD pCmd,
                   uint32_t u32ClientId,
                   uint32_t u32Function,
                   uint32_t cParms,
                   VBOXHGCMSVCPARM *paParms)
{
    LogFlowFunc(("pHGCMPort = %p, pCmd = %p, u32ClientId = %d, u32Function = %d, cParms = %d, paParms = %p\n",
                  pHGCMPort, pCmd, u32ClientId, u32Function, cParms, paParms));

    if (!pHGCMPort || !pCmd || u32ClientId == 0)
    {
        return VERR_INVALID_PARAMETER;
    }

    int rc = VERR_HGCM_INVALID_CLIENT_ID;

    /* Resolve the client handle to the client instance pointer. */
    HGCMClient *pClient = (HGCMClient *)hgcmObjReference (u32ClientId, HGCMOBJ_CLIENT);

    if (pClient)
    {
        AssertRelease(pClient->pService);

        /* Forward the message to the service thread. */
        rc = pClient->pService->GuestCall (pHGCMPort, pCmd, u32ClientId, u32Function, cParms, paParms);

        hgcmObjDereference (pClient);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

/* The host calls the service.
 *
 * @param pszServiceName The service name to be called.
 * @param u32Function    The function number.
 * @param cParms         Number of parameters.
 * @param paParms        Pointer to array of parameters.
 * @return VBox rc.
 */
int HGCMHostCall (const char *pszServiceName,
                  uint32_t u32Function,
                  uint32_t cParms,
                  VBOXHGCMSVCPARM *paParms)
{
    LogFlowFunc(("name = %s, u32Function = %d, cParms = %d, paParms = %p\n",
                 pszServiceName, u32Function, cParms, paParms));

    if (!pszServiceName)
    {
        return VERR_INVALID_PARAMETER;
    }

    HGCMMSGHANDLE hMsg = 0;

    /* Host calls go to main HGCM thread that resolves the service name to the
     * service instance pointer and then, using the service pointer, forwards
     * the message to the service thread.
     * So it is slow but host calls are intended mostly for configuration and
     * other non-time-critical functions.
     */
    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_HOSTCALL, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgMainHostCall *pMsg = (HGCMMsgMainHostCall *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pszServiceName = (char *)pszServiceName;
        pMsg->u32Function    = u32Function;
        pMsg->cParms         = cParms;
        pMsg->paParms        = paParms;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

#ifdef VBOX_WITH_CRHGSMI
int HGCMHostSvcHandleCreate (const char *pszServiceName, HGCMCVSHANDLE * phSvc)
{
    LogFlowFunc(("name = %s\n", pszServiceName));

    if (!pszServiceName)
    {
        return VERR_INVALID_PARAMETER;
    }

    if (!phSvc)
    {
        return VERR_INVALID_PARAMETER;
    }

    HGCMMSGHANDLE hMsg = 0;

    /* Host calls go to main HGCM thread that resolves the service name to the
     * service instance pointer and then, using the service pointer, forwards
     * the message to the service thread.
     * So it is slow but host calls are intended mostly for configuration and
     * other non-time-critical functions.
     */
    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_SVCAQUIRE, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgMainSvcAcquire *pMsg = (HGCMMsgMainSvcAcquire *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pszServiceName = (char *)pszServiceName;
        pMsg->pService = NULL;

        rc = hgcmMsgSend (hMsg);
        if (RT_SUCCESS(rc))
        {
            /* for simplicity just use a svc ptr as handle for now */
            *phSvc = (HGCMCVSHANDLE)pMsg->pService;
        }

        hgcmObjDereference (pMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

int HGCMHostSvcHandleDestroy (HGCMCVSHANDLE hSvc)
{
    LogFlowFunc(("hSvc = %p\n", hSvc));

    if (!hSvc)
    {
        return VERR_INVALID_PARAMETER;
    }

    HGCMMSGHANDLE hMsg = 0;

    /* Host calls go to main HGCM thread that resolves the service name to the
     * service instance pointer and then, using the service pointer, forwards
     * the message to the service thread.
     * So it is slow but host calls are intended mostly for configuration and
     * other non-time-critical functions.
     */
    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_SVCRELEASE, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        HGCMMsgMainSvcRelease *pMsg = (HGCMMsgMainSvcRelease *)hgcmObjReference (hMsg, HGCMOBJ_MSG);
        AssertRelease(pMsg);

        pMsg->pService = (HGCMService *)hSvc;

        hgcmObjDereference (pMsg);

        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

int HGCMHostFastCallAsync (HGCMCVSHANDLE hSvc, uint32_t function, VBOXHGCMSVCPARM *pParm, PHGCMHOSTFASTCALLCB pfnCompletion, void *pvCompletion)
{
    LogFlowFunc(("hSvc = %p, u32Function = %d, pParm = %p\n",
            hSvc, function, pParm));

    if (!hSvc)
    {
        return VERR_INVALID_PARAMETER;
    }

    HGCMService *pService = (HGCMService *)hSvc;
    int rc = pService->HostFastCallAsync (function, pParm, pfnCompletion, pvCompletion);

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}
#endif

int HGCMHostReset (void)
{
    LogFlowFunc(("\n"));

    /* Disconnect all clients.
     */

    HGCMMSGHANDLE hMsg = 0;

    int rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_RESET, hgcmMainMessageAlloc);

    if (RT_SUCCESS(rc))
    {
        rc = hgcmMsgSend (hMsg);
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

int HGCMHostInit (void)
{
    LogFlowFunc(("\n"));

    int rc = hgcmThreadInit ();

    if (RT_SUCCESS(rc))
    {
        /*
         * Start main HGCM thread.
         */

        rc = hgcmThreadCreate (&g_hgcmThread, "MainHGCMthread", hgcmThread, NULL);

        if (RT_FAILURE(rc))
        {
            LogRel(("Failed to start HGCM thread. HGCM services will be unavailable!!! rc = %Rrc\n", rc));
        }
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}

int HGCMHostShutdown (void)
{
    LogFlowFunc(("\n"));

    /*
     * Do HGCMReset and then unload all services.
     */

    int rc = HGCMHostReset ();

    if (RT_SUCCESS(rc))
    {
        /* Send the quit message to the main hgcmThread. */
        HGCMMSGHANDLE hMsg = 0;

        rc = hgcmMsgAlloc (g_hgcmThread, &hMsg, HGCM_MSG_QUIT, hgcmMainMessageAlloc);

        if (RT_SUCCESS(rc))
        {
            rc = hgcmMsgSend (hMsg);

            if (RT_SUCCESS(rc))
            {
                /* Wait for the thread termination. */
                hgcmThreadWait (g_hgcmThread);
                g_hgcmThread = 0;

                hgcmThreadUninit ();
            }
        }
    }

    LogFlowFunc(("rc = %Rrc\n", rc));
    return rc;
}