/
ProcessGDBRemote.cpp
5032 lines (4471 loc) · 193 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 ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/Config.h"
// C Includes
#include <errno.h>
#include <stdlib.h>
#ifndef LLDB_DISABLE_POSIX
#include <netinet/in.h>
#include <sys/mman.h> // for mmap
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
// C++ Includes
#include <algorithm>
#include <map>
#include <mutex>
#include "lldb/Breakpoint/Watchpoint.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/State.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Core/Timer.h"
#include "lldb/Core/Value.h"
#include "lldb/DataFormatters/FormatManager.h"
#include "lldb/Host/HostThread.h"
#include "lldb/Host/StringConvert.h"
#include "lldb/Host/Symbols.h"
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Host/TimeValue.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/OptionValueProperties.h"
#include "lldb/Interpreter/Options.h"
#include "lldb/Interpreter/OptionGroupBoolean.h"
#include "lldb/Interpreter/OptionGroupUInt64.h"
#include "lldb/Interpreter/Property.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/DynamicLoader.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/TargetList.h"
#include "lldb/Target/ThreadPlanCallFunction.h"
#include "lldb/Target/SystemRuntime.h"
#include "lldb/Utility/PseudoTerminal.h"
// Project includes
#include "lldb/Host/Host.h"
#include "Plugins/Process/Utility/GDBRemoteSignals.h"
#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
#include "Plugins/Process/Utility/StopInfoMachException.h"
#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
#include "Utility/StringExtractorGDBRemote.h"
#include "GDBRemoteRegisterContext.h"
#include "ProcessGDBRemote.h"
#include "ProcessGDBRemoteLog.h"
#include "ThreadGDBRemote.h"
#define DEBUGSERVER_BASENAME "debugserver"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
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)
{
StreamFile strm;
Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
if (error.Success())
((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
}
}
namespace {
static PropertyDefinition
g_properties[] =
{
{ "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
{ "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
{ NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
};
enum
{
ePropertyPacketTimeout,
ePropertyTargetDefinitionFile
};
class PluginProperties : public Properties
{
public:
static ConstString
GetSettingName ()
{
return ProcessGDBRemote::GetPluginNameStatic();
}
PluginProperties() :
Properties ()
{
m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
m_collection_sp->Initialize(g_properties);
}
virtual
~PluginProperties()
{
}
uint64_t
GetPacketTimeout()
{
const uint32_t idx = ePropertyPacketTimeout;
return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
}
bool
SetPacketTimeout(uint64_t timeout)
{
const uint32_t idx = ePropertyPacketTimeout;
return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
}
FileSpec
GetTargetDefinitionFile () const
{
const uint32_t idx = ePropertyTargetDefinitionFile;
return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
}
};
typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
static const ProcessKDPPropertiesSP &
GetGlobalPluginProperties()
{
static ProcessKDPPropertiesSP g_settings_sp;
if (!g_settings_sp)
g_settings_sp.reset (new PluginProperties ());
return g_settings_sp;
}
} // anonymous namespace end
class ProcessGDBRemote::GDBLoadedModuleInfoList
{
public:
class LoadedModuleInfo
{
public:
enum e_data_point
{
e_has_name = 0,
e_has_base ,
e_has_dynamic ,
e_has_link_map ,
e_num
};
LoadedModuleInfo ()
{
for (uint32_t i = 0; i < e_num; ++i)
m_has[i] = false;
};
void set_name (const std::string & name)
{
m_name = name;
m_has[e_has_name] = true;
}
bool get_name (std::string & out) const
{
out = m_name;
return m_has[e_has_name];
}
void set_base (const lldb::addr_t base)
{
m_base = base;
m_has[e_has_base] = true;
}
bool get_base (lldb::addr_t & out) const
{
out = m_base;
return m_has[e_has_base];
}
void set_link_map (const lldb::addr_t addr)
{
m_link_map = addr;
m_has[e_has_link_map] = true;
}
bool get_link_map (lldb::addr_t & out) const
{
out = m_link_map;
return m_has[e_has_link_map];
}
void set_dynamic (const lldb::addr_t addr)
{
m_dynamic = addr;
m_has[e_has_dynamic] = true;
}
bool get_dynamic (lldb::addr_t & out) const
{
out = m_dynamic;
return m_has[e_has_dynamic];
}
bool has_info (e_data_point datum)
{
assert (datum < e_num);
return m_has[datum];
}
protected:
bool m_has[e_num];
std::string m_name;
lldb::addr_t m_link_map;
lldb::addr_t m_base;
lldb::addr_t m_dynamic;
};
GDBLoadedModuleInfoList ()
: m_list ()
, m_link_map (LLDB_INVALID_ADDRESS)
{}
void add (const LoadedModuleInfo & mod)
{
m_list.push_back (mod);
}
void clear ()
{
m_list.clear ();
}
std::vector<LoadedModuleInfo> m_list;
lldb::addr_t m_link_map;
};
// 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
#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
static bool rand_initialized = false;
static inline uint16_t
get_random_port ()
{
if (!rand_initialized)
{
time_t seed = time(NULL);
rand_initialized = true;
srand(seed);
}
return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
}
#endif
ConstString
ProcessGDBRemote::GetPluginNameStatic()
{
static ConstString g_name("gdb-remote");
return g_name;
}
const char *
ProcessGDBRemote::GetPluginDescriptionStatic()
{
return "GDB Remote protocol based debugging plug-in.";
}
void
ProcessGDBRemote::Terminate()
{
PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
}
lldb::ProcessSP
ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
{
lldb::ProcessSP process_sp;
if (crash_file_path == NULL)
process_sp.reset (new ProcessGDBRemote (target, listener));
return process_sp;
}
bool
ProcessGDBRemote::CanDebug (Target &target, 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.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 exe_module->GetFileSpec().Exists();
}
// However, if there is no executable module, we return true since we might be preparing to attach.
return true;
}
//----------------------------------------------------------------------
// ProcessGDBRemote constructor
//----------------------------------------------------------------------
ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
Process (target, listener),
m_flags (0),
m_gdb_comm (),
m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
m_register_info (),
m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
m_thread_ids (),
m_threads_info_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_destroy_tried_resuming (false),
m_command_sp (),
m_breakpoint_pc_offset (0),
m_initial_tid (LLDB_INVALID_THREAD_ID)
{
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");
const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
if (timeout_seconds > 0)
m_gdb_comm.SetPacketTimeout(timeout_seconds);
}
//----------------------------------------------------------------------
// 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();
// 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();
}
//----------------------------------------------------------------------
// PluginInterface
//----------------------------------------------------------------------
ConstString
ProcessGDBRemote::GetPluginName()
{
return GetPluginNameStatic();
}
uint32_t
ProcessGDBRemote::GetPluginVersion()
{
return 1;
}
bool
ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
{
ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Error 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 = 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->GetAsInteger())
m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
}
if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
{
return true;
}
}
}
return false;
}
static size_t
SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> ®nums, int base)
{
regnums.clear();
std::pair<llvm::StringRef, llvm::StringRef> value_pair;
value_pair.second = comma_separated_regiter_numbers;
do
{
value_pair = value_pair.second.split(',');
if (!value_pair.first.empty())
{
uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
if (reg != LLDB_INVALID_REGNUM)
regnums.push_back (reg);
}
} while (!value_pair.second.empty());
return regnums.size();
}
void
ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
{
if (!force && m_register_info.GetNumRegisters() > 0)
return;
m_register_info.Clear();
// 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 uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
if (host_packet_timeout)
{
GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
}
// 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.
FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
if (target_definition_fspec)
{
// See if we can get register definitions from a python file
if (ParsePythonTargetDefinition (target_definition_fspec))
return;
}
if (GetGDBServerRegisterInfo ())
return;
char packet[128];
uint32_t reg_offset = 0;
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));
StringExtractorGDBRemote response;
if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
{
response_type = response.GetResponseType();
if (response_type == StringExtractorGDBRemote::eResponse)
{
std::string name;
std::string value;
ConstString reg_name;
ConstString alt_name;
ConstString set_name;
std::vector<uint32_t> value_regs;
std::vector<uint32_t> invalidate_regs;
RegisterInfo reg_info = { NULL, // Name
NULL, // Alt name
0, // byte size
reg_offset, // offset
eEncodingUint, // encoding
eFormatHex, // formate
{
LLDB_INVALID_REGNUM, // GCC reg num
LLDB_INVALID_REGNUM, // DWARF reg num
LLDB_INVALID_REGNUM, // generic reg num
reg_num, // GDB reg num
reg_num // native register number
},
NULL,
NULL
};
while (response.GetNameColonValue(name, value))
{
if (name.compare("name") == 0)
{
reg_name.SetCString(value.c_str());
}
else if (name.compare("alt-name") == 0)
{
alt_name.SetCString(value.c_str());
}
else if (name.compare("bitsize") == 0)
{
reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
}
else if (name.compare("offset") == 0)
{
uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
if (reg_offset != offset)
{
reg_offset = offset;
}
}
else if (name.compare("encoding") == 0)
{
const Encoding encoding = Args::StringToEncoding (value.c_str());
if (encoding != eEncodingInvalid)
reg_info.encoding = encoding;
}
else if (name.compare("format") == 0)
{
Format format = eFormatInvalid;
if (Args::StringToFormat (value.c_str(), format, NULL).Success())
reg_info.format = format;
else if (value.compare("binary") == 0)
reg_info.format = eFormatBinary;
else if (value.compare("decimal") == 0)
reg_info.format = eFormatDecimal;
else if (value.compare("hex") == 0)
reg_info.format = eFormatHex;
else if (value.compare("float") == 0)
reg_info.format = eFormatFloat;
else if (value.compare("vector-sint8") == 0)
reg_info.format = eFormatVectorOfSInt8;
else if (value.compare("vector-uint8") == 0)
reg_info.format = eFormatVectorOfUInt8;
else if (value.compare("vector-sint16") == 0)
reg_info.format = eFormatVectorOfSInt16;
else if (value.compare("vector-uint16") == 0)
reg_info.format = eFormatVectorOfUInt16;
else if (value.compare("vector-sint32") == 0)
reg_info.format = eFormatVectorOfSInt32;
else if (value.compare("vector-uint32") == 0)
reg_info.format = eFormatVectorOfUInt32;
else if (value.compare("vector-float32") == 0)
reg_info.format = eFormatVectorOfFloat32;
else if (value.compare("vector-uint128") == 0)
reg_info.format = eFormatVectorOfUInt128;
}
else if (name.compare("set") == 0)
{
set_name.SetCString(value.c_str());
}
else if (name.compare("gcc") == 0)
{
reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
}
else if (name.compare("dwarf") == 0)
{
reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
}
else if (name.compare("generic") == 0)
{
reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
}
else if (name.compare("container-regs") == 0)
{
SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
}
else if (name.compare("invalidate-regs") == 0)
{
SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
}
}
reg_info.byte_offset = reg_offset;
assert (reg_info.byte_size != 0);
reg_offset += reg_info.byte_size;
if (!value_regs.empty())
{
value_regs.push_back(LLDB_INVALID_REGNUM);
reg_info.value_regs = value_regs.data();
}
if (!invalidate_regs.empty())
{
invalidate_regs.push_back(LLDB_INVALID_REGNUM);
reg_info.invalidate_regs = invalidate_regs.data();
}
m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
}
else
{
break; // ensure exit before reg_num is incremented
}
}
else
{
break;
}
}
if (m_register_info.GetNumRegisters() > 0)
{
m_register_info.Finalize(GetTarget().GetArchitecture());
return;
}
// We didn't get anything if the accumulated reg_num is zero. See if we are
// debugging ARM and fill with a hard coded register set until we can get an
// updated debugserver down on the devices.
// On the other hand, if the accumulated reg_num is positive, see if we can
// add composite registers to the existing primordial ones.
bool from_scratch = (m_register_info.GetNumRegisters() == 0);
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 remote_arch;
if (remote_process_arch.IsValid ())
remote_arch = remote_process_arch;
else
remote_arch = remote_host_arch;
if (!target_arch.IsValid())
{
if (remote_arch.IsValid()
&& remote_arch.GetMachine() == llvm::Triple::arm
&& remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
m_register_info.HardcodeARMRegisters(from_scratch);
}
else if (target_arch.GetMachine() == llvm::Triple::arm)
{
m_register_info.HardcodeARMRegisters(from_scratch);
}
// At this point, we can finalize our register info.
m_register_info.Finalize (GetTarget().GetArchitecture());
}
Error
ProcessGDBRemote::WillLaunch (Module* module)
{
return WillLaunchOrAttach ();
}
Error
ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
{
return WillLaunchOrAttach ();
}
Error
ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
{
return WillLaunchOrAttach ();
}
Error
ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
{
Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Error 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);
// '?' Packets must be handled differently in non-stop mode
if (GetTarget().GetNonStopModeEnabled())
HandleStopReplySequence();
if (!m_target.GetArchitecture().IsValid())
{
if (m_gdb_comm.GetProcessArchitecture().IsValid())
{
m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
}
else
{
m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
}
}
const StateType state = SetThreadStopInfo (response);
if (state == eStateStopped)
{
SetPrivateState (state);
}
else
error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
}
else
error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
}
if (log)
log->Printf ("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());
}
if (log)
log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
if (error.Success())
SetUnixSignals(std::make_shared<GDBRemoteSignals>(GetTarget().GetPlatform()->GetUnixSignals()));
return error;
}
Error
ProcessGDBRemote::WillLaunchOrAttach ()
{
Error error;
m_stdio_communication.Clear ();
return error;
}
//----------------------------------------------------------------------
// Process Control
//----------------------------------------------------------------------
Error
ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
{
Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Error error;
if (log)
log->Printf ("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)
log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
__FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
else
log->Printf ("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");
ObjectFile * object_file = exe_module->GetObjectFile();
if (object_file)
{
// Make sure we aren't already connected?
if (!m_gdb_comm.IsConnected())
{
error = LaunchAndConnectToDebugserver (launch_info);
}
if (error.Success())
{
lldb_utility::PseudoTerminal pty;
const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
PlatformSP platform_sp (m_target.GetPlatform());
if (disable_stdio)
{
// set to /dev/null unless redirected to a file above
if (!stdin_file_spec)
stdin_file_spec.SetFile("/dev/null", false);
if (!stdout_file_spec)
stdout_file_spec.SetFile("/dev/null", false);
if (!stderr_file_spec)
stderr_file_spec.SetFile("/dev/null", false);
}
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) &&
pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
{
FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
if (!stdin_file_spec)
stdin_file_spec = slave_name;
if (!stdout_file_spec)
stdout_file_spec = slave_name;
if (!stderr_file_spec)
stderr_file_spec = slave_name;
}
if (log)
log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
__FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
}
if (log)
log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
__FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
stderr_file_spec ? stderr_file_spec.GetCString() : "<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 (m_target.GetArchitecture().GetArchitectureName());
const char * launch_event_data = launch_info.GetLaunchEventData();
if (launch_event_data != NULL && *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
const Args &environment = launch_info.GetEnvironmentEntries();
if (environment.GetArgumentCount())
{
size_t num_environment_entries = environment.GetArgumentCount();
for (size_t i=0; i<num_environment_entries; ++i)
{
const char *env_entry = environment.GetArgumentAtIndex(i);
if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
break;
}
}
{
// Scope for the scoped timeout object
GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);