blob: 7f1fbefc1b7e4bbbb64aabf825b3ce448165677a [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
Virgile Bellob2f1fb22013-08-23 12:44:05 +000011#include "lldb/Host/Config.h"
Daniel Malea93a64302012-12-05 00:20:57 +000012
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C Includes
14#include <errno.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifndef LLDB_DISABLE_POSIX
17#include <spawn.h>
Sean Callanan224f6f52012-07-19 18:07:36 +000018#include <netinet/in.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000019#include <sys/mman.h> // for mmap
Virgile Bellob2f1fb22013-08-23 12:44:05 +000020#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include <sys/stat.h>
Greg Clayton2a48f522011-05-14 01:50:35 +000022#include <sys/types.h>
Stephen Wilsondc916862011-03-30 00:12:40 +000023#include <time.h>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024
25// C++ Includes
26#include <algorithm>
27#include <map>
28
29// Other libraries and framework includes
30
Johnny Chen01a67862011-10-14 00:42:25 +000031#include "lldb/Breakpoint/Watchpoint.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000032#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Core/ArchSpec.h"
34#include "lldb/Core/Debugger.h"
35#include "lldb/Core/ConnectionFileDescriptor.h"
Greg Clayton53239f02011-02-08 05:05:52 +000036#include "lldb/Host/FileSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Core/InputReader.h"
38#include "lldb/Core/Module.h"
Greg Clayton1f746072012-08-29 21:13:06 +000039#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Core/PluginManager.h"
41#include "lldb/Core/State.h"
Greg Claytond451c1a2012-04-13 21:24:18 +000042#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Core/StreamString.h"
44#include "lldb/Core/Timer.h"
Greg Clayton70b57652011-05-15 01:25:55 +000045#include "lldb/Core/Value.h"
Jason Molendad1fae142012-09-29 08:03:33 +000046#include "lldb/Host/Symbols.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Host/TimeValue.h"
Greg Clayton02686b82012-10-15 22:42:16 +000048#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton1d19a2f2012-10-19 22:22:57 +000049#include "lldb/Interpreter/CommandObject.h"
50#include "lldb/Interpreter/CommandObjectMultiword.h"
Greg Clayton02686b82012-10-15 22:42:16 +000051#include "lldb/Interpreter/CommandReturnObject.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000052#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +000053#include "lldb/Interpreter/PythonDataObjects.h"
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +000054#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055#include "lldb/Symbol/ObjectFile.h"
56#include "lldb/Target/DynamicLoader.h"
57#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
Greg Clayton2a48f522011-05-14 01:50:35 +000059#include "lldb/Target/ThreadPlanCallFunction.h"
Jason Molendaa34a0c62010-06-09 21:28:42 +000060#include "lldb/Utility/PseudoTerminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061
62// Project includes
63#include "lldb/Host/Host.h"
Peter Collingbourne99f9aa02011-06-03 20:40:38 +000064#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Jason Molendac42d2432012-07-25 03:40:06 +000065#include "Plugins/Process/Utility/StopInfoMachException.h"
Jim Ingham43c555d2012-07-04 00:35:43 +000066#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
Greg Claytonc982c762010-07-09 20:39:50 +000067#include "Utility/StringExtractorGDBRemote.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068#include "GDBRemoteRegisterContext.h"
69#include "ProcessGDBRemote.h"
70#include "ProcessGDBRemoteLog.h"
71#include "ThreadGDBRemote.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000072
Jason Molenda5e8534e2012-10-03 01:29:34 +000073
Greg Claytonc1422c12012-04-09 22:46:21 +000074namespace lldb
75{
76 // Provide a function that can easily dump the packet history if we know a
77 // ProcessGDBRemote * value (which we can get from logs or from debugging).
78 // We need the function in the lldb namespace so it makes it into the final
79 // executable since the LLDB shared library only exports stuff in the lldb
80 // namespace. This allows you to attach with a debugger and call this
81 // function and get the packet history dumped to a file.
82 void
83 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
84 {
Greg Claytond451c1a2012-04-13 21:24:18 +000085 lldb_private::StreamFile strm;
86 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate));
87 if (error.Success())
88 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +000089 }
Filipe Cabecinhasc34f7762012-05-23 16:27:09 +000090}
Chris Lattner30fdc8d2010-06-08 16:52:24 +000091
Chris Lattner30fdc8d2010-06-08 16:52:24 +000092#define DEBUGSERVER_BASENAME "debugserver"
93using namespace lldb;
94using namespace lldb_private;
95
Greg Clayton7f982402013-07-15 22:54:20 +000096
97namespace {
98
99 static PropertyDefinition
100 g_properties[] =
101 {
102 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
Greg Claytonef8180a2013-10-15 00:14:28 +0000103 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
Greg Clayton7f982402013-07-15 22:54:20 +0000104 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
105 };
106
107 enum
108 {
Greg Claytonef8180a2013-10-15 00:14:28 +0000109 ePropertyPacketTimeout,
110 ePropertyTargetDefinitionFile
Greg Clayton7f982402013-07-15 22:54:20 +0000111 };
112
113 class PluginProperties : public Properties
114 {
115 public:
116
117 static ConstString
118 GetSettingName ()
119 {
120 return ProcessGDBRemote::GetPluginNameStatic();
121 }
122
123 PluginProperties() :
124 Properties ()
125 {
126 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
127 m_collection_sp->Initialize(g_properties);
128 }
129
130 virtual
131 ~PluginProperties()
132 {
133 }
134
135 uint64_t
136 GetPacketTimeout()
137 {
138 const uint32_t idx = ePropertyPacketTimeout;
139 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
140 }
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000141
142 bool
143 SetPacketTimeout(uint64_t timeout)
144 {
145 const uint32_t idx = ePropertyPacketTimeout;
146 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
147 }
148
Greg Claytonef8180a2013-10-15 00:14:28 +0000149 FileSpec
150 GetTargetDefinitionFile () const
151 {
152 const uint32_t idx = ePropertyTargetDefinitionFile;
153 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
154 }
Greg Clayton7f982402013-07-15 22:54:20 +0000155 };
156
157 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
158
159 static const ProcessKDPPropertiesSP &
160 GetGlobalPluginProperties()
161 {
162 static ProcessKDPPropertiesSP g_settings_sp;
163 if (!g_settings_sp)
164 g_settings_sp.reset (new PluginProperties ());
165 return g_settings_sp;
166 }
167
168} // anonymous namespace end
169
Jim Ingham7572fa72011-03-29 21:45:47 +0000170static bool rand_initialized = false;
171
Sean Callanan224f6f52012-07-19 18:07:36 +0000172// TODO Randomly assigning a port is unsafe. We should get an unused
173// ephemeral port from the kernel and make sure we reserve it before passing
174// it to debugserver.
175
176#if defined (__APPLE__)
177#define LOW_PORT (IPPORT_RESERVED)
178#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
179#else
180#define LOW_PORT (1024u)
181#define HIGH_PORT (49151u)
182#endif
183
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184static inline uint16_t
185get_random_port ()
186{
Jim Ingham7572fa72011-03-29 21:45:47 +0000187 if (!rand_initialized)
188 {
Stephen Wilsondc916862011-03-30 00:12:40 +0000189 time_t seed = time(NULL);
190
Jim Ingham7572fa72011-03-29 21:45:47 +0000191 rand_initialized = true;
Stephen Wilsondc916862011-03-30 00:12:40 +0000192 srand(seed);
Jim Ingham7572fa72011-03-29 21:45:47 +0000193 }
Sean Callanan224f6f52012-07-19 18:07:36 +0000194 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000195}
196
197
Greg Clayton57abc5d2013-05-10 21:47:16 +0000198lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199ProcessGDBRemote::GetPluginNameStatic()
200{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000201 static ConstString g_name("gdb-remote");
202 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203}
204
205const char *
206ProcessGDBRemote::GetPluginDescriptionStatic()
207{
208 return "GDB Remote protocol based debugging plug-in.";
209}
210
211void
212ProcessGDBRemote::Terminate()
213{
214 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
215}
216
217
Greg Claytonc3776bf2012-02-09 06:16:32 +0000218lldb::ProcessSP
219ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000220{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000221 lldb::ProcessSP process_sp;
222 if (crash_file_path == NULL)
223 process_sp.reset (new ProcessGDBRemote (target, listener));
224 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000225}
226
227bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000228ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229{
Greg Clayton596ed242011-10-21 21:41:45 +0000230 if (plugin_specified_by_name)
231 return true;
232
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000233 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000234 Module *exe_module = target.GetExecutableModulePointer();
235 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000236 {
237 ObjectFile *exe_objfile = exe_module->GetObjectFile();
238 // We can't debug core files...
239 switch (exe_objfile->GetType())
240 {
241 case ObjectFile::eTypeInvalid:
242 case ObjectFile::eTypeCoreFile:
243 case ObjectFile::eTypeDebugInfo:
244 case ObjectFile::eTypeObjectFile:
245 case ObjectFile::eTypeSharedLibrary:
246 case ObjectFile::eTypeStubLibrary:
247 return false;
248 case ObjectFile::eTypeExecutable:
249 case ObjectFile::eTypeDynamicLinker:
250 case ObjectFile::eTypeUnknown:
251 break;
252 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000253 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000254 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000255 // However, if there is no executable module, we return true since we might be preparing to attach.
256 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000257}
258
259//----------------------------------------------------------------------
260// ProcessGDBRemote constructor
261//----------------------------------------------------------------------
262ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
263 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000264 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000265 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000266 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000267 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000268 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000270 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000271 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000272 m_async_thread_state(eAsyncThreadNotStarted),
273 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000274 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000275 m_continue_c_tids (),
276 m_continue_C_tids (),
277 m_continue_s_tids (),
278 m_continue_S_tids (),
Greg Claytonc982c762010-07-09 20:39:50 +0000279 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000280 m_addr_to_mmap_size (),
281 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000282 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000283 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000284 m_command_sp (),
285 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000286{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000287 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
288 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000289 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000290 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
291 if (timeout_seconds > 0)
292 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000293}
294
295//----------------------------------------------------------------------
296// Destructor
297//----------------------------------------------------------------------
298ProcessGDBRemote::~ProcessGDBRemote()
299{
300 // m_mach_process.UnregisterNotificationCallbacks (this);
301 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000302 // We need to call finalize on the process before destroying ourselves
303 // to make sure all of the broadcaster cleanup goes as planned. If we
304 // destruct this class, then Process::~Process() might have problems
305 // trying to fully destroy the broadcaster.
306 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000307
308 // The general Finalize is going to try to destroy the process and that SHOULD
309 // shut down the async thread. However, if we don't kill it it will get stranded and
310 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
311 StopAsyncThread();
312 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000313}
314
315//----------------------------------------------------------------------
316// PluginInterface
317//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000318ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000319ProcessGDBRemote::GetPluginName()
320{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321 return GetPluginNameStatic();
322}
323
324uint32_t
325ProcessGDBRemote::GetPluginVersion()
326{
327 return 1;
328}
329
Greg Claytonef8180a2013-10-15 00:14:28 +0000330bool
331ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
332{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000333#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000334 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
335 Error error;
336 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
337 if (module_object_sp)
338 {
339 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
340 &GetTarget(),
341 "gdb-server-target-definition",
342 error));
343
344 PythonDictionary target_dict(target_definition_sp);
345
346 if (target_dict)
347 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000348 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
349 if (host_info_dict)
350 {
351 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
352
353 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
354 {
355 GetTarget().SetArchitecture(host_arch);
356 }
357
358 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000359 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
360
Greg Clayton312bcbe2013-10-17 01:10:23 +0000361 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000362 {
363 return true;
364 }
365 }
366 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000367#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000368 return false;
369}
370
371
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000372void
Greg Clayton513c26c2011-01-29 07:10:55 +0000373ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374{
Greg Clayton513c26c2011-01-29 07:10:55 +0000375 if (!force && m_register_info.GetNumRegisters() > 0)
376 return;
377
378 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380 uint32_t reg_offset = 0;
381 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000382 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000383 response_type == StringExtractorGDBRemote::eResponse;
384 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000386 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000387 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +0000389 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390 {
Greg Clayton576d8832011-03-22 04:00:09 +0000391 response_type = response.GetResponseType();
392 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393 {
394 std::string name;
395 std::string value;
396 ConstString reg_name;
397 ConstString alt_name;
398 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000399 std::vector<uint32_t> value_regs;
400 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401 RegisterInfo reg_info = { NULL, // Name
402 NULL, // Alt name
403 0, // byte size
404 reg_offset, // offset
405 eEncodingUint, // encoding
406 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407 {
408 LLDB_INVALID_REGNUM, // GCC reg num
409 LLDB_INVALID_REGNUM, // DWARF reg num
410 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000411 reg_num, // GDB reg num
412 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000413 },
414 NULL,
415 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416 };
417
418 while (response.GetNameColonValue(name, value))
419 {
420 if (name.compare("name") == 0)
421 {
422 reg_name.SetCString(value.c_str());
423 }
424 else if (name.compare("alt-name") == 0)
425 {
426 alt_name.SetCString(value.c_str());
427 }
428 else if (name.compare("bitsize") == 0)
429 {
430 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
431 }
432 else if (name.compare("offset") == 0)
433 {
434 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000435 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436 {
437 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438 }
439 }
440 else if (name.compare("encoding") == 0)
441 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000442 const Encoding encoding = Args::StringToEncoding (value.c_str());
443 if (encoding != eEncodingInvalid)
444 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445 }
446 else if (name.compare("format") == 0)
447 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000448 Format format = eFormatInvalid;
449 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
450 reg_info.format = format;
451 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452 reg_info.format = eFormatBinary;
453 else if (value.compare("decimal") == 0)
454 reg_info.format = eFormatDecimal;
455 else if (value.compare("hex") == 0)
456 reg_info.format = eFormatHex;
457 else if (value.compare("float") == 0)
458 reg_info.format = eFormatFloat;
459 else if (value.compare("vector-sint8") == 0)
460 reg_info.format = eFormatVectorOfSInt8;
461 else if (value.compare("vector-uint8") == 0)
462 reg_info.format = eFormatVectorOfUInt8;
463 else if (value.compare("vector-sint16") == 0)
464 reg_info.format = eFormatVectorOfSInt16;
465 else if (value.compare("vector-uint16") == 0)
466 reg_info.format = eFormatVectorOfUInt16;
467 else if (value.compare("vector-sint32") == 0)
468 reg_info.format = eFormatVectorOfSInt32;
469 else if (value.compare("vector-uint32") == 0)
470 reg_info.format = eFormatVectorOfUInt32;
471 else if (value.compare("vector-float32") == 0)
472 reg_info.format = eFormatVectorOfFloat32;
473 else if (value.compare("vector-uint128") == 0)
474 reg_info.format = eFormatVectorOfUInt128;
475 }
476 else if (name.compare("set") == 0)
477 {
478 set_name.SetCString(value.c_str());
479 }
480 else if (name.compare("gcc") == 0)
481 {
482 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
483 }
484 else if (name.compare("dwarf") == 0)
485 {
486 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
487 }
488 else if (name.compare("generic") == 0)
489 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000490 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000491 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000492 else if (name.compare("container-regs") == 0)
493 {
494 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
495 value_pair.second = value;
496 do
497 {
498 value_pair = value_pair.second.split(',');
499 if (!value_pair.first.empty())
500 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000501 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
502 if (reg != LLDB_INVALID_REGNUM)
503 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000504 }
505 } while (!value_pair.second.empty());
506 }
507 else if (name.compare("invalidate-regs") == 0)
508 {
509 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
510 value_pair.second = value;
511 do
512 {
513 value_pair = value_pair.second.split(',');
514 if (!value_pair.first.empty())
515 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000516 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
517 if (reg != LLDB_INVALID_REGNUM)
518 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000519 }
520 } while (!value_pair.second.empty());
521 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000522 }
523
Jason Molenda743e86a2010-06-11 23:44:18 +0000524 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000525 assert (reg_info.byte_size != 0);
526 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000527 if (!value_regs.empty())
528 {
529 value_regs.push_back(LLDB_INVALID_REGNUM);
530 reg_info.value_regs = value_regs.data();
531 }
532 if (!invalidate_regs.empty())
533 {
534 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
535 reg_info.invalidate_regs = invalidate_regs.data();
536 }
537
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
539 }
540 }
541 else
542 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000543 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000544 }
545 }
546
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000547 // Check if qHostInfo specified a specific packet timeout for this connection.
548 // If so then lets update our setting so the user knows what the timeout is
549 // and can see it.
550 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
551 if (host_packet_timeout)
552 {
553 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
554 }
555
556
Greg Claytonef8180a2013-10-15 00:14:28 +0000557 if (reg_num == 0)
558 {
559 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000560
561 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000562 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000563 // See if we can get register definitions from a python file
564 if (ParsePythonTargetDefinition (target_definition_fspec))
565 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000566 }
567 }
568
Johnny Chen2fa9de12012-05-14 18:44:23 +0000569 // We didn't get anything if the accumulated reg_num is zero. See if we are
570 // debugging ARM and fill with a hard coded register set until we can get an
571 // updated debugserver down on the devices.
572 // On the other hand, if the accumulated reg_num is positive, see if we can
573 // add composite registers to the existing primordial ones.
574 bool from_scratch = (reg_num == 0);
575
576 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000577 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
578 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
579
580 // Use the process' architecture instead of the host arch, if available
581 ArchSpec remote_arch;
582 if (remote_process_arch.IsValid ())
583 remote_arch = remote_process_arch;
584 else
585 remote_arch = remote_host_arch;
586
Johnny Chen2fa9de12012-05-14 18:44:23 +0000587 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000588 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000589 if (remote_arch.IsValid()
590 && remote_arch.GetMachine() == llvm::Triple::arm
591 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
592 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000593 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000594 else if (target_arch.GetMachine() == llvm::Triple::arm)
595 {
596 m_register_info.HardcodeARMRegisters(from_scratch);
597 }
598
599 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000600 m_register_info.Finalize ();
601}
602
603Error
604ProcessGDBRemote::WillLaunch (Module* module)
605{
606 return WillLaunchOrAttach ();
607}
608
609Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000610ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611{
612 return WillLaunchOrAttach ();
613}
614
615Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000616ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000617{
618 return WillLaunchOrAttach ();
619}
620
621Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000622ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000623{
624 Error error (WillLaunchOrAttach ());
625
626 if (error.Fail())
627 return error;
628
Greg Clayton2289fa42011-04-30 01:09:13 +0000629 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000630
631 if (error.Fail())
632 return error;
633 StartAsyncThread ();
634
Greg Claytonc574ede2011-03-10 02:26:48 +0000635 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000636 if (pid == LLDB_INVALID_PROCESS_ID)
637 {
638 // We don't have a valid process ID, so note that we are connected
639 // and could now request to launch or attach, or get remote process
640 // listings...
641 SetPrivateState (eStateConnected);
642 }
643 else
644 {
645 // We have a valid process
646 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000647 GetThreadList();
Greg Claytondd0e5a52011-06-02 22:22:38 +0000648 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytonb766a732011-02-04 01:58:07 +0000649 {
Carlo Kok74389122013-10-14 07:09:13 +0000650 if (!m_target.GetArchitecture().IsValid()) { // Make sure we have an architecture
651 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
652 }
653
654
Greg Claytondd0e5a52011-06-02 22:22:38 +0000655 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000656 if (state == eStateStopped)
657 {
658 SetPrivateState (state);
659 }
660 else
Daniel Malead01b2952012-11-29 21:49:15 +0000661 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
Greg Claytonb766a732011-02-04 01:58:07 +0000662 }
663 else
Daniel Malead01b2952012-11-29 21:49:15 +0000664 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000665 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000666
667 if (error.Success()
668 && !GetTarget().GetArchitecture().IsValid()
669 && m_gdb_comm.GetHostArchitecture().IsValid())
670 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000671 // Prefer the *process'* architecture over that of the *host*, if available.
672 if (m_gdb_comm.GetProcessArchitecture().IsValid())
673 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
674 else
675 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000676 }
677
Greg Claytonb766a732011-02-04 01:58:07 +0000678 return error;
679}
680
681Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682ProcessGDBRemote::WillLaunchOrAttach ()
683{
684 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000685 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000686 return error;
687}
688
689//----------------------------------------------------------------------
690// Process Control
691//----------------------------------------------------------------------
692Error
Greg Clayton982c9762011-11-03 21:22:33 +0000693ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694{
Greg Clayton4957bf62010-09-30 21:49:03 +0000695 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000696
697 uint32_t launch_flags = launch_info.GetFlags().Get();
698 const char *stdin_path = NULL;
699 const char *stdout_path = NULL;
700 const char *stderr_path = NULL;
701 const char *working_dir = launch_info.GetWorkingDirectory();
702
703 const ProcessLaunchInfo::FileAction *file_action;
704 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
705 if (file_action)
706 {
707 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
708 stdin_path = file_action->GetPath();
709 }
710 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
711 if (file_action)
712 {
713 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
714 stdout_path = file_action->GetPath();
715 }
716 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
717 if (file_action)
718 {
719 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
720 stderr_path = file_action->GetPath();
721 }
722
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
724 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
725 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000726 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727
Greg Clayton982c9762011-11-03 21:22:33 +0000728 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729 if (object_file)
730 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 char host_port[128];
732 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
Greg Claytonb766a732011-02-04 01:58:07 +0000733 char connect_url[128];
734 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735
Greg Clayton71337622011-02-24 22:24:29 +0000736 // Make sure we aren't already connected?
737 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738 {
Han Ming Ong84647042012-02-25 01:07:38 +0000739 error = StartDebugserverProcess (host_port, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740 if (error.Fail())
Greg Claytonc235ac72011-08-09 05:20:29 +0000741 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000742 if (log)
743 log->Printf("failed to start debugserver process: %s", error.AsCString());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 return error;
Greg Claytonc235ac72011-08-09 05:20:29 +0000745 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746
Greg Claytonb766a732011-02-04 01:58:07 +0000747 error = ConnectToDebugserver (connect_url);
Greg Clayton71337622011-02-24 22:24:29 +0000748 }
749
750 if (error.Success())
751 {
752 lldb_utility::PseudoTerminal pty;
753 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000754
755 // If the debugserver is local and we aren't disabling STDIO, lets use
756 // a pseudo terminal to instead of relying on the 'O' packets for stdio
757 // since 'O' packets can really slow down debugging if the inferior
758 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000759 PlatformSP platform_sp (m_target.GetPlatform());
760 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000761 {
762 const char *slave_name = NULL;
763 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764 {
Greg Clayton71337622011-02-24 22:24:29 +0000765 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
766 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767 }
Greg Clayton71337622011-02-24 22:24:29 +0000768 if (stdin_path == NULL)
769 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000770
Greg Clayton71337622011-02-24 22:24:29 +0000771 if (stdout_path == NULL)
772 stdout_path = slave_name;
773
774 if (stderr_path == NULL)
775 stderr_path = slave_name;
776 }
777
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000778 // Set STDIN to /dev/null if we want STDIO disabled or if either
779 // STDOUT or STDERR have been set to something and STDIN hasn't
780 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000781 stdin_path = "/dev/null";
782
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000783 // Set STDOUT to /dev/null if we want STDIO disabled or if either
784 // STDIN or STDERR have been set to something and STDOUT hasn't
785 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000786 stdout_path = "/dev/null";
787
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000788 // Set STDERR to /dev/null if we want STDIO disabled or if either
789 // STDIN or STDOUT have been set to something and STDERR hasn't
790 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000791 stderr_path = "/dev/null";
792
793 if (stdin_path)
794 m_gdb_comm.SetSTDIN (stdin_path);
795 if (stdout_path)
796 m_gdb_comm.SetSTDOUT (stdout_path);
797 if (stderr_path)
798 m_gdb_comm.SetSTDERR (stderr_path);
799
800 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
801
Greg Claytonc4103b32011-05-08 04:53:50 +0000802 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000803
804 if (working_dir && working_dir[0])
805 {
806 m_gdb_comm.SetWorkingDir (working_dir);
807 }
808
809 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000810 const Args &environment = launch_info.GetEnvironmentEntries();
811 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000812 {
Greg Clayton982c9762011-11-03 21:22:33 +0000813 size_t num_environment_entries = environment.GetArgumentCount();
814 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000815 {
Greg Clayton982c9762011-11-03 21:22:33 +0000816 const char *env_entry = environment.GetArgumentAtIndex(i);
817 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000818 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000819 }
Greg Clayton71337622011-02-24 22:24:29 +0000820 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000821
Greg Claytonc574ede2011-03-10 02:26:48 +0000822 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000823 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000824 if (arg_packet_err == 0)
825 {
826 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000827 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000829 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830 }
831 else
832 {
Greg Clayton71337622011-02-24 22:24:29 +0000833 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834 }
Greg Clayton71337622011-02-24 22:24:29 +0000835 }
836 else
837 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000838 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000839 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000840
841 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000842
Greg Clayton71337622011-02-24 22:24:29 +0000843 if (GetID() == LLDB_INVALID_PROCESS_ID)
844 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000845 if (log)
846 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000847 KillDebugserverProcess ();
848 return error;
849 }
850
Greg Claytondd0e5a52011-06-02 22:22:38 +0000851 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Clayton71337622011-02-24 22:24:29 +0000852 {
Carlo Kok74389122013-10-14 07:09:13 +0000853 if (!m_target.GetArchitecture().IsValid()) { // Make sure we have an architecture
854 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
855 }
856
Greg Claytondd0e5a52011-06-02 22:22:38 +0000857 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000858
859 if (!disable_stdio)
860 {
861 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000862 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000863 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864 }
865 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000866 else
867 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000868 if (log)
869 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000870 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000871 }
872 else
873 {
874 // Set our user ID to an invalid process ID.
875 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000876 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
877 exe_module->GetFileSpec().GetFilename().AsCString(),
878 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000881
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882}
883
884
885Error
Greg Claytonb766a732011-02-04 01:58:07 +0000886ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887{
888 Error error;
889 // Sleep and wait a bit for debugserver to start to listen...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000890 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 if (conn_ap.get())
892 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893 const uint32_t max_retry_count = 50;
894 uint32_t retry_count = 0;
895 while (!m_gdb_comm.IsConnected())
896 {
Greg Claytonb766a732011-02-04 01:58:07 +0000897 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000898 {
899 m_gdb_comm.SetConnection (conn_ap.release());
900 break;
901 }
Jim Ingham4e5c8212013-06-07 22:09:53 +0000902 else if (error.WasInterrupted())
903 {
904 // If we were interrupted, don't keep retrying.
905 break;
906 }
907
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908 retry_count++;
Jim Ingham4e5c8212013-06-07 22:09:53 +0000909
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 if (retry_count >= max_retry_count)
911 break;
912
913 usleep (100000);
914 }
915 }
916
917 if (!m_gdb_comm.IsConnected())
918 {
919 if (error.Success())
920 error.SetErrorString("not connected to remote gdb server");
921 return error;
922 }
923
Greg Clayton32e0a752011-03-30 18:16:51 +0000924 // We always seem to be able to open a connection to a local port
925 // so we need to make sure we can then send data to it. If we can't
926 // then we aren't actually connected to anything, so try and do the
927 // handshake with the remote GDB server and make sure that goes
928 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +0000929 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000931 m_gdb_comm.Disconnect();
932 if (error.Success())
933 error.SetErrorString("not connected to remote gdb server");
934 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000936 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000937 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000938 m_gdb_comm.GetHostInfo ();
939 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000940 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000941
942 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
943 for (size_t idx = 0; idx < num_cmds; idx++)
944 {
945 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000946 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
947 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000948 return error;
949}
950
951void
952ProcessGDBRemote::DidLaunchOrAttach ()
953{
Greg Clayton5160ce52013-03-27 23:08:40 +0000954 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000955 if (log)
956 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000957 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000959 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000960
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000962
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000963 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
964
965 // See if the GDB server supports the qProcessInfo packet, if so
966 // prefer that over the Host information as it will be more specific
967 // to our process.
968
969 if (m_gdb_comm.GetProcessArchitecture().IsValid())
970 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
971
Greg Claytond314e812011-03-23 00:09:55 +0000972 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000973 {
Greg Claytond314e812011-03-23 00:09:55 +0000974 ArchSpec &target_arch = GetTarget().GetArchitecture();
975
976 if (target_arch.IsValid())
977 {
978 // If the remote host is ARM and we have apple as the vendor, then
979 // ARM executables and shared libraries can have mixed ARM architectures.
980 // You can have an armv6 executable, and if the host is armv7, then the
981 // system will load the best possible architecture for all shared libraries
982 // it has, so we really need to take the remote host architecture as our
983 // defacto architecture in this case.
984
985 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
986 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
987 {
988 target_arch = gdb_remote_arch;
989 }
990 else
991 {
992 // Fill in what is missing in the triple
993 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
994 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000995 if (target_triple.getVendorName().size() == 0)
996 {
Greg Claytond314e812011-03-23 00:09:55 +0000997 target_triple.setVendor (remote_triple.getVendor());
998
Greg Clayton70b57652011-05-15 01:25:55 +0000999 if (target_triple.getOSName().size() == 0)
1000 {
1001 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +00001002
Greg Clayton70b57652011-05-15 01:25:55 +00001003 if (target_triple.getEnvironmentName().size() == 0)
1004 target_triple.setEnvironment (remote_triple.getEnvironment());
1005 }
1006 }
Greg Claytond314e812011-03-23 00:09:55 +00001007 }
1008 }
1009 else
1010 {
1011 // The target doesn't have a valid architecture yet, set it from
1012 // the architecture we got from the remote GDB server
1013 target_arch = gdb_remote_arch;
1014 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +00001015 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016 }
1017}
1018
1019void
1020ProcessGDBRemote::DidLaunch ()
1021{
1022 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023}
1024
1025Error
Greg Claytonc982c762010-07-09 20:39:50 +00001026ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027{
Han Ming Ong84647042012-02-25 01:07:38 +00001028 ProcessAttachInfo attach_info;
1029 return DoAttachToProcessWithID(attach_pid, attach_info);
1030}
1031
1032Error
1033ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1034{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035 Error error;
1036 // Clear out and clean up from any current state
1037 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1039 {
Greg Clayton71337622011-02-24 22:24:29 +00001040 // Make sure we aren't already connected?
1041 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001042 {
Greg Clayton71337622011-02-24 22:24:29 +00001043 char host_port[128];
1044 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1045 char connect_url[128];
1046 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047
Han Ming Ong84647042012-02-25 01:07:38 +00001048 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001049
1050 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051 {
Greg Clayton71337622011-02-24 22:24:29 +00001052 const char *error_string = error.AsCString();
1053 if (error_string == NULL)
1054 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1055
1056 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057 }
Greg Clayton71337622011-02-24 22:24:29 +00001058 else
1059 {
1060 error = ConnectToDebugserver (connect_url);
1061 }
1062 }
1063
1064 if (error.Success())
1065 {
1066 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001067 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001068 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001069 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 }
1071 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072 return error;
1073}
1074
1075size_t
1076ProcessGDBRemote::AttachInputReaderCallback
1077(
1078 void *baton,
1079 InputReader *reader,
1080 lldb::InputReaderAction notification,
1081 const char *bytes,
1082 size_t bytes_len
1083)
1084{
1085 if (notification == eInputReaderGotToken)
1086 {
1087 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1088 if (gdb_process->m_waiting_for_attach)
1089 gdb_process->m_waiting_for_attach = false;
1090 reader->SetIsDone(true);
1091 return 1;
1092 }
1093 return 0;
1094}
1095
1096Error
Han Ming Ong84647042012-02-25 01:07:38 +00001097ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098{
1099 Error error;
1100 // Clear out and clean up from any current state
1101 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 if (process_name && process_name[0])
1104 {
Greg Clayton71337622011-02-24 22:24:29 +00001105 // Make sure we aren't already connected?
1106 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107 {
Greg Clayton71337622011-02-24 22:24:29 +00001108 char host_port[128];
1109 snprintf (host_port, sizeof(host_port), "localhost:%u", get_random_port ());
1110 char connect_url[128];
1111 snprintf (connect_url, sizeof(connect_url), "connect://%s", host_port);
1112
Han Ming Ong84647042012-02-25 01:07:38 +00001113 error = StartDebugserverProcess (host_port, attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001114 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115 {
Greg Clayton71337622011-02-24 22:24:29 +00001116 const char *error_string = error.AsCString();
1117 if (error_string == NULL)
1118 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119
Greg Clayton71337622011-02-24 22:24:29 +00001120 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121 }
Greg Clayton71337622011-02-24 22:24:29 +00001122 else
1123 {
1124 error = ConnectToDebugserver (connect_url);
1125 }
1126 }
1127
1128 if (error.Success())
1129 {
1130 StreamString packet;
1131
1132 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +00001133 {
1134 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1135 {
1136 packet.PutCString ("vAttachWait");
1137 }
1138 else
1139 {
1140 if (attach_info.GetIgnoreExisting())
1141 packet.PutCString("vAttachWait");
1142 else
1143 packet.PutCString ("vAttachOrWait");
1144 }
1145 }
Greg Clayton71337622011-02-24 22:24:29 +00001146 else
1147 packet.PutCString("vAttachName");
1148 packet.PutChar(';');
1149 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1150
1151 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1152
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153 }
1154 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155 return error;
1156}
1157
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158
Greg Claytonfbb76342013-11-20 21:07:01 +00001159bool
1160ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1161{
1162 m_gdb_comm.Disconnect();
1163 return Process::SetExitStatus (exit_status, cstr);
1164}
1165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166void
1167ProcessGDBRemote::DidAttach ()
1168{
Greg Claytonb766a732011-02-04 01:58:07 +00001169 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170}
1171
Greg Clayton90ba8112012-12-05 00:16:59 +00001172
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173Error
1174ProcessGDBRemote::WillResume ()
1175{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001176 m_continue_c_tids.clear();
1177 m_continue_C_tids.clear();
1178 m_continue_s_tids.clear();
1179 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180 return Error();
1181}
1182
1183Error
1184ProcessGDBRemote::DoResume ()
1185{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001186 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001187 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001188 if (log)
1189 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001190
1191 Listener listener ("gdb-remote.resume-packet-sent");
1192 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1193 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001194 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1195
Greg Claytond1d06e42013-04-20 00:27:58 +00001196 const size_t num_threads = GetThreadList().GetSize();
1197
Greg Clayton71fc2a32011-02-12 06:28:37 +00001198 StreamString continue_packet;
1199 bool continue_packet_error = false;
1200 if (m_gdb_comm.HasAnyVContSupport ())
1201 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001202 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001203 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001204 // All threads are continuing, just send a "c" packet
1205 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001206 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001207 else
1208 {
1209 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001210
Greg Claytond1d06e42013-04-20 00:27:58 +00001211 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001212 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001213 if (m_gdb_comm.GetVContSupported ('c'))
1214 {
1215 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)
1216 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1217 }
1218 else
1219 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001220 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001221
1222 if (!continue_packet_error && !m_continue_C_tids.empty())
1223 {
1224 if (m_gdb_comm.GetVContSupported ('C'))
1225 {
1226 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)
1227 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1228 }
1229 else
1230 continue_packet_error = true;
1231 }
Greg Claytone5219662010-12-03 06:02:24 +00001232
Greg Claytond1d06e42013-04-20 00:27:58 +00001233 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001234 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001235 if (m_gdb_comm.GetVContSupported ('s'))
1236 {
1237 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)
1238 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1239 }
1240 else
1241 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001242 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001243
1244 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001245 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001246 if (m_gdb_comm.GetVContSupported ('S'))
1247 {
1248 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)
1249 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1250 }
1251 else
1252 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001253 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001254
1255 if (continue_packet_error)
1256 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001257 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001258 }
1259 else
1260 continue_packet_error = true;
1261
1262 if (continue_packet_error)
1263 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001264 // Either no vCont support, or we tried to use part of the vCont
1265 // packet that wasn't supported by the remote GDB server.
1266 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001267 const size_t num_continue_c_tids = m_continue_c_tids.size();
1268 const size_t num_continue_C_tids = m_continue_C_tids.size();
1269 const size_t num_continue_s_tids = m_continue_s_tids.size();
1270 const size_t num_continue_S_tids = m_continue_S_tids.size();
1271 if (num_continue_c_tids > 0)
1272 {
1273 if (num_continue_c_tids == num_threads)
1274 {
1275 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001276 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001277 continue_packet.PutChar ('c');
1278 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001279 }
1280 else if (num_continue_c_tids == 1 &&
1281 num_continue_C_tids == 0 &&
1282 num_continue_s_tids == 0 &&
1283 num_continue_S_tids == 0 )
1284 {
1285 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001286 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001287 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001288 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001289 }
1290 }
1291
Greg Clayton0c74e782011-06-24 03:21:43 +00001292 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001293 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001294 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1295 num_continue_C_tids > 0 &&
1296 num_continue_s_tids == 0 &&
1297 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001298 {
1299 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001300 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001301 if (num_continue_C_tids > 1)
1302 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001303 // More that one thread with a signal, yet we don't have
1304 // vCont support and we are being asked to resume each
1305 // thread with a signal, we need to make sure they are
1306 // all the same signal, or we can't issue the continue
1307 // accurately with the current support...
1308 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001309 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001310 continue_packet_error = false;
1311 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1312 {
1313 if (m_continue_C_tids[i].second != continue_signo)
1314 continue_packet_error = true;
1315 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001316 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001317 if (!continue_packet_error)
1318 m_gdb_comm.SetCurrentThreadForRun (-1);
1319 }
1320 else
1321 {
1322 // Set the continue thread ID
1323 continue_packet_error = false;
1324 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001325 }
1326 if (!continue_packet_error)
1327 {
1328 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001329 continue_packet.Printf("C%2.2x", continue_signo);
1330 }
1331 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001332 }
1333
Greg Clayton0c74e782011-06-24 03:21:43 +00001334 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001335 {
1336 if (num_continue_s_tids == num_threads)
1337 {
1338 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001339 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001340 continue_packet.PutChar ('s');
1341 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001342 }
1343 else if (num_continue_c_tids == 0 &&
1344 num_continue_C_tids == 0 &&
1345 num_continue_s_tids == 1 &&
1346 num_continue_S_tids == 0 )
1347 {
1348 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001349 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001350 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001351 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001352 }
1353 }
1354
1355 if (!continue_packet_error && num_continue_S_tids > 0)
1356 {
1357 if (num_continue_S_tids == num_threads)
1358 {
1359 const int step_signo = m_continue_S_tids.front().second;
1360 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001361 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001362 if (num_continue_S_tids > 1)
1363 {
1364 for (size_t i=1; i<num_threads; ++i)
1365 {
1366 if (m_continue_S_tids[i].second != step_signo)
1367 continue_packet_error = true;
1368 }
1369 }
1370 if (!continue_packet_error)
1371 {
1372 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001373 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001374 continue_packet.Printf("S%2.2x", step_signo);
1375 }
1376 }
1377 else if (num_continue_c_tids == 0 &&
1378 num_continue_C_tids == 0 &&
1379 num_continue_s_tids == 0 &&
1380 num_continue_S_tids == 1 )
1381 {
1382 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001383 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001384 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001385 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001386 }
1387 }
1388 }
1389
1390 if (continue_packet_error)
1391 {
1392 error.SetErrorString ("can't make continue packet for this resume");
1393 }
1394 else
1395 {
1396 EventSP event_sp;
1397 TimeValue timeout;
1398 timeout = TimeValue::Now();
1399 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001400 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1401 {
1402 error.SetErrorString ("Trying to resume but the async thread is dead.");
1403 if (log)
1404 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1405 return error;
1406 }
1407
Greg Clayton71fc2a32011-02-12 06:28:37 +00001408 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1409
1410 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001411 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001412 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001413 if (log)
1414 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1415 }
1416 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1417 {
1418 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1419 if (log)
1420 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1421 return error;
1422 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001423 }
Greg Claytone5219662010-12-03 06:02:24 +00001424 }
1425
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001426 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427}
1428
Greg Clayton9e920902012-04-10 02:25:43 +00001429void
1430ProcessGDBRemote::ClearThreadIDList ()
1431{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001432 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001433 m_thread_ids.clear();
1434}
1435
1436bool
1437ProcessGDBRemote::UpdateThreadIDList ()
1438{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001439 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001440 bool sequence_mutex_unavailable = false;
1441 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1442 if (sequence_mutex_unavailable)
1443 {
Greg Clayton9e920902012-04-10 02:25:43 +00001444 return false; // We just didn't get the list
1445 }
1446 return true;
1447}
1448
Greg Clayton9fc13552012-04-10 00:18:59 +00001449bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001450ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001451{
1452 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001453 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001454 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001455 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001456
1457 size_t num_thread_ids = m_thread_ids.size();
1458 // The "m_thread_ids" thread ID list should always be updated after each stop
1459 // reply packet, but in case it isn't, update it here.
1460 if (num_thread_ids == 0)
1461 {
1462 if (!UpdateThreadIDList ())
1463 return false;
1464 num_thread_ids = m_thread_ids.size();
1465 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001466
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001467 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001468 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001470 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471 {
Greg Clayton9e920902012-04-10 02:25:43 +00001472 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001473 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001474 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001475 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001476 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001477 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1478 log->Printf(
1479 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1480 __FUNCTION__,
1481 thread_sp.get(),
1482 thread_sp->GetID());
1483 }
1484 else
1485 {
1486 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1487 log->Printf(
1488 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1489 __FUNCTION__,
1490 thread_sp.get(),
1491 thread_sp->GetID());
1492 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001493 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001494 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001495 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001496
1497 // Whatever that is left in old_thread_list_copy are not
1498 // present in new_thread_list. Remove non-existent threads from internal id table.
1499 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1500 for (size_t i=0; i<old_num_thread_ids; i++)
1501 {
1502 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1503 if (old_thread_sp)
1504 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001505 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001506 m_thread_id_to_index_id_map.erase(old_thread_id);
1507 }
1508 }
1509
Greg Clayton9fc13552012-04-10 00:18:59 +00001510 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001511}
1512
1513
1514StateType
1515ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1516{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001517 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001518 const char stop_type = stop_packet.GetChar();
1519 switch (stop_type)
1520 {
1521 case 'T':
1522 case 'S':
1523 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001524 // This is a bit of a hack, but is is required. If we did exec, we
1525 // need to clear our thread lists and also know to rebuild our dynamic
1526 // register info before we lookup and threads and populate the expedited
1527 // register values so we need to know this right away so we can cleanup
1528 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001529 const uint32_t stop_id = GetStopID();
1530 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001531 {
1532 // Our first stop, make sure we have a process ID, and also make
1533 // sure we know about our registers
1534 if (GetID() == LLDB_INVALID_PROCESS_ID)
1535 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001536 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001537 if (pid != LLDB_INVALID_PROCESS_ID)
1538 SetID (pid);
1539 }
1540 BuildDynamicRegisterInfo (true);
1541 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542 // Stop with signal and thread info
1543 const uint8_t signo = stop_packet.GetHexU8();
1544 std::string name;
1545 std::string value;
1546 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001547 std::string reason;
1548 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001549 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001550 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001551 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001552 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001553 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001554
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001555 while (stop_packet.GetNameColonValue(name, value))
1556 {
1557 if (name.compare("metype") == 0)
1558 {
1559 // exception type in big endian hex
1560 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1561 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001562 else if (name.compare("medata") == 0)
1563 {
1564 // exception data in big endian hex
1565 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1566 }
1567 else if (name.compare("thread") == 0)
1568 {
1569 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001570 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001571 // m_thread_list_real does have its own mutex, but we need to
1572 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1573 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1574 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1575 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001576
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001577 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001578 {
Greg Claytone576ab22011-02-15 00:19:15 +00001579 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001580 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001581 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1582 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1583 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1584 __FUNCTION__,
1585 thread_sp.get(),
1586 thread_sp->GetID());
1587
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001588 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001589 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001590 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592 }
Greg Clayton9e920902012-04-10 02:25:43 +00001593 else if (name.compare("threads") == 0)
1594 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001595 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001596 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001597 // A comma separated list of all threads in the current
1598 // process that includes the thread for this stop reply
1599 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001600 size_t comma_pos;
1601 lldb::tid_t tid;
1602 while ((comma_pos = value.find(',')) != std::string::npos)
1603 {
1604 value[comma_pos] = '\0';
1605 // thread in big endian hex
1606 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1607 if (tid != LLDB_INVALID_THREAD_ID)
1608 m_thread_ids.push_back (tid);
1609 value.erase(0, comma_pos + 1);
1610
1611 }
1612 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1613 if (tid != LLDB_INVALID_THREAD_ID)
1614 m_thread_ids.push_back (tid);
1615 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001616 else if (name.compare("hexname") == 0)
1617 {
1618 StringExtractor name_extractor;
1619 // Swap "value" over into "name_extractor"
1620 name_extractor.GetStringRef().swap(value);
1621 // Now convert the HEX bytes into a string value
1622 name_extractor.GetHexByteString (value);
1623 thread_name.swap (value);
1624 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001625 else if (name.compare("name") == 0)
1626 {
1627 thread_name.swap (value);
1628 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001629 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001630 {
1631 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1632 }
Greg Claytona658fd22011-06-04 01:26:29 +00001633 else if (name.compare("reason") == 0)
1634 {
1635 reason.swap(value);
1636 }
1637 else if (name.compare("description") == 0)
1638 {
1639 StringExtractor desc_extractor;
1640 // Swap "value" over into "name_extractor"
1641 desc_extractor.GetStringRef().swap(value);
1642 // Now convert the HEX bytes into a string value
1643 desc_extractor.GetHexByteString (thread_name);
1644 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001645 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1646 {
1647 // We have a register number that contains an expedited
1648 // register value. Lets supply this register to our thread
1649 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001650 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001651 {
1652 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1653
1654 if (reg != UINT32_MAX)
1655 {
1656 StringExtractor reg_value_extractor;
1657 // Swap "value" over into "reg_value_extractor"
1658 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001659 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001660 {
1661 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1662 name.c_str(),
1663 reg,
1664 reg,
1665 reg_value_extractor.GetStringRef().c_str(),
1666 stop_packet.GetStringRef().c_str());
1667 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001668 }
1669 }
1670 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001671 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672
1673 if (thread_sp)
1674 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001675 // Clear the stop info just in case we don't set it to anything
1676 thread_sp->SetStopInfo (StopInfoSP());
1677
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001678 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001679 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680 if (exc_type != 0)
1681 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001682 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001683
Greg Clayton160c9d82013-05-01 21:54:04 +00001684 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1685 exc_type,
1686 exc_data_size,
1687 exc_data_size >= 1 ? exc_data[0] : 0,
1688 exc_data_size >= 2 ? exc_data[1] : 0,
1689 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001690 }
Greg Claytona658fd22011-06-04 01:26:29 +00001691 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001692 {
Greg Claytona658fd22011-06-04 01:26:29 +00001693 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001694 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001695 if (!reason.empty())
1696 {
1697 if (reason.compare("trace") == 0)
1698 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001699 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001700 handled = true;
1701 }
1702 else if (reason.compare("breakpoint") == 0)
1703 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001704 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1705 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001706 if (bp_site_sp)
1707 {
1708 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1709 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1710 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001711 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001712 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001713 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001714 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001715 }
1716 else
1717 {
1718 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001719 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001720 }
1721 }
1722
Greg Claytona658fd22011-06-04 01:26:29 +00001723 }
1724 else if (reason.compare("trap") == 0)
1725 {
1726 // Let the trap just use the standard signal stop reason below...
1727 }
1728 else if (reason.compare("watchpoint") == 0)
1729 {
1730 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1731 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001732 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001733 handled = true;
1734 }
1735 else if (reason.compare("exception") == 0)
1736 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001737 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001738 handled = true;
1739 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001740 else if (reason.compare("exec") == 0)
1741 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001742 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001743 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1744 handled = true;
1745 }
Greg Claytona658fd22011-06-04 01:26:29 +00001746 }
1747
Greg Clayton15fc2be2013-05-21 01:00:52 +00001748 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001749 {
1750 if (signo == SIGTRAP)
1751 {
1752 // Currently we are going to assume SIGTRAP means we are either
1753 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001754 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001755 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001756 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001757
Greg Claytona658fd22011-06-04 01:26:29 +00001758 if (bp_site_sp)
1759 {
1760 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1761 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1762 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
Greg Clayton160c9d82013-05-01 21:54:04 +00001763 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001764 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001765 if(m_breakpoint_pc_offset != 0)
1766 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001767 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001768 }
1769 else
1770 {
1771 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001772 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001773 }
1774 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001775 else
Greg Claytona658fd22011-06-04 01:26:29 +00001776 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001777 // If we were stepping then assume the stop was the result of the trace. If we were
1778 // not stepping then report the SIGTRAP.
1779 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001780 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1781 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001782 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001783 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001784 }
1785 }
1786 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001787 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001788 }
Greg Claytona658fd22011-06-04 01:26:29 +00001789
1790 if (!description.empty())
1791 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001792 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001793 if (stop_info_sp)
1794 {
1795 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001796 }
Greg Claytona658fd22011-06-04 01:26:29 +00001797 else
1798 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001799 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001800 }
1801 }
1802 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 }
1804 return eStateStopped;
1805 }
1806 break;
1807
1808 case 'W':
1809 // process exited
1810 return eStateExited;
1811
1812 default:
1813 break;
1814 }
1815 return eStateInvalid;
1816}
1817
1818void
1819ProcessGDBRemote::RefreshStateAfterStop ()
1820{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001821 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001822 m_thread_ids.clear();
1823 // Set the thread stop info. It might have a "threads" key whose value is
1824 // a list of all thread IDs in the current process, so m_thread_ids might
1825 // get set.
1826 SetThreadStopInfo (m_last_stop_packet);
1827 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1828 if (m_thread_ids.empty())
1829 {
1830 // No, we need to fetch the thread list manually
1831 UpdateThreadIDList();
1832 }
1833
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 // Let all threads recover from stopping and do any clean up based
1835 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001836 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001837
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838}
1839
1840Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001841ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842{
1843 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001844
Greg Clayton6ed95942011-01-22 07:12:45 +00001845 bool timed_out = false;
1846 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001847
1848 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001849 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001850 // We are being asked to halt during an attach. We need to just close
1851 // our file handle and debugserver will go away, and we can be done...
1852 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001853 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001854 else
1855 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001856 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001857 {
1858 if (timed_out)
1859 error.SetErrorString("timed out sending interrupt packet");
1860 else
1861 error.SetErrorString("unknown error sending interrupt packet");
1862 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001863
1864 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001865 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001866 return error;
1867}
1868
1869Error
Jim Inghamacff8952013-05-02 00:27:30 +00001870ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001871{
1872 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001873 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001874 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001875 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1876
Greg Clayton594e5ed2010-09-27 21:07:38 +00001877 DisableAllBreakpointSites ();
1878
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001879 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001880
Jim Inghamacff8952013-05-02 00:27:30 +00001881 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001882 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001883 {
Jim Inghamacff8952013-05-02 00:27:30 +00001884 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001885 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1886 else
Jim Inghamacff8952013-05-02 00:27:30 +00001887 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001888 }
Jim Inghamacff8952013-05-02 00:27:30 +00001889
1890 if (!error.Success())
1891 return error;
1892
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001893 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001894 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001895
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001896 SetPrivateState (eStateDetached);
1897 ResumePrivateStateThread();
1898
1899 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001900 return error;
1901}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902
Jim Ingham43c555d2012-07-04 00:35:43 +00001903
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904Error
1905ProcessGDBRemote::DoDestroy ()
1906{
1907 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001908 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001909 if (log)
1910 log->Printf ("ProcessGDBRemote::DoDestroy()");
1911
Jim Ingham43c555d2012-07-04 00:35:43 +00001912 // There is a bug in older iOS debugservers where they don't shut down the process
1913 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1914 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1915 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1916 // destroy it again.
1917 //
1918 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1919 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1920 // the debugservers with this bug are equal. There really should be a better way to test this!
1921 //
1922 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1923 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1924 // just do the straight-forward kill.
1925 //
1926 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1927 // necessary (or helpful) to do any of this.
1928
1929 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1930 {
1931 PlatformSP platform_sp = GetTarget().GetPlatform();
1932
1933 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1934 if (platform_sp
1935 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001936 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001937 {
1938 if (m_destroy_tried_resuming)
1939 {
1940 if (log)
1941 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1942 }
1943 else
1944 {
1945 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1946 // but we really need it to happen here and it doesn't matter if we do it twice.
1947 m_thread_list.DiscardThreadPlans();
1948 DisableAllBreakpointSites();
1949
1950 bool stop_looks_like_crash = false;
1951 ThreadList &threads = GetThreadList();
1952
1953 {
Jim Ingham45350372012-09-11 00:08:52 +00001954 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001955
1956 size_t num_threads = threads.GetSize();
1957 for (size_t i = 0; i < num_threads; i++)
1958 {
1959 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001960 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001961 StopReason reason = eStopReasonInvalid;
1962 if (stop_info_sp)
1963 reason = stop_info_sp->GetStopReason();
1964 if (reason == eStopReasonBreakpoint
1965 || reason == eStopReasonException)
1966 {
1967 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001968 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1969 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001970 stop_info_sp->GetDescription());
1971 stop_looks_like_crash = true;
1972 break;
1973 }
1974 }
1975 }
1976
1977 if (stop_looks_like_crash)
1978 {
1979 if (log)
1980 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1981 m_destroy_tried_resuming = true;
1982
1983 // If we are going to run again before killing, it would be good to suspend all the threads
1984 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1985 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1986 // have to run the risk of letting those threads proceed a bit.
1987
1988 {
Jim Ingham45350372012-09-11 00:08:52 +00001989 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001990
1991 size_t num_threads = threads.GetSize();
1992 for (size_t i = 0; i < num_threads; i++)
1993 {
1994 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001995 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001996 StopReason reason = eStopReasonInvalid;
1997 if (stop_info_sp)
1998 reason = stop_info_sp->GetStopReason();
1999 if (reason != eStopReasonBreakpoint
2000 && reason != eStopReasonException)
2001 {
2002 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00002003 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2004 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00002005 thread_sp->SetResumeState(eStateSuspended);
2006 }
2007 }
2008 }
2009 Resume ();
2010 return Destroy();
2011 }
2012 }
2013 }
2014 }
2015
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002016 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00002017 int exit_status = SIGABRT;
2018 std::string exit_string;
2019
Greg Clayton6ed95942011-01-22 07:12:45 +00002020 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002021 {
Jim Inghamaab78372011-10-28 01:11:35 +00002022 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00002023 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002024
2025 StringExtractorGDBRemote response;
2026 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002027 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
2028
Greg Claytonc574ede2011-03-10 02:26:48 +00002029 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00002030 {
2031 char packet_cmd = response.GetChar(0);
2032
2033 if (packet_cmd == 'W' || packet_cmd == 'X')
2034 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002035 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002036 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00002037 exit_status = response.GetHexU8();
2038 }
2039 else
2040 {
2041 if (log)
2042 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2043 exit_string.assign("got unexpected response to k packet: ");
2044 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002045 }
2046 }
2047 else
2048 {
Jim Inghambabfc382012-06-06 00:32:39 +00002049 if (log)
2050 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2051 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002052 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002053
2054 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002055 }
Jim Inghambabfc382012-06-06 00:32:39 +00002056 else
2057 {
2058 if (log)
2059 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00002060 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002061 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002062 }
Jim Inghambabfc382012-06-06 00:32:39 +00002063 else
2064 {
2065 // If we missed setting the exit status on the way out, do it here.
2066 // NB set exit status can be called multiple times, the first one sets the status.
2067 exit_string.assign("destroying when not connected to debugserver");
2068 }
2069
2070 SetExitStatus(exit_status, exit_string.c_str());
2071
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002072 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073 KillDebugserverProcess ();
2074 return error;
2075}
2076
Greg Clayton8cda7f02013-05-21 21:55:59 +00002077void
2078ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2079{
2080 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2081 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2082 if (did_exec)
2083 {
2084 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2085 if (log)
2086 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2087
2088 m_thread_list_real.Clear();
2089 m_thread_list.Clear();
2090 BuildDynamicRegisterInfo (true);
2091 m_gdb_comm.ResetDiscoverableSettings();
2092 }
2093 m_last_stop_packet = response;
2094}
2095
2096
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097//------------------------------------------------------------------
2098// Process Queries
2099//------------------------------------------------------------------
2100
2101bool
2102ProcessGDBRemote::IsAlive ()
2103{
Greg Clayton10177aa2010-12-08 05:08:21 +00002104 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105}
2106
2107addr_t
2108ProcessGDBRemote::GetImageInfoAddress()
2109{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002110 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111}
2112
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113//------------------------------------------------------------------
2114// Process Memory
2115//------------------------------------------------------------------
2116size_t
2117ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2118{
2119 if (size > m_max_memory_size)
2120 {
2121 // Keep memory read sizes down to a sane limit. This function will be
2122 // called multiple times in order to complete the task by
2123 // lldb_private::Process so it is ok to do this.
2124 size = m_max_memory_size;
2125 }
2126
2127 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002128 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002129 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002131 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002132 {
Greg Clayton576d8832011-03-22 04:00:09 +00002133 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134 {
2135 error.Clear();
2136 return response.GetHexBytes(buf, size, '\xdd');
2137 }
Greg Clayton576d8832011-03-22 04:00:09 +00002138 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002139 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002140 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002141 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002143 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144 }
2145 else
2146 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002147 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148 }
2149 return 0;
2150}
2151
2152size_t
2153ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2154{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002155 if (size > m_max_memory_size)
2156 {
2157 // Keep memory read sizes down to a sane limit. This function will be
2158 // called multiple times in order to complete the task by
2159 // lldb_private::Process so it is ok to do this.
2160 size = m_max_memory_size;
2161 }
2162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002163 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002164 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002165 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002167 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168 {
Greg Clayton576d8832011-03-22 04:00:09 +00002169 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002170 {
2171 error.Clear();
2172 return size;
2173 }
Greg Clayton576d8832011-03-22 04:00:09 +00002174 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002175 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002176 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002177 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002179 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002180 }
2181 else
2182 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002183 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184 }
2185 return 0;
2186}
2187
2188lldb::addr_t
2189ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2190{
Greg Clayton2a48f522011-05-14 01:50:35 +00002191 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2192
Greg Clayton70b57652011-05-15 01:25:55 +00002193 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002194 switch (supported)
2195 {
2196 case eLazyBoolCalculate:
2197 case eLazyBoolYes:
2198 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2199 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2200 return allocated_addr;
2201
2202 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002203 // Call mmap() to create memory in the inferior..
2204 unsigned prot = 0;
2205 if (permissions & lldb::ePermissionsReadable)
2206 prot |= eMmapProtRead;
2207 if (permissions & lldb::ePermissionsWritable)
2208 prot |= eMmapProtWrite;
2209 if (permissions & lldb::ePermissionsExecutable)
2210 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002211
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002212 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2213 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2214 m_addr_to_mmap_size[allocated_addr] = size;
2215 else
2216 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002217 break;
2218 }
2219
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002220 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002221 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222 else
2223 error.Clear();
2224 return allocated_addr;
2225}
2226
2227Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002228ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2229 MemoryRegionInfo &region_info)
2230{
2231
2232 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2233 return error;
2234}
2235
2236Error
Johnny Chen64637202012-05-23 21:09:52 +00002237ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2238{
2239
2240 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2241 return error;
2242}
2243
2244Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002245ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2246{
2247 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2248 return error;
2249}
2250
2251Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2253{
2254 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002255 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2256
2257 switch (supported)
2258 {
2259 case eLazyBoolCalculate:
2260 // We should never be deallocating memory without allocating memory
2261 // first so we should never get eLazyBoolCalculate
2262 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2263 break;
2264
2265 case eLazyBoolYes:
2266 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002267 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002268 break;
2269
2270 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002271 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002272 {
2273 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002274 if (pos != m_addr_to_mmap_size.end() &&
2275 InferiorCallMunmap(this, addr, pos->second))
2276 m_addr_to_mmap_size.erase (pos);
2277 else
Daniel Malead01b2952012-11-29 21:49:15 +00002278 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002279 }
2280 break;
2281 }
2282
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283 return error;
2284}
2285
2286
2287//------------------------------------------------------------------
2288// Process STDIO
2289//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290size_t
2291ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2292{
2293 if (m_stdio_communication.IsConnected())
2294 {
2295 ConnectionStatus status;
2296 m_stdio_communication.Write(src, src_len, status, NULL);
2297 }
2298 return 0;
2299}
2300
2301Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002302ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303{
2304 Error error;
2305 assert (bp_site != NULL);
2306
Greg Clayton5160ce52013-03-27 23:08:40 +00002307 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002308 user_id_t site_id = bp_site->GetID();
2309 const addr_t addr = bp_site->GetLoadAddress();
2310 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002311 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312
2313 if (bp_site->IsEnabled())
2314 {
2315 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002316 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317 return error;
2318 }
2319 else
2320 {
2321 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2322
Greg Claytoneb023e72013-10-11 19:48:25 +00002323 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 {
2325 // Try and set hardware breakpoint, and if that fails, fall through
2326 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002327 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002328 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002329 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 {
2331 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002332 bp_site->SetType (BreakpointSite::eHardware);
Greg Claytoneb023e72013-10-11 19:48:25 +00002333 }
2334 else
2335 {
2336 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002339 else
2340 {
2341 error.SetErrorString("hardware breakpoints are not supported");
2342 }
2343 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002345 else if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002347 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2348 {
2349 bp_site->SetEnabled(true);
2350 bp_site->SetType (BreakpointSite::eExternal);
2351 return error;
2352 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002354
2355 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 }
2357
2358 if (log)
2359 {
2360 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002361 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002362 bp_site->GetLoadAddress(),
2363 err_string ? err_string : "NULL");
2364 }
2365 // We shouldn't reach here on a successful breakpoint enable...
2366 if (error.Success())
2367 error.SetErrorToGenericError();
2368 return error;
2369}
2370
2371Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002372ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373{
2374 Error error;
2375 assert (bp_site != NULL);
2376 addr_t addr = bp_site->GetLoadAddress();
2377 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002378 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002379 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002380 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381
2382 if (bp_site->IsEnabled())
2383 {
2384 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2385
Greg Clayton8b82f082011-04-12 05:54:46 +00002386 BreakpointSite::Type bp_type = bp_site->GetType();
2387 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002389 case BreakpointSite::eSoftware:
2390 error = DisableSoftwareBreakpoint (bp_site);
2391 break;
2392
2393 case BreakpointSite::eHardware:
2394 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2395 error.SetErrorToGenericError();
2396 break;
2397
2398 case BreakpointSite::eExternal:
2399 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2400 error.SetErrorToGenericError();
2401 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002403 if (error.Success())
2404 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002405 }
2406 else
2407 {
2408 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002409 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 return error;
2411 }
2412
2413 if (error.Success())
2414 error.SetErrorToGenericError();
2415 return error;
2416}
2417
Johnny Chen11309a32011-09-06 22:38:36 +00002418// Pre-requisite: wp != NULL.
2419static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002420GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002421{
2422 assert(wp);
2423 bool watch_read = wp->WatchpointRead();
2424 bool watch_write = wp->WatchpointWrite();
2425
2426 // watch_read and watch_write cannot both be false.
2427 assert(watch_read || watch_write);
2428 if (watch_read && watch_write)
2429 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002430 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002431 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002432 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002433 return eWatchpointWrite;
2434}
2435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002437ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002438{
2439 Error error;
2440 if (wp)
2441 {
2442 user_id_t watchID = wp->GetID();
2443 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002444 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002445 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002446 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002447 if (wp->IsEnabled())
2448 {
2449 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002450 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 return error;
2452 }
Johnny Chen11309a32011-09-06 22:38:36 +00002453
2454 GDBStoppointType type = GetGDBStoppointType(wp);
2455 // Pass down an appropriate z/Z packet...
2456 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002457 {
Johnny Chen11309a32011-09-06 22:38:36 +00002458 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2459 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002460 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002461 return error;
2462 }
2463 else
2464 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002465 }
Johnny Chen11309a32011-09-06 22:38:36 +00002466 else
2467 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468 }
2469 else
2470 {
Johnny Chen01a67862011-10-14 00:42:25 +00002471 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472 }
2473 if (error.Success())
2474 error.SetErrorToGenericError();
2475 return error;
2476}
2477
2478Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002479ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480{
2481 Error error;
2482 if (wp)
2483 {
2484 user_id_t watchID = wp->GetID();
2485
Greg Clayton5160ce52013-03-27 23:08:40 +00002486 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002487
2488 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002489
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002490 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002491 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492
Johnny Chen11309a32011-09-06 22:38:36 +00002493 if (!wp->IsEnabled())
2494 {
2495 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002496 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
Johnny Chen892943f2012-08-23 22:28:26 +00002497 // See also 'class WatchpointSentry' within StopInfo.cpp.
2498 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2499 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002500 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002501 return error;
2502 }
2503
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002504 if (wp->IsHardware())
2505 {
Johnny Chen11309a32011-09-06 22:38:36 +00002506 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002508 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2509 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002510 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002511 return error;
2512 }
2513 else
2514 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002515 }
2516 // TODO: clear software watchpoints if we implement them
2517 }
2518 else
2519 {
Johnny Chen01a67862011-10-14 00:42:25 +00002520 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002521 }
2522 if (error.Success())
2523 error.SetErrorToGenericError();
2524 return error;
2525}
2526
2527void
2528ProcessGDBRemote::Clear()
2529{
2530 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002531 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533}
2534
2535Error
2536ProcessGDBRemote::DoSignal (int signo)
2537{
2538 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002539 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002540 if (log)
2541 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2542
2543 if (!m_gdb_comm.SendAsyncSignal (signo))
2544 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2545 return error;
2546}
2547
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002548Error
Han Ming Ong84647042012-02-25 01:07:38 +00002549ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url)
2550{
2551 ProcessLaunchInfo launch_info;
2552 return StartDebugserverProcess(debugserver_url, launch_info);
2553}
2554
2555Error
2556ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...")
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002557{
2558 Error error;
2559 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2560 {
2561 // If we locate debugserver, keep that located version around
2562 static FileSpec g_debugserver_file_spec;
2563
Han Ming Ong84647042012-02-25 01:07:38 +00002564 ProcessLaunchInfo debugserver_launch_info;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002565 char debugserver_path[PATH_MAX];
Han Ming Ong84647042012-02-25 01:07:38 +00002566 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002567
2568 // Always check to see if we have an environment override for the path
2569 // to the debugserver to use and use it if we do.
2570 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
2571 if (env_debugserver_path)
Greg Clayton274060b2010-10-20 20:54:39 +00002572 debugserver_file_spec.SetFile (env_debugserver_path, false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002573 else
2574 debugserver_file_spec = g_debugserver_file_spec;
2575 bool debugserver_exists = debugserver_file_spec.Exists();
2576 if (!debugserver_exists)
2577 {
2578 // The debugserver binary is in the LLDB.framework/Resources
2579 // directory.
Greg Claytondd36def2010-10-17 22:03:32 +00002580 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002581 {
Greg Claytondd36def2010-10-17 22:03:32 +00002582 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583 debugserver_exists = debugserver_file_spec.Exists();
Greg Claytondd36def2010-10-17 22:03:32 +00002584 if (debugserver_exists)
2585 {
2586 g_debugserver_file_spec = debugserver_file_spec;
2587 }
2588 else
2589 {
2590 g_debugserver_file_spec.Clear();
2591 debugserver_file_spec.Clear();
2592 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593 }
2594 }
2595
2596 if (debugserver_exists)
2597 {
2598 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
2599
2600 m_stdio_communication.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601
Greg Clayton5160ce52013-03-27 23:08:40 +00002602 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002603
Han Ming Ong84647042012-02-25 01:07:38 +00002604 Args &debugserver_args = debugserver_launch_info.GetArguments();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002605 char arg_cstr[PATH_MAX];
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002606
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002607 // Start args with "debugserver /file/path -r --"
2608 debugserver_args.AppendArgument(debugserver_path);
2609 debugserver_args.AppendArgument(debugserver_url);
Greg Claytondd36def2010-10-17 22:03:32 +00002610 // use native registers, not the GDB registers
2611 debugserver_args.AppendArgument("--native-regs");
2612 // make debugserver run in its own session so signals generated by
2613 // special terminal key sequences (^C) don't affect debugserver
2614 debugserver_args.AppendArgument("--setsid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
2617 if (env_debugserver_log_file)
2618 {
2619 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
2620 debugserver_args.AppendArgument(arg_cstr);
2621 }
2622
2623 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
2624 if (env_debugserver_log_flags)
2625 {
2626 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
2627 debugserver_args.AppendArgument(arg_cstr);
2628 }
Jim Inghama0cc6b22012-10-03 22:31:30 +00002629// debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt");
2630// debugserver_args.AppendArgument("--log-flags=0x802e0e");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631
Greg Clayton8b82f082011-04-12 05:54:46 +00002632 // We currently send down all arguments, attach pids, or attach
2633 // process names in dedicated GDB server packets, so we don't need
2634 // to pass them as arguments. This is currently because of all the
2635 // things we need to setup prior to launching: the environment,
2636 // current working dir, file actions, etc.
2637#if 0
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002638 // Now append the program arguments
Greg Clayton71337622011-02-24 22:24:29 +00002639 if (inferior_argv)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002640 {
Greg Clayton71337622011-02-24 22:24:29 +00002641 // Terminate the debugserver args so we can now append the inferior args
2642 debugserver_args.AppendArgument("--");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643
Greg Clayton71337622011-02-24 22:24:29 +00002644 for (int i = 0; inferior_argv[i] != NULL; ++i)
2645 debugserver_args.AppendArgument (inferior_argv[i]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002646 }
2647 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
2648 {
2649 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid);
2650 debugserver_args.AppendArgument (arg_cstr);
2651 }
2652 else if (attach_name && attach_name[0])
2653 {
2654 if (wait_for_launch)
2655 debugserver_args.AppendArgument ("--waitfor");
2656 else
2657 debugserver_args.AppendArgument ("--attach");
2658 debugserver_args.AppendArgument (attach_name);
2659 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002660#endif
Greg Clayton8b82f082011-04-12 05:54:46 +00002661
2662 ProcessLaunchInfo::FileAction file_action;
2663
2664 // Close STDIN, STDOUT and STDERR. We might need to redirect them
2665 // to "/dev/null" if we run into any problems.
2666 file_action.Close (STDIN_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002667 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002668 file_action.Close (STDOUT_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002669 debugserver_launch_info.AppendFileAction (file_action);
Greg Clayton8b82f082011-04-12 05:54:46 +00002670 file_action.Close (STDERR_FILENO);
Han Ming Ong84647042012-02-25 01:07:38 +00002671 debugserver_launch_info.AppendFileAction (file_action);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672
2673 if (log)
2674 {
2675 StreamString strm;
2676 debugserver_args.Dump (&strm);
2677 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData());
2678 }
2679
Han Ming Ong84647042012-02-25 01:07:38 +00002680 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2681 debugserver_launch_info.SetUserID(process_info.GetUserID());
Greg Claytone4e45922011-11-16 05:37:56 +00002682
Han Ming Ong84647042012-02-25 01:07:38 +00002683 error = Host::LaunchProcess(debugserver_launch_info);
Greg Clayton0b42ac32010-07-02 01:29:13 +00002684
Greg Clayton8b82f082011-04-12 05:54:46 +00002685 if (error.Success ())
Han Ming Ong84647042012-02-25 01:07:38 +00002686 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Greg Clayton8b82f082011-04-12 05:54:46 +00002687 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2689
2690 if (error.Fail() || log)
Greg Clayton5160ce52013-03-27 23:08:40 +00002691 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002692 }
2693 else
2694 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002695 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696 }
2697
2698 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2699 StartAsyncThread ();
2700 }
2701 return error;
2702}
2703
2704bool
2705ProcessGDBRemote::MonitorDebugserverProcess
2706(
2707 void *callback_baton,
2708 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002709 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710 int signo, // Zero for no signal
2711 int exit_status // Exit value of process if signal is zero
2712)
2713{
Greg Claytone4e45922011-11-16 05:37:56 +00002714 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2715 // and might not exist anymore, so we need to carefully try to get the
2716 // target for this process first since we have a race condition when
2717 // we are done running between getting the notice that the inferior
2718 // process has died and the debugserver that was debugging this process.
2719 // In our test suite, we are also continually running process after
2720 // process, so we must be very careful to make sure:
2721 // 1 - process object hasn't been deleted already
2722 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002723
2724 // "debugserver_pid" argument passed in is the process ID for
2725 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002726 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002728 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002729
Greg Claytone4e45922011-11-16 05:37:56 +00002730 // Get a shared pointer to the target that has a matching process pointer.
2731 // This target could be gone, or the target could already have a new process
2732 // object inside of it
2733 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2734
Greg Clayton6779606a2011-01-22 23:43:18 +00002735 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002736 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
Greg Clayton6779606a2011-01-22 23:43:18 +00002737
Greg Claytone4e45922011-11-16 05:37:56 +00002738 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739 {
Greg Claytone4e45922011-11-16 05:37:56 +00002740 // We found a process in a target that matches, but another thread
2741 // might be in the process of launching a new process that will
2742 // soon replace it, so get a shared pointer to the process so we
2743 // can keep it alive.
2744 ProcessSP process_sp (target_sp->GetProcessSP());
2745 // Now we have a shared pointer to the process that can't go away on us
2746 // so we now make sure it was the same as the one passed in, and also make
2747 // sure that our previous "process *" didn't get deleted and have a new
2748 // "process *" created in its place with the same pointer. To verify this
2749 // we make sure the process has our debugserver process ID. If we pass all
2750 // of these tests, then we are sure that this process is the one we were
2751 // looking for.
2752 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 {
Greg Claytone4e45922011-11-16 05:37:56 +00002754 // Sleep for a half a second to make sure our inferior process has
2755 // time to set its exit status before we set it incorrectly when
2756 // both the debugserver and the inferior process shut down.
2757 usleep (500000);
2758 // If our process hasn't yet exited, debugserver might have died.
2759 // If the process did exit, the we are reaping it.
2760 const StateType state = process->GetState();
2761
2762 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2763 state != eStateInvalid &&
2764 state != eStateUnloaded &&
2765 state != eStateExited &&
2766 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767 {
Greg Claytone4e45922011-11-16 05:37:56 +00002768 char error_str[1024];
2769 if (signo)
2770 {
2771 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2772 if (signal_cstr)
2773 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2774 else
2775 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2776 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777 else
Greg Claytone4e45922011-11-16 05:37:56 +00002778 {
2779 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2780 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002781
Greg Claytone4e45922011-11-16 05:37:56 +00002782 process->SetExitStatus (-1, error_str);
2783 }
2784 // Debugserver has exited we need to let our ProcessGDBRemote
2785 // know that it no longer has a debugserver instance
2786 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002787 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788 }
2789 return true;
2790}
2791
2792void
2793ProcessGDBRemote::KillDebugserverProcess ()
2794{
Greg Claytonfbb76342013-11-20 21:07:01 +00002795 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002796 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2797 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002798 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002799 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2800 }
2801}
2802
2803void
2804ProcessGDBRemote::Initialize()
2805{
2806 static bool g_initialized = false;
2807
2808 if (g_initialized == false)
2809 {
2810 g_initialized = true;
2811 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2812 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002813 CreateInstance,
2814 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815
2816 Log::Callbacks log_callbacks = {
2817 ProcessGDBRemoteLog::DisableLog,
2818 ProcessGDBRemoteLog::EnableLog,
2819 ProcessGDBRemoteLog::ListLogCategories
2820 };
2821
2822 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2823 }
2824}
2825
Greg Clayton7f982402013-07-15 22:54:20 +00002826void
2827ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2828{
2829 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2830 {
2831 const bool is_global_setting = true;
2832 PluginManager::CreateSettingForProcessPlugin (debugger,
2833 GetGlobalPluginProperties()->GetValueProperties(),
2834 ConstString ("Properties for the gdb-remote process plug-in."),
2835 is_global_setting);
2836 }
2837}
2838
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002840ProcessGDBRemote::StartAsyncThread ()
2841{
Greg Clayton5160ce52013-03-27 23:08:40 +00002842 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843
2844 if (log)
2845 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002846
2847 Mutex::Locker start_locker(m_async_thread_state_mutex);
2848 if (m_async_thread_state == eAsyncThreadNotStarted)
2849 {
2850 // Create a thread that watches our internal state and controls which
2851 // events make it to clients (into the DCProcess event queue).
2852 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2853 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2854 {
2855 m_async_thread_state = eAsyncThreadRunning;
2856 return true;
2857 }
2858 else
2859 return false;
2860 }
2861 else
2862 {
2863 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2864 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2865 if (log)
2866 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2867 if (m_async_thread_state == eAsyncThreadRunning)
2868 return true;
2869 else
2870 return false;
2871 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002872}
2873
2874void
2875ProcessGDBRemote::StopAsyncThread ()
2876{
Greg Clayton5160ce52013-03-27 23:08:40 +00002877 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878
2879 if (log)
2880 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2881
Jim Ingham455fa5c2012-11-01 01:15:33 +00002882 Mutex::Locker start_locker(m_async_thread_state_mutex);
2883 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002885 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2886
2887 // This will shut down the async thread.
2888 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2889
2890 // Stop the stdio thread
2891 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2892 {
2893 Host::ThreadJoin (m_async_thread, NULL, NULL);
2894 }
2895 m_async_thread_state = eAsyncThreadDone;
2896 }
2897 else
2898 {
2899 if (log)
2900 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901 }
2902}
2903
2904
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002905thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002906ProcessGDBRemote::AsyncThread (void *arg)
2907{
2908 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2909
Greg Clayton5160ce52013-03-27 23:08:40 +00002910 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002912 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913
2914 Listener listener ("ProcessGDBRemote::AsyncThread");
2915 EventSP event_sp;
2916 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2917 eBroadcastBitAsyncThreadShouldExit;
2918
2919 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2920 {
Greg Clayton71337622011-02-24 22:24:29 +00002921 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2922
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002923 bool done = false;
2924 while (!done)
2925 {
2926 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002927 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002928 if (listener.WaitForEvent (NULL, event_sp))
2929 {
2930 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002931 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932 {
Greg Clayton71337622011-02-24 22:24:29 +00002933 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002934 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935
Greg Clayton71337622011-02-24 22:24:29 +00002936 switch (event_type)
2937 {
2938 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939 {
Greg Clayton71337622011-02-24 22:24:29 +00002940 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941
Greg Clayton71337622011-02-24 22:24:29 +00002942 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 {
Greg Clayton71337622011-02-24 22:24:29 +00002944 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2945 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2946 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002947 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948
Greg Clayton71337622011-02-24 22:24:29 +00002949 if (::strstr (continue_cstr, "vAttach") == NULL)
2950 process->SetPrivateState(eStateRunning);
2951 StringExtractorGDBRemote response;
2952 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002953
Greg Clayton0772ded2012-05-16 02:48:06 +00002954 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2955 // The thread ID list might be contained within the "response", or the stop reply packet that
2956 // caused the stop. So clear it now before we give the stop reply packet to the process
2957 // using the process->SetLastStopPacket()...
2958 process->ClearThreadIDList ();
2959
Greg Clayton71337622011-02-24 22:24:29 +00002960 switch (stop_state)
2961 {
2962 case eStateStopped:
2963 case eStateCrashed:
2964 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002965 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002966 process->SetPrivateState (stop_state);
2967 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968
Greg Clayton71337622011-02-24 22:24:29 +00002969 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002970 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002971 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002972 response.SetFilePos(1);
2973 process->SetExitStatus(response.GetHexU8(), NULL);
2974 done = true;
2975 break;
2976
2977 case eStateInvalid:
2978 process->SetExitStatus(-1, "lost connection");
2979 break;
2980
2981 default:
2982 process->SetPrivateState (stop_state);
2983 break;
2984 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002985 }
2986 }
Greg Clayton71337622011-02-24 22:24:29 +00002987 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002988
Greg Clayton71337622011-02-24 22:24:29 +00002989 case eBroadcastBitAsyncThreadShouldExit:
2990 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002991 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002992 done = true;
2993 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994
Greg Clayton71337622011-02-24 22:24:29 +00002995 default:
2996 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002997 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
Greg Clayton71337622011-02-24 22:24:29 +00002998 done = true;
2999 break;
3000 }
3001 }
3002 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3003 {
3004 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
3005 {
3006 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003007 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00003008 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003009 }
3010 }
3011 else
3012 {
3013 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003014 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 done = true;
3016 }
3017 }
3018 }
3019
3020 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003021 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022
3023 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
3024 return NULL;
3025}
3026
Greg Claytone996fd32011-03-08 22:40:15 +00003027//uint32_t
3028//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3029//{
3030// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3031// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3032// if (m_local_debugserver)
3033// {
3034// return Host::ListProcessesMatchingName (name, matches, pids);
3035// }
3036// else
3037// {
3038// // FIXME: Implement talking to the remote debugserver.
3039// return 0;
3040// }
3041//
3042//}
3043//
Jim Ingham1c823b42011-01-22 01:33:44 +00003044bool
3045ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3046 lldb_private::StoppointCallbackContext *context,
3047 lldb::user_id_t break_id,
3048 lldb::user_id_t break_loc_id)
3049{
3050 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3051 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00003052 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00003053 if (log)
3054 log->Printf("Hit New Thread Notification breakpoint.");
3055 return false;
3056}
3057
3058
3059bool
3060ProcessGDBRemote::StartNoticingNewThreads()
3061{
Greg Clayton5160ce52013-03-27 23:08:40 +00003062 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00003063 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003064 {
Greg Clayton4116e932012-05-15 02:33:01 +00003065 if (log && log->GetVerbose())
3066 log->Printf("Enabled noticing new thread breakpoint.");
3067 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003068 }
Greg Clayton4116e932012-05-15 02:33:01 +00003069 else
Jim Ingham1c823b42011-01-22 01:33:44 +00003070 {
Greg Clayton4116e932012-05-15 02:33:01 +00003071 PlatformSP platform_sp (m_target.GetPlatform());
3072 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003073 {
Greg Clayton4116e932012-05-15 02:33:01 +00003074 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3075 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00003076 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00003077 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00003078 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3079 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00003080 }
3081 else
3082 {
3083 if (log)
3084 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00003085 }
3086 }
3087 }
Greg Clayton4116e932012-05-15 02:33:01 +00003088 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00003089}
3090
3091bool
3092ProcessGDBRemote::StopNoticingNewThreads()
3093{
Greg Clayton5160ce52013-03-27 23:08:40 +00003094 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00003095 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00003096 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00003097
3098 if (m_thread_create_bp_sp)
3099 m_thread_create_bp_sp->SetEnabled(false);
3100
Jim Ingham1c823b42011-01-22 01:33:44 +00003101 return true;
3102}
3103
Jason Molenda5e8534e2012-10-03 01:29:34 +00003104lldb_private::DynamicLoader *
3105ProcessGDBRemote::GetDynamicLoader ()
3106{
3107 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00003108 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00003109 return m_dyld_ap.get();
3110}
Jim Ingham1c823b42011-01-22 01:33:44 +00003111
Greg Clayton998255b2012-10-13 02:07:45 +00003112
Greg Clayton02686b82012-10-15 22:42:16 +00003113class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00003114{
3115private:
3116
3117public:
Greg Clayton02686b82012-10-15 22:42:16 +00003118 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00003119 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00003120 "process plugin packet history",
3121 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00003122 NULL)
3123 {
3124 }
3125
Greg Clayton02686b82012-10-15 22:42:16 +00003126 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00003127 {
3128 }
3129
3130 bool
3131 DoExecute (Args& command, CommandReturnObject &result)
3132 {
Greg Clayton02686b82012-10-15 22:42:16 +00003133 const size_t argc = command.GetArgumentCount();
3134 if (argc == 0)
3135 {
3136 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3137 if (process)
3138 {
3139 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
3140 result.SetStatus (eReturnStatusSuccessFinishResult);
3141 return true;
3142 }
3143 }
3144 else
3145 {
3146 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3147 }
3148 result.SetStatus (eReturnStatusFailed);
3149 return false;
3150 }
3151};
3152
3153class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3154{
3155private:
3156
3157public:
3158 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3159 CommandObjectParsed (interpreter,
3160 "process plugin packet send",
3161 "Send a custom packet through the GDB remote protocol and print the answer. "
3162 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3163 NULL)
3164 {
3165 }
3166
3167 ~CommandObjectProcessGDBRemotePacketSend ()
3168 {
3169 }
3170
3171 bool
3172 DoExecute (Args& command, CommandReturnObject &result)
3173 {
3174 const size_t argc = command.GetArgumentCount();
3175 if (argc == 0)
3176 {
3177 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3178 result.SetStatus (eReturnStatusFailed);
3179 return false;
3180 }
3181
3182 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3183 if (process)
3184 {
Han Ming Ong84145852012-11-26 20:42:03 +00003185 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003186 {
Han Ming Ong84145852012-11-26 20:42:03 +00003187 const char *packet_cstr = command.GetArgumentAtIndex(0);
3188 bool send_async = true;
3189 StringExtractorGDBRemote response;
3190 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3191 result.SetStatus (eReturnStatusSuccessFinishResult);
3192 Stream &output_strm = result.GetOutputStream();
3193 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003194 std::string &response_str = response.GetStringRef();
3195
Han Ming Ong399289e2013-06-21 19:56:59 +00003196 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003197 {
3198 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3199 }
3200
Han Ming Ong84145852012-11-26 20:42:03 +00003201 if (response_str.empty())
3202 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3203 else
3204 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003205 }
Greg Clayton02686b82012-10-15 22:42:16 +00003206 }
Greg Clayton998255b2012-10-13 02:07:45 +00003207 return true;
3208 }
3209};
3210
Greg Claytonba4a0a52013-02-01 23:03:47 +00003211class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3212{
3213private:
3214
3215public:
3216 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3217 CommandObjectRaw (interpreter,
3218 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003219 "Send a qRcmd packet through the GDB remote protocol and print the response."
3220 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
Greg Claytonba4a0a52013-02-01 23:03:47 +00003221 NULL)
3222 {
3223 }
3224
3225 ~CommandObjectProcessGDBRemotePacketMonitor ()
3226 {
3227 }
3228
3229 bool
3230 DoExecute (const char *command, CommandReturnObject &result)
3231 {
3232 if (command == NULL || command[0] == '\0')
3233 {
3234 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3235 result.SetStatus (eReturnStatusFailed);
3236 return false;
3237 }
3238
3239 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3240 if (process)
3241 {
3242 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003243 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003244 packet.PutBytesAsRawHex8(command, strlen(command));
3245 const char *packet_cstr = packet.GetString().c_str();
3246
3247 bool send_async = true;
3248 StringExtractorGDBRemote response;
3249 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3250 result.SetStatus (eReturnStatusSuccessFinishResult);
3251 Stream &output_strm = result.GetOutputStream();
3252 output_strm.Printf (" packet: %s\n", packet_cstr);
3253 const std::string &response_str = response.GetStringRef();
3254
3255 if (response_str.empty())
3256 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3257 else
3258 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3259 }
3260 return true;
3261 }
3262};
3263
Greg Clayton02686b82012-10-15 22:42:16 +00003264class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3265{
3266private:
3267
3268public:
3269 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3270 CommandObjectMultiword (interpreter,
3271 "process plugin packet",
3272 "Commands that deal with GDB remote packets.",
3273 NULL)
3274 {
3275 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3276 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003277 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003278 }
3279
3280 ~CommandObjectProcessGDBRemotePacket ()
3281 {
3282 }
3283};
Greg Clayton998255b2012-10-13 02:07:45 +00003284
3285class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3286{
3287public:
3288 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3289 CommandObjectMultiword (interpreter,
3290 "process plugin",
3291 "A set of commands for operating on a ProcessGDBRemote process.",
3292 "process plugin <subcommand> [<subcommand-options>]")
3293 {
3294 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3295 }
3296
3297 ~CommandObjectMultiwordProcessGDBRemote ()
3298 {
3299 }
3300};
3301
Greg Clayton998255b2012-10-13 02:07:45 +00003302CommandObject *
3303ProcessGDBRemote::GetPluginCommandObject()
3304{
3305 if (!m_command_sp)
3306 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3307 return m_command_sp.get();
3308}