forked from cheat-engine/cheat-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathultimap2.c
1707 lines (1310 loc) · 42.1 KB
/
ultimap2.c
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
#pragma warning( disable: 4100 4706)
#include <ntifs.h>
#include <ntddk.h>
#include <minwindef.h>
#include <wdm.h>
#include <windef.h>
#include "Ntstrsafe.h"
#include "DBKFunc.h"
#include "ultimap2\apic.h"
#include "ultimap2.h"
PSSUSPENDPROCESS PsSuspendProcess;
PSSUSPENDPROCESS PsResumeProcess;
KDPC RTID_DPC;
BOOL LogKernelMode;
BOOL LogUserMode;
PEPROCESS CurrentTarget;
UINT64 CurrentCR3;
HANDLE Ultimap2Handle;
volatile BOOLEAN UltimapActive = FALSE;
volatile BOOLEAN isSuspended = FALSE;
volatile BOOLEAN flushallbuffers = FALSE; //set to TRUE if all the data should be flushed
KEVENT FlushData;
BOOL SaveToFile;
WCHAR OutputPath[200];
int Ultimap2RangeCount;
PURANGE Ultimap2Ranges = NULL;
PVOID *Ultimap2_DataReady;
#if (NTDDI_VERSION < NTDDI_VISTA)
//implement this function for XP
unsigned int KeQueryMaximumProcessorCount()
{
CCHAR cpunr;
KAFFINITY cpus, original;
ULONG cpucount;
cpucount = 0;
cpus = KeQueryActiveProcessors();
original = cpus;
while (cpus)
{
if (cpus % 2)
cpucount++;
cpus = cpus / 2;
}
return cpucount;
}
#endif
typedef struct
{
PToPA_ENTRY ToPAHeader;
PToPA_ENTRY ToPAHeader2;
PVOID ToPABuffer;
PVOID ToPABuffer2;
PMDL ToPABufferMDL;
PMDL ToPABuffer2MDL;
PRTL_GENERIC_TABLE ToPALookupTable;
PRTL_GENERIC_TABLE ToPALookupTable2;
KEVENT Buffer2ReadyForSwap;
KEVENT InitiateSave;
KEVENT DataReady;
KEVENT DataProcessed;
UINT64 CurrentOutputBase;
UINT64 CurrentSaveOutputBase;
UINT64 CurrentSaveOutputMask;
UINT64 MappedAddress; //set by WaitForData , use with continue
UINT64 Buffer2FlushSize; //used by WaitForData
KDPC OwnDPC;
HANDLE WriterThreadHandle;
//for saveToFile mode
HANDLE FileHandle;
KEVENT FileAccess;
UINT64 TraceFileSize;
volatile BOOL Interrupted;
} ProcessorInfo, *PProcessorInfo;
volatile PProcessorInfo *PInfo;
int Ultimap2CpuCount;
KMUTEX SuspendMutex;
KEVENT SuspendEvent;
HANDLE SuspendThreadHandle;
volatile int suspendCount;
BOOL ultimapEnabled = FALSE;
BOOL singleToPASystem = FALSE;
BOOL NoPMIMode = FALSE;
void suspendThread(PVOID StartContext)
/* Thread responsible for suspending the target process when the buffer is getting full */
{
NTSTATUS wr;
__try
{
while (UltimapActive)
{
wr = KeWaitForSingleObject(&SuspendEvent, Executive, KernelMode, FALSE, NULL);
if (!UltimapActive) return;
DbgPrint("suspendThread event triggered");
KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL);
if (!isSuspended)
{
if (CurrentTarget == 0)
{
if (PsSuspendProcess(CurrentTarget) == 0)
isSuspended = TRUE;
else
DbgPrint("Failed to suspend target\n");
}
}
KeReleaseMutex(&SuspendMutex, FALSE);
}
}
__except (1)
{
DbgPrint("Exception in suspendThread thread\n");
}
}
NTSTATUS ultimap2_continue(int cpunr)
{
NTSTATUS r = STATUS_UNSUCCESSFUL;
if ((cpunr < 0) || (cpunr >= Ultimap2CpuCount))
{
DbgPrint("ultimap2_continue(%d)", cpunr);
return STATUS_UNSUCCESSFUL;
}
if (PInfo)
{
PProcessorInfo pi = PInfo[cpunr];
if (pi->MappedAddress)
{
MmUnmapLockedPages((PVOID)(UINT_PTR)pi->MappedAddress, pi->ToPABuffer2MDL); //unmap this memory
pi->MappedAddress = 0;
r = STATUS_SUCCESS;
}
else
DbgPrint("MappedAddress was 0");
DbgPrint("%d DataProcessed", cpunr);
KeSetEvent(&pi->DataProcessed, 0, FALSE); //let the next swap happen if needed
}
return r;
}
NTSTATUS ultimap2_waitForData(ULONG timeout, PULTIMAP2DATAEVENT data)
{
NTSTATUS r=STATUS_UNSUCCESSFUL;
//Wait for the events in the list
//If an event is triggered find out which one is triggered, then map that block into the usermode space and return the address and block
//That block will be needed to continue
if (UltimapActive)
{
NTSTATUS wr = STATUS_UNSUCCESSFUL;
LARGE_INTEGER wait;
PKWAIT_BLOCK waitblock;
int cpunr;
waitblock = ExAllocatePool(NonPagedPool, Ultimap2CpuCount*sizeof(KWAIT_BLOCK));
wait.QuadPart = -10000LL * timeout;
if (timeout == 0xffffffff) //infinite wait
wr = KeWaitForMultipleObjects(Ultimap2CpuCount, Ultimap2_DataReady, WaitAny, UserRequest, UserMode, TRUE, NULL, waitblock);
else
wr = KeWaitForMultipleObjects(Ultimap2CpuCount, Ultimap2_DataReady, WaitAny, UserRequest, UserMode, TRUE, &wait, waitblock);
ExFreePool(waitblock);
DbgPrint("ultimap2_waitForData wait returned %x", wr);
cpunr = wr - STATUS_WAIT_0;
if ((cpunr < Ultimap2CpuCount) && (cpunr>=0))
{
PProcessorInfo pi = PInfo[cpunr];
if (pi->Buffer2FlushSize)
{
if (pi->ToPABuffer2MDL)
{
__try
{
data->Address = (UINT64)MmMapLockedPagesSpecifyCache(pi->ToPABuffer2MDL, UserMode, MmCached, NULL, FALSE, NormalPagePriority);
DbgPrint("MmMapLockedPagesSpecifyCache returned address %p\n", data->Address);
if (data->Address)
{
data->Size = pi->Buffer2FlushSize;
data->CpuID = cpunr;
pi->MappedAddress = data->Address;
r = STATUS_SUCCESS;
}
}
__except (1)
{
DbgPrint("ultimap2_waitForData: Failure mapping memory into waiter process. Count=%d", (int)MmGetMdlByteCount(pi->ToPABuffer2MDL));
}
}
else
{
DbgPrint("ToPABuffer2MDL is NULL. Not even gonna try");
}
}
else
{
DbgPrint("ultimap2_waitForData flushsize was 0");
}
}
}
DbgPrint("ultimap2_waitForData returned %x\n", r);
return r;
}
void createUltimap2OutputFile(int cpunr)
{
NTSTATUS r;
PProcessorInfo pi = PInfo[cpunr];
UNICODE_STRING usFile;
OBJECT_ATTRIBUTES oaFile;
IO_STATUS_BLOCK iosb;
WCHAR Buffer[200];
#ifdef AMD64
DbgPrint("OutputPath=%S", OutputPath);
swprintf_s(Buffer, 200, L"%sCPU%d.trace", OutputPath, cpunr);
#else
RtlStringCbPrintfW(Buffer, 200, L"%sCPU%d.trace", OutputPath, cpunr);
#endif
DbgPrint("Buffer=%S", Buffer);
RtlInitUnicodeString(&usFile, Buffer);
InitializeObjectAttributes(&oaFile, &usFile, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
DbgPrint("Creating file %S", usFile.Buffer);
pi->FileHandle = 0;
ZwDeleteFile(&oaFile);
r = ZwCreateFile(&pi->FileHandle, SYNCHRONIZE | FILE_READ_DATA | FILE_APPEND_DATA | GENERIC_ALL, &oaFile, &iosb, 0, FILE_ATTRIBUTE_NORMAL, 0, FILE_SUPERSEDE, FILE_SEQUENTIAL_ONLY | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0);
DbgPrint("%d: ZwCreateFile=%x\n", (int)cpunr, r);
}
void WriteThreadForSpecificCPU(PVOID StartContext)
{
int cpunr = (int)(UINT_PTR)StartContext;
PProcessorInfo pi = PInfo[cpunr];
IO_STATUS_BLOCK iosb;
NTSTATUS r = STATUS_UNSUCCESSFUL;
//DbgPrint("WriteThreadForSpecificCPU %d alive", (int)StartContext);
if (SaveToFile)
{
if (KeWaitForSingleObject(&pi->FileAccess, Executive, KernelMode, FALSE, NULL) == STATUS_SUCCESS)
{
createUltimap2OutputFile(cpunr);
KeSetEvent(&pi->FileAccess, 0, FALSE);
}
else
createUltimap2OutputFile(cpunr);
}
KeSetSystemAffinityThread((KAFFINITY)(1 << cpunr));
while (UltimapActive)
{
NTSTATUS wr = KeWaitForSingleObject(&pi->InitiateSave, Executive, KernelMode, FALSE, NULL);
//DbgPrint("WriteThreadForSpecificCPU %d: wr=%x", (int)StartContext, wr);
if (!UltimapActive)
break;
if (wr == STATUS_SUCCESS)
{
UINT64 Size;
ToPA_LOOKUP tl;
PToPA_LOOKUP result;
//DbgPrint("%d: writing buffer", (int)StartContext);
//figure out the size
tl.PhysicalAddress = pi->CurrentSaveOutputBase;
tl.index = 0;
result = RtlLookupElementGenericTable(pi->ToPALookupTable2, &tl);
if (result)
{
//write...
//DbgPrint("%d: result->index=%d CurrentSaveOutputMask=%p", (int)StartContext, result->index, pi->CurrentSaveOutputMask);
if (singleToPASystem)
Size = pi->CurrentSaveOutputMask >> 32;
else
Size = ((result->index * 511) + ((pi->CurrentSaveOutputMask & 0xffffffff) >> 7)) * 4096 + (pi->CurrentSaveOutputMask >> 32);
if (Size > 0)
{
if (SaveToFile)
{
wr = KeWaitForSingleObject(&pi->FileAccess, Executive, KernelMode, FALSE, NULL);
if (wr==STATUS_SUCCESS)
{
if (pi->FileHandle==0) //a usermode flush has happened
createUltimap2OutputFile(cpunr);
r = ZwWriteFile(pi->FileHandle, NULL, NULL, NULL, &iosb, pi->ToPABuffer2, (ULONG)Size, NULL, NULL);
pi->TraceFileSize += Size;
//DbgPrint("%d: ZwCreateFile(%p, %d)=%x\n", (int)StartContext, pi->ToPABuffer2, (ULONG)Size, r);
KeSetEvent(&pi->FileAccess, 0, FALSE);
}
}
else
{
//map ToPABuffer2 into the CE process
//wake up a worker thread
pi->Buffer2FlushSize = Size;
DbgPrint("%d: WorkerThread(%p, %d)=%x\n", (int)(UINT_PTR)StartContext, pi->ToPABuffer2, (ULONG)Size, r);
KeSetEvent(&pi->DataReady, 0, TRUE); //a ce thread waiting in ultimap2_waitForData should now wake and process the data
//and wait for it to finish
r=KeWaitForSingleObject(&pi->DataProcessed, Executive, KernelMode, FALSE, NULL);
DbgPrint("KeWaitForSingleObject(DataProcessed)=%x", r);
}
//DbgPrint("%d: Writing %x bytes\n", (int)StartContext, Size);
}
}
else
DbgPrint("Unexpected physical address while writing results for cpu %d (%p)", (int)(UINT_PTR)StartContext, pi->CurrentSaveOutputBase);
KeSetEvent(&pi->Buffer2ReadyForSwap, 0, FALSE);
}
}
KeSetSystemAffinityThread(KeQueryActiveProcessors());
if (pi->FileHandle)
ZwClose(pi->FileHandle);
KeSetEvent(&pi->Buffer2ReadyForSwap, 0, FALSE);
}
void ultimap2_LockFile(int cpunr)
{
if ((cpunr < 0) || (cpunr >= Ultimap2CpuCount))
return;
if (PInfo)
{
NTSTATUS wr;
PProcessorInfo pi = PInfo[cpunr];
//DbgPrint("AcquireUltimap2File()");
wr = KeWaitForSingleObject(&pi->FileAccess, Executive, KernelMode, FALSE, NULL);
if (wr == STATUS_SUCCESS)
{
//DbgPrint("Acquired");
if (pi->FileHandle)
{
ZwClose(pi->FileHandle);
pi->FileHandle = 0;
}
}
}
}
void ultimap2_ReleaseFile(int cpunr)
{
if ((cpunr < 0) || (cpunr >= Ultimap2CpuCount))
return;
if (PInfo)
{
PProcessorInfo pi = PInfo[cpunr];
KeSetEvent(&pi->FileAccess, 0, FALSE);
//DbgPrint("Released");
}
}
UINT64 ultimap2_GetTraceFileSize()
//Gets an aproximation of the filesize. Don't take this too exact
{
UINT64 size = 0;
if (PInfo)
{
int i;
for (i = 0; i < Ultimap2CpuCount; i++)
size += PInfo[i]->TraceFileSize;
}
return size;
}
void ultimap2_ResetTraceFileSize()
{
if (PInfo)
{
int i;
for (i = 0; i < Ultimap2CpuCount; i++)
PInfo[i]->TraceFileSize = 0;
}
}
void SwitchToPABuffer(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
/*
DPC routine that switches the Buffer pointer and marks buffer2 that it's ready for data saving
Only called when buffer2 is ready for flushing
*/
{
//write the contents of the current cpu buffer
PProcessorInfo pi = PInfo[KeGetCurrentProcessorNumber()];
//DbgPrint("SwitchToPABuffer for cpu %d\n", KeGetCurrentProcessorNumber());
if (pi)
{
UINT64 CTL = __readmsr(IA32_RTIT_CTL);
UINT64 Status = __readmsr(IA32_RTIT_STATUS);
PVOID temp;
if ((Status >> 5) & 1) //Stopped
DbgPrint("%d Not all data recorded\n", KeGetCurrentProcessorNumber());
if ((Status >> 4) & 1)
DbgPrint("ALL LOST");
//only if the buffer is bigger than 2 pages. That you can check in IA32_RTIT_OUTPUT_MASK_PTRS and IA32_RTIT_OUTPUT_BASE
//if (KeGetCurrentProcessorNumber() == 0)
// DbgPrint("%d: pi->CurrentOutputBase=%p __readmsr(IA32_RTIT_OUTPUT_BASE)=%p __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)=%p", KeGetCurrentProcessorNumber(), pi->CurrentOutputBase, __readmsr(IA32_RTIT_OUTPUT_BASE), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS));
if (pi->Interrupted == FALSE)
{
//return; //debug test. remove me when released
if (!singleToPASystem)
{
if ((!flushallbuffers) && (((__readmsr(IA32_RTIT_OUTPUT_MASK_PTRS) & 0xffffffff) >> 7) < 2))
return; //don't flush yet
}
else
{
INT64 offset = __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS);
/*if (KeGetCurrentProcessorNumber() == 0)
{
DbgPrint("pi->CurrentOutputBase=%p", pi->CurrentOutputBase);
DbgPrint("offset=%p", offset);
}*/
offset = offset >> 32;
//if (KeGetCurrentProcessorNumber() == 0)
// DbgPrint("offset=%p", offset);
if ((!flushallbuffers) && (((pi->CurrentOutputBase == 0) || (offset < 8192))))
return; //don't flush yet
}
}
else
{
DbgPrint("%d:Flushing because of interrupt", KeGetCurrentProcessorNumber());
}
DbgPrint("%d: Flush this data (%p)", KeGetCurrentProcessorNumber(), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS));
//DbgPrint("%d: pi->CurrentOutputBase=%p __readmsr(IA32_RTIT_OUTPUT_BASE)=%p __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)=%p", KeGetCurrentProcessorNumber(), pi->CurrentOutputBase, __readmsr(IA32_RTIT_OUTPUT_BASE), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS));
__writemsr(IA32_RTIT_CTL, 0); //disable packet generation
__writemsr(IA32_RTIT_STATUS, 0);
//DbgPrint("%d: pi->CurrentOutputBase=%p __readmsr(IA32_RTIT_OUTPUT_BASE)=%p __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS)=%p", KeGetCurrentProcessorNumber(), pi->CurrentOutputBase, __readmsr(IA32_RTIT_OUTPUT_BASE), __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS));
//switch the pointer to the secondary buffers
KeClearEvent(&pi->Buffer2ReadyForSwap);
//swap the buffer
temp = pi->ToPABuffer;
pi->ToPABuffer = pi->ToPABuffer2;
pi->ToPABuffer2 = temp;
//swap the MDL that describes it
temp = pi->ToPABufferMDL;
pi->ToPABufferMDL = pi->ToPABuffer2MDL;
pi->ToPABuffer2MDL = temp;
//swap the header
temp = pi->ToPAHeader;
pi->ToPAHeader = pi->ToPAHeader2;
pi->ToPAHeader2 = temp;
//swap the lookup table
temp = pi->ToPALookupTable;
pi->ToPALookupTable = pi->ToPALookupTable2;
pi->ToPALookupTable2 = temp;
//lookup which entry it's pointing at
pi->CurrentSaveOutputBase = __readmsr(IA32_RTIT_OUTPUT_BASE);
pi->CurrentSaveOutputMask = __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS);
KeSetEvent(&pi->InitiateSave,0,FALSE);
pi->Interrupted = FALSE;
//reactivate packet generation
pi->CurrentOutputBase = MmGetPhysicalAddress(pi->ToPAHeader).QuadPart;
__writemsr(IA32_RTIT_OUTPUT_BASE, pi->CurrentOutputBase);
__writemsr(IA32_RTIT_OUTPUT_MASK_PTRS, 0);
__writemsr(IA32_RTIT_CTL, CTL);
}
}
void WaitForWriteToFinishAndSwapWriteBuffers(BOOL interruptedOnly)
{
int i;
for (i = 0; i < Ultimap2CpuCount; i++)
{
PProcessorInfo pi = PInfo[i];
if ((pi->ToPABuffer2) && ((pi->Interrupted) || (!interruptedOnly)))
{
KeWaitForSingleObject(&pi->Buffer2ReadyForSwap, Executive, KernelMode, FALSE, NULL);
if (!UltimapActive) return;
KeInsertQueueDpc(&pi->OwnDPC, NULL, NULL);
}
}
KeFlushQueuedDpcs();
}
void bufferWriterThread(PVOID StartContext)
{
//passive mode
//wait for event
LARGE_INTEGER Timeout;
NTSTATUS wr;
DbgPrint("bufferWriterThread active");
while (UltimapActive)
{
if (NoPMIMode)
Timeout.QuadPart = -1000LL; //- 10000LL=1 millisecond //-100000000LL = 10 seconds -1000000LL= 0.1 second
else
Timeout.QuadPart = -10000LL; //- 10000LL=1 millisecond //-100000000LL = 10 seconds -1000000LL= 0.1 second
//DbgPrint("%d : Wait for FlushData", cpunr());
wr = KeWaitForSingleObject(&FlushData, Executive, KernelMode, FALSE, &Timeout);
//DbgPrint("%d : After wait for FlushData", cpunr());
//wr = KeWaitForSingleObject(&FlushData, Executive, KernelMode, FALSE, NULL);
//DbgPrint("bufferWriterThread: Alive (wr==%x)", wr);
if (!UltimapActive)
{
DbgPrint("bufferWriterThread: Terminating");
return;
}
//if (wr != STATUS_SUCCESS) continue; //DEBUG code so PMI's get triggered
if ((wr == STATUS_SUCCESS) || (wr == STATUS_TIMEOUT))
{
if ((wr == STATUS_SUCCESS) && (!isSuspended))
{
//woken up by a dpc
DbgPrint("FlushData event set and not suspended. Suspending target process\n");
KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL);
if (!isSuspended)
{
DbgPrint("Still going to suspend target process");
if (PsSuspendProcess(CurrentTarget)==0)
isSuspended = TRUE;
}
KeReleaseMutex(&SuspendMutex, FALSE);
DbgPrint("After the target has been suspended (isSuspended=%d)\n", isSuspended);
}
if (wr == STATUS_SUCCESS) //the filled cpu's must take preference
{
unsigned int i;
BOOL found = TRUE;
//DbgPrint("bufferWriterThread: Suspended");
//first flush the CPU's that complained their buffers are full
DbgPrint("Flushing full CPU\'s");
while (found)
{
WaitForWriteToFinishAndSwapWriteBuffers(TRUE);
if (!UltimapActive) return;
//check if no interrupt has been triggered while this was busy ('could' happen as useless info like core ratio is still recorded)
found = FALSE;
for (i = 0; i < KeQueryMaximumProcessorCount(); i++)
{
if (PInfo[i]->Interrupted)
{
DbgPrint("PInfo[%d]->Interrupted\n", PInfo[i]->Interrupted);
found = TRUE;
break;
}
}
}
}
//wait till the previous buffers are done writing
//DbgPrint("%d: Normal flush", cpunr());
WaitForWriteToFinishAndSwapWriteBuffers(FALSE);
//DbgPrint("%d : after flush", cpunr());
if (isSuspended)
{
KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL);
if (isSuspended)
{
DbgPrint("Resuming target process");
PsResumeProcess(CurrentTarget);
isSuspended = FALSE;
}
KeReleaseMutex(&SuspendMutex, FALSE);
}
//an interrupt could have fired while WaitForWriteToFinishAndSwapWriteBuffers was busy, pausing the process. If that happened, then the next KeWaitForSingleObject will exit instantly due to it being signaled
}
else
DbgPrint("Unexpected wait result");
}
}
NTSTATUS ultimap2_flushBuffers()
{
if (!UltimapActive)
return STATUS_UNSUCCESSFUL;
DbgPrint("ultimap2_flushBuffers");
KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL);
if (CurrentTarget)
{
if (!isSuspended)
{
PsSuspendProcess(CurrentTarget);
isSuspended = TRUE;
}
}
KeReleaseMutex(&SuspendMutex, FALSE);
flushallbuffers = TRUE;
DbgPrint("wait1");
WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //write the last saved buffer
DbgPrint("wait2");
WaitForWriteToFinishAndSwapWriteBuffers(FALSE); //write the current buffer
flushallbuffers = FALSE;
DbgPrint("after wait");
KeWaitForSingleObject(&SuspendMutex, Executive, KernelMode, FALSE, NULL);
if (CurrentTarget)
{
if (isSuspended)
{
PsResumeProcess(CurrentTarget);
isSuspended = FALSE;
}
}
KeReleaseMutex(&SuspendMutex, FALSE);
DbgPrint("ultimap2_flushBuffers exit");
return STATUS_SUCCESS;
}
void RTIT_DPC_Handler(__in struct _KDPC *Dpc, __in_opt PVOID DeferredContext, __in_opt PVOID SystemArgument1,__in_opt PVOID SystemArgument2)
{
//Signal the bufferWriterThread
KeSetEvent(&SuspendEvent, 0, FALSE);
KeSetEvent(&FlushData, 0, FALSE);
}
void PMI(__in struct _KINTERRUPT *Interrupt, __in PVOID ServiceContext)
{
//check if caused by me, if so defer to dpc
DbgPrint("PMI");
__try
{
if ((__readmsr(IA32_PERF_GLOBAL_STATUS) >> 55) & 1)
{
UINT64 Status = __readmsr(IA32_RTIT_STATUS);
DbgPrint("PMI: caused by me");
__writemsr(IA32_PERF_GLOBAL_OVF_CTRL, (UINT64)1 << 55); //clear ToPA full status
if ((__readmsr(IA32_PERF_GLOBAL_STATUS) >> 55) & 1)
{
DbgPrint("PMI: Failed to clear the status\n");
}
DbgPrint("PMI: IA32_RTIT_OUTPUT_MASK_PTRS=%p\n", __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS));
DbgPrint("PMI: IA32_RTIT_STATUS=%p\n", Status);
if ((Status >> 5) & 1) //Stopped
DbgPrint("PMI %d: Not all data recorded (AT THE PMI!)\n", KeGetCurrentProcessorNumber());
DbgPrint("PMI: IA32_RTIT_OUTPUT_MASK_PTRS %p\n", __readmsr(IA32_RTIT_OUTPUT_MASK_PTRS));
PInfo[KeGetCurrentProcessorNumber()]->Interrupted = TRUE;
KeInsertQueueDpc(&RTID_DPC, NULL, NULL);
//clear apic state
apic_clearPerfmon();
}
else
{
DbgPrint("Unexpected PMI");
}
}
__except (0)
{
DbgPrint("PMI exception");
}
}
void *pperfmon_hook2 = (void *)PMI;
void ultimap2_disable_dpc(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
{
DbgPrint("ultimap2_disable_dpc for cpu %d\n", KeGetCurrentProcessorNumber());
__try
{
if (DeferredContext) //only pause
{
RTIT_CTL ctl;
DbgPrint("temp disable\n");
ctl.Value = __readmsr(IA32_RTIT_CTL);
ctl.Bits.TraceEn = 0;
__writemsr(IA32_RTIT_CTL, ctl.Value);
}
else
{
DbgPrint("%d: disable all\n", KeGetCurrentProcessorNumber());
__writemsr(IA32_RTIT_CTL, 0);
__writemsr(IA32_RTIT_STATUS, 0);
__writemsr(IA32_RTIT_CR3_MATCH, 0);
__writemsr(IA32_RTIT_OUTPUT_BASE, 0);
__writemsr(IA32_RTIT_OUTPUT_MASK_PTRS, 0);
}
}
__except (1)
{
DbgPrint("ultimap2_disable_dpc exception");
}
}
void ultimap2_setup_dpc(struct _KDPC *Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
{
RTIT_CTL ctl;
RTIT_STATUS s;
int i = -1;
__try
{
ctl.Value = __readmsr(IA32_RTIT_CTL);
}
__except (1)
{
DbgPrint("ultimap2_setup_dpc: IA32_RTIT_CTL in unreadable");
return;
}
ctl.Bits.TraceEn = 1;
if (LogKernelMode)
ctl.Bits.OS = 1;
else
ctl.Bits.OS = 0;
if (LogUserMode)
ctl.Bits.USER = 1;
else
ctl.Bits.USER = 0;
if (CurrentCR3)
ctl.Bits.CR3Filter = 1;
else
ctl.Bits.CR3Filter = 0;
ctl.Bits.ToPA = 1;
ctl.Bits.TSCEn = 0;
ctl.Bits.DisRETC = 0;
ctl.Bits.BranchEn = 1;
if (PInfo == NULL)
return;
if (PInfo[KeGetCurrentProcessorNumber()]->ToPABuffer == NULL)
{
DbgPrint("ToPA for cpu %d not setup\n", KeGetCurrentProcessorNumber());
return;
}
__try
{
int cpunr = KeGetCurrentProcessorNumber();
i = 0;
PInfo[cpunr]->CurrentOutputBase = MmGetPhysicalAddress(PInfo[cpunr]->ToPAHeader).QuadPart;
__writemsr(IA32_RTIT_OUTPUT_BASE, PInfo[cpunr]->CurrentOutputBase);
i = 1;
__writemsr(IA32_RTIT_OUTPUT_MASK_PTRS, 0);
i = 2;
__try
{
__writemsr(IA32_RTIT_CR3_MATCH, CurrentCR3);
}
__except (1)
{
CurrentCR3 = CurrentCR3 & 0xfffffffffffff000ULL;
DbgPrint("Failed to set the actual CR3. Using a sanitized CR3: %llx\n", CurrentCR3);
}
i = 3;
//ranges
if (Ultimap2Ranges && Ultimap2RangeCount)
{
for (i = 0; i < Ultimap2RangeCount; i++)
{
ULONG msr_start = IA32_RTIT_ADDR0_A + (2 * i);
ULONG msr_stop = IA32_RTIT_ADDR0_B + (2 * i);
UINT64 bit = 32 + (i * 4);
DbgPrint("Range %d: (%p -> %p)", i, (PVOID)(UINT_PTR)(Ultimap2Ranges[i].StartAddress), (PVOID)(UINT_PTR)(Ultimap2Ranges[i].EndAddress));
DbgPrint("Writing range %d to msr %x and %x", i, msr_start, msr_stop);
__writemsr(msr_start, Ultimap2Ranges[i].StartAddress);
__writemsr(msr_stop, Ultimap2Ranges[i].EndAddress);
DbgPrint("bit=%d", bit);
DbgPrint("Value before=%llx", ctl.Value);
if (Ultimap2Ranges[i].IsStopAddress)
ctl.Value |= (UINT64)2ULL << bit; //TraceStop This stops all tracing on this cpu. Doesn't get reactivated
else
ctl.Value |= (UINT64)1ULL << bit; //FilterEn //not supported in the latest windows build
DbgPrint("Value after=%llx", ctl.Value);
}
}
i = 4;
__writemsr(IA32_RTIT_STATUS, 0);
i = 5;
//if (KeGetCurrentProcessorNumber() == 0)
__writemsr(IA32_RTIT_CTL, ctl.Value);
i = 6;
s.Value=__readmsr(IA32_RTIT_STATUS);
if (s.Bits.Error)
DbgPrint("Setup for cpu %d failed", KeGetCurrentProcessorNumber());
else
DbgPrint("Setup for cpu %d succesful", KeGetCurrentProcessorNumber());
}
__except (1)
{
DbgPrint("Error in ultimap2_setup_dpc. i=%d",i);
DbgPrint("ctl.Value=%p\n", ctl.Value);
DbgPrint("CR3=%p\n", CurrentCR3);
//DbgPrint("OutputBase=%p", __readmsr(IA32_RTIT_OUTPUT_BASE));
}
}
int getToPAHeaderCount(ULONG _BufferSize)
{
return 1 + (_BufferSize / 4096) / 511;
}
int getToPAHeaderSize(ULONG _BufferSize)
{
//511 entries per ToPA header (4096*511=2093056 bytes per ToPA header)
//BufferSize / 2093056 = Number of ToPA headers needed
return getToPAHeaderCount(_BufferSize) * 4096;
}
RTL_GENERIC_COMPARE_RESULTS NTAPI ToPACompare(__in struct _RTL_GENERIC_TABLE *Table, __in PToPA_LOOKUP FirstStruct, __in PToPA_LOOKUP SecondStruct)
{
//DbgPrint("Comparing %p with %p", FirstStruct->PhysicalAddress, FirstStruct->PhysicalAddress);
if (FirstStruct->PhysicalAddress == SecondStruct->PhysicalAddress)
return GenericEqual;
else
{
if (SecondStruct->PhysicalAddress < FirstStruct->PhysicalAddress)
return GenericLessThan;
else
return GenericGreaterThan;
}
}