summaryrefslogtreecommitdiff
path: root/src/VBox/Debugger/DBGPlugInLinux.cpp
blob: 14377c109ae0d0e0f650cf7acccda911363b58bb (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
/* $Id$ */
/** @file
 * DBGPlugInLinux - Debugger and Guest OS Digger Plugin For Linux.
 */

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


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DBGF /// @todo add new log group.
#include "DBGPlugIns.h"
#include "DBGPlugInCommonELF.h"
#include <VBox/vmm/vmmr3vtable.h>
#include <VBox/dis.h>
#include <iprt/ctype.h>
#include <iprt/file.h>
#include <iprt/err.h>
#include <iprt/mem.h>
#include <iprt/stream.h>
#include <iprt/string.h>
#include <iprt/vfs.h>
#include <iprt/zip.h>


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/

/** @name InternalLinux structures
 * @{ */


/** @} */


/**
 * Config item type.
 */
typedef enum DBGDIGGERLINUXCFGITEMTYPE
{
    /** Invalid type. */
    DBGDIGGERLINUXCFGITEMTYPE_INVALID = 0,
    /** String. */
    DBGDIGGERLINUXCFGITEMTYPE_STRING,
    /** Number. */
    DBGDIGGERLINUXCFGITEMTYPE_NUMBER,
    /** Flag whether this feature is included in the
     * kernel or as a module. */
    DBGDIGGERLINUXCFGITEMTYPE_FLAG
} DBGDIGGERLINUXCFGITEMTYPE;

/**
 * Item in the config database.
 */
typedef struct DBGDIGGERLINUXCFGITEM
{
    /** String space core. */
    RTSTRSPACECORE            Core;
    /** Config item type. */
    DBGDIGGERLINUXCFGITEMTYPE enmType;
    /** Data based on the type. */
    union
    {
        /** Number. */
        int64_t               i64Num;
        /** Flag. */
        bool                  fModule;
        /** String - variable in size. */
        char                  aszString[1];
    } u;
} DBGDIGGERLINUXCFGITEM;
/** Pointer to a config database item. */
typedef DBGDIGGERLINUXCFGITEM *PDBGDIGGERLINUXCFGITEM;
/** Pointer to a const config database item. */
typedef const DBGDIGGERLINUXCFGITEM *PCDBGDIGGERLINUXCFGITEM;

/**
 * Linux guest OS digger instance data.
 */
typedef struct DBGDIGGERLINUX
{
    /** Whether the information is valid or not.
     * (For fending off illegal interface method calls.) */
    bool fValid;
    /** Set if 64-bit, clear if 32-bit.  */
    bool f64Bit;
    /** Set if the kallsyms table uses relative addressing, clear
     * if absolute addresses are used. */
    bool fRelKrnlAddr;
    /** The relative base when kernel symbols use offsets rather than
     * absolute addresses. */
    RTGCUINTPTR uKernelRelativeBase;
    /** The guest kernel version used for version comparisons. */
    uint32_t    uKrnlVer;
    /** The guest kernel major version. */
    uint32_t    uKrnlVerMaj;
    /** The guest kernel minor version. */
    uint32_t    uKrnlVerMin;
    /** The guest kernel build version. */
    uint32_t    uKrnlVerBld;

    /** The address of the linux banner.
     * This is set during probing. */
    DBGFADDRESS AddrLinuxBanner;
    /** Kernel base address.
     * This is set during probing, refined during kallsyms parsing. */
    DBGFADDRESS AddrKernelBase;
    /** The kernel size.   */
    uint32_t    cbKernel;

    /** The number of kernel symbols (kallsyms_num_syms).
     * This is set during init.  */
    uint32_t   cKernelSymbols;
    /** The size of the kernel name table (sizeof(kallsyms_names)).   */
    uint32_t   cbKernelNames;
    /** Number of entries in the kernel_markers table. */
    uint32_t   cKernelNameMarkers;
    /** The size of the kernel symbol token table. */
    uint32_t   cbKernelTokenTable;
    /** The address of the encoded kernel symbol names (kallsyms_names). */
    DBGFADDRESS AddrKernelNames;
    /** The address of the kernel symbol addresses (kallsyms_addresses). */
    DBGFADDRESS AddrKernelAddresses;
    /** The address of the kernel symbol name markers (kallsyms_markers). */
    DBGFADDRESS AddrKernelNameMarkers;
    /** The address of the kernel symbol token table (kallsyms_token_table). */
    DBGFADDRESS AddrKernelTokenTable;
    /** The address of the kernel symbol token index table (kallsyms_token_index). */
    DBGFADDRESS AddrKernelTokenIndex;

    /** The kernel message log interface. */
    DBGFOSIDMESG    IDmesg;

    /** The config database root. */
    RTSTRSPACE      hCfgDb;
} DBGDIGGERLINUX;
/** Pointer to the linux guest OS digger instance data. */
typedef DBGDIGGERLINUX *PDBGDIGGERLINUX;


/**
 * The current printk_log structure.
 */
typedef struct LNXPRINTKHDR
{
    /** Monotonic timestamp. */
    uint64_t nsTimestamp;
    /** The total size of this message record. */
    uint16_t cbTotal;
    /** The size of the text part (immediately follows the header). */
    uint16_t cbText;
    /** The size of the optional dictionary part (follows the text). */
    uint16_t cbDict;
    /** The syslog facility number. */
    uint8_t  bFacility;
    /** First 5 bits are internal flags, next 3 bits are log level. */
    uint8_t  fFlagsAndLevel;
} LNXPRINTKHDR;
AssertCompileSize(LNXPRINTKHDR, 2*sizeof(uint64_t));
/** Pointer to linux printk_log header. */
typedef LNXPRINTKHDR *PLNXPRINTKHDR;
/** Pointer to linux const printk_log header. */
typedef LNXPRINTKHDR const *PCLNXPRINTKHDR;


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** First kernel map address for 32bit Linux hosts (__START_KERNEL_map). */
#define LNX32_KERNEL_ADDRESS_START      UINT32_C(0xc0000000)
/** First kernel map address for 64bit Linux hosts (__START_KERNEL_map). */
#define LNX64_KERNEL_ADDRESS_START      UINT64_C(0xffffffff80000000)
/** Validates a 32-bit linux kernel address */
#define LNX32_VALID_ADDRESS(Addr)       ((Addr) > UINT32_C(0x80000000) && (Addr) < UINT32_C(0xfffff000))
/** Validates a 64-bit linux kernel address */
#define LNX64_VALID_ADDRESS(Addr)       ((Addr) > UINT64_C(0xffff800000000000) && (Addr) < UINT64_C(0xfffffffffffff000))

/** The max kernel size. */
#define LNX_MAX_KERNEL_SIZE                 UINT32_C(0x0f000000)
/** Maximum kernel log buffer size. */
#define LNX_MAX_KERNEL_LOG_SIZE             (16 * _1M)

/** The maximum size we expect for kallsyms_names. */
#define LNX_MAX_KALLSYMS_NAMES_SIZE         UINT32_C(0x200000)
/** The maximum size we expect for kallsyms_token_table. */
#define LNX_MAX_KALLSYMS_TOKEN_TABLE_SIZE   UINT32_C(0x10000)
/** The minimum number of symbols we expect in kallsyms_num_syms. */
#define LNX_MIN_KALLSYMS_SYMBOLS            UINT32_C(2048)
/** The maximum number of symbols we expect in kallsyms_num_syms. */
#define LNX_MAX_KALLSYMS_SYMBOLS            UINT32_C(1048576)
/** The min length an encoded symbol in kallsyms_names is expected to have. */
#define LNX_MIN_KALLSYMS_ENC_LENGTH         UINT8_C(1)
/** The max length an encoded symbol in kallsyms_names is expected to have.
 * @todo check real life here.  */
#define LNX_MAX_KALLSYMS_ENC_LENGTH         UINT8_C(28)
/** The approximate maximum length of a string token. */
#define LNX_MAX_KALLSYMS_TOKEN_LEN          UINT16_C(32)
/** Maximum compressed config size expected. */
#define LNX_MAX_COMPRESSED_CFG_SIZE         _1M

/** Module tag for linux ('linuxmod' on little endian ASCII systems). */
#define DIG_LNX_MOD_TAG                     UINT64_C(0x545f5d78758e898c)
/** Macro for building a Linux kernel version which can be used for comparisons. */
#define LNX_MK_VER(major, minor, build)     (((major) << 22) | ((minor) << 12) | (build))


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static DECLCALLBACK(int)  dbgDiggerLinuxInit(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData);


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** Table of common linux kernel addresses. */
static uint64_t g_au64LnxKernelAddresses[] =
{
    UINT64_C(0xc0100000),
    UINT64_C(0x90100000),
    UINT64_C(0xffffffff80200000)
};

static const uint8_t g_abLinuxVersion[] = "Linux version ";
/** The needle for searching for the kernel log area (the value is observed in pretty much all 32bit and 64bit x86 kernels).
 * This needle should appear only once in the memory due to the address being filled in by a format string. */
static const uint8_t g_abKrnlLogNeedle[] = "BIOS-e820: [mem 0x0000000000000000";


/**
 * Tries to resolve the kernel log buffer start and end by searching for needle.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pGCPtrLogBuf        Where to store the start of the kernel log buffer on success.
 * @param   pcbLogBuf           Where to store the size of the kernel log buffer on success.
 */
static int dbgDiggerLinuxKrnlLogBufFindByNeedle(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
                                                RTGCPTR *pGCPtrLogBuf, uint32_t *pcbLogBuf)
{
    int rc = VINF_SUCCESS;

    /* Try to find the needle, it should be very early in the kernel log buffer. */
    DBGFADDRESS AddrScan;
    DBGFADDRESS AddrHit;
    pVMM->pfnDBGFR3AddrFromFlat(pUVM, &AddrScan, pThis->f64Bit ? LNX64_KERNEL_ADDRESS_START : LNX32_KERNEL_ADDRESS_START);

    rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &AddrScan, ~(RTGCUINTPTR)0, 1 /*uAlign*/,
                                g_abKrnlLogNeedle, sizeof(g_abKrnlLogNeedle) - 1, &AddrHit);
    if (RT_SUCCESS(rc))
    {
        uint32_t cbLogBuf = 0;
        uint64_t tsLastNs = 0;
        DBGFADDRESS AddrCur;

        pVMM->pfnDBGFR3AddrSub(&AddrHit, sizeof(LNXPRINTKHDR));
        AddrCur = AddrHit;

        /* Try to find the end of the kernel log buffer. */
        for (;;)
        {
            if (cbLogBuf >= LNX_MAX_KERNEL_LOG_SIZE)
                break;

            LNXPRINTKHDR Hdr;
            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &AddrCur, &Hdr, sizeof(Hdr));
            if (RT_SUCCESS(rc))
            {
                uint32_t const cbLogAlign = 4;

                /*
                 * If the header does not look valid anymore we stop.
                 * Timestamps are monotonically increasing.
                 */
                if (   !Hdr.cbTotal /* Zero entry size means there is no record anymore, doesn't make sense to look futher. */
                    || Hdr.cbText + Hdr.cbDict + sizeof(Hdr) > Hdr.cbTotal
                    || (Hdr.cbTotal & (cbLogAlign - 1)) != 0
                    || tsLastNs > Hdr.nsTimestamp)
                    break;

                /** @todo Maybe read text part and verify it is all ASCII. */

                cbLogBuf += Hdr.cbTotal;
                pVMM->pfnDBGFR3AddrAdd(&AddrCur, Hdr.cbTotal);
            }

            if (RT_FAILURE(rc))
                break;
        }

        /** @todo Go back to find the start address of the kernel log (or we loose potential kernel log messages). */

        if (   RT_SUCCESS(rc)
            && cbLogBuf)
        {
            /* Align log buffer size to a power of two. */
            uint32_t idxBitLast = ASMBitLastSetU32(cbLogBuf);
            idxBitLast--; /* There is at least one bit set, see check above. */

            if (cbLogBuf & (RT_BIT_32(idxBitLast) - 1))
                idxBitLast++;

            *pGCPtrLogBuf = AddrHit.FlatPtr;
            *pcbLogBuf    = RT_MIN(RT_BIT_32(idxBitLast), LNX_MAX_KERNEL_LOG_SIZE);
        }
        else if (RT_SUCCESS(rc))
            rc = VERR_NOT_FOUND;
    }

    return rc;
}


/**
 * Converts a given offset into an absolute address if relative kernel offsets are used for
 * kallsyms.
 *
 * @returns The absolute kernel address.
 * @param   pThis               The Linux digger data.
 * @param   uOffset             The offset to convert.
 */
DECLINLINE(RTGCUINTPTR) dbgDiggerLinuxConvOffsetToAddr(PDBGDIGGERLINUX pThis, int32_t uOffset)
{
    RTGCUINTPTR uAddr;

    /*
     * How the absolute address is calculated from the offset depends on the
     * CONFIG_KALLSYMS_ABSOLUTE_PERCPU config which is only set for 64bit
     * SMP kernels (we assume that all 64bit kernels always have SMP enabled too).
     */
    if (pThis->f64Bit)
    {
        if (uOffset >= 0)
            uAddr = uOffset;
        else
            uAddr = pThis->uKernelRelativeBase - 1 - uOffset;
    }
    else
        uAddr = pThis->uKernelRelativeBase + (uint32_t)uOffset;

    return uAddr;
}

/**
 * Disassembles a simple getter returning the value for it.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The VM handle.
 * @param   pVMM                The VMM function table.
 * @param   hMod                The module to use.
 * @param   pszSymbol           The symbol of the getter.
 * @param   pvVal               Where to store the value on success.
 * @param   cbVal               Size of the value in bytes.
 */
static int dbgDiggerLinuxDisassembleSimpleGetter(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, RTDBGMOD hMod,
                                                 const char *pszSymbol, void *pvVal, uint32_t cbVal)
{
    int rc = VINF_SUCCESS;

    RTDBGSYMBOL SymInfo;
    rc = RTDbgModSymbolByName(hMod, pszSymbol, &SymInfo);
    if (RT_SUCCESS(rc))
    {
        /*
         * Do the diassembling. Disassemble until a ret instruction is encountered
         * or a limit is reached (don't want to disassemble for too long as the getter
         * should be short).
         * push and pop instructions are skipped as well as any mov instructions not
         * touching the rax or eax register (depending on the size of the value).
         */
        unsigned cInstrDisassembled = 0;
        uint32_t offInstr = 0;
        bool fRet = false;
        DISSTATE DisState;
        RT_ZERO(DisState);

        do
        {
            DBGFADDRESS Addr;
            RTGCPTR GCPtrCur = (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr + offInstr;
            pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, GCPtrCur);

            /* Prefetch the instruction. */
            uint8_t abInstr[32];
            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &abInstr[0], sizeof(abInstr));
            if (RT_SUCCESS(rc))
            {
                uint32_t cbInstr = 0;

                rc = DISInstr(&abInstr[0], pThis->f64Bit ? DISCPUMODE_64BIT : DISCPUMODE_32BIT, &DisState, &cbInstr);
                if (RT_SUCCESS(rc))
                {
                    switch (DisState.pCurInstr->uOpcode)
                    {
                        case OP_PUSH:
                        case OP_POP:
                        case OP_NOP:
                        case OP_LEA:
                            break;
                        case OP_RETN:
                            /* Getter returned, abort disassembling. */
                            fRet = true;
                            break;
                        case OP_MOV:
                            /*
                             * Check that the destination is either rax or eax depending on the
                             * value size.
                             *
                             * Param1 is the destination and Param2 the source.
                             */
                            if (   (   (   (DisState.Param1.fUse & (DISUSE_BASE | DISUSE_REG_GEN32))
                                        && cbVal == sizeof(uint32_t))
                                    || (    (DisState.Param1.fUse & (DISUSE_BASE | DISUSE_REG_GEN64))
                                         && cbVal == sizeof(uint64_t)))
                                && DisState.Param1.arch.x86.Base.idxGenReg == DISGREG_RAX)
                            {
                                /* Parse the source. */
                                if (DisState.Param2.fUse & (DISUSE_IMMEDIATE32 | DISUSE_IMMEDIATE64))
                                    memcpy(pvVal, &DisState.Param2.uValue, cbVal);
                                else if (DisState.Param2.fUse & (DISUSE_RIPDISPLACEMENT32|DISUSE_DISPLACEMENT32|DISUSE_DISPLACEMENT64))
                                {
                                    RTGCPTR GCPtrVal = 0;

                                    if (DisState.Param2.fUse & DISUSE_RIPDISPLACEMENT32)
                                        GCPtrVal = GCPtrCur + DisState.Param2.arch.x86.uDisp.i32 + cbInstr;
                                    else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT32)
                                        GCPtrVal = (RTGCPTR)DisState.Param2.arch.x86.uDisp.u32;
                                    else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT64)
                                        GCPtrVal = (RTGCPTR)DisState.Param2.arch.x86.uDisp.u64;
                                    else
                                        AssertMsgFailedBreakStmt(("Invalid displacement\n"), rc = VERR_INVALID_STATE);

                                    DBGFADDRESS AddrVal;
                                    rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
                                                                pVMM->pfnDBGFR3AddrFromFlat(pUVM, &AddrVal, GCPtrVal),
                                                                pvVal, cbVal);
                                }
                            }
                            break;
                        default:
                            /* All other instructions will cause an error for now (playing safe here). */
                            rc = VERR_INVALID_PARAMETER;
                            break;
                    }
                    cInstrDisassembled++;
                    offInstr += cbInstr;
                }
            }
        } while (   RT_SUCCESS(rc)
                 && cInstrDisassembled < 20
                 && !fRet);
    }

    return rc;
}

/**
 * Try to get at the log buffer starting address and size by disassembling emit_log_char.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The VM handle.
 * @param   pVMM                The VMM function table.
 * @param   hMod                The module to use.
 * @param   pGCPtrLogBuf        Where to store the log buffer pointer on success.
 * @param   pcbLogBuf           Where to store the size of the log buffer on success.
 */
static int dbgDiggerLinuxQueryAsciiLogBufferPtrs(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, RTDBGMOD hMod,
                                                 RTGCPTR *pGCPtrLogBuf, uint32_t *pcbLogBuf)
{
    int rc = VINF_SUCCESS;

    /**
     * We disassemble emit_log_char to get at the log buffer address and size.
     * This is used in case the symbols are not exported in kallsyms.
     *
     * This is what it typically looks like:
     * vmlinux!emit_log_char:
     * %00000000c01204a1 56                      push esi
     * %00000000c01204a2 8b 35 d0 1c 34 c0       mov esi, dword [0c0341cd0h]
     * %00000000c01204a8 53                      push ebx
     * %00000000c01204a9 8b 1d 74 3b 3e c0       mov ebx, dword [0c03e3b74h]
     * %00000000c01204af 8b 0d d8 1c 34 c0       mov ecx, dword [0c0341cd8h]
     * %00000000c01204b5 8d 56 ff                lea edx, [esi-001h]
     * %00000000c01204b8 21 da                   and edx, ebx
     * %00000000c01204ba 88 04 11                mov byte [ecx+edx], al
     * %00000000c01204bd 8d 53 01                lea edx, [ebx+001h]
     * %00000000c01204c0 89 d0                   mov eax, edx
     * [...]
     */
    RTDBGSYMBOL SymInfo;
    rc = RTDbgModSymbolByName(hMod, "emit_log_char", &SymInfo);
    if (RT_SUCCESS(rc))
    {
        /*
         * Do the diassembling. Disassemble until a ret instruction is encountered
         * or a limit is reached (don't want to disassemble for too long as the getter
         * should be short). Certain instructions found are ignored (push, nop, etc.).
         */
        unsigned cInstrDisassembled = 0;
        uint32_t offInstr = 0;
        bool fRet = false;
        DISSTATE DisState;
        unsigned cAddressesUsed = 0;
        struct { size_t cb; RTGCPTR GCPtrOrigSrc; } aAddresses[5];
        RT_ZERO(DisState);
        RT_ZERO(aAddresses);

        do
        {
            DBGFADDRESS Addr;
            RTGCPTR GCPtrCur = (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr + offInstr;
            pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, GCPtrCur);

            /* Prefetch the instruction. */
            uint8_t abInstr[32];
            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &Addr, &abInstr[0], sizeof(abInstr));
            if (RT_SUCCESS(rc))
            {
                uint32_t cbInstr = 0;

                rc = DISInstr(&abInstr[0], pThis->f64Bit ? DISCPUMODE_64BIT : DISCPUMODE_32BIT, &DisState, &cbInstr);
                if (RT_SUCCESS(rc))
                {
                    switch (DisState.pCurInstr->uOpcode)
                    {
                        case OP_PUSH:
                        case OP_POP:
                        case OP_NOP:
                        case OP_LEA:
                        case OP_AND:
                        case OP_CBW:
                        case OP_DEC:
                            break;
                        case OP_RETN:
                            /* emit_log_char returned, abort disassembling. */
                            rc = VERR_NOT_FOUND;
                            fRet = true;
                            break;
                        case OP_MOV:
                        case OP_MOVSXD:
                            /*
                             * If a mov is encountered writing to memory with al (or dil for amd64) being the source the
                             * character is stored and we can infer the base address and size of the log buffer from
                             * the source addresses.
                             */
                            if (   (DisState.Param2.fUse & DISUSE_REG_GEN8)
                                && (   (DisState.Param2.arch.x86.Base.idxGenReg == DISGREG_AL && !pThis->f64Bit)
                                    || (DisState.Param2.arch.x86.Base.idxGenReg == DISGREG_DIL && pThis->f64Bit))
                                && DISUSE_IS_EFFECTIVE_ADDR(DisState.Param1.fUse))
                            {
                                RTGCPTR GCPtrLogBuf = 0;
                                uint32_t cbLogBuf = 0;

                                /*
                                 * We can stop disassembling now and inspect all registers, look for a valid kernel address first.
                                 * Only one of the accessed registers should hold a valid kernel address.
                                 * For the log size look for the biggest non kernel address.
                                 */
                                for (unsigned i = 0; i < cAddressesUsed; i++)
                                {
                                    DBGFADDRESS AddrVal;
                                    union { uint8_t abVal[8]; uint32_t u32Val; uint64_t u64Val; } Val;

                                    rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
                                                                pVMM->pfnDBGFR3AddrFromFlat(pUVM, &AddrVal,
                                                                                            aAddresses[i].GCPtrOrigSrc),
                                                                &Val.abVal[0], aAddresses[i].cb);
                                    if (RT_SUCCESS(rc))
                                    {
                                        if (pThis->f64Bit && aAddresses[i].cb == sizeof(uint64_t))
                                        {
                                            if (LNX64_VALID_ADDRESS(Val.u64Val))
                                            {
                                                if (GCPtrLogBuf == 0)
                                                    GCPtrLogBuf = Val.u64Val;
                                                else
                                                {
                                                    rc = VERR_NOT_FOUND;
                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            AssertMsgBreakStmt(aAddresses[i].cb == sizeof(uint32_t),
                                                               ("Invalid value size\n"), rc = VERR_INVALID_STATE);

                                            /* Might be a kernel address or a size indicator. */
                                            if (!pThis->f64Bit && LNX32_VALID_ADDRESS(Val.u32Val))
                                            {
                                                if (GCPtrLogBuf == 0)
                                                    GCPtrLogBuf = Val.u32Val;
                                                else
                                                {
                                                    rc = VERR_NOT_FOUND;
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                /*
                                                 * The highest value will be the log buffer because the other
                                                 * accessed variables are indexes into the buffer and hence
                                                 * always smaller than the size.
                                                 */
                                                if (cbLogBuf < Val.u32Val)
                                                    cbLogBuf = Val.u32Val;
                                            }
                                        }
                                    }
                                }

                                if (   RT_SUCCESS(rc)
                                    && GCPtrLogBuf != 0
                                    && cbLogBuf != 0)
                                {
                                    *pGCPtrLogBuf = GCPtrLogBuf;
                                    *pcbLogBuf = cbLogBuf;
                                }
                                else if (RT_SUCCESS(rc))
                                    rc = VERR_NOT_FOUND;

                                fRet = true;
                                break;
                            }
                            else
                            {
                                /*
                                 * In case of a memory to register move store the destination register index and the
                                 * source address in the relation table for later processing.
                                 */
                                if (   (DisState.Param1.fUse & (DISUSE_BASE | DISUSE_REG_GEN32 | DISUSE_REG_GEN64))
                                    && (DisState.Param2.arch.x86.cb == sizeof(uint32_t) || DisState.Param2.arch.x86.cb == sizeof(uint64_t))
                                    && (DisState.Param2.fUse & (DISUSE_RIPDISPLACEMENT32|DISUSE_DISPLACEMENT32|DISUSE_DISPLACEMENT64)))
                                {
                                    RTGCPTR GCPtrVal = 0;

                                    if (DisState.Param2.fUse & DISUSE_RIPDISPLACEMENT32)
                                        GCPtrVal = GCPtrCur + DisState.Param2.arch.x86.uDisp.i32 + cbInstr;
                                    else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT32)
                                        GCPtrVal = (RTGCPTR)DisState.Param2.arch.x86.uDisp.u32;
                                    else if (DisState.Param2.fUse & DISUSE_DISPLACEMENT64)
                                        GCPtrVal = (RTGCPTR)DisState.Param2.arch.x86.uDisp.u64;
                                    else
                                        AssertMsgFailedBreakStmt(("Invalid displacement\n"), rc = VERR_INVALID_STATE);

                                    if (cAddressesUsed < RT_ELEMENTS(aAddresses))
                                    {
                                        /* movsxd reads always 32bits. */
                                        if (DisState.pCurInstr->uOpcode == OP_MOVSXD)
                                            aAddresses[cAddressesUsed].cb = sizeof(uint32_t);
                                        else
                                            aAddresses[cAddressesUsed].cb = DisState.Param2.arch.x86.cb;
                                        aAddresses[cAddressesUsed].GCPtrOrigSrc = GCPtrVal;
                                        cAddressesUsed++;
                                    }
                                    else
                                    {
                                        rc = VERR_INVALID_PARAMETER;
                                        break;
                                    }
                                }
                            }
                            break;
                        default:
                            /* All other instructions will cause an error for now (playing safe here). */
                            rc = VERR_INVALID_PARAMETER;
                            break;
                    }
                    cInstrDisassembled++;
                    offInstr += cbInstr;
                }
            }
        } while (   RT_SUCCESS(rc)
                 && cInstrDisassembled < 20
                 && !fRet);
    }

    return rc;
}

/**
 * Try to get at the log buffer starting address and size by disassembling some exposed helpers.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The VM handle.
 * @param   pVMM                The VMM function table.
 * @param   hMod                The module to use.
 * @param   pGCPtrLogBuf        Where to store the log buffer pointer on success.
 * @param   pcbLogBuf           Where to store the size of the log buffer on success.
 */
static int dbgDiggerLinuxQueryLogBufferPtrs(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, RTDBGMOD hMod,
                                            RTGCPTR *pGCPtrLogBuf, uint32_t *pcbLogBuf)
{
    int rc = VINF_SUCCESS;

    struct { void *pvVar; uint32_t cbHost, cbGuest; const char *pszSymbol; } aSymbols[] =
    {
        { pGCPtrLogBuf, (uint32_t)sizeof(RTGCPTR),  (uint32_t)(pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t)), "log_buf_addr_get" },
        { pcbLogBuf,    (uint32_t)sizeof(uint32_t), (uint32_t)sizeof(uint32_t),                                      "log_buf_len_get" }
    };
    for (uint32_t i = 0; i < RT_ELEMENTS(aSymbols) && RT_SUCCESS(rc); i++)
    {
        RT_BZERO(aSymbols[i].pvVar, aSymbols[i].cbHost);
        Assert(aSymbols[i].cbHost >= aSymbols[i].cbGuest);
        rc = dbgDiggerLinuxDisassembleSimpleGetter(pThis, pUVM, pVMM, hMod, aSymbols[i].pszSymbol,
                                                   aSymbols[i].pvVar, aSymbols[i].cbGuest);
    }

    return rc;
}

/**
 * Returns whether the log buffer is a simple ascii buffer or a record based implementation
 * based on the kernel version found.
 *
 * @returns Flag whether the log buffer is the simple ascii buffer.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 */
static bool dbgDiggerLinuxLogBufferIsAsciiBuffer(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM)
{
    char szTmp[128];
    char const *pszVer = &szTmp[sizeof(g_abLinuxVersion) - 1];

    RT_ZERO(szTmp);
    int rc = pVMM->pfnDBGFR3MemReadString(pUVM, 0, &pThis->AddrLinuxBanner, szTmp, sizeof(szTmp) - 1);
    if (    RT_SUCCESS(rc)
        &&  RTStrVersionCompare(pszVer, "3.4") == -1)
        return true;

    return false;
}

/**
 * Worker to get at the kernel log for pre 3.4 kernels where the log buffer was just a char buffer.
 *
 * @returns VBox status code.
 * @param   pThis       The Linux digger data.
 * @param   pUVM        The VM user mdoe handle.
 * @param   pVMM        The VMM function table.
 * @param   hMod        The debug module handle.
 * @param   fFlags      Flags reserved for future use, MBZ.
 * @param   cMessages   The number of messages to retrieve, counting from the
 *                      end of the log (i.e. like tail), use UINT32_MAX for all.
 * @param   pszBuf      The output buffer.
 * @param   cbBuf       The buffer size.
 * @param   pcbActual   Where to store the number of bytes actually returned,
 *                      including zero terminator.  On VERR_BUFFER_OVERFLOW this
 *                      holds the necessary buffer size.  Optional.
 */
static int dbgDiggerLinuxLogBufferQueryAscii(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, RTDBGMOD hMod,
                                             uint32_t fFlags, uint32_t cMessages,
                                             char *pszBuf, size_t cbBuf, size_t *pcbActual)
{
    RT_NOREF2(fFlags, cMessages);
    int rc = VINF_SUCCESS;
    RTGCPTR  GCPtrLogBuf;
    uint32_t cbLogBuf;

    struct { void *pvVar; size_t cbHost, cbGuest; const char *pszSymbol; } aSymbols[] =
    {
        { &GCPtrLogBuf, sizeof(GCPtrLogBuf),    pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t),   "log_buf" },
        { &cbLogBuf,    sizeof(cbLogBuf),       sizeof(cbLogBuf),                                      "log_buf_len" },
    };
    for (uint32_t i = 0; i < RT_ELEMENTS(aSymbols); i++)
    {
        RTDBGSYMBOL SymInfo;
        rc = RTDbgModSymbolByName(hMod, aSymbols[i].pszSymbol, &SymInfo);
        if (RT_SUCCESS(rc))
        {
            RT_BZERO(aSymbols[i].pvVar, aSymbols[i].cbHost);
            Assert(aSymbols[i].cbHost >= aSymbols[i].cbGuest);
            DBGFADDRESS Addr;
            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
                                        pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr,
                                                                    (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr),
                                        aSymbols[i].pvVar,  aSymbols[i].cbGuest);
            if (RT_SUCCESS(rc))
                continue;
            LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Reading '%s' at %RGv: %Rrc\n", aSymbols[i].pszSymbol, Addr.FlatPtr, rc));
        }
        else
            LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error looking up '%s': %Rrc\n", aSymbols[i].pszSymbol, rc));
        rc = VERR_NOT_FOUND;
        break;
    }

    /*
     * Some kernels don't expose the variables in kallsyms so we have to try disassemble
     * some public helpers to get at the addresses.
     *
     * @todo: Maybe cache those values so we don't have to do the heavy work every time?
     */
    if (rc == VERR_NOT_FOUND)
    {
        rc = dbgDiggerLinuxQueryAsciiLogBufferPtrs(pThis, pUVM, pVMM, hMod, &GCPtrLogBuf, &cbLogBuf);
        if (RT_FAILURE(rc))
            return rc;
    }

    /*
     * Check if the values make sense.
     */
    if (pThis->f64Bit ? !LNX64_VALID_ADDRESS(GCPtrLogBuf) : !LNX32_VALID_ADDRESS(GCPtrLogBuf))
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf' value %RGv is not valid.\n", GCPtrLogBuf));
        return VERR_NOT_FOUND;
    }
    if (   cbLogBuf < 4096
        || !RT_IS_POWER_OF_TWO(cbLogBuf)
        || cbLogBuf > 16*_1M)
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf_len' value %#x is not valid.\n", cbLogBuf));
        return VERR_NOT_FOUND;
    }

    /*
     * Read the whole log buffer.
     */
    uint8_t *pbLogBuf = (uint8_t *)RTMemAlloc(cbLogBuf);
    if (!pbLogBuf)
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Failed to allocate %#x bytes for log buffer\n", cbLogBuf));
        return VERR_NO_MEMORY;
    }
    DBGFADDRESS Addr;
    rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, GCPtrLogBuf), pbLogBuf, cbLogBuf);
    if (RT_FAILURE(rc))
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error reading %#x bytes of log buffer at %RGv: %Rrc\n",
                cbLogBuf, Addr.FlatPtr, rc));
        RTMemFree(pbLogBuf);
        return VERR_NOT_FOUND;
    }

    /** @todo Try to parse where the single messages start to make use of cMessages. */
    size_t cchLength = RTStrNLen((const char *)pbLogBuf, cbLogBuf);
    memcpy(&pszBuf[0], pbLogBuf, RT_MIN(cbBuf, cchLength));

    /* Done with the buffer. */
    RTMemFree(pbLogBuf);

    /* Set return size value. */
    if (pcbActual)
        *pcbActual = RT_MIN(cbBuf, cchLength);

    return cbBuf <= cchLength ? VERR_BUFFER_OVERFLOW : VINF_SUCCESS;
}


/**
 * Worker to process a given record based kernel log.
 *
 * @returns VBox status code.
 * @param   pThis       The Linux digger data.
 * @param   pUVM        The VM user mode handle.
 * @param   pVMM        The VMM function table.
 * @param   GCPtrLogBuf Flat guest address of the start of the log buffer.
 * @param   cbLogBuf    Power of two aligned size of the log buffer.
 * @param   idxFirst    Index in the log bfufer of the first message.
 * @param   idxNext     Index where to write hte next message in the log buffer.
 * @param   fFlags      Flags reserved for future use, MBZ.
 * @param   cMessages   The number of messages to retrieve, counting from the
 *                      end of the log (i.e. like tail), use UINT32_MAX for all.
 * @param   pszBuf      The output buffer.
 * @param   cbBuf       The buffer size.
 * @param   pcbActual   Where to store the number of bytes actually returned,
 *                      including zero terminator.  On VERR_BUFFER_OVERFLOW this
 *                      holds the necessary buffer size.  Optional.
 */
static int dbgDiggerLinuxKrnLogBufferProcess(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, RTGCPTR GCPtrLogBuf,
                                             uint32_t cbLogBuf, uint32_t idxFirst, uint32_t idxNext,
                                             uint32_t fFlags, uint32_t cMessages, char *pszBuf, size_t cbBuf,
                                             size_t *pcbActual)
{
    RT_NOREF(fFlags);

    /*
     * Check if the values make sense.
     */
    if (pThis->f64Bit ? !LNX64_VALID_ADDRESS(GCPtrLogBuf) : !LNX32_VALID_ADDRESS(GCPtrLogBuf))
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf' value %RGv is not valid.\n", GCPtrLogBuf));
        return VERR_NOT_FOUND;
    }
    if (   cbLogBuf < _4K
        || !RT_IS_POWER_OF_TWO(cbLogBuf)
        || cbLogBuf > LNX_MAX_KERNEL_LOG_SIZE)
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_buf_len' value %#x is not valid.\n", cbLogBuf));
        return VERR_NOT_FOUND;
    }
    uint32_t const cbLogAlign = 4;
    if (   idxFirst > cbLogBuf - sizeof(LNXPRINTKHDR)
        || (idxFirst & (cbLogAlign - 1)) != 0)
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_first_idx' value %#x is not valid.\n", idxFirst));
        return VERR_NOT_FOUND;
    }
    if (   idxNext > cbLogBuf - sizeof(LNXPRINTKHDR)
        || (idxNext & (cbLogAlign - 1)) != 0)
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: 'log_next_idx' value %#x is not valid.\n", idxNext));
        return VERR_NOT_FOUND;
    }

    /*
     * Read the whole log buffer.
     */
    uint8_t *pbLogBuf = (uint8_t *)RTMemAlloc(cbLogBuf);
    if (!pbLogBuf)
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Failed to allocate %#x bytes for log buffer\n", cbLogBuf));
        return VERR_NO_MEMORY;
    }
    DBGFADDRESS Addr;
    int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, GCPtrLogBuf), pbLogBuf, cbLogBuf);
    if (RT_FAILURE(rc))
    {
        LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error reading %#x bytes of log buffer at %RGv: %Rrc\n",
                cbLogBuf, Addr.FlatPtr, rc));
        RTMemFree(pbLogBuf);
        return VERR_NOT_FOUND;
    }

    /*
     * Count the messages in the buffer while doing some basic validation.
     */
    uint32_t const cbUsed = idxFirst == idxNext ? cbLogBuf /* could be empty... */
                          : idxFirst < idxNext  ? idxNext - idxFirst : cbLogBuf - idxFirst + idxNext;
    uint32_t cbLeft    = cbUsed;
    uint32_t offCur    = idxFirst;
    uint32_t cLogMsgs  = 0;

    while (cbLeft > 0)
    {
        PCLNXPRINTKHDR pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
        if (!pHdr->cbTotal)
        {
            /* Wrap around packet, most likely... */
            if (cbLogBuf - offCur >= cbLeft)
                break;
            offCur = 0;
            pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
        }
        if (RT_UNLIKELY(   pHdr->cbTotal > cbLogBuf - sizeof(*pHdr) - offCur
                        || pHdr->cbTotal > cbLeft
                        || (pHdr->cbTotal & (cbLogAlign - 1)) != 0
                        || pHdr->cbTotal < (uint32_t)pHdr->cbText + (uint32_t)pHdr->cbDict + sizeof(*pHdr) ))
        {
            LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Invalid printk_log record at %#x: cbTotal=%#x cbText=%#x cbDict=%#x cbLogBuf=%#x cbLeft=%#x\n",
                    offCur, pHdr->cbTotal, pHdr->cbText, pHdr->cbDict, cbLogBuf, cbLeft));
            break;
        }

        if (pHdr->cbText > 0)
            cLogMsgs++;

        /* next */
        offCur += pHdr->cbTotal;
        cbLeft -= pHdr->cbTotal;
    }
    if (!cLogMsgs)
    {
        RTMemFree(pbLogBuf);
        return VERR_NOT_FOUND;
    }

    /*
     * Copy the messages into the output buffer.
     */
    offCur = idxFirst;
    cbLeft = cbUsed - cbLeft;

    /* Skip messages that the caller doesn't want. */
    if (cMessages < cLogMsgs)
    {
        uint32_t cToSkip = cLogMsgs - cMessages;
        cLogMsgs -= cToSkip;

        while (cToSkip > 0)
        {
            PCLNXPRINTKHDR pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
            if (!pHdr->cbTotal)
            {
                offCur = 0;
                pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
            }
            if (pHdr->cbText > 0)
                cToSkip--;

            /* next */
            offCur += pHdr->cbTotal;
            cbLeft -= pHdr->cbTotal;
        }
    }

    /* Now copy the messages. */
    size_t offDst = 0;
    while (cbLeft > 0)
    {
        PCLNXPRINTKHDR pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
        if (   !pHdr->cbTotal
            || !cLogMsgs)
        {
            if (cbLogBuf - offCur >= cbLeft)
                break;
            offCur = 0;
            pHdr = (PCLNXPRINTKHDR)&pbLogBuf[offCur];
        }

        if (pHdr->cbText > 0)
        {
            char  *pchText = (char *)(pHdr + 1);
            size_t cchText = RTStrNLen(pchText, pHdr->cbText);
            if (offDst + cchText < cbBuf)
            {
                memcpy(&pszBuf[offDst], pHdr + 1, cchText);
                pszBuf[offDst + cchText] = '\n';
            }
            else if (offDst < cbBuf)
                memcpy(&pszBuf[offDst], pHdr + 1, cbBuf - offDst);
            offDst += cchText + 1;
        }

        /* next */
        offCur += pHdr->cbTotal;
        cbLeft -= pHdr->cbTotal;
    }

    /* Done with the buffer. */
    RTMemFree(pbLogBuf);

    /* Make sure we've reserved a char for the terminator. */
    if (!offDst)
        offDst = 1;

    /* Set return size value. */
    if (pcbActual)
        *pcbActual = offDst;

    if (offDst <= cbBuf)
        return VINF_SUCCESS;
    return VERR_BUFFER_OVERFLOW;
}


/**
 * Worker to get at the kernel log for post 3.4 kernels where the log buffer contains records.
 *
 * @returns VBox status code.
 * @param   pThis       The Linux digger data.
 * @param   pUVM        The VM user mdoe handle.
 * @param   pVMM        The VMM function table.
 * @param   hMod        The debug module handle.
 * @param   fFlags      Flags reserved for future use, MBZ.
 * @param   cMessages   The number of messages to retrieve, counting from the
 *                      end of the log (i.e. like tail), use UINT32_MAX for all.
 * @param   pszBuf      The output buffer.
 * @param   cbBuf       The buffer size.
 * @param   pcbActual   Where to store the number of bytes actually returned,
 *                      including zero terminator.  On VERR_BUFFER_OVERFLOW this
 *                      holds the necessary buffer size.  Optional.
 */
static int dbgDiggerLinuxLogBufferQueryRecords(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, RTDBGMOD hMod,
                                               uint32_t fFlags, uint32_t cMessages,
                                               char *pszBuf, size_t cbBuf, size_t *pcbActual)
{
    int rc = VINF_SUCCESS;
    RTGCPTR  GCPtrLogBuf;
    uint32_t cbLogBuf;
    uint32_t idxFirst;
    uint32_t idxNext;

    struct { void *pvVar; size_t cbHost, cbGuest; const char *pszSymbol; } aSymbols[] =
    {
        { &GCPtrLogBuf, sizeof(GCPtrLogBuf),    pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t),   "log_buf" },
        { &cbLogBuf,    sizeof(cbLogBuf),       sizeof(cbLogBuf),                                      "log_buf_len" },
        { &idxFirst,    sizeof(idxFirst),       sizeof(idxFirst),                                      "log_first_idx" },
        { &idxNext,     sizeof(idxNext),        sizeof(idxNext),                                       "log_next_idx" },
    };
    for (uint32_t i = 0; i < RT_ELEMENTS(aSymbols); i++)
    {
        RTDBGSYMBOL SymInfo;
        rc = RTDbgModSymbolByName(hMod, aSymbols[i].pszSymbol, &SymInfo);
        if (RT_SUCCESS(rc))
        {
            RT_BZERO(aSymbols[i].pvVar, aSymbols[i].cbHost);
            Assert(aSymbols[i].cbHost >= aSymbols[i].cbGuest);
            DBGFADDRESS Addr;
            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
                                        pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr,
                                                                    (RTGCPTR)SymInfo.Value + pThis->AddrKernelBase.FlatPtr),
                                        aSymbols[i].pvVar,  aSymbols[i].cbGuest);
            if (RT_SUCCESS(rc))
                continue;
            LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Reading '%s' at %RGv: %Rrc\n", aSymbols[i].pszSymbol, Addr.FlatPtr, rc));
        }
        else
            LogRel(("dbgDiggerLinuxIDmsg_QueryKernelLog: Error looking up '%s': %Rrc\n", aSymbols[i].pszSymbol, rc));
        rc = VERR_NOT_FOUND;
        break;
    }

    /*
     * Some kernels don't expose the variables in kallsyms so we have to try disassemble
     * some public helpers to get at the addresses.
     *
     * @todo: Maybe cache those values so we don't have to do the heavy work every time?
     */
    if (rc == VERR_NOT_FOUND)
    {
        idxFirst = 0;
        idxNext = 0;
        rc = dbgDiggerLinuxQueryLogBufferPtrs(pThis, pUVM, pVMM, hMod, &GCPtrLogBuf, &cbLogBuf);
        if (RT_FAILURE(rc))
        {
            /*
             * Last resort, scan for a known value which should appear only once in the kernel log buffer
             * and try to deduce the boundaries from there.
             */
            return dbgDiggerLinuxKrnlLogBufFindByNeedle(pThis, pUVM, pVMM, &GCPtrLogBuf, &cbLogBuf);
        }
    }

    return dbgDiggerLinuxKrnLogBufferProcess(pThis, pUVM, pVMM, GCPtrLogBuf, cbLogBuf, idxFirst, idxNext,
                                             fFlags, cMessages, pszBuf, cbBuf, pcbActual);
}

/**
 * @interface_method_impl{DBGFOSIDMESG,pfnQueryKernelLog}
 */
static DECLCALLBACK(int) dbgDiggerLinuxIDmsg_QueryKernelLog(PDBGFOSIDMESG pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, uint32_t fFlags,
                                                            uint32_t cMessages, char *pszBuf, size_t cbBuf, size_t *pcbActual)
{
    PDBGDIGGERLINUX pData = RT_FROM_MEMBER(pThis, DBGDIGGERLINUX, IDmesg);

    if (cMessages < 1)
        return VERR_INVALID_PARAMETER;

    /*
     * Resolve the symbols we need and read their values.
     */
    RTDBGAS  hAs = pVMM->pfnDBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
    RTDBGMOD hMod;
    int rc = RTDbgAsModuleByName(hAs, "vmlinux", 0, &hMod);
    RTDbgAsRelease(hAs);

    size_t cbActual = 0;
    if (RT_SUCCESS(rc))
    {
        /*
         * Check whether the kernel log buffer is a simple char buffer or the newer
         * record based implementation.
         * The record based implementation was presumably introduced with kernel 3.4,
         * see: http://thread.gmane.org/gmane.linux.kernel/1284184
         */
        if (dbgDiggerLinuxLogBufferIsAsciiBuffer(pData, pUVM, pVMM))
            rc = dbgDiggerLinuxLogBufferQueryAscii(pData, pUVM, pVMM, hMod, fFlags, cMessages, pszBuf, cbBuf, &cbActual);
        else
            rc = dbgDiggerLinuxLogBufferQueryRecords(pData, pUVM, pVMM, hMod, fFlags, cMessages, pszBuf, cbBuf, &cbActual);

        /* Release the module in any case. */
        RTDbgModRelease(hMod);
    }
    else
    {
        /*
         * For the record based kernel versions we have a last resort heuristic which doesn't
         * require any symbols, try that here.
         */
        if (!dbgDiggerLinuxLogBufferIsAsciiBuffer(pData, pUVM, pVMM))
        {
            RTGCPTR GCPtrLogBuf = 0;
            uint32_t cbLogBuf = 0;

            rc = dbgDiggerLinuxKrnlLogBufFindByNeedle(pData, pUVM, pVMM, &GCPtrLogBuf, &cbLogBuf);
            if (RT_SUCCESS(rc))
                rc = dbgDiggerLinuxKrnLogBufferProcess(pData, pUVM, pVMM, GCPtrLogBuf, cbLogBuf, 0 /*idxFirst*/, 0 /*idxNext*/,
                                                       fFlags, cMessages, pszBuf, cbBuf, &cbActual);
        }
        else
            rc = VERR_NOT_FOUND;
    }

    if (RT_FAILURE(rc) && rc != VERR_BUFFER_OVERFLOW)
        return rc;

    if (pcbActual)
        *pcbActual = cbActual;

    /*
     * All VBox strings are UTF-8 and bad things may in theory happen if we
     * pass bad UTF-8 to code which assumes it's all valid.  So, we enforce
     * UTF-8 upon the guest kernel messages here even if they (probably) have
     * no defined code set in reality.
     */
    if (   RT_SUCCESS(rc)
        && cbActual <= cbBuf)
    {
        pszBuf[cbActual - 1] = '\0';
        RTStrPurgeEncoding(pszBuf);
        return VINF_SUCCESS;
    }

    if (cbBuf)
    {
        pszBuf[cbBuf - 1] = '\0';
        RTStrPurgeEncoding(pszBuf);
    }
    return VERR_BUFFER_OVERFLOW;
}


/**
 * Worker destroying the config database.
 */
static DECLCALLBACK(int) dbgDiggerLinuxCfgDbDestroyWorker(PRTSTRSPACECORE pStr, void *pvUser)
{
    PDBGDIGGERLINUXCFGITEM pCfgItem = (PDBGDIGGERLINUXCFGITEM)pStr;
    RTStrFree((char *)pCfgItem->Core.pszString);
    RTMemFree(pCfgItem);
    NOREF(pvUser);
    return 0;
}


/**
 * Destroy the config database.
 *
 * @returns nothing.
 * @param   pThis               The Linux digger data.
 */
static void dbgDiggerLinuxCfgDbDestroy(PDBGDIGGERLINUX pThis)
{
    RTStrSpaceDestroy(&pThis->hCfgDb, dbgDiggerLinuxCfgDbDestroyWorker, NULL);
}


/**
 * @copydoc DBGFOSREG::pfnStackUnwindAssist
 */
static DECLCALLBACK(int) dbgDiggerLinuxStackUnwindAssist(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData, VMCPUID idCpu,
                                                         PDBGFSTACKFRAME pFrame, PRTDBGUNWINDSTATE pState, PCCPUMCTX pInitialCtx,
                                                         RTDBGAS hAs, uint64_t *puScratch)
{
    RT_NOREF(pUVM, pVMM, pvData, idCpu, pFrame, pState, pInitialCtx, hAs, puScratch);
    return VINF_SUCCESS;
}


/**
 * @copydoc DBGFOSREG::pfnQueryInterface
 */
static DECLCALLBACK(void *) dbgDiggerLinuxQueryInterface(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData, DBGFOSINTERFACE enmIf)
{
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
    RT_NOREF(pUVM, pVMM);

    switch (enmIf)
    {
        case DBGFOSINTERFACE_DMESG:
            return &pThis->IDmesg;

        default:
            return NULL;
    }
}


/**
 * @copydoc DBGFOSREG::pfnQueryVersion
 */
static DECLCALLBACK(int)  dbgDiggerLinuxQueryVersion(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData,
                                                     char *pszVersion, size_t cchVersion)
{
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
    Assert(pThis->fValid);

    /*
     * It's all in the linux banner.
     */
    int rc = pVMM->pfnDBGFR3MemReadString(pUVM, 0, &pThis->AddrLinuxBanner, pszVersion, cchVersion);
    if (RT_SUCCESS(rc))
    {
        char *pszEnd = RTStrEnd(pszVersion, cchVersion);
        AssertReturn(pszEnd, VERR_BUFFER_OVERFLOW);
        while (     pszEnd > pszVersion
               &&   RT_C_IS_SPACE(pszEnd[-1]))
            pszEnd--;
        *pszEnd = '\0';
    }
    else
        RTStrPrintf(pszVersion, cchVersion, "DBGFR3MemRead -> %Rrc", rc);

    return rc;
}


/**
 * @copydoc DBGFOSREG::pfnTerm
 */
static DECLCALLBACK(void)  dbgDiggerLinuxTerm(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
{
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
    Assert(pThis->fValid);

    /*
     * Destroy configuration database.
     */
    dbgDiggerLinuxCfgDbDestroy(pThis);

    /*
     * Unlink and release our modules.
     */
    RTDBGAS hDbgAs = pVMM->pfnDBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
    if (hDbgAs != NIL_RTDBGAS)
    {
        uint32_t iMod = RTDbgAsModuleCount(hDbgAs);
        while (iMod-- > 0)
        {
            RTDBGMOD hMod = RTDbgAsModuleByIndex(hDbgAs, iMod);
            if (hMod != NIL_RTDBGMOD)
            {
                if (RTDbgModGetTag(hMod) == DIG_LNX_MOD_TAG)
                {
                    int rc = RTDbgAsModuleUnlink(hDbgAs, hMod);
                    AssertRC(rc);
                }
                RTDbgModRelease(hMod);
            }
        }
        RTDbgAsRelease(hDbgAs);
    }

    pThis->fValid = false;
}


/**
 * @copydoc DBGFOSREG::pfnRefresh
 */
static DECLCALLBACK(int)  dbgDiggerLinuxRefresh(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
{
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
    RT_NOREF(pThis);
    Assert(pThis->fValid);

    /*
     * For now we'll flush and reload everything.
     */
    dbgDiggerLinuxTerm(pUVM, pVMM, pvData);
    return dbgDiggerLinuxInit(pUVM, pVMM, pvData);
}


/**
 * Worker for dbgDiggerLinuxFindStartOfNamesAndSymbolCount that update the
 * digger data.
 *
 * @returns VINF_SUCCESS.
 * @param   pThis               The Linux digger data to update.
 * @param   pVMM                The VMM function table.
 * @param   pAddrKernelNames    The kallsyms_names address.
 * @param   cKernelSymbols      The number of kernel symbol.
 * @param   cbAddress           The guest address size.
 */
static int dbgDiggerLinuxFoundStartOfNames(PDBGDIGGERLINUX pThis, PCVMMR3VTABLE pVMM, PCDBGFADDRESS pAddrKernelNames,
                                           uint32_t cKernelSymbols, uint32_t cbAddress)
{
    pThis->cKernelSymbols = cKernelSymbols;
    pThis->AddrKernelNames = *pAddrKernelNames;
    pThis->AddrKernelAddresses = *pAddrKernelNames;
    uint32_t cbSymbolsSkip = (pThis->fRelKrnlAddr ? 2 : 1) * cbAddress; /* Relative addressing introduces kallsyms_relative_base. */
    uint32_t cbOffsets = pThis->fRelKrnlAddr ? sizeof(int32_t) : cbAddress; /* Offsets are always 32bits wide for relative addressing. */
    uint32_t cbAlign = 0;

    /*
     * If the number of symbols is odd there is padding to align the following guest pointer
     * sized data properly on 64bit systems with relative addressing.
     */
    if (   pThis->fRelKrnlAddr
        && pThis->f64Bit
        && (pThis->cKernelSymbols & 1))
        cbAlign = sizeof(int32_t);
    pVMM->pfnDBGFR3AddrSub(&pThis->AddrKernelAddresses, cKernelSymbols * cbOffsets + cbSymbolsSkip + cbAlign);

    Log(("dbgDiggerLinuxFoundStartOfNames: AddrKernelAddresses=%RGv\n"
         "dbgDiggerLinuxFoundStartOfNames: cKernelSymbols=%#x (at %RGv)\n"
         "dbgDiggerLinuxFoundStartOfNames: AddrKernelName=%RGv\n",
         pThis->AddrKernelAddresses.FlatPtr,
         pThis->cKernelSymbols, pThis->AddrKernelNames.FlatPtr - cbAddress,
         pThis->AddrKernelNames.FlatPtr));
    return VINF_SUCCESS;
}


/**
 * Tries to find the address of the kallsyms_names, kallsyms_num_syms and
 * kallsyms_addresses symbols.
 *
 * The kallsyms_num_syms is read and stored in pThis->cKernelSymbols, while the
 * addresses of the other two are stored as pThis->AddrKernelNames and
 * pThis->AddrKernelAddresses.
 *
 * @returns VBox status code, success indicating that all three variables have
 *          been found and taken down.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 * @param   pHitAddr            An address we think is inside kallsyms_names.
 */
static int dbgDiggerLinuxFindStartOfNamesAndSymbolCount(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis,
                                                        PCDBGFADDRESS pHitAddr)
{
    /*
     * Search backwards in chunks.
     */
    union
    {
        uint8_t  ab[0x1000];
        uint32_t au32[0x1000 / sizeof(uint32_t)];
        uint64_t au64[0x1000 / sizeof(uint64_t)];
    } uBuf;
    uint32_t        cbLeft  = LNX_MAX_KALLSYMS_NAMES_SIZE;
    uint32_t        cbBuf   = pHitAddr->FlatPtr & (sizeof(uBuf) - 1);
    DBGFADDRESS     CurAddr = *pHitAddr;
    pVMM->pfnDBGFR3AddrSub(&CurAddr, cbBuf);
    cbBuf += sizeof(uint64_t) - 1;      /* In case our kobj hit is in the first 4/8 bytes. */
    for (;;)
    {
        int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &CurAddr, &uBuf, sizeof(uBuf));
        if (RT_FAILURE(rc))
            return rc;

        /*
         * Since Linux 4.6 there are two different methods to store the kallsyms addresses
         * in the image.
         *
         * The first and longer existing method is to store the absolute addresses in an
         * array starting at kallsyms_addresses followed by a field which stores the number
         * of kernel symbols called kallsyms_num_syms.
         * The newer method is to use offsets stored in kallsyms_offsets and have a base pointer
         * to relate the offsets to called kallsyms_relative_base. One entry in kallsyms_offsets is
         * always 32bit wide regardless of the guest pointer size (this halves the table on 64bit
         * systems) but means more work for us for the 64bit case.
         *
         * When absolute addresses are used the following assumptions hold:
         *
         *     We assume that the three symbols are aligned on guest pointer boundary.
         *
         *     The boundary between the two tables should be noticable as the number
         *     is unlikely to be more than 16 millions, there will be at least one zero
         *     byte where it is, 64-bit will have 5 zero bytes.  Zero bytes aren't all
         *     that common in the kallsyms_names table.
         *
         *     Also the kallsyms_names table starts with a length byte, which means
         *     we're likely to see a byte in the range 1..31.
         *
         *     The kallsyms_addresses are mostly sorted (except for the start where the
         *     absolute symbols are), so we'll spot a bunch of kernel addresses
         *     immediately preceeding the kallsyms_num_syms field.
         *
         *     Lazy bird: If kallsyms_num_syms is on a buffer boundrary, we skip
         *                the check for kernel addresses preceeding it.
         *
         * For relative offsets most of the assumptions from above are true too
         * except that we have to distinguish between the relative base address and the offsets.
         * Every observed kernel has a valid kernel address fo the relative base and kallsyms_relative_base
         * always comes before kallsyms_num_syms and is aligned on a guest pointer boundary.
         * Offsets are stored before kallsyms_relative_base and don't contain valid kernel addresses.
         *
         * To distinguish between absolute and relative offsetting we check the data before a candidate
         * for kallsyms_num_syms. If all entries before the kallsyms_num_syms candidate are valid kernel
         * addresses absolute addresses are assumed. If this is not the case but the first entry before
         * kallsyms_num_syms is a valid kernel address we check whether the data before and the possible
         * relative base form a valid kernel address and assume relative offsets.
         *
         * Other notable changes between various Linux kernel versions:
         *
         *     4.20.0+: Commit 80ffbaa5b1bd98e80e3239a3b8cfda2da433009a made kallsyms_num_syms 32bit
         *              even on 64bit systems but the alignment of the variables makes the code below work for now
         *              (tested with a 5.4 and 5.12 kernel) do we keep it that way to avoid making the code even
         *              messy.
         */
        if (pThis->f64Bit)
        {
            uint32_t i = cbBuf / sizeof(uint64_t) - 1;
            while (i-- > 0)
                if (   uBuf.au64[i] <= LNX_MAX_KALLSYMS_SYMBOLS
                    && uBuf.au64[i] >= LNX_MIN_KALLSYMS_SYMBOLS)
                {
                    uint8_t *pb = (uint8_t *)&uBuf.au64[i + 1];
                    if (   pb[0] <= LNX_MAX_KALLSYMS_ENC_LENGTH
                        && pb[0] >= LNX_MIN_KALLSYMS_ENC_LENGTH)
                    {
                        /*
                         * Check whether we have a valid kernel address and try to distinguish
                         * whether the kernel uses relative offsetting or absolute addresses.
                         */
                        if (   (i >= 1 && LNX64_VALID_ADDRESS(uBuf.au64[i - 1]))
                            && (i >= 2 && !LNX64_VALID_ADDRESS(uBuf.au64[i - 2]))
                            && (i >= 3 && !LNX64_VALID_ADDRESS(uBuf.au64[i - 3])))
                        {
                            RTGCUINTPTR uKrnlRelBase = uBuf.au64[i - 1];
                            DBGFADDRESS RelAddr = CurAddr;
                            int32_t aiRelOff[3];
                            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/,
                                                        pVMM->pfnDBGFR3AddrAdd(&RelAddr,
                                                                               (i - 1) * sizeof(uint64_t) - sizeof(aiRelOff)),
                                                        &aiRelOff[0], sizeof(aiRelOff));
                            if (   RT_SUCCESS(rc)
                                && LNX64_VALID_ADDRESS(uKrnlRelBase + aiRelOff[0])
                                && LNX64_VALID_ADDRESS(uKrnlRelBase + aiRelOff[1])
                                && LNX64_VALID_ADDRESS(uKrnlRelBase + aiRelOff[2]))
                            {
                                Log(("dbgDiggerLinuxFindStartOfNamesAndSymbolCount: relative base %RGv (at %RGv)\n",
                                     uKrnlRelBase, CurAddr.FlatPtr + (i - 1) * sizeof(uint64_t)));
                                pThis->fRelKrnlAddr = true;
                                pThis->uKernelRelativeBase = uKrnlRelBase;
                                return dbgDiggerLinuxFoundStartOfNames(pThis, pVMM,
                                                                       pVMM->pfnDBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint64_t)),
                                                                       (uint32_t)uBuf.au64[i], sizeof(uint64_t));
                            }
                        }

                        if (   (i <= 0 || LNX64_VALID_ADDRESS(uBuf.au64[i - 1]))
                            && (i <= 1 || LNX64_VALID_ADDRESS(uBuf.au64[i - 2]))
                            && (i <= 2 || LNX64_VALID_ADDRESS(uBuf.au64[i - 3])))
                            return dbgDiggerLinuxFoundStartOfNames(pThis, pVMM,
                                                                   pVMM->pfnDBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint64_t)),
                                                                   (uint32_t)uBuf.au64[i], sizeof(uint64_t));
                    }
                }
        }
        else
        {
            uint32_t i = cbBuf / sizeof(uint32_t) - 1;
            while (i-- > 0)
                if (   uBuf.au32[i] <= LNX_MAX_KALLSYMS_SYMBOLS
                    && uBuf.au32[i] >= LNX_MIN_KALLSYMS_SYMBOLS)
                {
                    uint8_t *pb = (uint8_t *)&uBuf.au32[i + 1];
                    if (   pb[0] <= LNX_MAX_KALLSYMS_ENC_LENGTH
                        && pb[0] >= LNX_MIN_KALLSYMS_ENC_LENGTH)
                    {
                        /* Check for relative base addressing. */
                        if (i >= 1 && LNX32_VALID_ADDRESS(uBuf.au32[i - 1]))
                        {
                            RTGCUINTPTR uKrnlRelBase = uBuf.au32[i - 1];
                            if (   (i <= 1 || LNX32_VALID_ADDRESS(uKrnlRelBase + uBuf.au32[i - 2]))
                                && (i <= 2 || LNX32_VALID_ADDRESS(uKrnlRelBase + uBuf.au32[i - 3])))
                            {
                                Log(("dbgDiggerLinuxFindStartOfNamesAndSymbolCount: relative base %RGv (at %RGv)\n",
                                     uKrnlRelBase, CurAddr.FlatPtr + (i - 1) * sizeof(uint32_t)));
                                pThis->fRelKrnlAddr = true;
                                pThis->uKernelRelativeBase = uKrnlRelBase;
                                return dbgDiggerLinuxFoundStartOfNames(pThis, pVMM,
                                                                       pVMM->pfnDBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint32_t)),
                                                                       uBuf.au32[i], sizeof(uint32_t));
                            }
                        }

                        if (   (i <= 0 || LNX32_VALID_ADDRESS(uBuf.au32[i - 1]))
                            && (i <= 1 || LNX32_VALID_ADDRESS(uBuf.au32[i - 2]))
                            && (i <= 2 || LNX32_VALID_ADDRESS(uBuf.au32[i - 3])))
                            return dbgDiggerLinuxFoundStartOfNames(pThis, pVMM,
                                                                   pVMM->pfnDBGFR3AddrAdd(&CurAddr, (i + 1) * sizeof(uint32_t)),
                                                                   uBuf.au32[i], sizeof(uint32_t));
                    }
                }
        }

        /*
         * Advance
         */
        if (RT_UNLIKELY(cbLeft <= sizeof(uBuf)))
        {
            Log(("dbgDiggerLinuxFindStartOfNamesAndSymbolCount: failed (pHitAddr=%RGv)\n", pHitAddr->FlatPtr));
            return VERR_NOT_FOUND;
        }
        cbLeft -= sizeof(uBuf);
        pVMM->pfnDBGFR3AddrSub(&CurAddr, sizeof(uBuf));
        cbBuf = sizeof(uBuf);
    }
}


/**
 * Worker for dbgDiggerLinuxFindEndNames that records the findings.
 *
 * @returns VINF_SUCCESS
 * @param   pThis           The linux digger data to update.
 * @param   pVMM                The VMM function table.
 * @param   pAddrMarkers    The address of the marker (kallsyms_markers).
 * @param   cbMarkerEntry   The size of a marker entry (32-bit or 64-bit).
 */
static int dbgDiggerLinuxFoundMarkers(PDBGDIGGERLINUX pThis, PCVMMR3VTABLE pVMM,
                                      PCDBGFADDRESS pAddrMarkers, uint32_t cbMarkerEntry)
{
    pThis->cbKernelNames         = pAddrMarkers->FlatPtr - pThis->AddrKernelNames.FlatPtr;
    pThis->AddrKernelNameMarkers = *pAddrMarkers;
    pThis->cKernelNameMarkers    = RT_ALIGN_32(pThis->cKernelSymbols, 256) / 256;
    pThis->AddrKernelTokenTable  = *pAddrMarkers;
    pVMM->pfnDBGFR3AddrAdd(&pThis->AddrKernelTokenTable, pThis->cKernelNameMarkers * cbMarkerEntry);

    Log(("dbgDiggerLinuxFoundMarkers: AddrKernelNames=%RGv cbKernelNames=%#x\n"
         "dbgDiggerLinuxFoundMarkers: AddrKernelNameMarkers=%RGv cKernelNameMarkers=%#x\n"
         "dbgDiggerLinuxFoundMarkers: AddrKernelTokenTable=%RGv\n",
         pThis->AddrKernelNames.FlatPtr, pThis->cbKernelNames,
         pThis->AddrKernelNameMarkers.FlatPtr, pThis->cKernelNameMarkers,
         pThis->AddrKernelTokenTable.FlatPtr));
    return VINF_SUCCESS;
}


/**
 * Tries to find the end of kallsyms_names and thereby the start of
 * kallsyms_markers and kallsyms_token_table.
 *
 * The kallsyms_names size is stored in pThis->cbKernelNames, the addresses of
 * the two other symbols in pThis->AddrKernelNameMarkers and
 * pThis->AddrKernelTokenTable.  The number of marker entries is stored in
 * pThis->cKernelNameMarkers.
 *
 * @returns VBox status code, success indicating that all three variables have
 *          been found and taken down.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 * @param   pHitAddr            An address we think is inside kallsyms_names.
 */
static int dbgDiggerLinuxFindEndOfNamesAndMore(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis, PCDBGFADDRESS pHitAddr)
{
    /*
     * Search forward in chunks.
     */
    union
    {
        uint8_t  ab[0x1000];
        uint32_t au32[0x1000 / sizeof(uint32_t)];
        uint64_t au64[0x1000 / sizeof(uint64_t)];
    } uBuf;
    bool            fPendingZeroHit = false;
    uint32_t        cbLeft  = LNX_MAX_KALLSYMS_NAMES_SIZE + sizeof(uBuf);
    uint32_t        offBuf  = pHitAddr->FlatPtr & (sizeof(uBuf) - 1);
    DBGFADDRESS     CurAddr = *pHitAddr;
    pVMM->pfnDBGFR3AddrSub(&CurAddr, offBuf);
    for (;;)
    {
        int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &CurAddr, &uBuf, sizeof(uBuf));
        if (RT_FAILURE(rc))
            return rc;

        /*
         * The kallsyms_names table is followed by kallsyms_markers we assume,
         * using sizeof(unsigned long) alignment like the preceeding symbols.
         *
         * The kallsyms_markers table has entried sizeof(unsigned long) and
         * contains offsets into kallsyms_names.  The kallsyms_markers used to
         * index kallsyms_names and reduce seek time when looking up the name
         * of an address/symbol.  Each entry in kallsyms_markers covers 256
         * symbol names.
         *
         * Because of this, the first entry is always zero and all the entries
         * are ascending.  It also follows that the size of the table can be
         * calculated from kallsyms_num_syms.
         *
         * Note! We could also have walked kallsyms_names by skipping
         *       kallsyms_num_syms names, but this is faster and we will
         *       validate the encoded names later.
         *
         * git commit 80ffbaa5b1bd98e80e3239a3b8cfda2da433009a (which became 4.20+) makes kallsyms_markers
         * and kallsyms_num_syms uint32_t, even on 64bit systems. Take that into account.
         */
        if (   pThis->f64Bit
            && pThis->uKrnlVer < LNX_MK_VER(4, 20, 0))
        {
            if (   RT_UNLIKELY(fPendingZeroHit)
                && uBuf.au64[0] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
                && uBuf.au64[0] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
                return dbgDiggerLinuxFoundMarkers(pThis, pVMM,
                                                  pVMM->pfnDBGFR3AddrSub(&CurAddr, sizeof(uint64_t)), sizeof(uint64_t));

            uint32_t const cEntries = sizeof(uBuf) / sizeof(uint64_t);
            for (uint32_t i = offBuf / sizeof(uint64_t); i < cEntries; i++)
                if (uBuf.au64[i] == 0)
                {
                    if (RT_UNLIKELY(i + 1 >= cEntries))
                    {
                        fPendingZeroHit = true;
                        break;
                    }
                    if (   uBuf.au64[i + 1] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
                        && uBuf.au64[i + 1] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
                        return dbgDiggerLinuxFoundMarkers(pThis, pVMM,
                                                          pVMM->pfnDBGFR3AddrAdd(&CurAddr, i * sizeof(uint64_t)), sizeof(uint64_t));
                }
        }
        else
        {
            if (   RT_UNLIKELY(fPendingZeroHit)
                && uBuf.au32[0] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
                && uBuf.au32[0] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
                return dbgDiggerLinuxFoundMarkers(pThis, pVMM,
                                                  pVMM->pfnDBGFR3AddrSub(&CurAddr, sizeof(uint32_t)), sizeof(uint32_t));

            uint32_t const cEntries = sizeof(uBuf) / sizeof(uint32_t);
            for (uint32_t i = offBuf / sizeof(uint32_t); i < cEntries; i++)
                if (uBuf.au32[i] == 0)
                {
                    if (RT_UNLIKELY(i + 1 >= cEntries))
                    {
                        fPendingZeroHit = true;
                        break;
                    }
                    if (   uBuf.au32[i + 1] >= (LNX_MIN_KALLSYMS_ENC_LENGTH + 1) * 256
                        && uBuf.au32[i + 1] <= (LNX_MAX_KALLSYMS_ENC_LENGTH + 1) * 256)
                        return dbgDiggerLinuxFoundMarkers(pThis, pVMM,
                                                          pVMM->pfnDBGFR3AddrAdd(&CurAddr, i * sizeof(uint32_t)), sizeof(uint32_t));
                }
        }

        /*
         * Advance
         */
        if (RT_UNLIKELY(cbLeft <= sizeof(uBuf)))
        {
            Log(("dbgDiggerLinuxFindEndOfNamesAndMore: failed (pHitAddr=%RGv)\n", pHitAddr->FlatPtr));
            return VERR_NOT_FOUND;
        }
        cbLeft -= sizeof(uBuf);
        pVMM->pfnDBGFR3AddrAdd(&CurAddr, sizeof(uBuf));
        offBuf = 0;
    }
}


/**
 * Locates the kallsyms_token_index table.
 *
 * Storing the address in pThis->AddrKernelTokenIndex and the size of the token
 * table in pThis->cbKernelTokenTable.
 *
 * @returns VBox status code.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 */
static int dbgDiggerLinuxFindTokenIndex(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis)
{
    /*
     * The kallsyms_token_table is very much like a string table.  Due to the
     * nature of the compression algorithm it is reasonably short (one example
     * here is 853 bytes), so we'll not be reading it in chunks but in full.
     * To be on the safe side, we read 8KB, ASSUMING we won't run into unmapped
     * memory or any other nasty stuff...
     */
    union
    {
        uint8_t  ab[0x2000];
        uint16_t au16[0x2000 / sizeof(uint16_t)];
    } uBuf;
    DBGFADDRESS CurAddr = pThis->AddrKernelTokenTable;
    int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &CurAddr, &uBuf, sizeof(uBuf));
    if (RT_FAILURE(rc))
        return rc;

    /*
     * We've got two choices here, either walk the string table or look for
     * the next structure, kallsyms_token_index.
     *
     * The token index is a table of 256 uint16_t entries (index by bytes
     * from kallsyms_names) that gives offsets in kallsyms_token_table.  It
     * starts with a zero entry and the following entries are sorted in
     * ascending order.  The range of the entries are reasonably small since
     * kallsyms_token_table is small.
     *
     * The alignment seems to be sizeof(unsigned long), just like
     * kallsyms_token_table.
     *
     * So, we start by looking for a zero 16-bit entry.
     */
    uint32_t cIncr = (pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t)) / sizeof(uint16_t);

    for (uint32_t i = 0; i < sizeof(uBuf) / sizeof(uint16_t) - 16; i += cIncr)
        if (   uBuf.au16[i] == 0
            && uBuf.au16[i + 1] >  0
            && uBuf.au16[i + 1] <= LNX_MAX_KALLSYMS_TOKEN_LEN
            && (uint16_t)(uBuf.au16[i + 2] - uBuf.au16[i + 1] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
            && (uint16_t)(uBuf.au16[i + 3] - uBuf.au16[i + 2] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
            && (uint16_t)(uBuf.au16[i + 4] - uBuf.au16[i + 3] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
            && (uint16_t)(uBuf.au16[i + 5] - uBuf.au16[i + 4] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
            && (uint16_t)(uBuf.au16[i + 6] - uBuf.au16[i + 5] - 1U) <= (uint16_t)LNX_MAX_KALLSYMS_TOKEN_LEN
            )
        {
            pThis->AddrKernelTokenIndex = CurAddr;
            pVMM->pfnDBGFR3AddrAdd(&pThis->AddrKernelTokenIndex, i * sizeof(uint16_t));
            pThis->cbKernelTokenTable = i * sizeof(uint16_t);
            return VINF_SUCCESS;
        }

    Log(("dbgDiggerLinuxFindTokenIndex: Failed (%RGv..%RGv)\n", CurAddr.FlatPtr, CurAddr.FlatPtr + (RTGCUINTPTR)sizeof(uBuf)));
    return VERR_NOT_FOUND;
}


/**
 * Loads the kernel symbols from the given kallsyms offset table decoding the symbol names
 * (worker common for dbgDiggerLinuxLoadKernelSymbolsAbsolute() and dbgDiggerLinuxLoadKernelSymbolsRelative()).
 *
 * @returns VBox status code.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 * @param   uKernelStart        Flat kernel start address.
 * @param   cbKernel            Size of the kernel in bytes.
 * @param   pauSymOff           Pointer to the array of symbol offsets in the kallsyms table
 *                              relative to the start of the kernel.
 */
static int dbgDiggerLinuxLoadKernelSymbolsWorker(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis, RTGCUINTPTR uKernelStart,
                                                 RTGCUINTPTR cbKernel, RTGCUINTPTR *pauSymOff)
{
    uint8_t *pbNames = (uint8_t *)RTMemAllocZ(pThis->cbKernelNames);
    int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelNames, pbNames, pThis->cbKernelNames);
    if (RT_SUCCESS(rc))
    {
        char *pszzTokens = (char *)RTMemAllocZ(pThis->cbKernelTokenTable);
        rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelTokenTable, pszzTokens, pThis->cbKernelTokenTable);
        if (RT_SUCCESS(rc))
        {
            uint16_t *paoffTokens = (uint16_t *)RTMemAllocZ(256 * sizeof(uint16_t));
            rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelTokenIndex, paoffTokens, 256 * sizeof(uint16_t));
            if (RT_SUCCESS(rc))
            {
                /*
                 * Create a module for the kernel.
                 */
                RTDBGMOD hMod;
                rc = RTDbgModCreate(&hMod, "vmlinux", cbKernel, 0 /*fFlags*/);
                if (RT_SUCCESS(rc))
                {
                    rc = RTDbgModSetTag(hMod, DIG_LNX_MOD_TAG); AssertRC(rc);
                    rc = VINF_SUCCESS;

                    /*
                     * Enumerate the symbols.
                     */
                    uint32_t        offName   = 0;
                    uint32_t        cLeft = pThis->cKernelSymbols;
                    while (cLeft-- > 0 && RT_SUCCESS(rc))
                    {
                        /* Decode the symbol name first. */
                        if (RT_LIKELY(offName < pThis->cbKernelNames))
                        {
                            uint8_t cbName = pbNames[offName++];
                            if (RT_LIKELY(offName + cbName <= pThis->cbKernelNames))
                            {
                                char     szSymbol[4096];
                                uint32_t offSymbol = 0;
                                while (cbName-- > 0)
                                {
                                    uint8_t  bEnc     = pbNames[offName++];
                                    uint16_t offToken = paoffTokens[bEnc];
                                    if (RT_LIKELY(offToken < pThis->cbKernelTokenTable))
                                    {
                                        const char *pszToken = &pszzTokens[offToken];
                                        char ch;
                                        while ((ch = *pszToken++) != '\0')
                                            if (offSymbol < sizeof(szSymbol) - 1)
                                                szSymbol[offSymbol++] = ch;
                                    }
                                    else
                                    {
                                        rc = VERR_INVALID_UTF8_ENCODING;
                                        break;
                                    }
                                }
                                szSymbol[offSymbol < sizeof(szSymbol) ? offSymbol : sizeof(szSymbol) - 1] = '\0';

                                /* The offset. */
                                RTGCUINTPTR uSymOff = *pauSymOff;
                                pauSymOff++;

                                /* Add it without the type char. */
                                if (uSymOff <= cbKernel)
                                {
                                    rc = RTDbgModSymbolAdd(hMod, &szSymbol[1], RTDBGSEGIDX_RVA, uSymOff,
                                                           0 /*cb*/, 0 /*fFlags*/, NULL);
                                    if (RT_FAILURE(rc))
                                    {
                                        if (   rc == VERR_DBG_SYMBOL_NAME_OUT_OF_RANGE
                                            || rc == VERR_DBG_INVALID_RVA
                                            || rc == VERR_DBG_ADDRESS_CONFLICT
                                            || rc == VERR_DBG_DUPLICATE_SYMBOL)
                                        {
                                            Log2(("dbgDiggerLinuxLoadKernelSymbols: RTDbgModSymbolAdd(,%s,) failed %Rrc (ignored)\n", szSymbol, rc));
                                            rc = VINF_SUCCESS;
                                        }
                                        else
                                            Log(("dbgDiggerLinuxLoadKernelSymbols: RTDbgModSymbolAdd(,%s,) failed %Rrc\n", szSymbol, rc));
                                    }
                                }
                            }
                            else
                            {
                                rc = VERR_END_OF_STRING;
                                Log(("dbgDiggerLinuxLoadKernelSymbols: offName=%#x cLeft=%#x cbName=%#x cbKernelNames=%#x\n",
                                     offName, cLeft, cbName, pThis->cbKernelNames));
                            }
                        }
                        else
                        {
                            rc = VERR_END_OF_STRING;
                            Log(("dbgDiggerLinuxLoadKernelSymbols: offName=%#x cLeft=%#x cbKernelNames=%#x\n",
                                 offName, cLeft, pThis->cbKernelNames));
                        }
                    }

                    /*
                     * Link the module into the address space.
                     */
                    if (RT_SUCCESS(rc))
                    {
                        RTDBGAS hAs = pVMM->pfnDBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
                        if (hAs != NIL_RTDBGAS)
                            rc = RTDbgAsModuleLink(hAs, hMod, uKernelStart, RTDBGASLINK_FLAGS_REPLACE);
                        else
                            rc = VERR_INTERNAL_ERROR;
                        RTDbgAsRelease(hAs);
                    }
                    else
                        Log(("dbgDiggerLinuxLoadKernelSymbols: Failed: %Rrc\n", rc));
                    RTDbgModRelease(hMod);
                }
                else
                    Log(("dbgDiggerLinuxLoadKernelSymbols: RTDbgModCreate failed: %Rrc\n", rc));
            }
            else
                Log(("dbgDiggerLinuxLoadKernelSymbols: Reading token index at %RGv failed: %Rrc\n",
                     pThis->AddrKernelTokenIndex.FlatPtr, rc));
            RTMemFree(paoffTokens);
        }
        else
            Log(("dbgDiggerLinuxLoadKernelSymbols: Reading token table at %RGv failed: %Rrc\n",
                 pThis->AddrKernelTokenTable.FlatPtr, rc));
        RTMemFree(pszzTokens);
    }
    else
        Log(("dbgDiggerLinuxLoadKernelSymbols: Reading encoded names at %RGv failed: %Rrc\n",
             pThis->AddrKernelNames.FlatPtr, rc));
    RTMemFree(pbNames);

    return rc;
}

/**
 * Loads the kernel symbols from the kallsyms table if it contains absolute addresses
 *
 * @returns VBox status code.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 */
static int dbgDiggerLinuxLoadKernelSymbolsAbsolute(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis)
{
    /*
     * Allocate memory for temporary table copies, reading the tables as we go.
     */
    uint32_t const cbGuestAddr = pThis->f64Bit ? sizeof(uint64_t) : sizeof(uint32_t);
    void *pvAddresses = RTMemAllocZ(pThis->cKernelSymbols * cbGuestAddr);
    int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelAddresses,
                                    pvAddresses, pThis->cKernelSymbols * cbGuestAddr);
    if (RT_SUCCESS(rc))
    {
        /*
         * Figure out the kernel start and end and convert the absolute addresses to relative offsets.
         */
        RTGCUINTPTR uKernelStart = pThis->AddrKernelAddresses.FlatPtr;
        RTGCUINTPTR uKernelEnd   = pThis->AddrKernelTokenIndex.FlatPtr + 256 * sizeof(uint16_t);
        RTGCUINTPTR *pauSymOff   = (RTGCUINTPTR *)RTMemTmpAllocZ(pThis->cKernelSymbols * sizeof(RTGCUINTPTR));
        uint32_t    i;
        if (cbGuestAddr == sizeof(uint64_t))
        {
            uint64_t *pauAddrs = (uint64_t *)pvAddresses;
            for (i = 0; i < pThis->cKernelSymbols; i++)
                if (   pauAddrs[i] < uKernelStart
                    && LNX64_VALID_ADDRESS(pauAddrs[i])
                    && uKernelStart - pauAddrs[i] < LNX_MAX_KERNEL_SIZE)
                    uKernelStart = pauAddrs[i];

            for (i = pThis->cKernelSymbols - 1; i > 0; i--)
                if (   pauAddrs[i] > uKernelEnd
                    && LNX64_VALID_ADDRESS(pauAddrs[i])
                    && pauAddrs[i] - uKernelEnd < LNX_MAX_KERNEL_SIZE)
                    uKernelEnd = pauAddrs[i];

            for (i = 0; i < pThis->cKernelSymbols; i++)
                pauSymOff[i] = pauAddrs[i] - uKernelStart;
        }
        else
        {
            uint32_t *pauAddrs = (uint32_t *)pvAddresses;
            for (i = 0; i < pThis->cKernelSymbols; i++)
                if (   pauAddrs[i] < uKernelStart
                    && LNX32_VALID_ADDRESS(pauAddrs[i])
                    && uKernelStart - pauAddrs[i] < LNX_MAX_KERNEL_SIZE)
                    uKernelStart = pauAddrs[i];

            for (i = pThis->cKernelSymbols - 1; i > 0; i--)
                if (   pauAddrs[i] > uKernelEnd
                    && LNX32_VALID_ADDRESS(pauAddrs[i])
                    && pauAddrs[i] - uKernelEnd < LNX_MAX_KERNEL_SIZE)
                    uKernelEnd = pauAddrs[i];

            for (i = 0; i < pThis->cKernelSymbols; i++)
                pauSymOff[i] = pauAddrs[i] - uKernelStart;
        }

        RTGCUINTPTR cbKernel = uKernelEnd - uKernelStart;
        pThis->cbKernel = (uint32_t)cbKernel;
        pVMM->pfnDBGFR3AddrFromFlat(pUVM, &pThis->AddrKernelBase, uKernelStart);
        Log(("dbgDiggerLinuxLoadKernelSymbolsAbsolute: uKernelStart=%RGv cbKernel=%#x\n", uKernelStart, cbKernel));

        rc = dbgDiggerLinuxLoadKernelSymbolsWorker(pUVM, pVMM, pThis, uKernelStart, cbKernel, pauSymOff);
        if (RT_FAILURE(rc))
            Log(("dbgDiggerLinuxLoadKernelSymbolsAbsolute: Loading symbols from given offset table failed: %Rrc\n", rc));
        RTMemTmpFree(pauSymOff);
    }
    else
        Log(("dbgDiggerLinuxLoadKernelSymbolsAbsolute: Reading symbol addresses at %RGv failed: %Rrc\n",
             pThis->AddrKernelAddresses.FlatPtr, rc));
    RTMemFree(pvAddresses);

    return rc;
}


/**
 * Loads the kernel symbols from the kallsyms table if it contains absolute addresses
 *
 * @returns VBox status code.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 */
static int dbgDiggerLinuxLoadKernelSymbolsRelative(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis)
{
    /*
     * Allocate memory for temporary table copies, reading the tables as we go.
     */
    int32_t *pai32Offsets = (int32_t *)RTMemAllocZ(pThis->cKernelSymbols * sizeof(int32_t));
    int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &pThis->AddrKernelAddresses,
                                    pai32Offsets, pThis->cKernelSymbols * sizeof(int32_t));
    if (RT_SUCCESS(rc))
    {
        /*
         * Figure out the kernel start and end and convert the absolute addresses to relative offsets.
         */
        RTGCUINTPTR uKernelStart = pThis->AddrKernelAddresses.FlatPtr;
        RTGCUINTPTR uKernelEnd   = pThis->AddrKernelTokenIndex.FlatPtr + 256 * sizeof(uint16_t);
        RTGCUINTPTR *pauSymOff   = (RTGCUINTPTR *)RTMemTmpAllocZ(pThis->cKernelSymbols * sizeof(RTGCUINTPTR));
        uint32_t    i;

        for (i = 0; i < pThis->cKernelSymbols; i++)
        {
            RTGCUINTPTR uSymAddr = dbgDiggerLinuxConvOffsetToAddr(pThis, pai32Offsets[i]);

            if (   uSymAddr < uKernelStart
                && (pThis->f64Bit ? LNX64_VALID_ADDRESS(uSymAddr) : LNX32_VALID_ADDRESS(uSymAddr))
                && uKernelStart - uSymAddr < LNX_MAX_KERNEL_SIZE)
                uKernelStart = uSymAddr;
        }

        for (i = pThis->cKernelSymbols - 1; i > 0; i--)
        {
            RTGCUINTPTR uSymAddr = dbgDiggerLinuxConvOffsetToAddr(pThis, pai32Offsets[i]);

            if (   uSymAddr > uKernelEnd
                && (pThis->f64Bit ? LNX64_VALID_ADDRESS(uSymAddr) : LNX32_VALID_ADDRESS(uSymAddr))
                && uSymAddr - uKernelEnd < LNX_MAX_KERNEL_SIZE)
                uKernelEnd = uSymAddr;

            /* Store the offset from the derived kernel start address. */
            pauSymOff[i] = uSymAddr - uKernelStart;
        }

        RTGCUINTPTR cbKernel = uKernelEnd - uKernelStart;
        pThis->cbKernel = (uint32_t)cbKernel;
        pVMM->pfnDBGFR3AddrFromFlat(pUVM, &pThis->AddrKernelBase, uKernelStart);
        Log(("dbgDiggerLinuxLoadKernelSymbolsRelative: uKernelStart=%RGv cbKernel=%#x\n", uKernelStart, cbKernel));

        rc = dbgDiggerLinuxLoadKernelSymbolsWorker(pUVM, pVMM, pThis, uKernelStart, cbKernel, pauSymOff);
        if (RT_FAILURE(rc))
            Log(("dbgDiggerLinuxLoadKernelSymbolsRelative: Loading symbols from given offset table failed: %Rrc\n", rc));
        RTMemTmpFree(pauSymOff);
    }
    else
        Log(("dbgDiggerLinuxLoadKernelSymbolsRelative: Reading symbol addresses at %RGv failed: %Rrc\n",
             pThis->AddrKernelAddresses.FlatPtr, rc));
    RTMemFree(pai32Offsets);

    return rc;
}


/**
 * Loads the kernel symbols.
 *
 * @returns VBox status code.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pThis               The Linux digger data.
 */
static int dbgDiggerLinuxLoadKernelSymbols(PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGDIGGERLINUX pThis)
{
    /*
     * First the kernel itself.
     */
    if (pThis->fRelKrnlAddr)
        return dbgDiggerLinuxLoadKernelSymbolsRelative(pUVM, pVMM, pThis);
    return dbgDiggerLinuxLoadKernelSymbolsAbsolute(pUVM, pVMM, pThis);
}


/*
 * The module structure changed it was easier to produce different code for
 * each version of the structure.  The C preprocessor rules!
 */
#define LNX_TEMPLATE_HEADER "DBGPlugInLinuxModuleCodeTmpl.cpp.h"

#define LNX_BIT_SUFFIX      _amd64
#define LNX_PTR_T           uint64_t
#define LNX_64BIT           1
#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"

#define LNX_BIT_SUFFIX      _x86
#define LNX_PTR_T           uint32_t
#define LNX_64BIT           0
#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"

#undef  LNX_TEMPLATE_HEADER

static const struct
{
    uint32_t    uVersion;
    bool        f64Bit;
    uint64_t  (*pfnProcessModule)(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM, PDBGFADDRESS pAddrModule);
} g_aModVersions[] =
{
#define LNX_TEMPLATE_HEADER "DBGPlugInLinuxModuleTableEntryTmpl.cpp.h"

#define LNX_BIT_SUFFIX      _amd64
#define LNX_64BIT           1
#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"

#define LNX_BIT_SUFFIX      _x86
#define LNX_64BIT           0
#include "DBGPlugInLinuxModuleVerTmpl.cpp.h"

#undef  LNX_TEMPLATE_HEADER
};


/**
 * Tries to find and process the module list.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 */
static int dbgDiggerLinuxLoadModules(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM)
{
    /*
     * Locate the list head.
     */
    RTDBGAS     hAs = pVMM->pfnDBGFR3AsResolveAndRetain(pUVM, DBGF_AS_KERNEL);
    RTDBGSYMBOL SymInfo;
    int rc = RTDbgAsSymbolByName(hAs, "vmlinux!modules", &SymInfo, NULL);
    RTDbgAsRelease(hAs);
    if (RT_FAILURE(rc))
        return VERR_NOT_FOUND;

    if (RT_FAILURE(rc))
    {
        LogRel(("dbgDiggerLinuxLoadModules: Failed to locate the module list (%Rrc).\n", rc));
        return VERR_NOT_FOUND;
    }

    /*
     * Read the list anchor.
     */
    union
    {
        uint32_t volatile u32Pair[2];
        uint64_t u64Pair[2];
    } uListAnchor;
    DBGFADDRESS Addr;
    rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, SymInfo.Value),
                                &uListAnchor, pThis->f64Bit ? sizeof(uListAnchor.u64Pair) : sizeof(uListAnchor.u32Pair));
    if (RT_FAILURE(rc))
    {
        LogRel(("dbgDiggerLinuxLoadModules: Error reading list anchor at %RX64: %Rrc\n", SymInfo.Value, rc));
        return VERR_NOT_FOUND;
    }
    if (!pThis->f64Bit)
    {
        uListAnchor.u64Pair[1] = uListAnchor.u32Pair[1];
        ASMCompilerBarrier();
        uListAnchor.u64Pair[0] = uListAnchor.u32Pair[0];
    }

    if (pThis->uKrnlVer == 0)
    {
        LogRel(("dbgDiggerLinuxLoadModules: No valid kernel version given: %#x\n", pThis->uKrnlVer));
        return VERR_NOT_FOUND;
    }

    /*
     * Find the g_aModVersion entry that fits the best.
     * ASSUMES strict descending order by bitcount and version.
     */
    Assert(g_aModVersions[0].f64Bit == true);
    unsigned i = 0;
    if (!pThis->f64Bit)
        while (i < RT_ELEMENTS(g_aModVersions) && g_aModVersions[i].f64Bit)
            i++;
    while (   i < RT_ELEMENTS(g_aModVersions)
           && g_aModVersions[i].f64Bit == pThis->f64Bit
           && pThis->uKrnlVer < g_aModVersions[i].uVersion)
        i++;
    if (i >= RT_ELEMENTS(g_aModVersions))
    {
        LogRel(("dbgDiggerLinuxLoadModules: Failed to find anything matching version: %u.%u.%u\n",
                pThis->uKrnlVerMaj, pThis->uKrnlVerMin, pThis->uKrnlVerBld));
        return VERR_NOT_FOUND;
    }

    /*
     * Walk the list.
     */
    uint64_t uModAddr = uListAnchor.u64Pair[0];
    for (size_t iModule = 0; iModule < 4096 && uModAddr != SymInfo.Value && uModAddr != 0; iModule++)
        uModAddr = g_aModVersions[i].pfnProcessModule(pThis, pUVM, pVMM, pVMM->pfnDBGFR3AddrFromFlat(pUVM, &Addr, uModAddr));

    return VINF_SUCCESS;
}


/**
 * Checks if there is a likely kallsyms_names fragment at pHitAddr.
 *
 * @returns true if it's a likely fragment, false if not.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pHitAddr            The address where paNeedle was found.
 * @param   pabNeedle           The fragment we've been searching for.
 * @param   cbNeedle            The length of the fragment.
 */
static bool dbgDiggerLinuxIsLikelyNameFragment(PUVM pUVM, PCVMMR3VTABLE pVMM, PCDBGFADDRESS pHitAddr,
                                               uint8_t const *pabNeedle, uint8_t cbNeedle)
{
    /*
     * Examples of lead and tail bytes of our choosen needle in a randomly
     * picked kernel:
     *         k  o  b  j
     *     22  6b 6f 62 6a  aa
     *     fc  6b 6f 62 6a  aa
     *     82  6b 6f 62 6a  5f      - ascii trail byte (_).
     *     ee  6b 6f 62 6a  aa
     *     fc  6b 6f 62 6a  5f      - ascii trail byte (_).
     *  0a 74  6b 6f 62 6a  5f ea   - ascii lead (t) and trail (_) bytes.
     *  0b 54  6b 6f 62 6a  aa      - ascii lead byte (T).
     * ... omitting 29 samples similar to the last two ...
     *     d8  6b 6f 62 6a  aa
     *     d8  6b 6f 62 6a  aa
     *     d8  6b 6f 62 6a  aa
     *     d8  6b 6f 62 6a  aa
     *  f9 5f  6b 6f 62 6a  5f 94   - ascii lead and trail bytes (_)
     *  f9 5f  6b 6f 62 6a  0c      - ascii lead byte (_).
     *     fd  6b 6f 62 6a  0f
     *  ... enough.
     */
    uint8_t         abBuf[32];
    DBGFADDRESS     ReadAddr = *pHitAddr;
    pVMM->pfnDBGFR3AddrSub(&ReadAddr, 2);
    int rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, &ReadAddr, abBuf, 2 + cbNeedle + 2);
    if (RT_SUCCESS(rc))
    {
        if (memcmp(&abBuf[2], pabNeedle, cbNeedle) == 0) /* paranoia */
        {
            uint8_t const bLead = abBuf[1] == '_' || abBuf[1] == 'T' || abBuf[1] == 't' ? abBuf[0] : abBuf[1];
            uint8_t const offTail = 2 + cbNeedle;
            uint8_t const bTail = abBuf[offTail] == '_' ? abBuf[offTail] : abBuf[offTail + 1];
            if (   bLead >= 1 && (bLead < 0x20 || bLead >= 0x80)
                && bTail >= 1 && (bTail < 0x20 || bTail >= 0x80))
                return true;
            Log(("dbgDiggerLinuxIsLikelyNameFragment: failed at %RGv: bLead=%#x bTail=%#x (offTail=%#x)\n",
                 pHitAddr->FlatPtr, bLead, bTail, offTail));
        }
        else
            Log(("dbgDiggerLinuxIsLikelyNameFragment: failed at %RGv: Needle changed!\n", pHitAddr->FlatPtr));
    }
    else
        Log(("dbgDiggerLinuxIsLikelyNameFragment: failed at %RGv: %Rrc\n", pHitAddr->FlatPtr, rc));

    return false;
}

/**
 * Tries to find and load the kernel symbol table with the given needle.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pabNeedle           The needle to use for searching.
 * @param   cbNeedle            Size of the needle in bytes.
 */
static int dbgDiggerLinuxFindSymbolTableFromNeedle(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
                                                   uint8_t const *pabNeedle, uint8_t cbNeedle)
{
    /*
     * Go looking for the kallsyms table.  If it's there, it will be somewhere
     * after the linux_banner symbol, so use it for starting the search.
     */
    int         rc      = VINF_SUCCESS;
    DBGFADDRESS CurAddr = pThis->AddrLinuxBanner;
    uint32_t    cbLeft  = LNX_MAX_KERNEL_SIZE;
    while (cbLeft > 4096)
    {
        DBGFADDRESS          HitAddr;
        rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &CurAddr, cbLeft, 1 /*uAlign*/,
                                    pabNeedle, cbNeedle, &HitAddr);
        if (RT_FAILURE(rc))
            break;
        if (dbgDiggerLinuxIsLikelyNameFragment(pUVM, pVMM, &HitAddr, pabNeedle, cbNeedle))
        {
            /* There will be another hit near by. */
            pVMM->pfnDBGFR3AddrAdd(&HitAddr, 1);
            rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &HitAddr, LNX_MAX_KALLSYMS_NAMES_SIZE, 1 /*uAlign*/,
                                        pabNeedle, cbNeedle, &HitAddr);
            if (   RT_SUCCESS(rc)
                && dbgDiggerLinuxIsLikelyNameFragment(pUVM, pVMM, &HitAddr, pabNeedle, cbNeedle))
            {
                /*
                 * We've got a very likely candidate for a location inside kallsyms_names.
                 * Try find the start of it, that is to say, try find kallsyms_num_syms.
                 * kallsyms_num_syms is aligned on sizeof(unsigned long) boundrary
                 */
                rc = dbgDiggerLinuxFindStartOfNamesAndSymbolCount(pUVM, pVMM, pThis, &HitAddr);
                if (RT_SUCCESS(rc))
                    rc = dbgDiggerLinuxFindEndOfNamesAndMore(pUVM, pVMM, pThis, &HitAddr);
                if (RT_SUCCESS(rc))
                    rc = dbgDiggerLinuxFindTokenIndex(pUVM, pVMM, pThis);
                if (RT_SUCCESS(rc))
                    rc = dbgDiggerLinuxLoadKernelSymbols(pUVM, pVMM, pThis);
                if (RT_SUCCESS(rc))
                {
                    rc = dbgDiggerLinuxLoadModules(pThis, pUVM, pVMM);
                    break;
                }
            }
        }

        /*
         * Advance.
         */
        RTGCUINTPTR cbDistance = HitAddr.FlatPtr - CurAddr.FlatPtr + cbNeedle;
        if (RT_UNLIKELY(cbDistance >= cbLeft))
        {
            Log(("dbgDiggerLinuxInit: Failed to find kallsyms\n"));
            break;
        }
        cbLeft -= cbDistance;
        pVMM->pfnDBGFR3AddrAdd(&CurAddr, cbDistance);
    }

    return rc;
}

/**
 * Skips whitespace and comments in the given config returning the pointer
 * to the first non whitespace character.
 *
 * @returns Pointer to the first non whitespace character or NULL if the end
 *          of the string was reached.
 * @param   pszCfg              The config string.
 */
static const char *dbgDiggerLinuxCfgSkipWhitespace(const char *pszCfg)
{
    do
    {
        while (   *pszCfg != '\0'
               && (   RT_C_IS_SPACE(*pszCfg)
                   || *pszCfg == '\n'))
            pszCfg++;

        /* Do we have a comment? Skip it. */
        if (*pszCfg == '#')
        {
            while (   *pszCfg != '\n'
                   && *pszCfg != '\0')
                pszCfg++;
        }
    } while (   *pszCfg != '\0'
             && (   RT_C_IS_SPACE(*pszCfg)
                 || *pszCfg == '\n'
                 || *pszCfg == '#'));

    return pszCfg;
}

/**
 * Parses an identifier at the given position.
 *
 * @returns VBox status code.
 * @param   pszCfg              The config data.
 * @param   ppszCfgNext         Where to store the pointer to the data following the identifier.
 * @param   ppszIde             Where to store the pointer to the identifier on success.
 *                              Free with RTStrFree().
 */
static int dbgDiggerLinuxCfgParseIde(const char *pszCfg, const char **ppszCfgNext, char **ppszIde)
{
    int rc = VINF_SUCCESS;
    size_t cchIde = 0;

    while (   *pszCfg != '\0'
           && (   RT_C_IS_ALNUM(*pszCfg)
               || *pszCfg == '_'))
    {
        cchIde++;
        pszCfg++;
    }

    if (cchIde)
    {
        *ppszIde = RTStrDupN(pszCfg - cchIde, cchIde);
        if (!*ppszIde)
            rc = VERR_NO_STR_MEMORY;
    }

    *ppszCfgNext = pszCfg;
    return rc;
}

/**
 * Parses a value for a config item.
 *
 * @returns VBox status code.
 * @param   pszCfg              The config data.
 * @param   ppszCfgNext         Where to store the pointer to the data following the identifier.
 * @param   ppCfgItem           Where to store the created config item on success.
 */
static int dbgDiggerLinuxCfgParseVal(const char *pszCfg, const char **ppszCfgNext,
                                     PDBGDIGGERLINUXCFGITEM *ppCfgItem)
{
    int rc = VINF_SUCCESS;
    PDBGDIGGERLINUXCFGITEM pCfgItem = NULL;

    if (RT_C_IS_DIGIT(*pszCfg) || *pszCfg == '-')
    {
        /* Parse the number. */
        int64_t i64Num;
        rc = RTStrToInt64Ex(pszCfg, (char **)ppszCfgNext, 0, &i64Num);
        if (   RT_SUCCESS(rc)
            || rc == VWRN_TRAILING_CHARS
            || rc == VWRN_TRAILING_SPACES)
        {
            pCfgItem = (PDBGDIGGERLINUXCFGITEM)RTMemAllocZ(sizeof(DBGDIGGERLINUXCFGITEM));
            if (pCfgItem)
            {
                pCfgItem->enmType = DBGDIGGERLINUXCFGITEMTYPE_NUMBER;
                pCfgItem->u.i64Num = i64Num;
            }
            else
                rc = VERR_NO_MEMORY;
        }
    }
    else if (*pszCfg == '\"')
    {
        /* Parse a string. */
        const char *pszCfgCur = pszCfg + 1;
        while (   *pszCfgCur != '\0'
               && *pszCfgCur != '\"')
            pszCfgCur++;

        if (*pszCfgCur == '\"')
        {
            pCfgItem = (PDBGDIGGERLINUXCFGITEM)RTMemAllocZ(RT_UOFFSETOF_DYN(DBGDIGGERLINUXCFGITEM,
                                                                            u.aszString[pszCfgCur - pszCfg + 1]));
            if (pCfgItem)
            {
                pCfgItem->enmType = DBGDIGGERLINUXCFGITEMTYPE_STRING;
                RTStrCopyEx(&pCfgItem->u.aszString[0], pszCfgCur - pszCfg + 1, pszCfg, pszCfgCur - pszCfg);
                *ppszCfgNext = pszCfgCur + 1;
            }
            else
                rc = VERR_NO_MEMORY;
        }
        else
            rc = VERR_INVALID_STATE;
    }
    else if (   *pszCfg == 'y'
             || *pszCfg == 'm')
    {
        /* Included or module. */
        pCfgItem = (PDBGDIGGERLINUXCFGITEM)RTMemAllocZ(sizeof(DBGDIGGERLINUXCFGITEM));
        if (pCfgItem)
        {
            pCfgItem->enmType = DBGDIGGERLINUXCFGITEMTYPE_FLAG;
            pCfgItem->u.fModule = *pszCfg == 'm';
        }
        else
            rc = VERR_NO_MEMORY;
        pszCfg++;
        *ppszCfgNext = pszCfg;
    }
    else
        rc = VERR_INVALID_STATE;

    if (RT_SUCCESS(rc))
        *ppCfgItem = pCfgItem;
    else if (pCfgItem)
        RTMemFree(pCfgItem);

    return rc;
}

/**
 * Parses the given kernel config and creates the config database.
 *
 * @returns VBox status code
 * @param   pThis               The Linux digger data.
 * @param   pszCfg              The config string.
 */
static int dbgDiggerLinuxCfgParse(PDBGDIGGERLINUX pThis, const char *pszCfg)
{
    int rc = VINF_SUCCESS;

    /*
     * The config is a text file with the following elements:
     *     # starts a comment which goes till the end of the line
     *     <Ide>=<val> where <Ide> is an identifier consisting of
     *                 alphanumerical characters (including _)
     *     <val> denotes the value for the identifier and can have the following
     *           formats:
     *               (-)[0-9]* for numbers
     *               "..."     for a string value
     *               m         when a feature is enabled as a module
     *               y         when a feature is enabled
     * Newlines are used as a separator between values and mark the end
     * of a comment
     */
    const char *pszCfgCur = pszCfg;
    while (   RT_SUCCESS(rc)
           && *pszCfgCur != '\0')
    {
        /* Start skipping the whitespace. */
        pszCfgCur = dbgDiggerLinuxCfgSkipWhitespace(pszCfgCur);
        if (   pszCfgCur
            && *pszCfgCur != '\0')
        {
            char *pszIde = NULL;
            /* Must be an identifier, parse it. */
            rc = dbgDiggerLinuxCfgParseIde(pszCfgCur, &pszCfgCur, &pszIde);
            if (RT_SUCCESS(rc))
            {
                /*
                 * Skip whitespace again (shouldn't be required because = follows immediately
                 * in the observed configs).
                 */
                pszCfgCur = dbgDiggerLinuxCfgSkipWhitespace(pszCfgCur);
                if (   pszCfgCur
                    && *pszCfgCur == '=')
                {
                    pszCfgCur++;
                    pszCfgCur = dbgDiggerLinuxCfgSkipWhitespace(pszCfgCur);
                    if (   pszCfgCur
                        && *pszCfgCur != '\0')
                    {
                        /* Get the value. */
                        PDBGDIGGERLINUXCFGITEM pCfgItem = NULL;
                        rc = dbgDiggerLinuxCfgParseVal(pszCfgCur, &pszCfgCur, &pCfgItem);
                        if (RT_SUCCESS(rc))
                        {
                            pCfgItem->Core.pszString = pszIde;
                            bool fRc = RTStrSpaceInsert(&pThis->hCfgDb, &pCfgItem->Core);
                            if (!fRc)
                            {
                                RTStrFree(pszIde);
                                RTMemFree(pCfgItem);
                                rc = VERR_INVALID_STATE;
                            }
                        }
                    }
                    else
                        rc = VERR_EOF;
                }
                else
                    rc = VERR_INVALID_STATE;
            }

            if (RT_FAILURE(rc))
                RTStrFree(pszIde);
        }
        else
            break; /* Reached the end of the config. */
    }

    if (RT_FAILURE(rc))
        dbgDiggerLinuxCfgDbDestroy(pThis);

    return rc;
}

/**
 * Decompresses the given config and validates the UTF-8 encoding.
 *
 * @returns VBox status code.
 * @param   pbCfgComp           The compressed config.
 * @param   cbCfgComp           Size of the compressed config.
 * @param   ppszCfg             Where to store the pointer to the decompressed config
 *                              on success.
 */
static int dbgDiggerLinuxCfgDecompress(const uint8_t *pbCfgComp, size_t cbCfgComp, char **ppszCfg)
{
    int rc = VINF_SUCCESS;
    RTVFSIOSTREAM hVfsIos = NIL_RTVFSIOSTREAM;

    rc = RTVfsIoStrmFromBuffer(RTFILE_O_READ, pbCfgComp, cbCfgComp, &hVfsIos);
    if (RT_SUCCESS(rc))
    {
        RTVFSIOSTREAM hVfsIosDecomp = NIL_RTVFSIOSTREAM;
        rc = RTZipGzipDecompressIoStream(hVfsIos, RTZIPGZIPDECOMP_F_ALLOW_ZLIB_HDR, &hVfsIosDecomp);
        if (RT_SUCCESS(rc))
        {
            char *pszCfg = NULL;
            size_t cchCfg = 0;
            size_t cbRead = 0;

            do
            {
                uint8_t abBuf[_64K];
                rc = RTVfsIoStrmRead(hVfsIosDecomp, abBuf, sizeof(abBuf), true /*fBlocking*/, &cbRead);
                if (rc == VINF_EOF && cbRead == 0)
                    rc = VINF_SUCCESS;
                if (   RT_SUCCESS(rc)
                    && cbRead > 0)
                {
                    /* Append data. */
                    char *pszCfgNew = pszCfg;
                    rc = RTStrRealloc(&pszCfgNew, cchCfg + cbRead + 1);
                    if (RT_SUCCESS(rc))
                    {
                        pszCfg = pszCfgNew;
                        memcpy(pszCfg + cchCfg, &abBuf[0], cbRead);
                        cchCfg += cbRead;
                        pszCfg[cchCfg] = '\0'; /* Enforce string termination. */
                    }
                }
            } while (RT_SUCCESS(rc) && cbRead > 0);

            if (RT_SUCCESS(rc))
                *ppszCfg = pszCfg;
            else if (RT_FAILURE(rc) && pszCfg)
                RTStrFree(pszCfg);

            RTVfsIoStrmRelease(hVfsIosDecomp);
        }
        RTVfsIoStrmRelease(hVfsIos);
    }

    return rc;
}

/**
 * Reads and decodes the compressed kernel config.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   pAddrStart          The start address of the compressed config.
 * @param   cbCfgComp           The size of the compressed config.
 */
static int dbgDiggerLinuxCfgDecode(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
                                   PCDBGFADDRESS pAddrStart, size_t cbCfgComp)
{
    int rc = VINF_SUCCESS;
    uint8_t *pbCfgComp = (uint8_t *)RTMemTmpAlloc(cbCfgComp);
    if (!pbCfgComp)
        return VERR_NO_MEMORY;

    rc = pVMM->pfnDBGFR3MemRead(pUVM, 0 /*idCpu*/, pAddrStart, pbCfgComp, cbCfgComp);
    if (RT_SUCCESS(rc))
    {
        char *pszCfg = NULL;
        rc = dbgDiggerLinuxCfgDecompress(pbCfgComp, cbCfgComp, &pszCfg);
        if (RT_SUCCESS(rc))
        {
            if (RTStrIsValidEncoding(pszCfg))
                rc = dbgDiggerLinuxCfgParse(pThis, pszCfg);
            else
                rc = VERR_INVALID_UTF8_ENCODING;
            RTStrFree(pszCfg);
        }
    }

    RTMemFree(pbCfgComp);
    return rc;
}

/**
 * Tries to find the compressed kernel config in the kernel address space
 * and sets up the config database.
 *
 * @returns VBox status code.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 */
static int dbgDiggerLinuxCfgFind(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM)
{
    /*
     * Go looking for the IKCFG_ST string which indicates the start
     * of the compressed config file.
     */
    static const uint8_t s_abCfgNeedleStart[] = "IKCFG_ST";
    static const uint8_t s_abCfgNeedleEnd[] = "IKCFG_ED";
    int         rc      = VINF_SUCCESS;
    DBGFADDRESS CurAddr = pThis->AddrLinuxBanner;
    uint32_t    cbLeft  = LNX_MAX_KERNEL_SIZE;
    while (cbLeft > 4096)
    {
        DBGFADDRESS HitAddrStart;
        rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /*idCpu*/, &CurAddr, cbLeft, 1 /*uAlign*/,
                                    s_abCfgNeedleStart, sizeof(s_abCfgNeedleStart) - 1, &HitAddrStart);
        if (RT_FAILURE(rc))
            break;

        /* Check for the end marker which shouldn't be that far away. */
        pVMM->pfnDBGFR3AddrAdd(&HitAddrStart, sizeof(s_abCfgNeedleStart) - 1);
        DBGFADDRESS HitAddrEnd;
        rc = pVMM->pfnDBGFR3MemScan(pUVM, 0 /* idCpu */, &HitAddrStart, LNX_MAX_COMPRESSED_CFG_SIZE,
                                    1 /* uAlign */, s_abCfgNeedleEnd, sizeof(s_abCfgNeedleEnd) - 1, &HitAddrEnd);
        if (RT_SUCCESS(rc))
        {
            /* Allocate a buffer to hold the compressed data between the markers and fetch it. */
            RTGCUINTPTR cbCfg = HitAddrEnd.FlatPtr - HitAddrStart.FlatPtr;
            Assert(cbCfg == (size_t)cbCfg);
            rc = dbgDiggerLinuxCfgDecode(pThis, pUVM, pVMM, &HitAddrStart, cbCfg);
            if (RT_SUCCESS(rc))
                break;
        }

        /*
         * Advance.
         */
        RTGCUINTPTR cbDistance = HitAddrStart.FlatPtr - CurAddr.FlatPtr + sizeof(s_abCfgNeedleStart) - 1;
        if (RT_UNLIKELY(cbDistance >= cbLeft))
        {
            LogFunc(("Failed to find compressed kernel config\n"));
            break;
        }
        cbLeft -= cbDistance;
        pVMM->pfnDBGFR3AddrAdd(&CurAddr, cbDistance);
    }

    return rc;
}

/**
 * Probes for a Linux kernel starting at the given address.
 *
 * @returns Flag whether something which looks like a valid Linux kernel was found.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 * @param   uAddrStart          The address to start scanning at.
 * @param   cbScan              How much to scan.
 */
static bool dbgDiggerLinuxProbeWithAddr(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM,
                                        RTGCUINTPTR uAddrStart, size_t cbScan)
{
    /*
     * Look for "Linux version " at the start of the rodata segment.
     * Hope that this comes before any message buffer or other similar string.
     */
    DBGFADDRESS KernelAddr;
    pVMM->pfnDBGFR3AddrFromFlat(pUVM, &KernelAddr, uAddrStart);
    DBGFADDRESS HitAddr;
    int rc = pVMM->pfnDBGFR3MemScan(pUVM, 0, &KernelAddr, cbScan, 1,
                                    g_abLinuxVersion, sizeof(g_abLinuxVersion) - 1, &HitAddr);
    if (RT_SUCCESS(rc))
    {
        char szTmp[128];
        char const *pszX = &szTmp[sizeof(g_abLinuxVersion) - 1];
        rc = pVMM->pfnDBGFR3MemReadString(pUVM, 0, &HitAddr, szTmp, sizeof(szTmp));
        if (    RT_SUCCESS(rc)
            &&  (   (   pszX[0] == '2'  /* 2.x.y with x in {0..6} */
                     && pszX[1] == '.'
                     && pszX[2] >= '0'
                     && pszX[2] <= '6')
                 || (   pszX[0] >= '3'  /* 3.x, 4.x, ... 9.x */
                     && pszX[0] <= '9'
                     && pszX[1] == '.'
                     && pszX[2] >= '0'
                     && pszX[2] <= '9')
                 )
            )
        {
            pThis->AddrKernelBase  = KernelAddr;
            pThis->AddrLinuxBanner = HitAddr;
            return true;
        }
    }

    return false;
}

/**
 * Probes for a Linux kernel which has KASLR enabled.
 *
 * @returns Flag whether a possible candidate location was found.
 * @param   pThis               The Linux digger data.
 * @param   pUVM                The user mode VM handle.
 * @param   pVMM                The VMM function table.
 */
static bool dbgDiggerLinuxProbeKaslr(PDBGDIGGERLINUX pThis, PUVM pUVM, PCVMMR3VTABLE pVMM)
{
    /**
     * With KASLR the kernel is loaded at a different address at each boot making detection
     * more difficult for us.
     *
     * The randomization is done in arch/x86/boot/compressed/kaslr.c:choose_random_location() (as of Nov 2017).
     * At the end of the method a random offset is chosen using find_random_virt_addr() which is added to the
     * kernel map start in the caller (the start of the kernel depends on the bit size, see LNX32_KERNEL_ADDRESS_START
     * and LNX64_KERNEL_ADDRESS_START for 32bit and 64bit kernels respectively).
     * The lowest offset possible is LOAD_PHYSICAL_ADDR which is defined in arch/x86/include/asm/boot.h
     * using CONFIG_PHYSICAL_START aligned to CONFIG_PHYSICAL_ALIGN.
     * The default CONFIG_PHYSICAL_START and CONFIG_PHYSICAL_ALIGN are both 0x1000000 no matter whether a 32bit
     * or a 64bit kernel is used. So the lowest offset to the kernel start address is 0x1000000.
     * The find_random_virt_addr() the number of possible slots where the kernel can be placed based on the image size
     * is calculated using the following formula:
     *    cSlots = ((KERNEL_IMAGE_SIZE - 0x1000000 (minimum) - image_size) / 0x1000000 (CONFIG_PHYSICAL_ALIGN)) + 1
     *
     * KERNEL_IMAGE_SIZE is 1GB for 64bit kernels and 512MB for 32bit kernels, so the maximum number of slots (resulting
     * in the largest possible offset) can be achieved when image_size (which contains the real size of the kernel image
     * which is unknown for us) goes to 0 and a 1GB KERNEL_IMAGE_SIZE is assumed. With that the biggest cSlots which can be
     * achieved is 64. The chosen random offset is taken from a random long integer using kaslr_get_random_long() modulo the
     * number of slots which selects a slot between 0 and 63. The final offset is calculated using:
     *    offAddr = random_addr * 0x1000000 (CONFIG_PHYSICAL_ALIGN) + 0x1000000 (minimum)
     *
     * So the highest offset the kernel can start is 0x40000000 which is 1GB (plus the maximum kernel size we defined).
     */
    if (dbgDiggerLinuxProbeWithAddr(pThis, pUVM, pVMM, LNX64_KERNEL_ADDRESS_START, _1G + LNX_MAX_KERNEL_SIZE))
        return true;

    /*
     * 32bit variant, makes sure we don't exceed the 4GB address space or DBGFR3MemScan() returns VERR_DBGF_MEM_NOT_FOUND immediately
     * without searching the remainder of the address space.
     *
     * The default split is 3GB userspace and 1GB kernel, so we just search the entire upper 1GB kernel space.
     */
    if (dbgDiggerLinuxProbeWithAddr(pThis, pUVM, pVMM, LNX32_KERNEL_ADDRESS_START, _4G - LNX32_KERNEL_ADDRESS_START))
        return true;

    return false;
}

/**
 * @copydoc DBGFOSREG::pfnInit
 */
static DECLCALLBACK(int)  dbgDiggerLinuxInit(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
{
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
    Assert(!pThis->fValid);

    char szVersion[256] = "Linux version 4.19.0";
    int rc = pVMM->pfnDBGFR3MemReadString(pUVM, 0, &pThis->AddrLinuxBanner, &szVersion[0], sizeof(szVersion));
    if (RT_SUCCESS(rc))
    {
        /*
         * Get a numerical version number.
         */
        const char *pszVersion = szVersion;
        while (*pszVersion && !RT_C_IS_DIGIT(*pszVersion))
            pszVersion++;

        size_t   offVersion = 0;
        uint32_t uMajor = 0;
        while (pszVersion[offVersion] && RT_C_IS_DIGIT(pszVersion[offVersion]))
            uMajor = uMajor * 10 + pszVersion[offVersion++] - '0';

        if (pszVersion[offVersion] == '.')
            offVersion++;

        uint32_t uMinor = 0;
        while (pszVersion[offVersion] && RT_C_IS_DIGIT(pszVersion[offVersion]))
            uMinor = uMinor * 10 + pszVersion[offVersion++] - '0';

        if (pszVersion[offVersion] == '.')
            offVersion++;

        uint32_t uBuild = 0;
        while (pszVersion[offVersion] && RT_C_IS_DIGIT(pszVersion[offVersion]))
            uBuild = uBuild * 10 + pszVersion[offVersion++] - '0';

        pThis->uKrnlVer = LNX_MK_VER(uMajor, uMinor, uBuild);
        pThis->uKrnlVerMaj = uMajor;
        pThis->uKrnlVerMin = uMinor;
        pThis->uKrnlVerBld = uBuild;
        if (pThis->uKrnlVer == 0)
            LogRel(("dbgDiggerLinuxInit: Failed to parse version string: %s\n", pszVersion));
    }

    /*
     * Assume 64-bit kernels all live way beyond 32-bit address space.
     */
    pThis->f64Bit = pThis->AddrLinuxBanner.FlatPtr > UINT32_MAX;
    pThis->fRelKrnlAddr = false;

    pThis->hCfgDb = NULL;

    /*
     * Try to find the compressed kernel config and parse it before we try
     * to get the symbol table, the config database is required to select
     * the method to use.
     */
    rc = dbgDiggerLinuxCfgFind(pThis, pUVM, pVMM);
    if (RT_FAILURE(rc))
        LogFlowFunc(("Failed to find kernel config (%Rrc), no config database available\n", rc));

    static const uint8_t s_abNeedle[] = "kobj";
    rc = dbgDiggerLinuxFindSymbolTableFromNeedle(pThis, pUVM, pVMM, s_abNeedle, sizeof(s_abNeedle) - 1);
    if (RT_FAILURE(rc))
    {
        /* Try alternate needle (seen on older x86 Linux kernels). */
        static const uint8_t s_abNeedleAlt[] = "kobjec";
        rc = dbgDiggerLinuxFindSymbolTableFromNeedle(pThis, pUVM, pVMM, s_abNeedleAlt, sizeof(s_abNeedleAlt) - 1);
        if (RT_FAILURE(rc))
        {
            static const uint8_t s_abNeedleOSuseX86[] = "nmi"; /* OpenSuSe 10.2 x86 */
            rc = dbgDiggerLinuxFindSymbolTableFromNeedle(pThis, pUVM, pVMM, s_abNeedleOSuseX86, sizeof(s_abNeedleOSuseX86) - 1);
        }
    }

    pThis->fValid = true;
    return VINF_SUCCESS;
}


/**
 * @copydoc DBGFOSREG::pfnProbe
 */
static DECLCALLBACK(bool)  dbgDiggerLinuxProbe(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
{
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;

    for (unsigned i = 0; i < RT_ELEMENTS(g_au64LnxKernelAddresses); i++)
    {
        if (dbgDiggerLinuxProbeWithAddr(pThis, pUVM, pVMM, g_au64LnxKernelAddresses[i], LNX_MAX_KERNEL_SIZE))
            return true;
    }

    /* Maybe the kernel uses KASLR. */
    if (dbgDiggerLinuxProbeKaslr(pThis, pUVM, pVMM))
        return true;

    return false;
}


/**
 * @copydoc DBGFOSREG::pfnDestruct
 */
static DECLCALLBACK(void)  dbgDiggerLinuxDestruct(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
{
    RT_NOREF(pUVM, pVMM, pvData);
}


/**
 * @copydoc DBGFOSREG::pfnConstruct
 */
static DECLCALLBACK(int)  dbgDiggerLinuxConstruct(PUVM pUVM, PCVMMR3VTABLE pVMM, void *pvData)
{
    RT_NOREF(pUVM, pVMM);
    PDBGDIGGERLINUX pThis = (PDBGDIGGERLINUX)pvData;
    pThis->IDmesg.u32Magic = DBGFOSIDMESG_MAGIC;
    pThis->IDmesg.pfnQueryKernelLog = dbgDiggerLinuxIDmsg_QueryKernelLog;
    pThis->IDmesg.u32EndMagic = DBGFOSIDMESG_MAGIC;

    return VINF_SUCCESS;
}


const DBGFOSREG g_DBGDiggerLinux =
{
    /* .u32Magic = */               DBGFOSREG_MAGIC,
    /* .fFlags = */                 0,
    /* .cbData = */                 sizeof(DBGDIGGERLINUX),
    /* .szName = */                 "Linux",
    /* .pfnConstruct = */           dbgDiggerLinuxConstruct,
    /* .pfnDestruct = */            dbgDiggerLinuxDestruct,
    /* .pfnProbe = */               dbgDiggerLinuxProbe,
    /* .pfnInit = */                dbgDiggerLinuxInit,
    /* .pfnRefresh = */             dbgDiggerLinuxRefresh,
    /* .pfnTerm = */                dbgDiggerLinuxTerm,
    /* .pfnQueryVersion = */        dbgDiggerLinuxQueryVersion,
    /* .pfnQueryInterface = */      dbgDiggerLinuxQueryInterface,
    /* .pfnStackUnwindAssist = */   dbgDiggerLinuxStackUnwindAssist,
    /* .u32EndMagic = */            DBGFOSREG_MAGIC
};