1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/lldb-python.h"
11 #include "lldb/Host/Config.h"
12
13 // C Includes
14 #include <errno.h>
15 #include <stdlib.h>
16 #ifndef LLDB_DISABLE_POSIX
17 #include <spawn.h>
18 #include <netinet/in.h>
19 #include <sys/mman.h> // for mmap
20 #endif
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <time.h>
24
25 // C++ Includes
26 #include <algorithm>
27 #include <map>
28
29 // Other libraries and framework includes
30
31 #include "lldb/Breakpoint/Watchpoint.h"
32 #include "lldb/Interpreter/Args.h"
33 #include "lldb/Core/ArchSpec.h"
34 #include "lldb/Core/Debugger.h"
35 #include "lldb/Core/ConnectionFileDescriptor.h"
36 #include "lldb/Host/FileSpec.h"
37 #include "lldb/Core/Module.h"
38 #include "lldb/Core/ModuleSpec.h"
39 #include "lldb/Core/PluginManager.h"
40 #include "lldb/Core/State.h"
41 #include "lldb/Core/StreamFile.h"
42 #include "lldb/Core/StreamString.h"
43 #include "lldb/Core/Timer.h"
44 #include "lldb/Core/Value.h"
45 #include "lldb/Host/Symbols.h"
46 #include "lldb/Host/TimeValue.h"
47 #include "lldb/Interpreter/CommandInterpreter.h"
48 #include "lldb/Interpreter/CommandObject.h"
49 #include "lldb/Interpreter/CommandObjectMultiword.h"
50 #include "lldb/Interpreter/CommandReturnObject.h"
51 #ifndef LLDB_DISABLE_PYTHON
52 #include "lldb/Interpreter/PythonDataObjects.h"
53 #endif
54 #include "lldb/Symbol/ObjectFile.h"
55 #include "lldb/Target/DynamicLoader.h"
56 #include "lldb/Target/Target.h"
57 #include "lldb/Target/TargetList.h"
58 #include "lldb/Target/ThreadPlanCallFunction.h"
59 #include "lldb/Utility/PseudoTerminal.h"
60
61 // Project includes
62 #include "lldb/Host/Host.h"
63 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
64 #include "Plugins/Process/Utility/StopInfoMachException.h"
65 #include "Utility/StringExtractorGDBRemote.h"
66 #include "GDBRemoteRegisterContext.h"
67 #include "ProcessGDBRemote.h"
68 #include "ProcessGDBRemoteLog.h"
69 #include "ThreadGDBRemote.h"
70
71
72 namespace lldb
73 {
74 // Provide a function that can easily dump the packet history if we know a
75 // ProcessGDBRemote * value (which we can get from logs or from debugging).
76 // We need the function in the lldb namespace so it makes it into the final
77 // executable since the LLDB shared library only exports stuff in the lldb
78 // namespace. This allows you to attach with a debugger and call this
79 // function and get the packet history dumped to a file.
80 void
DumpProcessGDBRemotePacketHistory(void * p,const char * path)81 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
82 {
83 lldb_private::StreamFile strm;
84 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
85 if (error.Success())
86 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
87 }
88 }
89
90 #define DEBUGSERVER_BASENAME "debugserver"
91 using namespace lldb;
92 using namespace lldb_private;
93
94
95 namespace {
96
97 static PropertyDefinition
98 g_properties[] =
99 {
100 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
101 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
102 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
103 };
104
105 enum
106 {
107 ePropertyPacketTimeout,
108 ePropertyTargetDefinitionFile
109 };
110
111 class PluginProperties : public Properties
112 {
113 public:
114
115 static ConstString
GetSettingName()116 GetSettingName ()
117 {
118 return ProcessGDBRemote::GetPluginNameStatic();
119 }
120
PluginProperties()121 PluginProperties() :
122 Properties ()
123 {
124 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
125 m_collection_sp->Initialize(g_properties);
126 }
127
128 virtual
~PluginProperties()129 ~PluginProperties()
130 {
131 }
132
133 uint64_t
GetPacketTimeout()134 GetPacketTimeout()
135 {
136 const uint32_t idx = ePropertyPacketTimeout;
137 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
138 }
139
140 bool
SetPacketTimeout(uint64_t timeout)141 SetPacketTimeout(uint64_t timeout)
142 {
143 const uint32_t idx = ePropertyPacketTimeout;
144 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
145 }
146
147 FileSpec
GetTargetDefinitionFile() const148 GetTargetDefinitionFile () const
149 {
150 const uint32_t idx = ePropertyTargetDefinitionFile;
151 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
152 }
153 };
154
155 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
156
157 static const ProcessKDPPropertiesSP &
GetGlobalPluginProperties()158 GetGlobalPluginProperties()
159 {
160 static ProcessKDPPropertiesSP g_settings_sp;
161 if (!g_settings_sp)
162 g_settings_sp.reset (new PluginProperties ());
163 return g_settings_sp;
164 }
165
166 } // anonymous namespace end
167
168 static bool rand_initialized = false;
169
170 // TODO Randomly assigning a port is unsafe. We should get an unused
171 // ephemeral port from the kernel and make sure we reserve it before passing
172 // it to debugserver.
173
174 #if defined (__APPLE__)
175 #define LOW_PORT (IPPORT_RESERVED)
176 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
177 #else
178 #define LOW_PORT (1024u)
179 #define HIGH_PORT (49151u)
180 #endif
181
182 static inline uint16_t
get_random_port()183 get_random_port ()
184 {
185 if (!rand_initialized)
186 {
187 time_t seed = time(NULL);
188
189 rand_initialized = true;
190 srand(seed);
191 }
192 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
193 }
194
195
196 lldb_private::ConstString
GetPluginNameStatic()197 ProcessGDBRemote::GetPluginNameStatic()
198 {
199 static ConstString g_name("gdb-remote");
200 return g_name;
201 }
202
203 const char *
GetPluginDescriptionStatic()204 ProcessGDBRemote::GetPluginDescriptionStatic()
205 {
206 return "GDB Remote protocol based debugging plug-in.";
207 }
208
209 void
Terminate()210 ProcessGDBRemote::Terminate()
211 {
212 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
213 }
214
215
216 lldb::ProcessSP
CreateInstance(Target & target,Listener & listener,const FileSpec * crash_file_path)217 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
218 {
219 lldb::ProcessSP process_sp;
220 if (crash_file_path == NULL)
221 process_sp.reset (new ProcessGDBRemote (target, listener));
222 return process_sp;
223 }
224
225 bool
CanDebug(Target & target,bool plugin_specified_by_name)226 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
227 {
228 if (plugin_specified_by_name)
229 return true;
230
231 // For now we are just making sure the file exists for a given module
232 Module *exe_module = target.GetExecutableModulePointer();
233 if (exe_module)
234 {
235 ObjectFile *exe_objfile = exe_module->GetObjectFile();
236 // We can't debug core files...
237 switch (exe_objfile->GetType())
238 {
239 case ObjectFile::eTypeInvalid:
240 case ObjectFile::eTypeCoreFile:
241 case ObjectFile::eTypeDebugInfo:
242 case ObjectFile::eTypeObjectFile:
243 case ObjectFile::eTypeSharedLibrary:
244 case ObjectFile::eTypeStubLibrary:
245 return false;
246 case ObjectFile::eTypeExecutable:
247 case ObjectFile::eTypeDynamicLinker:
248 case ObjectFile::eTypeUnknown:
249 break;
250 }
251 return exe_module->GetFileSpec().Exists();
252 }
253 // However, if there is no executable module, we return true since we might be preparing to attach.
254 return true;
255 }
256
257 //----------------------------------------------------------------------
258 // ProcessGDBRemote constructor
259 //----------------------------------------------------------------------
ProcessGDBRemote(Target & target,Listener & listener)260 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
261 Process (target, listener),
262 m_flags (0),
263 m_gdb_comm(false),
264 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
265 m_last_stop_packet (),
266 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
267 m_register_info (),
268 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
269 m_async_thread (LLDB_INVALID_HOST_THREAD),
270 m_async_thread_state(eAsyncThreadNotStarted),
271 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
272 m_thread_ids (),
273 m_continue_c_tids (),
274 m_continue_C_tids (),
275 m_continue_s_tids (),
276 m_continue_S_tids (),
277 m_max_memory_size (512),
278 m_addr_to_mmap_size (),
279 m_thread_create_bp_sp (),
280 m_waiting_for_attach (false),
281 m_destroy_tried_resuming (false),
282 m_command_sp (),
283 m_breakpoint_pc_offset (0)
284 {
285 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
286 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
287 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
288 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
289 if (timeout_seconds > 0)
290 m_gdb_comm.SetPacketTimeout(timeout_seconds);
291 }
292
293 //----------------------------------------------------------------------
294 // Destructor
295 //----------------------------------------------------------------------
~ProcessGDBRemote()296 ProcessGDBRemote::~ProcessGDBRemote()
297 {
298 // m_mach_process.UnregisterNotificationCallbacks (this);
299 Clear();
300 // We need to call finalize on the process before destroying ourselves
301 // to make sure all of the broadcaster cleanup goes as planned. If we
302 // destruct this class, then Process::~Process() might have problems
303 // trying to fully destroy the broadcaster.
304 Finalize();
305
306 // The general Finalize is going to try to destroy the process and that SHOULD
307 // shut down the async thread. However, if we don't kill it it will get stranded and
308 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
309 StopAsyncThread();
310 KillDebugserverProcess();
311 }
312
313 //----------------------------------------------------------------------
314 // PluginInterface
315 //----------------------------------------------------------------------
316 ConstString
GetPluginName()317 ProcessGDBRemote::GetPluginName()
318 {
319 return GetPluginNameStatic();
320 }
321
322 uint32_t
GetPluginVersion()323 ProcessGDBRemote::GetPluginVersion()
324 {
325 return 1;
326 }
327
328 bool
ParsePythonTargetDefinition(const FileSpec & target_definition_fspec)329 ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
330 {
331 #ifndef LLDB_DISABLE_PYTHON
332 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
333 Error error;
334 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
335 if (module_object_sp)
336 {
337 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
338 &GetTarget(),
339 "gdb-server-target-definition",
340 error));
341
342 PythonDictionary target_dict(target_definition_sp);
343
344 if (target_dict)
345 {
346 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
347 if (host_info_dict)
348 {
349 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
350
351 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
352 {
353 GetTarget().SetArchitecture(host_arch);
354 }
355
356 }
357 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
358
359 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
360 {
361 return true;
362 }
363 }
364 }
365 #endif
366 return false;
367 }
368
369
370 void
BuildDynamicRegisterInfo(bool force)371 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
372 {
373 if (!force && m_register_info.GetNumRegisters() > 0)
374 return;
375
376 char packet[128];
377 m_register_info.Clear();
378 uint32_t reg_offset = 0;
379 uint32_t reg_num = 0;
380 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
381 response_type == StringExtractorGDBRemote::eResponse;
382 ++reg_num)
383 {
384 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
385 assert (packet_len < (int)sizeof(packet));
386 StringExtractorGDBRemote response;
387 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
388 {
389 response_type = response.GetResponseType();
390 if (response_type == StringExtractorGDBRemote::eResponse)
391 {
392 std::string name;
393 std::string value;
394 ConstString reg_name;
395 ConstString alt_name;
396 ConstString set_name;
397 std::vector<uint32_t> value_regs;
398 std::vector<uint32_t> invalidate_regs;
399 RegisterInfo reg_info = { NULL, // Name
400 NULL, // Alt name
401 0, // byte size
402 reg_offset, // offset
403 eEncodingUint, // encoding
404 eFormatHex, // formate
405 {
406 LLDB_INVALID_REGNUM, // GCC reg num
407 LLDB_INVALID_REGNUM, // DWARF reg num
408 LLDB_INVALID_REGNUM, // generic reg num
409 reg_num, // GDB reg num
410 reg_num // native register number
411 },
412 NULL,
413 NULL
414 };
415
416 while (response.GetNameColonValue(name, value))
417 {
418 if (name.compare("name") == 0)
419 {
420 reg_name.SetCString(value.c_str());
421 }
422 else if (name.compare("alt-name") == 0)
423 {
424 alt_name.SetCString(value.c_str());
425 }
426 else if (name.compare("bitsize") == 0)
427 {
428 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
429 }
430 else if (name.compare("offset") == 0)
431 {
432 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
433 if (reg_offset != offset)
434 {
435 reg_offset = offset;
436 }
437 }
438 else if (name.compare("encoding") == 0)
439 {
440 const Encoding encoding = Args::StringToEncoding (value.c_str());
441 if (encoding != eEncodingInvalid)
442 reg_info.encoding = encoding;
443 }
444 else if (name.compare("format") == 0)
445 {
446 Format format = eFormatInvalid;
447 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
448 reg_info.format = format;
449 else if (value.compare("binary") == 0)
450 reg_info.format = eFormatBinary;
451 else if (value.compare("decimal") == 0)
452 reg_info.format = eFormatDecimal;
453 else if (value.compare("hex") == 0)
454 reg_info.format = eFormatHex;
455 else if (value.compare("float") == 0)
456 reg_info.format = eFormatFloat;
457 else if (value.compare("vector-sint8") == 0)
458 reg_info.format = eFormatVectorOfSInt8;
459 else if (value.compare("vector-uint8") == 0)
460 reg_info.format = eFormatVectorOfUInt8;
461 else if (value.compare("vector-sint16") == 0)
462 reg_info.format = eFormatVectorOfSInt16;
463 else if (value.compare("vector-uint16") == 0)
464 reg_info.format = eFormatVectorOfUInt16;
465 else if (value.compare("vector-sint32") == 0)
466 reg_info.format = eFormatVectorOfSInt32;
467 else if (value.compare("vector-uint32") == 0)
468 reg_info.format = eFormatVectorOfUInt32;
469 else if (value.compare("vector-float32") == 0)
470 reg_info.format = eFormatVectorOfFloat32;
471 else if (value.compare("vector-uint128") == 0)
472 reg_info.format = eFormatVectorOfUInt128;
473 }
474 else if (name.compare("set") == 0)
475 {
476 set_name.SetCString(value.c_str());
477 }
478 else if (name.compare("gcc") == 0)
479 {
480 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
481 }
482 else if (name.compare("dwarf") == 0)
483 {
484 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
485 }
486 else if (name.compare("generic") == 0)
487 {
488 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
489 }
490 else if (name.compare("container-regs") == 0)
491 {
492 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
493 value_pair.second = value;
494 do
495 {
496 value_pair = value_pair.second.split(',');
497 if (!value_pair.first.empty())
498 {
499 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
500 if (reg != LLDB_INVALID_REGNUM)
501 value_regs.push_back (reg);
502 }
503 } while (!value_pair.second.empty());
504 }
505 else if (name.compare("invalidate-regs") == 0)
506 {
507 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
508 value_pair.second = value;
509 do
510 {
511 value_pair = value_pair.second.split(',');
512 if (!value_pair.first.empty())
513 {
514 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
515 if (reg != LLDB_INVALID_REGNUM)
516 invalidate_regs.push_back (reg);
517 }
518 } while (!value_pair.second.empty());
519 }
520 }
521
522 reg_info.byte_offset = reg_offset;
523 assert (reg_info.byte_size != 0);
524 reg_offset += reg_info.byte_size;
525 if (!value_regs.empty())
526 {
527 value_regs.push_back(LLDB_INVALID_REGNUM);
528 reg_info.value_regs = value_regs.data();
529 }
530 if (!invalidate_regs.empty())
531 {
532 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
533 reg_info.invalidate_regs = invalidate_regs.data();
534 }
535
536 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
537 }
538 else
539 {
540 break; // ensure exit before reg_num is incremented
541 }
542 }
543 else
544 {
545 break;
546 }
547 }
548
549 // Check if qHostInfo specified a specific packet timeout for this connection.
550 // If so then lets update our setting so the user knows what the timeout is
551 // and can see it.
552 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
553 if (host_packet_timeout)
554 {
555 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
556 }
557
558
559 if (reg_num == 0)
560 {
561 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
562
563 if (target_definition_fspec)
564 {
565 // See if we can get register definitions from a python file
566 if (ParsePythonTargetDefinition (target_definition_fspec))
567 return;
568 }
569 }
570
571 // We didn't get anything if the accumulated reg_num is zero. See if we are
572 // debugging ARM and fill with a hard coded register set until we can get an
573 // updated debugserver down on the devices.
574 // On the other hand, if the accumulated reg_num is positive, see if we can
575 // add composite registers to the existing primordial ones.
576 bool from_scratch = (reg_num == 0);
577
578 const ArchSpec &target_arch = GetTarget().GetArchitecture();
579 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
580 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
581
582 // Use the process' architecture instead of the host arch, if available
583 ArchSpec remote_arch;
584 if (remote_process_arch.IsValid ())
585 remote_arch = remote_process_arch;
586 else
587 remote_arch = remote_host_arch;
588
589 if (!target_arch.IsValid())
590 {
591 if (remote_arch.IsValid()
592 && remote_arch.GetMachine() == llvm::Triple::arm
593 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
594 m_register_info.HardcodeARMRegisters(from_scratch);
595 }
596 else if (target_arch.GetMachine() == llvm::Triple::arm)
597 {
598 m_register_info.HardcodeARMRegisters(from_scratch);
599 }
600
601 // At this point, we can finalize our register info.
602 m_register_info.Finalize ();
603 }
604
605 Error
WillLaunch(Module * module)606 ProcessGDBRemote::WillLaunch (Module* module)
607 {
608 return WillLaunchOrAttach ();
609 }
610
611 Error
WillAttachToProcessWithID(lldb::pid_t pid)612 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
613 {
614 return WillLaunchOrAttach ();
615 }
616
617 Error
WillAttachToProcessWithName(const char * process_name,bool wait_for_launch)618 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
619 {
620 return WillLaunchOrAttach ();
621 }
622
623 Error
DoConnectRemote(Stream * strm,const char * remote_url)624 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
625 {
626 Error error (WillLaunchOrAttach ());
627
628 if (error.Fail())
629 return error;
630
631 error = ConnectToDebugserver (remote_url);
632
633 if (error.Fail())
634 return error;
635 StartAsyncThread ();
636
637 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
638 if (pid == LLDB_INVALID_PROCESS_ID)
639 {
640 // We don't have a valid process ID, so note that we are connected
641 // and could now request to launch or attach, or get remote process
642 // listings...
643 SetPrivateState (eStateConnected);
644 }
645 else
646 {
647 // We have a valid process
648 SetID (pid);
649 GetThreadList();
650 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
651 {
652 if (!m_target.GetArchitecture().IsValid())
653 {
654 if (m_gdb_comm.GetProcessArchitecture().IsValid())
655 {
656 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
657 }
658 else
659 {
660 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
661 }
662 }
663
664 const StateType state = SetThreadStopInfo (m_last_stop_packet);
665 if (state == eStateStopped)
666 {
667 SetPrivateState (state);
668 }
669 else
670 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
671 }
672 else
673 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
674 }
675
676 if (error.Success()
677 && !GetTarget().GetArchitecture().IsValid()
678 && m_gdb_comm.GetHostArchitecture().IsValid())
679 {
680 // Prefer the *process'* architecture over that of the *host*, if available.
681 if (m_gdb_comm.GetProcessArchitecture().IsValid())
682 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
683 else
684 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
685 }
686
687 return error;
688 }
689
690 Error
WillLaunchOrAttach()691 ProcessGDBRemote::WillLaunchOrAttach ()
692 {
693 Error error;
694 m_stdio_communication.Clear ();
695 return error;
696 }
697
698 //----------------------------------------------------------------------
699 // Process Control
700 //----------------------------------------------------------------------
701 Error
DoLaunch(Module * exe_module,ProcessLaunchInfo & launch_info)702 ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
703 {
704 Error error;
705
706 uint32_t launch_flags = launch_info.GetFlags().Get();
707 const char *stdin_path = NULL;
708 const char *stdout_path = NULL;
709 const char *stderr_path = NULL;
710 const char *working_dir = launch_info.GetWorkingDirectory();
711
712 const ProcessLaunchInfo::FileAction *file_action;
713 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
714 if (file_action)
715 {
716 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
717 stdin_path = file_action->GetPath();
718 }
719 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
720 if (file_action)
721 {
722 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
723 stdout_path = file_action->GetPath();
724 }
725 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
726 if (file_action)
727 {
728 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
729 stderr_path = file_action->GetPath();
730 }
731
732 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
733 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
734 // ::LogSetLogFile ("/dev/stdout");
735 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
736
737 ObjectFile * object_file = exe_module->GetObjectFile();
738 if (object_file)
739 {
740 // Make sure we aren't already connected?
741 if (!m_gdb_comm.IsConnected())
742 {
743 error = LaunchAndConnectToDebugserver (launch_info);
744 }
745
746 if (error.Success())
747 {
748 lldb_utility::PseudoTerminal pty;
749 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
750
751 // If the debugserver is local and we aren't disabling STDIO, lets use
752 // a pseudo terminal to instead of relying on the 'O' packets for stdio
753 // since 'O' packets can really slow down debugging if the inferior
754 // does a lot of output.
755 PlatformSP platform_sp (m_target.GetPlatform());
756 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
757 {
758 const char *slave_name = NULL;
759 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
760 {
761 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
762 slave_name = pty.GetSlaveName (NULL, 0);
763 }
764 if (stdin_path == NULL)
765 stdin_path = slave_name;
766
767 if (stdout_path == NULL)
768 stdout_path = slave_name;
769
770 if (stderr_path == NULL)
771 stderr_path = slave_name;
772 }
773
774 // Set STDIN to /dev/null if we want STDIO disabled or if either
775 // STDOUT or STDERR have been set to something and STDIN hasn't
776 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
777 stdin_path = "/dev/null";
778
779 // Set STDOUT to /dev/null if we want STDIO disabled or if either
780 // STDIN or STDERR have been set to something and STDOUT hasn't
781 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
782 stdout_path = "/dev/null";
783
784 // Set STDERR to /dev/null if we want STDIO disabled or if either
785 // STDIN or STDOUT have been set to something and STDERR hasn't
786 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
787 stderr_path = "/dev/null";
788
789 if (stdin_path)
790 m_gdb_comm.SetSTDIN (stdin_path);
791 if (stdout_path)
792 m_gdb_comm.SetSTDOUT (stdout_path);
793 if (stderr_path)
794 m_gdb_comm.SetSTDERR (stderr_path);
795
796 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
797
798 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
799
800 if (working_dir && working_dir[0])
801 {
802 m_gdb_comm.SetWorkingDir (working_dir);
803 }
804
805 // Send the environment and the program + arguments after we connect
806 const Args &environment = launch_info.GetEnvironmentEntries();
807 if (environment.GetArgumentCount())
808 {
809 size_t num_environment_entries = environment.GetArgumentCount();
810 for (size_t i=0; i<num_environment_entries; ++i)
811 {
812 const char *env_entry = environment.GetArgumentAtIndex(i);
813 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
814 break;
815 }
816 }
817
818 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
819 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
820 if (arg_packet_err == 0)
821 {
822 std::string error_str;
823 if (m_gdb_comm.GetLaunchSuccess (error_str))
824 {
825 SetID (m_gdb_comm.GetCurrentProcessID ());
826 }
827 else
828 {
829 error.SetErrorString (error_str.c_str());
830 }
831 }
832 else
833 {
834 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
835 }
836
837 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
838
839 if (GetID() == LLDB_INVALID_PROCESS_ID)
840 {
841 if (log)
842 log->Printf("failed to connect to debugserver: %s", error.AsCString());
843 KillDebugserverProcess ();
844 return error;
845 }
846
847 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
848 {
849 if (!m_target.GetArchitecture().IsValid())
850 {
851 if (m_gdb_comm.GetProcessArchitecture().IsValid())
852 {
853 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
854 }
855 else
856 {
857 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
858 }
859 }
860
861 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
862
863 if (!disable_stdio)
864 {
865 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
866 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
867 }
868 }
869 }
870 else
871 {
872 if (log)
873 log->Printf("failed to connect to debugserver: %s", error.AsCString());
874 }
875 }
876 else
877 {
878 // Set our user ID to an invalid process ID.
879 SetID(LLDB_INVALID_PROCESS_ID);
880 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
881 exe_module->GetFileSpec().GetFilename().AsCString(),
882 exe_module->GetArchitecture().GetArchitectureName());
883 }
884 return error;
885
886 }
887
888
889 Error
ConnectToDebugserver(const char * connect_url)890 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
891 {
892 Error error;
893 // Only connect if we have a valid connect URL
894
895 if (connect_url && connect_url[0])
896 {
897 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
898 if (conn_ap.get())
899 {
900 const uint32_t max_retry_count = 50;
901 uint32_t retry_count = 0;
902 while (!m_gdb_comm.IsConnected())
903 {
904 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
905 {
906 m_gdb_comm.SetConnection (conn_ap.release());
907 break;
908 }
909 else if (error.WasInterrupted())
910 {
911 // If we were interrupted, don't keep retrying.
912 break;
913 }
914
915 retry_count++;
916
917 if (retry_count >= max_retry_count)
918 break;
919
920 usleep (100000);
921 }
922 }
923 }
924
925 if (!m_gdb_comm.IsConnected())
926 {
927 if (error.Success())
928 error.SetErrorString("not connected to remote gdb server");
929 return error;
930 }
931
932 // We always seem to be able to open a connection to a local port
933 // so we need to make sure we can then send data to it. If we can't
934 // then we aren't actually connected to anything, so try and do the
935 // handshake with the remote GDB server and make sure that goes
936 // alright.
937 if (!m_gdb_comm.HandshakeWithServer (&error))
938 {
939 m_gdb_comm.Disconnect();
940 if (error.Success())
941 error.SetErrorString("not connected to remote gdb server");
942 return error;
943 }
944 m_gdb_comm.GetThreadSuffixSupported ();
945 m_gdb_comm.GetListThreadsInStopReplySupported ();
946 m_gdb_comm.GetHostInfo ();
947 m_gdb_comm.GetVContSupported ('c');
948 m_gdb_comm.GetVAttachOrWaitSupported();
949
950 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
951 for (size_t idx = 0; idx < num_cmds; idx++)
952 {
953 StringExtractorGDBRemote response;
954 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
955 }
956 return error;
957 }
958
959 void
DidLaunchOrAttach()960 ProcessGDBRemote::DidLaunchOrAttach ()
961 {
962 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
963 if (log)
964 log->Printf ("ProcessGDBRemote::DidLaunch()");
965 if (GetID() != LLDB_INVALID_PROCESS_ID)
966 {
967 BuildDynamicRegisterInfo (false);
968
969 // See if the GDB server supports the qHostInfo information
970
971 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
972
973 // See if the GDB server supports the qProcessInfo packet, if so
974 // prefer that over the Host information as it will be more specific
975 // to our process.
976
977 if (m_gdb_comm.GetProcessArchitecture().IsValid())
978 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
979
980 if (gdb_remote_arch.IsValid())
981 {
982 ArchSpec &target_arch = GetTarget().GetArchitecture();
983
984 if (target_arch.IsValid())
985 {
986 // If the remote host is ARM and we have apple as the vendor, then
987 // ARM executables and shared libraries can have mixed ARM architectures.
988 // You can have an armv6 executable, and if the host is armv7, then the
989 // system will load the best possible architecture for all shared libraries
990 // it has, so we really need to take the remote host architecture as our
991 // defacto architecture in this case.
992
993 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
994 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
995 {
996 target_arch = gdb_remote_arch;
997 }
998 else
999 {
1000 // Fill in what is missing in the triple
1001 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
1002 llvm::Triple &target_triple = target_arch.GetTriple();
1003 if (target_triple.getVendorName().size() == 0)
1004 {
1005 target_triple.setVendor (remote_triple.getVendor());
1006
1007 if (target_triple.getOSName().size() == 0)
1008 {
1009 target_triple.setOS (remote_triple.getOS());
1010
1011 if (target_triple.getEnvironmentName().size() == 0)
1012 target_triple.setEnvironment (remote_triple.getEnvironment());
1013 }
1014 }
1015 }
1016 }
1017 else
1018 {
1019 // The target doesn't have a valid architecture yet, set it from
1020 // the architecture we got from the remote GDB server
1021 target_arch = gdb_remote_arch;
1022 }
1023 }
1024 }
1025 }
1026
1027 void
DidLaunch()1028 ProcessGDBRemote::DidLaunch ()
1029 {
1030 DidLaunchOrAttach ();
1031 }
1032
1033 Error
DoAttachToProcessWithID(lldb::pid_t attach_pid)1034 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
1035 {
1036 ProcessAttachInfo attach_info;
1037 return DoAttachToProcessWithID(attach_pid, attach_info);
1038 }
1039
1040 Error
DoAttachToProcessWithID(lldb::pid_t attach_pid,const ProcessAttachInfo & attach_info)1041 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1042 {
1043 Error error;
1044 // Clear out and clean up from any current state
1045 Clear();
1046 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1047 {
1048 // Make sure we aren't already connected?
1049 if (!m_gdb_comm.IsConnected())
1050 {
1051 error = LaunchAndConnectToDebugserver (attach_info);
1052
1053 if (error.Fail())
1054 {
1055 const char *error_string = error.AsCString();
1056 if (error_string == NULL)
1057 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1058
1059 SetExitStatus (-1, error_string);
1060 }
1061 }
1062
1063 if (error.Success())
1064 {
1065 char packet[64];
1066 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1067 SetID (attach_pid);
1068 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1069 }
1070 }
1071 return error;
1072 }
1073
1074 Error
DoAttachToProcessWithName(const char * process_name,const ProcessAttachInfo & attach_info)1075 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1076 {
1077 Error error;
1078 // Clear out and clean up from any current state
1079 Clear();
1080
1081 if (process_name && process_name[0])
1082 {
1083 // Make sure we aren't already connected?
1084 if (!m_gdb_comm.IsConnected())
1085 {
1086 error = LaunchAndConnectToDebugserver (attach_info);
1087
1088 if (error.Fail())
1089 {
1090 const char *error_string = error.AsCString();
1091 if (error_string == NULL)
1092 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1093
1094 SetExitStatus (-1, error_string);
1095 }
1096 }
1097
1098 if (error.Success())
1099 {
1100 StreamString packet;
1101
1102 if (attach_info.GetWaitForLaunch())
1103 {
1104 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1105 {
1106 packet.PutCString ("vAttachWait");
1107 }
1108 else
1109 {
1110 if (attach_info.GetIgnoreExisting())
1111 packet.PutCString("vAttachWait");
1112 else
1113 packet.PutCString ("vAttachOrWait");
1114 }
1115 }
1116 else
1117 packet.PutCString("vAttachName");
1118 packet.PutChar(';');
1119 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1120
1121 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1122
1123 }
1124 }
1125 return error;
1126 }
1127
1128
1129 bool
SetExitStatus(int exit_status,const char * cstr)1130 ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1131 {
1132 m_gdb_comm.Disconnect();
1133 return Process::SetExitStatus (exit_status, cstr);
1134 }
1135
1136 void
DidAttach()1137 ProcessGDBRemote::DidAttach ()
1138 {
1139 DidLaunchOrAttach ();
1140 }
1141
1142
1143 Error
WillResume()1144 ProcessGDBRemote::WillResume ()
1145 {
1146 m_continue_c_tids.clear();
1147 m_continue_C_tids.clear();
1148 m_continue_s_tids.clear();
1149 m_continue_S_tids.clear();
1150 return Error();
1151 }
1152
1153 Error
DoResume()1154 ProcessGDBRemote::DoResume ()
1155 {
1156 Error error;
1157 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1158 if (log)
1159 log->Printf ("ProcessGDBRemote::Resume()");
1160
1161 Listener listener ("gdb-remote.resume-packet-sent");
1162 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1163 {
1164 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1165
1166 const size_t num_threads = GetThreadList().GetSize();
1167
1168 StreamString continue_packet;
1169 bool continue_packet_error = false;
1170 if (m_gdb_comm.HasAnyVContSupport ())
1171 {
1172 if (m_continue_c_tids.size() == num_threads ||
1173 (m_continue_c_tids.empty() &&
1174 m_continue_C_tids.empty() &&
1175 m_continue_s_tids.empty() &&
1176 m_continue_S_tids.empty()))
1177 {
1178 // All threads are continuing, just send a "c" packet
1179 continue_packet.PutCString ("c");
1180 }
1181 else
1182 {
1183 continue_packet.PutCString ("vCont");
1184
1185 if (!m_continue_c_tids.empty())
1186 {
1187 if (m_gdb_comm.GetVContSupported ('c'))
1188 {
1189 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos)
1190 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1191 }
1192 else
1193 continue_packet_error = true;
1194 }
1195
1196 if (!continue_packet_error && !m_continue_C_tids.empty())
1197 {
1198 if (m_gdb_comm.GetVContSupported ('C'))
1199 {
1200 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos)
1201 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1202 }
1203 else
1204 continue_packet_error = true;
1205 }
1206
1207 if (!continue_packet_error && !m_continue_s_tids.empty())
1208 {
1209 if (m_gdb_comm.GetVContSupported ('s'))
1210 {
1211 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos)
1212 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1213 }
1214 else
1215 continue_packet_error = true;
1216 }
1217
1218 if (!continue_packet_error && !m_continue_S_tids.empty())
1219 {
1220 if (m_gdb_comm.GetVContSupported ('S'))
1221 {
1222 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos)
1223 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1224 }
1225 else
1226 continue_packet_error = true;
1227 }
1228
1229 if (continue_packet_error)
1230 continue_packet.GetString().clear();
1231 }
1232 }
1233 else
1234 continue_packet_error = true;
1235
1236 if (continue_packet_error)
1237 {
1238 // Either no vCont support, or we tried to use part of the vCont
1239 // packet that wasn't supported by the remote GDB server.
1240 // We need to try and make a simple packet that can do our continue
1241 const size_t num_continue_c_tids = m_continue_c_tids.size();
1242 const size_t num_continue_C_tids = m_continue_C_tids.size();
1243 const size_t num_continue_s_tids = m_continue_s_tids.size();
1244 const size_t num_continue_S_tids = m_continue_S_tids.size();
1245 if (num_continue_c_tids > 0)
1246 {
1247 if (num_continue_c_tids == num_threads)
1248 {
1249 // All threads are resuming...
1250 m_gdb_comm.SetCurrentThreadForRun (-1);
1251 continue_packet.PutChar ('c');
1252 continue_packet_error = false;
1253 }
1254 else if (num_continue_c_tids == 1 &&
1255 num_continue_C_tids == 0 &&
1256 num_continue_s_tids == 0 &&
1257 num_continue_S_tids == 0 )
1258 {
1259 // Only one thread is continuing
1260 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1261 continue_packet.PutChar ('c');
1262 continue_packet_error = false;
1263 }
1264 }
1265
1266 if (continue_packet_error && num_continue_C_tids > 0)
1267 {
1268 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1269 num_continue_C_tids > 0 &&
1270 num_continue_s_tids == 0 &&
1271 num_continue_S_tids == 0 )
1272 {
1273 const int continue_signo = m_continue_C_tids.front().second;
1274 // Only one thread is continuing
1275 if (num_continue_C_tids > 1)
1276 {
1277 // More that one thread with a signal, yet we don't have
1278 // vCont support and we are being asked to resume each
1279 // thread with a signal, we need to make sure they are
1280 // all the same signal, or we can't issue the continue
1281 // accurately with the current support...
1282 if (num_continue_C_tids > 1)
1283 {
1284 continue_packet_error = false;
1285 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1286 {
1287 if (m_continue_C_tids[i].second != continue_signo)
1288 continue_packet_error = true;
1289 }
1290 }
1291 if (!continue_packet_error)
1292 m_gdb_comm.SetCurrentThreadForRun (-1);
1293 }
1294 else
1295 {
1296 // Set the continue thread ID
1297 continue_packet_error = false;
1298 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1299 }
1300 if (!continue_packet_error)
1301 {
1302 // Add threads continuing with the same signo...
1303 continue_packet.Printf("C%2.2x", continue_signo);
1304 }
1305 }
1306 }
1307
1308 if (continue_packet_error && num_continue_s_tids > 0)
1309 {
1310 if (num_continue_s_tids == num_threads)
1311 {
1312 // All threads are resuming...
1313 m_gdb_comm.SetCurrentThreadForRun (-1);
1314 continue_packet.PutChar ('s');
1315 continue_packet_error = false;
1316 }
1317 else if (num_continue_c_tids == 0 &&
1318 num_continue_C_tids == 0 &&
1319 num_continue_s_tids == 1 &&
1320 num_continue_S_tids == 0 )
1321 {
1322 // Only one thread is stepping
1323 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1324 continue_packet.PutChar ('s');
1325 continue_packet_error = false;
1326 }
1327 }
1328
1329 if (!continue_packet_error && num_continue_S_tids > 0)
1330 {
1331 if (num_continue_S_tids == num_threads)
1332 {
1333 const int step_signo = m_continue_S_tids.front().second;
1334 // Are all threads trying to step with the same signal?
1335 continue_packet_error = false;
1336 if (num_continue_S_tids > 1)
1337 {
1338 for (size_t i=1; i<num_threads; ++i)
1339 {
1340 if (m_continue_S_tids[i].second != step_signo)
1341 continue_packet_error = true;
1342 }
1343 }
1344 if (!continue_packet_error)
1345 {
1346 // Add threads stepping with the same signo...
1347 m_gdb_comm.SetCurrentThreadForRun (-1);
1348 continue_packet.Printf("S%2.2x", step_signo);
1349 }
1350 }
1351 else if (num_continue_c_tids == 0 &&
1352 num_continue_C_tids == 0 &&
1353 num_continue_s_tids == 0 &&
1354 num_continue_S_tids == 1 )
1355 {
1356 // Only one thread is stepping with signal
1357 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1358 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1359 continue_packet_error = false;
1360 }
1361 }
1362 }
1363
1364 if (continue_packet_error)
1365 {
1366 error.SetErrorString ("can't make continue packet for this resume");
1367 }
1368 else
1369 {
1370 EventSP event_sp;
1371 TimeValue timeout;
1372 timeout = TimeValue::Now();
1373 timeout.OffsetWithSeconds (5);
1374 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1375 {
1376 error.SetErrorString ("Trying to resume but the async thread is dead.");
1377 if (log)
1378 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1379 return error;
1380 }
1381
1382 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1383
1384 if (listener.WaitForEvent (&timeout, event_sp) == false)
1385 {
1386 error.SetErrorString("Resume timed out.");
1387 if (log)
1388 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1389 }
1390 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1391 {
1392 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1393 if (log)
1394 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1395 return error;
1396 }
1397 }
1398 }
1399
1400 return error;
1401 }
1402
1403 void
ClearThreadIDList()1404 ProcessGDBRemote::ClearThreadIDList ()
1405 {
1406 Mutex::Locker locker(m_thread_list_real.GetMutex());
1407 m_thread_ids.clear();
1408 }
1409
1410 bool
UpdateThreadIDList()1411 ProcessGDBRemote::UpdateThreadIDList ()
1412 {
1413 Mutex::Locker locker(m_thread_list_real.GetMutex());
1414 bool sequence_mutex_unavailable = false;
1415 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1416 if (sequence_mutex_unavailable)
1417 {
1418 return false; // We just didn't get the list
1419 }
1420 return true;
1421 }
1422
1423 bool
UpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)1424 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1425 {
1426 // locker will keep a mutex locked until it goes out of scope
1427 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1428 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1429 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1430
1431 size_t num_thread_ids = m_thread_ids.size();
1432 // The "m_thread_ids" thread ID list should always be updated after each stop
1433 // reply packet, but in case it isn't, update it here.
1434 if (num_thread_ids == 0)
1435 {
1436 if (!UpdateThreadIDList ())
1437 return false;
1438 num_thread_ids = m_thread_ids.size();
1439 }
1440
1441 ThreadList old_thread_list_copy(old_thread_list);
1442 if (num_thread_ids > 0)
1443 {
1444 for (size_t i=0; i<num_thread_ids; ++i)
1445 {
1446 tid_t tid = m_thread_ids[i];
1447 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1448 if (!thread_sp)
1449 {
1450 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1451 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1452 log->Printf(
1453 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1454 __FUNCTION__,
1455 thread_sp.get(),
1456 thread_sp->GetID());
1457 }
1458 else
1459 {
1460 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1461 log->Printf(
1462 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1463 __FUNCTION__,
1464 thread_sp.get(),
1465 thread_sp->GetID());
1466 }
1467 new_thread_list.AddThread(thread_sp);
1468 }
1469 }
1470
1471 // Whatever that is left in old_thread_list_copy are not
1472 // present in new_thread_list. Remove non-existent threads from internal id table.
1473 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1474 for (size_t i=0; i<old_num_thread_ids; i++)
1475 {
1476 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1477 if (old_thread_sp)
1478 {
1479 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1480 m_thread_id_to_index_id_map.erase(old_thread_id);
1481 }
1482 }
1483
1484 return true;
1485 }
1486
1487
1488 StateType
SetThreadStopInfo(StringExtractor & stop_packet)1489 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1490 {
1491 stop_packet.SetFilePos (0);
1492 const char stop_type = stop_packet.GetChar();
1493 switch (stop_type)
1494 {
1495 case 'T':
1496 case 'S':
1497 {
1498 // This is a bit of a hack, but is is required. If we did exec, we
1499 // need to clear our thread lists and also know to rebuild our dynamic
1500 // register info before we lookup and threads and populate the expedited
1501 // register values so we need to know this right away so we can cleanup
1502 // and update our registers.
1503 const uint32_t stop_id = GetStopID();
1504 if (stop_id == 0)
1505 {
1506 // Our first stop, make sure we have a process ID, and also make
1507 // sure we know about our registers
1508 if (GetID() == LLDB_INVALID_PROCESS_ID)
1509 {
1510 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
1511 if (pid != LLDB_INVALID_PROCESS_ID)
1512 SetID (pid);
1513 }
1514 BuildDynamicRegisterInfo (true);
1515 }
1516 // Stop with signal and thread info
1517 const uint8_t signo = stop_packet.GetHexU8();
1518 std::string name;
1519 std::string value;
1520 std::string thread_name;
1521 std::string reason;
1522 std::string description;
1523 uint32_t exc_type = 0;
1524 std::vector<addr_t> exc_data;
1525 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1526 ThreadSP thread_sp;
1527 ThreadGDBRemote *gdb_thread = NULL;
1528
1529 while (stop_packet.GetNameColonValue(name, value))
1530 {
1531 if (name.compare("metype") == 0)
1532 {
1533 // exception type in big endian hex
1534 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1535 }
1536 else if (name.compare("medata") == 0)
1537 {
1538 // exception data in big endian hex
1539 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1540 }
1541 else if (name.compare("thread") == 0)
1542 {
1543 // thread in big endian hex
1544 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1545 // m_thread_list_real does have its own mutex, but we need to
1546 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1547 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1548 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1549 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1550
1551 if (!thread_sp)
1552 {
1553 // Create the thread if we need to
1554 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1555 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1556 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1557 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1558 __FUNCTION__,
1559 thread_sp.get(),
1560 thread_sp->GetID());
1561
1562 m_thread_list_real.AddThread(thread_sp);
1563 }
1564 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1565
1566 }
1567 else if (name.compare("threads") == 0)
1568 {
1569 Mutex::Locker locker(m_thread_list_real.GetMutex());
1570 m_thread_ids.clear();
1571 // A comma separated list of all threads in the current
1572 // process that includes the thread for this stop reply
1573 // packet
1574 size_t comma_pos;
1575 lldb::tid_t tid;
1576 while ((comma_pos = value.find(',')) != std::string::npos)
1577 {
1578 value[comma_pos] = '\0';
1579 // thread in big endian hex
1580 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1581 if (tid != LLDB_INVALID_THREAD_ID)
1582 m_thread_ids.push_back (tid);
1583 value.erase(0, comma_pos + 1);
1584
1585 }
1586 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1587 if (tid != LLDB_INVALID_THREAD_ID)
1588 m_thread_ids.push_back (tid);
1589 }
1590 else if (name.compare("hexname") == 0)
1591 {
1592 StringExtractor name_extractor;
1593 // Swap "value" over into "name_extractor"
1594 name_extractor.GetStringRef().swap(value);
1595 // Now convert the HEX bytes into a string value
1596 name_extractor.GetHexByteString (value);
1597 thread_name.swap (value);
1598 }
1599 else if (name.compare("name") == 0)
1600 {
1601 thread_name.swap (value);
1602 }
1603 else if (name.compare("qaddr") == 0)
1604 {
1605 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1606 }
1607 else if (name.compare("reason") == 0)
1608 {
1609 reason.swap(value);
1610 }
1611 else if (name.compare("description") == 0)
1612 {
1613 StringExtractor desc_extractor;
1614 // Swap "value" over into "name_extractor"
1615 desc_extractor.GetStringRef().swap(value);
1616 // Now convert the HEX bytes into a string value
1617 desc_extractor.GetHexByteString (thread_name);
1618 }
1619 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1620 {
1621 // We have a register number that contains an expedited
1622 // register value. Lets supply this register to our thread
1623 // so it won't have to go and read it.
1624 if (gdb_thread)
1625 {
1626 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1627
1628 if (reg != UINT32_MAX)
1629 {
1630 StringExtractor reg_value_extractor;
1631 // Swap "value" over into "reg_value_extractor"
1632 reg_value_extractor.GetStringRef().swap(value);
1633 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
1634 {
1635 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1636 name.c_str(),
1637 reg,
1638 reg,
1639 reg_value_extractor.GetStringRef().c_str(),
1640 stop_packet.GetStringRef().c_str());
1641 }
1642 }
1643 }
1644 }
1645 }
1646
1647 // If the response is old style 'S' packet which does not provide us with thread information
1648 // then update the thread list and choose the first one.
1649 if (!thread_sp)
1650 {
1651 UpdateThreadIDList ();
1652
1653 if (!m_thread_ids.empty ())
1654 {
1655 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1656 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false);
1657 if (thread_sp)
1658 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ());
1659 }
1660 }
1661
1662 if (thread_sp)
1663 {
1664 // Clear the stop info just in case we don't set it to anything
1665 thread_sp->SetStopInfo (StopInfoSP());
1666
1667 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1668 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1669 if (exc_type != 0)
1670 {
1671 const size_t exc_data_size = exc_data.size();
1672
1673 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1674 exc_type,
1675 exc_data_size,
1676 exc_data_size >= 1 ? exc_data[0] : 0,
1677 exc_data_size >= 2 ? exc_data[1] : 0,
1678 exc_data_size >= 3 ? exc_data[2] : 0));
1679 }
1680 else
1681 {
1682 bool handled = false;
1683 bool did_exec = false;
1684 if (!reason.empty())
1685 {
1686 if (reason.compare("trace") == 0)
1687 {
1688 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1689 handled = true;
1690 }
1691 else if (reason.compare("breakpoint") == 0)
1692 {
1693 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1694 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1695 if (bp_site_sp)
1696 {
1697 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1698 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1699 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1700 handled = true;
1701 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1702 {
1703 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1704 }
1705 else
1706 {
1707 StopInfoSP invalid_stop_info_sp;
1708 thread_sp->SetStopInfo (invalid_stop_info_sp);
1709 }
1710 }
1711
1712 }
1713 else if (reason.compare("trap") == 0)
1714 {
1715 // Let the trap just use the standard signal stop reason below...
1716 }
1717 else if (reason.compare("watchpoint") == 0)
1718 {
1719 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1720 // TODO: locate the watchpoint somehow...
1721 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
1722 handled = true;
1723 }
1724 else if (reason.compare("exception") == 0)
1725 {
1726 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
1727 handled = true;
1728 }
1729 else if (reason.compare("exec") == 0)
1730 {
1731 did_exec = true;
1732 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1733 handled = true;
1734 }
1735 }
1736
1737 if (!handled && signo && did_exec == false)
1738 {
1739 if (signo == SIGTRAP)
1740 {
1741 // Currently we are going to assume SIGTRAP means we are either
1742 // hitting a breakpoint or hardware single stepping.
1743 handled = true;
1744 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1745 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1746
1747 if (bp_site_sp)
1748 {
1749 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1750 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1751 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1752 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1753 {
1754 if(m_breakpoint_pc_offset != 0)
1755 thread_sp->GetRegisterContext()->SetPC(pc);
1756 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1757 }
1758 else
1759 {
1760 StopInfoSP invalid_stop_info_sp;
1761 thread_sp->SetStopInfo (invalid_stop_info_sp);
1762 }
1763 }
1764 else
1765 {
1766 // If we were stepping then assume the stop was the result of the trace. If we were
1767 // not stepping then report the SIGTRAP.
1768 // FIXME: We are still missing the case where we single step over a trap instruction.
1769 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1770 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1771 else
1772 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
1773 }
1774 }
1775 if (!handled)
1776 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
1777 }
1778
1779 if (!description.empty())
1780 {
1781 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
1782 if (stop_info_sp)
1783 {
1784 stop_info_sp->SetDescription (description.c_str());
1785 }
1786 else
1787 {
1788 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
1789 }
1790 }
1791 }
1792 }
1793 return eStateStopped;
1794 }
1795 break;
1796
1797 case 'W':
1798 // process exited
1799 return eStateExited;
1800
1801 default:
1802 break;
1803 }
1804 return eStateInvalid;
1805 }
1806
1807 void
RefreshStateAfterStop()1808 ProcessGDBRemote::RefreshStateAfterStop ()
1809 {
1810 Mutex::Locker locker(m_thread_list_real.GetMutex());
1811 m_thread_ids.clear();
1812 // Set the thread stop info. It might have a "threads" key whose value is
1813 // a list of all thread IDs in the current process, so m_thread_ids might
1814 // get set.
1815 SetThreadStopInfo (m_last_stop_packet);
1816 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1817 if (m_thread_ids.empty())
1818 {
1819 // No, we need to fetch the thread list manually
1820 UpdateThreadIDList();
1821 }
1822
1823 // Let all threads recover from stopping and do any clean up based
1824 // on the previous thread state (if any).
1825 m_thread_list_real.RefreshStateAfterStop();
1826
1827 }
1828
1829 Error
DoHalt(bool & caused_stop)1830 ProcessGDBRemote::DoHalt (bool &caused_stop)
1831 {
1832 Error error;
1833
1834 bool timed_out = false;
1835 Mutex::Locker locker;
1836
1837 if (m_public_state.GetValue() == eStateAttaching)
1838 {
1839 // We are being asked to halt during an attach. We need to just close
1840 // our file handle and debugserver will go away, and we can be done...
1841 m_gdb_comm.Disconnect();
1842 }
1843 else
1844 {
1845 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
1846 {
1847 if (timed_out)
1848 error.SetErrorString("timed out sending interrupt packet");
1849 else
1850 error.SetErrorString("unknown error sending interrupt packet");
1851 }
1852
1853 caused_stop = m_gdb_comm.GetInterruptWasSent ();
1854 }
1855 return error;
1856 }
1857
1858 Error
DoDetach(bool keep_stopped)1859 ProcessGDBRemote::DoDetach(bool keep_stopped)
1860 {
1861 Error error;
1862 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1863 if (log)
1864 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1865
1866 DisableAllBreakpointSites ();
1867
1868 m_thread_list.DiscardThreadPlans();
1869
1870 error = m_gdb_comm.Detach (keep_stopped);
1871 if (log)
1872 {
1873 if (error.Success())
1874 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1875 else
1876 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
1877 }
1878
1879 if (!error.Success())
1880 return error;
1881
1882 // Sleep for one second to let the process get all detached...
1883 StopAsyncThread ();
1884
1885 SetPrivateState (eStateDetached);
1886 ResumePrivateStateThread();
1887
1888 //KillDebugserverProcess ();
1889 return error;
1890 }
1891
1892
1893 Error
DoDestroy()1894 ProcessGDBRemote::DoDestroy ()
1895 {
1896 Error error;
1897 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1898 if (log)
1899 log->Printf ("ProcessGDBRemote::DoDestroy()");
1900
1901 #if 0 // XXX Currently no iOS target support on FreeBSD
1902 // There is a bug in older iOS debugservers where they don't shut down the process
1903 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1904 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1905 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1906 // destroy it again.
1907 //
1908 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1909 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1910 // the debugservers with this bug are equal. There really should be a better way to test this!
1911 //
1912 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1913 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1914 // just do the straight-forward kill.
1915 //
1916 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1917 // necessary (or helpful) to do any of this.
1918
1919 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1920 {
1921 PlatformSP platform_sp = GetTarget().GetPlatform();
1922
1923 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1924 if (platform_sp
1925 && platform_sp->GetName()
1926 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
1927 {
1928 if (m_destroy_tried_resuming)
1929 {
1930 if (log)
1931 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1932 }
1933 else
1934 {
1935 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1936 // but we really need it to happen here and it doesn't matter if we do it twice.
1937 m_thread_list.DiscardThreadPlans();
1938 DisableAllBreakpointSites();
1939
1940 bool stop_looks_like_crash = false;
1941 ThreadList &threads = GetThreadList();
1942
1943 {
1944 Mutex::Locker locker(threads.GetMutex());
1945
1946 size_t num_threads = threads.GetSize();
1947 for (size_t i = 0; i < num_threads; i++)
1948 {
1949 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1950 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1951 StopReason reason = eStopReasonInvalid;
1952 if (stop_info_sp)
1953 reason = stop_info_sp->GetStopReason();
1954 if (reason == eStopReasonBreakpoint
1955 || reason == eStopReasonException)
1956 {
1957 if (log)
1958 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1959 thread_sp->GetProtocolID(),
1960 stop_info_sp->GetDescription());
1961 stop_looks_like_crash = true;
1962 break;
1963 }
1964 }
1965 }
1966
1967 if (stop_looks_like_crash)
1968 {
1969 if (log)
1970 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1971 m_destroy_tried_resuming = true;
1972
1973 // If we are going to run again before killing, it would be good to suspend all the threads
1974 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1975 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1976 // have to run the risk of letting those threads proceed a bit.
1977
1978 {
1979 Mutex::Locker locker(threads.GetMutex());
1980
1981 size_t num_threads = threads.GetSize();
1982 for (size_t i = 0; i < num_threads; i++)
1983 {
1984 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
1985 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
1986 StopReason reason = eStopReasonInvalid;
1987 if (stop_info_sp)
1988 reason = stop_info_sp->GetStopReason();
1989 if (reason != eStopReasonBreakpoint
1990 && reason != eStopReasonException)
1991 {
1992 if (log)
1993 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1994 thread_sp->GetProtocolID());
1995 thread_sp->SetResumeState(eStateSuspended);
1996 }
1997 }
1998 }
1999 Resume ();
2000 return Destroy();
2001 }
2002 }
2003 }
2004 }
2005 #endif
2006
2007 // Interrupt if our inferior is running...
2008 int exit_status = SIGABRT;
2009 std::string exit_string;
2010
2011 if (m_gdb_comm.IsConnected())
2012 {
2013 if (m_public_state.GetValue() != eStateAttaching)
2014 {
2015
2016 StringExtractorGDBRemote response;
2017 bool send_async = true;
2018 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2019
2020 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2021 {
2022 char packet_cmd = response.GetChar(0);
2023
2024 if (packet_cmd == 'W' || packet_cmd == 'X')
2025 {
2026 #if defined(__APPLE__)
2027 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2028 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2029 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2030 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2031 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2032 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2033 // Anyway, so call waitpid here to finally reap it.
2034 PlatformSP platform_sp(GetTarget().GetPlatform());
2035 if (platform_sp && platform_sp->IsHost())
2036 {
2037 int status;
2038 ::pid_t reap_pid;
2039 reap_pid = waitpid (GetID(), &status, WNOHANG);
2040 if (log)
2041 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2042 }
2043 #endif
2044 SetLastStopPacket (response);
2045 ClearThreadIDList ();
2046 exit_status = response.GetHexU8();
2047 }
2048 else
2049 {
2050 if (log)
2051 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2052 exit_string.assign("got unexpected response to k packet: ");
2053 exit_string.append(response.GetStringRef());
2054 }
2055 }
2056 else
2057 {
2058 if (log)
2059 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2060 exit_string.assign("failed to send the k packet");
2061 }
2062
2063 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
2064 }
2065 else
2066 {
2067 if (log)
2068 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2069 exit_string.assign ("killed or interrupted while attaching.");
2070 }
2071 }
2072 else
2073 {
2074 // If we missed setting the exit status on the way out, do it here.
2075 // NB set exit status can be called multiple times, the first one sets the status.
2076 exit_string.assign("destroying when not connected to debugserver");
2077 }
2078
2079 SetExitStatus(exit_status, exit_string.c_str());
2080
2081 StopAsyncThread ();
2082 KillDebugserverProcess ();
2083 return error;
2084 }
2085
2086 void
SetLastStopPacket(const StringExtractorGDBRemote & response)2087 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2088 {
2089 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2090 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2091 if (did_exec)
2092 {
2093 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2094 if (log)
2095 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2096
2097 m_thread_list_real.Clear();
2098 m_thread_list.Clear();
2099 BuildDynamicRegisterInfo (true);
2100 m_gdb_comm.ResetDiscoverableSettings();
2101 }
2102 m_last_stop_packet = response;
2103 }
2104
2105
2106 //------------------------------------------------------------------
2107 // Process Queries
2108 //------------------------------------------------------------------
2109
2110 bool
IsAlive()2111 ProcessGDBRemote::IsAlive ()
2112 {
2113 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2114 }
2115
2116 addr_t
GetImageInfoAddress()2117 ProcessGDBRemote::GetImageInfoAddress()
2118 {
2119 return m_gdb_comm.GetShlibInfoAddr();
2120 }
2121
2122 //------------------------------------------------------------------
2123 // Process Memory
2124 //------------------------------------------------------------------
2125 size_t
DoReadMemory(addr_t addr,void * buf,size_t size,Error & error)2126 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2127 {
2128 if (size > m_max_memory_size)
2129 {
2130 // Keep memory read sizes down to a sane limit. This function will be
2131 // called multiple times in order to complete the task by
2132 // lldb_private::Process so it is ok to do this.
2133 size = m_max_memory_size;
2134 }
2135
2136 char packet[64];
2137 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2138 assert (packet_len + 1 < (int)sizeof(packet));
2139 StringExtractorGDBRemote response;
2140 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
2141 {
2142 if (response.IsNormalResponse())
2143 {
2144 error.Clear();
2145 return response.GetHexBytes(buf, size, '\xdd');
2146 }
2147 else if (response.IsErrorResponse())
2148 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2149 else if (response.IsUnsupportedResponse())
2150 error.SetErrorStringWithFormat("GDB server does not support reading memory");
2151 else
2152 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2153 }
2154 else
2155 {
2156 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2157 }
2158 return 0;
2159 }
2160
2161 size_t
DoWriteMemory(addr_t addr,const void * buf,size_t size,Error & error)2162 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2163 {
2164 if (size > m_max_memory_size)
2165 {
2166 // Keep memory read sizes down to a sane limit. This function will be
2167 // called multiple times in order to complete the task by
2168 // lldb_private::Process so it is ok to do this.
2169 size = m_max_memory_size;
2170 }
2171
2172 StreamString packet;
2173 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2174 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2175 StringExtractorGDBRemote response;
2176 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
2177 {
2178 if (response.IsOKResponse())
2179 {
2180 error.Clear();
2181 return size;
2182 }
2183 else if (response.IsErrorResponse())
2184 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2185 else if (response.IsUnsupportedResponse())
2186 error.SetErrorStringWithFormat("GDB server does not support writing memory");
2187 else
2188 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2189 }
2190 else
2191 {
2192 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2193 }
2194 return 0;
2195 }
2196
2197 lldb::addr_t
DoAllocateMemory(size_t size,uint32_t permissions,Error & error)2198 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2199 {
2200 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2201
2202 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2203 switch (supported)
2204 {
2205 case eLazyBoolCalculate:
2206 case eLazyBoolYes:
2207 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2208 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2209 return allocated_addr;
2210
2211 case eLazyBoolNo:
2212 // Call mmap() to create memory in the inferior..
2213 unsigned prot = 0;
2214 if (permissions & lldb::ePermissionsReadable)
2215 prot |= eMmapProtRead;
2216 if (permissions & lldb::ePermissionsWritable)
2217 prot |= eMmapProtWrite;
2218 if (permissions & lldb::ePermissionsExecutable)
2219 prot |= eMmapProtExec;
2220
2221 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2222 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2223 m_addr_to_mmap_size[allocated_addr] = size;
2224 else
2225 allocated_addr = LLDB_INVALID_ADDRESS;
2226 break;
2227 }
2228
2229 if (allocated_addr == LLDB_INVALID_ADDRESS)
2230 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
2231 else
2232 error.Clear();
2233 return allocated_addr;
2234 }
2235
2236 Error
GetMemoryRegionInfo(addr_t load_addr,MemoryRegionInfo & region_info)2237 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2238 MemoryRegionInfo ®ion_info)
2239 {
2240
2241 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2242 return error;
2243 }
2244
2245 Error
GetWatchpointSupportInfo(uint32_t & num)2246 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2247 {
2248
2249 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2250 return error;
2251 }
2252
2253 Error
GetWatchpointSupportInfo(uint32_t & num,bool & after)2254 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2255 {
2256 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2257 return error;
2258 }
2259
2260 Error
DoDeallocateMemory(lldb::addr_t addr)2261 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2262 {
2263 Error error;
2264 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2265
2266 switch (supported)
2267 {
2268 case eLazyBoolCalculate:
2269 // We should never be deallocating memory without allocating memory
2270 // first so we should never get eLazyBoolCalculate
2271 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2272 break;
2273
2274 case eLazyBoolYes:
2275 if (!m_gdb_comm.DeallocateMemory (addr))
2276 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2277 break;
2278
2279 case eLazyBoolNo:
2280 // Call munmap() to deallocate memory in the inferior..
2281 {
2282 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2283 if (pos != m_addr_to_mmap_size.end() &&
2284 InferiorCallMunmap(this, addr, pos->second))
2285 m_addr_to_mmap_size.erase (pos);
2286 else
2287 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
2288 }
2289 break;
2290 }
2291
2292 return error;
2293 }
2294
2295
2296 //------------------------------------------------------------------
2297 // Process STDIO
2298 //------------------------------------------------------------------
2299 size_t
PutSTDIN(const char * src,size_t src_len,Error & error)2300 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2301 {
2302 if (m_stdio_communication.IsConnected())
2303 {
2304 ConnectionStatus status;
2305 m_stdio_communication.Write(src, src_len, status, NULL);
2306 }
2307 return 0;
2308 }
2309
2310 Error
EnableBreakpointSite(BreakpointSite * bp_site)2311 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
2312 {
2313 Error error;
2314 assert(bp_site != NULL);
2315
2316 // Get logging info
2317 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2318 user_id_t site_id = bp_site->GetID();
2319
2320 // Get the breakpoint address
2321 const addr_t addr = bp_site->GetLoadAddress();
2322
2323 // Log that a breakpoint was requested
2324 if (log)
2325 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
2326
2327 // Breakpoint already exists and is enabled
2328 if (bp_site->IsEnabled())
2329 {
2330 if (log)
2331 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
2332 return error;
2333 }
2334
2335 // Get the software breakpoint trap opcode size
2336 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2337
2338 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
2339 // is supported by the remote stub. These are set to true by default, and later set to false
2340 // only after we receive an unimplemented response when sending a breakpoint packet. This means
2341 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
2342 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
2343 // indicates if the user specifically asked for hardware breakpoints. If true then we will
2344 // skip over software breakpoints.
2345 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
2346 {
2347 // Try to send off a software breakpoint packet ($Z0)
2348 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2349 {
2350 // The breakpoint was placed successfully
2351 bp_site->SetEnabled(true);
2352 bp_site->SetType(BreakpointSite::eExternal);
2353 return error;
2354 }
2355
2356 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
2357 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
2358 // or if we have learned that this breakpoint type is unsupported. To do this, we
2359 // must test the support boolean for this breakpoint type to see if it now indicates that
2360 // this breakpoint type is unsupported. If they are still supported then we should return
2361 // with the error code. If they are now unsupported, then we would like to fall through
2362 // and try another form of breakpoint.
2363 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
2364 return error;
2365
2366 // We reach here when software breakpoints have been found to be unsupported. For future
2367 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
2368 // known not to be supported.
2369 if (log)
2370 log->Printf("Software breakpoints are unsupported");
2371
2372 // So we will fall through and try a hardware breakpoint
2373 }
2374
2375 // The process of setting a hardware breakpoint is much the same as above. We check the
2376 // supported boolean for this breakpoint type, and if it is thought to be supported then we
2377 // will try to set this breakpoint with a hardware breakpoint.
2378 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2379 {
2380 // Try to send off a hardware breakpoint packet ($Z1)
2381 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
2382 {
2383 // The breakpoint was placed successfully
2384 bp_site->SetEnabled(true);
2385 bp_site->SetType(BreakpointSite::eHardware);
2386 return error;
2387 }
2388
2389 // Check if the error was something other then an unsupported breakpoint type
2390 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
2391 {
2392 // Unable to set this hardware breakpoint
2393 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
2394 return error;
2395 }
2396
2397 // We will reach here when the stub gives an unsported response to a hardware breakpoint
2398 if (log)
2399 log->Printf("Hardware breakpoints are unsupported");
2400
2401 // Finally we will falling through to a #trap style breakpoint
2402 }
2403
2404 // Don't fall through when hardware breakpoints were specifically requested
2405 if (bp_site->HardwareRequired())
2406 {
2407 error.SetErrorString("hardware breakpoints are not supported");
2408 return error;
2409 }
2410
2411 // As a last resort we want to place a manual breakpoint. An instruction
2412 // is placed into the process memory using memory write packets.
2413 return EnableSoftwareBreakpoint(bp_site);
2414 }
2415
2416 Error
DisableBreakpointSite(BreakpointSite * bp_site)2417 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
2418 {
2419 Error error;
2420 assert (bp_site != NULL);
2421 addr_t addr = bp_site->GetLoadAddress();
2422 user_id_t site_id = bp_site->GetID();
2423 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
2424 if (log)
2425 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
2426
2427 if (bp_site->IsEnabled())
2428 {
2429 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2430
2431 BreakpointSite::Type bp_type = bp_site->GetType();
2432 switch (bp_type)
2433 {
2434 case BreakpointSite::eSoftware:
2435 error = DisableSoftwareBreakpoint (bp_site);
2436 break;
2437
2438 case BreakpointSite::eHardware:
2439 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
2440 error.SetErrorToGenericError();
2441 break;
2442
2443 case BreakpointSite::eExternal:
2444 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2445 error.SetErrorToGenericError();
2446 break;
2447 }
2448 if (error.Success())
2449 bp_site->SetEnabled(false);
2450 }
2451 else
2452 {
2453 if (log)
2454 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
2455 return error;
2456 }
2457
2458 if (error.Success())
2459 error.SetErrorToGenericError();
2460 return error;
2461 }
2462
2463 // Pre-requisite: wp != NULL.
2464 static GDBStoppointType
GetGDBStoppointType(Watchpoint * wp)2465 GetGDBStoppointType (Watchpoint *wp)
2466 {
2467 assert(wp);
2468 bool watch_read = wp->WatchpointRead();
2469 bool watch_write = wp->WatchpointWrite();
2470
2471 // watch_read and watch_write cannot both be false.
2472 assert(watch_read || watch_write);
2473 if (watch_read && watch_write)
2474 return eWatchpointReadWrite;
2475 else if (watch_read)
2476 return eWatchpointRead;
2477 else // Must be watch_write, then.
2478 return eWatchpointWrite;
2479 }
2480
2481 Error
EnableWatchpoint(Watchpoint * wp,bool notify)2482 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
2483 {
2484 Error error;
2485 if (wp)
2486 {
2487 user_id_t watchID = wp->GetID();
2488 addr_t addr = wp->GetLoadAddress();
2489 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2490 if (log)
2491 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
2492 if (wp->IsEnabled())
2493 {
2494 if (log)
2495 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
2496 return error;
2497 }
2498
2499 GDBStoppointType type = GetGDBStoppointType(wp);
2500 // Pass down an appropriate z/Z packet...
2501 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
2502 {
2503 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2504 {
2505 wp->SetEnabled(true, notify);
2506 return error;
2507 }
2508 else
2509 error.SetErrorString("sending gdb watchpoint packet failed");
2510 }
2511 else
2512 error.SetErrorString("watchpoints not supported");
2513 }
2514 else
2515 {
2516 error.SetErrorString("Watchpoint argument was NULL.");
2517 }
2518 if (error.Success())
2519 error.SetErrorToGenericError();
2520 return error;
2521 }
2522
2523 Error
DisableWatchpoint(Watchpoint * wp,bool notify)2524 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
2525 {
2526 Error error;
2527 if (wp)
2528 {
2529 user_id_t watchID = wp->GetID();
2530
2531 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
2532
2533 addr_t addr = wp->GetLoadAddress();
2534
2535 if (log)
2536 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
2537
2538 if (!wp->IsEnabled())
2539 {
2540 if (log)
2541 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
2542 // See also 'class WatchpointSentry' within StopInfo.cpp.
2543 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2544 // the watchpoint object to intelligently process this action.
2545 wp->SetEnabled(false, notify);
2546 return error;
2547 }
2548
2549 if (wp->IsHardware())
2550 {
2551 GDBStoppointType type = GetGDBStoppointType(wp);
2552 // Pass down an appropriate z/Z packet...
2553 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2554 {
2555 wp->SetEnabled(false, notify);
2556 return error;
2557 }
2558 else
2559 error.SetErrorString("sending gdb watchpoint packet failed");
2560 }
2561 // TODO: clear software watchpoints if we implement them
2562 }
2563 else
2564 {
2565 error.SetErrorString("Watchpoint argument was NULL.");
2566 }
2567 if (error.Success())
2568 error.SetErrorToGenericError();
2569 return error;
2570 }
2571
2572 void
Clear()2573 ProcessGDBRemote::Clear()
2574 {
2575 m_flags = 0;
2576 m_thread_list_real.Clear();
2577 m_thread_list.Clear();
2578 }
2579
2580 Error
DoSignal(int signo)2581 ProcessGDBRemote::DoSignal (int signo)
2582 {
2583 Error error;
2584 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2585 if (log)
2586 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2587
2588 if (!m_gdb_comm.SendAsyncSignal (signo))
2589 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2590 return error;
2591 }
2592
2593 Error
LaunchAndConnectToDebugserver(const ProcessInfo & process_info)2594 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
2595 {
2596 Error error;
2597 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2598 {
2599 // If we locate debugserver, keep that located version around
2600 static FileSpec g_debugserver_file_spec;
2601
2602 ProcessLaunchInfo debugserver_launch_info;
2603 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2604 debugserver_launch_info.SetUserID(process_info.GetUserID());
2605
2606 #if defined (__APPLE__) && defined (__arm__)
2607 // On iOS, still do a local connection using a random port
2608 const char *hostname = "localhost";
2609 uint16_t port = get_random_port ();
2610 #else
2611 // Set hostname being NULL to do the reverse connect where debugserver
2612 // will bind to port zero and it will communicate back to us the port
2613 // that we will connect to
2614 const char *hostname = NULL;
2615 uint16_t port = 0;
2616 #endif
2617
2618 error = m_gdb_comm.StartDebugserverProcess (hostname,
2619 port,
2620 debugserver_launch_info,
2621 port);
2622
2623 if (error.Success ())
2624 m_debugserver_pid = debugserver_launch_info.GetProcessID();
2625 else
2626 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2627
2628 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2629 StartAsyncThread ();
2630
2631 if (error.Fail())
2632 {
2633 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2634
2635 if (log)
2636 log->Printf("failed to start debugserver process: %s", error.AsCString());
2637 return error;
2638 }
2639
2640 if (m_gdb_comm.IsConnected())
2641 {
2642 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2643 ConnectToDebugserver (NULL);
2644 }
2645 else
2646 {
2647 StreamString connect_url;
2648 connect_url.Printf("connect://%s:%u", hostname, port);
2649 error = ConnectToDebugserver (connect_url.GetString().c_str());
2650 }
2651
2652 }
2653 return error;
2654 }
2655
2656 bool
MonitorDebugserverProcess(void * callback_baton,lldb::pid_t debugserver_pid,bool exited,int signo,int exit_status)2657 ProcessGDBRemote::MonitorDebugserverProcess
2658 (
2659 void *callback_baton,
2660 lldb::pid_t debugserver_pid,
2661 bool exited, // True if the process did exit
2662 int signo, // Zero for no signal
2663 int exit_status // Exit value of process if signal is zero
2664 )
2665 {
2666 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2667 // and might not exist anymore, so we need to carefully try to get the
2668 // target for this process first since we have a race condition when
2669 // we are done running between getting the notice that the inferior
2670 // process has died and the debugserver that was debugging this process.
2671 // In our test suite, we are also continually running process after
2672 // process, so we must be very careful to make sure:
2673 // 1 - process object hasn't been deleted already
2674 // 2 - that a new process object hasn't been recreated in its place
2675
2676 // "debugserver_pid" argument passed in is the process ID for
2677 // debugserver that we are tracking...
2678 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2679
2680 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
2681
2682 // Get a shared pointer to the target that has a matching process pointer.
2683 // This target could be gone, or the target could already have a new process
2684 // object inside of it
2685 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2686
2687 if (log)
2688 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
2689
2690 if (target_sp)
2691 {
2692 // We found a process in a target that matches, but another thread
2693 // might be in the process of launching a new process that will
2694 // soon replace it, so get a shared pointer to the process so we
2695 // can keep it alive.
2696 ProcessSP process_sp (target_sp->GetProcessSP());
2697 // Now we have a shared pointer to the process that can't go away on us
2698 // so we now make sure it was the same as the one passed in, and also make
2699 // sure that our previous "process *" didn't get deleted and have a new
2700 // "process *" created in its place with the same pointer. To verify this
2701 // we make sure the process has our debugserver process ID. If we pass all
2702 // of these tests, then we are sure that this process is the one we were
2703 // looking for.
2704 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
2705 {
2706 // Sleep for a half a second to make sure our inferior process has
2707 // time to set its exit status before we set it incorrectly when
2708 // both the debugserver and the inferior process shut down.
2709 usleep (500000);
2710 // If our process hasn't yet exited, debugserver might have died.
2711 // If the process did exit, the we are reaping it.
2712 const StateType state = process->GetState();
2713
2714 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2715 state != eStateInvalid &&
2716 state != eStateUnloaded &&
2717 state != eStateExited &&
2718 state != eStateDetached)
2719 {
2720 char error_str[1024];
2721 if (signo)
2722 {
2723 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2724 if (signal_cstr)
2725 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2726 else
2727 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2728 }
2729 else
2730 {
2731 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2732 }
2733
2734 process->SetExitStatus (-1, error_str);
2735 }
2736 // Debugserver has exited we need to let our ProcessGDBRemote
2737 // know that it no longer has a debugserver instance
2738 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2739 }
2740 }
2741 return true;
2742 }
2743
2744 void
KillDebugserverProcess()2745 ProcessGDBRemote::KillDebugserverProcess ()
2746 {
2747 m_gdb_comm.Disconnect();
2748 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2749 {
2750 Host::Kill (m_debugserver_pid, SIGINT);
2751 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2752 }
2753 }
2754
2755 void
Initialize()2756 ProcessGDBRemote::Initialize()
2757 {
2758 static bool g_initialized = false;
2759
2760 if (g_initialized == false)
2761 {
2762 g_initialized = true;
2763 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2764 GetPluginDescriptionStatic(),
2765 CreateInstance,
2766 DebuggerInitialize);
2767
2768 Log::Callbacks log_callbacks = {
2769 ProcessGDBRemoteLog::DisableLog,
2770 ProcessGDBRemoteLog::EnableLog,
2771 ProcessGDBRemoteLog::ListLogCategories
2772 };
2773
2774 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2775 }
2776 }
2777
2778 void
DebuggerInitialize(lldb_private::Debugger & debugger)2779 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2780 {
2781 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2782 {
2783 const bool is_global_setting = true;
2784 PluginManager::CreateSettingForProcessPlugin (debugger,
2785 GetGlobalPluginProperties()->GetValueProperties(),
2786 ConstString ("Properties for the gdb-remote process plug-in."),
2787 is_global_setting);
2788 }
2789 }
2790
2791 bool
StartAsyncThread()2792 ProcessGDBRemote::StartAsyncThread ()
2793 {
2794 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2795
2796 if (log)
2797 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2798
2799 Mutex::Locker start_locker(m_async_thread_state_mutex);
2800 if (m_async_thread_state == eAsyncThreadNotStarted)
2801 {
2802 // Create a thread that watches our internal state and controls which
2803 // events make it to clients (into the DCProcess event queue).
2804 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2805 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2806 {
2807 m_async_thread_state = eAsyncThreadRunning;
2808 return true;
2809 }
2810 else
2811 return false;
2812 }
2813 else
2814 {
2815 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2816 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2817 if (log)
2818 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2819 if (m_async_thread_state == eAsyncThreadRunning)
2820 return true;
2821 else
2822 return false;
2823 }
2824 }
2825
2826 void
StopAsyncThread()2827 ProcessGDBRemote::StopAsyncThread ()
2828 {
2829 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2830
2831 if (log)
2832 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2833
2834 Mutex::Locker start_locker(m_async_thread_state_mutex);
2835 if (m_async_thread_state == eAsyncThreadRunning)
2836 {
2837 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2838
2839 // This will shut down the async thread.
2840 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2841
2842 // Stop the stdio thread
2843 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2844 {
2845 Host::ThreadJoin (m_async_thread, NULL, NULL);
2846 }
2847 m_async_thread_state = eAsyncThreadDone;
2848 }
2849 else
2850 {
2851 if (log)
2852 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2853 }
2854 }
2855
2856
2857 thread_result_t
AsyncThread(void * arg)2858 ProcessGDBRemote::AsyncThread (void *arg)
2859 {
2860 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2861
2862 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2863 if (log)
2864 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
2865
2866 Listener listener ("ProcessGDBRemote::AsyncThread");
2867 EventSP event_sp;
2868 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2869 eBroadcastBitAsyncThreadShouldExit;
2870
2871 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2872 {
2873 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2874
2875 bool done = false;
2876 while (!done)
2877 {
2878 if (log)
2879 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
2880 if (listener.WaitForEvent (NULL, event_sp))
2881 {
2882 const uint32_t event_type = event_sp->GetType();
2883 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
2884 {
2885 if (log)
2886 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
2887
2888 switch (event_type)
2889 {
2890 case eBroadcastBitAsyncContinue:
2891 {
2892 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
2893
2894 if (continue_packet)
2895 {
2896 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2897 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2898 if (log)
2899 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
2900
2901 if (::strstr (continue_cstr, "vAttach") == NULL)
2902 process->SetPrivateState(eStateRunning);
2903 StringExtractorGDBRemote response;
2904 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
2905
2906 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2907 // The thread ID list might be contained within the "response", or the stop reply packet that
2908 // caused the stop. So clear it now before we give the stop reply packet to the process
2909 // using the process->SetLastStopPacket()...
2910 process->ClearThreadIDList ();
2911
2912 switch (stop_state)
2913 {
2914 case eStateStopped:
2915 case eStateCrashed:
2916 case eStateSuspended:
2917 process->SetLastStopPacket (response);
2918 process->SetPrivateState (stop_state);
2919 break;
2920
2921 case eStateExited:
2922 process->SetLastStopPacket (response);
2923 process->ClearThreadIDList();
2924 response.SetFilePos(1);
2925 process->SetExitStatus(response.GetHexU8(), NULL);
2926 done = true;
2927 break;
2928
2929 case eStateInvalid:
2930 process->SetExitStatus(-1, "lost connection");
2931 break;
2932
2933 default:
2934 process->SetPrivateState (stop_state);
2935 break;
2936 }
2937 }
2938 }
2939 break;
2940
2941 case eBroadcastBitAsyncThreadShouldExit:
2942 if (log)
2943 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
2944 done = true;
2945 break;
2946
2947 default:
2948 if (log)
2949 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
2950 done = true;
2951 break;
2952 }
2953 }
2954 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2955 {
2956 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2957 {
2958 process->SetExitStatus (-1, "lost connection");
2959 done = true;
2960 }
2961 }
2962 }
2963 else
2964 {
2965 if (log)
2966 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
2967 done = true;
2968 }
2969 }
2970 }
2971
2972 if (log)
2973 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
2974
2975 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2976 return NULL;
2977 }
2978
2979 //uint32_t
2980 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2981 //{
2982 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2983 // // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2984 // if (m_local_debugserver)
2985 // {
2986 // return Host::ListProcessesMatchingName (name, matches, pids);
2987 // }
2988 // else
2989 // {
2990 // // FIXME: Implement talking to the remote debugserver.
2991 // return 0;
2992 // }
2993 //
2994 //}
2995 //
2996 bool
NewThreadNotifyBreakpointHit(void * baton,lldb_private::StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)2997 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2998 lldb_private::StoppointCallbackContext *context,
2999 lldb::user_id_t break_id,
3000 lldb::user_id_t break_loc_id)
3001 {
3002 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3003 // run so I can stop it if that's what I want to do.
3004 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3005 if (log)
3006 log->Printf("Hit New Thread Notification breakpoint.");
3007 return false;
3008 }
3009
3010
3011 bool
StartNoticingNewThreads()3012 ProcessGDBRemote::StartNoticingNewThreads()
3013 {
3014 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3015 if (m_thread_create_bp_sp)
3016 {
3017 if (log && log->GetVerbose())
3018 log->Printf("Enabled noticing new thread breakpoint.");
3019 m_thread_create_bp_sp->SetEnabled(true);
3020 }
3021 else
3022 {
3023 PlatformSP platform_sp (m_target.GetPlatform());
3024 if (platform_sp)
3025 {
3026 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3027 if (m_thread_create_bp_sp)
3028 {
3029 if (log && log->GetVerbose())
3030 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3031 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3032 }
3033 else
3034 {
3035 if (log)
3036 log->Printf("Failed to create new thread notification breakpoint.");
3037 }
3038 }
3039 }
3040 return m_thread_create_bp_sp.get() != NULL;
3041 }
3042
3043 bool
StopNoticingNewThreads()3044 ProcessGDBRemote::StopNoticingNewThreads()
3045 {
3046 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3047 if (log && log->GetVerbose())
3048 log->Printf ("Disabling new thread notification breakpoint.");
3049
3050 if (m_thread_create_bp_sp)
3051 m_thread_create_bp_sp->SetEnabled(false);
3052
3053 return true;
3054 }
3055
3056 lldb_private::DynamicLoader *
GetDynamicLoader()3057 ProcessGDBRemote::GetDynamicLoader ()
3058 {
3059 if (m_dyld_ap.get() == NULL)
3060 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3061 return m_dyld_ap.get();
3062 }
3063
3064
3065 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
3066 {
3067 private:
3068
3069 public:
CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter & interpreter)3070 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
3071 CommandObjectParsed (interpreter,
3072 "process plugin packet history",
3073 "Dumps the packet history buffer. ",
3074 NULL)
3075 {
3076 }
3077
~CommandObjectProcessGDBRemotePacketHistory()3078 ~CommandObjectProcessGDBRemotePacketHistory ()
3079 {
3080 }
3081
3082 bool
DoExecute(Args & command,CommandReturnObject & result)3083 DoExecute (Args& command, CommandReturnObject &result)
3084 {
3085 const size_t argc = command.GetArgumentCount();
3086 if (argc == 0)
3087 {
3088 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3089 if (process)
3090 {
3091 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3092 result.SetStatus (eReturnStatusSuccessFinishResult);
3093 return true;
3094 }
3095 }
3096 else
3097 {
3098 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3099 }
3100 result.SetStatus (eReturnStatusFailed);
3101 return false;
3102 }
3103 };
3104
3105 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3106 {
3107 private:
3108
3109 public:
CommandObjectProcessGDBRemotePacketSend(CommandInterpreter & interpreter)3110 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3111 CommandObjectParsed (interpreter,
3112 "process plugin packet send",
3113 "Send a custom packet through the GDB remote protocol and print the answer. "
3114 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3115 NULL)
3116 {
3117 }
3118
~CommandObjectProcessGDBRemotePacketSend()3119 ~CommandObjectProcessGDBRemotePacketSend ()
3120 {
3121 }
3122
3123 bool
DoExecute(Args & command,CommandReturnObject & result)3124 DoExecute (Args& command, CommandReturnObject &result)
3125 {
3126 const size_t argc = command.GetArgumentCount();
3127 if (argc == 0)
3128 {
3129 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3130 result.SetStatus (eReturnStatusFailed);
3131 return false;
3132 }
3133
3134 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3135 if (process)
3136 {
3137 for (size_t i=0; i<argc; ++ i)
3138 {
3139 const char *packet_cstr = command.GetArgumentAtIndex(0);
3140 bool send_async = true;
3141 StringExtractorGDBRemote response;
3142 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3143 result.SetStatus (eReturnStatusSuccessFinishResult);
3144 Stream &output_strm = result.GetOutputStream();
3145 output_strm.Printf (" packet: %s\n", packet_cstr);
3146 std::string &response_str = response.GetStringRef();
3147
3148 if (strstr(packet_cstr, "qGetProfileData") != NULL)
3149 {
3150 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3151 }
3152
3153 if (response_str.empty())
3154 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3155 else
3156 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3157 }
3158 }
3159 return true;
3160 }
3161 };
3162
3163 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3164 {
3165 private:
3166
3167 public:
CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter & interpreter)3168 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3169 CommandObjectRaw (interpreter,
3170 "process plugin packet monitor",
3171 "Send a qRcmd packet through the GDB remote protocol and print the response."
3172 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
3173 NULL)
3174 {
3175 }
3176
~CommandObjectProcessGDBRemotePacketMonitor()3177 ~CommandObjectProcessGDBRemotePacketMonitor ()
3178 {
3179 }
3180
3181 bool
DoExecute(const char * command,CommandReturnObject & result)3182 DoExecute (const char *command, CommandReturnObject &result)
3183 {
3184 if (command == NULL || command[0] == '\0')
3185 {
3186 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3187 result.SetStatus (eReturnStatusFailed);
3188 return false;
3189 }
3190
3191 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3192 if (process)
3193 {
3194 StreamString packet;
3195 packet.PutCString("qRcmd,");
3196 packet.PutBytesAsRawHex8(command, strlen(command));
3197 const char *packet_cstr = packet.GetString().c_str();
3198
3199 bool send_async = true;
3200 StringExtractorGDBRemote response;
3201 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3202 result.SetStatus (eReturnStatusSuccessFinishResult);
3203 Stream &output_strm = result.GetOutputStream();
3204 output_strm.Printf (" packet: %s\n", packet_cstr);
3205 const std::string &response_str = response.GetStringRef();
3206
3207 if (response_str.empty())
3208 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3209 else
3210 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3211 }
3212 return true;
3213 }
3214 };
3215
3216 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3217 {
3218 private:
3219
3220 public:
CommandObjectProcessGDBRemotePacket(CommandInterpreter & interpreter)3221 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3222 CommandObjectMultiword (interpreter,
3223 "process plugin packet",
3224 "Commands that deal with GDB remote packets.",
3225 NULL)
3226 {
3227 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3228 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
3229 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
3230 }
3231
~CommandObjectProcessGDBRemotePacket()3232 ~CommandObjectProcessGDBRemotePacket ()
3233 {
3234 }
3235 };
3236
3237 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3238 {
3239 public:
CommandObjectMultiwordProcessGDBRemote(CommandInterpreter & interpreter)3240 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3241 CommandObjectMultiword (interpreter,
3242 "process plugin",
3243 "A set of commands for operating on a ProcessGDBRemote process.",
3244 "process plugin <subcommand> [<subcommand-options>]")
3245 {
3246 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3247 }
3248
~CommandObjectMultiwordProcessGDBRemote()3249 ~CommandObjectMultiwordProcessGDBRemote ()
3250 {
3251 }
3252 };
3253
3254 CommandObject *
GetPluginCommandObject()3255 ProcessGDBRemote::GetPluginCommandObject()
3256 {
3257 if (!m_command_sp)
3258 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3259 return m_command_sp.get();
3260 }
3261