-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathdbgengttdadapter.cpp
More file actions
2422 lines (2086 loc) · 68.2 KB
/
dbgengttdadapter.cpp
File metadata and controls
2422 lines (2086 loc) · 68.2 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
#include "dbgengttdadapter.h"
#include <filesystem>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace BinaryNinjaDebugger;
using namespace std;
DbgEngTTDAdapter::DbgEngTTDAdapter(BinaryView* data) : DbgEngAdapter(data)
{
m_usePDBFileName = false;
m_eventsCached = false;
GenerateDefaultAdapterSettings(data);
}
bool DbgEngTTDAdapter::ExecuteWithArgsInternal(const std::string& path, const std::string& args,
const std::string& workingDir, const LaunchConfigurations& configs) {
m_aboutToBeKilled = false;
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
auto tracePath = adapterSettings->Get<std::string>("launch.trace_path", data, &scope);
scope = SettingsResourceScope;
auto inputFile = adapterSettings->Get<std::string>("common.inputFile", data, &scope);
if (this->m_dbgengInitialized) {
this->Reset();
}
if (!Start()) {
this->Reset();
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("Failed to initialize DbgEng");
event.data.errorData.shortError = fmt::format("Failed to initialize DbgEng");
PostDebuggerEvent(event);
return false;
}
if (const auto result = this->m_debugControl->SetEngineOptions(DEBUG_ENGOPT_INITIAL_BREAK); result != S_OK) {
this->Reset();
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("Failed to engine option DEBUG_ENGOPT_INITIAL_BREAK");
event.data.errorData.shortError = fmt::format("Failed to engine option");
PostDebuggerEvent(event);
return false;
}
if (const auto result = this->m_debugClient->OpenDumpFile(const_cast<char *>(tracePath.c_str()));
result != S_OK) {
this->Reset();
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("OpenDumpFile failed: 0x{:x}", result);
event.data.errorData.shortError = fmt::format("OpenDumpFile failed: 0x{:x}", result);
PostDebuggerEvent(event);
return false;
}
// The WaitForEvent() must be called once before the engine fully attaches to the target.
if (!Wait()) {
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("WaitForEvent failed");
event.data.errorData.shortError = fmt::format("WaitForEvent failed");
PostDebuggerEvent(event);
}
// Apply the breakpoints added before the m_debugClient is created
ApplyBreakpoints();
DbgEngAdapter::InvokeBackendCommand("!index");
auto settings = Settings::Instance();
if (settings->Get<bool>("debugger.stopAtEntryPoint") && m_hasEntryFunction) {
AddBreakpoint(ModuleNameAndOffset(inputFile, m_entryPoint - m_start));
}
if (!settings->Get<bool>("debugger.stopAtSystemEntryPoint")) {
if (this->m_debugControl->SetExecutionStatus(DEBUG_STATUS_GO) != S_OK) {
this->Reset();
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("Failed to resume the target after the system entry point");
event.data.errorData.shortError = fmt::format("Failed to resume target");
PostDebuggerEvent(event);
return false;
}
}
return true;
}
bool DbgEngTTDAdapter::WriteMemory(std::uintptr_t address, const BinaryNinja::DataBuffer& buffer)
{
return false;
}
bool DbgEngTTDAdapter::WriteRegister(const std::string& reg, intx::uint512 value)
{
return false;
}
bool DbgEngTTDAdapter::Start()
{
if (this->m_dbgengInitialized)
this->Reset();
auto handle = GetModuleHandleA("dbgeng.dll");
if (handle == nullptr)
false;
// HRESULT DebugCreate(
// [in] REFIID InterfaceId,
// [out] PVOID *Interface
// );
typedef HRESULT(__stdcall * pfunDebugCreate)(REFIID, PVOID*);
auto DebugCreate = (pfunDebugCreate)GetProcAddress(handle, "DebugCreate");
if (DebugCreate == nullptr)
return false;
if (const auto result = DebugCreate(__uuidof(IDebugClient7), reinterpret_cast<void**>(&this->m_debugClient));
result != S_OK)
throw std::runtime_error("Failed to create IDebugClient7");
QUERY_DEBUG_INTERFACE(IDebugControl7, &this->m_debugControl);
QUERY_DEBUG_INTERFACE(IDebugDataSpaces, &this->m_debugDataSpaces);
QUERY_DEBUG_INTERFACE(IDebugRegisters, &this->m_debugRegisters);
QUERY_DEBUG_INTERFACE(IDebugSymbols3, &this->m_debugSymbols);
QUERY_DEBUG_INTERFACE(IDebugSystemObjects, &this->m_debugSystemObjects);
QUERY_DEBUG_INTERFACE(IHostDataModelAccess, &this->m_dataModelManager);
m_dataModelManager->GetDataModel(&m_modelMgr, &m_debugHost);
if (m_debugHost->QueryInterface(__uuidof(IDebugHostEvaluator), reinterpret_cast<void**>(&m_hostEvaluator)) != S_OK)
{
LogWarn("Failed to get IDebugHostEvaluator interface");
}
m_debugEventCallbacks.SetAdapter(this);
if (const auto result = this->m_debugClient->SetEventCallbacks(&this->m_debugEventCallbacks); result != S_OK)
{
LogWarn("Failed to set event callbacks");
return false;
}
m_outputCallbacks.SetAdapter(this);
if (const auto result = this->m_debugClient->SetOutputCallbacks(&this->m_outputCallbacks); result != S_OK)
{
LogWarn("Failed to set output callbacks");
return false;
}
m_inputCallbacks.SetDbgControl(m_debugControl);
if (const auto result = this->m_debugClient->SetInputCallbacks(&this->m_inputCallbacks); result != S_OK)
{
LogWarn("Failed to set input callbacks");
return false;
}
this->m_dbgengInitialized = true;
return true;
}
void DbgEngTTDAdapter::Reset()
{
m_aboutToBeKilled = false;
// Clear TTD events cache when resetting
ClearTTDEventsCache();
if (!this->m_dbgengInitialized)
return;
// Free up the resources if the dbgsrv is launched by the adapter. Otherwise, the dbgsrv is launched outside BN,
// we should keep everything active.
SAFE_RELEASE(this->m_debugControl);
SAFE_RELEASE(this->m_debugDataSpaces);
SAFE_RELEASE(this->m_debugRegisters);
SAFE_RELEASE(this->m_debugSymbols);
SAFE_RELEASE(this->m_dataModelManager);
SAFE_RELEASE(this->m_modelMgr);
SAFE_RELEASE(this->m_debugHost);
SAFE_RELEASE(this->m_hostEvaluator);
if (this->m_debugClient)
{
this->m_debugClient->EndSession(DEBUG_END_PASSIVE);
m_server = 0;
}
// There seems to be an internal ref-counting issue in the DbgEng TTD engine, that the reference for the debug
// client is not properly freed after the target has exited. To properly free the debug client instance, here we
// are calling Release() a few more times to ensure the ref count goes down to 0. Luckily this would not cause
// a UAF or crash.
// This might be related to the weird behavior of not terminating the target when we call TerminateProcesses(),
// (see comment in `DbgEngTTDAdapter::Quit()`).
// The same issue is not observed when we do forward debugging using the regular DbgEng. Also, I cannot reproduce
// the issue using my script https://github.com/xusheng6/dbgeng_test.
for (size_t i = 0; i < 100; i++)
m_debugClient->Release();
SAFE_RELEASE(this->m_debugClient);
this->m_dbgengInitialized = false;
}
bool DbgEngTTDAdapter::GoReverse()
{
if (ExecStatus() != DEBUG_STATUS_BREAK)
return false;
m_lastOperationIsStepInto = false;
if (this->m_debugControl->SetExecutionStatus(DEBUG_STATUS_REVERSE_GO) != S_OK)
return false;
m_debugClient->ExitDispatch(reinterpret_cast<PDEBUG_CLIENT>(m_debugClient));
return true;
}
bool DbgEngTTDAdapter::StepIntoReverse()
{
if (ExecStatus() != DEBUG_STATUS_BREAK)
return false;
m_lastOperationIsStepInto = true;
if (this->m_debugControl->SetExecutionStatus(DEBUG_STATUS_REVERSE_STEP_INTO) != S_OK)
return false;
m_debugClient->ExitDispatch(reinterpret_cast<PDEBUG_CLIENT>(m_debugClient));
return true;
}
bool DbgEngTTDAdapter::StepOverReverse()
{
if (ExecStatus() != DEBUG_STATUS_BREAK)
return false;
m_lastOperationIsStepInto = true;
if (this->m_debugControl->SetExecutionStatus(DEBUG_STATUS_REVERSE_STEP_OVER) != S_OK)
return false;
m_debugClient->ExitDispatch(reinterpret_cast<PDEBUG_CLIENT>(m_debugClient));
return true;
}
bool DbgEngTTDAdapter::StepReturnReverse()
{
if (ExecStatus() != DEBUG_STATUS_BREAK)
return false;
InvokeBackendCommand("g-u");
return true;
}
bool DbgEngTTDAdapter::SupportFeature(DebugAdapterCapacity feature)
{
return DbgEngAdapter::SupportFeature(feature) || feature == DebugAdapterSupportTTD ||
feature == DebugAdapterSupportStepOverReverse;
}
bool DbgEngTTDAdapter::Quit()
{
m_aboutToBeKilled = true;
m_lastOperationIsStepInto = false;
if (!this->m_debugClient)
return false;
// I am not sure why TerminateProcesses() would not work. It just let the target run freely till the end of the
// trace and not terminating the process at all.
if (this->m_debugClient->TerminateCurrentProcess() != S_OK)
return false;
m_debugClient->ExitDispatch(reinterpret_cast<PDEBUG_CLIENT>(m_debugClient));
return true;
}
DbgEngTTDAdapterType::DbgEngTTDAdapterType() : DebugAdapterType("DBGENG_TTD") {}
DebugAdapter* DbgEngTTDAdapterType::Create(BinaryNinja::BinaryView* data)
{
// TODO: someone should free this.
return new DbgEngTTDAdapter(data);
}
bool DbgEngTTDAdapterType::IsValidForData(BinaryNinja::BinaryView* data)
{
return data->GetTypeName() == "PE" || data->GetTypeName() == "Raw" || data->GetTypeName() == "Mapped";
}
bool DbgEngTTDAdapterType::CanConnect(BinaryNinja::BinaryView* data)
{
return true;
}
bool DbgEngTTDAdapterType::CanExecute(BinaryNinja::BinaryView* data)
{
#ifdef WIN32
return true;
#endif
return false;
}
Ref<Settings> DbgEngTTDAdapter::GetAdapterSettings()
{
return DbgEngTTDAdapterType::GetAdapterSettings();
}
Ref<Settings> DbgEngTTDAdapterType::GetAdapterSettings()
{
static Ref<Settings> settings = RegisterAdapterSettings();
return settings;
}
Ref<Settings> DbgEngTTDAdapterType::RegisterAdapterSettings()
{
Ref<Settings> settings = Settings::Instance("DbgEngTTDAdapterSettings");
settings->SetResourceId("dbgeng_ttd_adapter_settings");
settings->RegisterSetting("common.inputFile",
R"({
"title" : "Input File",
"type" : "string",
"default" : "",
"description" : "Input file to use to find the base address of the binary view",
"readOnly" : false,
"uiSelectionAction" : "file"
})");
settings->RegisterSetting("launch.trace_path",
R"({
"title" : "Trace Path",
"type" : "string",
"default" : "",
"description" : "Path of the trace file to replay.",
"readOnly" : false,
"uiSelectionAction" : "file"
})");
settings->RegisterSetting("ttd.maxMemoryQueryResults",
R"({
"title" : "Max Memory Query Results",
"type" : "number",
"default" : 100000,
"minValue" : 0,
"maxValue" : 18446744073709551615,
"description" : "Maximum number of results to return from TTD Memory queries. Set to 0 for no limit.",
"readOnly" : false
})");
settings->RegisterSetting("ttd.maxCallsQueryResults",
R"({
"title" : "Max Calls Query Results",
"type" : "number",
"default" : 100000,
"minValue" : 0,
"maxValue" : 18446744073709551615,
"description" : "Maximum number of results to return from TTD Calls queries. Set to 0 for no limit.",
"readOnly" : false
})");
settings->RegisterSetting("ttd.maxEventsQueryResults",
R"({
"title" : "Max Events Query Results",
"type" : "number",
"default" : 100000,
"minValue" : 0,
"maxValue" : 18446744073709551615,
"description" : "Maximum number of results to return from TTD Events queries. Set to 0 for no limit.",
"readOnly" : false
})");
return settings;
}
std::vector<TTDMemoryEvent> DbgEngTTDAdapter::GetTTDMemoryAccessForAddress(uint64_t startAddress, uint64_t endAddress, TTDMemoryAccessType accessType)
{
std::vector<TTDMemoryEvent> events;
if (!QueryMemoryAccessByAddress(startAddress, endAddress, accessType, events))
{
LogError("Failed to query TTD memory access events for address range 0x%llx-0x%llx", startAddress, endAddress);
}
return events;
}
std::vector<TTDPositionRangeIndexedMemoryEvent> DbgEngTTDAdapter::GetTTDMemoryAccessForPositionRange(uint64_t startAddress, uint64_t endAddress, TTDMemoryAccessType accessType, const TTDPosition startTime, const TTDPosition endTime)
{
std::vector<TTDPositionRangeIndexedMemoryEvent> events;
if (!QueryMemoryAccessByAddressAndPositionRange(startAddress, endAddress, accessType, startTime, endTime, events))
{
LogError("Failed to query TTD memory access events for address range 0x%llx-0x%llx", startAddress, endAddress);
}
return events;
}
TTDPosition DbgEngTTDAdapter::GetCurrentTTDPosition()
{
TTDPosition position;
if (!m_debugControl)
{
LogError("Debug control interface not available");
return position;
}
// Always use the !position command to retrieve the current timestamp
std::string output = InvokeBackendCommand("!position");
if (!output.empty())
{
// Parse the position output (format like "Time Travel Position: 602C:0")
size_t prefixPos = output.find("Time Travel Position:");
if (prefixPos != std::string::npos)
{
// Find the position data after the prefix
size_t dataStart = prefixPos + strlen("Time Travel Position:");
std::string positionData = output.substr(dataStart);
// Find the colon in the position data
size_t colonPos = positionData.find(':');
if (colonPos != std::string::npos)
{
try
{
std::string seqStr = positionData.substr(0, colonPos);
std::string stepStr = positionData.substr(colonPos + 1);
// Remove any non-hex characters
seqStr.erase(std::remove_if(seqStr.begin(), seqStr.end(),
[](char c) { return !std::isxdigit(c); }), seqStr.end());
stepStr.erase(std::remove_if(stepStr.begin(), stepStr.end(),
[](char c) { return !std::isxdigit(c); }), stepStr.end());
if (!seqStr.empty() && !stepStr.empty())
{
position.sequence = std::stoull(seqStr, nullptr, 16);
position.step = std::stoull(stepStr, nullptr, 16);
}
}
catch (const std::exception& e)
{
LogError("Failed to parse TTD position: %s", e.what());
}
}
}
else
{
// Fallback: try to find a simple "XXXX:Y" pattern in the output
size_t colonPos = output.find(':');
if (colonPos != std::string::npos)
{
try
{
// Look backwards from colon to find start of hex sequence
size_t seqStart = colonPos;
while (seqStart > 0 && std::isxdigit(output[seqStart - 1]))
seqStart--;
// Look forwards from colon to find end of hex step
size_t stepEnd = colonPos + 1;
while (stepEnd < output.length() && std::isxdigit(output[stepEnd]))
stepEnd++;
if (seqStart < colonPos && stepEnd > colonPos + 1)
{
std::string seqStr = output.substr(seqStart, colonPos - seqStart);
std::string stepStr = output.substr(colonPos + 1, stepEnd - colonPos - 1);
if (!seqStr.empty() && !stepStr.empty())
{
position.sequence = std::stoull(seqStr, nullptr, 16);
position.step = std::stoull(stepStr, nullptr, 16);
}
}
}
catch (const std::exception& e)
{
LogError("Failed to parse TTD position from fallback parsing: %s", e.what());
}
}
}
}
return position;
}
bool DbgEngTTDAdapter::SetTTDPosition(const TTDPosition& position)
{
if (!m_debugControl)
{
LogError("Debug control interface not available");
return false;
}
// Use InvokeBackendCommand with !tt command to navigate to position
std::string command = fmt::format("!tt {:X}:{:X}", position.sequence, position.step);
std::string output = InvokeBackendCommand(command);
// Check if the command succeeded (basic check)
bool success = output.find("error") == std::string::npos && output.find("failed") == std::string::npos;
if (success)
{
LogInfo("%s", fmt::format("Successfully navigated to TTD position {:X}:{:X}", position.sequence, position.step).c_str());
}
else
{
LogError("%s", fmt::format("Failed to navigate to TTD position {:X}:{:X}", position.sequence, position.step).c_str());
}
return success;
}
std::pair<bool, TTDMemoryEvent> DbgEngTTDAdapter::GetTTDNextMemoryAccess(uint64_t address, uint64_t size, TTDMemoryAccessType accessType)
{
if (!m_debugControl)
{
LogError("Debug control interface not available");
return {false, TTDMemoryEvent()};
}
try
{
std::string accessTypeStr;
if (accessType & TTDMemoryRead) accessTypeStr += "r";
if (accessType & TTDMemoryWrite) accessTypeStr += "w";
if (accessType & TTDMemoryExecute) accessTypeStr += "e";
if (accessTypeStr.empty())
{
LogError("Invalid access type specified");
return {false, TTDMemoryEvent()};
}
std::string expression = fmt::format("@$curprocess.TTD.NextMemoryAccess(\"{}\",0x{:x},0x{:x})", accessTypeStr, address, size);
LogInfo("Executing TTD NextMemoryAccess query: %s", expression.c_str());
return ParseSingleTTDMemoryObject(expression, accessType);
}
catch (const std::exception& e)
{
LogError("Exception in GetTTDNextMemoryAccess: %s", e.what());
return {false, TTDMemoryEvent()};
}
}
std::pair<bool, TTDMemoryEvent> DbgEngTTDAdapter::GetTTDPrevMemoryAccess(uint64_t address, uint64_t size, TTDMemoryAccessType accessType)
{
if (!m_debugControl)
{
LogError("Debug control interface not available");
return {false, TTDMemoryEvent()};
}
try
{
std::string accessTypeStr;
if (accessType & TTDMemoryRead) accessTypeStr += "r";
if (accessType & TTDMemoryWrite) accessTypeStr += "w";
if (accessType & TTDMemoryExecute) accessTypeStr += "e";
if (accessTypeStr.empty())
{
LogError("Invalid access type specified");
return {false, TTDMemoryEvent()};
}
std::string expression = fmt::format("@$curprocess.TTD.PrevMemoryAccess(\"{}\",0x{:x},0x{:x})", accessTypeStr, address, size);
LogInfo("Executing TTD PrevMemoryAccess query: %s", expression.c_str());
return ParseSingleTTDMemoryObject(expression, accessType);
}
catch (const std::exception& e)
{
LogError("Exception in GetTTDPrevMemoryAccess: %s", e.what());
return {false, TTDMemoryEvent()};
}
}
bool DbgEngTTDAdapter::QueryMemoryAccessByAddress(uint64_t startAddress, uint64_t endAddress, TTDMemoryAccessType accessType, std::vector<TTDMemoryEvent>& events)
{
if (!m_debugControl)
{
LogError("Debug control interface not available");
return false;
}
try
{
// Build the access type string for TTD memory queries - combine flags as needed
std::string accessTypeStr;
if (accessType & TTDMemoryRead) accessTypeStr += "r";
if (accessType & TTDMemoryWrite) accessTypeStr += "w";
if (accessType & TTDMemoryExecute) accessTypeStr += "e";
if (accessTypeStr.empty())
{
LogError("Invalid access type specified");
return false;
}
// Create the actual TTD memory query expression
std::string expression = fmt::format("@$cursession.TTD.Memory(0x{:x},0x{:x},\"{}\")", startAddress, endAddress, accessTypeStr);
LogInfo("Executing TTD memory query: %s", expression.c_str());
// Execute the query and parse results
if (!ParseTTDMemoryObjects(expression, accessType, events))
{
LogError("Failed to parse TTD memory objects from query");
return false;
}
LogInfo("Successfully retrieved %zu TTD memory events", events.size());
return true;
}
catch (const std::exception& e)
{
LogError("Exception in QueryMemoryAccessByAddress: %s", e.what());
return false;
}
}
bool DbgEngTTDAdapter::QueryMemoryAccessByAddressAndPositionRange(uint64_t startAddress, uint64_t endAddress, TTDMemoryAccessType accessType, TTDPosition startTime, TTDPosition endTime, std::vector<TTDPositionRangeIndexedMemoryEvent>& events)
{
if (!m_debugControl)
{
LogError("Debug control interface not available");
return false;
}
try
{
// Build the access type string for TTD memory queries - combine flags as needed
std::string accessTypeStr;
if (accessType & TTDMemoryRead) accessTypeStr += "r";
if (accessType & TTDMemoryWrite) accessTypeStr += "w";
if (accessType & TTDMemoryExecute) accessTypeStr += "e";
if (accessTypeStr.empty())
{
LogError("Invalid access type specified");
return false;
}
// Create the actual TTD memory query expression
std::string expression = fmt::format("@$cursession.TTD.MemoryForPositionRange(0x{:x},0x{:x},\"{}\",\"{:x}:{:x}\",\"{:x}:{:x}\")", startAddress, endAddress, accessTypeStr, startTime.sequence,startTime.step, endTime.sequence, endTime.step);
LogInfo("Executing TTD memory query: %s", expression.c_str());
// Execute the query and parse results
if (!ParseTTDPositionRangeIndexedMemoryObjects(expression, accessType, events))
{
LogError("Failed to parse TTD memory objects from query");
return false;
}
LogInfo("Successfully retrieved %zu TTD memory events", events.size());
return true;
}
catch (const std::exception& e)
{
LogError("Exception in QueryMemoryAccessByAddressAndPositionRange: %s", e.what());
return false;
}
}
void DbgEngTTDAdapter::GenerateDefaultAdapterSettings(BinaryView* data)
{
auto adapterSettings = GetAdapterSettings();
BNSettingsScope scope = SettingsResourceScope;
adapterSettings->Get<std::string>("common.inputFile", data, &scope);
if (scope != SettingsResourceScope)
adapterSettings->Set("common.inputFile", data->GetFile()->GetOriginalFilename(), data, SettingsResourceScope);
}
// Data model helper method implementation
std::string DbgEngTTDAdapter::EvaluateDataModelExpression(const std::string& expression)
{
if (!m_hostEvaluator)
{
LogError("Data model evaluator not available");
return "";
}
try
{
// Convert expression to wide string
std::wstring wExpression(expression.begin(), expression.end());
// Create context for evaluation
ComPtr<IDebugHostContext> hostContext;
if (FAILED(m_debugHost->GetCurrentContext(hostContext.GetAddressOf())))
{
LogError("Failed to get current debug host context");
return "";
}
// Evaluate the expression
ComPtr<IModelObject> result;
ComPtr<IKeyStore> metadata;
HRESULT hr = m_hostEvaluator->EvaluateExtendedExpression(
hostContext.Get(),
wExpression.c_str(),
nullptr, // No binding context
result.GetAddressOf(),
metadata.GetAddressOf()
);
if (FAILED(hr))
{
LogError("Failed to evaluate expression '%s': 0x%08x", expression.c_str(), hr);
return "";
}
// Convert result to string
if (result)
{
// Try to get intrinsic value directly
VARIANT vtValue;
VariantInit(&vtValue);
if (SUCCEEDED(result->GetIntrinsicValueAs(VT_BSTR, &vtValue)))
{
if (vtValue.vt == VT_BSTR && vtValue.bstrVal)
{
// Convert BSTR to std::string
int len = WideCharToMultiByte(CP_UTF8, 0, vtValue.bstrVal, -1, nullptr, 0, nullptr, nullptr);
if (len > 0)
{
std::string result_str(len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, vtValue.bstrVal, -1, &result_str[0], len, nullptr, nullptr);
VariantClear(&vtValue);
return result_str;
}
}
}
VariantClear(&vtValue);
// If we can't get intrinsic value, try to convert object to string representation
// This is a simplified approach - real implementation might need more sophisticated handling
LogInfo("Successfully evaluated expression '%s' (complex result)", expression.c_str());
return "complex_result"; // Placeholder
}
return "";
}
catch (const std::exception& e)
{
LogError("Exception in EvaluateDataModelExpression: %s", e.what());
return "";
}
}
// Implementation of TTD memory objects parsing
bool DbgEngTTDAdapter::ParseTTDMemoryObjects(const std::string& expression, TTDMemoryAccessType accessType, std::vector<TTDMemoryEvent>& events)
{
if (!m_hostEvaluator)
{
LogError("Data model evaluator not available");
return false;
}
try
{
// Convert expression to wide string
std::wstring wExpression(expression.begin(), expression.end());
// Create context for evaluation
ComPtr<IDebugHostContext> hostContext;
if (FAILED(m_debugHost->GetCurrentContext(hostContext.GetAddressOf())))
{
LogError("Failed to get current debug host context");
return false;
}
// Evaluate the TTD memory collection expression
ComPtr<IModelObject> result;
ComPtr<IKeyStore> metadata;
HRESULT hr = m_hostEvaluator->EvaluateExtendedExpression(
hostContext.Get(),
wExpression.c_str(),
nullptr, // No binding context
result.GetAddressOf(),
metadata.GetAddressOf()
);
if (FAILED(hr))
{
LogError("Failed to evaluate TTD memory expression '%s': 0x%08x", expression.c_str(), hr);
return false;
}
// Check if result is iterable (collection)
ComPtr<IIterableConcept> iterableConcept;
if (FAILED(result->GetConcept(__uuidof(IIterableConcept), &iterableConcept, nullptr)))
{
LogError("TTD memory result is not iterable");
return false;
}
// Get iterator
ComPtr<IModelIterator> iterator;
if (FAILED(iterableConcept->GetIterator(result.Get(), &iterator)))
{
LogError("Failed to get iterator for TTD memory objects");
return false;
}
// Iterate through memory objects
ComPtr<IModelObject> memoryObject;
ComPtr<IKeyStore> metadataKeyStore;
// Get the max results setting
auto adapterSettings = GetAdapterSettings();
BNSettingsScope scope = SettingsResourceScope;
auto maxResults = adapterSettings->Get<uint64_t>("ttd.maxMemoryQueryResults", GetData(), &scope);
uint64_t resultCounter = 0;
bool wasLimited = false;
while (SUCCEEDED(iterator->GetNext(&memoryObject, 0, nullptr, &metadataKeyStore)))
{
if (!memoryObject)
break;
// Check if we've reached the limit (0 means no limit)
if (maxResults > 0 && resultCounter >= maxResults)
{
wasLimited = true;
break;
}
TTDMemoryEvent event;
// Extract all fields from the memory object based on Microsoft documentation
// Get EventType (should be "MemoryAccess")
ComPtr<IModelObject> eventTypeObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"EventType", &eventTypeObj, nullptr)))
{
VARIANT vtEventType;
VariantInit(&vtEventType);
if (SUCCEEDED(eventTypeObj->GetIntrinsicValueAs(VT_BSTR, &vtEventType)) && vtEventType.bstrVal)
{
// Convert BSTR to std::string
_bstr_t bstr(vtEventType.bstrVal);
event.eventType = std::string(bstr);
}
VariantClear(&vtEventType);
}
// Get ThreadId
ComPtr<IModelObject> threadIdObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"ThreadId", &threadIdObj, nullptr)))
{
VARIANT vtThreadId;
VariantInit(&vtThreadId);
if (SUCCEEDED(threadIdObj->GetIntrinsicValueAs(VT_UI4, &vtThreadId)))
{
event.threadId = vtThreadId.ulVal;
}
VariantClear(&vtThreadId);
}
// Get UniqueThreadId
ComPtr<IModelObject> uniqueThreadIdObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"UniqueThreadId", &uniqueThreadIdObj, nullptr)))
{
VARIANT vtUniqueThreadId;
VariantInit(&vtUniqueThreadId);
if (SUCCEEDED(uniqueThreadIdObj->GetIntrinsicValueAs(VT_UI4, &vtUniqueThreadId)))
{
event.uniqueThreadId = vtUniqueThreadId.ulVal;
}
VariantClear(&vtUniqueThreadId);
}
// Get TimeStart for position
ComPtr<IModelObject> timeStartObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"TimeStart", &timeStartObj, nullptr)))
{
// TimeStart is typically a TTD position object with Sequence and Steps
ComPtr<IModelObject> sequenceObj, stepsObj;
if (SUCCEEDED(timeStartObj->GetKeyValue(L"Sequence", &sequenceObj, nullptr)))
{
VARIANT vtSequence;
VariantInit(&vtSequence);
if (SUCCEEDED(sequenceObj->GetIntrinsicValueAs(VT_UI8, &vtSequence)))
{
event.timeStart.sequence = vtSequence.ullVal;
}
VariantClear(&vtSequence);
}
if (SUCCEEDED(timeStartObj->GetKeyValue(L"Steps", &stepsObj, nullptr)))
{
VARIANT vtSteps;
VariantInit(&vtSteps);
if (SUCCEEDED(stepsObj->GetIntrinsicValueAs(VT_UI8, &vtSteps)))
{
event.timeStart.step = vtSteps.ullVal;
}
VariantClear(&vtSteps);
}
}
// Get TimeEnd for position
ComPtr<IModelObject> timeEndObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"TimeEnd", &timeEndObj, nullptr)))
{
// TimeEnd is typically a TTD position object with Sequence and Steps
ComPtr<IModelObject> sequenceObj, stepsObj;
if (SUCCEEDED(timeEndObj->GetKeyValue(L"Sequence", &sequenceObj, nullptr)))
{
VARIANT vtSequence;
VariantInit(&vtSequence);
if (SUCCEEDED(sequenceObj->GetIntrinsicValueAs(VT_UI8, &vtSequence)))
{
event.timeEnd.sequence = vtSequence.ullVal;
}
VariantClear(&vtSequence);
}
if (SUCCEEDED(timeEndObj->GetKeyValue(L"Steps", &stepsObj, nullptr)))
{
VARIANT vtSteps;
VariantInit(&vtSteps);
if (SUCCEEDED(stepsObj->GetIntrinsicValueAs(VT_UI8, &vtSteps)))
{
event.timeEnd.step = vtSteps.ullVal;
}
VariantClear(&vtSteps);
}
}
// Get Address
ComPtr<IModelObject> addressObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"Address", &addressObj, nullptr)))
{
VARIANT vtAddress;
VariantInit(&vtAddress);
if (SUCCEEDED(addressObj->GetIntrinsicValueAs(VT_UI8, &vtAddress)))
{
event.address = vtAddress.ullVal;
}
VariantClear(&vtAddress);
}
// Get MemoryAddress (may be same as Address)
ComPtr<IModelObject> memoryAddressObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"MemoryAddress", &memoryAddressObj, nullptr)))
{
VARIANT vtMemoryAddress;
VariantInit(&vtMemoryAddress);
if (SUCCEEDED(memoryAddressObj->GetIntrinsicValueAs(VT_UI8, &vtMemoryAddress)))
{
event.memoryAddress = vtMemoryAddress.ullVal;
}
VariantClear(&vtMemoryAddress);
}
else
{
// If MemoryAddress is not available, use Address as fallback
event.memoryAddress = event.address;
}
// Get Size
ComPtr<IModelObject> sizeObj;
if (SUCCEEDED(memoryObject->GetKeyValue(L"Size", &sizeObj, nullptr)))
{
VARIANT vtSize;
VariantInit(&vtSize);
if (SUCCEEDED(sizeObj->GetIntrinsicValueAs(VT_UI8, &vtSize)))