-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathlldbadapter.cpp
More file actions
2433 lines (2092 loc) · 71.1 KB
/
lldbadapter.cpp
File metadata and controls
2433 lines (2092 loc) · 71.1 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-2026 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 <inttypes.h>
#include <filesystem>
#include "lldbadapter.h"
#include "thread"
#include "../../vendor/intx/intx.hpp"
#include "../debuggercontroller.h"
using namespace lldb;
using namespace BinaryNinjaDebugger;
using namespace std;
static std::string lldbArchNameForBinaryNinjaArchName(std::string name)
{
if (name == "x86")
return "x86";
if (name == "x86_64")
return "x86_64";
else if (name == "aarch64")
return "arm64";
else if (name == "armv7")
return "arm";
else if (name == "ppc")
return "powerpc";
else if (name == "ppc64")
return "powerpc64";
return "";
}
LldbAdapter::LldbAdapter(BinaryView* data) : DebugAdapter(data)
{
m_targetActive = false;
SBDebugger::Initialize();
m_debugger = SBDebugger::Create();
if (!m_debugger.IsValid())
LogWarn("Invalid debugger");
m_isElFWithoutDynamicLoader = IsELFWithoutDynamicLoader(data);
// Set auto-confirm to true so operations that ask for confirmation will proceed automatically.
// Otherwise, the confirmation prompt will be sent to the terminal that BN is launched from, which is a very
// confusing behavior.
InvokeBackendCommand("settings set auto-confirm true");
m_debugger.SetAsync(false);
GenerateDefaultAdapterSettings(data);
}
LldbAdapter::~LldbAdapter()
{
m_process.Destroy();
SBDebugger::Destroy(m_debugger);
}
LldbAdapterType::LldbAdapterType() : DebugAdapterType("LLDB") {}
DebugAdapter* LldbAdapterType::Create(BinaryNinja::BinaryView* data)
{
#ifdef WIN32
// Since we have applied delay load on liblldb.dll, we must explicitly specify the directory the liblldb.dll is in
// and load it by ourselves. This is because the delay load only search for the directory that the binaryninja.exe
// is in, and it does not search for the directory where the user/default plugin is in, which is exactly where
// the liblldb.dll is located.
// As a note, the reason for us to apply delay load on liblldb.dll is that if we load it early, it will also load
// the system's default dbgeng dlls, which does not work for our dbgeng adapter.
std::string lldbDir;
if (getenv("BN_STANDALONE_DEBUGGER") != nullptr)
lldbDir = GetUserPluginDirectory();
else
lldbDir = GetBundledPluginDirectory();
auto lldbPath = lldbDir + '\\' + "liblldb.dll";
auto module = LoadLibraryA(lldbPath.c_str());
if (module == NULL)
throw std::runtime_error(std::string("fail to load ") + lldbPath);
#endif
// TODO: someone should free this.
return new LldbAdapter(data);
}
bool LldbAdapterType::IsValidForData(BinaryNinja::BinaryView* data)
{
// it does not matter what the BinaryViewType is -- as long as we can connect to it, it is fine.
return true;
}
bool LldbAdapterType::CanConnect(BinaryNinja::BinaryView* data)
{
// We can connect to remote lldb on any host system
// TODO: we need to create a new API to get available adapters, rather the
// DebugAdapterType::GetAvailableAdapters(), which returns true when either the CanConnect() and CanExecute()
// returns true.
return true;
}
bool LldbAdapterType::CanExecute(BinaryNinja::BinaryView* data)
{
if (data->GetTypeName() == "PE")
return false;
return true;
}
Ref<Settings> LldbAdapterType::RegisterAdapterSettings()
{
Ref<Settings> settings = Settings::Instance("LLDBAdapterSettings");
settings->SetResourceId("lldb_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.executablePath",
R"({
"title" : "Executable Path",
"type" : "string",
"default" : "",
"description" : "Path of the executable to launch.",
"readOnly" : false,
"uiSelectionAction" : "file"
})");
settings->RegisterSetting("launch.workingDirectory",
R"({
"title" : "Working Directory",
"type" : "string",
"default" : "",
"description" : "Working directory to launch the target in.",
"readOnly" : false,
"uiSelectionAction" : "directory"
})");
settings->RegisterSetting("launch.commandLineArguments",
R"({
"title" : "Command Line Arguments",
"type" : "string",
"default" : "",
"description" : "Command line arguments to pass to the target",
"readOnly" : false
})");
settings->RegisterSetting("launch.terminalEmulator",
R"({
"title" : "Run in Separate Terminal",
"type" : "boolean",
"default" : false,
"description" : "Execute the target in a separate terminal. The user can then interact with the process in that terminal",
"readOnly" : false
})");
settings->RegisterSetting("launch.disableAslr",
R"({
"title" : "Disable ASLR",
"type" : "boolean",
"default" : true,
"description" : "Disable ASLR during launch.",
"readOnly" : false
})");
settings->RegisterSetting("launch.redirectStdin",
R"({
"title" : "Redirect stdin",
"type" : "string",
"default" : "",
"description" : "Redirect stdin from the selected file.",
"readOnly" : false,
"uiSelectionAction" : "file"
})");
settings->RegisterSetting("launch.redirectStdout",
R"({
"title" : "Redirect stdout",
"type" : "string",
"default" : "",
"description" : "Redirect stdout to the selected file.",
"readOnly" : false,
"uiSelectionAction" : "file"
})");
settings->RegisterSetting("launch.redirectStderr",
R"({
"title" : "Redirect stderr",
"type" : "string",
"default" : "",
"description" : "Redirect stderr to the selected file.",
"readOnly" : false,
"uiSelectionAction" : "file"
})");
settings->RegisterSetting("launch.environmentVariables",
R"({
"title" : "Environment Variables",
"type" : "array",
"sorted" : false,
"default" : [],
"description" : "Environment Variables for the target. Provide the list of in the form of [\"var1=val1\", \"var2=val2\"]",
"readOnly" : false
})");
settings->RegisterSetting("connect.ipAddress",
R"({
"title" : "IP Address",
"type" : "string",
"default" : "127.0.0.1",
"description" : "IP address of the debug stub to connect to",
"readOnly" : false
})");
settings->RegisterSetting("connect.port",
R"({
"title" : "Port",
"type" : "number",
"default" : 31337,
"minValue" : 0,
"maxValue" : 65535,
"description" : "Port of the debug stub to connect to",
"readOnly" : false
})");
settings->RegisterSetting("connect.processPlugin",
R"({
"title" : "Process Plugin",
"type" : "string",
"enum" : ["debugserver/lldb", "gdb-remote"],
"enumDescriptions" : [
"The debug stub is lldb-server or debugserver",
"The debug stub is gdb-remote"],
"default" : "gdb-remote",
"description" : "Process plugin to use to connect to the debug stub",
"readOnly" : false
})");
settings->RegisterSetting("debugServer.ipAddress",
R"({
"title" : "IP Address",
"type" : "string",
"default" : "127.0.0.1",
"description" : "IP address of the debug server to connect to",
"readOnly" : false
})");
settings->RegisterSetting("debugServer.port",
R"({
"title" : "Port",
"type" : "number",
"default" : 31337,
"minValue" : 0,
"maxValue" : 65535,
"description" : "Port of the debug server to connect to",
"readOnly" : false
})");
settings->RegisterSetting("debugServer.platform",
R"({
"title" : "Platform",
"type" : "string",
"enum" : [""],
"description" : "LLDB platform plugin to use to connect to the debug server",
"readOnly" : false
})");
settings->RegisterSetting("attach.pid",
R"({
"title" : "PID to attach to",
"type" : "number",
"default" : 0,
"minValue" : 0,
"maxValue" : 4294967295,
"description" : "PID of the process to attach to",
"readOnly" : false
})");
settings->RegisterSetting("common.followForkMode",
R"({
"title": "Follow Fork Mode",
"type": "string",
"enum": ["default", "parent", "child"],
"default": "default",
"description": "Determines which process to follow when a fork occurs",
"readOnly": false
})");
settings->RegisterSetting("common.initialLLDBCommand",
R"({
"title": "Initial LLDB Commands",
"type": "array",
"sorted": false,
"default": [],
"description": "Specifies LLDB commands to execute immediately after launching/attaching/connecting to the target",
"readOnly": false
})");
settings->RegisterSetting("debugServer.disableAutoInstall",
R"({
"title": "Disable Auto Install",
"type": "boolean",
"default": true,
"description": "Disable automatic binary upload during remote debugging. This prevents LLDB from deleting and re-uploading the binary when debugging on localhost or when the binary already exists on the remote system.",
"readOnly": false
})");
return settings;
}
Ref<Settings> LldbAdapterType::GetAdapterSettings()
{
static Ref<Settings> settings = LldbAdapterType::RegisterAdapterSettings();
return settings;
}
void BinaryNinjaDebugger::InitLldbAdapterType()
{
static LldbAdapterType lldbType;
DebugAdapterType::Register(&lldbType);
}
void LldbAdapter::ApplyBreakpoints()
{
// Apply pending software breakpoints immediately - these work fine before process starts
for (const auto& bp : m_pendingBreakpoints)
{
AddBreakpoint(bp);
}
// Clear the pending breakpoint list so that when the adapter launch/attach/connect to the target for the next time,
// it always gets a clean list of breakpoints from the controller.
m_pendingBreakpoints.clear();
// DEFER hardware breakpoints instead of applying now
//
// WHY: LLDB has a known issue where hardware breakpoints set before the process starts often fail to work.
// Hardware breakpoints require the process to be running and stopped at least once so that LLDB can
// properly register them with the CPU's hardware debug registers.
//
// WHEN THIS WORKS:
// - Launch scenarios: Process will hit entry point or first instruction, we apply HW BP then
// - Attach scenarios: Process is already running, we apply on first break
// - Connect scenarios: Remote process is running, we apply on first break
//
// WHEN THIS DOESN'T WORK:
// - If the code you want to break on executes BEFORE the first stop (very rare, usually just entry point)
// - If LLDB is fixed in future versions and this workaround becomes unnecessary overhead
// - Non-stop mode debugging (not currently supported anyway)
//
// ALTERNATIVE APPROACHES CONSIDERED:
// - Applying immediately: Doesn't work due to LLDB bug
// - Remove and re-add on first stop: Works but wasteful
// - Platform-specific APIs: Same underlying issue
//
// Move hardware breakpoints to deferred list instead of applying now
m_deferredHardwareBreakpoints = std::move(m_pendingHardwareBreakpoints);
m_pendingHardwareBreakpoints.clear();
// Set flag to apply deferred hardware breakpoints on first stop
if (!m_deferredHardwareBreakpoints.empty())
{
m_needsHardwareBreakpointReapplication = true;
}
}
bool LldbAdapter::IsELFWithoutDynamicLoader(BinaryView* data)
{
if (!data)
return false;
auto name = data->GetTypeName();
if (name != "ELF")
return false;
auto syms = data->GetSymbolsByName("__elf_interp");
return syms.empty();
}
bool LldbAdapter::Execute(const std::string& path, const LaunchConfigurations& configs)
{
return ExecuteWithArgs(path, "", "", configs);
}
bool LldbAdapter::ExecuteWithArgs(const std::string& path, const std::string& args, const std::string& workingDir,
const LaunchConfigurations& configs)
{
m_debugger.SetAsync(true);
// We must start the event listener before calling CreateTarget, since CreateTarget will send out the initial
// batch of module load events.
std::thread thread([&]() { EventListener(); });
thread.detach();
SBError err;
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 separateTerminal = adapterSettings->Get<bool>("launch.terminalEmulator", data, &scope);
scope = SettingsResourceScope;
auto disableASLR = adapterSettings->Get<bool>("launch.disableAslr", data, &scope);
scope = SettingsResourceScope;
auto redirectStdin = adapterSettings->Get<std::string>("launch.redirectStdin", data, &scope);
scope = SettingsResourceScope;
auto redirectStdout = adapterSettings->Get<std::string>("launch.redirectStdout", data, &scope);
scope = SettingsResourceScope;
auto redirectStderr = adapterSettings->Get<std::string>("launch.redirectStderr", data, &scope);
scope = SettingsResourceScope;
auto envVariables = adapterSettings->Get<vector<string>>("launch.environmentVariables", data, &scope);
scope = SettingsResourceScope;
auto followForkMode = adapterSettings->Get<std::string>("common.followForkMode", data, &scope);
scope = SettingsResourceScope;
auto initialLLDBCommand = adapterSettings->Get<vector<string>>("common.initialLLDBCommand", data, &scope);
CreateTarget(inputFile);
if (!m_target.IsValid())
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.shortError = "LLDB failed to create target.";
event.data.errorData.error =
fmt::format("LLDB Failed to create target with \"{}\"", err.GetCString() ? err.GetCString() : "");
PostDebuggerEvent(event);
return false;
}
m_targetActive = true;
// Breakpoints are added to this adapter right after the adapter gets created. However, at that time, the target is
// not created yet, so there is no way the adapter could apply the breakpoints to the target. Instead, the adapter
// stores all the breakpoints in m_pendingBreakpoints, and applies them when launching/connecting/attaching to the
// target.
ApplyBreakpoints();
if (Settings::Instance()->Get<bool>("debugger.stopAtEntryPoint") && m_hasEntryFunction)
AddBreakpoint(ModuleNameAndOffset(inputFile, m_entryPoint - m_start));
// TODO: the adapter should record whether it is connected to a debug server itself, rather than relying on the
// info from the configs dict
if (GetController()->IsConnectedToDebugServer())
{
// During remote debugging. lldb will try to upload the samples to the working directory before launching.
// The working directory defaults to the path the lldb-server is in, which is likely not the intended one.
// Here we set the remote working directory to the one specified by the user
auto result = InvokeBackendCommand(fmt::format("platform settings -w \"{}\"", workingDirectory));
}
if (followForkMode != "default")
InvokeBackendCommand(fmt::format("settings set target.process.follow-fork-mode \"{}\"", followForkMode));
if (!initialLLDBCommand.empty())
{
for (const auto& command : initialLLDBCommand)
{
if (command.empty())
continue;
InvokeBackendCommand(command);
}
}
std::string launchCommand = "process launch";
if (Settings::Instance()->Get<bool>("debugger.stopAtSystemEntryPoint") ||
(m_isElFWithoutDynamicLoader && (executablePath == inputFile)))
launchCommand += " --stop-at-entry";
if (separateTerminal)
launchCommand += " --tty";
if (!workingDirectory.empty())
launchCommand += fmt::format(" --working-dir \"{}\"", workingDirectory);
launchCommand += " --disable-aslr ";
launchCommand += disableASLR ? "true" : "false";
if (!redirectStdin.empty())
launchCommand += fmt::format(" --stdin \"{}\"", redirectStdin);
if (!redirectStdout.empty())
launchCommand += fmt::format(" --stdout \"{}\"", redirectStdout);
if (!redirectStderr.empty())
launchCommand += fmt::format(" --stderr \"{}\"", redirectStderr);
if (!envVariables.empty())
{
for (const auto& var : envVariables)
{
if (var.empty())
continue;
launchCommand += fmt::format(" --environment \"{}\"", var);
}
}
if (!commandLineArgs.empty())
launchCommand += (" -- " + commandLineArgs);
LogWarn("LLDB launchCommand: %s", launchCommand.c_str());
auto result = InvokeBackendCommand(launchCommand);
DebuggerEvent evt;
evt.type = BackendMessageEventType;
evt.data.messageData.message = result;
PostDebuggerEvent(evt);
m_process = m_target.GetProcess();
if (!m_process.IsValid() || (m_process.GetState() == StateType::eStateInvalid) || (result.rfind("error: ", 0) == 0))
{
auto it = result.find_last_not_of('\n');
result.erase(it + 1);
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.shortError = fmt::format("LLDB failed to launch target.");
event.data.errorData.error = fmt::format("LLDB Failed to launch target with \"{}\"", result.c_str());
PostDebuggerEvent(event);
return false;
}
return true;
}
bool LldbAdapter::Attach(std::uint32_t pid)
{
m_debugger.SetAsync(true);
std::thread thread([&]() { EventListener(); });
thread.detach();
SBError err;
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
auto inputFile = adapterSettings->Get<std::string>("common.inputFile", data, &scope);
scope = SettingsResourceScope;
auto attachPID = adapterSettings->Get<uint64_t>("attach.pid", data, &scope);
scope = SettingsResourceScope;
auto followForkMode = adapterSettings->Get<std::string>("common.followForkMode", data, &scope);
scope = SettingsResourceScope;
auto initialLLDBCommand = adapterSettings->Get<vector<string>>("common.initialLLDBCommand", data, &scope);
CreateTarget(inputFile);
if (!m_target.IsValid())
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.shortError = fmt::format("LLDB failed to attach to target.");
event.data.errorData.error =
fmt::format("LLDB failed to attach to target with \"{}\"", err.GetCString() ? err.GetCString() : "");
PostDebuggerEvent(event);
return false;
}
m_targetActive = true;
ApplyBreakpoints();
if (followForkMode != "default")
InvokeBackendCommand(fmt::format("settings set target.process.follow-fork-mode \"{}\"", followForkMode));
if (!initialLLDBCommand.empty())
{
for (const auto& command : initialLLDBCommand)
{
if (command.empty())
continue;
InvokeBackendCommand(command);
}
}
SBAttachInfo info(attachPID);
m_process = m_target.Attach(info, err);
if (!m_process.IsValid() || (m_process.GetState() == StateType::eStateInvalid) || err.Fail())
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.shortError = fmt::format("LLDB failed to attach to target.");
event.data.errorData.error =
fmt::format("LLDB Failed to attach to target with \"{}\"", err.GetCString() ? err.GetCString() : "");
PostDebuggerEvent(event);
return false;
}
// LLDB event listener does not get an event when the attach operation completes, so we must send an event here.
// This is NOT needed for Connect(), since LLDB event listener sends an event in that case.
DebuggerEvent dbgevt;
dbgevt.type = AdapterStoppedEventType;
dbgevt.data.targetStoppedData.reason = InitialBreakpoint;
PostDebuggerEvent(dbgevt);
return true;
}
bool LldbAdapter::CreateTarget(const std::string &file)
{
// We try different ways to create a target until one of them works...
auto archName = lldbArchNameForBinaryNinjaArchName(m_defaultArchitecture);
std::string triple = "";
if (!archName.empty())
triple = archName + "-unknown-none";
m_target = m_debugger.CreateTargetWithFileAndArch(file.c_str(), archName.c_str());
if (m_target.IsValid())
return true;
m_target = m_debugger.CreateTargetWithFileAndArch(file.c_str(), "");
if (m_target.IsValid())
return true;
SBError err;
m_target = m_debugger.CreateTarget(file.c_str(), triple.c_str(), "", true, err);
if (m_target.IsValid())
return true;
m_target = m_debugger.CreateTarget(file.c_str(), "", "", true, err);
if (m_target.IsValid())
return true;
m_target = m_debugger.CreateTarget("", "", "", true, err);
if (m_target.IsValid())
return true;
return false;
}
bool LldbAdapter::Connect(const std::string& server, std::uint32_t port)
{
m_debugger.SetAsync(true);
std::thread thread([&]() { EventListener(); });
thread.detach();
SBError err;
BNSettingsScope scope = SettingsResourceScope;
auto data = GetData();
auto adapterSettings = GetAdapterSettings();
auto inputFile = adapterSettings->Get<std::string>("common.inputFile", data, &scope);
scope = SettingsResourceScope;
auto ipAddress = adapterSettings->Get<std::string>("connect.ipAddress", data, &scope);
scope = SettingsResourceScope;
auto serverPort = adapterSettings->Get<uint64_t>("connect.port", data, &scope);
scope = SettingsResourceScope;
auto processPlugin = adapterSettings->Get<std::string>("connect.processPlugin", data, &scope);
scope = SettingsResourceScope;
auto followForkMode = adapterSettings->Get<std::string>("common.followForkMode", data, &scope);
scope = SettingsResourceScope;
auto initialLLDBCommand = adapterSettings->Get<vector<string>>("common.initialLLDBCommand", data, &scope);
CreateTarget(inputFile);
if (!m_target.IsValid())
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.shortError = fmt::format("LLDB failed to connect to target.");
event.data.errorData.error =
fmt::format("LLDB failed to connect to target with \"{}\"", err.GetCString() ? err.GetCString() : "");
PostDebuggerEvent(event);
return false;
}
m_targetActive = true;
ApplyBreakpoints();
if (followForkMode != "default")
InvokeBackendCommand(fmt::format("settings set target.process.follow-fork-mode \"{}\"", followForkMode));
if (!initialLLDBCommand.empty())
{
for (const auto& command : initialLLDBCommand)
{
if (command.empty())
continue;
InvokeBackendCommand(command);
}
}
if (Settings::Instance()->Get<bool>("debugger.stopAtEntryPoint") && m_hasEntryFunction)
AddBreakpoint(ModuleNameAndOffset(inputFile, m_entryPoint - m_start));
std::string url = fmt::format("connect://{}:{}", ipAddress, serverPort);
SBListener listener;
const char* plugin = nullptr;
if (!processPlugin.empty() && processPlugin != "debugserver/lldb")
plugin = processPlugin.c_str();
m_process = m_target.ConnectRemote(listener, url.c_str(), plugin, err);
if (!m_process.IsValid() || (m_process.GetState() == StateType::eStateInvalid) || err.Fail())
{
DebuggerEvent event;
event.type = LaunchFailureEventType;
event.data.errorData.shortError = fmt::format("LLDB failed to connect to target.");
event.data.errorData.error =
fmt::format("LLDB Failed to connect to target with \"{}\"", err.GetCString() ? err.GetCString() : "");
PostDebuggerEvent(event);
return false;
}
return true;
}
bool LldbAdapter::Detach()
{
std::unique_lock<std::mutex> lock(m_quitingMutex);
SBError error = m_process.Detach();
if (error.Success())
return true;
// There is a situation where the reqeust to Quit or Detach can fail, and the target will continue to execute but
// the DebuggerController is freed. To avoid UAF, when that happens, make sure at least we break from the
// EventListener() loop
m_userRequestedQuit = true;
return false;
}
bool LldbAdapter::Quit()
{
std::unique_lock<std::mutex> lock(m_quitingMutex);
SBError error = m_process.Kill();
if (error.Success())
return true;
// There is a situation where the reqeust to Quit or Detach can fail, and the target will continue to execute but
// the DebuggerController is freed. To avoid UAF, when that happens, make sure at least we break from the
// EventListener() loop
m_userRequestedQuit = true;
return false;
}
std::vector<DebugProcess> LldbAdapter::GetProcessList()
{
std::vector<DebugProcess> debug_processes {};
std::istringstream processList(InvokeBackendCommand("platform process list"));
std::string line;
while (getline(processList, line, '\n'))
{
uint32_t pid{};
// skip header lines and lines that have len <= 56
if (line.rfind("matching processes were found on") != std::string::npos
|| line.rfind("PID PARENT USER") != std::string::npos
|| line.rfind("====== ======") != std::string::npos
|| line.size() <= 56)
{
continue;
}
if (sscanf(line.c_str(), "%d", &pid) == 0)
continue;
// example output lines:
// 1268 944 csrss.exe
// 37635 9677 xusheng arm64-apple-* Code Helper (Renderer)
//
// we've 56 bytes until process name which is calculated like this:
// (6 + 1) + (6 + 1) + (10 + 1) + (30 + 1)
std::string processName(std::next(line.begin(), 56), line.end());
debug_processes.emplace_back(pid, processName);
}
return debug_processes;
}
std::uint32_t LldbAdapter::GetActivePID()
{
if (!m_process.IsValid())
return 0;
return (uint32_t)m_process.GetProcessID();
}
std::vector<DebugThread> LldbAdapter::GetThreadList()
{
size_t threadCount = m_process.GetNumThreads();
std::vector<DebugThread> result;
for (size_t i = 0; i < threadCount; i++)
{
SBThread thread = m_process.GetThreadAtIndex(i);
if (!thread.IsValid())
continue;
auto tid = thread.GetThreadID();
uint64_t pc = 0;
size_t frameCount = thread.GetNumFrames();
if (frameCount > 0)
{
SBFrame frame = thread.GetFrameAtIndex(0);
if (frame.IsValid())
pc = frame.GetPC();
}
result.emplace_back((uint32_t)tid, pc);
}
return result;
}
DebugThread LldbAdapter::GetActiveThread() const
{
SBThread thread = m_process.GetSelectedThread();
if (!thread.IsValid())
return DebugThread {};
auto tid = thread.GetThreadID();
uint64_t pc = 0;
size_t frameCount = thread.GetNumFrames();
if (frameCount > 0)
{
SBFrame frame = thread.GetFrameAtIndex(0);
if (frame.IsValid())
pc = frame.GetPC();
}
return DebugThread((uint32_t)tid, pc);
}
uint32_t LldbAdapter::GetActiveThreadId() const
{
SBThread thread = m_process.GetSelectedThread();
if (!thread.IsValid())
return 0;
auto tid = thread.GetThreadID();
// TODO: we should probably change the return value to uint64_t
return (uint32_t)tid;
}
bool LldbAdapter::SetActiveThread(const DebugThread& thread)
{
return SetActiveThreadId(thread.m_tid);
}
bool LldbAdapter::SetActiveThreadId(std::uint32_t tid)
{
return m_process.SetSelectedThreadByID(tid);
}
bool LldbAdapter::SuspendThread(std::uint32_t tid)
{
SBError error;
SBThread thread = m_process.GetThreadByID(tid);
if (!thread.IsValid())
return false;
if (!thread.Suspend(error))
return false;
if (!error.Success())
return false;
return true;
}
bool LldbAdapter::ResumeThread(std::uint32_t tid)
{
SBError error;
SBThread thread = m_process.GetThreadByID(tid);
if (!thread.IsValid())
return false;
if (!thread.Resume(error))
return false;
if (!error.Success())
return false;
return true;
}
std::vector<DebugFrame> LldbAdapter::GetFramesOfThread(uint32_t tid)
{
size_t threadCount = m_process.GetNumThreads();
std::vector<DebugFrame> result;
result.reserve(threadCount);
for (size_t i = 0; i < threadCount; i++)
{
SBThread thread = m_process.GetThreadAtIndex(i);
if (!thread.IsValid())
continue;
if (tid == thread.GetThreadID())
{
uint32_t frameCount = thread.GetNumFrames();
for (uint32_t j = 0; j < frameCount; j++)
{
SBFrame frame = thread.GetFrameAtIndex(j);
if (!frame.IsValid())
continue;
SBModule module = frame.GetModule();
SBFileSpec fileSpec = module.GetFileSpec();
std::string modulePath;
if (fileSpec.GetFilename())
modulePath = fileSpec.GetFilename();
uint64_t startAddress = 0;
SBFunction function = frame.GetFunction();
if (function.IsValid())
{
startAddress = function.GetStartAddress().GetLoadAddress(m_target);
}
else
{
SBSymbol symbol = frame.GetSymbol();
if (symbol.IsValid())
startAddress = symbol.GetStartAddress().GetLoadAddress(m_target);
}
std::string frameFunctionName;
if (frame.GetFunctionName())
frameFunctionName = std::string(frame.GetFunctionName());
DebugFrame f(
j, frame.GetPC(), frame.GetSP(), frame.GetFP(), frameFunctionName, startAddress, modulePath);
result.push_back(f);
}
return result;
}
}
return result;
}
DebugBreakpoint LldbAdapter::AddBreakpoint(const std::uintptr_t address, unsigned long breakpoint_type)
{
// Check if this is a hardware breakpoint type
if (breakpoint_type == HardwareExecuteBreakpoint)
{
if (AddHardwareBreakpoint(address, HardwareExecuteBreakpoint))
return DebugBreakpoint(address, 0, true, HardwareExecuteBreakpoint);
else
return DebugBreakpoint {};
}
// Default software breakpoint
SBBreakpoint bp = m_target.BreakpointCreateByAddress(address);
if (!bp.IsValid())
return DebugBreakpoint {};
return DebugBreakpoint(address, bp.GetID(), bp.IsEnabled(), SoftwareBreakpoint);
}
bool LldbAdapter::ResolveModuleAddress(const ModuleNameAndOffset& location, uint64_t& address)
{
// Try to find the module in the loaded module list
auto modules = GetModuleList();
for (const auto& module : modules)
{
if (module.IsSameBaseModule(location.module))
{
address = module.m_address + location.offset;
return true;
}
}
// Module not found - caller should fall back to module+offset handling
return false;
}
DebugBreakpoint LldbAdapter::AddBreakpoint(const ModuleNameAndOffset& address, unsigned long breakpoint_type)
{
if (!m_targetActive)
{
if (std::find(m_pendingBreakpoints.begin(), m_pendingBreakpoints.end(), address) == m_pendingBreakpoints.end())