summaryrefslogtreecommitdiff
path: root/src/VBox/Main/ConsoleImpl2.cpp
blob: be9b14867223ce7472ef6b1bb05ac3803f85925e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
/* $Id: ConsoleImpl2.cpp $ */
/** @file
 * VBox Console COM Class implementation
 *
 * @remark  We've split out the code that the 64-bit VC++ v8 compiler finds
 *          problematic to optimize so we can disable optimizations and later,
 *          perhaps, find a real solution for it (like rewriting the code and
 *          to stop resemble a tonne of spaghetti).
 */

/*
 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
 *
 * 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.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 USA or visit http://www.sun.com if you need
 * additional information or have any questions.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include "ConsoleImpl.h"
#include "DisplayImpl.h"
#include "VMMDev.h"

// generated header
#include "SchemaDefs.h"

#include "Logging.h"

#include <iprt/buildconfig.h>
#include <iprt/string.h>
#include <iprt/path.h>
#include <iprt/dir.h>
#include <iprt/param.h>
#if 0 /* enable to play with lots of memory. */
# include <iprt/env.h>
#endif
#include <iprt/file.h>

#include <VBox/vmapi.h>
#include <VBox/err.h>
#include <VBox/version.h>
#include <VBox/HostServices/VBoxClipboardSvc.h>
#ifdef VBOX_WITH_CROGL
#include <VBox/HostServices/VBoxCrOpenGLSvc.h>
#endif
#ifdef VBOX_WITH_GUEST_PROPS
# include <VBox/HostServices/GuestPropertySvc.h>
# include <VBox/com/defs.h>
# include <VBox/com/array.h>
# include <hgcm/HGCM.h> /** @todo it should be possible to register a service
                          * extension using a VMMDev callback. */
# include <vector>
#endif /* VBOX_WITH_GUEST_PROPS */
#include <VBox/intnet.h>

#include <VBox/com/com.h>
#include <VBox/com/string.h>
#include <VBox/com/array.h>

#if defined(RT_OS_SOLARIS) && defined(VBOX_WITH_NETFLT)
# include <zone.h>
#endif

#if defined(RT_OS_LINUX) && defined(VBOX_WITH_NETFLT)
# include <unistd.h>
# include <sys/ioctl.h>
# include <sys/socket.h>
# include <linux/types.h>
# include <linux/if.h>
# include <linux/wireless.h>
#endif

#if defined(RT_OS_FREEBSD) && defined(VBOX_WITH_NETFLT)
# include <unistd.h>
# include <sys/types.h>
# include <sys/ioctl.h>
# include <sys/socket.h>
# include <net/if.h>
#endif

#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
# include <VBox/WinNetConfig.h>
# include <Ntddndis.h>
# include <devguid.h>
#endif

#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
# include <HostNetworkInterfaceImpl.h>
# include <netif.h>
#endif

#include "DHCPServerRunner.h"

#include <VBox/param.h>

/* Comment out the following line to remove VMWare compatibility hack. */
#define VMWARE_NET_IN_SLOT_11

/**
 * Translate IDE StorageControllerType_T to string representation.
 */
const char* controllerString(StorageControllerType_T enmType)
{
    switch (enmType)
    {
        case StorageControllerType_PIIX3:
            return "PIIX3";
        case StorageControllerType_PIIX4:
            return "PIIX4";
        case StorageControllerType_ICH6:
            return "ICH6";
        default:
            return "Unknown";
    }
}

/*
 * VC++ 8 / amd64 has some serious trouble with this function.
 * As a temporary measure, we'll drop global optimizations.
 */
#if defined(_MSC_VER) && defined(RT_ARCH_AMD64)
# pragma optimize("g", off)
#endif

static int findEfiRom(IVirtualBox* vbox, FirmwareType_T aFirmwareType, Utf8Str& aEfiRomFile)
{
    int rc;
    BOOL fPresent = FALSE;
    Bstr aFilePath, empty;

    rc = vbox->CheckFirmwarePresent(aFirmwareType, empty,
                                    empty.asOutParam(), aFilePath.asOutParam(), &fPresent);
    if (RT_FAILURE(rc))
        AssertComRCReturn (rc, VERR_FILE_NOT_FOUND);

    if (!fPresent)
        return VERR_FILE_NOT_FOUND;

    aEfiRomFile = Utf8Str(aFilePath);

    return S_OK;
}

/**
 *  Construct the VM configuration tree (CFGM).
 *
 *  This is a callback for VMR3Create() call. It is called from CFGMR3Init()
 *  in the emulation thread (EMT). Any per thread COM/XPCOM initialization
 *  is done here.
 *
 *  @param   pVM                 VM handle.
 *  @param   pvConsole           Pointer to the VMPowerUpTask object.
 *  @return  VBox status code.
 *
 *  @note Locks the Console object for writing.
 */
DECLCALLBACK(int) Console::configConstructor(PVM pVM, void *pvConsole)
{
    LogFlowFuncEnter();
    /* Note: hardcoded assumption about number of slots; see rom bios */
    bool afPciDeviceNo[32] = {false};
    bool fFdcEnabled = false;
    BOOL fIs64BitGuest = false;

#if !defined (VBOX_WITH_XPCOM)
    {
        /* initialize COM */
        HRESULT hrc = CoInitializeEx(NULL,
                                     COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE |
                                     COINIT_SPEED_OVER_MEMORY);
        LogFlow (("Console::configConstructor(): CoInitializeEx()=%08X\n", hrc));
        AssertComRCReturn (hrc, VERR_GENERAL_FAILURE);
    }
#endif

    AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
    ComObjPtr<Console> pConsole = static_cast <Console *> (pvConsole);

    AutoCaller autoCaller(pConsole);
    AssertComRCReturn (autoCaller.rc(), VERR_ACCESS_DENIED);

    /* lock the console because we widely use internal fields and methods */
    AutoWriteLock alock(pConsole);

    /* Save the VM pointer in the machine object */
    pConsole->mpVM = pVM;

    ComPtr<IMachine> pMachine = pConsole->machine();

    int             rc;
    HRESULT         hrc;
    BSTR            str = NULL;

#define STR_FREE()  do { if (str) { SysFreeString(str); str = NULL; } } while (0)
#define RC_CHECK()  do { if (RT_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc));  STR_FREE(); return rc;                   } } while (0)
#define H()         do { if (FAILED(hrc))    { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)

    /*
     * Get necessary objects and frequently used parameters.
     */
    ComPtr<IVirtualBox> virtualBox;
    hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam());                     H();

    ComPtr<IHost> host;
    hrc = virtualBox->COMGETTER(Host)(host.asOutParam());                           H();

    ComPtr<ISystemProperties> systemProperties;
    hrc = virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());   H();

    ComPtr<IBIOSSettings> biosSettings;
    hrc = pMachine->COMGETTER(BIOSSettings)(biosSettings.asOutParam());             H();

    hrc = pMachine->COMGETTER(HardwareUUID)(&str);                                  H();
    RTUUID HardwareUuid;
    rc = RTUuidFromUtf16(&HardwareUuid, str);                                       RC_CHECK();
    STR_FREE();

    ULONG cRamMBs;
    hrc = pMachine->COMGETTER(MemorySize)(&cRamMBs);                                H();
#if 0 /* enable to play with lots of memory. */
    if (RTEnvExist("VBOX_RAM_SIZE"))
        cRamMBs = RTStrToUInt64(RTEnvGet("VBOX_RAM_SIZE"));
#endif
    uint64_t const cbRam = cRamMBs * (uint64_t)_1M;
    uint32_t const cbRamHole = MM_RAM_HOLE_SIZE_DEFAULT;

    ULONG cCpus = 1;
    hrc = pMachine->COMGETTER(CPUCount)(&cCpus);                                    H();

    Bstr osTypeId;
    hrc = pMachine->COMGETTER(OSTypeId)(osTypeId.asOutParam());                     H();

    BOOL fIOAPIC;
    hrc = biosSettings->COMGETTER(IOAPICEnabled)(&fIOAPIC);                          H();

    /*
     * Get root node first.
     * This is the only node in the tree.
     */
    PCFGMNODE pRoot = CFGMR3GetRoot(pVM);
    Assert(pRoot);

    /*
     * Set the root (and VMM) level values.
     */
    hrc = pMachine->COMGETTER(Name)(&str);                                          H();
    rc = CFGMR3InsertStringW(pRoot, "Name",                 str);                   RC_CHECK();
    rc = CFGMR3InsertBytes(pRoot,   "UUID", &HardwareUuid, sizeof(HardwareUuid));   RC_CHECK();
    rc = CFGMR3InsertInteger(pRoot, "RamSize",              cbRam);                 RC_CHECK();
    rc = CFGMR3InsertInteger(pRoot, "RamHoleSize",          cbRamHole);             RC_CHECK();
    rc = CFGMR3InsertInteger(pRoot, "NumCPUs",              cCpus);                 RC_CHECK();
    rc = CFGMR3InsertInteger(pRoot, "TimerMillies",         10);                    RC_CHECK();
#ifdef VBOX_WITH_RAW_MODE
    rc = CFGMR3InsertInteger(pRoot, "RawR3Enabled",         1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertInteger(pRoot, "RawR0Enabled",         1);     /* boolean */   RC_CHECK();
    /** @todo Config: RawR0, PATMEnabled and CSAMEnabled needs attention later. */
    rc = CFGMR3InsertInteger(pRoot, "PATMEnabled",          1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertInteger(pRoot, "CSAMEnabled",          1);     /* boolean */   RC_CHECK();
#endif

    /* cpuid leaf overrides. */
    static uint32_t const s_auCpuIdRanges[] =
    {
        UINT32_C(0x00000000), UINT32_C(0x0000000a),
        UINT32_C(0x80000000), UINT32_C(0x8000000a)
    };
    for (unsigned i = 0; i < RT_ELEMENTS(s_auCpuIdRanges); i += 2)
        for (uint32_t uLeaf = s_auCpuIdRanges[i]; uLeaf < s_auCpuIdRanges[i + 1]; uLeaf++)
        {
            ULONG ulEax, ulEbx, ulEcx, ulEdx;
            hrc = pMachine->GetCpuIdLeaf(uLeaf, &ulEax, &ulEbx, &ulEcx, &ulEdx);
            if (SUCCEEDED(hrc))
            {
                PCFGMNODE pLeaf;
                rc = CFGMR3InsertNodeF(pRoot, &pLeaf, "CPUM/HostCPUID/%RX32", uLeaf);   RC_CHECK();

                rc = CFGMR3InsertInteger(pLeaf, "eax", ulEax);                          RC_CHECK();
                rc = CFGMR3InsertInteger(pLeaf, "ebx", ulEbx);                          RC_CHECK();
                rc = CFGMR3InsertInteger(pLeaf, "ecx", ulEcx);                          RC_CHECK();
                rc = CFGMR3InsertInteger(pLeaf, "edx", ulEdx);                          RC_CHECK();
            }
            else if (hrc != E_INVALIDARG)                                               H();
        }

    if (osTypeId == "WindowsNT4")
    {
        /*
         * We must limit CPUID count for Windows NT 4, as otherwise it stops
         * with error 0x3e (MULTIPROCESSOR_CONFIGURATION_NOT_SUPPORTED).
         */
        LogRel(("Limiting CPUID leaf count for NT4 guests\n"));
        PCFGMNODE pCPUM;
        rc = CFGMR3InsertNode(pRoot, "CPUM", &pCPUM);                               RC_CHECK();
        rc = CFGMR3InsertInteger(pCPUM, "NT4LeafLimit", true);                      RC_CHECK();
    }

    /* hardware virtualization extensions */
    BOOL fHWVirtExEnabled;
    BOOL fHwVirtExtForced;
#ifdef VBOX_WITH_RAW_MODE
    hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Enabled, &fHWVirtExEnabled); H();
    if (cCpus > 1) /** @todo SMP: This isn't nice, but things won't work on mac otherwise. */
        fHWVirtExEnabled = TRUE;
# ifdef RT_OS_DARWIN
    fHwVirtExtForced = fHWVirtExEnabled;
# else
    /* - With more than 4GB PGM will use different RAMRANGE sizes for raw
         mode and hv mode to optimize lookup times.
       - With more than one virtual CPU, raw-mode isn't a fallback option. */
    fHwVirtExtForced = fHWVirtExEnabled
                    && (   cbRam > (_4G - cbRamHole)
                        || cCpus > 1);
# endif
#else  /* !VBOX_WITH_RAW_MODE */
    fHWVirtExEnabled = fHwVirtExtForced = TRUE;
#endif /* !VBOX_WITH_RAW_MODE */
    rc = CFGMR3InsertInteger(pRoot, "HwVirtExtForced",      fHwVirtExtForced);      RC_CHECK();

    PCFGMNODE pHWVirtExt;
    rc = CFGMR3InsertNode(pRoot, "HWVirtExt", &pHWVirtExt);                         RC_CHECK();
    if (fHWVirtExEnabled)
    {
        rc = CFGMR3InsertInteger(pHWVirtExt, "Enabled",     1);                     RC_CHECK();

        /* Indicate whether 64-bit guests are supported or not. */
        /** @todo This is currently only forced off on 32-bit hosts only because it
         *        makes a lof of difference there (REM and Solaris performance).
         */

        ComPtr<IGuestOSType> guestOSType;
        hrc = virtualBox->GetGuestOSType(osTypeId, guestOSType.asOutParam());       H();

        BOOL fSupportsLongMode = false;
        hrc = host->GetProcessorFeature(ProcessorFeature_LongMode,
                                        &fSupportsLongMode);                        H();
        hrc = guestOSType->COMGETTER(Is64Bit)(&fIs64BitGuest);                      H();

        if (fSupportsLongMode && fIs64BitGuest)
        {
            rc = CFGMR3InsertInteger(pHWVirtExt, "64bitEnabled", 1);                RC_CHECK();
#if ARCH_BITS == 32 /* The recompiler must use VBoxREM64 (32-bit host only). */
            PCFGMNODE pREM;
            rc = CFGMR3InsertNode(pRoot, "REM", &pREM);                             RC_CHECK();
            rc = CFGMR3InsertInteger(pREM, "64bitEnabled", 1);                      RC_CHECK();
#endif
        }
#if ARCH_BITS == 32 /* 32-bit guests only. */
        else
        {
            rc = CFGMR3InsertInteger(pHWVirtExt, "64bitEnabled", 0);                RC_CHECK();
        }
#endif

        /** @todo Not exactly pretty to check strings; VBOXOSTYPE would be better, but that requires quite a bit of API change in Main. */
        if (    !fIs64BitGuest
            &&  fIOAPIC
            &&  (   osTypeId == "WindowsNT4"
                 || osTypeId == "Windows2000"
                 || osTypeId == "WindowsXP"
                 || osTypeId == "Windows2003"))
        {
            /* Only allow TPR patching for NT, Win2k, XP and Windows Server 2003. (32 bits mode)
             * We may want to consider adding more guest OSes (Solaris) later on.
             */
            rc = CFGMR3InsertInteger(pHWVirtExt, "TPRPatchingEnabled", 1);          RC_CHECK();
        }
    }

    /* HWVirtEx exclusive mode */
    BOOL fHWVirtExExclusive = true;
    hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_Exclusive, &fHWVirtExExclusive);  H();
    rc = CFGMR3InsertInteger(pHWVirtExt, "Exclusive", fHWVirtExExclusive);                     RC_CHECK();

    /* Nested paging (VT-x/AMD-V) */
    BOOL fEnableNestedPaging = false;
    hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_NestedPaging, &fEnableNestedPaging);   H();
    rc = CFGMR3InsertInteger(pHWVirtExt, "EnableNestedPaging", fEnableNestedPaging);     RC_CHECK();

    /* VPID (VT-x) */
    BOOL fEnableVPID = false;
    hrc = pMachine->GetHWVirtExProperty(HWVirtExPropertyType_VPID, &fEnableVPID);        H();
    rc = CFGMR3InsertInteger(pHWVirtExt, "EnableVPID", fEnableVPID);                     RC_CHECK();

    /* Physical Address Extension (PAE) */
    BOOL fEnablePAE = false;
    hrc = pMachine->GetCpuProperty(CpuPropertyType_PAE, &fEnablePAE);               H();
    rc = CFGMR3InsertInteger(pRoot, "EnablePAE", fEnablePAE);                       RC_CHECK();

    /* Synthetic CPU */
    BOOL fSyntheticCpu = false;
    hrc = pMachine->GetCpuProperty(CpuPropertyType_Synthetic, &fSyntheticCpu);      H();
    rc = CFGMR3InsertInteger(pRoot, "SyntheticCpu", fSyntheticCpu);                 RC_CHECK();

    BOOL fPXEDebug;
    hrc = biosSettings->COMGETTER(PXEDebugEnabled)(&fPXEDebug);                      H();

    /*
     * PDM config.
     *  Load drivers in VBoxC.[so|dll]
     */
    PCFGMNODE pPDM;
    PCFGMNODE pDrivers;
    PCFGMNODE pMod;
    rc = CFGMR3InsertNode(pRoot,    "PDM", &pPDM);                                     RC_CHECK();
    rc = CFGMR3InsertNode(pPDM,     "Drivers", &pDrivers);                             RC_CHECK();
    rc = CFGMR3InsertNode(pDrivers, "VBoxC", &pMod);                                   RC_CHECK();
#ifdef VBOX_WITH_XPCOM
    // VBoxC is located in the components subdirectory
    char szPathVBoxC[RTPATH_MAX];
    rc = RTPathAppPrivateArch(szPathVBoxC, RTPATH_MAX - sizeof("/components/VBoxC")); AssertRC(rc);
    strcat(szPathVBoxC, "/components/VBoxC");
    rc = CFGMR3InsertString(pMod,   "Path",  szPathVBoxC);                             RC_CHECK();
#else
    rc = CFGMR3InsertString(pMod,   "Path",  "VBoxC");                                 RC_CHECK();
#endif

    /*
     * Devices
     */
    PCFGMNODE pDevices = NULL;      /* /Devices */
    PCFGMNODE pDev = NULL;          /* /Devices/Dev/ */
    PCFGMNODE pInst = NULL;         /* /Devices/Dev/0/ */
    PCFGMNODE pCfg = NULL;          /* /Devices/Dev/.../Config/ */
    PCFGMNODE pLunL0 = NULL;        /* /Devices/Dev/0/LUN#0/ */
    PCFGMNODE pLunL1 = NULL;        /* /Devices/Dev/0/LUN#0/AttachedDriver/ */
    PCFGMNODE pLunL2 = NULL;        /* /Devices/Dev/0/LUN#0/AttachedDriver/Config/ */
    PCFGMNODE pBiosCfg = NULL;      /* /Devices/pcbios/0/Config/ */

    rc = CFGMR3InsertNode(pRoot, "Devices", &pDevices);                             RC_CHECK();

    /*
     * PC Arch.
     */
    rc = CFGMR3InsertNode(pDevices, "pcarch", &pDev);                               RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();

    /*
     * The time offset
     */
    LONG64 timeOffset;
    hrc = biosSettings->COMGETTER(TimeOffset)(&timeOffset);                         H();
    PCFGMNODE pTMNode;
    rc = CFGMR3InsertNode(pRoot, "TM", &pTMNode);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pTMNode, "UTCOffset", timeOffset * 1000000);           RC_CHECK();

    /*
     * DMA
     */
    rc = CFGMR3InsertNode(pDevices, "8237A", &pDev);                                RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted", 1);                  /* boolean */   RC_CHECK();

    /*
     * PCI buses.
     */
    rc = CFGMR3InsertNode(pDevices, "pci", &pDev); /* piix3 */                      RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "IOAPIC", fIOAPIC);                             RC_CHECK();

#if 0 /* enable this to test PCI bridging */
    rc = CFGMR3InsertNode(pDevices, "pcibridge", &pDev);                            RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",         14);                     RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                     RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIBusNo",             0);/* -> pci[0] */      RC_CHECK();

    rc = CFGMR3InsertNode(pDev,     "1", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          1);                     RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                     RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIBusNo",             1);/* ->pcibridge[0] */ RC_CHECK();

    rc = CFGMR3InsertNode(pDev,     "2", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          3);                     RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                     RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIBusNo",             1);/* ->pcibridge[0] */ RC_CHECK();
#endif

    /*
     * Temporary hack for enabling the next three devices and various ACPI features.
     */
    Bstr tmpStr2;
    hrc = pMachine->GetExtraData(Bstr("VBoxInternal2/SupportExtHwProfile"), tmpStr2.asOutParam()); H();
    BOOL fExtProfile = tmpStr2 == Bstr("on");

    /*
     * High Precision Event Timer (HPET)
     */
    BOOL fHpetEnabled;
#ifdef VBOX_WITH_HPET
    fHpetEnabled = fExtProfile;
#else
    fHpetEnabled = false;
#endif
    if (fHpetEnabled)
    {
        rc = CFGMR3InsertNode(pDevices, "hpet", &pDev);                      RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                        RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted",   1);     /* boolean */   RC_CHECK();
    }

    /*
     * System Management Controller (SMC)
     */
    BOOL fSmcEnabled;
#ifdef VBOX_WITH_SMC
    fSmcEnabled = fExtProfile;
#else
    fSmcEnabled = false;
#endif
    if (fSmcEnabled)
    {
        rc = CFGMR3InsertNode(pDevices, "smc", &pDev);                       RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                        RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted",   1);     /* boolean */   RC_CHECK();
    }

    /*
     * Low Pin Count (LPC) bus
     */
    BOOL fLpcEnabled;
    /** @todo: implement appropriate getter */
#ifdef VBOX_WITH_LPC
    fLpcEnabled = fExtProfile;
#else
    fLpcEnabled = false;
#endif
    if (fLpcEnabled)
    {
        rc = CFGMR3InsertNode(pDevices, "lpc", &pDev);                       RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                        RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted",   1);     /* boolean */   RC_CHECK();
    }

    /*
     * PS/2 keyboard & mouse.
     */
    rc = CFGMR3InsertNode(pDevices, "pckbd", &pDev);                                RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();

    rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                              RC_CHECK();
    rc = CFGMR3InsertString(pLunL0, "Driver",               "KeyboardQueue");       RC_CHECK();
    rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "QueueSize",            64);                    RC_CHECK();

    rc = CFGMR3InsertNode(pLunL0,   "AttachedDriver", &pLunL1);                     RC_CHECK();
    rc = CFGMR3InsertString(pLunL1, "Driver",               "MainKeyboard");        RC_CHECK();
    rc = CFGMR3InsertNode(pLunL1,   "Config", &pCfg);                               RC_CHECK();
    Keyboard *pKeyboard = pConsole->mKeyboard;
    rc = CFGMR3InsertInteger(pCfg,  "Object",     (uintptr_t)pKeyboard);            RC_CHECK();

    rc = CFGMR3InsertNode(pInst,    "LUN#1", &pLunL0);                              RC_CHECK();
    rc = CFGMR3InsertString(pLunL0, "Driver",               "MouseQueue");          RC_CHECK();
    rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "QueueSize",            128);                   RC_CHECK();

    rc = CFGMR3InsertNode(pLunL0,   "AttachedDriver", &pLunL1);                     RC_CHECK();
    rc = CFGMR3InsertString(pLunL1, "Driver",               "MainMouse");           RC_CHECK();
    rc = CFGMR3InsertNode(pLunL1,   "Config", &pCfg);                               RC_CHECK();
    Mouse *pMouse = pConsole->mMouse;
    rc = CFGMR3InsertInteger(pCfg,  "Object",     (uintptr_t)pMouse);               RC_CHECK();

    /*
     * i8254 Programmable Interval Timer And Dummy Speaker
     */
    rc = CFGMR3InsertNode(pDevices, "i8254", &pDev);                                RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
#ifdef DEBUG
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
#endif

    /*
     * i8259 Programmable Interrupt Controller.
     */
    rc = CFGMR3InsertNode(pDevices, "i8259", &pDev);                                RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();

    /*
     * Advanced Programmable Interrupt Controller.
     * SMP: Each CPU has a LAPIC, but we have a single device representing all LAPICs states,
     *      thus only single insert
     */
    rc = CFGMR3InsertNode(pDevices, "apic", &pDev);                                 RC_CHECK();
    rc = CFGMR3InsertNode(pDev, "0", &pInst);                                       RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "IOAPIC", fIOAPIC);                             RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "NumCPUs", cCpus);                              RC_CHECK();

    if (fIOAPIC)
    {
        /*
         * I/O Advanced Programmable Interrupt Controller.
         */
        rc = CFGMR3InsertNode(pDevices, "ioapic", &pDev);                           RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                               RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted",          1);     /* boolean */   RC_CHECK();
        rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                           RC_CHECK();
    }

    /*
     * RTC MC146818.
     */
    rc = CFGMR3InsertNode(pDevices, "mc146818", &pDev);                             RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();

    /*
     * VGA.
     */
    rc = CFGMR3InsertNode(pDevices, "vga", &pDev);                                  RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          2);                     RC_CHECK();
    Assert(!afPciDeviceNo[2]);
    afPciDeviceNo[2] = true;
    rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                     RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    ULONG cVRamMBs;
    hrc = pMachine->COMGETTER(VRAMSize)(&cVRamMBs);                                 H();
    rc = CFGMR3InsertInteger(pCfg,  "VRamSize",             cVRamMBs * _1M);        RC_CHECK();
    ULONG cMonitorCount;
    hrc = pMachine->COMGETTER(MonitorCount)(&cMonitorCount);                        H();
    rc = CFGMR3InsertInteger(pCfg,  "MonitorCount",         cMonitorCount);         RC_CHECK();
#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE /* not safe here yet. */ /** @todo this needs fixing !!! No wonder VGA is slooooooooow on 32-bit darwin! */
    rc = CFGMR3InsertInteger(pCfg,  "R0Enabled",            fHWVirtExEnabled);      RC_CHECK();
#endif

    /*
     * BIOS logo
     */
    BOOL fFadeIn;
    hrc = biosSettings->COMGETTER(LogoFadeIn)(&fFadeIn);                            H();
    rc = CFGMR3InsertInteger(pCfg,  "FadeIn",  fFadeIn ? 1 : 0);                    RC_CHECK();
    BOOL fFadeOut;
    hrc = biosSettings->COMGETTER(LogoFadeOut)(&fFadeOut);                          H();
    rc = CFGMR3InsertInteger(pCfg,  "FadeOut", fFadeOut ? 1: 0);                    RC_CHECK();
    ULONG logoDisplayTime;
    hrc = biosSettings->COMGETTER(LogoDisplayTime)(&logoDisplayTime);               H();
    rc = CFGMR3InsertInteger(pCfg,  "LogoTime", logoDisplayTime);                   RC_CHECK();
    Bstr logoImagePath;
    hrc = biosSettings->COMGETTER(LogoImagePath)(logoImagePath.asOutParam());       H();
    rc = CFGMR3InsertString(pCfg,   "LogoFile", logoImagePath ? Utf8Str(logoImagePath).c_str() : ""); RC_CHECK();

    /*
     * Boot menu
     */
    BIOSBootMenuMode_T eBootMenuMode;
    int iShowBootMenu;
    biosSettings->COMGETTER(BootMenuMode)(&eBootMenuMode);
    switch (eBootMenuMode)
    {
        case BIOSBootMenuMode_Disabled: iShowBootMenu = 0;  break;
        case BIOSBootMenuMode_MenuOnly: iShowBootMenu = 1;  break;
        default:                        iShowBootMenu = 2;  break;
    }
    rc = CFGMR3InsertInteger(pCfg, "ShowBootMenu", iShowBootMenu);                  RC_CHECK();

    /* Custom VESA mode list */
    unsigned cModes = 0;
    for (unsigned iMode = 1; iMode <= 16; ++iMode)
    {
        char szExtraDataKey[sizeof("CustomVideoModeXX")];
        RTStrPrintf(szExtraDataKey, sizeof(szExtraDataKey), "CustomVideoMode%u", iMode);
        hrc = pMachine->GetExtraData(Bstr(szExtraDataKey), &str);                   H();
        if (!str || !*str)
            break;
        rc = CFGMR3InsertStringW(pCfg, szExtraDataKey, str);                        RC_CHECK();
        STR_FREE();
        ++cModes;
    }
    STR_FREE();
    rc = CFGMR3InsertInteger(pCfg,  "CustomVideoModes", cModes);

    /* VESA height reduction */
    ULONG ulHeightReduction;
    IFramebuffer *pFramebuffer = pConsole->getDisplay()->getFramebuffer();
    if (pFramebuffer)
    {
        hrc = pFramebuffer->COMGETTER(HeightReduction)(&ulHeightReduction);         H();
    }
    else
    {
        /* If framebuffer is not available, there is no height reduction. */
        ulHeightReduction = 0;
    }
    rc = CFGMR3InsertInteger(pCfg,  "HeightReduction", ulHeightReduction);          RC_CHECK();

    /* Attach the display. */
    rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                              RC_CHECK();
    rc = CFGMR3InsertString(pLunL0, "Driver",               "MainDisplay");         RC_CHECK();
    rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
    Display *pDisplay = pConsole->mDisplay;
    rc = CFGMR3InsertInteger(pCfg,  "Object", (uintptr_t)pDisplay);                 RC_CHECK();


    /*
     * Firmware.
     */
    FirmwareType_T eFwType =  FirmwareType_BIOS;
    hrc = pMachine->COMGETTER(FirmwareType)(&eFwType);                                H();

#ifdef VBOX_WITH_EFI
    BOOL fEfiEnabled = (eFwType >= FirmwareType_EFI) && (eFwType <= FirmwareType_EFIDUAL);
#else
    BOOL fEfiEnabled = false;
#endif
    if (!fEfiEnabled)
    {
        /*
         * PC Bios.
         */
        rc = CFGMR3InsertNode(pDevices, "pcbios", &pDev);                               RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
        rc = CFGMR3InsertNode(pInst,    "Config", &pBiosCfg);                           RC_CHECK();
        rc = CFGMR3InsertInteger(pBiosCfg,  "RamSize",              cbRam);             RC_CHECK();
        rc = CFGMR3InsertInteger(pBiosCfg,  "RamHoleSize",          cbRamHole);         RC_CHECK();
        rc = CFGMR3InsertInteger(pBiosCfg,  "NumCPUs",              cCpus);             RC_CHECK();
        rc = CFGMR3InsertString(pBiosCfg,   "HardDiskDevice",       "piix3ide");        RC_CHECK();
        rc = CFGMR3InsertString(pBiosCfg,   "FloppyDevice",         "i82078");          RC_CHECK();
        rc = CFGMR3InsertInteger(pBiosCfg,  "IOAPIC",               fIOAPIC);           RC_CHECK();
        rc = CFGMR3InsertInteger(pBiosCfg,  "PXEDebug",             fPXEDebug);         RC_CHECK();
        rc = CFGMR3InsertBytes(pBiosCfg,    "UUID", &HardwareUuid,sizeof(HardwareUuid));RC_CHECK();

        DeviceType_T bootDevice;
        if (SchemaDefs::MaxBootPosition > 9)
        {
            AssertMsgFailed (("Too many boot devices %d\n",
                              SchemaDefs::MaxBootPosition));
            return VERR_INVALID_PARAMETER;
        }

        for (ULONG pos = 1; pos <= SchemaDefs::MaxBootPosition; ++pos)
        {
            hrc = pMachine->GetBootOrder(pos, &bootDevice);                             H();

            char szParamName[] = "BootDeviceX";
            szParamName[sizeof (szParamName) - 2] = ((char (pos - 1)) + '0');

            const char *pszBootDevice;
            switch (bootDevice)
            {
                case DeviceType_Null:
                    pszBootDevice = "NONE";
                    break;
                case DeviceType_HardDisk:
                    pszBootDevice = "IDE";
                    break;
                case DeviceType_DVD:
                    pszBootDevice = "DVD";
                    break;
                case DeviceType_Floppy:
                    pszBootDevice = "FLOPPY";
                    break;
                case DeviceType_Network:
                    pszBootDevice = "LAN";
                    break;
                default:
                    AssertMsgFailed(("Invalid bootDevice=%d\n", bootDevice));
                    return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
                                      N_("Invalid boot device '%d'"), bootDevice);
            }
            rc = CFGMR3InsertString(pBiosCfg, szParamName, pszBootDevice);              RC_CHECK();
        }
    }
    else
    {
        Utf8Str efiRomFile;

        /* Autodetect firmware type, basing on guest type */
        if (eFwType == FirmwareType_EFI)
        {
            eFwType =
                    fIs64BitGuest ?
                    (FirmwareType_T)FirmwareType_EFI64
                    :
                    (FirmwareType_T)FirmwareType_EFI32;
        }

        rc = findEfiRom(virtualBox, eFwType, efiRomFile);                                                                                                                          RC_CHECK();
        bool f64BitEntry = eFwType == FirmwareType_EFI64;
        /*
         * EFI.
         */
        rc = CFGMR3InsertNode(pDevices, "efi", &pDev);                              RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                               RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted", 1);              /* boolean */   RC_CHECK();
        rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                           RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "RamSize",          cbRam);                 RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "RamHoleSize",      cbRamHole);             RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "NumCPUs",          cCpus);                 RC_CHECK();
        rc = CFGMR3InsertString(pCfg,   "EfiRom",           efiRomFile.raw());      RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "IOAPIC",               fIOAPIC);           RC_CHECK();
        rc = CFGMR3InsertBytes(pCfg,    "UUID", &HardwareUuid,sizeof(HardwareUuid));RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "64BitEntry", f64BitEntry); /* boolean */   RC_CHECK();
    }

    /*
     * Storage controllers.
     */
    com::SafeIfaceArray<IStorageController> ctrls;
    PCFGMNODE aCtrlNodes[StorageControllerType_I82078 + 1] = {};
    hrc = pMachine->COMGETTER(StorageControllers)(ComSafeArrayAsOutParam(ctrls));               H();

    for (size_t i = 0; i < ctrls.size(); ++ i)
    {
        DeviceType_T *paLedDevType = NULL;

        StorageControllerType_T enmCtrlType;
        rc = ctrls[i]->COMGETTER(ControllerType)(&enmCtrlType);                                 H();
        AssertRelease((unsigned)enmCtrlType < RT_ELEMENTS(aCtrlNodes));

        StorageBus_T enmBus;
        rc = ctrls[i]->COMGETTER(Bus)(&enmBus);                                                 H();

        Bstr controllerName;
        rc = ctrls[i]->COMGETTER(Name)(controllerName.asOutParam());                            H();

        ULONG ulInstance = 999;
        rc = ctrls[i]->COMGETTER(Instance)(&ulInstance);                                        H();

        /* /Devices/<ctrldev>/ */
        const char *pszCtrlDev = pConsole->convertControllerTypeToDev(enmCtrlType);
        pDev = aCtrlNodes[enmCtrlType];
        if (!pDev)
        {
            rc = CFGMR3InsertNode(pDevices, pszCtrlDev, &pDev);                                 RC_CHECK();
            aCtrlNodes[enmCtrlType] = pDev; /* IDE variants are handled in the switch */
        }

        /* /Devices/<ctrldev>/<instance>/ */
        PCFGMNODE pCtlInst = NULL;
        rc = CFGMR3InsertNodeF(pDev, &pCtlInst, "%u", ulInstance);                              RC_CHECK();

        /* Device config: /Devices/<ctrldev>/<instance>/<values> & /ditto/Config/<values> */
        rc = CFGMR3InsertInteger(pCtlInst, "Trusted",   1);                                     RC_CHECK();
        rc = CFGMR3InsertNode(pCtlInst,    "Config",    &pCfg);                                 RC_CHECK();

        switch (enmCtrlType)
        {
            case StorageControllerType_LsiLogic:
            {
                rc = CFGMR3InsertInteger(pCtlInst, "PCIDeviceNo",          20);                 RC_CHECK();
                Assert(!afPciDeviceNo[20]);
                afPciDeviceNo[20] = true;
                rc = CFGMR3InsertInteger(pCtlInst, "PCIFunctionNo",        0);                  RC_CHECK();

                /* Attach the status driver */
                rc = CFGMR3InsertNode(pCtlInst, "LUN#999", &pLunL0);                            RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");          RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapStorageLeds[iLedScsi]); RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "First",    0);                                 RC_CHECK();
                Assert(cLedScsi >= 16);
                rc = CFGMR3InsertInteger(pCfg,  "Last",     15);                                RC_CHECK();
                paLedDevType = &pConsole->maStorageDevType[iLedScsi];
                break;
            }

            case StorageControllerType_BusLogic:
            {
                rc = CFGMR3InsertInteger(pCtlInst, "PCIDeviceNo",          21);                 RC_CHECK();
                Assert(!afPciDeviceNo[21]);
                afPciDeviceNo[21] = true;
                rc = CFGMR3InsertInteger(pCtlInst, "PCIFunctionNo",        0);                  RC_CHECK();

                /* Attach the status driver */
                rc = CFGMR3InsertNode(pCtlInst, "LUN#999", &pLunL0);                            RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");          RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapStorageLeds[iLedScsi]); RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "First",    0);                                 RC_CHECK();
                Assert(cLedScsi >= 16);
                rc = CFGMR3InsertInteger(pCfg,  "Last",     15);                                RC_CHECK();
                paLedDevType = &pConsole->maStorageDevType[iLedScsi];
                break;
            }

            case StorageControllerType_IntelAhci:
            {
                rc = CFGMR3InsertInteger(pCtlInst, "PCIDeviceNo",          13);                 RC_CHECK();
                Assert(!afPciDeviceNo[13]);
                afPciDeviceNo[13] = true;
                rc = CFGMR3InsertInteger(pCtlInst, "PCIFunctionNo",        0);                  RC_CHECK();

                ULONG cPorts = 0;
                hrc = ctrls[i]->COMGETTER(PortCount)(&cPorts);                                  H();
                rc = CFGMR3InsertInteger(pCfg, "PortCount", cPorts);                            RC_CHECK();

                /* Needed configuration values for the bios. */
                if (pBiosCfg)
                {
                    rc = CFGMR3InsertString(pBiosCfg, "SataHardDiskDevice", "ahci");            RC_CHECK();
                }

                for (uint32_t j = 0; j < 4; ++j)
                {
                    static const char * const s_apszConfig[4] =
                    { "PrimaryMaster", "PrimarySlave", "SecondaryMaster", "SecondarySlave" };
                    static const char * const s_apszBiosConfig[4] =
                    { "SataPrimaryMasterLUN", "SataPrimarySlaveLUN", "SataSecondaryMasterLUN", "SataSecondarySlaveLUN" };

                    LONG lPortNumber = -1;
                    hrc = ctrls[i]->GetIDEEmulationPort(j, &lPortNumber);                       H();
                    rc = CFGMR3InsertInteger(pCfg, s_apszConfig[j], lPortNumber);               RC_CHECK();
                    if (pBiosCfg)
                    {
                        rc = CFGMR3InsertInteger(pBiosCfg, s_apszBiosConfig[j], lPortNumber);   RC_CHECK();
                    }
                }

                /* Attach the status driver */
                rc = CFGMR3InsertNode(pCtlInst, "LUN#999", &pLunL0);                            RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");          RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
                AssertRelease(cPorts <= cLedSata);
                rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapStorageLeds[iLedSata]); RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "First",    0);                                 RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "Last",     cPorts - 1);                        RC_CHECK();
                paLedDevType = &pConsole->maStorageDevType[iLedSata];
                break;
            }

            case StorageControllerType_PIIX3:
            case StorageControllerType_PIIX4:
            case StorageControllerType_ICH6:
            {
                /*
                 * IDE (update this when the main interface changes)
                 */
                rc = CFGMR3InsertInteger(pCtlInst, "PCIDeviceNo",          1);                  RC_CHECK();
                Assert(!afPciDeviceNo[1]);
                afPciDeviceNo[1] = true;
                rc = CFGMR3InsertInteger(pCtlInst, "PCIFunctionNo",        1);                  RC_CHECK();
                rc = CFGMR3InsertString(pCfg,  "Type", controllerString(enmCtrlType));          RC_CHECK();

                /* Attach the status driver */
                rc = CFGMR3InsertNode(pCtlInst,    "LUN#999", &pLunL0);                         RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");          RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapStorageLeds[iLedIde]); RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "First",    0);                                 RC_CHECK();
                Assert(cLedIde >= 4);
                rc = CFGMR3InsertInteger(pCfg,  "Last",     3);                                 RC_CHECK();
                paLedDevType = &pConsole->maStorageDevType[iLedIde];

                /* IDE flavors */
                aCtrlNodes[StorageControllerType_PIIX3] = pDev;
                aCtrlNodes[StorageControllerType_PIIX4] = pDev;
                aCtrlNodes[StorageControllerType_ICH6]  = pDev;
                break;
            }

            case StorageControllerType_I82078:
            {
                /*
                 * i82078 Floppy drive controller
                 */
                fFdcEnabled = true;
                rc = CFGMR3InsertInteger(pCfg,  "IRQ",       6);                                RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "DMA",       2);                                RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "MemMapped", 0 );                               RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "IOBase",    0x3f0);                            RC_CHECK();

                /* Attach the status driver */
                rc = CFGMR3InsertNode(pCtlInst, "LUN#999", &pLunL0);                            RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");          RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapStorageLeds[iLedFloppy]); RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "First",    0);                                 RC_CHECK();
                Assert(cLedFloppy >= 1);
                rc = CFGMR3InsertInteger(pCfg,  "Last",     0);                                 RC_CHECK();
                paLedDevType = &pConsole->maStorageDevType[iLedFloppy];
                break;
            }

            default:
                AssertMsgFailedReturn(("invalid storage controller type: %d\n", enmCtrlType), VERR_GENERAL_FAILURE);
        }

        /* Attach the media to the storage controllers. */
        com::SafeIfaceArray<IMediumAttachment> atts;
        hrc = pMachine->GetMediumAttachmentsOfController(controllerName,
                                                         ComSafeArrayAsOutParam(atts));         H();

        for (size_t j = 0; j < atts.size(); ++j)
        {
            ComPtr<IMedium> medium;
            hrc = atts [j]->COMGETTER(Medium)(medium.asOutParam());                             H();
            LONG lDev;
            hrc = atts[j]->COMGETTER(Device)(&lDev);                                            H();
            LONG lPort;
            hrc = atts[j]->COMGETTER(Port)(&lPort);                                             H();
            DeviceType_T lType;
            hrc = atts[j]->COMGETTER(Type)(&lType);                                             H();

            unsigned uLUN;
            hrc = pConsole->convertBusPortDeviceToLun(enmBus, lPort, lDev, uLUN);               H();
            rc = CFGMR3InsertNodeF(pCtlInst, &pLunL0, "LUN#%u", uLUN);                          RC_CHECK();

            /* SCSI has a another driver between device and block. */
            if (enmBus == StorageBus_SCSI)
            {
                rc = CFGMR3InsertString(pLunL0, "Driver", "SCSI");                              RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                                 RC_CHECK();

                rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0);                       RC_CHECK();
            }

            BOOL fHostDrive = FALSE;
            if (!medium.isNull())
            {
                hrc = medium->COMGETTER(HostDrive)(&fHostDrive);                                H();
            }

            if (fHostDrive)
            {
                Assert(!medium.isNull());
                if (lType == DeviceType_DVD)
                {
                    rc = CFGMR3InsertString(pLunL0, "Driver", "HostDVD");                       RC_CHECK();
                    rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                             RC_CHECK();

                    hrc = medium->COMGETTER(Location)(&str);                                    H();
                    rc = CFGMR3InsertStringW(pCfg, "Path", str);                                RC_CHECK();
                    STR_FREE();

                    BOOL fPassthrough;
                    hrc = atts[j]->COMGETTER(Passthrough)(&fPassthrough);                       H();
                    rc = CFGMR3InsertInteger(pCfg, "Passthrough", !!fPassthrough);              RC_CHECK();
                }
                else if (lType == DeviceType_Floppy)
                {
                    rc = CFGMR3InsertString(pLunL0, "Driver", "HostFloppy");                    RC_CHECK();
                    rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                             RC_CHECK();

                    hrc = medium->COMGETTER(Location)(&str);                                    H();
                    rc = CFGMR3InsertStringW(pCfg, "Path", str);                                RC_CHECK();
                    STR_FREE();
                }
            }
            else
            {
                rc = CFGMR3InsertString(pLunL0, "Driver", "Block");                             RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                                 RC_CHECK();
                switch (lType)
                {
                    case DeviceType_DVD:
                        rc = CFGMR3InsertString(pCfg, "Type", "DVD");                           RC_CHECK();
                        rc = CFGMR3InsertInteger(pCfg, "Mountable", 1);                         RC_CHECK();
                        break;
                    case DeviceType_Floppy:
                        rc = CFGMR3InsertString(pCfg, "Type", "Floppy 1.44");                   RC_CHECK();
                        rc = CFGMR3InsertInteger(pCfg, "Mountable", 1);                         RC_CHECK();
                        break;
                    case DeviceType_HardDisk:
                    default:
                        rc = CFGMR3InsertString(pCfg, "Type", "HardDisk");                      RC_CHECK();
                        rc = CFGMR3InsertInteger(pCfg, "Mountable", 0);                         RC_CHECK();
                }

                if (!medium.isNull())
                {
                    rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL1);                   RC_CHECK();
                    rc = CFGMR3InsertString(pLunL1, "Driver", "VD");                            RC_CHECK();
                    rc = CFGMR3InsertNode(pLunL1, "Config", &pCfg);                             RC_CHECK();

                    hrc = medium->COMGETTER(Location)(&str);                                    H();
                    rc = CFGMR3InsertStringW(pCfg, "Path", str);                                RC_CHECK();
                    STR_FREE();

                    hrc = medium->COMGETTER(Format)(&str);                                      H();
                    rc = CFGMR3InsertStringW(pCfg, "Format", str);                              RC_CHECK();
                    STR_FREE();

                    /* DVDs are always readonly */
                    if (lType == DeviceType_DVD)
                    {
                        rc = CFGMR3InsertInteger(pCfg, "ReadOnly", 1);                          RC_CHECK();
                    }
                    /* Start without exclusive write access to the images. */
                    /** @todo Live Migration: I don't quite like this, we risk screwing up when
                     *        we're resuming the VM if some 3rd dude have any of the VDIs open
                     *        with write sharing denied.  However, if the two VMs are sharing a
                     *        image it really is necessary....
                     *
                     *        So, on the "lock-media" command, the target teleporter should also
                     *        make DrvVD undo TempReadOnly.  It gets interesting if we fail after
                     *        that. Grumble. */
                    else if (pConsole->mMachineState == MachineState_TeleportingIn)
                    {
                        rc = CFGMR3InsertInteger(pCfg, "TempReadOnly", 1);                      RC_CHECK();
                    }

                    /* Pass all custom parameters. */
                    bool fHostIP = true;
                    SafeArray<BSTR> names;
                    SafeArray<BSTR> values;
                    hrc = medium->GetProperties(NULL,
                                                ComSafeArrayAsOutParam(names),
                                                ComSafeArrayAsOutParam(values));                H();

                    if (names.size() != 0)
                    {
                        PCFGMNODE pVDC;
                        rc = CFGMR3InsertNode(pCfg, "VDConfig", &pVDC);                         RC_CHECK();
                        for (size_t ii = 0; ii < names.size(); ++ii)
                        {
                            if (values[ii] && *values[ii])
                            {
                                Utf8Str name = names[ii];
                                Utf8Str value = values[ii];
                                rc = CFGMR3InsertString(pVDC, name.c_str(), value.c_str());     RC_CHECK();
                                if (    name.compare("HostIPStack") == 0
                                    &&  value.compare("0") == 0)
                                    fHostIP = false;
                            }
                        }
                    }

                    /* Create an inversed tree of parents. */
                    ComPtr<IMedium> parentMedium = medium;
                    for (PCFGMNODE pParent = pCfg;;)
                    {
                        hrc = parentMedium->COMGETTER(Parent)(medium.asOutParam());             H();
                        if (medium.isNull())
                            break;

                        PCFGMNODE pCur;
                        rc = CFGMR3InsertNode(pParent, "Parent", &pCur);                        RC_CHECK();
                        hrc = medium->COMGETTER(Location)(&str);                                H();
                        rc = CFGMR3InsertStringW(pCur, "Path", str);                            RC_CHECK();
                        STR_FREE();

                        hrc = medium->COMGETTER(Format)(&str);                                  H();
                        rc = CFGMR3InsertStringW(pCur, "Format", str);                          RC_CHECK();
                        STR_FREE();

                        /* Pass all custom parameters. */
                        SafeArray<BSTR> aNames;
                        SafeArray<BSTR> aValues;
                        hrc = medium->GetProperties(NULL,
                                                    ComSafeArrayAsOutParam(aNames),
                                                    ComSafeArrayAsOutParam(aValues));           H();

                        if (aNames.size() != 0)
                        {
                            PCFGMNODE pVDC;
                            rc = CFGMR3InsertNode(pCur, "VDConfig", &pVDC);                     RC_CHECK();
                            for (size_t ii = 0; ii < aNames.size(); ++ii)
                            {
                                if (aValues[ii] && *aValues[ii])
                                {
                                    Utf8Str name = aNames[ii];
                                    Utf8Str value = aValues[ii];
                                    rc = CFGMR3InsertString(pVDC, name.c_str(), value.c_str()); RC_CHECK();
                                    if (    name.compare("HostIPStack") == 0
                                        &&  value.compare("0") == 0)
                                        fHostIP = false;
                                }
                            }
                        }

                        /* Custom code: put marker to not use host IP stack to driver
                         * configuration node. Simplifies life of DrvVD a bit. */
                        if (!fHostIP)
                        {
                            rc = CFGMR3InsertInteger(pCfg, "HostIPStack", 0);                   RC_CHECK();
                        }

                        /* next */
                        pParent = pCur;
                        parentMedium = medium;
                    }
                }
            }

            if (paLedDevType)
                paLedDevType[uLUN] = lType;
        }
        H();
    }
    H();

    /*
     * Network adapters
     */
#ifdef VMWARE_NET_IN_SLOT_11
    bool fSwapSlots3and11 = false;
#endif
    PCFGMNODE pDevPCNet = NULL;          /* PCNet-type devices */
    rc = CFGMR3InsertNode(pDevices, "pcnet", &pDevPCNet);                           RC_CHECK();
#ifdef VBOX_WITH_E1000
    PCFGMNODE pDevE1000 = NULL;          /* E1000-type devices */
    rc = CFGMR3InsertNode(pDevices, "e1000", &pDevE1000);                           RC_CHECK();
#endif
#ifdef VBOX_WITH_VIRTIO
    PCFGMNODE pDevVirtioNet = NULL;          /* Virtio network devices */
    rc = CFGMR3InsertNode(pDevices, "virtio-net", &pDevVirtioNet);                  RC_CHECK();
#endif /* VBOX_WITH_VIRTIO */
    for (ULONG ulInstance = 0; ulInstance < SchemaDefs::NetworkAdapterCount; ++ulInstance)
    {
        ComPtr<INetworkAdapter> networkAdapter;
        hrc = pMachine->GetNetworkAdapter(ulInstance, networkAdapter.asOutParam()); H();
        BOOL fEnabled = FALSE;
        hrc = networkAdapter->COMGETTER(Enabled)(&fEnabled);                        H();
        if (!fEnabled)
            continue;

        /*
         * The virtual hardware type. Create appropriate device first.
         */
        const char *pszAdapterName = "pcnet";
        NetworkAdapterType_T adapterType;
        hrc = networkAdapter->COMGETTER(AdapterType)(&adapterType);                 H();
        switch (adapterType)
        {
            case NetworkAdapterType_Am79C970A:
            case NetworkAdapterType_Am79C973:
                pDev = pDevPCNet;
                break;
#ifdef VBOX_WITH_E1000
            case NetworkAdapterType_I82540EM:
            case NetworkAdapterType_I82543GC:
            case NetworkAdapterType_I82545EM:
                pDev = pDevE1000;
                pszAdapterName = "e1000";
                break;
#endif
#ifdef VBOX_WITH_VIRTIO
            case NetworkAdapterType_Virtio:
                pDev = pDevVirtioNet;
                pszAdapterName = "virtio-net";
                break;
#endif /* VBOX_WITH_VIRTIO */
            default:
                AssertMsgFailed(("Invalid network adapter type '%d' for slot '%d'",
                                 adapterType, ulInstance));
                return VMSetError(pVM, VERR_INVALID_PARAMETER, RT_SRC_POS,
                                  N_("Invalid network adapter type '%d' for slot '%d'"),
                                  adapterType, ulInstance);
        }

        rc = CFGMR3InsertNodeF(pDev, &pInst, "%u", ulInstance);                     RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted",              1); /* boolean */   RC_CHECK();
        /* the first network card gets the PCI ID 3, the next 3 gets 8..10,
         * next 4 get 16..19. */
        unsigned iPciDeviceNo = 3;
        if (ulInstance)
        {
            if (ulInstance < 4)
                iPciDeviceNo = ulInstance - 1 + 8;
            else
                iPciDeviceNo = ulInstance - 4 + 16;
        }
#ifdef VMWARE_NET_IN_SLOT_11
        /*
         * Dirty hack for PCI slot compatibility with VMWare,
         * it assigns slot 11 to the first network controller.
         */
        if (iPciDeviceNo == 3 && adapterType == NetworkAdapterType_I82545EM)
        {
            iPciDeviceNo = 0x11;
            fSwapSlots3and11 = true;
        }
        else if (iPciDeviceNo == 0x11 && fSwapSlots3and11)
            iPciDeviceNo = 3;
#endif
        rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo", iPciDeviceNo);               RC_CHECK();
        Assert(!afPciDeviceNo[iPciDeviceNo]);
        afPciDeviceNo[iPciDeviceNo] = true;
        rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                 RC_CHECK();
        rc = CFGMR3InsertNode(pInst, "Config", &pCfg);                              RC_CHECK();
#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE /* not safe here yet. */
        if (pDev == pDevPCNet)
        {
            rc = CFGMR3InsertInteger(pCfg,  "R0Enabled",    false);                 RC_CHECK();
        }
#endif

        /*
         * The virtual hardware type. PCNet supports two types.
         */
        switch (adapterType)
        {
            case NetworkAdapterType_Am79C970A:
                rc = CFGMR3InsertInteger(pCfg, "Am79C973", 0);                      RC_CHECK();
                break;
            case NetworkAdapterType_Am79C973:
                rc = CFGMR3InsertInteger(pCfg, "Am79C973", 1);                      RC_CHECK();
                break;
            case NetworkAdapterType_I82540EM:
                rc = CFGMR3InsertInteger(pCfg, "AdapterType", 0);                   RC_CHECK();
                break;
            case NetworkAdapterType_I82543GC:
                rc = CFGMR3InsertInteger(pCfg, "AdapterType", 1);                   RC_CHECK();
                break;
            case NetworkAdapterType_I82545EM:
                rc = CFGMR3InsertInteger(pCfg, "AdapterType", 2);                   RC_CHECK();
                break;
        }

        /*
         * Get the MAC address and convert it to binary representation
         */
        Bstr macAddr;
        hrc = networkAdapter->COMGETTER(MACAddress)(macAddr.asOutParam());          H();
        Assert(macAddr);
        Utf8Str macAddrUtf8 = macAddr;
        char *macStr = (char*)macAddrUtf8.raw();
        Assert(strlen(macStr) == 12);
        RTMAC Mac;
        memset(&Mac, 0, sizeof(Mac));
        char *pMac = (char*)&Mac;
        for (uint32_t i = 0; i < 6; ++i)
        {
            char c1 = *macStr++ - '0';
            if (c1 > 9)
                c1 -= 7;
            char c2 = *macStr++ - '0';
            if (c2 > 9)
                c2 -= 7;
            *pMac++ = ((c1 & 0x0f) << 4) | (c2 & 0x0f);
        }
        rc = CFGMR3InsertBytes(pCfg, "MAC", &Mac, sizeof(Mac));                     RC_CHECK();

        /*
         * Check if the cable is supposed to be unplugged
         */
        BOOL fCableConnected;
        hrc = networkAdapter->COMGETTER(CableConnected)(&fCableConnected);          H();
        rc = CFGMR3InsertInteger(pCfg, "CableConnected", fCableConnected ? 1 : 0);  RC_CHECK();

        /*
         * Line speed to report from custom drivers
         */
        ULONG ulLineSpeed;
        hrc = networkAdapter->COMGETTER(LineSpeed)(&ulLineSpeed);                   H();
        rc = CFGMR3InsertInteger(pCfg, "LineSpeed", ulLineSpeed);                   RC_CHECK();

        /*
         * Attach the status driver.
         */
        rc = CFGMR3InsertNode(pInst,    "LUN#999", &pLunL0);                        RC_CHECK();
        rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");      RC_CHECK();
        rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                           RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapNetworkLeds[ulInstance]); RC_CHECK();

        /*
         * Configure the network card now
         */
        rc = configNetwork(pConsole, pszAdapterName, ulInstance, 0, networkAdapter,
                           pCfg, pLunL0, pInst, false /*fAttachDetach*/);           RC_CHECK();
    }

    /*
     * Serial (UART) Ports
     */
    rc = CFGMR3InsertNode(pDevices, "serial", &pDev);                               RC_CHECK();
    for (ULONG ulInstance = 0; ulInstance < SchemaDefs::SerialPortCount; ++ulInstance)
    {
        ComPtr<ISerialPort> serialPort;
        hrc = pMachine->GetSerialPort (ulInstance, serialPort.asOutParam());        H();
        BOOL fEnabled = FALSE;
        if (serialPort)
            hrc = serialPort->COMGETTER(Enabled)(&fEnabled);                        H();
        if (!fEnabled)
            continue;

        rc = CFGMR3InsertNodeF(pDev, &pInst, "%u", ulInstance);                     RC_CHECK();
        rc = CFGMR3InsertNode(pInst, "Config", &pCfg);                              RC_CHECK();

        ULONG ulIRQ;
        hrc = serialPort->COMGETTER(IRQ)(&ulIRQ);                                   H();
        rc = CFGMR3InsertInteger(pCfg,   "IRQ", ulIRQ);                             RC_CHECK();
        ULONG ulIOBase;
        hrc = serialPort->COMGETTER(IOBase)(&ulIOBase);                             H();
        rc = CFGMR3InsertInteger(pCfg,   "IOBase", ulIOBase);                       RC_CHECK();
        BOOL  fServer;
        hrc = serialPort->COMGETTER(Server)(&fServer);                              H();
        hrc = serialPort->COMGETTER(Path)(&str);                                    H();
        PortMode_T eHostMode;
        hrc = serialPort->COMGETTER(HostMode)(&eHostMode);                          H();
        if (eHostMode != PortMode_Disconnected)
        {
            rc = CFGMR3InsertNode(pInst,     "LUN#0", &pLunL0);                     RC_CHECK();
            if (eHostMode == PortMode_HostPipe)
            {
                rc = CFGMR3InsertString(pLunL0,  "Driver", "Char");                 RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,    "AttachedDriver", &pLunL1);        RC_CHECK();
                rc = CFGMR3InsertString(pLunL1,  "Driver", "NamedPipe");            RC_CHECK();
                rc = CFGMR3InsertNode(pLunL1,    "Config", &pLunL2);                RC_CHECK();
                rc = CFGMR3InsertStringW(pLunL2, "Location", str);                  RC_CHECK();
                rc = CFGMR3InsertInteger(pLunL2, "IsServer", fServer);              RC_CHECK();
            }
            else if (eHostMode == PortMode_HostDevice)
            {
                rc = CFGMR3InsertString(pLunL0,  "Driver", "Host Serial");          RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,    "Config", &pLunL1);                RC_CHECK();
                rc = CFGMR3InsertStringW(pLunL1, "DevicePath", str);                RC_CHECK();
            }
            else if (eHostMode == PortMode_RawFile)
            {
                rc = CFGMR3InsertString(pLunL0,  "Driver", "Char");                 RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,    "AttachedDriver", &pLunL1);        RC_CHECK();
                rc = CFGMR3InsertString(pLunL1,  "Driver", "RawFile");              RC_CHECK();
                rc = CFGMR3InsertNode(pLunL1,    "Config", &pLunL2);                RC_CHECK();
                rc = CFGMR3InsertStringW(pLunL2, "Location", str);                  RC_CHECK();
            }
        }
        STR_FREE();
    }

    /*
     * Parallel (LPT) Ports
     */
    rc = CFGMR3InsertNode(pDevices, "parallel", &pDev);                             RC_CHECK();
    for (ULONG ulInstance = 0; ulInstance < SchemaDefs::ParallelPortCount; ++ulInstance)
    {
        ComPtr<IParallelPort> parallelPort;
        hrc = pMachine->GetParallelPort(ulInstance, parallelPort.asOutParam());     H();
        BOOL fEnabled = FALSE;
        if (parallelPort)
        {
            hrc = parallelPort->COMGETTER(Enabled)(&fEnabled);                      H();
        }
        if (!fEnabled)
            continue;

        rc = CFGMR3InsertNodeF(pDev, &pInst, "%u", ulInstance);                     RC_CHECK();
        rc = CFGMR3InsertNode(pInst, "Config", &pCfg);                              RC_CHECK();

        ULONG ulIRQ;
        hrc = parallelPort->COMGETTER(IRQ)(&ulIRQ);                                 H();
        rc = CFGMR3InsertInteger(pCfg,   "IRQ", ulIRQ);                             RC_CHECK();
        ULONG ulIOBase;
        hrc = parallelPort->COMGETTER(IOBase)(&ulIOBase);                           H();
        rc = CFGMR3InsertInteger(pCfg,   "IOBase", ulIOBase);                       RC_CHECK();
        rc = CFGMR3InsertNode(pInst,     "LUN#0", &pLunL0);                         RC_CHECK();
        rc = CFGMR3InsertString(pLunL0,  "Driver", "HostParallel");                 RC_CHECK();
        rc = CFGMR3InsertNode(pLunL0,    "AttachedDriver", &pLunL1);                RC_CHECK();
        hrc = parallelPort->COMGETTER(Path)(&str);                                  H();
        rc = CFGMR3InsertStringW(pLunL1,  "DevicePath", str);                       RC_CHECK();
        STR_FREE();
    }

    /*
     * VMM Device
     */
    rc = CFGMR3InsertNode(pDevices, "VMMDev", &pDev);                               RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "Trusted",              1);     /* boolean */   RC_CHECK();
    rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          4);                     RC_CHECK();
    Assert(!afPciDeviceNo[4]);
    afPciDeviceNo[4] = true;
    rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                     RC_CHECK();
    Bstr hwVersion;
    hrc = pMachine->COMGETTER(HardwareVersion)(hwVersion.asOutParam());             H();
    if (hwVersion.compare(Bstr("1")) == 0) /* <= 2.0.x */
    {
        CFGMR3InsertInteger(pCfg, "HeapEnabled", 0);                                RC_CHECK();
    }

    /* the VMM device's Main driver */
    rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                              RC_CHECK();
    rc = CFGMR3InsertString(pLunL0, "Driver",               "HGCM");                RC_CHECK();
    rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
    VMMDev *pVMMDev = pConsole->mVMMDev;
    rc = CFGMR3InsertInteger(pCfg,  "Object", (uintptr_t)pVMMDev);                  RC_CHECK();

    /*
     * Attach the status driver.
     */
    rc = CFGMR3InsertNode(pInst,    "LUN#999", &pLunL0);                            RC_CHECK();
    rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");          RC_CHECK();
    rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapSharedFolderLed); RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "First",    0);                                 RC_CHECK();
    rc = CFGMR3InsertInteger(pCfg,  "Last",     0);                                 RC_CHECK();

    /*
     * Audio Sniffer Device
     */
    rc = CFGMR3InsertNode(pDevices, "AudioSniffer", &pDev);                         RC_CHECK();
    rc = CFGMR3InsertNode(pDev,     "0", &pInst);                                   RC_CHECK();
    rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                               RC_CHECK();

    /* the Audio Sniffer device's Main driver */
    rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                              RC_CHECK();
    rc = CFGMR3InsertString(pLunL0, "Driver",               "MainAudioSniffer");    RC_CHECK();
    rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                               RC_CHECK();
    AudioSniffer *pAudioSniffer = pConsole->mAudioSniffer;
    rc = CFGMR3InsertInteger(pCfg,  "Object", (uintptr_t)pAudioSniffer);            RC_CHECK();

    /*
     * AC'97 ICH / SoundBlaster16 audio
     */
    BOOL enabled;
    ComPtr<IAudioAdapter> audioAdapter;
    hrc = pMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());             H();
    if (audioAdapter)
        hrc = audioAdapter->COMGETTER(Enabled)(&enabled);                           H();

    if (enabled)
    {
        AudioControllerType_T audioController;
        hrc = audioAdapter->COMGETTER(AudioController)(&audioController);           H();
        switch (audioController)
        {
            case AudioControllerType_AC97:
            {
                /* default: ICH AC97 */
                rc = CFGMR3InsertNode(pDevices, "ichac97", &pDev);                  RC_CHECK();
                rc = CFGMR3InsertNode(pDev,     "0", &pInst);
                rc = CFGMR3InsertInteger(pInst, "Trusted",          1); /* bool */  RC_CHECK();
                rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",      5);             RC_CHECK();
                Assert(!afPciDeviceNo[5]);
                afPciDeviceNo[5] = true;
                rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",    0);             RC_CHECK();
                rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                   RC_CHECK();
                break;
            }
            case AudioControllerType_SB16:
            {
                /* legacy SoundBlaster16 */
                rc = CFGMR3InsertNode(pDevices, "sb16", &pDev);                     RC_CHECK();
                rc = CFGMR3InsertNode(pDev,     "0", &pInst);                       RC_CHECK();
                rc = CFGMR3InsertInteger(pInst, "Trusted",          1); /* bool */  RC_CHECK();
                rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                   RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "IRQ", 5);                          RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "DMA", 1);                          RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "DMA16", 5);                        RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "Port", 0x220);                     RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "Version", 0x0405);                 RC_CHECK();
                break;
            }
        }

        /* the Audio driver */
        rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                          RC_CHECK();
        rc = CFGMR3InsertString(pLunL0, "Driver",               "AUDIO");           RC_CHECK();
        rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                           RC_CHECK();

        AudioDriverType_T audioDriver;
        hrc = audioAdapter->COMGETTER(AudioDriver)(&audioDriver);                   H();
        switch (audioDriver)
        {
            case AudioDriverType_Null:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "null");               RC_CHECK();
                break;
            }
#ifdef RT_OS_WINDOWS
#ifdef VBOX_WITH_WINMM
            case AudioDriverType_WinMM:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "winmm");              RC_CHECK();
                break;
            }
#endif
            case AudioDriverType_DirectSound:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "dsound");             RC_CHECK();
                break;
            }
#endif /* RT_OS_WINDOWS */
#ifdef RT_OS_SOLARIS
            case AudioDriverType_SolAudio:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "solaudio");           RC_CHECK();
                break;
            }
#endif
#ifdef RT_OS_LINUX
# ifdef VBOX_WITH_ALSA
            case AudioDriverType_ALSA:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "alsa");               RC_CHECK();
                break;
            }
# endif
# ifdef VBOX_WITH_PULSE
            case AudioDriverType_Pulse:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "pulse");              RC_CHECK();
                break;
            }
# endif
#endif /* RT_OS_LINUX */
#if defined (RT_OS_LINUX) || defined (RT_OS_FREEBSD) || defined(VBOX_WITH_SOLARIS_OSS)
            case AudioDriverType_OSS:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "oss");                RC_CHECK();
                break;
            }
#endif
#ifdef RT_OS_DARWIN
            case AudioDriverType_CoreAudio:
            {
                rc = CFGMR3InsertString(pCfg, "AudioDriver", "coreaudio");          RC_CHECK();
                break;
            }
#endif
        }
        hrc = pMachine->COMGETTER(Name)(&str);                                      H();
        rc = CFGMR3InsertStringW(pCfg, "StreamName", str);                          RC_CHECK();
        STR_FREE();
    }

    /*
     * The USB Controller.
     */
    ComPtr<IUSBController> USBCtlPtr;
    hrc = pMachine->COMGETTER(USBController)(USBCtlPtr.asOutParam());
    if (USBCtlPtr)
    {
        BOOL fEnabled;
        hrc = USBCtlPtr->COMGETTER(Enabled)(&fEnabled);                             H();
        if (fEnabled)
        {
            rc = CFGMR3InsertNode(pDevices, "usb-ohci", &pDev);                     RC_CHECK();
            rc = CFGMR3InsertNode(pDev,     "0", &pInst);                           RC_CHECK();
            rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                       RC_CHECK();
            rc = CFGMR3InsertInteger(pInst, "Trusted",              1); /* boolean */   RC_CHECK();
            rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          6);                 RC_CHECK();
            Assert(!afPciDeviceNo[6]);
            afPciDeviceNo[6] = true;
            rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                 RC_CHECK();

            rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                          RC_CHECK();
            rc = CFGMR3InsertString(pLunL0, "Driver",               "VUSBRootHub");     RC_CHECK();
            rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                           RC_CHECK();

            /*
             * Attach the status driver.
             */
            rc = CFGMR3InsertNode(pInst,    "LUN#999", &pLunL0);                        RC_CHECK();
            rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");      RC_CHECK();
            rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                           RC_CHECK();
            rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapUSBLed[0]);RC_CHECK();
            rc = CFGMR3InsertInteger(pCfg,  "First",    0);                             RC_CHECK();
            rc = CFGMR3InsertInteger(pCfg,  "Last",     0);                             RC_CHECK();

#ifdef VBOX_WITH_EHCI
            hrc = USBCtlPtr->COMGETTER(EnabledEhci)(&fEnabled);                         H();
            if (fEnabled)
            {
                rc = CFGMR3InsertNode(pDevices, "usb-ehci", &pDev);                     RC_CHECK();
                rc = CFGMR3InsertNode(pDev,     "0", &pInst);                           RC_CHECK();
                rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                       RC_CHECK();
                rc = CFGMR3InsertInteger(pInst, "Trusted",              1); /* bool */  RC_CHECK();
                rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          11);            RC_CHECK();
                Assert(!afPciDeviceNo[11]);
                afPciDeviceNo[11] = true;
                rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);             RC_CHECK();

                rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                      RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "VUSBRootHub"); RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                       RC_CHECK();

                /*
                 * Attach the status driver.
                 */
                rc = CFGMR3InsertNode(pInst,    "LUN#999", &pLunL0);                    RC_CHECK();
                rc = CFGMR3InsertString(pLunL0, "Driver",               "MainStatus");  RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                       RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "papLeds", (uintptr_t)&pConsole->mapUSBLed[1]);RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "First",    0);                         RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg,  "Last",     0);                         RC_CHECK();
            }
            else
#endif
            {
                /*
                 * Global USB options, currently unused as we'll apply the 2.0 -> 1.1 morphing
                 * on a per device level now.
                 */
                rc = CFGMR3InsertNode(pRoot, "USB", &pCfg);                             RC_CHECK();
                rc = CFGMR3InsertNode(pCfg, "USBProxy", &pCfg);                         RC_CHECK();
                rc = CFGMR3InsertNode(pCfg, "GlobalConfig", &pCfg);                     RC_CHECK();
                // This globally enables the 2.0 -> 1.1 device morphing of proxied devies to keep windows quiet.
                //rc = CFGMR3InsertInteger(pCfg, "Force11Device", true);                RC_CHECK();
                // The following breaks stuff, but it makes MSDs work in vista. (I include it here so
                // that it's documented somewhere.) Users needing it can use:
                //      VBoxManage setextradata "myvm" "VBoxInternal/USB/USBProxy/GlobalConfig/Force11PacketSize" 1
                //rc = CFGMR3InsertInteger(pCfg, "Force11PacketSize", true);            RC_CHECK();
            }
        }
    }

    /*
     * Clipboard
     */
    {
        ClipboardMode_T mode = ClipboardMode_Disabled;
        hrc = pMachine->COMGETTER(ClipboardMode)(&mode);                                H();

        if (mode != ClipboardMode_Disabled)
        {
            /* Load the service */
            rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedClipboard", "VBoxSharedClipboard");

            if (RT_FAILURE(rc))
            {
                LogRel(("VBoxSharedClipboard is not available. rc = %Rrc\n", rc));
                /* That is not a fatal failure. */
                rc = VINF_SUCCESS;
            }
            else
            {
                /* Setup the service. */
                VBOXHGCMSVCPARM parm;

                parm.type = VBOX_HGCM_SVC_PARM_32BIT;

                switch (mode)
                {
                    default:
                    case ClipboardMode_Disabled:
                    {
                        LogRel(("VBoxSharedClipboard mode: Off\n"));
                        parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_OFF;
                        break;
                    }
                    case ClipboardMode_GuestToHost:
                    {
                        LogRel(("VBoxSharedClipboard mode: Guest to Host\n"));
                        parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_GUEST_TO_HOST;
                        break;
                    }
                    case ClipboardMode_HostToGuest:
                    {
                        LogRel(("VBoxSharedClipboard mode: Host to Guest\n"));
                        parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_HOST_TO_GUEST;
                        break;
                    }
                    case ClipboardMode_Bidirectional:
                    {
                        LogRel(("VBoxSharedClipboard mode: Bidirectional\n"));
                        parm.u.uint32 = VBOX_SHARED_CLIPBOARD_MODE_BIDIRECTIONAL;
                        break;
                    }
                }

                pConsole->mVMMDev->hgcmHostCall ("VBoxSharedClipboard", VBOX_SHARED_CLIPBOARD_HOST_FN_SET_MODE, 1, &parm);

                Log(("Set VBoxSharedClipboard mode\n"));
            }
        }
    }

#ifdef VBOX_WITH_CROGL
    /*
     * crOpenGL
     */
    {
        BOOL fEnabled = false;
        hrc = pMachine->COMGETTER(Accelerate3DEnabled)(&fEnabled); H();

        if (fEnabled)
        {
            /* Load the service */
            rc = pConsole->mVMMDev->hgcmLoadService ("VBoxSharedCrOpenGL", "VBoxSharedCrOpenGL");
            if (RT_FAILURE(rc))
            {
                LogRel(("Failed to load Shared OpenGL service %Rrc\n", rc));
                /* That is not a fatal failure. */
                rc = VINF_SUCCESS;
            }
            else
            {
                LogRel(("Shared crOpenGL service loaded.\n"));

                /* Setup the service. */
                VBOXHGCMSVCPARM parm;
                parm.type = VBOX_HGCM_SVC_PARM_PTR;

                parm.u.pointer.addr = pConsole->getDisplay()->getFramebuffer();
                parm.u.pointer.size = sizeof(IFramebuffer *);

                rc = pConsole->mVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_FRAMEBUFFER, 1, &parm);
                if (!RT_SUCCESS(rc))
                    AssertMsgFailed(("SHCRGL_HOST_FN_SET_FRAMEBUFFER failed with %Rrc\n", rc));

                parm.u.pointer.addr = pVM;
                parm.u.pointer.size = sizeof(pVM);
                rc = pConsole->mVMMDev->hgcmHostCall("VBoxSharedCrOpenGL", SHCRGL_HOST_FN_SET_VM, 1, &parm);
                if (!RT_SUCCESS(rc))
                    AssertMsgFailed(("SHCRGL_HOST_FN_SET_VM failed with %Rrc\n", rc));
            }

        }
    }
#endif

#ifdef VBOX_WITH_GUEST_PROPS
    /*
     * Guest property service
     */

    rc = configGuestProperties(pConsole);
#endif /* VBOX_WITH_GUEST_PROPS defined */

    /*
     * CFGM overlay handling.
     *
     * Here we check the extra data entries for CFGM values
     * and create the nodes and insert the values on the fly. Existing
     * values will be removed and reinserted. CFGM is typed, so by default
     * we will guess whether it's a string or an integer (byte arrays are
     * not currently supported). It's possible to override this autodetection
     * by adding "string:", "integer:" or "bytes:" (future).
     *
     * We first perform a run on global extra data, then on the machine
     * extra data to support global settings with local overrides.
     *
     */
    /** @todo add support for removing nodes and byte blobs. */
    SafeArray<BSTR> aGlobalExtraDataKeys;
    SafeArray<BSTR> aMachineExtraDataKeys;
    /*
        * Get the next key
        */
    if (FAILED(hrc = virtualBox->GetExtraDataKeys(ComSafeArrayAsOutParam(aGlobalExtraDataKeys))))
        AssertMsgFailed(("VirtualBox::GetExtraDataKeys failed with %Rrc\n", hrc));

    // remember the no. of global values so we can call the correct method below
    size_t cGlobalValues = aGlobalExtraDataKeys.size();

    if (FAILED(hrc = pMachine->GetExtraDataKeys(ComSafeArrayAsOutParam(aMachineExtraDataKeys))))
        AssertMsgFailed(("IMachine::GetExtraDataKeys failed with %Rrc\n", hrc));

    // build a combined list from global keys...
    std::list<Utf8Str> llExtraDataKeys;
    size_t i = 0;

    for (i = 0; i < aGlobalExtraDataKeys.size(); ++i)
        llExtraDataKeys.push_back(Utf8Str(aGlobalExtraDataKeys[i]));
    // ... and machine keys
    for (i = 0; i < aMachineExtraDataKeys.size(); ++i)
        llExtraDataKeys.push_back(Utf8Str(aMachineExtraDataKeys[i]));

    i = 0;
    for (std::list<Utf8Str>::const_iterator it = llExtraDataKeys.begin();
         it != llExtraDataKeys.end();
         ++it, ++i)
    {
        const Utf8Str &strKey = *it;

        /*
         * We only care about keys starting with "VBoxInternal/" (skip "G:" or "M:")
         */
        if (!strKey.startsWith("VBoxInternal/"))
            continue;

        const char *pszExtraDataKey = strKey.raw() + sizeof("VBoxInternal/") - 1;

        // get the value
        Bstr strExtraDataValue;
        if (i < cGlobalValues)
            // this is still one of the global values:
            hrc = virtualBox->GetExtraData(Bstr(strKey), strExtraDataValue.asOutParam());
        else
            hrc = pMachine->GetExtraData(Bstr(strKey), strExtraDataValue.asOutParam());
        if (FAILED(hrc))
            LogRel(("Warning: Cannot get extra data key %s, rc = %Rrc\n", strKey.raw(), hrc));

        /*
         * The key will be in the format "Node1/Node2/Value" or simply "Value".
         * Split the two and get the node, delete the value and create the node
         * if necessary.
         */
        PCFGMNODE pNode;
        const char *pszCFGMValueName = strrchr(pszExtraDataKey, '/');
        if (pszCFGMValueName)
        {
            /* terminate the node and advance to the value (Utf8Str might not
               offically like this but wtf) */
            *(char*)pszCFGMValueName = '\0';
            ++pszCFGMValueName;

            /* does the node already exist? */
            pNode = CFGMR3GetChild(pRoot, pszExtraDataKey);
            if (pNode)
                CFGMR3RemoveValue(pNode, pszCFGMValueName);
            else
            {
                /* create the node */
                rc = CFGMR3InsertNode(pRoot, pszExtraDataKey, &pNode);
                if (RT_FAILURE(rc))
                {
                    AssertLogRelMsgRC(rc, ("failed to insert node '%s'\n", pszExtraDataKey));
                    continue;
                }
                Assert(pNode);
            }
        }
        else
        {
            /* root value (no node path). */
            pNode = pRoot;
            pszCFGMValueName = pszExtraDataKey;
            pszExtraDataKey--;
            CFGMR3RemoveValue(pNode, pszCFGMValueName);
        }

        /*
         * Now let's have a look at the value.
         * Empty strings means that we should remove the value, which we've
         * already done above.
         */
        Utf8Str strCFGMValueUtf8(strExtraDataValue);
        const char *pszCFGMValue = strCFGMValueUtf8.raw();
        if (    pszCFGMValue
            && *pszCFGMValue)
        {
            uint64_t u64Value;

            /* check for type prefix first. */
            if (!strncmp(pszCFGMValue, "string:", sizeof("string:") - 1))
                rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue + sizeof("string:") - 1);
            else if (!strncmp(pszCFGMValue, "integer:", sizeof("integer:") - 1))
            {
                rc = RTStrToUInt64Full(pszCFGMValue + sizeof("integer:") - 1, 0, &u64Value);
                if (RT_SUCCESS(rc))
                    rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
            }
            else if (!strncmp(pszCFGMValue, "bytes:", sizeof("bytes:") - 1))
                rc = VERR_NOT_IMPLEMENTED;
            /* auto detect type. */
            else if (RT_SUCCESS(RTStrToUInt64Full(pszCFGMValue, 0, &u64Value)))
                rc = CFGMR3InsertInteger(pNode, pszCFGMValueName, u64Value);
            else
                rc = CFGMR3InsertString(pNode, pszCFGMValueName, pszCFGMValue);
            AssertLogRelMsgRC(rc, ("failed to insert CFGM value '%s' to key '%s'\n", pszCFGMValue, pszExtraDataKey));
        }
    }

    /*
     * ACPI
     */
    BOOL fACPI;
    hrc = biosSettings->COMGETTER(ACPIEnabled)(&fACPI);                             H();
    if (fACPI)
    {
        BOOL fShowCpu = fExtProfile;
        /* Always show the CPU leafs when we have multiple VCPUs or when the IO-APIC is enabled.
         * The Windows SMP kernel needs a CPU leaf or else its idle loop will burn cpu cycles; the
         * intelppm driver refuses to register an idle state handler.
         */
        if ((cCpus > 1) ||  fIOAPIC)
            fShowCpu = true;

        rc = CFGMR3InsertNode(pDevices, "acpi", &pDev);                             RC_CHECK();
        rc = CFGMR3InsertNode(pDev,     "0", &pInst);                               RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "Trusted", 1);              /* boolean */   RC_CHECK();
        rc = CFGMR3InsertNode(pInst,    "Config", &pCfg);                           RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "RamSize",          cbRam);                 RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "RamHoleSize",      cbRamHole);             RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "NumCPUs",          cCpus);                 RC_CHECK();

        rc = CFGMR3InsertInteger(pCfg,  "IOAPIC", fIOAPIC);                         RC_CHECK();
        rc = CFGMR3InsertInteger(pCfg,  "FdcEnabled", fFdcEnabled);                 RC_CHECK();
#ifdef VBOX_WITH_HPET
        rc = CFGMR3InsertInteger(pCfg,  "HpetEnabled", fHpetEnabled);               RC_CHECK();
#endif
#ifdef VBOX_WITH_SMC
        rc = CFGMR3InsertInteger(pCfg,  "SmcEnabled", fSmcEnabled);                 RC_CHECK();
#endif
        rc = CFGMR3InsertInteger(pCfg,  "ShowRtc", fExtProfile);                    RC_CHECK();

        rc = CFGMR3InsertInteger(pCfg,  "ShowCpu", fShowCpu);                       RC_CHECK();
        rc = CFGMR3InsertInteger(pInst, "PCIDeviceNo",          7);                 RC_CHECK();
        Assert(!afPciDeviceNo[7]);
        afPciDeviceNo[7] = true;
        rc = CFGMR3InsertInteger(pInst, "PCIFunctionNo",        0);                 RC_CHECK();

        rc = CFGMR3InsertNode(pInst,    "LUN#0", &pLunL0);                          RC_CHECK();
        rc = CFGMR3InsertString(pLunL0, "Driver",               "ACPIHost");        RC_CHECK();
        rc = CFGMR3InsertNode(pLunL0,   "Config", &pCfg);                           RC_CHECK();
    }

#undef STR_FREE
#undef H
#undef RC_CHECK

    /* Register VM state change handler */
    int rc2 = VMR3AtStateRegister (pVM, Console::vmstateChangeCallback, pConsole);
    AssertRC (rc2);
    if (RT_SUCCESS(rc))
        rc = rc2;

    /* Register VM runtime error handler */
    rc2 = VMR3AtRuntimeErrorRegister (pVM, Console::setVMRuntimeErrorCallback, pConsole);
    AssertRC (rc2);
    if (RT_SUCCESS(rc))
        rc = rc2;

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

    return rc;
}

/**
 * Ellipsis to va_list wrapper for calling setVMRuntimeErrorCallback.
 */
/*static*/ void Console::setVMRuntimeErrorCallbackF(PVM pVM, void *pvConsole, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
{
    va_list va;
    va_start(va, pszFormat);
    setVMRuntimeErrorCallback(pVM, pvConsole, fFlags, pszErrorId, pszFormat, va);
    va_end(va);
}

/**
 *  Construct the Network configuration tree
 *
 *  @returns VBox status code.
 *
 *  @param   pThis               Pointer to the Console object.
 *  @param   pszDevice           The PDM device name.
 *  @param   uInstance           The PDM device instance.
 *  @param   uLun                The PDM LUN number of the drive.
 *  @param   aNetworkAdapter     The network adapter whose attachment needs to be changed
 *  @param   pCfg                Configuration node for the device
 *  @param   pLunL0              To store the pointer to the LUN#0.
 *  @param   pInst               The instance CFGM node
 *  @param   fAttachDetach       To determine if the network attachment should
 *                               be attached/detached after/before
 *                               configuration.
 *
 *  @note Locks the Console object for writing.
 */
/*static*/ int Console::configNetwork(Console *pThis, const char *pszDevice,
                                      unsigned uInstance, unsigned uLun,
                                      INetworkAdapter *aNetworkAdapter,
                                      PCFGMNODE pCfg, PCFGMNODE pLunL0,
                                      PCFGMNODE pInst, bool fAttachDetach)
{
    int rc = VINF_SUCCESS;

    AutoCaller autoCaller(pThis);
    AssertComRCReturn(autoCaller.rc(), VERR_ACCESS_DENIED);

    /*
     * Locking the object before doing VMR3* calls is quite safe here, since
     * we're on EMT. Write lock is necessary because we indirectly modify the
     * meAttachmentType member.
     */
    AutoWriteLock alock(pThis);

    PVM     pVM = pThis->mpVM;
    BSTR    str = NULL;

#define STR_FREE()  do { if (str) { SysFreeString(str); str = NULL; } } while (0)
#define RC_CHECK()  do { if (RT_FAILURE(rc)) { AssertMsgFailed(("rc=%Rrc\n", rc));  STR_FREE(); return rc;                   } } while (0)
#define H()         do { if (FAILED(hrc))    { AssertMsgFailed(("hrc=%#x\n", hrc)); STR_FREE(); return VERR_GENERAL_FAILURE; } } while (0)

    HRESULT hrc;
    ComPtr<IMachine> pMachine = pThis->machine();

    ComPtr<IVirtualBox> virtualBox;
    hrc = pMachine->COMGETTER(Parent)(virtualBox.asOutParam());
    H();

    ComPtr<IHost> host;
    hrc = virtualBox->COMGETTER(Host)(host.asOutParam());
    H();

    BOOL fSniffer;
    hrc = aNetworkAdapter->COMGETTER(TraceEnabled)(&fSniffer);
    H();

    if (fAttachDetach && fSniffer)
    {
        const char *pszNetDriver = "IntNet";
        if (pThis->meAttachmentType[uInstance] == NetworkAttachmentType_NAT)
            pszNetDriver = "NAT";
#if !defined(VBOX_WITH_NETFLT) && defined(RT_OS_LINUX)
        if (pThis->meAttachmentType[uInstance] == NetworkAttachmentType_Bridged)
            pszNetDriver = "HostInterface";
#endif

        rc = PDMR3DriverDetach(pVM, pszDevice, uInstance, uLun, pszNetDriver, 0, 0 /*fFlags*/);
        if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
            rc = VINF_SUCCESS;
        AssertLogRelRCReturn(rc, rc);

        pLunL0 = CFGMR3GetChildF(pInst, "LUN#%u", uLun);
        PCFGMNODE pLunAD = CFGMR3GetChildF(pLunL0, "AttachedDriver");
        if (pLunAD)
        {
            CFGMR3RemoveNode(pLunAD);
        }
        else
        {
            CFGMR3RemoveNode(pLunL0);
            rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);                 RC_CHECK();
            rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer");        RC_CHECK();
            rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                 RC_CHECK();
            hrc = aNetworkAdapter->COMGETTER(TraceFile)(&str);              H();
            if (str) /* check convention for indicating default file. */
            {
                rc = CFGMR3InsertStringW(pCfg, "File", str);                RC_CHECK();
            }
            STR_FREE();
        }
    }
    else if (fAttachDetach && !fSniffer)
    {
        rc = PDMR3DeviceDetach(pVM, pszDevice, uInstance, uLun, 0 /*fFlags*/);
        if (rc == VINF_PDM_NO_DRIVER_ATTACHED_TO_LUN)
            rc = VINF_SUCCESS;
        AssertLogRelRCReturn(rc, rc);

        /* nuke anything which might have been left behind. */
        CFGMR3RemoveNode(CFGMR3GetChildF(pInst, "LUN#%u", uLun));
    }
    else if (!fAttachDetach && fSniffer)
    {
        /* insert the sniffer filter driver. */
        rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);                 RC_CHECK();
        rc = CFGMR3InsertString(pLunL0, "Driver", "NetSniffer");        RC_CHECK();
        rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                 RC_CHECK();
        hrc = aNetworkAdapter->COMGETTER(TraceFile)(&str);              H();
        if (str) /* check convention for indicating default file. */
        {
            rc = CFGMR3InsertStringW(pCfg, "File", str);                RC_CHECK();
        }
        STR_FREE();
    }

    Bstr networkName, trunkName, trunkType;
    NetworkAttachmentType_T eAttachmentType;
    hrc = aNetworkAdapter->COMGETTER(AttachmentType)(&eAttachmentType); H();
    switch (eAttachmentType)
    {
        case NetworkAttachmentType_Null:
            break;

        case NetworkAttachmentType_NAT:
        {
            if (fSniffer)
            {
                rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0); RC_CHECK();
            }
            else
            {
                rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);         RC_CHECK();
            }
            rc = CFGMR3InsertString(pLunL0, "Driver", "NAT");           RC_CHECK();
            rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);             RC_CHECK();

            /* Configure TFTP prefix and boot filename. */
            hrc = virtualBox->COMGETTER(HomeFolder)(&str);              H();
            if (str && *str)
            {
                rc = CFGMR3InsertStringF(pCfg, "TFTPPrefix", "%ls%c%s", str, RTPATH_DELIMITER, "TFTP"); RC_CHECK();
            }
            STR_FREE();
            hrc = pMachine->COMGETTER(Name)(&str);                      H();
            rc = CFGMR3InsertStringF(pCfg, "BootFile", "%ls.pxe", str); RC_CHECK();
            STR_FREE();

            hrc = aNetworkAdapter->COMGETTER(NATNetwork)(&str);         H();
            if (str && *str)
            {
                rc = CFGMR3InsertStringW(pCfg, "Network", str);         RC_CHECK();
                /* NAT uses its own DHCP implementation */
                //networkName = Bstr(psz);
            }
            STR_FREE();
            break;
        }

        case NetworkAttachmentType_Bridged:
        {
#if (defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)) && !defined(VBOX_WITH_NETFLT)
            hrc = pThis->attachToTapInterface(aNetworkAdapter);
            if (FAILED(hrc))
            {
                switch (hrc)
                {
                    case VERR_ACCESS_DENIED:
                        return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,  N_(
                                         "Failed to open '/dev/net/tun' for read/write access. Please check the "
                                         "permissions of that node. Either run 'chmod 0666 /dev/net/tun' or "
                                         "change the group of that node and make yourself a member of that group. Make "
                                         "sure that these changes are permanent, especially if you are "
                                         "using udev"));
                    default:
                        AssertMsgFailed(("Could not attach to host interface! Bad!\n"));
                        return VMSetError(pVM, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS, N_(
                                         "Failed to initialize Host Interface Networking"));
                }
            }

            Assert ((int)pThis->maTapFD[uInstance] >= 0);
            if ((int)pThis->maTapFD[uInstance] >= 0)
            {
                if (fSniffer)
                {
                    rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0);               RC_CHECK();
                }
                else
                {
                    rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);                         RC_CHECK();
                }
                rc = CFGMR3InsertString(pLunL0, "Driver", "HostInterface");                 RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                             RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg, "FileHandle", pThis->maTapFD[uInstance]);    RC_CHECK();
            }

#elif defined(VBOX_WITH_NETFLT)
            /*
             * This is the new VBoxNetFlt+IntNet stuff.
             */
            if (fSniffer)
            {
                rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0);                   RC_CHECK();
            }
            else
            {
                rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);                             RC_CHECK();
            }

            Bstr HifName;
            hrc = aNetworkAdapter->COMGETTER(HostInterface)(HifName.asOutParam());
            if (FAILED(hrc))
            {
                LogRel(("NetworkAttachmentType_Bridged: COMGETTER(HostInterface) failed, hrc (0x%x)", hrc));
                H();
            }

            Utf8Str HifNameUtf8(HifName);
            const char *pszHifName = HifNameUtf8.raw();

# if defined(RT_OS_DARWIN)
            /* The name is on the form 'ifX: long name', chop it off at the colon. */
            char szTrunk[8];
            strncpy(szTrunk, pszHifName, sizeof(szTrunk));
            char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
            if (!pszColon)
            {
                /*
                 * Dynamic changing of attachment causes an attempt to configure
                 * network with invalid host adapter (as it is must be changed before
                 * the attachment), calling Detach here will cause a deadlock.
                 * See #4750.
                 * hrc = aNetworkAdapter->Detach();                        H();
                 */
                return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
                                  N_("Malformed host interface networking name '%ls'"),
                                  HifName.raw());
            }
            *pszColon = '\0';
            const char *pszTrunk = szTrunk;

# elif defined(RT_OS_SOLARIS)
            /* The name is on the form format 'ifX[:1] - long name, chop it off at space. */
            char szTrunk[256];
            strlcpy(szTrunk, pszHifName, sizeof(szTrunk));
            char *pszSpace = (char *)memchr(szTrunk, ' ', sizeof(szTrunk));

            /*
             * Currently don't bother about malformed names here for the sake of people using
             * VBoxManage and setting only the NIC name from there. If there is a space we
             * chop it off and proceed, otherwise just use whatever we've got.
             */
            if (pszSpace)
                *pszSpace = '\0';

            /* Chop it off at the colon (zone naming eg: e1000g:1 we need only the e1000g) */
            char *pszColon = (char *)memchr(szTrunk, ':', sizeof(szTrunk));
            if (pszColon)
                *pszColon = '\0';

            const char *pszTrunk = szTrunk;

# elif defined(RT_OS_WINDOWS)
            ComPtr<IHostNetworkInterface> hostInterface;
            hrc = host->FindHostNetworkInterfaceByName(HifName, hostInterface.asOutParam());
            if (!SUCCEEDED(hrc))
            {
                AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: FindByName failed, rc=%Rhrc (0x%x)", hrc, hrc));
                return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
                                  N_("Inexistent host networking interface, name '%ls'"),
                                  HifName.raw());
            }

            HostNetworkInterfaceType_T eIfType;
            hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
            if (FAILED(hrc))
            {
                LogRel(("NetworkAttachmentType_Bridged: COMGETTER(InterfaceType) failed, hrc (0x%x)", hrc));
                H();
            }

            if (eIfType != HostNetworkInterfaceType_Bridged)
            {
                return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
                                                      N_("Interface ('%ls') is not a Bridged Adapter interface"),
                                                      HifName.raw());
            }

            hrc = hostInterface->COMGETTER(Id)(&str);
            if (FAILED(hrc))
            {
                LogRel(("NetworkAttachmentType_Bridged: COMGETTER(Id) failed, hrc (0x%x)", hrc));
                H();
            }
            Guid hostIFGuid(str);
            STR_FREE();

            INetCfg              *pNc;
            ComPtr<INetCfgComponent> pAdaptorComponent;
            LPWSTR                pszApp;
            int rc = VERR_INTNET_FLT_IF_NOT_FOUND;

            hrc = VBoxNetCfgWinQueryINetCfg(FALSE /*fGetWriteLock*/,
                                            L"VirtualBox",
                                            &pNc,
                                            &pszApp);
            Assert(hrc == S_OK);
            if (hrc == S_OK)
            {
                /* get the adapter's INetCfgComponent*/
                hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.ptr(), pAdaptorComponent.asOutParam());
                if (hrc != S_OK)
                {
                    VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
                    LogRel(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
                    H();
                }
            }
#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
            char szTrunkName[INTNET_MAX_TRUNK_NAME];
            char *pszTrunkName = szTrunkName;
            wchar_t * pswzBindName;
            hrc = pAdaptorComponent->GetBindName(&pswzBindName);
            Assert(hrc == S_OK);
            if (hrc == S_OK)
            {
                int cwBindName = (int)wcslen(pswzBindName) + 1;
                int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
                if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
                {
                    strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
                    pszTrunkName += cbFullBindNamePrefix-1;
                    if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
                                             sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
                    {
                        DWORD err = GetLastError();
                        hrc = HRESULT_FROM_WIN32(err);
                        AssertMsgFailed(("%hrc=%Rhrc %#x\n", hrc, hrc));
                        AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
                    }
                }
                else
                {
                    AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: insufficient szTrunkName buffer space\n"));
                    /** @todo set appropriate error code */
                    hrc = E_FAIL;
                }

                if (hrc != S_OK)
                {
                    AssertFailed();
                    CoTaskMemFree(pswzBindName);
                    VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
                    H();
                }

                /* we're not freeing the bind name since we'll use it later for detecting wireless*/
            }
            else
            {
                VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
                AssertLogRelMsgFailed(("NetworkAttachmentType_Bridged: VBoxNetCfgWinGetComponentByGuid failed, hrc (0x%x)", hrc));
                H();
            }
            const char *pszTrunk = szTrunkName;
            /* we're not releasing the INetCfg stuff here since we use it later to figure out whether it is wireless */

# elif defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
            /** @todo Check for malformed names. */
            const char *pszTrunk = pszHifName;

            /* Issue a warning if the interface is down */
            {
                int iSock = socket(AF_INET, SOCK_DGRAM, 0);
                if (iSock >= 0)
                {
                    struct ifreq Req;

                    memset(&Req, 0, sizeof(Req));
                    strncpy(Req.ifr_name, pszHifName, sizeof(Req.ifr_name) - 1);
                    if (ioctl(iSock, SIOCGIFFLAGS, &Req) >= 0)
                        if ((Req.ifr_flags & IFF_UP) == 0)
                        {
                            setVMRuntimeErrorCallbackF(pVM, pThis, 0, "BridgedInterfaceDown", "Bridged interface %s is down. Guest will not be able to use this interface", pszHifName);
                        }

                    close(iSock);
                }
            }

# else
#  error "PORTME (VBOX_WITH_NETFLT)"
# endif

            rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet");                    RC_CHECK();
            rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                         RC_CHECK();
            rc = CFGMR3InsertString(pCfg, "Trunk", pszTrunk);                       RC_CHECK();
            rc = CFGMR3InsertInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);
            RC_CHECK();
            char szNetwork[INTNET_MAX_NETWORK_NAME];
            RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHifName);
            rc = CFGMR3InsertString(pCfg, "Network", szNetwork);                    RC_CHECK();
            networkName = Bstr(szNetwork);
            trunkName = Bstr(pszTrunk);
            trunkType = Bstr(TRUNKTYPE_NETFLT);

# if defined(RT_OS_DARWIN)
            /** @todo Come up with a better deal here. Problem is that IHostNetworkInterface is completely useless here. */
            if (    strstr(pszHifName, "Wireless")
                ||  strstr(pszHifName, "AirPort" ))
            {
                rc = CFGMR3InsertInteger(pCfg, "SharedMacOnWire", true);            RC_CHECK();
            }
# elif defined(RT_OS_LINUX)
            int iSock = socket(AF_INET, SOCK_DGRAM, 0);
            if (iSock >= 0)
            {
                struct iwreq WRq;

                memset(&WRq, 0, sizeof(WRq));
                strncpy(WRq.ifr_name, pszHifName, IFNAMSIZ);
                bool fSharedMacOnWire = ioctl(iSock, SIOCGIWNAME, &WRq) >= 0;
                close(iSock);
                if (fSharedMacOnWire)
                {
                    rc = CFGMR3InsertInteger(pCfg, "SharedMacOnWire", true);
                    RC_CHECK();
                    Log(("Set SharedMacOnWire\n"));
                }
                else
                    Log(("Failed to get wireless name\n"));
            }
            else
                Log(("Failed to open wireless socket\n"));
# elif defined(RT_OS_WINDOWS)
#  define DEVNAME_PREFIX L"\\\\.\\"
            /* we are getting the medium type via IOCTL_NDIS_QUERY_GLOBAL_STATS Io Control
             * there is a pretty long way till there though since we need to obtain the symbolic link name
             * for the adapter device we are going to query given the device Guid */


            /* prepend the "\\\\.\\" to the bind name to obtain the link name */

            wchar_t FileName[MAX_PATH];
            wcscpy(FileName, DEVNAME_PREFIX);
            wcscpy((wchar_t*)(((char*)FileName) + sizeof(DEVNAME_PREFIX) - sizeof(FileName[0])), pswzBindName);

            /* open the device */
            HANDLE hDevice = CreateFile(FileName,
                                        GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
                                        NULL,
                                        OPEN_EXISTING,
                                        FILE_ATTRIBUTE_NORMAL,
                                        NULL);

            if (hDevice != INVALID_HANDLE_VALUE)
            {
                bool fSharedMacOnWire = false;

                /* now issue the OID_GEN_PHYSICAL_MEDIUM query */
                DWORD Oid = OID_GEN_PHYSICAL_MEDIUM;
                NDIS_PHYSICAL_MEDIUM PhMedium;
                DWORD cbResult;
                if (DeviceIoControl(hDevice,
                                    IOCTL_NDIS_QUERY_GLOBAL_STATS,
                                    &Oid,
                                    sizeof(Oid),
                                    &PhMedium,
                                    sizeof(PhMedium),
                                    &cbResult,
                                    NULL))
                {
                    /* that was simple, now examine PhMedium */
                    if (   PhMedium == NdisPhysicalMediumWirelessWan
                        || PhMedium == NdisPhysicalMediumWirelessLan
                        || PhMedium == NdisPhysicalMediumNative802_11
                        || PhMedium == NdisPhysicalMediumBluetooth)
                        fSharedMacOnWire = true;
                }
                else
                {
                    int winEr = GetLastError();
                    LogRel(("Console::configConstructor: DeviceIoControl failed, err (0x%x), ignoring\n", winEr));
                    Assert(winEr == ERROR_INVALID_PARAMETER || winEr == ERROR_NOT_SUPPORTED || winEr == ERROR_BAD_COMMAND);
                }
                CloseHandle(hDevice);

                if (fSharedMacOnWire)
                {
                    Log(("this is a wireless adapter"));
                    rc = CFGMR3InsertInteger(pCfg, "SharedMacOnWire", true); RC_CHECK();
                    Log(("Set SharedMacOnWire\n"));
                }
                else
                    Log(("this is NOT a wireless adapter"));
            }
            else
            {
                int winEr = GetLastError();
                AssertLogRelMsgFailed(("Console::configConstructor: CreateFile failed, err (0x%x), ignoring\n", winEr));
            }

            CoTaskMemFree(pswzBindName);

            pAdaptorComponent.setNull();
            /* release the pNc finally */
            VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
# else
            /** @todo PORTME: wireless detection */
# endif

# if defined(RT_OS_SOLARIS)
#  if 0 /* bird: this is a bit questionable and might cause more trouble than its worth.  */
            /* Zone access restriction, don't allow snopping the global zone. */
            zoneid_t ZoneId = getzoneid();
            if (ZoneId != GLOBAL_ZONEID)
            {
                rc = CFGMR3InsertInteger(pCfg, "IgnoreAllPromisc", true);   RC_CHECK();
            }
#  endif
# endif

#elif defined(RT_OS_WINDOWS) /* not defined NetFlt */
            /* NOTHING TO DO HERE */
#elif defined(RT_OS_LINUX)
/// @todo aleksey: is there anything to be done here?
#elif defined(RT_OS_FREEBSD)
/** @todo FreeBSD: Check out this later (HIF networking). */
#else
# error "Port me"
#endif
            break;
        }

        case NetworkAttachmentType_Internal:
        {
            hrc = aNetworkAdapter->COMGETTER(InternalNetwork)(&str);    H();
            if (str && *str)
            {
                if (fSniffer)
                {
                    rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0);
                    RC_CHECK();
                }
                else
                {
                    rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);
                    RC_CHECK();
                }
                rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet");    RC_CHECK();
                rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);         RC_CHECK();
                rc = CFGMR3InsertStringW(pCfg, "Network", str);         RC_CHECK();
                rc = CFGMR3InsertInteger(pCfg, "TrunkType", kIntNetTrunkType_WhateverNone); RC_CHECK();
                networkName = str;
                trunkType = Bstr(TRUNKTYPE_WHATEVER);
            }
            STR_FREE();
            break;
        }

        case NetworkAttachmentType_HostOnly:
        {
            if (fSniffer)
            {
                rc = CFGMR3InsertNode(pLunL0, "AttachedDriver", &pLunL0);
                RC_CHECK();
            }
            else
            {
                rc = CFGMR3InsertNode(pInst, "LUN#0", &pLunL0);
                RC_CHECK();
            }

            rc = CFGMR3InsertString(pLunL0, "Driver", "IntNet");            RC_CHECK();
            rc = CFGMR3InsertNode(pLunL0, "Config", &pCfg);                 RC_CHECK();

            Bstr HifName;
            hrc = aNetworkAdapter->COMGETTER(HostInterface)(HifName.asOutParam());
            if (FAILED(hrc))
            {
                LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(HostInterface) failed, hrc (0x%x)\n", hrc));
                H();
            }

            Utf8Str HifNameUtf8(HifName);
            const char *pszHifName = HifNameUtf8.raw();
            ComPtr<IHostNetworkInterface> hostInterface;
            rc = host->FindHostNetworkInterfaceByName(HifName, hostInterface.asOutParam());
            if (!SUCCEEDED(rc))
            {
                LogRel(("NetworkAttachmentType_HostOnly: FindByName failed, rc (0x%x)\n", rc));
                return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
                                  N_("Inexistent host networking interface, name '%ls'"),
                                  HifName.raw());
            }

            char szNetwork[INTNET_MAX_NETWORK_NAME];
            RTStrPrintf(szNetwork, sizeof(szNetwork), "HostInterfaceNetworking-%s", pszHifName);

#if defined(RT_OS_WINDOWS)
# ifndef VBOX_WITH_NETFLT
            hrc = E_NOTIMPL;
            LogRel(("NetworkAttachmentType_HostOnly: Not Implemented\n"));
            H();
# else  /* defined VBOX_WITH_NETFLT*/
            /** @todo r=bird: Put this in a function. */

            HostNetworkInterfaceType_T eIfType;
            hrc = hostInterface->COMGETTER(InterfaceType)(&eIfType);
            if (FAILED(hrc))
            {
                LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(InterfaceType) failed, hrc (0x%x)\n", hrc));
                H();
            }

            if (eIfType != HostNetworkInterfaceType_HostOnly)
                return VMSetError(pVM, VERR_INTERNAL_ERROR, RT_SRC_POS,
                                  N_("Interface ('%ls') is not a Host-Only Adapter interface"),
                                  HifName.raw());

            hrc = hostInterface->COMGETTER(Id)(&str);
            if (FAILED(hrc))
            {
                LogRel(("NetworkAttachmentType_HostOnly: COMGETTER(Id) failed, hrc (0x%x)\n", hrc));
                H();
            }
            Guid hostIFGuid(str);
            STR_FREE();

            INetCfg *pNc;
            ComPtr<INetCfgComponent> pAdaptorComponent;
            LPWSTR pszApp;
            rc = VERR_INTNET_FLT_IF_NOT_FOUND;

            hrc = VBoxNetCfgWinQueryINetCfg(FALSE,
                                            L"VirtualBox",
                                            &pNc,
                                            &pszApp);
            Assert(hrc == S_OK);
            if (hrc == S_OK)
            {
                /* get the adapter's INetCfgComponent*/
                hrc = VBoxNetCfgWinGetComponentByGuid(pNc, &GUID_DEVCLASS_NET, (GUID*)hostIFGuid.ptr(), pAdaptorComponent.asOutParam());
                if (hrc != S_OK)
                {
                    VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
                    LogRel(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
                    H();
                }
            }
#define VBOX_WIN_BINDNAME_PREFIX "\\DEVICE\\"
            char szTrunkName[INTNET_MAX_TRUNK_NAME];
            char *pszTrunkName = szTrunkName;
            wchar_t * pswzBindName;
            hrc = pAdaptorComponent->GetBindName(&pswzBindName);
            Assert(hrc == S_OK);
            if (hrc == S_OK)
            {
                int cwBindName = (int)wcslen(pswzBindName) + 1;
                int cbFullBindNamePrefix = sizeof(VBOX_WIN_BINDNAME_PREFIX);
                if (sizeof(szTrunkName) > cbFullBindNamePrefix + cwBindName)
                {
                    strcpy(szTrunkName, VBOX_WIN_BINDNAME_PREFIX);
                    pszTrunkName += cbFullBindNamePrefix-1;
                    if (!WideCharToMultiByte(CP_ACP, 0, pswzBindName, cwBindName, pszTrunkName,
                                             sizeof(szTrunkName) - cbFullBindNamePrefix + 1, NULL, NULL))
                    {
                        DWORD err = GetLastError();
                        hrc = HRESULT_FROM_WIN32(err);
                        AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: WideCharToMultiByte failed, hr=%Rhrc (0x%x) err=%u\n", hrc, hrc, err));
                    }
                }
                else
                {
                    AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: insufficient szTrunkName buffer space\n"));
                    /** @todo set appropriate error code */
                    hrc = E_FAIL;
                }

                if (hrc != S_OK)
                {
                    AssertFailed();
                    CoTaskMemFree(pswzBindName);
                    VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
                    H();
                }
            }
            else
            {
                VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);
                AssertLogRelMsgFailed(("NetworkAttachmentType_HostOnly: VBoxNetCfgWinGetComponentByGuid failed, hrc=%Rhrc (0x%x)\n", hrc, hrc));
                H();
            }


            CoTaskMemFree(pswzBindName);

            pAdaptorComponent.setNull();
            /* release the pNc finally */
            VBoxNetCfgWinReleaseINetCfg(pNc, FALSE /*fHasWriteLock*/);

            const char *pszTrunk = szTrunkName;

            rc = CFGMR3InsertInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);   RC_CHECK();
            rc = CFGMR3InsertString(pCfg, "Trunk", pszTrunk);                       RC_CHECK();
            rc = CFGMR3InsertString(pCfg, "Network", szNetwork);                    RC_CHECK();
            networkName = Bstr(szNetwork);
            trunkName   = Bstr(pszTrunk);
            trunkType   = TRUNKTYPE_NETADP;
# endif /* defined VBOX_WITH_NETFLT*/
#elif defined(RT_OS_DARWIN)
            rc = CFGMR3InsertString(pCfg, "Trunk", pszHifName);                     RC_CHECK();
            rc = CFGMR3InsertString(pCfg, "Network", szNetwork);                    RC_CHECK();
            rc = CFGMR3InsertInteger(pCfg, "TrunkType", kIntNetTrunkType_NetAdp);   RC_CHECK();
            networkName = Bstr(szNetwork);
            trunkName   = Bstr(pszHifName);
            trunkType   = TRUNKTYPE_NETADP;
#else
            rc = CFGMR3InsertString(pCfg, "Trunk", pszHifName);                     RC_CHECK();
            rc = CFGMR3InsertString(pCfg, "Network", szNetwork);                    RC_CHECK();
            rc = CFGMR3InsertInteger(pCfg, "TrunkType", kIntNetTrunkType_NetFlt);   RC_CHECK();
            networkName = Bstr(szNetwork);
            trunkName   = Bstr(pszHifName);
            trunkType   = TRUNKTYPE_NETFLT;
#endif
#if !defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)

            Bstr tmpAddr, tmpMask;

            hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPAddress", pszHifName), tmpAddr.asOutParam());
            if (SUCCEEDED(hrc) && !tmpAddr.isEmpty())
            {
                hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPNetMask", pszHifName), tmpMask.asOutParam());
                if (SUCCEEDED(hrc) && !tmpMask.isEmpty())
                    hrc = hostInterface->EnableStaticIpConfig(tmpAddr, tmpMask);
                else
                    hrc = hostInterface->EnableStaticIpConfig(tmpAddr,
                                                              Bstr(VBOXNET_IPV4MASK_DEFAULT));
            }
            else
                hrc = hostInterface->EnableStaticIpConfig(Bstr(VBOXNET_IPV4ADDR_DEFAULT),
                                                          Bstr(VBOXNET_IPV4MASK_DEFAULT));
            ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */

            hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6Address", pszHifName), tmpAddr.asOutParam());
            if (SUCCEEDED(hrc))
                hrc = virtualBox->GetExtraData(BstrFmt("HostOnly/%s/IPV6NetMask", pszHifName), tmpMask.asOutParam());
            if (SUCCEEDED(hrc) && !tmpAddr.isEmpty() && !tmpMask.isEmpty())
            {
                hrc = hostInterface->EnableStaticIpConfigV6(tmpAddr, Utf8Str(tmpMask).toUInt32());
                ComAssertComRC(hrc); /** @todo r=bird: Why this isn't fatal? (H()) */
            }
#endif
            break;
        }

        default:
            AssertMsgFailed(("should not get here!\n"));
            break;
    }

    /*
     * Attempt to attach the driver.
     */
    switch (eAttachmentType)
    {
        case NetworkAttachmentType_Null:
            break;

        case NetworkAttachmentType_Bridged:
        case NetworkAttachmentType_Internal:
        case NetworkAttachmentType_HostOnly:
        case NetworkAttachmentType_NAT:
        {
            if (SUCCEEDED(hrc) && SUCCEEDED(rc))
            {
                if (fAttachDetach)
                {
                    rc = PDMR3DriverAttach(pVM, pszDevice, uInstance, uLun, 0 /*fFlags*/, NULL /* ppBase */);
                    //AssertRC(rc);
                }

                {
                    /** @todo pritesh: get the dhcp server name from the
                     * previous network configuration and then stop the server
                     * else it may conflict with the dhcp server running  with
                     * the current attachment type
                     */
                    /* Stop the hostonly DHCP Server */
                }

                if (!networkName.isNull())
                {
                    /*
                     * Until we implement service reference counters DHCP Server will be stopped
                     * by DHCPServerRunner destructor.
                     */
                    ComPtr<IDHCPServer> dhcpServer;
                    hrc = virtualBox->FindDHCPServerByNetworkName(networkName.mutableRaw(), dhcpServer.asOutParam());
                    if (SUCCEEDED(hrc))
                    {
                        /* there is a DHCP server available for this network */
                        BOOL fEnabled;
                        hrc = dhcpServer->COMGETTER(Enabled)(&fEnabled);
                        if (FAILED(hrc))
                        {
                            LogRel(("DHCP svr: COMGETTER(Enabled) failed, hrc (%Rhrc)", hrc));
                            H();
                        }

                        if (fEnabled)
                            hrc = dhcpServer->Start(networkName, trunkName, trunkType);
                    }
                    else
                        hrc = S_OK;
                }
            }

            break;
        }

        default:
            AssertMsgFailed(("should not get here!\n"));
            break;
    }

    pThis->meAttachmentType[uInstance] = eAttachmentType;

#undef STR_FREE
#undef H
#undef RC_CHECK

    return VINF_SUCCESS;
}

#ifdef VBOX_WITH_GUEST_PROPS
/**
 * Set an array of guest properties
 */
static void configSetProperties(VMMDev * const pVMMDev, void *names,
                                void *values, void *timestamps, void *flags)
{
    VBOXHGCMSVCPARM parms[4];

    parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[0].u.pointer.addr = names;
    parms[0].u.pointer.size = 0;  /* We don't actually care. */
    parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[1].u.pointer.addr = values;
    parms[1].u.pointer.size = 0;  /* We don't actually care. */
    parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[2].u.pointer.addr = timestamps;
    parms[2].u.pointer.size = 0;  /* We don't actually care. */
    parms[3].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[3].u.pointer.addr = flags;
    parms[3].u.pointer.size = 0;  /* We don't actually care. */

    pVMMDev->hgcmHostCall ("VBoxGuestPropSvc", guestProp::SET_PROPS_HOST, 4,
                           &parms[0]);
}

/**
 * Set a single guest property
 */
static void configSetProperty(VMMDev * const pVMMDev, const char *pszName,
                              const char *pszValue, const char *pszFlags)
{
    VBOXHGCMSVCPARM parms[4];

    AssertPtrReturnVoid(pszName);
    AssertPtrReturnVoid(pszValue);
    AssertPtrReturnVoid(pszFlags);
    parms[0].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[0].u.pointer.addr = (void *)pszName;
    parms[0].u.pointer.size = strlen(pszName) + 1;
    parms[1].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[1].u.pointer.addr = (void *)pszValue;
    parms[1].u.pointer.size = strlen(pszValue) + 1;
    parms[2].type = VBOX_HGCM_SVC_PARM_PTR;
    parms[2].u.pointer.addr = (void *)pszFlags;
    parms[2].u.pointer.size = strlen(pszFlags) + 1;
    pVMMDev->hgcmHostCall ("VBoxGuestPropSvc", guestProp::SET_PROP_HOST, 3,
                           &parms[0]);
}

/**
 * Set the global flags value by calling the service
 * @returns the status returned by the call to the service
 *
 * @param   pTable  the service instance handle
 * @param   eFlags  the flags to set
 */
int configSetGlobalPropertyFlags(VMMDev * const pVMMDev,
                                 guestProp::ePropFlags eFlags)
{
    VBOXHGCMSVCPARM paParm;
    paParm.setUInt32(eFlags);
    int rc = pVMMDev->hgcmHostCall ("VBoxGuestPropSvc",
                                    guestProp::SET_GLOBAL_FLAGS_HOST, 1,
                                    &paParm);
    if (RT_FAILURE(rc))
    {
        char szFlags[guestProp::MAX_FLAGS_LEN];
        if (RT_FAILURE(writeFlags(eFlags, szFlags)))
            Log(("Failed to set the global flags.\n"));
        else
            Log(("Failed to set the global flags \"%s\".\n", szFlags));
    }
    return rc;
}
#endif /* VBOX_WITH_GUEST_PROPS */

/**
 * Set up the Guest Property service, populate it with properties read from
 * the machine XML and set a couple of initial properties.
 */
/* static */ int Console::configGuestProperties(void *pvConsole)
{
#ifdef VBOX_WITH_GUEST_PROPS
    AssertReturn(pvConsole, VERR_GENERAL_FAILURE);
    ComObjPtr<Console> pConsole = static_cast <Console *> (pvConsole);

    /* Load the service */
    int rc = pConsole->mVMMDev->hgcmLoadService ("VBoxGuestPropSvc", "VBoxGuestPropSvc");

    if (RT_FAILURE(rc))
    {
        LogRel(("VBoxGuestPropSvc is not available. rc = %Rrc\n", rc));
        /* That is not a fatal failure. */
        rc = VINF_SUCCESS;
    }
    else
    {
        /*
         * Initialize built-in properties that can be changed and saved.
         *
         * These are typically transient properties that the guest cannot
         * change.
         */

        /* Sysprep execution by VBoxService. */
        configSetProperty(pConsole->mVMMDev,
                          "/VirtualBox/HostGuest/SysprepExec", "",
                          "TRANSIENT, RDONLYGUEST");
        configSetProperty(pConsole->mVMMDev,
                          "/VirtualBox/HostGuest/SysprepArgs", "",
                          "TRANSIENT, RDONLYGUEST");

        /*
         * Pull over the properties from the server.
         */
        SafeArray<BSTR> namesOut;
        SafeArray<BSTR> valuesOut;
        SafeArray<ULONG64> timestampsOut;
        SafeArray<BSTR> flagsOut;
        HRESULT hrc;
        hrc = pConsole->mControl->PullGuestProperties(ComSafeArrayAsOutParam(namesOut),
                                                      ComSafeArrayAsOutParam(valuesOut),
                                                      ComSafeArrayAsOutParam(timestampsOut),
                                                      ComSafeArrayAsOutParam(flagsOut));
        AssertMsgReturn(SUCCEEDED(hrc), ("hrc=%Rrc\n", hrc), VERR_GENERAL_FAILURE);
        size_t cProps = namesOut.size();
        size_t cAlloc = cProps + 1;
        if (   valuesOut.size() != cProps
            || timestampsOut.size() != cProps
            || flagsOut.size() != cProps
           )
            AssertFailedReturn(VERR_INVALID_PARAMETER);

        char **papszNames, **papszValues, **papszFlags;
        char szEmpty[] = "";
        ULONG64 *pau64Timestamps;
        papszNames = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
        papszValues = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
        pau64Timestamps = (ULONG64 *)RTMemTmpAllocZ(sizeof(ULONG64) * cAlloc);
        papszFlags = (char **)RTMemTmpAllocZ(sizeof(void *) * cAlloc);
        if (papszNames && papszValues && pau64Timestamps && papszFlags)
        {
            for (unsigned i = 0; RT_SUCCESS(rc) && i < cProps; ++i)
            {
                AssertPtrReturn(namesOut[i], VERR_INVALID_PARAMETER);
                rc = RTUtf16ToUtf8(namesOut[i], &papszNames[i]);
                if (RT_FAILURE(rc))
                    break;
                if (valuesOut[i])
                    rc = RTUtf16ToUtf8(valuesOut[i], &papszValues[i]);
                else
                    papszValues[i] = szEmpty;
                if (RT_FAILURE(rc))
                    break;
                pau64Timestamps[i] = timestampsOut[i];
                if (flagsOut[i])
                    rc = RTUtf16ToUtf8(flagsOut[i], &papszFlags[i]);
                else
                    papszFlags[i] = szEmpty;
            }
            if (RT_SUCCESS(rc))
                configSetProperties(pConsole->mVMMDev,
                                    (void *)papszNames,
                                    (void *)papszValues,
                                    (void *)pau64Timestamps,
                                    (void *)papszFlags);
            for (unsigned i = 0; i < cProps; ++i)
            {
                RTStrFree(papszNames[i]);
                if (valuesOut[i])
                    RTStrFree(papszValues[i]);
                if (flagsOut[i])
                    RTStrFree(papszFlags[i]);
            }
        }
        else
            rc = VERR_NO_MEMORY;
        RTMemTmpFree(papszNames);
        RTMemTmpFree(papszValues);
        RTMemTmpFree(pau64Timestamps);
        RTMemTmpFree(papszFlags);
        AssertRCReturn(rc, rc);

        /*
         * These properties have to be set before pulling over the properties
         * from the machine XML, to ensure that properties saved in the XML
         * will override them.
         */
        /* Set the VBox version string as a guest property */
        configSetProperty(pConsole->mVMMDev, "/VirtualBox/HostInfo/VBoxVer",
                          VBOX_VERSION_STRING, "TRANSIENT, RDONLYGUEST");
        /* Set the VBox SVN revision as a guest property */
        configSetProperty(pConsole->mVMMDev, "/VirtualBox/HostInfo/VBoxRev",
                          RTBldCfgRevisionStr(), "TRANSIENT, RDONLYGUEST");

        /*
         * Register the host notification callback
         */
        HGCMSVCEXTHANDLE hDummy;
        HGCMHostRegisterServiceExtension(&hDummy, "VBoxGuestPropSvc",
                                         Console::doGuestPropNotification,
                                         pvConsole);

#ifdef VBOX_WITH_GUEST_PROPS_RDONLY_GUEST
        rc = configSetGlobalPropertyFlags(pConsole->mVMMDev,
                                          guestProp::RDONLYGUEST);
        AssertRCReturn(rc, rc);
#endif

        Log(("Set VBoxGuestPropSvc property store\n"));
    }
    return VINF_SUCCESS;
#else /* !VBOX_WITH_GUEST_PROPS */
    return VERR_NOT_SUPPORTED;
#endif /* !VBOX_WITH_GUEST_PROPS */
}