-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathdbgengadapter.cpp
More file actions
2082 lines (1750 loc) · 57.9 KB
/
dbgengadapter.cpp
File metadata and controls
2082 lines (1750 loc) · 57.9 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
/*
Copyright 2020-2025 Vector 35 Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <thread>
#include <chrono>
#include <algorithm>
#include <string>
#include <binaryninjacore.h>
#include <binaryninjaapi.h>
#include <lowlevelilinstruction.h>
#include <mediumlevelilinstruction.h>
#include <highlevelilinstruction.h>
#include <memory>
#include <filesystem>
#ifdef _WIN32
#include <shellapi.h>
#endif
#include "dbgengadapter.h"
#include "../../cli/log.h"
#include "../debuggerevent.h"
#include "shlobj_core.h"
#pragma warning(push)
// warning C40005, macro redefinition
#pragma warning(disable : 5)
#include "ntstatus.h"
#pragma warning(pop)
using namespace BinaryNinjaDebugger;
using namespace std;
static bool IsValidDbgEngPaths(const std::string& path)
{
if (path.empty())
return false;
auto enginePath = filesystem::path(path);
if (!filesystem::exists(enginePath))
return false;
if (!filesystem::exists(enginePath / "dbgeng.dll"))
return false;
if (!filesystem::exists(enginePath / "dbghelp.dll"))
return false;
if (!filesystem::exists(enginePath / "dbgmodel.dll"))
return false;
if (!filesystem::exists(enginePath / "dbgcore.dll"))
return false;
if (!filesystem::exists(enginePath / "dbgsrv.exe"))
return false;
return true;
}
std::string DbgEngAdapter::GetDbgEngPath(const std::string& arch)
{
std::string path;
if (arch == "amd64")
path = Settings::Instance()->Get<string>("debugger.x64dbgEngPath");
else
path = Settings::Instance()->Get<string>("debugger.x86dbgEngPath");
if (!path.empty())
{
// If the user has specified the path in the setting, then check it for validity. If it is valid, then use it;
// if it is invalid, fail the operation -- do not fallback to the default one
if (IsValidDbgEngPaths(path))
return path;
else
return "";
}
std::string pluginRoot;
if (getenv("BN_STANDALONE_DEBUGGER") != nullptr)
pluginRoot = GetUserPluginDirectory();
else
pluginRoot = GetBundledPluginDirectory();
// If the user does not specify a path (the default case), find the one from the plugins/dbgeng/arch
auto debuggerRoot = filesystem::path(pluginRoot) / "dbgeng" / arch;
if (IsValidDbgEngPaths(debuggerRoot.string()))
return debuggerRoot.string();
return "";
}
static bool LoadOneDLL(const string& path, const string& name, bool strictCheckPath = true, bool forceUnload = true)
{
auto handle = GetModuleHandleA(name.c_str());
if (handle)
{
LogDebug("Module %s is already loaded before the debugger tries to load it, this is suspicious", name.c_str());
if (!strictCheckPath)
// The module is already loaded and we do not wish to validate its path, treat it as a success
return true;
char actualPath[MAX_PATH];
if (!GetModuleFileNameA(handle, actualPath, MAX_PATH))
{
LogWarn("Failed to get the path of the loaded %s, error: %lu", name.c_str(), GetLastError());
return false;
}
string path1 = actualPath;
std::transform(path1.begin(), path1.end(), path1.begin(), ::toupper);
string path2 = path + '\\' + name;
std::transform(path2.begin(), path2.end(), path2.begin(), ::toupper);
if (path1 == path2)
// two paths match, ok
return true;
LogWarn("%s is loaded from %s, but we expect it from %s", name.c_str(), actualPath, path.c_str());
if (!forceUnload)
return false;
size_t unloadMaxTries = 100;
bool unloaded = false;
for (size_t i = 0; i < unloadMaxTries; i++)
{
FreeLibrary(handle);
handle = GetModuleHandleA(name.c_str());
if (handle == NULL)
{
unloaded = true;
break;
}
}
if (!unloaded)
{
LogDebug("Failed to unload module %s", name.c_str());
return false;
}
else
{
LogDebug("Module %s has been unloaded", name.c_str());
}
}
auto dllFullPath = path + '\\' + name;
handle = LoadLibraryA(dllFullPath.c_str());
if (handle == nullptr)
{
LogWarn("Failed to load %s, error: %lu", dllFullPath.c_str(), GetLastError());
return false;
}
return true;
}
bool DbgEngAdapter::LoadDngEngLibraries()
{
auto enginePath = GetDbgEngPath("amd64");
if (enginePath.empty())
{
LogWarn("The debugger cannot find the path for the DbgEng DLLs. "
"If you have set debugger.x64dbgEngPath, check if it valid");
return false;
}
LogDebug("DbgEng libraries in path %s", enginePath.c_str());
auto settings = Settings::Instance();
auto strictCheckPath = settings->Get<bool>("debugger.checkDbgEngDLLPath");
auto forceUnload = settings->Get<bool>("debugger.tryUnloadWrongDbgEngDLL");
if (!LoadOneDLL(enginePath, "dbghelp.dll", strictCheckPath, forceUnload))
return false;
if (!LoadOneDLL(enginePath, "dbgcore.dll", strictCheckPath, forceUnload))
return false;
if (!LoadOneDLL(enginePath, "dbgmodel.dll", strictCheckPath, forceUnload))
return false;
if (!LoadOneDLL(enginePath, "dbgeng.dll", strictCheckPath, forceUnload))
return false;
return true;
}
std::string DbgEngAdapter::GenerateRandomPipeName()
{
const std::string chars = "abcdefghijklmnopqrstuvwxyz1234567890";
constexpr size_t length = 16;
srand(time(NULL));
std::string result;
result.resize(length);
for (size_t i = 0; i < length; i++)
result[i] = chars[rand() % chars.length()];
return result;
}
bool DbgEngAdapter::LaunchDbgSrv(const std::string& commandLine)
{
// Check if we should run as administrator
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
bool runAsAdmin = adapterSettings->Get<bool>("common.runAsAdministrator", data, &scope);
if (runAsAdmin)
{
// Parse command line to extract executable path and arguments
// Command line format: "path\to\dbgsrv.exe" -t arguments
std::string exePath;
std::string args;
if (commandLine.size() > 0 && commandLine[0] == '"')
{
// Find the closing quote
size_t endQuote = commandLine.find('"', 1);
if (endQuote != std::string::npos)
{
exePath = commandLine.substr(1, endQuote - 1);
if (endQuote + 1 < commandLine.size())
{
// Skip the closing quote and any leading space
size_t argsStart = endQuote + 1;
if (argsStart < commandLine.size() && commandLine[argsStart] == ' ')
argsStart++;
if (argsStart < commandLine.size())
args = commandLine.substr(argsStart);
}
}
}
else
{
// No quotes, split on first space
size_t spacePos = commandLine.find(' ');
if (spacePos != std::string::npos)
{
exePath = commandLine.substr(0, spacePos);
args = commandLine.substr(spacePos + 1);
}
else
{
exePath = commandLine;
}
}
if (exePath.empty())
{
LogWarn("Failed to parse executable path from command line: %s", commandLine.c_str());
return false;
}
// Use ShellExecuteEx with "runas" verb to launch with elevated privileges
SHELLEXECUTEINFOA sei = { 0 };
sei.cbSize = sizeof(sei);
sei.fMask = 0; // No special flags needed
sei.lpVerb = "runas";
sei.lpFile = exePath.c_str();
sei.lpParameters = args.empty() ? NULL : args.c_str();
sei.nShow = SW_HIDE;
if (!ShellExecuteExA(&sei))
{
DWORD error = GetLastError();
LogWarn("Failed to launch dbgsrv.exe with administrator privileges. Error: %lu", error);
return false;
}
m_dbgSrvLaunchedByAdapter = true;
return true;
}
else
{
// Use original CreateProcess method
STARTUPINFOA si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
memset(&pi, 0, sizeof(pi));
if (!CreateProcessA(NULL, (LPSTR)commandLine.c_str(), NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
{
return false;
}
m_dbgSrvLaunchedByAdapter = true;
return true;
}
}
bool DbgEngAdapter::ConnectToDebugServerInternal(const std::string& connectionString)
{
auto handle = GetModuleHandleA("dbgeng.dll");
if (handle == nullptr)
{
LogWarn("Failed to get module handle for dbgeng.dll");
return false;
}
// HRESULT DebugCreate(
// [in] REFIID InterfaceId,
// [out] PVOID *Interface
// );
typedef HRESULT(__stdcall * pfunDebugCreate)(REFIID, PVOID*);
auto DebugCreate = (pfunDebugCreate)GetProcAddress(handle, "DebugCreate");
if (DebugCreate == nullptr)
{
LogWarn("Failed to get the address of DebugCreate function");
return false;
}
if (const auto result = DebugCreate(__uuidof(IDebugClient7), reinterpret_cast<void**>(&this->m_debugClient));
result != S_OK)
{
LogWarn("Failed to create IDebugClient7");
return false;
}
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);
constexpr size_t CONNECTION_MAX_TRY = 300;
for (size_t i = 0; i < CONNECTION_MAX_TRY; i++)
{
auto result = m_debugClient->ConnectProcessServer(connectionString.c_str(), &m_server);
if (result == S_OK)
{
m_connectedToDebugServer = true;
return true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
LogWarn("ConnectToDebugServerInternal timeout");
return false;
}
bool DbgEngAdapter::Start()
{
if (this->m_dbgengInitialized)
{
// Debugger is already started, return success
return true;
}
if (!m_connectedToDebugServer)
{
auto pipeName = GenerateRandomPipeName();
auto connectString = fmt::format("npipe:pipe={},Server=localhost", pipeName);
auto arch = m_defaultArchitecture == "x86" ? "x86" : "amd64";
auto enginePath = GetDbgEngPath(arch);
if (enginePath.empty())
return false;
auto dbgsrvCommandLine = fmt::format("\"{}\\dbgsrv.exe\" -t {}", enginePath, connectString);
if (!LaunchDbgSrv(dbgsrvCommandLine))
{
LogWarn("Command %s failed", dbgsrvCommandLine.c_str());
return false;
}
if (!ConnectToDebugServerInternal(connectString))
{
LogWarn("Failed to connect process server");
return false;
}
}
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 DbgEngAdapter::Reset()
{
std::unique_lock lock(m_engineLoopMutex);
m_aboutToBeKilled = false;
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.
if (m_dbgSrvLaunchedByAdapter)
{
SAFE_RELEASE(this->m_debugControl);
SAFE_RELEASE(this->m_debugDataSpaces);
SAFE_RELEASE(this->m_debugRegisters);
SAFE_RELEASE(this->m_debugSymbols);
SAFE_RELEASE(this->m_debugSystemObjects);
if (this->m_debugClient)
{
this->m_debugClient->EndSession(DEBUG_END_PASSIVE);
this->m_debugClient->EndProcessServer(m_server);
m_dbgSrvLaunchedByAdapter = false;
m_connectedToDebugServer = false;
m_server = 0;
}
SAFE_RELEASE(this->m_debugClient);
}
this->m_dbgengInitialized = false;
this->m_activelyDebugging = false;
}
DbgEngAdapter::DbgEngAdapter(BinaryView* data) : DebugAdapter(data)
{
auto metadata = data->QueryMetadata("PDB_FILENAME");
if (metadata && metadata->IsString())
m_pdbFileName = metadata->GetString();
GenerateDefaultAdapterSettings(data);
}
DbgEngAdapter::~DbgEngAdapter()
{
}
bool DbgEngAdapter::Init()
{
return true;
}
bool DbgEngAdapter::Execute(const std::string& path, const LaunchConfigurations& configs)
{
return this->ExecuteWithArgs(path, "", "", {});
}
bool DbgEngAdapter::ExecuteWithArgs(const std::string& path, const std::string& args, const std::string& workingDir,
const LaunchConfigurations& configs)
{
std::atomic_bool ret = false;
std::atomic_bool finished = false;
// Doing the operation on a different thread ensures the same thread starts the session and runs EngineLoop().
// This is required by DngEng. Although things sometimes work even if it is violated, it can fail randomly.
std::thread([=, &ret, &finished]() {
ret = ExecuteWithArgsInternal(path, args, workingDir, configs);
finished = true;
if (ret)
EngineLoop();
}).detach();
while (!finished)
{}
return ret;
}
bool DbgEngAdapter::ExecuteWithArgsInternal(const std::string& path, const std::string& args,
const std::string& workingDir, const LaunchConfigurations& configs)
{
std::unique_lock lock(m_engineLoopMutex);
// If we're actively debugging, fail instead of resetting to prevent crashes
if (this->m_activelyDebugging)
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("Cannot launch while actively debugging another target");
event.data.errorData.shortError = fmt::format("Already debugging");
PostDebuggerEvent(event);
return false;
}
m_aboutToBeKilled = false;
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
auto executablePath = adapterSettings->Get<std::string>("launch.executablePath", data, &scope);
scope = SettingsResourceScope;
auto workingDirectory = adapterSettings->Get<std::string>("launch.workingDirectory", data, &scope);
scope = SettingsResourceScope;
auto commandLineArgs = adapterSettings->Get<std::string>("launch.commandLineArguments", data, &scope);
scope = SettingsResourceScope;
auto inputFile = adapterSettings->Get<std::string>("common.inputFile", data, &scope);
scope = SettingsResourceScope;
auto envVariables = adapterSettings->Get<vector<string>>("launch.environmentVariables", data, &scope);
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;
}
/* TODO: parse args better */
std::string path_with_args {executablePath};
if (!commandLineArgs.empty())
{
path_with_args.append(" ");
path_with_args.append(commandLineArgs);
}
DEBUG_CREATE_PROCESS_OPTIONS options;
options.CreateFlags = DEBUG_ONLY_THIS_PROCESS;
options.EngCreateFlags = 0;
options.VerifierFlags = 0;
options.Reserved = 0;
// CreateProcess2() is picky about the InitialDirectory parameter. It is OK to send in a NULL, but if a non-NULL
// string which is empty gets passed in, the call fails.
char* directory = _strdup(workingDirectory.c_str());
if (workingDirectory.empty())
directory = nullptr;
char* env = nullptr;
std::string envWithNull{};
if (!envVariables.empty())
{
for (const auto& var : envVariables)
{
envWithNull += var;
envWithNull += '\0';
}
envWithNull += '\0';
env = (char*)malloc(envWithNull.length());
memcpy(env, envWithNull.c_str(), envWithNull.length());
}
if (const auto result = this->m_debugClient->CreateProcess2(m_server, const_cast<char*>(path_with_args.c_str()),
&options, sizeof(DEBUG_CREATE_PROCESS_OPTIONS), directory, env);
result != S_OK)
{
this->Reset();
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("CreateProcess2 failed: 0x{:x}", result);
event.data.errorData.shortError = fmt::format("CreateProcess2 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();
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;
}
}
// Mark that we're now actively debugging a target
this->m_activelyDebugging = true;
return true;
}
void DbgEngAdapter::EngineLoop()
{
// When the user rapidly restarts the target, there is a race condition that could lead to a crash:
// 1) The target is killed, and the EngineLoop is about to exit, but not yet
// 2) The restart code tries to restart the target, which calls ExecuteWithArgsInternal() -> Reset() -> set
// m_debugControl to nullptr
// 3) Crash in EngineLoop
// This lock prevents Reset() from proceeding until the EngineLoop() actually exits
std::unique_lock lock(m_engineLoopMutex);
auto settings = Settings::Instance();
bool outputStateOnStop = settings->Get<bool>("debugger.dbgEngOutputStateOnStop");
m_lastExecutionStatus = DEBUG_STATUS_NO_DEBUGGEE;
bool finished = false;
while (true)
{
if (finished)
break;
//Wait();
unsigned long execution_status {};
while (true)
{
if (this->m_debugControl->GetExecutionStatus(&execution_status) != S_OK)
{}
if (execution_status == DEBUG_STATUS_BREAK)
{
if (m_lastExecutionStatus != DEBUG_STATUS_BREAK)
{
if (outputStateOnStop)
{
// m_debugRegisters->OutputRegisters(DEBUG_OUTCTL_THIS_CLIENT, DEBUG_REGISTERS_DEFAULT);
m_debugControl->OutputCurrentState(DEBUG_OUTCTL_THIS_CLIENT, DEBUG_CURRENT_DEFAULT);
}
DebuggerEvent event;
event.type = AdapterStoppedEventType;
event.data.targetStoppedData.reason = StopReason();
PostDebuggerEvent(event);
}
// This is NOT actually dispatching callback, since the callbacks are already dispatched in
// WaitForEvent(). The real purpose of this call is to wait until the UI/API initiates another control
// operation, which then calls ExitDispatch(), which causes the DispatchCallbacks() to return.
m_debugClient->DispatchCallbacks(INFINITE);
}
// TODO: add step branch and step backs
else if ((execution_status == DEBUG_STATUS_GO) || (execution_status == DEBUG_STATUS_STEP_INTO)
|| (execution_status == DEBUG_STATUS_STEP_OVER) || (execution_status == DEBUG_STATUS_GO_HANDLED)
|| (execution_status == DEBUG_STATUS_STEP_BRANCH)
|| (execution_status == DEBUG_STATUS_GO_NOT_HANDLED) || (execution_status == DEBUG_STATUS_REVERSE_GO)
|| (execution_status == DEBUG_STATUS_REVERSE_STEP_OVER)
|| (execution_status == DEBUG_STATUS_REVERSE_STEP_INTO)
|| (execution_status == DEBUG_STATUS_REVERSE_STEP_BRANCH))
{
DebuggerEvent dbgevt;
if ((execution_status == DEBUG_STATUS_GO) || (execution_status == DEBUG_STATUS_REVERSE_GO)
|| ((execution_status == DEBUG_STATUS_GO_HANDLED))
|| (execution_status == DEBUG_STATUS_GO_NOT_HANDLED))
{
dbgevt.type = ResumeEventType;
PostDebuggerEvent(dbgevt);
}
else if ((execution_status == DEBUG_STATUS_STEP_INTO) || (execution_status == DEBUG_STATUS_STEP_OVER)
|| (execution_status == DEBUG_STATUS_STEP_BRANCH)
|| (execution_status == DEBUG_STATUS_REVERSE_STEP_OVER)
|| (execution_status == DEBUG_STATUS_REVERSE_STEP_INTO)
|| (execution_status == DEBUG_STATUS_REVERSE_STEP_BRANCH))
{
dbgevt.type = StepIntoEventType;
PostDebuggerEvent(dbgevt);
}
break;
}
else if (execution_status == DEBUG_STATUS_NO_DEBUGGEE)
{
finished = true;
DebuggerEvent event;
event.type = TargetExitedEventType;
event.data.exitData.exitCode = ExitCode();
PostDebuggerEvent(event);
Reset();
break;
}
m_lastExecutionStatus = execution_status;
}
m_lastExecutionStatus = execution_status;
if (finished)
break;
Wait();
}
m_lastExecutionStatus = DEBUG_STATUS_NO_DEBUGGEE;
}
bool DbgEngAdapter::AttachInternal(std::uint32_t pid)
{
std::unique_lock lock(m_engineLoopMutex);
// If we're actively debugging, fail instead of resetting to prevent crashes
if (this->m_activelyDebugging)
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("Cannot attach while actively debugging another target");
event.data.errorData.shortError = fmt::format("Already debugging");
PostDebuggerEvent(event);
return false;
}
m_aboutToBeKilled = false;
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
auto attachPID = adapterSettings->Get<uint64_t>("attach.pid", data, &scope);
this->Start();
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->AttachProcess(m_server, attachPID, 0); result != S_OK)
{
this->Reset();
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("AttachProcess failed: 0x{:x}", result);
event.data.errorData.shortError = fmt::format("AttachProcess failed: 0x{:x}", result);
PostDebuggerEvent(event);
return false;
}
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);
}
ApplyBreakpoints();
// Mark that we're now actively debugging a target
this->m_activelyDebugging = true;
return true;
}
bool DbgEngAdapter::Attach(std::uint32_t pid)
{
std::atomic_bool ret = false;
std::atomic_bool finished = false;
// Doing the operation on a different thread ensures the same thread starts the session and runs EngineLoop().
// This is required by DngEng. Although things sometimes work even if it is violated, it can fail randomly.
std::thread([=, &ret, &finished]() {
ret = AttachInternal(pid);
finished = true;
if (ret)
EngineLoop();
}).detach();
while (!finished)
{}
return ret;
}
bool DbgEngAdapter::Connect(const std::string& server, std::uint32_t port)
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.error = fmt::format("Connect() is not implemented in DbgEng");
event.data.errorData.shortError = fmt::format("Connect() is not implemented in DbgEng");
PostDebuggerEvent(event);
return false;
}
bool DbgEngAdapter::ConnectToDebugServer(const std::string& server, std::uint32_t port)
{
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
auto ipAddress = adapterSettings->Get<std::string>("debugServer.ipAddress", data, &scope);
scope = SettingsResourceScope;
auto serverPort = adapterSettings->Get<uint64_t>("debugServer.port", data, &scope);
std::string connectionString = fmt::format("tcp:port={}, Server={}", serverPort, ipAddress);
return ConnectToDebugServerInternal(connectionString);
}
bool DbgEngAdapter::DisconnectDebugServer()
{
if (!m_connectedToDebugServer)
return true;
auto ret = m_debugClient->DisconnectProcessServer(m_server);
m_connectedToDebugServer = false;
m_server = 0;
return ret == S_OK;
}
bool DbgEngAdapter::Detach()
{
m_aboutToBeKilled = true;
m_lastOperationIsStepInto = false;
if (!this->m_debugClient)
return false;
if (this->m_debugClient->DetachProcesses() != S_OK)
return false;
m_debugClient->ExitDispatch(reinterpret_cast<PDEBUG_CLIENT>(m_debugClient));
return true;
}
bool DbgEngAdapter::Quit()
{
m_aboutToBeKilled = true;
m_lastOperationIsStepInto = false;
if (!this->m_debugClient)
return false;
if (this->m_debugClient->TerminateProcesses() != S_OK)
return false;
m_debugClient->ExitDispatch(reinterpret_cast<PDEBUG_CLIENT>(m_debugClient));
return true;
}
std::vector<DebugProcess> DbgEngAdapter::GetProcessList()
{
// we need to start dbgserver in order to get process list
if (!m_dbgengInitialized)
{
if (!Start())
return {};
}
ULONG Count = 0;
if (m_debugClient->GetRunningProcessSystemIds(m_server, 0, 0, &Count) != S_OK)
{
LogError("Failed to get system process count.");
return {};
}
auto procIds = std::make_unique<unsigned long[]>(Count);
if (m_debugClient->GetRunningProcessSystemIds(m_server, procIds.get(), Count, &Count) != S_OK)
{
LogError("Failed to get system process ids.");
return {};
}
std::vector<DebugProcess> debug_processes {};
for (int i = 0; i < Count; i++)
{
char processName[MAX_PATH];
ZeroMemory(processName, MAX_PATH);
if (m_debugClient->GetRunningProcessDescription(
m_server,
procIds[i],
DEBUG_PROC_DESC_DEFAULT,
processName,
sizeof(processName),
NULL,
NULL,
0,
NULL) != S_OK)
{
strcpy_s(processName, MAX_PATH, "<could not get process name>");
}
debug_processes.emplace_back(procIds[i], processName);
}
return debug_processes;
}
std::vector<DebugThread> DbgEngAdapter::GetThreadList()
{
if (!m_debugSystemObjects)
return {};
unsigned long number_threads {};
if (this->m_debugSystemObjects->GetNumberThreads(&number_threads) != S_OK)
return {};
auto tids = std::make_unique<unsigned long[]>(number_threads);
auto sysids = std::make_unique<unsigned long[]>(number_threads);
if (this->m_debugSystemObjects->GetThreadIdsByIndex(0, number_threads, tids.get(), sysids.get()) != S_OK)
return {};
std::vector<DebugThread> debug_threads {};
DebugThread activeThead = GetActiveThread();
for (std::size_t index {}; index < number_threads; index++)
{
SetActiveThreadId(tids[index]);
uint64_t pc = GetInstructionOffset();
debug_threads.emplace_back(tids[index], pc);
}
SetActiveThread(activeThead);
return debug_threads;
}
// Note, on Windows, we use engine thread ID, but on Linux/macOS, we use system thread ID.
// System thread ID is also available on Windows, We should later add a new field to the DebugThread struct
DebugThread DbgEngAdapter::GetActiveThread() const
{
// Temporary hacky to get the code compile without changing everything
if (!m_debugRegisters)
return DebugThread {};
return DebugThread(this->GetActiveThreadId(), ((DbgEngAdapter*)this)->GetInstructionOffset());
}
std::uint32_t DbgEngAdapter::GetActiveThreadId() const
{
unsigned long current_tid {};
if (this->m_debugSystemObjects->GetCurrentThreadId(¤t_tid) != S_OK)
return {};
return current_tid;
}
bool DbgEngAdapter::SetActiveThread(const DebugThread& thread)
{
return this->SetActiveThreadId(thread.m_tid);
}
bool DbgEngAdapter::SetActiveThreadId(std::uint32_t tid)
{
if (this->m_debugSystemObjects->SetCurrentThreadId(tid) != S_OK)
return false;
return true;
}
bool DbgEngAdapter::SuspendThread(std::uint32_t tid)
{
std::string suspendCmd = fmt::format("~{}f", tid);
InvokeBackendCommand(suspendCmd);
return true;
}
bool DbgEngAdapter::ResumeThread(std::uint32_t tid)
{
std::string resumeCmd = fmt::format("~{}u", tid);
InvokeBackendCommand(resumeCmd);
return true;
}
DebugBreakpoint DbgEngAdapter::AddBreakpoint(const std::uintptr_t address, unsigned long breakpoint_flags)
{
// Handle hardware breakpoint types
if (breakpoint_flags != SoftwareBreakpoint)