-
Notifications
You must be signed in to change notification settings - Fork 14
/
hvext.js
1518 lines (1375 loc) · 54.7 KB
/
hvext.js
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
"use strict";
// Registers commands.
function initializeScript() {
return [
new host.apiVersionSupport(1, 7),
new host.functionAlias(hvextHelp, "hvext_help"),
new host.functionAlias(dumpDmar, "dump_dmar"),
new host.functionAlias(dumpEpt, "dump_ept"),
new host.functionAlias(dumpHlat, "dump_hlat"),
new host.functionAlias(dumpIo, "dump_io"),
new host.functionAlias(dumpMsr, "dump_msr"),
new host.functionAlias(dumpVmcs, "dump_vmcs"),
new host.functionAlias(eptPte, "ept_pte"),
new host.functionAlias(indexesFor, "indexes"),
new host.functionAlias(pte, "pte"),
];
}
// Cache of fully-parsed EPT, keyed by EPTP.
let g_eptCache = {};
// Cache of unparsed HLAT tables, keyed by an address of the tables.
let g_hlatCache = {};
// The virtual address of (the first) "VMREAD RAX, RAX" in the HV image range.
let g_vmreadAddress = null;
// Initializes the extension.
function invokeScript() {
exec(".load kext");
g_vmreadAddress = findFirstVmreadRaxRax();
println("hvext loaded. Execute !hvext_help [command] for help.");
// Returns the first virtual address with "VMREAD RAX, RAX" in the HV address range.
function findFirstVmreadRaxRax() {
const isVmreadRaxRax = (memory, i) => (
memory[i] == 0x0f &&
memory[i + 1] == 0x78 &&
memory[i + 2] == 0xc0
);
// Search each page in the HV image range. Returns the first hit.
let hvImageRange = findHvImageRange();
for (let i = hvImageRange.Start; i.compareTo(hvImageRange.End) == -1; i = i.add(0x1000)) {
let found = searchMemory(i, 0x1000, isVmreadRaxRax);
if (found.length != 0) {
return found[0];
}
}
throw new Error("No VMREAD RAX, RAX (0f 78 c0) found.");
// Returns the range of the virtual address where the HV image is mapped.
function findHvImageRange() {
// Get the range with "lm".
// eg: fffff876`b89e0000 fffff876`b8de2000 hv (no symbols)
let chunks = exec("lm m hv").Last().split(" ");
let start = chunks[0].replace("`", "");
let end = chunks[1].replace("`", "");
return {
"Start": host.parseInt64(start, 16),
"End": host.parseInt64(end, 16),
};
}
// Finds an array of virtual addresses that matches the specified condition.
function searchMemory(address, bytes, predicate) {
// Memory read can fail if the address is not mapped.
try {
var memory = host.memory.readMemoryValues(address, bytes);
} catch (error) {
return [];
}
let index = [];
for (let i = 0; i < bytes; i++) {
if (predicate(memory, i)) {
index.push(address.add(i));
}
}
return index;
}
}
}
// Implements the !hvext_help command.
function hvextHelp(command) {
switch (command) {
case "dump_dmar":
println("dump_dmar [pa] - Displays status and configurations of a DMA remapping unit.");
println(" pa - The PA of a DMAR remapping unit. It can be found in the DMAR ACPI table.");
break;
case "dump_ept":
println("dump_ept [verbosity] - Displays guest physical address translation managed through EPT.");
println(" verbosity - 0 = Shows valid translations in a summarized format (default).");
println(" 1 = Shows both valid and invalid translations in a summarized format.");
println(" 2 = Shows every valid translations without summarizing it.");
break;
case "dump_hlat":
println("dump_hlat [verbosity] - Displays linear address translation managed through HLAT.");
println(" verbosity - 0 = Shows valid translations in a summarized format (default).");
println(" 1 = Shows both valid and invalid translations in a summarized format.");
println(" 2 = Shows every valid translations without summarizing it.");
break;
case "dump_io":
println("dump_io - Displays contents of the IO bitmaps.");
break;
case "dump_msr":
println("dump_msr [verbosity] - Displays contents of the MSR bitmaps.");
println(" verbosity - 0 = Shows only MSRs that are not read or write protected (default).");
println(" 1 = Shows protections of all MSRs managed by the MSR bitmaps.");
break;
case "dump_vmcs":
println("dump_vmcs - Displays contents of the current VMCS.");
break;
case "ept_pte":
println("ept_pte [gpa] - Displays contents of EPT entries used to translated the given GPA");
println(" gpa - A GPA to translate with EPT (default= 0).");
break;
case "indexes":
println("indexes [address] - Displays index values to walk paging structures for the given address.");
println(" address - An address to decode (default= 0).");
break;
case "pte":
println("pte [la] - Displays contents of paging structure entries used to translated the given LA.");
println(" la - A LA to translate with the paging structures (default= 0).");
break;
case undefined:
default:
println("hvext_help [command] - Displays this message.");
println("dump_dmar [pa] - Displays status and configurations of a DMA remapping unit.");
println("dump_ept [verbosity] - Displays guest physical address translation managed through EPT.");
println("dump_hlat [verbosity] - Displays linear address translation managed through HLAT.");
println("dump_io - Displays contents of the IO bitmaps.");
println("dump_msr [verbosity] - Displays contents of the MSR bitmaps.");
println("dump_vmcs - Displays contents of the current VMCS.");
println("ept_pte [gpa] - Displays contents of EPT entries used to translated the given GPA.");
println("indexes [address] - Displays index values to walk paging structures for the given address.");
println("pte [la] - Displays contents of paging structure entries used to translated the given LA.");
println("");
println("Note: When executing some of those commands, the processor must be in VMX-root operation with an active VMCS.");
break;
}
}
// Implements the !dump_dmar command.
function dumpDmar(baseAddr, verbosity) {
// See: 9.1 Root Entry
class RootEntry {
constructor(bus, low64, _high64) {
// The higher 64 bits are "Reserved".
this.value = low64;
this.bus = bus;
this.present = bits(low64, 0, 1);
this.contextTablePointer = low64.bitwiseAnd(~0xfff);
this.contextEntries = [];
}
}
// See: 9.3 Context Entry
class ContextEntry {
constructor(device, func, low64, high64) {
this.value = low64;
this.device = device;
this.func = func;
this.present = bits(low64, 0, 1);
this.translationType = bits(low64, 2, 2);
this.ssptPointer = (this.translationType == 0b10) ? "Passthrough" : low64.bitwiseAnd(~0xfff);
this.domainId = bits(high64, 9, 16);
}
}
class DeviceTranslation {
constructor(rootEntry, contextEntry) {
this.bus = (rootEntry) ? rootEntry.bus : 0;
this.device = (contextEntry) ? contextEntry.device : 0;
this.func = (contextEntry) ? contextEntry.func : 0;
this.passthrough = (contextEntry) ? (contextEntry.translationType == 0b10) : false;
this.ssptPointer = (contextEntry) ? contextEntry.ssptPointer : 0;
}
toString() {
return (this.passthrough ? "Passthrough" : hex(this.ssptPointer)) + " - " + this.bdf();
}
bdf() {
return "B" + this.bus + ",D" + this.device + ",F" + this.func;
}
}
if (baseAddr === undefined) {
println("Specify a physical address of the remapping hardware unit. " +
"It is typically 0xfed90000 and 0xfed91000 but may vary between models.");
return;
}
if (verbosity === undefined) {
verbosity = 0;
}
// Read remapping hardware registers.
// See: 11.4 Register Descriptions
//
// 2: kd> !dq 0xfed90000 l6
// #fed90000 00000000`00000010 01c0000c`40660462
// #fed90010 0000019e`2ff0505e c7000000`00000000
// #fed90020 00000001`044fe000 08000000`00000000
let qwords = [];
parseEach16Bytes(baseAddr.bitwiseAnd(~0xfff), 3, (l, h) => qwords.push(l, h));
let version = qwords[0]; // 11.4.1 Version Register
let capability = qwords[1]; // 11.4.2 Capability Register
let capabilityEx = qwords[2]; // 11.4.3 Extended Capability Register
let status = bits(qwords[3], 32, 32); // 11.4.4 Global Command Interface Registers
let rootTableAddr = qwords[4]; // 11.4.5 Root Table Address Register
println("Remapping unit at " + hex(baseAddr));
println(" version: " + bits(version, 4, 4) + "." + bits(version, 0, 4));
println(" capability: " + hex(capability));
println(" extended capability: " + hex(capabilityEx));
println(" status: " + hex(status));
println(" root table address: " + hex(rootTableAddr));
println("");
// Bail if DMA remapping is not enabled.
let translationEnableStatus = bits(status, 31, 1);
if (translationEnableStatus == 0) {
println("DMA remapping is not enabled.");
return;
}
// Bail if not in the legacy translation mode.
let translationTableMode = bits(rootTableAddr, 10, 2);
if (translationTableMode != 0b00) {
println("Unsupported TTM.");
return;
}
// Parse the root table.
// See: 3.4.2 Legacy Mode Address Translation
let rootEntries = [];
parseEach16Bytes(rootTableAddr.bitwiseAnd(~0xfff), 0x100, (l, h) =>
rootEntries.push(new RootEntry(rootEntries.length, l, h)));
// Parse the context tables referenced from the root entries.
// See: 3.4.2 Legacy Mode Address Translation
for (let rootEntry of rootEntries) {
parseEach16Bytes(rootEntry.contextTablePointer, 0x100, (l, h) =>
rootEntry.contextEntries.push(new ContextEntry(
bits(rootEntry.contextEntries.length, 3, 5),
bits(rootEntry.contextEntries.length, 0, 3),
l,
h)));
}
// First, print which BDF is translated with which second stage page table
// (SSPT) structures. There are 65536 BDFs, but only a handful of SSPTs are
// used. So, summarize relation and gather the SSPTs into `ssptPointers`.
println("Translation Device");
let ssptPointers = [];
let start = new DeviceTranslation();
let previous = new DeviceTranslation();
for (let rootEntry of rootEntries) {
for (let contextEntry of rootEntry.contextEntries) {
let current = new DeviceTranslation(rootEntry, contextEntry);
// If the current entry points to a different SSPT than before...
if (current.ssptPointer != start.ssptPointer) {
// Print it out (except the very first entry).
if (start.ssptPointer != 0) {
if (start == previous) {
println(previous);
} else {
println(start + " .. " + previous.bdf());
}
}
// Save the SSPT except when it is pass-through, and record the
// current entry as a new start.
if (!current.passthrough) {
ssptPointers.push(current.ssptPointer);
}
start = current;
}
previous = current;
}
}
// Print the last entry.
if (start == previous) {
println(previous);
} else {
println(start + " .. " + previous.bdf());
}
// Dump the all unique SSPTs. SSPTs have the same format as the EPT entries.
for (let ssptPointer of Array.from(new Set(ssptPointers))) {
println("");
println("Dumping second stage page tables at " + hex(ssptPointer));
dumpEpt(verbosity, getEptPml4(ssptPointer));
}
}
// Implements the !dump_ept command.
function dumpEpt(verbosity = 0, pml4) {
class Region {
constructor(gpa, pa, flags, size) {
this.gpa = gpa;
this.pa = pa;
this.flags = flags;
this.size = size;
this.identifyMapping = (gpa == pa);
}
toString() {
// If this is identify mapping, display so instead of actual PA.
let translation = (this.identifyMapping) ?
"Identity".padEnd(12) :
hex(this.pa).padStart(12);
return hex(this.gpa).padStart(12) + " - " +
hex(this.gpa + this.size).padStart(12) + " -> " +
translation + " " +
this.flags;
}
}
const SIZE_4KB = 0x1000;
const SIZE_2MB = 0x200000;
const SIZE_1GB = 0x40000000;
const SIZE_512GB = 0x8000000000;
if (pml4 === undefined) {
pml4 = getCurrentEptPml4();
}
// Walk through all EPT entries and accumulate them as regions.
let regions = [];
for (let gpa = 0, page_size = 0; ; gpa += page_size) {
let indexFor = indexesFor(gpa);
let i1 = indexFor.Pt;
let i2 = indexFor.Pd;
let i3 = indexFor.Pdpt;
let i4 = indexFor.Pml4;
// Exit once GPA exceeds its max value (48bit-width).
if (gpa > 0xfffffffff000) {
break;
}
// Pick and check PML4e.
page_size = SIZE_512GB;
let pml4e = pml4.entries[i4];
if (!pml4e.flags.present()) {
continue;
}
// Pick and check PDPTe.
page_size = SIZE_1GB;
let pdpt = pml4e.nextTable;
let pdpte = pdpt.entries[i3];
if (!pdpte.flags.present()) {
continue;
}
if (pdpte.flags.large) {
let flags = getEffectiveFlags(pml4e, pdpte);
regions.push(new Region(gpa, pdpte.pfn.bitwiseShiftLeft(12), flags, page_size));
continue;
}
// Pick and check PDe.
page_size = SIZE_2MB;
let pd = pdpte.nextTable;
let pde = pd.entries[i2];
if (!pde.flags.present()) {
continue;
}
if (pde.flags.large) {
let flags = getEffectiveFlags(pml4e, pdpte, pde);
regions.push(new Region(gpa, pde.pfn.bitwiseShiftLeft(12), flags, page_size));
continue;
}
// Pick and check PTe.
page_size = SIZE_4KB;
let pt = pde.nextTable;
let pte = pt.entries[i1];
if (!pte.flags.present()) {
continue;
}
let flags = getEffectiveFlags(pml4e, pdpte, pde, pte);
regions.push(new Region(gpa, pte.pfn.bitwiseShiftLeft(12), flags, page_size));
}
// Display gathered regions.
println("GPA [begin, end) PA Flags");
if (verbosity > 1) {
// Just dump all regions.
regions.map(println);
} else {
// Combine regions that are effectively contiguous.
let combined_region = null;
for (let region of regions) {
if (combined_region === null) {
combined_region = region;
continue;
}
// Is this region contiguous to the current region? That is, both
// identify mapped, have the same flags and corresponding GPAs are
// contiguous.
if (combined_region.identifyMapping &&
region.identifyMapping &&
combined_region.flags.toString() == region.flags.toString() &&
combined_region.gpa + combined_region.size == region.gpa) {
// It is contiguous. Just expand the size.
combined_region.size += region.size;
} else {
// It is not contiguous. Display the current region.
println(combined_region);
// See if there is an unmapped regions before this region.
if (verbosity > 0 &&
combined_region.gpa + combined_region.size != region.gpa) {
// Yes, there is. Display that.
let unmapped_base = combined_region.gpa + combined_region.size;
let unmapped_size = region.gpa - unmapped_base;
println(hex(unmapped_base).padStart(12) + " - " +
hex(unmapped_base + unmapped_size).padStart(12) + " -> " +
"Unmapped".padEnd(12) + " " +
new EptFlags(0));
}
// Move on, and start checking contiguous regions from this region.
combined_region = region;
}
}
// Display the last one.
println(combined_region);
}
// Computes the effective flag value from the given EPT entries. The large bit
// is always reported as 0.
function getEffectiveFlags(pml4e, pdpte, pde, pte) {
let flags = new EptFlags(0);
flags.read = pml4e.flags.read & pdpte.flags.read;
flags.write = pml4e.flags.write & pdpte.flags.write;
flags.execute = pml4e.flags.execute & pdpte.flags.execute;
flags.executeForUserMode = pml4e.flags.executeForUserMode & pdpte.flags.executeForUserMode;
let leaf = pdpte;
if (pde) {
leaf = pde;
flags.read &= pde.flags.read;
flags.write &= pde.flags.write;
flags.execute &= pde.flags.execute;
flags.executeForUserMode &= pde.flags.executeForUserMode;
}
if (pte) {
leaf = pte;
flags.read &= pte.flags.read;
flags.write &= pte.flags.write;
flags.execute &= pte.flags.execute;
flags.executeForUserMode &= pte.flags.executeForUserMode;
}
flags.memoryType = leaf.flags.memoryType;
flags.verifyGuestPaging = leaf.flags.verifyGuestPaging;
flags.pagingWriteAccess = leaf.flags.pagingWriteAccess;
flags.supervisorShadowStack = leaf.flags.supervisorShadowStack;
return flags;
}
}
// Implements the !dump_hlat command.
function dumpHlat(verbosity = 0, pml4) {
class Region {
constructor(la, gpa, flags, size) {
this.la = la;
this.gpa = gpa; // `undefined` if unmapped.
this.flags = flags;
this.size = size;
this.identifyMapping = (la == gpa);
}
toString() {
// If this is identify mapping or unmapped, display so.
let translation = (this.identifyMapping) ?
"Identity".padEnd(12) :
(!this.flags.present()) ?
"Unmapped".padEnd(12) :
hex(this.gpa).padStart(12);
return hex(this.la).padStart(12) + " - " +
hex(this.la.add(this.size)).padStart(12) + " -> " +
translation + " " +
this.flags;
}
}
const SIZE_4KB = 0x1000;
const SIZE_2MB = 0x200000;
const SIZE_1GB = 0x40000000;
const SIZE_512GB = 0x8000000000;
if (pml4 === undefined) {
pml4 = getCurrentHlatPml4();
}
// If the HLAT prefix size is 1, HLAT is enabled for only linear addresses
// where the bit 63 of them is 1 (ake, kernel addresses). Windows only uses
// this setup, so we support only this too.
let hlat_prefix_size = readVmcs(0x00000006); // HLAT prefix size
if (hlat_prefix_size != 1) {
throw new Error("Unsupported HLAT prefix size: " + hlat_prefix_size);
}
// A set of empty tables to speed up parsing.
let emptyTableCache = new Set();
// Walk through all HLAT entries and accumulate them as regions. We start at
// 0xffff800000000000, the lowest canonical form address that HLAT page walk
// can happen when the HLAT prefix size is 1.
let regions = [];
let la = host.Int64(0xffff800000000000);
let indexFor = indexesFor(la);
for (let i4 = indexFor.Pml4; i4 < 512; i4++, la = la.add(SIZE_512GB)) {
let pml4e = pml4.entries[i4];
if (!pml4e.flags.present()) {
regions.push(new Region(la, undefined, new PsFlags(0), SIZE_512GB));
continue;
}
if (pml4e.flags.restart) {
continue;
}
let pdpt = pml4e.nextTable;
if (emptyTableCache.has(pdpt)) {
continue;
}
if (parsePdpt(indexFor, pdpt, la, regions, pml4e)) {
emptyTableCache.add(pdpt);
}
}
println("LA [begin, end) GPA Flags");
if (verbosity > 1) {
// Dump all regions with valid translations.
regions.map((region) => {
if (region.flags.present()) {
println(region);
}
});
} else {
// Combine regions that are effectively contiguous.
let combined_region = null;
for (let region of regions) {
if (combined_region === null) {
combined_region = region;
continue;
}
// Is this region contiguous to the current region? That is, ...
if (combined_region.flags.toString() == region.flags.toString() &&
combined_region.la.add(combined_region.size) == region.la &&
((!combined_region.flags.present() && !region.flags.present()) ||
(combined_region.flags.present() && region.flags.present() &&
combined_region.gpa.add(combined_region.size) == region.gpa))) {
// It is contiguous. Just expand the size.
combined_region.size += region.size;
} else {
// It is not contiguous. Display the current region if it is valid,
// or in a verbose mode.
if (combined_region.flags.present() || verbosity > 0) {
println(combined_region);
}
// If not, see if there is a restarted regions before this region.
if (verbosity > 0 &&
combined_region.la.add(combined_region.size) != region.la) {
// Yes, there is. Display that.
let missing_region_base = combined_region.la.add(combined_region.size);
let missing_region_size = region.la.subtract(missing_region_base);
println(hex(missing_region_base).padStart(12) + " - " +
hex(missing_region_base.add(missing_region_size)).padStart(12) + " -> " +
"Restart".padEnd(12) + " " +
new PsFlags(0));
}
// Move on, and start checking contiguous regions from this region.
combined_region = region;
}
}
// Display the last one.
if (combined_region.flags.present() || verbosity > 0) {
println(combined_region);
}
}
/// Parses HLAT PDPT and accumulates region information into `regions`.
/// Returns true if no entry with a valid translation exists in the table.
/// "Valid" in this context excludes pages that are marked as "restart" and
/// "not-present".
function parsePdpt(indexFor, pdpt, la, regions, pml4e) {
let empty = true;
for (let i3 = indexFor.Pdpt; i3 < 512; i3++, la = la.add(SIZE_1GB)) {
let pdpte = pdpt.entries[i3];
if (!pdpte.flags.present()) {
regions.push(new Region(la, undefined, new PsFlags(0), SIZE_1GB));
continue;
}
if (pdpte.flags.restart) {
continue;
}
if (pdpte.flags.large) {
let flags = getEffectiveFlags(pml4e, pdpte);
regions.push(new Region(la, pdpte.pfn.bitwiseShiftLeft(12), flags, SIZE_1GB));
empty = false;
continue;
}
let pd = pdpte.nextTable;
if (emptyTableCache.has(pd)) {
continue;
}
if (parsePd(indexFor, pd, la, regions, pml4e, pdpte)) {
emptyTableCache.add(pd);
} else {
empty = false;
}
}
return empty;
}
/// Parses HLAT PD. See parsePdpt for more details.
function parsePd(indexFor, pd, la, regions, pml4e, pdpte) {
let empty = true;
for (let i2 = indexFor.Pd; i2 < 512; i2++, la = la.add(SIZE_2MB)) {
let pde = pd.entries[i2];
if (!pde.flags.present()) {
regions.push(new Region(la, undefined, new PsFlags(0), SIZE_2MB));
continue;
}
if (pde.flags.restart) {
continue;
}
if (pde.flags.large) {
let flags = getEffectiveFlags(pml4e, pdpte, pde);
regions.push(new Region(la, pde.pfn.bitwiseShiftLeft(12), flags, SIZE_2MB));
empty = false;
continue;
}
let pt = pde.nextTable;
if (emptyTableCache.has(pt)) {
continue;
}
if (parsePt(indexFor, pt, la, regions, pml4e, pdpte, pde)) {
emptyTableCache.add(pt);
} else {
empty = false;
}
}
return empty;
}
/// Parses HLAT PT. See parsePdpt for more details.
function parsePt(indexFor, pt, la, regions, pml4e, pdpte, pde) {
let empty = true;
for (let i1 = indexFor.Pt; i1 < 512; i1++, la = la.add(SIZE_4KB)) {
let pte = pt.entries[i1];
if (!pte.flags.present()) {
regions.push(new Region(la, undefined, new PsFlags(0), SIZE_4KB));
continue;
}
if (pte.flags.restart) {
continue;
}
let flags = getEffectiveFlags(pml4e, pdpte, pde, pte);
regions.push(new Region(la, pte.pfn.bitwiseShiftLeft(12), flags, SIZE_4KB));
empty = false;
}
return empty;
}
// Computes the effective flag value from the given PS entries. The accessed,
// dirty, large, restart bits are always reported as 0.
function getEffectiveFlags(pml4e, pdpte, pde, pte) {
let flags = new PsFlags(0);
flags.valid = pml4e.flags.valid & pdpte.flags.valid;
flags.write = pml4e.flags.write & pdpte.flags.write;
flags.user = pml4e.flags.user & pdpte.flags.user;
flags.nonExecute = pml4e.flags.nonExecute | pdpte.flags.nonExecute;
let leaf = pdpte;
if (pde) {
leaf = pde;
flags.valid &= pde.flags.valid;
flags.write &= pde.flags.write;
flags.user &= pde.flags.user;
flags.nonExecute |= pde.flags.nonExecute;
}
if (pte) {
leaf = pte;
flags.valid &= pte.flags.valid;
flags.write &= pte.flags.write;
flags.user &= pte.flags.user;
flags.nonExecute |= pte.flags.nonExecute;
}
return flags;
}
}
// Returns fully-parsed HLAT entries pointed by the current HLATP VMCS encoding.
function getCurrentHlatPml4() {
let exec_control1 = readVmcs(0x00004002); // Primary processor-based VM-execution controls
if (bits(exec_control1, 17, 1) == 0) {
throw new Error("HLAT is not enabled");
}
let exec_control3 = readVmcs(0x00002034); // Tertiary processor-based VM-execution controls
if (bits(exec_control3, 1, 1) == 0) {
throw new Error("HLAT is not enabled");
}
let hlatp = readVmcs(0x00002040); // Hypervisor-managed linear-address translation pointer
if (hlatp === undefined) {
throw new Error("The VMREAD instruction failed");
}
println("Current HLAT pointer " + hex(hlatp));
return new HlatPml4(hlatp.bitwiseAnd(~0xfff));
}
// Implements the !dump_io command.
function dumpIo() {
class IoAccessibilityRange {
constructor(begin = undefined, end = undefined, intercepted = undefined) {
this.begin = begin;
this.end = end;
this.intercepted = intercepted;
}
toString() {
return (this.intercepted ? "-- " : "RW ") + hex(this.begin) +
(this.begin == this.end ? "" : " .. " + hex(this.end));
}
}
let exec_control = readVmcs(0x00004002); // Primary processor-based VM-execution controls
if (bits(exec_control, 25, 1) == 0) {
// Check "unconditional I/O exiting"
if (bits(exec_control, 24, 1) == 0) {
println("IO bitmaps are not used. IO port access does not cause VM-exit.");
} else {
println("IO port access unconditionally causes VM-exit.");
}
return;
}
let bitmap_low = readVmcs(0x00002000); // I/O bitmap A
let bitmap_high = readVmcs(0x00002002); // I/O bitmap B
// Convert the 4KB contents into an array of 64bit integers for processing.
let entries = [];
parseEach16Bytes(bitmap_low, 0x100, (l, h) => entries.push(l, h));
parseEach16Bytes(bitmap_high, 0x100, (l, h) => entries.push(l, h));
let ranges = [];
let range = undefined;
let port = 0;
for (let entry of entries) {
for (let bit_position = 0; bit_position < 64; bit_position++, port++) {
let intercepted = bits(entry, bit_position, 1);
if (port == 0) {
range = new IoAccessibilityRange(port, port, intercepted);
} else if (range.intercepted == intercepted) {
// Interception status remained same. Just extend the range.
range.end = port;
} else {
// Interception status changed. Save the range and start a new one.
ranges.push(range);
range = new IoAccessibilityRange(port, port, intercepted);
}
}
}
ranges.push(range);
ranges.map(println);
}
// Implements the !dump_msr command.
function dumpMsr(verbosity = 0) {
class MsrEntry {
constructor(bit_position, read_protected, write_protected) {
if (bit_position < 0x2000) {
this.msr = bit_position;
} else {
this.msr = bit_position - 0x2000 + 0xc0000000;
}
this.read_protected = read_protected;
this.write_protected = write_protected;
}
toString() {
return (
{ 1: "-", 0: "R" }[this.read_protected] +
{ 1: "-", 0: "W" }[this.write_protected] +
" " +
hex(this.msr)
);
}
}
let exec_control = readVmcs(0x00004002); // Primary processor-based VM-execution controls
if (bits(exec_control, 28, 1) == 0) {
println("MSR bitmaps are not used. MSR access unconditionally causes VM-exit.");
return;
}
let bitmap = readVmcs(0x00002004); // MSR bitmaps
// Convert the 4KB contents into an array of 64bit integers for processing.
let entries = [];
parseEach16Bytes(bitmap.bitwiseAnd(~0xfff), 0x100, (l, h) => entries.push(l, h));
// The MSR bitmaps are made up of two 2048 bytes segments. The first segment
// manages read access, and the 2nd manages write access, for the same ranges
// of MSRs. Let us walk the half of the `entries` and add offset 2048
// (= 0x100 * 8) to look both segments in a single loop.
let msrs = [];
for (let i = 0; i < 0x100; i++) {
let entry_low = entries[i];
let entry_hi = entries[i + 0x100];
// For the selected upper and lower 64bit entries, walk though each bit
// position and construct `MsrEntry` from the pair of the bits.
for (let bit_position = 0; bit_position < 64; bit_position++) {
let read_protected = bits(entry_low, bit_position, 1);
let write_protected = bits(entry_hi, bit_position, 1);
msrs.push(new MsrEntry(i * 64 + bit_position, read_protected, write_protected));
}
}
for (let msr of msrs) {
if (verbosity == 0) {
if (!msr.read_protected || !msr.write_protected) {
println(msr);
}
} else {
println(msr);
}
}
}
// Implements the !dump_vmcs command.
function dumpVmcs() {
// Capture the current state.
// eg: efl=00000242 rax=0000000000006c1c rip=fffff813d4f00ea1
let output = exec("r efl, rax, rip").Last();
let originalRflags = output.substring(4, 12);
let originalRax = output.substring(17, 33);
let originalRip = output.substring(38, 54);
// Loop over the VMCS encodings.
for (let i = 0; i < VMCS_ENCODINGS.length; i += 2) {
let name = VMCS_ENCODINGS[i];
let encoding = VMCS_ENCODINGS[i + 1];
let value = readVmcsUnsafe(encoding);
if (value === undefined) {
println("***** FAILED *****" + " " + name);
} else {
println(hex(value, 16) + " " + name);
}
}
// All done. Restore the original state.
exec("r rax=" + originalRax + ", " +
"rip=" + originalRip + ", " +
"efl=" + originalRflags);
}
// Implements the !ept_pte command.
function eptPte(gpa, pml4) {
if (gpa === undefined) {
gpa = 0;
}
if (pml4 === undefined) {
pml4 = getCurrentEptPml4();
}
let indexFor = indexesFor(gpa);
let i1 = indexFor.Pt;
let i2 = indexFor.Pd;
let i3 = indexFor.Pdpt;
let i4 = indexFor.Pml4;
// Pick and check PML4e.
let pml4e = pml4.entries[i4];
if (!pml4e.flags.present()) {
println("PML4e at " + hex(pml4.address.add(8 * i4)));
println("contains " + hex(pml4e.value));
println("pfn " + pml4e);
return;
}
// Pick and check PDPTe.
let pdpt = pml4e.nextTable;
let pdpte = pdpt.entries[i3];
if (!pdpte.flags.present() || pdpte.flags.large) {
println("PML4e at " + hex(pml4.address.add(8 * i4)).padEnd(18) +
"PDPTe at " + hex(pdpt.address.add(8 * i3)));
println("contains " + hex(pml4e.value).padEnd(18) +
"contains " + hex(pdpte.value));
println("pfn " + (pml4e + "").padEnd(23) +
"pfn " + pdpte);
return;
}
// Pick and check PDe.
let pd = pdpte.nextTable;
let pde = pd.entries[i2];
if (!pde.flags.present() || pde.flags.large) {
println("PML4e at " + hex(pml4.address.add(8 * i4)).padEnd(18) +
"PDPTe at " + hex(pdpt.address.add(8 * i3)).padEnd(18) +
"PDe at " + hex(pd.address.add(8 * i2)));
println("contains " + hex(pml4e.value).padEnd(18) +
"contains " + hex(pdpte.value).padEnd(18) +
"contains " + hex(pde.value));
println("pfn " + (pml4e + "").padEnd(23) +
"pfn " + (pdpte + "").padEnd(23) +
"pfn " + pde);
return;
}
// Pick PTe.
let pt = pde.nextTable;
let pte = pt.entries[i1];
println("PML4e at " + hex(pml4.address.add(8 * i4)).padEnd(18) +
"PDPTe at " + hex(pdpt.address.add(8 * i3)).padEnd(18) +
"PDe at " + hex(pd.address.add(8 * i2)).padEnd(20) +
"PTe at " + hex(pt.address.add(8 * i1)));
println("contains " + hex(pml4e.value).padEnd(18) +
"contains " + hex(pdpte.value).padEnd(18) +
"contains " + hex(pde.value).padEnd(18) +
"contains " + hex(pte.value));
println("pfn " + (pml4e + "").padEnd(23) +
"pfn " + (pdpte + "").padEnd(23) +
"pfn " + (pde + "").padEnd(23) +
"pfn " + pte);
}
// Implements the !indexes command.
function indexesFor(address) {
if (address == undefined) {
address = 0;
}
return {
"Pt": bits(address, 12, 9),
"Pd": bits(address, 21, 9),
"Pdpt": bits(address, 30, 9),
"Pml4": bits(address, 39, 9),
};
}
// Implements the !pte command.
function pte(la, pml4) {
if (la === undefined) {
la = 0;
}
if (pml4 === undefined) {
pml4 = host.currentThread.Registers.Kernel.cr3.bitwiseAnd(~0xfff);
}
let indexFor = indexesFor(la);
let i1 = indexFor.Pt;
let i2 = indexFor.Pd;
let i3 = indexFor.Pdpt;
let i4 = indexFor.Pml4;
// Pick and check PML4e.
let pml4e = new PsEntry(readEntry(pml4 + 8 * i4));
if (!pml4e.flags.present()) {
println("PML4e at " + hex(pml4.add(8 * i4)));
println("contains " + hex(pml4e.value));
println("pfn " + pml4e);
return;
}
// Pick and check PDPTe.
let pdpt = pml4e.pfn.bitwiseShiftLeft(12);
let pdpte = new PsEntry(readEntry(pdpt + 8 * i3));
if (!pdpte.flags.present() || pdpte.flags.large) {
println("PML4e at " + hex(pml4.add(8 * i4)).padEnd(18) +
"PDPTe at " + hex(pdpt.add(8 * i3)));
println("contains " + hex(pml4e.value).padEnd(18) +
"contains " + hex(pdpte.value));