forked from Dnawrkshp/NetCheatPS3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.cs
More file actions
1234 lines (1050 loc) · 44.8 KB
/
API.cs
File metadata and controls
1234 lines (1050 loc) · 44.8 KB
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
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using NCAppInterface;
namespace TMAPI_NCAPI
{
public class API : IAPI, IAddressAccessLoggerApi
{
[DllImport("user32.dll")]
internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public API()
{
}
//Declarations of all our internal API variables
string myName = "Target Manager API";
string myDescription = "NetCheat API for the Target Manager API (PS3).\n\nDEX only!\nRequires ProDG Target Manager to be installed on PC.";
string myAuthor = "Dnawrkshp and iMCSx";
string myVersion = "420.1.14.7";
string myPlatform = "PS3";
string myContactLink = "";
System.Drawing.Image myIcon = null;
/// <summary>
/// Website link to contact info or download (leave "" if no link)
/// </summary>
public string ContactLink
{
get { return myContactLink; }
}
/// <summary>
/// Name of the API (displayed on title bar of NetCheat)
/// </summary>
public string Name
{
get { return myName; }
}
/// <summary>
/// Description of the API's purpose
/// </summary>
public string Description
{
get {return myDescription;}
}
/// <summary>
/// Author(s) of the API
/// </summary>
public string Author
{
get { return myAuthor; }
}
/// <summary>
/// Current version of the API
/// </summary>
public string Version
{
get {return myVersion;}
}
/// <summary>
/// Name of platform (abbreviated, i.e. PC, PS3, XBOX, iOS)
/// </summary>
public string Platform
{
get { return myPlatform; }
}
/// <summary>
/// Returns whether the platform is little endian by default
/// </summary>
public bool isPlatformLittleEndian
{
get { return false; }
}
/// <summary>
/// Icon displayed along with the other data in the API tab, if null NetCheat icon is displayed
/// </summary>
public System.Drawing.Image Icon
{
get { return myIcon; }
}
/// <summary>
/// Read bytes from memory of target process.
/// Returns read bytes into bytes array.
/// Returns false if failed.
/// </summary>
public bool GetBytes(ulong address, ref byte[] bytes)
{
if (_tmapi == null)
_tmapi = new TMAPI();
return _tmapi.GetMemory((uint)address, bytes) == PS3TMAPI.SNRESULT.SN_S_OK;
}
/// <summary>
/// Write bytes to the memory of target process.
/// </summary>
public void SetBytes(ulong address, byte[] bytes)
{
if (_tmapi == null)
_tmapi = new TMAPI();
_tmapi.SetMemory((uint)address, bytes);
}
/// <summary>
/// Shutdown game or platform
/// </summary>
public void Shutdown()
{
if (_tmapi == null)
_tmapi = new TMAPI();
_tmapi.PowerOff(true);
}
private TMAPI _tmapi;
private readonly object addressAccessLoggerLock = new object();
private AddressAccessLoggerSession activeAddressAccessLogger;
public bool SupportsAddressAccessLogging
{
get { return true; }
}
public IAddressAccessLoggerSession StartAddressAccessLogger(ulong address, AddressAccessMode mode, Action<AddressAccessHit> hitCallback)
{
if (_tmapi == null)
_tmapi = new TMAPI();
AddressAccessLoggerSession previousSession = null;
lock (addressAccessLoggerLock)
{
if (activeAddressAccessLogger != null && activeAddressAccessLogger.IsRunning)
previousSession = activeAddressAccessLogger;
}
if (previousSession != null)
previousSession.Stop();
lock (addressAccessLoggerLock)
{
activeAddressAccessLogger = new AddressAccessLoggerSession(this, _tmapi, address, mode, hitCallback);
return activeAddressAccessLogger;
}
}
private void ClearAddressAccessLoggerSession(AddressAccessLoggerSession session)
{
lock (addressAccessLoggerLock)
{
if (Object.ReferenceEquals(activeAddressAccessLogger, session))
activeAddressAccessLogger = null;
}
}
private sealed class AddressAccessLoggerSession : IAddressAccessLoggerSession
{
private static readonly bool VerboseDabrDiagnostics = false;
private const int MaxPendingDabrHits = 128;
private const int ProcessingPcCoalesceWindowMilliseconds = 35;
private readonly API owner;
private readonly TMAPI tmapi;
private readonly Action<AddressAccessHit> hitCallback;
private readonly object sync = new object();
private readonly PS3TMAPI.TargetEventCallback targetEventCallback;
private readonly Action<string> nativeEventDiagnosticSink;
private readonly Queue<ulong> pendingPcOrder = new Queue<ulong>();
private readonly Dictionary<ulong, PendingDabrHitAggregate> pendingHitsByPc = new Dictionary<ulong, PendingDabrHitAggregate>();
private readonly Dictionary<ulong, byte[]> instructionBytesByPc = new Dictionary<ulong, byte[]>();
private readonly Dictionary<ulong, int> callbackPcCounts = new Dictionary<ulong, int>();
private readonly Queue<AddressAccessHit> pendingObservedPcDiagnostics = new Queue<AddressAccessHit>();
private Thread eventPumpWorker;
private bool processingPendingDabrHit;
private bool reportedDebugThreadControlInfo;
private bool receivedNativeCallback;
private bool isRunning;
private bool registeredEvents;
private bool savedOldDabr;
private bool dabrWasArmed;
private bool savedAutoStatusUpdate;
private bool previousAutoStatusUpdate;
private bool reportedDroppedDabrHitQueueFull;
private ulong currentlyProcessingPc;
private int currentlyProcessingCoalescedCount;
private DateTime currentlyProcessingPcUntilUtc;
private ulong oldDabr;
private ulong rawDabr;
private string lastNativeEventDiagnostic;
private DateTime lastNativeEventDiagnosticTime;
private DateTime lastHitStatusUtc;
private bool reportedKickSuccess;
private bool hasLastKickFailure;
private PS3TMAPI.SNRESULT lastKickFailure;
private bool reportedInvalidDabrParse;
public AddressAccessLoggerSession(API owner, TMAPI tmapi, ulong address, AddressAccessMode mode, Action<AddressAccessHit> hitCallback)
{
this.owner = owner;
this.tmapi = tmapi;
this.hitCallback = hitCallback;
Address = address;
Mode = mode;
targetEventCallback = HandleTargetEvents;
nativeEventDiagnosticSink = PublishNativeEventDiagnostic;
StartWorker();
}
private sealed class PendingDabrHitAggregate
{
public AddressAccessHit LastHit;
public int PendingCount;
public DateTime LastSeen;
}
public ulong Address { get; private set; }
public AddressAccessMode Mode { get; private set; }
public bool IsRunning
{
get
{
lock (sync)
{
return isRunning;
}
}
}
public void Stop()
{
bool shouldStop;
lock (sync)
{
shouldStop = isRunning;
isRunning = false;
}
if (!shouldStop)
return;
JoinWorker();
}
public void Dispose()
{
Stop();
}
private void StartWorker()
{
lock (sync)
{
isRunning = true;
}
eventPumpWorker = new Thread(RunLoggerWorker);
eventPumpWorker.IsBackground = true;
eventPumpWorker.Name = "TMAPI DABR callback/event pump";
eventPumpWorker.Start();
}
private void JoinWorker()
{
Thread worker = eventPumpWorker;
if (worker == null || worker == Thread.CurrentThread)
return;
if (!worker.Join(1000))
PublishDiagnostic("TMAPI DABR callback/event pump did not exit before timeout.");
}
private void RunLoggerWorker()
{
try
{
if (!StartOnWorkerThread())
return;
PumpTargetEventsOnWorkerThread();
}
catch (Exception ex)
{
PublishError("TMAPI DABR logger worker failed: " + ex.Message);
}
finally
{
CleanupOnWorkerThread();
lock (sync)
{
isRunning = false;
}
owner.ClearAddressAccessLoggerSession(this);
}
}
private bool StartOnWorkerThread()
{
PS3TMAPI.SNRESULT initResult = tmapi.EnsureTargetCommsInitialized();
PublishVerboseDiagnostic("InitTargetComms: " + initResult.ToString());
bool previousAutoStatus;
PS3TMAPI.SNRESULT autoStatusResult = tmapi.EnableAutoStatusUpdate(true, out previousAutoStatus);
PublishVerboseDiagnostic("EnableAutoStatusUpdate: " + autoStatusResult.ToString() +
", previous=" + previousAutoStatus.ToString() + ".");
savedAutoStatusUpdate = PS3TMAPI.SUCCEEDED(autoStatusResult);
previousAutoStatusUpdate = previousAutoStatus;
if (!IsRunning)
return false;
PS3TMAPI.NativeEventDiagnosticSink = nativeEventDiagnosticSink;
PublishVerboseDiagnostic("No TMAPI native callback has been received yet.");
PS3TMAPI.SNRESULT result = tmapi.GetDABR(out oldDabr);
savedOldDabr = PS3TMAPI.SUCCEEDED(result);
if (!IsRunning)
return false;
object userData = null;
result = tmapi.RegisterTargetEventHandler(targetEventCallback, ref userData);
PublishVerboseDiagnostic("RegisterTargetEventHandler: " + result.ToString());
if (!PS3TMAPI.SUCCEEDED(result))
{
PublishError("TMAPI RegisterTargetEventHandler failed: " + result.ToString());
return false;
}
registeredEvents = true;
if (!IsRunning)
return false;
rawDabr = BuildRawDabr(Address, Mode);
result = tmapi.ProcessStop();
PublishDiagnostic("ProcessStop before DABR arm: " + result.ToString() + ".");
if (!PS3TMAPI.SUCCEEDED(result))
{
PublishError("DABR logger startup failed because ProcessStop failed: " + result.ToString() + ".");
return false;
}
result = tmapi.SetDABR(rawDabr);
if (!PS3TMAPI.SUCCEEDED(result))
{
PS3TMAPI.SNRESULT continueAfterFailedArm = tmapi.ProcessContinue();
PublishDiagnostic("ProcessContinue after failed DABR arm: " + continueAfterFailedArm.ToString() + ".");
PublishError("TMAPI SetDABR failed while stopped: " + result.ToString());
return false;
}
PublishDiagnostic("DABR armed while stopped: " + result.ToString() + ".");
result = tmapi.ProcessContinue();
PublishDiagnostic("ProcessContinue after DABR arm: " + result.ToString() + ".");
if (!PS3TMAPI.SUCCEEDED(result))
{
try
{
PS3TMAPI.SNRESULT restoreResult = savedOldDabr
? tmapi.SetDABR(oldDabr)
: tmapi.SetDABR(0);
PublishDiagnostic("Restore/Clear DABR after failed arm continue: " + restoreResult.ToString() + ".");
}
catch (Exception ex)
{
PublishError("Failed to restore/clear DABR after failed arm continue: " + ex.Message);
}
PublishError("DABR logger startup failed because ProcessContinue after arm failed: " + result.ToString() + ".");
return false;
}
dabrWasArmed = true;
if (VerboseDabrDiagnostics)
PublishInitialThreadListProbe();
PublishVerboseDiagnostic("TMAPI DABR logger uses SNPS3Kick on the callback registration thread. Polling auto-resume remains disabled for target safety.");
PublishDiagnostic("DABR set to 0x" + rawDabr.ToString("X16") + ". Waiting for " + Mode.ToString().ToLowerInvariant() + " hit.");
return true;
}
private void CleanupOnWorkerThread()
{
if (!receivedNativeCallback)
PublishDiagnostic("No TMAPI native callback was received during this logger session.");
if (registeredEvents)
{
try
{
PS3TMAPI.SNRESULT result = tmapi.CancelTargetEvents();
PublishDiagnostic("CancelTargetEvents: " + result.ToString() + ".");
}
catch (Exception ex)
{
PublishError("Failed to cancel TMAPI target events: " + ex.Message);
}
finally
{
registeredEvents = false;
}
}
if (dabrWasArmed)
{
RestoreOrClearDabrOnStoppedProcess();
dabrWasArmed = false;
}
PublishObservedPcDiagnosticsOutsideCallback();
LogCallbackPcHistogram();
pendingPcOrder.Clear();
pendingHitsByPc.Clear();
pendingObservedPcDiagnostics.Clear();
processingPendingDabrHit = false;
RestoreAutoStatusUpdateOnWorkerThread();
if (Object.ReferenceEquals(PS3TMAPI.NativeEventDiagnosticSink, nativeEventDiagnosticSink))
PS3TMAPI.NativeEventDiagnosticSink = null;
}
private void RestoreOrClearDabrOnStoppedProcess()
{
PS3TMAPI.SNRESULT stopResult;
try
{
stopResult = tmapi.ProcessStop();
}
catch (Exception ex)
{
PublishError("ProcessStop before DABR clear threw: " + ex.Message);
return;
}
PublishDiagnostic("ProcessStop before DABR clear: " + stopResult.ToString() + ".");
if (!PS3TMAPI.SUCCEEDED(stopResult))
{
PublishError("DABR clear skipped because ProcessStop failed: " + stopResult.ToString() + ".");
return;
}
try
{
PS3TMAPI.SNRESULT restoreResult = savedOldDabr
? tmapi.SetDABR(oldDabr)
: tmapi.SetDABR(0);
PublishDiagnostic("Restore/Clear DABR while stopped: " + restoreResult.ToString() + ".");
}
catch (Exception ex)
{
PublishError("Failed to restore/clear DABR while stopped: " + ex.Message);
}
finally
{
try
{
PS3TMAPI.SNRESULT continueResult = tmapi.ProcessContinue();
PublishDiagnostic("ProcessContinue after DABR clear: " + continueResult.ToString() + ".");
}
catch (Exception ex)
{
PublishError("ProcessContinue after DABR clear threw: " + ex.Message);
}
}
}
private void RestoreAutoStatusUpdateOnWorkerThread()
{
if (!savedAutoStatusUpdate)
return;
savedAutoStatusUpdate = false;
try
{
bool ignoredPreviousState;
PS3TMAPI.SNRESULT result = tmapi.EnableAutoStatusUpdate(previousAutoStatusUpdate, out ignoredPreviousState);
PublishDiagnostic("Restore EnableAutoStatusUpdate: " + result.ToString() +
", restored=" + previousAutoStatusUpdate.ToString() + ".");
}
catch (Exception ex)
{
PublishError("Failed to restore TMAPI auto status update: " + ex.Message);
}
}
private static ulong BuildRawDabr(ulong address, AddressAccessMode mode)
{
ulong aligned = address & ~0x7UL;
// Experimental until runtime-tested: if read/write separation fires the
// same way for both modes, SNPS3SetHWBreakPointData may be needed later.
if (mode == AddressAccessMode.Write)
return aligned | 0x4UL | 0x2UL;
return aligned | 0x4UL | 0x1UL;
}
// SNPS3Kick invokes this callback on the logger worker thread. Keep it
// parser-only: no SetDABR, ProcessContinue, ThreadContinue, sleeps, or
// other target-control calls are safe while the callback stack is active.
private void HandleTargetEvents(
int target,
PS3TMAPI.SNRESULT result,
PS3TMAPI.TargetEvent[] targetEventList,
object userData)
{
if (!IsRunning)
return;
int eventCount = targetEventList == null ? 0 : targetEventList.Length;
PublishVerboseDiagnostic("Target event received: target=" + target.ToString() +
" result=" + result.ToString() +
" events=" + eventCount.ToString("N0") + ".");
bool handledDabrMatch = false;
bool ignoredTargetEvent = false;
if (targetEventList != null)
{
foreach (PS3TMAPI.TargetEvent targetEvent in targetEventList)
{
if (targetEvent.Type != PS3TMAPI.TargetEventType.TargetSpecific)
{
ignoredTargetEvent = true;
continue;
}
PS3TMAPI.TargetSpecificEvent specific = targetEvent.TargetSpecific;
if (specific.Data.Type != PS3TMAPI.TargetSpecificEventType.PPUExcDabrMatch)
{
ignoredTargetEvent = true;
continue;
}
handledDabrMatch = true;
HandleDabrMatch(specific);
}
}
if (!handledDabrMatch && ignoredTargetEvent)
PublishIgnoredNonDabrEvent();
}
private void HandleDabrMatch(PS3TMAPI.TargetSpecificEvent specific)
{
AddressAccessHit hit = new AddressAccessHit();
hit.WatchedAddress = Address;
hit.Mode = Mode;
hit.RawDabr = rawDabr;
hit.Timestamp = DateTime.Now;
PS3TMAPI.PPUExceptionData exceptionData = specific.Data.PPUException;
hit.ThreadId = exceptionData.ThreadID;
hit.HWThreadNumber = exceptionData.HWThreadNumber;
hit.ProgramCounter = exceptionData.PC;
hit.StackPointer = exceptionData.SP;
if ((hit.ProgramCounter == 0 || hit.ThreadId == 0) && specific.Data.PPUDataMatException.ThreadID != 0)
{
hit.ThreadId = specific.Data.PPUDataMatException.ThreadID;
hit.HWThreadNumber = specific.Data.PPUDataMatException.HWThreadNumber;
hit.ProgramCounter = specific.Data.PPUDataMatException.PC;
hit.StackPointer = specific.Data.PPUDataMatException.SP;
}
if (!IsSaneDabrHit(hit))
{
PublishInvalidDabrParse(specific);
PublishError("DABR event parsed with invalid or unreasonable ThreadID/PC; not resuming.");
return;
}
if (!QueuePendingDabrHit(hit))
return;
PublishVerboseDiagnostic("DABR payload parsed: thread=0x" + hit.ThreadId.ToString("X16") +
" pc=0x" + hit.ProgramCounter.ToString("X16") +
" sp=0x" + hit.StackPointer.ToString("X16") +
" hwThread=" + exceptionData.HWThreadNumber.ToString() + ".");
PublishVerboseDiagnostic("DABR callback queued hit; returning from callback.");
}
private static bool IsSaneDabrHit(AddressAccessHit hit)
{
if (hit == null)
return false;
if (hit.ThreadId == 0 || hit.ProgramCounter == 0)
return false;
if (hit.ProgramCounter >= 0x100000000UL)
return false;
return true;
}
private bool QueuePendingDabrHit(AddressAccessHit hit)
{
lock (sync)
{
if (!isRunning)
return false;
DateTime now = DateTime.UtcNow;
IncrementCallbackPcCount(hit);
if (processingPendingDabrHit &&
hit.ProgramCounter == currentlyProcessingPc &&
now < currentlyProcessingPcUntilUtc)
{
currentlyProcessingCoalescedCount++;
return true;
}
PendingDabrHitAggregate aggregate;
if (pendingHitsByPc.TryGetValue(hit.ProgramCounter, out aggregate))
{
aggregate.LastHit = hit;
aggregate.PendingCount++;
aggregate.LastSeen = now;
return true;
}
if (pendingHitsByPc.Count >= MaxPendingDabrHits)
{
ulong droppedPc = pendingPcOrder.Dequeue();
pendingHitsByPc.Remove(droppedPc);
if (!reportedDroppedDabrHitQueueFull)
{
reportedDroppedDabrHitQueueFull = true;
PublishVerboseDiagnostic("Dropped DABR hit because pending queue is full.");
}
}
aggregate = new PendingDabrHitAggregate();
aggregate.LastHit = hit;
aggregate.PendingCount = 1;
aggregate.LastSeen = now;
pendingHitsByPc.Add(hit.ProgramCounter, aggregate);
pendingPcOrder.Enqueue(hit.ProgramCounter);
return true;
}
}
private void IncrementCallbackPcCount(AddressAccessHit hit)
{
ulong programCounter = hit.ProgramCounter;
int count;
if (callbackPcCounts.TryGetValue(programCounter, out count))
{
callbackPcCounts[programCounter] = count + 1;
return;
}
callbackPcCounts.Add(programCounter, 1);
pendingObservedPcDiagnostics.Enqueue(CloneHit(hit));
}
private static AddressAccessHit CloneHit(AddressAccessHit hit)
{
if (hit == null)
return null;
AddressAccessHit clone = new AddressAccessHit();
clone.WatchedAddress = hit.WatchedAddress;
clone.ProgramCounter = hit.ProgramCounter;
clone.StackPointer = hit.StackPointer;
clone.ThreadId = hit.ThreadId;
clone.HWThreadNumber = hit.HWThreadNumber;
clone.RawDabr = hit.RawDabr;
clone.Mode = hit.Mode;
clone.Timestamp = hit.Timestamp;
return clone;
}
private void ProcessPendingDabrHitsOutsideCallback()
{
PendingDabrHitAggregate aggregate;
lock (sync)
{
if (!isRunning || pendingPcOrder.Count == 0 || processingPendingDabrHit)
return;
ulong programCounter = pendingPcOrder.Dequeue();
if (!pendingHitsByPc.TryGetValue(programCounter, out aggregate))
return;
pendingHitsByPc.Remove(programCounter);
processingPendingDabrHit = true;
currentlyProcessingPc = programCounter;
currentlyProcessingCoalescedCount = 0;
currentlyProcessingPcUntilUtc = DateTime.UtcNow.AddMilliseconds(ProcessingPcCoalesceWindowMilliseconds);
}
try
{
AddressAccessHit hit = aggregate == null ? null : aggregate.LastHit;
if (hit == null)
return;
PS3TMAPI.SNRESULT resumeResult = ContinueAfterValidDabrHit();
int coalescedCount;
lock (sync)
{
coalescedCount = currentlyProcessingCoalescedCount;
currentlyProcessingCoalescedCount = 0;
}
hit.CountDelta = Math.Max(1, aggregate.PendingCount + coalescedCount);
hit.InstructionBytes = GetInstructionBytesForHit(hit.ProgramCounter);
PublishHit(hit);
PublishVerboseDiagnostic("DABR hit: thread=0x" + hit.ThreadId.ToString("X16") +
" PC=0x" + hit.ProgramCounter.ToString("X8") + ".");
PublishHitResumeStatus(resumeResult);
}
finally
{
lock (sync)
{
processingPendingDabrHit = false;
currentlyProcessingCoalescedCount = 0;
}
}
}
// Working DABR hit handling:
// 1. Queue the callback data and return from SNPS3Kick's callback.
// 2. Outside the callback, request process-level resume with
// ProcessContinue. DABR stays armed across hits.
//
// SNPS3SetDABR requires all PPU threads stopped, so this logger arms
// DABR once at startup and restores/clears it once at stop. Re-arming
// on every hot hit caused blind windows and target freezes.
//
// Do not call ThreadExceptionClean here. TMAPI documentation says it
// clears the exception state and causes the thread to exit, which
// killed the DABR-hit thread during runtime testing.
private PS3TMAPI.SNRESULT ContinueAfterValidDabrHit()
{
if (!dabrWasArmed)
return PS3TMAPI.SNRESULT.SN_E_ERROR;
return TryProcessContinueAfterDabrHit();
}
private PS3TMAPI.SNRESULT TryProcessContinueAfterDabrHit()
{
try
{
PS3TMAPI.SNRESULT result = tmapi.ProcessContinue();
PublishVerboseDiagnostic("ProcessContinue after DABR hit: " + result.ToString() + ".");
return result;
}
catch (Exception ex)
{
PublishError("ProcessContinue after DABR hit threw: " + ex.Message);
return PS3TMAPI.SNRESULT.SN_E_COMMS_ERR;
}
}
private void PublishHitResumeStatus(PS3TMAPI.SNRESULT resumeResult)
{
if (!PS3TMAPI.SUCCEEDED(resumeResult))
{
PublishError("Hit logged, but ProcessContinue failed: " +
resumeResult.ToString() + ". Use ProDG/NetCheat Continue.");
return;
}
DateTime now = DateTime.UtcNow;
if ((now - lastHitStatusUtc).TotalMilliseconds < 250)
return;
lastHitStatusUtc = now;
PublishDiagnostic("Hit logged. Process resumed; DABR remains armed.");
}
private void PublishIgnoredNonDabrEvent()
{
DateTime now = DateTime.UtcNow;
lock (sync)
{
if (lastNativeEventDiagnostic == "Ignored non-DABR target event." &&
(now - lastNativeEventDiagnosticTime).TotalMilliseconds < 1000)
{
return;
}
lastNativeEventDiagnostic = "Ignored non-DABR target event.";
lastNativeEventDiagnosticTime = now;
}
PublishVerboseDiagnostic("Ignored non-DABR target event.");
}
private void PublishInvalidDabrParse(PS3TMAPI.TargetSpecificEvent specific)
{
if (reportedInvalidDabrParse)
return;
reportedInvalidDabrParse = true;
string diagnostic =
"Invalid DABR parse diagnostic: targetEventSize=" + specific.TargetEventSize.ToString("N0") +
" targetEvent=0x" + specific.TargetEventTypeRaw.ToString("X8") +
" commandID=0x" + specific.CommandID.ToString("X8") +
" requestID=0x" + specific.RequestID.ToString("X8") +
" dataLength=" + specific.DataLength.ToString("N0") +
" processID=0x" + specific.ProcessID.ToString("X8") +
" result=0x" + specific.Result.ToString("X8") +
" eventType=" + specific.Data.Type.ToString() +
" payloadOffset=" + specific.PayloadOffset.ToString("N0") +
" payloadSize=" + specific.PayloadSize.ToString("N0") +
" parseError=" + (specific.ParseError ?? String.Empty) +
" debugData[0..64]=" + (specific.RawDebugDataHex ?? String.Empty) + ".";
LogDabrDiagnostic(diagnostic);
PublishDiagnostic("Invalid DABR parse diagnostic written to NetCheatPS3_dabr_logger.log.");
}
private void LogDabrDiagnostic(string diagnostic)
{
try
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NetCheatPS3_dabr_logger.log");
File.AppendAllText(path,
"==================================================" + Environment.NewLine +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + Environment.NewLine +
diagnostic + Environment.NewLine + Environment.NewLine);
}
catch (Exception ex)
{
PublishDiagnostic("Failed to write DABR diagnostic log: " + ex.Message);
}
}
private void PumpTargetEventsOnWorkerThread()
{
while (IsRunning)
{
try
{
PumpOneTargetEventSlice();
PublishObservedPcDiagnosticsOutsideCallback();
ProcessPendingDabrHitsOutsideCallback();
if (VerboseDabrDiagnostics)
PublishDebugThreadControlInfoOnce();
}
catch (Exception ex)
{
PublishError("TMAPI event pump failed: " + ex.Message);
}
Thread.Sleep(15);
}
}
private void PublishObservedPcDiagnosticsOutsideCallback()
{
while (true)
{
AddressAccessHit hit;
lock (sync)
{
if (pendingObservedPcDiagnostics.Count == 0)
return;
hit = pendingObservedPcDiagnostics.Dequeue();
}
if (hit == null)
continue;
string message = "Observed DABR callback PC 0x" + hit.ProgramCounter.ToString("X8");
PublishDiagnostic(message);
LogDabrDiagnostic(
message +
" watched=0x" + hit.WatchedAddress.ToString("X8") +
" mode=" + hit.Mode.ToString() +
" thread=0x" + hit.ThreadId.ToString("X16") +
" hwThread=" + hit.HWThreadNumber.ToString() +
" sp=0x" + hit.StackPointer.ToString("X16") +
" timestamp=" + hit.Timestamp.ToString("O") + ".");
}
}
private void LogCallbackPcHistogram()
{
KeyValuePair<ulong, int>[] snapshot;
lock (sync)
{
if (callbackPcCounts.Count == 0)
return;
snapshot = new KeyValuePair<ulong, int>[callbackPcCounts.Count];
int index = 0;
foreach (KeyValuePair<ulong, int> entry in callbackPcCounts)
{
snapshot[index] = entry;
index++;
}
}
Array.Sort(snapshot, delegate(KeyValuePair<ulong, int> left, KeyValuePair<ulong, int> right)
{
return left.Key.CompareTo(right.Key);
});
StringBuilder sb = new StringBuilder();
sb.AppendLine("DABR callback PC histogram for 0x" + Address.ToString("X8") + ":");
foreach (KeyValuePair<ulong, int> entry in snapshot)
sb.AppendLine("0x" + entry.Key.ToString("X8") + " = " + entry.Value.ToString("N0"));
LogDabrDiagnostic(sb.ToString().TrimEnd());
}
private void PumpOneTargetEventSlice()
{
PS3TMAPI.SNRESULT kickResult = tmapi.Kick();
if (PS3TMAPI.SUCCEEDED(kickResult))
{
if (!reportedKickSuccess)
{
reportedKickSuccess = true;
PublishVerboseDiagnostic("SNPS3Kick event pump active on callback registration thread.");
}
hasLastKickFailure = false;
return;
}
if (!hasLastKickFailure || lastKickFailure != kickResult)
{
hasLastKickFailure = true;
lastKickFailure = kickResult;
PublishError("SNPS3Kick failed: " + kickResult.ToString());
}
}
private void PublishInitialThreadListProbe()
{
try
{
ulong[] ppuThreadIDs;
ulong[] spuThreadIDs;
PS3TMAPI.SNRESULT listResult = tmapi.GetThreadList(TMAPI.Target, tmapi.SCE.ProcessID(), out ppuThreadIDs, out spuThreadIDs);
int ppuCount = ppuThreadIDs == null ? 0 : ppuThreadIDs.Length;
int spuCount = spuThreadIDs == null ? 0 : spuThreadIDs.Length;
PublishDiagnostic("GetThreadList initial probe: " + listResult.ToString() +
", PPU=" + ppuCount.ToString("N0") +
", SPU=" + spuCount.ToString("N0") + ".");
if (listResult == PS3TMAPI.SNRESULT.SN_E_DLL_NOT_INITIALISED)
PublishDiagnostic("InitTargetComms last result: " + tmapi.LastTargetCommsInitResult.ToString() + ".");
}
catch (Exception ex)
{
PublishError("GetThreadList initial probe failed: " + ex.Message);
}
}
private void PublishDebugThreadControlInfoOnce()
{
if (reportedDebugThreadControlInfo)
return;
reportedDebugThreadControlInfo = true;
PublishDiagnostic(tmapi.GetDebugThreadControlInfoDiagnostic());
}
private void PublishNativeEventDiagnostic(string diagnostic)
{
lock (sync)
{