forked from swiftlang/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessGDBRemote.cpp
5894 lines (5204 loc) · 224 KB
/
ProcessGDBRemote.cpp
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
//===-- ProcessGDBRemote.cpp ----------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/Config.h"
#include <cerrno>
#include <cstdlib>
#if LLDB_ENABLE_POSIX
#include <netinet/in.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <sys/stat.h>
#if defined(__APPLE__)
#include <sys/sysctl.h>
#endif
#include <ctime>
#include <sys/types.h>
#include "lldb/Breakpoint/Watchpoint.h"
#include "lldb/Breakpoint/WatchpointAlgorithms.h"
#include "lldb/Breakpoint/WatchpointResource.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Value.h"
#include "lldb/DataFormatters/FormatManager.h"
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/HostThread.h"
#include "lldb/Host/PosixApi.h"
#include "lldb/Host/PseudoTerminal.h"
#include "lldb/Host/StreamFile.h"
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Host/XML.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandObject.h"
#include "lldb/Interpreter/CommandObjectMultiword.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Interpreter/OptionArgParser.h"
#include "lldb/Interpreter/OptionGroupBoolean.h"
#include "lldb/Interpreter/OptionGroupUInt64.h"
#include "lldb/Interpreter/OptionValueProperties.h"
#include "lldb/Interpreter/Options.h"
#include "lldb/Interpreter/Property.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/ABI.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/MemoryRegionInfo.h"
#include "lldb/Target/RegisterFlags.h"
#include "lldb/Target/SystemRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/TargetList.h"
#include "lldb/Target/ThreadPlanCallFunction.h"
#include "lldb/Utility/Args.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/State.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/Timer.h"
#include <algorithm>
#include <csignal>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <thread>
#include "GDBRemoteRegisterContext.h"
#include "GDBRemoteRegisterFallback.h"
#include "Plugins/Process/Utility/GDBRemoteSignals.h"
#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
#include "Plugins/Process/Utility/StopInfoMachException.h"
#include "ProcessGDBRemote.h"
#include "ProcessGDBRemoteLog.h"
#include "ThreadGDBRemote.h"
#include "lldb/Host/Host.h"
#include "lldb/Utility/StringExtractorGDBRemote.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUGSERVER_BASENAME "debugserver"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
namespace lldb {
// Provide a function that can easily dump the packet history if we know a
// ProcessGDBRemote * value (which we can get from logs or from debugging). We
// need the function in the lldb namespace so it makes it into the final
// executable since the LLDB shared library only exports stuff in the lldb
// namespace. This allows you to attach with a debugger and call this function
// and get the packet history dumped to a file.
void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
auto file = FileSystem::Instance().Open(
FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
if (!file) {
llvm::consumeError(file.takeError());
return;
}
StreamFile stream(std::move(file.get()));
((Process *)p)->DumpPluginHistory(stream);
}
} // namespace lldb
namespace {
#define LLDB_PROPERTIES_processgdbremote
#include "ProcessGDBRemoteProperties.inc"
enum {
#define LLDB_PROPERTIES_processgdbremote
#include "ProcessGDBRemotePropertiesEnum.inc"
};
class PluginProperties : public Properties {
public:
static llvm::StringRef GetSettingName() {
return ProcessGDBRemote::GetPluginNameStatic();
}
PluginProperties() : Properties() {
m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
m_collection_sp->Initialize(g_processgdbremote_properties);
}
~PluginProperties() override = default;
uint64_t GetPacketTimeout() {
const uint32_t idx = ePropertyPacketTimeout;
return GetPropertyAtIndexAs<uint64_t>(
idx, g_processgdbremote_properties[idx].default_uint_value);
}
bool SetPacketTimeout(uint64_t timeout) {
const uint32_t idx = ePropertyPacketTimeout;
return SetPropertyAtIndex(idx, timeout);
}
FileSpec GetTargetDefinitionFile() const {
const uint32_t idx = ePropertyTargetDefinitionFile;
return GetPropertyAtIndexAs<FileSpec>(idx, {});
}
bool GetUseSVR4() const {
const uint32_t idx = ePropertyUseSVR4;
return GetPropertyAtIndexAs<bool>(
idx, g_processgdbremote_properties[idx].default_uint_value != 0);
}
bool GetUseGPacketForReading() const {
const uint32_t idx = ePropertyUseGPacketForReading;
return GetPropertyAtIndexAs<bool>(idx, true);
}
};
} // namespace
static PluginProperties &GetGlobalPluginProperties() {
static PluginProperties g_settings;
return g_settings;
}
// TODO Randomly assigning a port is unsafe. We should get an unused
// ephemeral port from the kernel and make sure we reserve it before passing it
// to debugserver.
#if defined(__APPLE__)
#define LOW_PORT (IPPORT_RESERVED)
#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
#else
#define LOW_PORT (1024u)
#define HIGH_PORT (49151u)
#endif
llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
return "GDB Remote protocol based debugging plug-in.";
}
void ProcessGDBRemote::Terminate() {
PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
}
lldb::ProcessSP ProcessGDBRemote::CreateInstance(
lldb::TargetSP target_sp, ListenerSP listener_sp,
const FileSpec *crash_file_path, bool can_connect) {
lldb::ProcessSP process_sp;
if (crash_file_path == nullptr)
process_sp = std::shared_ptr<ProcessGDBRemote>(
new ProcessGDBRemote(target_sp, listener_sp));
return process_sp;
}
void ProcessGDBRemote::DumpPluginHistory(Stream &s) {
GDBRemoteCommunicationClient &gdb_comm(GetGDBRemote());
gdb_comm.DumpHistory(s);
}
std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
}
ArchSpec ProcessGDBRemote::GetSystemArchitecture() {
return m_gdb_comm.GetHostArchitecture();
}
bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
bool plugin_specified_by_name) {
if (plugin_specified_by_name)
return true;
// For now we are just making sure the file exists for a given module
Module *exe_module = target_sp->GetExecutableModulePointer();
if (exe_module) {
ObjectFile *exe_objfile = exe_module->GetObjectFile();
// We can't debug core files...
switch (exe_objfile->GetType()) {
case ObjectFile::eTypeInvalid:
case ObjectFile::eTypeCoreFile:
case ObjectFile::eTypeDebugInfo:
case ObjectFile::eTypeObjectFile:
case ObjectFile::eTypeSharedLibrary:
case ObjectFile::eTypeStubLibrary:
case ObjectFile::eTypeJIT:
return false;
case ObjectFile::eTypeExecutable:
case ObjectFile::eTypeDynamicLinker:
case ObjectFile::eTypeUnknown:
break;
}
return FileSystem::Instance().Exists(exe_module->GetFileSpec());
}
// However, if there is no executable module, we return true since we might
// be preparing to attach.
return true;
}
// ProcessGDBRemote constructor
ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
ListenerSP listener_sp)
: Process(target_sp, listener_sp),
m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
m_async_listener_sp(
Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
m_max_memory_size(0), m_remote_stub_max_memory_size(0),
m_addr_to_mmap_size(), m_thread_create_bp_sp(),
m_waiting_for_attach(false), m_command_sp(), m_breakpoint_pc_offset(0),
m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
m_erased_flash_ranges(), m_vfork_in_progress_count(0) {
m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
"async thread should exit");
m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
"async thread continue");
m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
"async thread did exit");
Log *log = GetLog(GDBRLog::Async);
const uint32_t async_event_mask =
eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
if (m_async_listener_sp->StartListeningForEvents(
&m_async_broadcaster, async_event_mask) != async_event_mask) {
LLDB_LOGF(log,
"ProcessGDBRemote::%s failed to listen for "
"m_async_broadcaster events",
__FUNCTION__);
}
const uint64_t timeout_seconds =
GetGlobalPluginProperties().GetPacketTimeout();
if (timeout_seconds > 0)
m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
m_use_g_packet_for_reading =
GetGlobalPluginProperties().GetUseGPacketForReading();
}
// Destructor
ProcessGDBRemote::~ProcessGDBRemote() {
// m_mach_process.UnregisterNotificationCallbacks (this);
Clear();
// We need to call finalize on the process before destroying ourselves to
// make sure all of the broadcaster cleanup goes as planned. If we destruct
// this class, then Process::~Process() might have problems trying to fully
// destroy the broadcaster.
Finalize(true /* destructing */);
// The general Finalize is going to try to destroy the process and that
// SHOULD shut down the async thread. However, if we don't kill it it will
// get stranded and its connection will go away so when it wakes up it will
// crash. So kill it for sure here.
StopAsyncThread();
KillDebugserverProcess();
}
bool ProcessGDBRemote::ParsePythonTargetDefinition(
const FileSpec &target_definition_fspec) {
ScriptInterpreter *interpreter =
GetTarget().GetDebugger().GetScriptInterpreter();
Status error;
StructuredData::ObjectSP module_object_sp(
interpreter->LoadPluginModule(target_definition_fspec, error));
if (module_object_sp) {
StructuredData::DictionarySP target_definition_sp(
interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
"gdb-server-target-definition", error));
if (target_definition_sp) {
StructuredData::ObjectSP target_object(
target_definition_sp->GetValueForKey("host-info"));
if (target_object) {
if (auto host_info_dict = target_object->GetAsDictionary()) {
StructuredData::ObjectSP triple_value =
host_info_dict->GetValueForKey("triple");
if (auto triple_string_value = triple_value->GetAsString()) {
std::string triple_string =
std::string(triple_string_value->GetValue());
ArchSpec host_arch(triple_string.c_str());
if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
GetTarget().SetArchitecture(host_arch);
}
}
}
}
m_breakpoint_pc_offset = 0;
StructuredData::ObjectSP breakpoint_pc_offset_value =
target_definition_sp->GetValueForKey("breakpoint-pc-offset");
if (breakpoint_pc_offset_value) {
if (auto breakpoint_pc_int_value =
breakpoint_pc_offset_value->GetAsSignedInteger())
m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
}
if (m_register_info_sp->SetRegisterInfo(
*target_definition_sp, GetTarget().GetArchitecture()) > 0) {
return true;
}
}
}
return false;
}
static size_t SplitCommaSeparatedRegisterNumberString(
const llvm::StringRef &comma_separated_register_numbers,
std::vector<uint32_t> ®nums, int base) {
regnums.clear();
for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
uint32_t reg;
if (llvm::to_integer(x, reg, base))
regnums.push_back(reg);
}
return regnums.size();
}
void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
if (!force && m_register_info_sp)
return;
m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
// Check if qHostInfo specified a specific packet timeout for this
// connection. If so then lets update our setting so the user knows what the
// timeout is and can see it.
const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
if (host_packet_timeout > std::chrono::seconds(0)) {
GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
}
// Register info search order:
// 1 - Use the target definition python file if one is specified.
// 2 - If the target definition doesn't have any of the info from the
// target.xml (registers) then proceed to read the target.xml.
// 3 - Fall back on the qRegisterInfo packets.
// 4 - Use hardcoded defaults if available.
FileSpec target_definition_fspec =
GetGlobalPluginProperties().GetTargetDefinitionFile();
if (!FileSystem::Instance().Exists(target_definition_fspec)) {
// If the filename doesn't exist, it may be a ~ not having been expanded -
// try to resolve it.
FileSystem::Instance().Resolve(target_definition_fspec);
}
if (target_definition_fspec) {
// See if we can get register definitions from a python file
if (ParsePythonTargetDefinition(target_definition_fspec))
return;
Debugger::ReportError("target description file " +
target_definition_fspec.GetPath() +
" failed to parse",
GetTarget().GetDebugger().GetID());
}
const ArchSpec &target_arch = GetTarget().GetArchitecture();
const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
// Use the process' architecture instead of the host arch, if available
ArchSpec arch_to_use;
if (remote_process_arch.IsValid())
arch_to_use = remote_process_arch;
else
arch_to_use = remote_host_arch;
if (!arch_to_use.IsValid())
arch_to_use = target_arch;
if (GetGDBServerRegisterInfo(arch_to_use))
return;
char packet[128];
std::vector<DynamicRegisterInfo::Register> registers;
uint32_t reg_num = 0;
for (StringExtractorGDBRemote::ResponseType response_type =
StringExtractorGDBRemote::eResponse;
response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
const int packet_len =
::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
assert(packet_len < (int)sizeof(packet));
UNUSED_IF_ASSERT_DISABLED(packet_len);
StringExtractorGDBRemote response;
if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
GDBRemoteCommunication::PacketResult::Success) {
response_type = response.GetResponseType();
if (response_type == StringExtractorGDBRemote::eResponse) {
llvm::StringRef name;
llvm::StringRef value;
DynamicRegisterInfo::Register reg_info;
while (response.GetNameColonValue(name, value)) {
if (name == "name") {
reg_info.name.SetString(value);
} else if (name == "alt-name") {
reg_info.alt_name.SetString(value);
} else if (name == "bitsize") {
if (!value.getAsInteger(0, reg_info.byte_size))
reg_info.byte_size /= CHAR_BIT;
} else if (name == "offset") {
value.getAsInteger(0, reg_info.byte_offset);
} else if (name == "encoding") {
const Encoding encoding = Args::StringToEncoding(value);
if (encoding != eEncodingInvalid)
reg_info.encoding = encoding;
} else if (name == "format") {
if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
.Success())
reg_info.format =
llvm::StringSwitch<Format>(value)
.Case("binary", eFormatBinary)
.Case("decimal", eFormatDecimal)
.Case("hex", eFormatHex)
.Case("float", eFormatFloat)
.Case("vector-sint8", eFormatVectorOfSInt8)
.Case("vector-uint8", eFormatVectorOfUInt8)
.Case("vector-sint16", eFormatVectorOfSInt16)
.Case("vector-uint16", eFormatVectorOfUInt16)
.Case("vector-sint32", eFormatVectorOfSInt32)
.Case("vector-uint32", eFormatVectorOfUInt32)
.Case("vector-float32", eFormatVectorOfFloat32)
.Case("vector-uint64", eFormatVectorOfUInt64)
.Case("vector-uint128", eFormatVectorOfUInt128)
.Default(eFormatInvalid);
} else if (name == "set") {
reg_info.set_name.SetString(value);
} else if (name == "gcc" || name == "ehframe") {
value.getAsInteger(0, reg_info.regnum_ehframe);
} else if (name == "dwarf") {
value.getAsInteger(0, reg_info.regnum_dwarf);
} else if (name == "generic") {
reg_info.regnum_generic = Args::StringToGenericRegister(value);
} else if (name == "container-regs") {
SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);
} else if (name == "invalidate-regs") {
SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);
}
}
assert(reg_info.byte_size != 0);
registers.push_back(reg_info);
} else {
break; // ensure exit before reg_num is incremented
}
} else {
break;
}
}
if (registers.empty())
registers = GetFallbackRegisters(arch_to_use);
AddRemoteRegisters(registers, arch_to_use);
}
Status ProcessGDBRemote::DoWillLaunch(lldb_private::Module *module) {
return WillLaunchOrAttach();
}
Status ProcessGDBRemote::DoWillAttachToProcessWithID(lldb::pid_t pid) {
return WillLaunchOrAttach();
}
Status ProcessGDBRemote::DoWillAttachToProcessWithName(const char *process_name,
bool wait_for_launch) {
return WillLaunchOrAttach();
}
Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
Log *log = GetLog(GDBRLog::Process);
Status error(WillLaunchOrAttach());
if (error.Fail())
return error;
error = ConnectToDebugserver(remote_url);
if (error.Fail())
return error;
StartAsyncThread();
lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
if (pid == LLDB_INVALID_PROCESS_ID) {
// We don't have a valid process ID, so note that we are connected and
// could now request to launch or attach, or get remote process listings...
SetPrivateState(eStateConnected);
} else {
// We have a valid process
SetID(pid);
GetThreadList();
StringExtractorGDBRemote response;
if (m_gdb_comm.GetStopReply(response)) {
SetLastStopPacket(response);
Target &target = GetTarget();
if (!target.GetArchitecture().IsValid()) {
if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
} else {
if (m_gdb_comm.GetHostArchitecture().IsValid()) {
target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
}
}
}
const StateType state = SetThreadStopInfo(response);
if (state != eStateInvalid) {
SetPrivateState(state);
} else
error = Status::FromErrorStringWithFormat(
"Process %" PRIu64 " was reported after connecting to "
"'%s', but state was not stopped: %s",
pid, remote_url.str().c_str(), StateAsCString(state));
} else
error = Status::FromErrorStringWithFormat(
"Process %" PRIu64 " was reported after connecting to '%s', "
"but no stop reply packet was received",
pid, remote_url.str().c_str());
}
LLDB_LOGF(log,
"ProcessGDBRemote::%s pid %" PRIu64
": normalizing target architecture initial triple: %s "
"(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
__FUNCTION__, GetID(),
GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
GetTarget().GetArchitecture().IsValid() ? "true" : "false",
m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
m_gdb_comm.GetHostArchitecture().IsValid()) {
// Prefer the *process'* architecture over that of the *host*, if
// available.
if (m_gdb_comm.GetProcessArchitecture().IsValid())
GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
else
GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
}
LLDB_LOGF(log,
"ProcessGDBRemote::%s pid %" PRIu64
": normalized target architecture triple: %s",
__FUNCTION__, GetID(),
GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
return error;
}
Status ProcessGDBRemote::WillLaunchOrAttach() {
Status error;
m_stdio_communication.Clear();
return error;
}
// Process Control
Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
ProcessLaunchInfo &launch_info) {
Log *log = GetLog(GDBRLog::Process);
Status error;
LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
uint32_t launch_flags = launch_info.GetFlags().Get();
FileSpec stdin_file_spec{};
FileSpec stdout_file_spec{};
FileSpec stderr_file_spec{};
FileSpec working_dir = launch_info.GetWorkingDirectory();
const FileAction *file_action;
file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
if (file_action) {
if (file_action->GetAction() == FileAction::eFileActionOpen)
stdin_file_spec = file_action->GetFileSpec();
}
file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
if (file_action) {
if (file_action->GetAction() == FileAction::eFileActionOpen)
stdout_file_spec = file_action->GetFileSpec();
}
file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
if (file_action) {
if (file_action->GetAction() == FileAction::eFileActionOpen)
stderr_file_spec = file_action->GetFileSpec();
}
if (log) {
if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
LLDB_LOGF(log,
"ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s",
__FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
else
LLDB_LOGF(log,
"ProcessGDBRemote::%s no STDIO paths given via launch_info",
__FUNCTION__);
}
const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
if (stdin_file_spec || disable_stdio) {
// the inferior will be reading stdin from the specified file or stdio is
// completely disabled
m_stdin_forward = false;
} else {
m_stdin_forward = true;
}
// ::LogSetBitMask (GDBR_LOG_DEFAULT);
// ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
// LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
// LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
// ::LogSetLogFile ("/dev/stdout");
error = EstablishConnectionIfNeeded(launch_info);
if (error.Success()) {
PseudoTerminal pty;
const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
PlatformSP platform_sp(GetTarget().GetPlatform());
if (disable_stdio) {
// set to /dev/null unless redirected to a file above
if (!stdin_file_spec)
stdin_file_spec.SetFile(FileSystem::DEV_NULL,
FileSpec::Style::native);
if (!stdout_file_spec)
stdout_file_spec.SetFile(FileSystem::DEV_NULL,
FileSpec::Style::native);
if (!stderr_file_spec)
stderr_file_spec.SetFile(FileSystem::DEV_NULL,
FileSpec::Style::native);
} else if (platform_sp && platform_sp->IsHost()) {
// If the debugserver is local and we aren't disabling STDIO, lets use
// a pseudo terminal to instead of relying on the 'O' packets for stdio
// since 'O' packets can really slow down debugging if the inferior
// does a lot of output.
if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
!errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
FileSpec secondary_name(pty.GetSecondaryName());
if (!stdin_file_spec)
stdin_file_spec = secondary_name;
if (!stdout_file_spec)
stdout_file_spec = secondary_name;
if (!stderr_file_spec)
stderr_file_spec = secondary_name;
}
LLDB_LOGF(
log,
"ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
"stderr=%s",
__FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
}
LLDB_LOGF(log,
"ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s",
__FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
if (stdin_file_spec)
m_gdb_comm.SetSTDIN(stdin_file_spec);
if (stdout_file_spec)
m_gdb_comm.SetSTDOUT(stdout_file_spec);
if (stderr_file_spec)
m_gdb_comm.SetSTDERR(stderr_file_spec);
m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
m_gdb_comm.SendLaunchArchPacket(
GetTarget().GetArchitecture().GetArchitectureName());
const char *launch_event_data = launch_info.GetLaunchEventData();
if (launch_event_data != nullptr && *launch_event_data != '\0')
m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
if (working_dir) {
m_gdb_comm.SetWorkingDir(working_dir);
}
// Send the environment and the program + arguments after we connect
m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
{
// Scope for the scoped timeout object
GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
std::chrono::seconds(10));
// Since we can't send argv0 separate from the executable path, we need to
// make sure to use the actual executable path found in the launch_info...
Args args = launch_info.GetArguments();
if (FileSpec exe_file = launch_info.GetExecutableFile())
args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));
if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) {
error = Status::FromErrorStringWithFormatv(
"Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),
llvm::fmt_consume(std::move(err)));
} else {
SetID(m_gdb_comm.GetCurrentProcessID());
}
}
if (GetID() == LLDB_INVALID_PROCESS_ID) {
LLDB_LOGF(log, "failed to connect to debugserver: %s",
error.AsCString());
KillDebugserverProcess();
return error;
}
StringExtractorGDBRemote response;
if (m_gdb_comm.GetStopReply(response)) {
SetLastStopPacket(response);
const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
if (process_arch.IsValid()) {
GetTarget().MergeArchitecture(process_arch);
} else {
const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
if (host_arch.IsValid())
GetTarget().MergeArchitecture(host_arch);
}
SetPrivateState(SetThreadStopInfo(response));
if (!disable_stdio) {
if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
}
}
} else {
LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
}
return error;
}
Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
Status error;
// Only connect if we have a valid connect URL
Log *log = GetLog(GDBRLog::Process);
if (!connect_url.empty()) {
LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
connect_url.str().c_str());
std::unique_ptr<ConnectionFileDescriptor> conn_up(
new ConnectionFileDescriptor());
if (conn_up) {
const uint32_t max_retry_count = 50;
uint32_t retry_count = 0;
while (!m_gdb_comm.IsConnected()) {
if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
m_gdb_comm.SetConnection(std::move(conn_up));
break;
}
retry_count++;
if (retry_count >= max_retry_count)
break;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
}
if (!m_gdb_comm.IsConnected()) {
if (error.Success())
error = Status::FromErrorString("not connected to remote gdb server");
return error;
}
// We always seem to be able to open a connection to a local port so we need
// to make sure we can then send data to it. If we can't then we aren't
// actually connected to anything, so try and do the handshake with the
// remote GDB server and make sure that goes alright.
if (!m_gdb_comm.HandshakeWithServer(&error)) {
m_gdb_comm.Disconnect();
if (error.Success())
error = Status::FromErrorString("not connected to remote gdb server");
return error;
}
m_gdb_comm.GetEchoSupported();
m_gdb_comm.GetThreadSuffixSupported();
m_gdb_comm.GetListThreadsInStopReplySupported();
m_gdb_comm.GetHostInfo();
m_gdb_comm.GetVContSupported('c');
m_gdb_comm.GetVAttachOrWaitSupported();
m_gdb_comm.EnableErrorStringInPacket();
// First dispatch any commands from the platform:
auto handle_cmds = [&] (const Args &args) -> void {
for (const Args::ArgEntry &entry : args) {
StringExtractorGDBRemote response;
m_gdb_comm.SendPacketAndWaitForResponse(
entry.c_str(), response);
}
};
PlatformSP platform_sp = GetTarget().GetPlatform();
if (platform_sp) {
handle_cmds(platform_sp->GetExtraStartupCommands());
}
// Then dispatch any process commands:
handle_cmds(GetExtraStartupCommands());
return error;
}
void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
Log *log = GetLog(GDBRLog::Process);
BuildDynamicRegisterInfo(false);
// See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
// qProcessInfo as it will be more specific to our process.
const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
if (remote_process_arch.IsValid()) {
process_arch = remote_process_arch;
LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
process_arch.GetArchitectureName(),
process_arch.GetTriple().getTriple());
} else {
process_arch = m_gdb_comm.GetHostArchitecture();
LLDB_LOG(log,
"gdb-remote did not have process architecture, using gdb-remote "
"host architecture {0} {1}",
process_arch.GetArchitectureName(),
process_arch.GetTriple().getTriple());
}
AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits();
SetAddressableBitMasks(addressable_bits);
if (process_arch.IsValid()) {
const ArchSpec &target_arch = GetTarget().GetArchitecture();
if (target_arch.IsValid()) {
LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
target_arch.GetArchitectureName(),
target_arch.GetTriple().getTriple());
// If the remote host is ARM and we have apple as the vendor, then
// ARM executables and shared libraries can have mixed ARM
// architectures.
// You can have an armv6 executable, and if the host is armv7, then the
// system will load the best possible architecture for all shared
// libraries it has, so we really need to take the remote host
// architecture as our defacto architecture in this case.
if ((process_arch.GetMachine() == llvm::Triple::arm ||
process_arch.GetMachine() == llvm::Triple::thumb) &&
process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
GetTarget().SetArchitecture(process_arch);
LLDB_LOG(log,
"remote process is ARM/Apple, "
"setting target arch to {0} {1}",
process_arch.GetArchitectureName(),
process_arch.GetTriple().getTriple());
} else {
// Fill in what is missing in the triple
const llvm::Triple &remote_triple = process_arch.GetTriple();
llvm::Triple new_target_triple = target_arch.GetTriple();
if (new_target_triple.getVendorName().size() == 0) {
new_target_triple.setVendor(remote_triple.getVendor());
if (new_target_triple.getOSName().size() == 0) {
new_target_triple.setOS(remote_triple.getOS());
if (new_target_triple.getEnvironmentName().size() == 0)
new_target_triple.setEnvironment(remote_triple.getEnvironment());
}
ArchSpec new_target_arch = target_arch;
new_target_arch.SetTriple(new_target_triple);
GetTarget().SetArchitecture(new_target_arch);
}
}
LLDB_LOG(log,
"final target arch after adjustments for remote architecture: "
"{0} {1}",
target_arch.GetArchitectureName(),
target_arch.GetTriple().getTriple());
} else {
// The target doesn't have a valid architecture yet, set it from the
// architecture we got from the remote GDB server
GetTarget().SetArchitecture(process_arch);
}
}
// Target and Process are reasonably initailized;
// load any binaries we have metadata for / set load address.
LoadStubBinaries();
MaybeLoadExecutableModule();
// Find out which StructuredDataPlugins are supported by the debug monitor.
// These plugins transmit data over async $J packets.
if (StructuredData::Array *supported_packets =
m_gdb_comm.GetSupportedStructuredDataPlugins())
MapSupportedStructuredDataPlugins(*supported_packets);
// If connected to LLDB ("native-signals+"), use signal defs for
// the remote platform. If connected to GDB, just use the standard set.
if (!m_gdb_comm.UsesNativeSignals()) {
SetUnixSignals(std::make_shared<GDBRemoteSignals>());
} else {
PlatformSP platform_sp = GetTarget().GetPlatform();
if (platform_sp && platform_sp->IsConnected())
SetUnixSignals(platform_sp->GetUnixSignals());
else
SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
}
}
void ProcessGDBRemote::LoadStubBinaries() {
// The remote stub may know about the "main binary" in
// the context of a firmware debug session, and can
// give us a UUID and an address/slide of where the
// binary is loaded in memory.
UUID standalone_uuid;
addr_t standalone_value;
bool standalone_value_is_offset;
if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,
standalone_value_is_offset)) {
ModuleSP module_sp;
if (standalone_uuid.IsValid()) {
const bool force_symbol_search = true;
const bool notify = true;
const bool set_address_in_target = true;