blob: 45278972ec1c9392e9a012a5b5fe0f53121354e8 [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
Greg Clayton57abc5d2013-05-10 21:47:16 +0000170lldb_private::ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000171ProcessGDBRemote::GetPluginNameStatic()
172{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000173 static ConstString g_name("gdb-remote");
174 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000175}
176
177const char *
178ProcessGDBRemote::GetPluginDescriptionStatic()
179{
180 return "GDB Remote protocol based debugging plug-in.";
181}
182
183void
184ProcessGDBRemote::Terminate()
185{
186 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
187}
188
189
Greg Claytonc3776bf2012-02-09 06:16:32 +0000190lldb::ProcessSP
191ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000192{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000193 lldb::ProcessSP process_sp;
194 if (crash_file_path == NULL)
195 process_sp.reset (new ProcessGDBRemote (target, listener));
196 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000197}
198
199bool
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000200ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201{
Greg Clayton596ed242011-10-21 21:41:45 +0000202 if (plugin_specified_by_name)
203 return true;
204
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000205 // For now we are just making sure the file exists for a given module
Greg Claytonaa149cb2011-08-11 02:48:45 +0000206 Module *exe_module = target.GetExecutableModulePointer();
207 if (exe_module)
Greg Claytonc3776bf2012-02-09 06:16:32 +0000208 {
209 ObjectFile *exe_objfile = exe_module->GetObjectFile();
210 // We can't debug core files...
211 switch (exe_objfile->GetType())
212 {
213 case ObjectFile::eTypeInvalid:
214 case ObjectFile::eTypeCoreFile:
215 case ObjectFile::eTypeDebugInfo:
216 case ObjectFile::eTypeObjectFile:
217 case ObjectFile::eTypeSharedLibrary:
218 case ObjectFile::eTypeStubLibrary:
219 return false;
220 case ObjectFile::eTypeExecutable:
221 case ObjectFile::eTypeDynamicLinker:
222 case ObjectFile::eTypeUnknown:
223 break;
224 }
Greg Claytonaa149cb2011-08-11 02:48:45 +0000225 return exe_module->GetFileSpec().Exists();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000226 }
Jim Ingham5aee1622010-08-09 23:31:02 +0000227 // However, if there is no executable module, we return true since we might be preparing to attach.
228 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229}
230
231//----------------------------------------------------------------------
232// ProcessGDBRemote constructor
233//----------------------------------------------------------------------
234ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
235 Process (target, listener),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000236 m_flags (0),
Greg Clayton8b82f082011-04-12 05:54:46 +0000237 m_gdb_comm(false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000238 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
Greg Claytonc982c762010-07-09 20:39:50 +0000239 m_last_stop_packet (),
Greg Clayton09c3e3d2011-12-06 04:51:14 +0000240 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000241 m_register_info (),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000242 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000243 m_async_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham455fa5c2012-11-01 01:15:33 +0000244 m_async_thread_state(eAsyncThreadNotStarted),
245 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
Greg Clayton9e920902012-04-10 02:25:43 +0000246 m_thread_ids (),
Greg Clayton71fc2a32011-02-12 06:28:37 +0000247 m_continue_c_tids (),
248 m_continue_C_tids (),
249 m_continue_s_tids (),
250 m_continue_S_tids (),
Greg Claytonc982c762010-07-09 20:39:50 +0000251 m_max_memory_size (512),
Greg Clayton4116e932012-05-15 02:33:01 +0000252 m_addr_to_mmap_size (),
253 m_thread_create_bp_sp (),
Jim Ingham43c555d2012-07-04 00:35:43 +0000254 m_waiting_for_attach (false),
Jason Molenda5e8534e2012-10-03 01:29:34 +0000255 m_destroy_tried_resuming (false),
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000256 m_command_sp (),
257 m_breakpoint_pc_offset (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000258{
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000259 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
260 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
Jim Inghamb1e2e842012-04-12 18:49:31 +0000261 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
Greg Clayton7f982402013-07-15 22:54:20 +0000262 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
263 if (timeout_seconds > 0)
264 m_gdb_comm.SetPacketTimeout(timeout_seconds);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000265}
266
267//----------------------------------------------------------------------
268// Destructor
269//----------------------------------------------------------------------
270ProcessGDBRemote::~ProcessGDBRemote()
271{
272 // m_mach_process.UnregisterNotificationCallbacks (this);
273 Clear();
Greg Clayton1ed54f52011-10-01 00:45:15 +0000274 // We need to call finalize on the process before destroying ourselves
275 // to make sure all of the broadcaster cleanup goes as planned. If we
276 // destruct this class, then Process::~Process() might have problems
277 // trying to fully destroy the broadcaster.
278 Finalize();
Jim Ingham455fa5c2012-11-01 01:15:33 +0000279
280 // The general Finalize is going to try to destroy the process and that SHOULD
281 // shut down the async thread. However, if we don't kill it it will get stranded and
282 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
283 StopAsyncThread();
284 KillDebugserverProcess();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000285}
286
287//----------------------------------------------------------------------
288// PluginInterface
289//----------------------------------------------------------------------
Greg Clayton57abc5d2013-05-10 21:47:16 +0000290ConstString
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000291ProcessGDBRemote::GetPluginName()
292{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000293 return GetPluginNameStatic();
294}
295
296uint32_t
297ProcessGDBRemote::GetPluginVersion()
298{
299 return 1;
300}
301
Greg Claytonef8180a2013-10-15 00:14:28 +0000302bool
303ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
304{
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000305#ifndef LLDB_DISABLE_PYTHON
Greg Claytonef8180a2013-10-15 00:14:28 +0000306 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
307 Error error;
308 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error));
309 if (module_object_sp)
310 {
311 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp,
312 &GetTarget(),
313 "gdb-server-target-definition",
314 error));
315
316 PythonDictionary target_dict(target_definition_sp);
317
318 if (target_dict)
319 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000320 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info"));
321 if (host_info_dict)
322 {
323 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple")));
324
325 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
326 {
327 GetTarget().SetArchitecture(host_arch);
328 }
329
330 }
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +0000331 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0);
332
Greg Clayton312bcbe2013-10-17 01:10:23 +0000333 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0)
Greg Claytonef8180a2013-10-15 00:14:28 +0000334 {
335 return true;
336 }
337 }
338 }
Joerg Sonnenbergere77b0422013-10-20 17:36:05 +0000339#endif
Greg Claytonef8180a2013-10-15 00:14:28 +0000340 return false;
341}
342
343
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000344void
Greg Clayton513c26c2011-01-29 07:10:55 +0000345ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000346{
Greg Clayton513c26c2011-01-29 07:10:55 +0000347 if (!force && m_register_info.GetNumRegisters() > 0)
348 return;
349
350 char packet[128];
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000351 m_register_info.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352 uint32_t reg_offset = 0;
353 uint32_t reg_num = 0;
Greg Clayton23f59502012-07-17 03:23:13 +0000354 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
Greg Clayton576d8832011-03-22 04:00:09 +0000355 response_type == StringExtractorGDBRemote::eResponse;
356 ++reg_num)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000357 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000358 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
Andy Gibbsa297a972013-06-19 19:04:53 +0000359 assert (packet_len < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +0000361 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000362 {
Greg Clayton576d8832011-03-22 04:00:09 +0000363 response_type = response.GetResponseType();
364 if (response_type == StringExtractorGDBRemote::eResponse)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000365 {
366 std::string name;
367 std::string value;
368 ConstString reg_name;
369 ConstString alt_name;
370 ConstString set_name;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000371 std::vector<uint32_t> value_regs;
372 std::vector<uint32_t> invalidate_regs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000373 RegisterInfo reg_info = { NULL, // Name
374 NULL, // Alt name
375 0, // byte size
376 reg_offset, // offset
377 eEncodingUint, // encoding
378 eFormatHex, // formate
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000379 {
380 LLDB_INVALID_REGNUM, // GCC reg num
381 LLDB_INVALID_REGNUM, // DWARF reg num
382 LLDB_INVALID_REGNUM, // generic reg num
Jason Molendafbcb7f22010-09-10 07:49:16 +0000383 reg_num, // GDB reg num
384 reg_num // native register number
Greg Clayton435d85a2012-02-29 19:27:27 +0000385 },
386 NULL,
387 NULL
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388 };
389
390 while (response.GetNameColonValue(name, value))
391 {
392 if (name.compare("name") == 0)
393 {
394 reg_name.SetCString(value.c_str());
395 }
396 else if (name.compare("alt-name") == 0)
397 {
398 alt_name.SetCString(value.c_str());
399 }
400 else if (name.compare("bitsize") == 0)
401 {
402 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
403 }
404 else if (name.compare("offset") == 0)
405 {
406 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0);
Jason Molenda743e86a2010-06-11 23:44:18 +0000407 if (reg_offset != offset)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408 {
409 reg_offset = offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410 }
411 }
412 else if (name.compare("encoding") == 0)
413 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000414 const Encoding encoding = Args::StringToEncoding (value.c_str());
415 if (encoding != eEncodingInvalid)
416 reg_info.encoding = encoding;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000417 }
418 else if (name.compare("format") == 0)
419 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000420 Format format = eFormatInvalid;
421 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
422 reg_info.format = format;
423 else if (value.compare("binary") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000424 reg_info.format = eFormatBinary;
425 else if (value.compare("decimal") == 0)
426 reg_info.format = eFormatDecimal;
427 else if (value.compare("hex") == 0)
428 reg_info.format = eFormatHex;
429 else if (value.compare("float") == 0)
430 reg_info.format = eFormatFloat;
431 else if (value.compare("vector-sint8") == 0)
432 reg_info.format = eFormatVectorOfSInt8;
433 else if (value.compare("vector-uint8") == 0)
434 reg_info.format = eFormatVectorOfUInt8;
435 else if (value.compare("vector-sint16") == 0)
436 reg_info.format = eFormatVectorOfSInt16;
437 else if (value.compare("vector-uint16") == 0)
438 reg_info.format = eFormatVectorOfUInt16;
439 else if (value.compare("vector-sint32") == 0)
440 reg_info.format = eFormatVectorOfSInt32;
441 else if (value.compare("vector-uint32") == 0)
442 reg_info.format = eFormatVectorOfUInt32;
443 else if (value.compare("vector-float32") == 0)
444 reg_info.format = eFormatVectorOfFloat32;
445 else if (value.compare("vector-uint128") == 0)
446 reg_info.format = eFormatVectorOfUInt128;
447 }
448 else if (name.compare("set") == 0)
449 {
450 set_name.SetCString(value.c_str());
451 }
452 else if (name.compare("gcc") == 0)
453 {
454 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
455 }
456 else if (name.compare("dwarf") == 0)
457 {
458 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
459 }
460 else if (name.compare("generic") == 0)
461 {
Greg Clayton2443cbd2012-08-24 01:42:50 +0000462 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000463 }
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000464 else if (name.compare("container-regs") == 0)
465 {
466 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
467 value_pair.second = value;
468 do
469 {
470 value_pair = value_pair.second.split(',');
471 if (!value_pair.first.empty())
472 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000473 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
474 if (reg != LLDB_INVALID_REGNUM)
475 value_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000476 }
477 } while (!value_pair.second.empty());
478 }
479 else if (name.compare("invalidate-regs") == 0)
480 {
481 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
482 value_pair.second = value;
483 do
484 {
485 value_pair = value_pair.second.split(',');
486 if (!value_pair.first.empty())
487 {
Greg Clayton0ba20242013-01-21 23:32:42 +0000488 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16);
489 if (reg != LLDB_INVALID_REGNUM)
490 invalidate_regs.push_back (reg);
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000491 }
492 } while (!value_pair.second.empty());
493 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000494 }
495
Jason Molenda743e86a2010-06-11 23:44:18 +0000496 reg_info.byte_offset = reg_offset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000497 assert (reg_info.byte_size != 0);
498 reg_offset += reg_info.byte_size;
Greg Claytonce1ffcf2013-01-21 22:17:50 +0000499 if (!value_regs.empty())
500 {
501 value_regs.push_back(LLDB_INVALID_REGNUM);
502 reg_info.value_regs = value_regs.data();
503 }
504 if (!invalidate_regs.empty())
505 {
506 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
507 reg_info.invalidate_regs = invalidate_regs.data();
508 }
509
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000510 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
511 }
512 }
513 else
514 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000515 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000516 }
517 }
518
Greg Clayton9ac6d2d2013-10-25 18:13:17 +0000519 // Check if qHostInfo specified a specific packet timeout for this connection.
520 // If so then lets update our setting so the user knows what the timeout is
521 // and can see it.
522 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
523 if (host_packet_timeout)
524 {
525 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
526 }
527
528
Greg Claytonef8180a2013-10-15 00:14:28 +0000529 if (reg_num == 0)
530 {
531 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
Greg Clayton312bcbe2013-10-17 01:10:23 +0000532
533 if (target_definition_fspec)
Greg Claytonef8180a2013-10-15 00:14:28 +0000534 {
Greg Clayton312bcbe2013-10-17 01:10:23 +0000535 // See if we can get register definitions from a python file
536 if (ParsePythonTargetDefinition (target_definition_fspec))
537 return;
Greg Claytonef8180a2013-10-15 00:14:28 +0000538 }
539 }
540
Johnny Chen2fa9de12012-05-14 18:44:23 +0000541 // We didn't get anything if the accumulated reg_num is zero. See if we are
542 // debugging ARM and fill with a hard coded register set until we can get an
543 // updated debugserver down on the devices.
544 // On the other hand, if the accumulated reg_num is positive, see if we can
545 // add composite registers to the existing primordial ones.
546 bool from_scratch = (reg_num == 0);
547
548 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000549 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
550 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
551
552 // Use the process' architecture instead of the host arch, if available
553 ArchSpec remote_arch;
554 if (remote_process_arch.IsValid ())
555 remote_arch = remote_process_arch;
556 else
557 remote_arch = remote_host_arch;
558
Johnny Chen2fa9de12012-05-14 18:44:23 +0000559 if (!target_arch.IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560 {
Johnny Chen2fa9de12012-05-14 18:44:23 +0000561 if (remote_arch.IsValid()
562 && remote_arch.GetMachine() == llvm::Triple::arm
563 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
564 m_register_info.HardcodeARMRegisters(from_scratch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000565 }
Johnny Chen2fa9de12012-05-14 18:44:23 +0000566 else if (target_arch.GetMachine() == llvm::Triple::arm)
567 {
568 m_register_info.HardcodeARMRegisters(from_scratch);
569 }
570
571 // At this point, we can finalize our register info.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000572 m_register_info.Finalize ();
573}
574
575Error
576ProcessGDBRemote::WillLaunch (Module* module)
577{
578 return WillLaunchOrAttach ();
579}
580
581Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000582ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000583{
584 return WillLaunchOrAttach ();
585}
586
587Error
Greg Clayton3af9ea52010-11-18 05:57:03 +0000588ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000589{
590 return WillLaunchOrAttach ();
591}
592
593Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +0000594ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +0000595{
596 Error error (WillLaunchOrAttach ());
597
598 if (error.Fail())
599 return error;
600
Greg Clayton2289fa42011-04-30 01:09:13 +0000601 error = ConnectToDebugserver (remote_url);
Greg Claytonb766a732011-02-04 01:58:07 +0000602
603 if (error.Fail())
604 return error;
605 StartAsyncThread ();
606
Greg Claytonc574ede2011-03-10 02:26:48 +0000607 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytonb766a732011-02-04 01:58:07 +0000608 if (pid == LLDB_INVALID_PROCESS_ID)
609 {
610 // We don't have a valid process ID, so note that we are connected
611 // and could now request to launch or attach, or get remote process
612 // listings...
613 SetPrivateState (eStateConnected);
614 }
615 else
616 {
617 // We have a valid process
618 SetID (pid);
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000619 GetThreadList();
Greg Claytondd0e5a52011-06-02 22:22:38 +0000620 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Claytonb766a732011-02-04 01:58:07 +0000621 {
Carlo Kok74389122013-10-14 07:09:13 +0000622 if (!m_target.GetArchitecture().IsValid()) { // Make sure we have an architecture
623 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
624 }
625
626
Greg Claytondd0e5a52011-06-02 22:22:38 +0000627 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000628 if (state == eStateStopped)
629 {
630 SetPrivateState (state);
631 }
632 else
Daniel Malead01b2952012-11-29 21:49:15 +0000633 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 +0000634 }
635 else
Daniel Malead01b2952012-11-29 21:49:15 +0000636 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 +0000637 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000638
639 if (error.Success()
640 && !GetTarget().GetArchitecture().IsValid()
641 && m_gdb_comm.GetHostArchitecture().IsValid())
642 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000643 // Prefer the *process'* architecture over that of the *host*, if available.
644 if (m_gdb_comm.GetProcessArchitecture().IsValid())
645 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
646 else
647 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000648 }
649
Greg Claytonb766a732011-02-04 01:58:07 +0000650 return error;
651}
652
653Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654ProcessGDBRemote::WillLaunchOrAttach ()
655{
656 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658 return error;
659}
660
661//----------------------------------------------------------------------
662// Process Control
663//----------------------------------------------------------------------
664Error
Greg Clayton982c9762011-11-03 21:22:33 +0000665ProcessGDBRemote::DoLaunch (Module *exe_module, const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666{
Greg Clayton4957bf62010-09-30 21:49:03 +0000667 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000668
669 uint32_t launch_flags = launch_info.GetFlags().Get();
670 const char *stdin_path = NULL;
671 const char *stdout_path = NULL;
672 const char *stderr_path = NULL;
673 const char *working_dir = launch_info.GetWorkingDirectory();
674
675 const ProcessLaunchInfo::FileAction *file_action;
676 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
677 if (file_action)
678 {
679 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
680 stdin_path = file_action->GetPath();
681 }
682 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
683 if (file_action)
684 {
685 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
686 stdout_path = file_action->GetPath();
687 }
688 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
689 if (file_action)
690 {
691 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
692 stderr_path = file_action->GetPath();
693 }
694
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000695 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
696 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
697 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000698 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699
Greg Clayton982c9762011-11-03 21:22:33 +0000700 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 if (object_file)
702 {
Greg Clayton71337622011-02-24 22:24:29 +0000703 // Make sure we aren't already connected?
704 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000706 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000707 }
708
709 if (error.Success())
710 {
711 lldb_utility::PseudoTerminal pty;
712 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000713
714 // If the debugserver is local and we aren't disabling STDIO, lets use
715 // a pseudo terminal to instead of relying on the 'O' packets for stdio
716 // since 'O' packets can really slow down debugging if the inferior
717 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000718 PlatformSP platform_sp (m_target.GetPlatform());
719 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000720 {
721 const char *slave_name = NULL;
722 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 {
Greg Clayton71337622011-02-24 22:24:29 +0000724 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
725 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726 }
Greg Clayton71337622011-02-24 22:24:29 +0000727 if (stdin_path == NULL)
728 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729
Greg Clayton71337622011-02-24 22:24:29 +0000730 if (stdout_path == NULL)
731 stdout_path = slave_name;
732
733 if (stderr_path == NULL)
734 stderr_path = slave_name;
735 }
736
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000737 // Set STDIN to /dev/null if we want STDIO disabled or if either
738 // STDOUT or STDERR have been set to something and STDIN hasn't
739 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000740 stdin_path = "/dev/null";
741
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000742 // Set STDOUT to /dev/null if we want STDIO disabled or if either
743 // STDIN or STDERR have been set to something and STDOUT hasn't
744 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000745 stdout_path = "/dev/null";
746
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000747 // Set STDERR to /dev/null if we want STDIO disabled or if either
748 // STDIN or STDOUT have been set to something and STDERR hasn't
749 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000750 stderr_path = "/dev/null";
751
752 if (stdin_path)
753 m_gdb_comm.SetSTDIN (stdin_path);
754 if (stdout_path)
755 m_gdb_comm.SetSTDOUT (stdout_path);
756 if (stderr_path)
757 m_gdb_comm.SetSTDERR (stderr_path);
758
759 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
760
Greg Claytonc4103b32011-05-08 04:53:50 +0000761 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000762
763 if (working_dir && working_dir[0])
764 {
765 m_gdb_comm.SetWorkingDir (working_dir);
766 }
767
768 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000769 const Args &environment = launch_info.GetEnvironmentEntries();
770 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000771 {
Greg Clayton982c9762011-11-03 21:22:33 +0000772 size_t num_environment_entries = environment.GetArgumentCount();
773 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000774 {
Greg Clayton982c9762011-11-03 21:22:33 +0000775 const char *env_entry = environment.GetArgumentAtIndex(i);
776 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000777 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000778 }
Greg Clayton71337622011-02-24 22:24:29 +0000779 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000780
Greg Claytonc574ede2011-03-10 02:26:48 +0000781 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000782 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000783 if (arg_packet_err == 0)
784 {
785 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000786 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000788 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 }
790 else
791 {
Greg Clayton71337622011-02-24 22:24:29 +0000792 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793 }
Greg Clayton71337622011-02-24 22:24:29 +0000794 }
795 else
796 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000797 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000798 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000799
800 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801
Greg Clayton71337622011-02-24 22:24:29 +0000802 if (GetID() == LLDB_INVALID_PROCESS_ID)
803 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000804 if (log)
805 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000806 KillDebugserverProcess ();
807 return error;
808 }
809
Greg Claytondd0e5a52011-06-02 22:22:38 +0000810 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false))
Greg Clayton71337622011-02-24 22:24:29 +0000811 {
Carlo Kok74389122013-10-14 07:09:13 +0000812 if (!m_target.GetArchitecture().IsValid()) { // Make sure we have an architecture
813 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
814 }
815
Greg Claytondd0e5a52011-06-02 22:22:38 +0000816 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000817
818 if (!disable_stdio)
819 {
820 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000821 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000822 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 }
824 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000825 else
826 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000827 if (log)
828 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000829 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830 }
831 else
832 {
833 // Set our user ID to an invalid process ID.
834 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000835 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
836 exe_module->GetFileSpec().GetFilename().AsCString(),
837 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000840
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841}
842
843
844Error
Greg Claytonb766a732011-02-04 01:58:07 +0000845ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846{
847 Error error;
848 // Sleep and wait a bit for debugserver to start to listen...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000849 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850 if (conn_ap.get())
851 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852 const uint32_t max_retry_count = 50;
853 uint32_t retry_count = 0;
854 while (!m_gdb_comm.IsConnected())
855 {
Greg Claytonb766a732011-02-04 01:58:07 +0000856 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000857 {
858 m_gdb_comm.SetConnection (conn_ap.release());
859 break;
860 }
Jim Ingham4e5c8212013-06-07 22:09:53 +0000861 else if (error.WasInterrupted())
862 {
863 // If we were interrupted, don't keep retrying.
864 break;
865 }
866
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000867 retry_count++;
Jim Ingham4e5c8212013-06-07 22:09:53 +0000868
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 if (retry_count >= max_retry_count)
870 break;
871
872 usleep (100000);
873 }
874 }
875
876 if (!m_gdb_comm.IsConnected())
877 {
878 if (error.Success())
879 error.SetErrorString("not connected to remote gdb server");
880 return error;
881 }
882
Greg Clayton32e0a752011-03-30 18:16:51 +0000883 // We always seem to be able to open a connection to a local port
884 // so we need to make sure we can then send data to it. If we can't
885 // then we aren't actually connected to anything, so try and do the
886 // handshake with the remote GDB server and make sure that goes
887 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +0000888 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000890 m_gdb_comm.Disconnect();
891 if (error.Success())
892 error.SetErrorString("not connected to remote gdb server");
893 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000895 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000896 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000897 m_gdb_comm.GetHostInfo ();
898 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000899 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000900
901 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
902 for (size_t idx = 0; idx < num_cmds; idx++)
903 {
904 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000905 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
906 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907 return error;
908}
909
910void
911ProcessGDBRemote::DidLaunchOrAttach ()
912{
Greg Clayton5160ce52013-03-27 23:08:40 +0000913 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000914 if (log)
915 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000916 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000917 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000918 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000919
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000920 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000921
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000922 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
923
924 // See if the GDB server supports the qProcessInfo packet, if so
925 // prefer that over the Host information as it will be more specific
926 // to our process.
927
928 if (m_gdb_comm.GetProcessArchitecture().IsValid())
929 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
930
Greg Claytond314e812011-03-23 00:09:55 +0000931 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000932 {
Greg Claytond314e812011-03-23 00:09:55 +0000933 ArchSpec &target_arch = GetTarget().GetArchitecture();
934
935 if (target_arch.IsValid())
936 {
937 // If the remote host is ARM and we have apple as the vendor, then
938 // ARM executables and shared libraries can have mixed ARM architectures.
939 // You can have an armv6 executable, and if the host is armv7, then the
940 // system will load the best possible architecture for all shared libraries
941 // it has, so we really need to take the remote host architecture as our
942 // defacto architecture in this case.
943
944 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
945 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
946 {
947 target_arch = gdb_remote_arch;
948 }
949 else
950 {
951 // Fill in what is missing in the triple
952 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
953 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000954 if (target_triple.getVendorName().size() == 0)
955 {
Greg Claytond314e812011-03-23 00:09:55 +0000956 target_triple.setVendor (remote_triple.getVendor());
957
Greg Clayton70b57652011-05-15 01:25:55 +0000958 if (target_triple.getOSName().size() == 0)
959 {
960 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000961
Greg Clayton70b57652011-05-15 01:25:55 +0000962 if (target_triple.getEnvironmentName().size() == 0)
963 target_triple.setEnvironment (remote_triple.getEnvironment());
964 }
965 }
Greg Claytond314e812011-03-23 00:09:55 +0000966 }
967 }
968 else
969 {
970 // The target doesn't have a valid architecture yet, set it from
971 // the architecture we got from the remote GDB server
972 target_arch = gdb_remote_arch;
973 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000974 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 }
976}
977
978void
979ProcessGDBRemote::DidLaunch ()
980{
981 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982}
983
984Error
Greg Claytonc982c762010-07-09 20:39:50 +0000985ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986{
Han Ming Ong84647042012-02-25 01:07:38 +0000987 ProcessAttachInfo attach_info;
988 return DoAttachToProcessWithID(attach_pid, attach_info);
989}
990
991Error
992ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
993{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994 Error error;
995 // Clear out and clean up from any current state
996 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997 if (attach_pid != LLDB_INVALID_PROCESS_ID)
998 {
Greg Clayton71337622011-02-24 22:24:29 +0000999 // Make sure we aren't already connected?
1000 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001002 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001003
1004 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 {
Greg Clayton71337622011-02-24 22:24:29 +00001006 const char *error_string = error.AsCString();
1007 if (error_string == NULL)
1008 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1009
1010 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011 }
Greg Clayton71337622011-02-24 22:24:29 +00001012 }
1013
1014 if (error.Success())
1015 {
1016 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001017 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001018 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001019 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 }
1021 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022 return error;
1023}
1024
1025size_t
1026ProcessGDBRemote::AttachInputReaderCallback
1027(
1028 void *baton,
1029 InputReader *reader,
1030 lldb::InputReaderAction notification,
1031 const char *bytes,
1032 size_t bytes_len
1033)
1034{
1035 if (notification == eInputReaderGotToken)
1036 {
1037 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1038 if (gdb_process->m_waiting_for_attach)
1039 gdb_process->m_waiting_for_attach = false;
1040 reader->SetIsDone(true);
1041 return 1;
1042 }
1043 return 0;
1044}
1045
1046Error
Han Ming Ong84647042012-02-25 01:07:38 +00001047ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048{
1049 Error error;
1050 // Clear out and clean up from any current state
1051 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001052
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053 if (process_name && process_name[0])
1054 {
Greg Clayton71337622011-02-24 22:24:29 +00001055 // Make sure we aren't already connected?
1056 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001058 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001059
Greg Clayton71337622011-02-24 22:24:29 +00001060 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001061 {
Greg Clayton71337622011-02-24 22:24:29 +00001062 const char *error_string = error.AsCString();
1063 if (error_string == NULL)
1064 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065
Greg Clayton71337622011-02-24 22:24:29 +00001066 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067 }
Greg Clayton71337622011-02-24 22:24:29 +00001068 }
1069
1070 if (error.Success())
1071 {
1072 StreamString packet;
1073
1074 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +00001075 {
1076 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1077 {
1078 packet.PutCString ("vAttachWait");
1079 }
1080 else
1081 {
1082 if (attach_info.GetIgnoreExisting())
1083 packet.PutCString("vAttachWait");
1084 else
1085 packet.PutCString ("vAttachOrWait");
1086 }
1087 }
Greg Clayton71337622011-02-24 22:24:29 +00001088 else
1089 packet.PutCString("vAttachName");
1090 packet.PutChar(';');
1091 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1092
1093 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1094
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095 }
1096 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001097 return error;
1098}
1099
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100
Greg Claytonfbb76342013-11-20 21:07:01 +00001101bool
1102ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1103{
1104 m_gdb_comm.Disconnect();
1105 return Process::SetExitStatus (exit_status, cstr);
1106}
1107
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108void
1109ProcessGDBRemote::DidAttach ()
1110{
Greg Claytonb766a732011-02-04 01:58:07 +00001111 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112}
1113
Greg Clayton90ba8112012-12-05 00:16:59 +00001114
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115Error
1116ProcessGDBRemote::WillResume ()
1117{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001118 m_continue_c_tids.clear();
1119 m_continue_C_tids.clear();
1120 m_continue_s_tids.clear();
1121 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 return Error();
1123}
1124
1125Error
1126ProcessGDBRemote::DoResume ()
1127{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001128 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001129 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001130 if (log)
1131 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001132
1133 Listener listener ("gdb-remote.resume-packet-sent");
1134 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1135 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001136 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1137
Greg Claytond1d06e42013-04-20 00:27:58 +00001138 const size_t num_threads = GetThreadList().GetSize();
1139
Greg Clayton71fc2a32011-02-12 06:28:37 +00001140 StreamString continue_packet;
1141 bool continue_packet_error = false;
1142 if (m_gdb_comm.HasAnyVContSupport ())
1143 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001144 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001145 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001146 // All threads are continuing, just send a "c" packet
1147 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001148 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001149 else
1150 {
1151 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001152
Greg Claytond1d06e42013-04-20 00:27:58 +00001153 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001154 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001155 if (m_gdb_comm.GetVContSupported ('c'))
1156 {
1157 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)
1158 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1159 }
1160 else
1161 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001162 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001163
1164 if (!continue_packet_error && !m_continue_C_tids.empty())
1165 {
1166 if (m_gdb_comm.GetVContSupported ('C'))
1167 {
1168 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)
1169 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1170 }
1171 else
1172 continue_packet_error = true;
1173 }
Greg Claytone5219662010-12-03 06:02:24 +00001174
Greg Claytond1d06e42013-04-20 00:27:58 +00001175 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001176 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001177 if (m_gdb_comm.GetVContSupported ('s'))
1178 {
1179 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)
1180 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1181 }
1182 else
1183 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001184 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001185
1186 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001187 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001188 if (m_gdb_comm.GetVContSupported ('S'))
1189 {
1190 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)
1191 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1192 }
1193 else
1194 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001195 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001196
1197 if (continue_packet_error)
1198 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001199 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001200 }
1201 else
1202 continue_packet_error = true;
1203
1204 if (continue_packet_error)
1205 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001206 // Either no vCont support, or we tried to use part of the vCont
1207 // packet that wasn't supported by the remote GDB server.
1208 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001209 const size_t num_continue_c_tids = m_continue_c_tids.size();
1210 const size_t num_continue_C_tids = m_continue_C_tids.size();
1211 const size_t num_continue_s_tids = m_continue_s_tids.size();
1212 const size_t num_continue_S_tids = m_continue_S_tids.size();
1213 if (num_continue_c_tids > 0)
1214 {
1215 if (num_continue_c_tids == num_threads)
1216 {
1217 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001218 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001219 continue_packet.PutChar ('c');
1220 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001221 }
1222 else if (num_continue_c_tids == 1 &&
1223 num_continue_C_tids == 0 &&
1224 num_continue_s_tids == 0 &&
1225 num_continue_S_tids == 0 )
1226 {
1227 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001228 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001229 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001230 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001231 }
1232 }
1233
Greg Clayton0c74e782011-06-24 03:21:43 +00001234 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001235 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001236 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1237 num_continue_C_tids > 0 &&
1238 num_continue_s_tids == 0 &&
1239 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001240 {
1241 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001242 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001243 if (num_continue_C_tids > 1)
1244 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001245 // More that one thread with a signal, yet we don't have
1246 // vCont support and we are being asked to resume each
1247 // thread with a signal, we need to make sure they are
1248 // all the same signal, or we can't issue the continue
1249 // accurately with the current support...
1250 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001251 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001252 continue_packet_error = false;
1253 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1254 {
1255 if (m_continue_C_tids[i].second != continue_signo)
1256 continue_packet_error = true;
1257 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001258 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001259 if (!continue_packet_error)
1260 m_gdb_comm.SetCurrentThreadForRun (-1);
1261 }
1262 else
1263 {
1264 // Set the continue thread ID
1265 continue_packet_error = false;
1266 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001267 }
1268 if (!continue_packet_error)
1269 {
1270 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001271 continue_packet.Printf("C%2.2x", continue_signo);
1272 }
1273 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001274 }
1275
Greg Clayton0c74e782011-06-24 03:21:43 +00001276 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001277 {
1278 if (num_continue_s_tids == num_threads)
1279 {
1280 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001281 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001282 continue_packet.PutChar ('s');
1283 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001284 }
1285 else if (num_continue_c_tids == 0 &&
1286 num_continue_C_tids == 0 &&
1287 num_continue_s_tids == 1 &&
1288 num_continue_S_tids == 0 )
1289 {
1290 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001291 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001292 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001293 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001294 }
1295 }
1296
1297 if (!continue_packet_error && num_continue_S_tids > 0)
1298 {
1299 if (num_continue_S_tids == num_threads)
1300 {
1301 const int step_signo = m_continue_S_tids.front().second;
1302 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001303 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001304 if (num_continue_S_tids > 1)
1305 {
1306 for (size_t i=1; i<num_threads; ++i)
1307 {
1308 if (m_continue_S_tids[i].second != step_signo)
1309 continue_packet_error = true;
1310 }
1311 }
1312 if (!continue_packet_error)
1313 {
1314 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001315 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001316 continue_packet.Printf("S%2.2x", step_signo);
1317 }
1318 }
1319 else if (num_continue_c_tids == 0 &&
1320 num_continue_C_tids == 0 &&
1321 num_continue_s_tids == 0 &&
1322 num_continue_S_tids == 1 )
1323 {
1324 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001325 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001326 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001327 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001328 }
1329 }
1330 }
1331
1332 if (continue_packet_error)
1333 {
1334 error.SetErrorString ("can't make continue packet for this resume");
1335 }
1336 else
1337 {
1338 EventSP event_sp;
1339 TimeValue timeout;
1340 timeout = TimeValue::Now();
1341 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001342 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1343 {
1344 error.SetErrorString ("Trying to resume but the async thread is dead.");
1345 if (log)
1346 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1347 return error;
1348 }
1349
Greg Clayton71fc2a32011-02-12 06:28:37 +00001350 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1351
1352 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001353 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001354 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001355 if (log)
1356 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1357 }
1358 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1359 {
1360 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1361 if (log)
1362 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1363 return error;
1364 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001365 }
Greg Claytone5219662010-12-03 06:02:24 +00001366 }
1367
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001368 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001369}
1370
Greg Clayton9e920902012-04-10 02:25:43 +00001371void
1372ProcessGDBRemote::ClearThreadIDList ()
1373{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001374 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001375 m_thread_ids.clear();
1376}
1377
1378bool
1379ProcessGDBRemote::UpdateThreadIDList ()
1380{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001381 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001382 bool sequence_mutex_unavailable = false;
1383 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1384 if (sequence_mutex_unavailable)
1385 {
Greg Clayton9e920902012-04-10 02:25:43 +00001386 return false; // We just didn't get the list
1387 }
1388 return true;
1389}
1390
Greg Clayton9fc13552012-04-10 00:18:59 +00001391bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001392ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001393{
1394 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001395 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001396 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001397 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001398
1399 size_t num_thread_ids = m_thread_ids.size();
1400 // The "m_thread_ids" thread ID list should always be updated after each stop
1401 // reply packet, but in case it isn't, update it here.
1402 if (num_thread_ids == 0)
1403 {
1404 if (!UpdateThreadIDList ())
1405 return false;
1406 num_thread_ids = m_thread_ids.size();
1407 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001408
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001409 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001410 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001412 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413 {
Greg Clayton9e920902012-04-10 02:25:43 +00001414 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001415 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001416 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001417 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001418 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001419 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1420 log->Printf(
1421 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1422 __FUNCTION__,
1423 thread_sp.get(),
1424 thread_sp->GetID());
1425 }
1426 else
1427 {
1428 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1429 log->Printf(
1430 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1431 __FUNCTION__,
1432 thread_sp.get(),
1433 thread_sp->GetID());
1434 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001435 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001436 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001438
1439 // Whatever that is left in old_thread_list_copy are not
1440 // present in new_thread_list. Remove non-existent threads from internal id table.
1441 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1442 for (size_t i=0; i<old_num_thread_ids; i++)
1443 {
1444 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1445 if (old_thread_sp)
1446 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001447 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001448 m_thread_id_to_index_id_map.erase(old_thread_id);
1449 }
1450 }
1451
Greg Clayton9fc13552012-04-10 00:18:59 +00001452 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001453}
1454
1455
1456StateType
1457ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1458{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001459 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001460 const char stop_type = stop_packet.GetChar();
1461 switch (stop_type)
1462 {
1463 case 'T':
1464 case 'S':
1465 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001466 // This is a bit of a hack, but is is required. If we did exec, we
1467 // need to clear our thread lists and also know to rebuild our dynamic
1468 // register info before we lookup and threads and populate the expedited
1469 // register values so we need to know this right away so we can cleanup
1470 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001471 const uint32_t stop_id = GetStopID();
1472 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001473 {
1474 // Our first stop, make sure we have a process ID, and also make
1475 // sure we know about our registers
1476 if (GetID() == LLDB_INVALID_PROCESS_ID)
1477 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001478 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001479 if (pid != LLDB_INVALID_PROCESS_ID)
1480 SetID (pid);
1481 }
1482 BuildDynamicRegisterInfo (true);
1483 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484 // Stop with signal and thread info
1485 const uint8_t signo = stop_packet.GetHexU8();
1486 std::string name;
1487 std::string value;
1488 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001489 std::string reason;
1490 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001491 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001492 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001494 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001495 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001496
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001497 while (stop_packet.GetNameColonValue(name, value))
1498 {
1499 if (name.compare("metype") == 0)
1500 {
1501 // exception type in big endian hex
1502 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1503 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 else if (name.compare("medata") == 0)
1505 {
1506 // exception data in big endian hex
1507 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1508 }
1509 else if (name.compare("thread") == 0)
1510 {
1511 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001512 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001513 // m_thread_list_real does have its own mutex, but we need to
1514 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1515 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1516 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1517 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001518
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001519 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001520 {
Greg Claytone576ab22011-02-15 00:19:15 +00001521 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001522 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001523 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1524 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1525 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1526 __FUNCTION__,
1527 thread_sp.get(),
1528 thread_sp->GetID());
1529
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001530 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001531 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001532 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1533
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001534 }
Greg Clayton9e920902012-04-10 02:25:43 +00001535 else if (name.compare("threads") == 0)
1536 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001537 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001538 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001539 // A comma separated list of all threads in the current
1540 // process that includes the thread for this stop reply
1541 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001542 size_t comma_pos;
1543 lldb::tid_t tid;
1544 while ((comma_pos = value.find(',')) != std::string::npos)
1545 {
1546 value[comma_pos] = '\0';
1547 // thread in big endian hex
1548 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1549 if (tid != LLDB_INVALID_THREAD_ID)
1550 m_thread_ids.push_back (tid);
1551 value.erase(0, comma_pos + 1);
1552
1553 }
1554 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1555 if (tid != LLDB_INVALID_THREAD_ID)
1556 m_thread_ids.push_back (tid);
1557 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001558 else if (name.compare("hexname") == 0)
1559 {
1560 StringExtractor name_extractor;
1561 // Swap "value" over into "name_extractor"
1562 name_extractor.GetStringRef().swap(value);
1563 // Now convert the HEX bytes into a string value
1564 name_extractor.GetHexByteString (value);
1565 thread_name.swap (value);
1566 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 else if (name.compare("name") == 0)
1568 {
1569 thread_name.swap (value);
1570 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001571 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001572 {
1573 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1574 }
Greg Claytona658fd22011-06-04 01:26:29 +00001575 else if (name.compare("reason") == 0)
1576 {
1577 reason.swap(value);
1578 }
1579 else if (name.compare("description") == 0)
1580 {
1581 StringExtractor desc_extractor;
1582 // Swap "value" over into "name_extractor"
1583 desc_extractor.GetStringRef().swap(value);
1584 // Now convert the HEX bytes into a string value
1585 desc_extractor.GetHexByteString (thread_name);
1586 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001587 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1588 {
1589 // We have a register number that contains an expedited
1590 // register value. Lets supply this register to our thread
1591 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001592 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001593 {
1594 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1595
1596 if (reg != UINT32_MAX)
1597 {
1598 StringExtractor reg_value_extractor;
1599 // Swap "value" over into "reg_value_extractor"
1600 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001601 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001602 {
1603 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1604 name.c_str(),
1605 reg,
1606 reg,
1607 reg_value_extractor.GetStringRef().c_str(),
1608 stop_packet.GetStringRef().c_str());
1609 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001610 }
1611 }
1612 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001613 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001614
1615 if (thread_sp)
1616 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001617 // Clear the stop info just in case we don't set it to anything
1618 thread_sp->SetStopInfo (StopInfoSP());
1619
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001620 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001621 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001622 if (exc_type != 0)
1623 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001624 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001625
Greg Clayton160c9d82013-05-01 21:54:04 +00001626 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1627 exc_type,
1628 exc_data_size,
1629 exc_data_size >= 1 ? exc_data[0] : 0,
1630 exc_data_size >= 2 ? exc_data[1] : 0,
1631 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632 }
Greg Claytona658fd22011-06-04 01:26:29 +00001633 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001634 {
Greg Claytona658fd22011-06-04 01:26:29 +00001635 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001636 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001637 if (!reason.empty())
1638 {
1639 if (reason.compare("trace") == 0)
1640 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001641 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001642 handled = true;
1643 }
1644 else if (reason.compare("breakpoint") == 0)
1645 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001646 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1647 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001648 if (bp_site_sp)
1649 {
1650 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1651 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1652 // 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 +00001653 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001654 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001655 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001656 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001657 }
1658 else
1659 {
1660 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001661 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001662 }
1663 }
1664
Greg Claytona658fd22011-06-04 01:26:29 +00001665 }
1666 else if (reason.compare("trap") == 0)
1667 {
1668 // Let the trap just use the standard signal stop reason below...
1669 }
1670 else if (reason.compare("watchpoint") == 0)
1671 {
1672 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1673 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001674 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001675 handled = true;
1676 }
1677 else if (reason.compare("exception") == 0)
1678 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001679 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001680 handled = true;
1681 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001682 else if (reason.compare("exec") == 0)
1683 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001684 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001685 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1686 handled = true;
1687 }
Greg Claytona658fd22011-06-04 01:26:29 +00001688 }
1689
Greg Clayton15fc2be2013-05-21 01:00:52 +00001690 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001691 {
1692 if (signo == SIGTRAP)
1693 {
1694 // Currently we are going to assume SIGTRAP means we are either
1695 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001696 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001697 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001698 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001699
Greg Claytona658fd22011-06-04 01:26:29 +00001700 if (bp_site_sp)
1701 {
1702 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1703 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1704 // 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 +00001705 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001706 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001707 if(m_breakpoint_pc_offset != 0)
1708 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001709 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001710 }
1711 else
1712 {
1713 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001714 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001715 }
1716 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001717 else
Greg Claytona658fd22011-06-04 01:26:29 +00001718 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001719 // If we were stepping then assume the stop was the result of the trace. If we were
1720 // not stepping then report the SIGTRAP.
1721 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001722 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1723 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001724 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001725 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001726 }
1727 }
1728 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001729 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001730 }
Greg Claytona658fd22011-06-04 01:26:29 +00001731
1732 if (!description.empty())
1733 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001734 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001735 if (stop_info_sp)
1736 {
1737 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001738 }
Greg Claytona658fd22011-06-04 01:26:29 +00001739 else
1740 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001741 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001742 }
1743 }
1744 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745 }
1746 return eStateStopped;
1747 }
1748 break;
1749
1750 case 'W':
1751 // process exited
1752 return eStateExited;
1753
1754 default:
1755 break;
1756 }
1757 return eStateInvalid;
1758}
1759
1760void
1761ProcessGDBRemote::RefreshStateAfterStop ()
1762{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001763 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001764 m_thread_ids.clear();
1765 // Set the thread stop info. It might have a "threads" key whose value is
1766 // a list of all thread IDs in the current process, so m_thread_ids might
1767 // get set.
1768 SetThreadStopInfo (m_last_stop_packet);
1769 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1770 if (m_thread_ids.empty())
1771 {
1772 // No, we need to fetch the thread list manually
1773 UpdateThreadIDList();
1774 }
1775
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001776 // Let all threads recover from stopping and do any clean up based
1777 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001778 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001779
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780}
1781
1782Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001783ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784{
1785 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001786
Greg Clayton6ed95942011-01-22 07:12:45 +00001787 bool timed_out = false;
1788 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001789
1790 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001791 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001792 // We are being asked to halt during an attach. We need to just close
1793 // our file handle and debugserver will go away, and we can be done...
1794 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001795 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001796 else
1797 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001798 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001799 {
1800 if (timed_out)
1801 error.SetErrorString("timed out sending interrupt packet");
1802 else
1803 error.SetErrorString("unknown error sending interrupt packet");
1804 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001805
1806 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001807 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 return error;
1809}
1810
1811Error
Jim Inghamacff8952013-05-02 00:27:30 +00001812ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001813{
1814 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001815 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001816 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001817 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1818
Greg Clayton594e5ed2010-09-27 21:07:38 +00001819 DisableAllBreakpointSites ();
1820
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001821 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001822
Jim Inghamacff8952013-05-02 00:27:30 +00001823 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001824 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001825 {
Jim Inghamacff8952013-05-02 00:27:30 +00001826 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001827 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1828 else
Jim Inghamacff8952013-05-02 00:27:30 +00001829 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001830 }
Jim Inghamacff8952013-05-02 00:27:30 +00001831
1832 if (!error.Success())
1833 return error;
1834
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001835 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001836 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001837
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001838 SetPrivateState (eStateDetached);
1839 ResumePrivateStateThread();
1840
1841 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001842 return error;
1843}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001844
Jim Ingham43c555d2012-07-04 00:35:43 +00001845
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001846Error
1847ProcessGDBRemote::DoDestroy ()
1848{
1849 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001850 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001851 if (log)
1852 log->Printf ("ProcessGDBRemote::DoDestroy()");
1853
Jim Ingham43c555d2012-07-04 00:35:43 +00001854 // There is a bug in older iOS debugservers where they don't shut down the process
1855 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1856 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1857 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1858 // destroy it again.
1859 //
1860 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1861 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1862 // the debugservers with this bug are equal. There really should be a better way to test this!
1863 //
1864 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1865 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1866 // just do the straight-forward kill.
1867 //
1868 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1869 // necessary (or helpful) to do any of this.
1870
1871 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1872 {
1873 PlatformSP platform_sp = GetTarget().GetPlatform();
1874
1875 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1876 if (platform_sp
1877 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001878 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001879 {
1880 if (m_destroy_tried_resuming)
1881 {
1882 if (log)
1883 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1884 }
1885 else
1886 {
1887 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1888 // but we really need it to happen here and it doesn't matter if we do it twice.
1889 m_thread_list.DiscardThreadPlans();
1890 DisableAllBreakpointSites();
1891
1892 bool stop_looks_like_crash = false;
1893 ThreadList &threads = GetThreadList();
1894
1895 {
Jim Ingham45350372012-09-11 00:08:52 +00001896 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001897
1898 size_t num_threads = threads.GetSize();
1899 for (size_t i = 0; i < num_threads; i++)
1900 {
1901 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001902 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001903 StopReason reason = eStopReasonInvalid;
1904 if (stop_info_sp)
1905 reason = stop_info_sp->GetStopReason();
1906 if (reason == eStopReasonBreakpoint
1907 || reason == eStopReasonException)
1908 {
1909 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001910 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1911 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001912 stop_info_sp->GetDescription());
1913 stop_looks_like_crash = true;
1914 break;
1915 }
1916 }
1917 }
1918
1919 if (stop_looks_like_crash)
1920 {
1921 if (log)
1922 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1923 m_destroy_tried_resuming = true;
1924
1925 // If we are going to run again before killing, it would be good to suspend all the threads
1926 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1927 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1928 // have to run the risk of letting those threads proceed a bit.
1929
1930 {
Jim Ingham45350372012-09-11 00:08:52 +00001931 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001932
1933 size_t num_threads = threads.GetSize();
1934 for (size_t i = 0; i < num_threads; i++)
1935 {
1936 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001937 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001938 StopReason reason = eStopReasonInvalid;
1939 if (stop_info_sp)
1940 reason = stop_info_sp->GetStopReason();
1941 if (reason != eStopReasonBreakpoint
1942 && reason != eStopReasonException)
1943 {
1944 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001945 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1946 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001947 thread_sp->SetResumeState(eStateSuspended);
1948 }
1949 }
1950 }
1951 Resume ();
1952 return Destroy();
1953 }
1954 }
1955 }
1956 }
1957
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001959 int exit_status = SIGABRT;
1960 std::string exit_string;
1961
Greg Clayton6ed95942011-01-22 07:12:45 +00001962 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001963 {
Jim Inghamaab78372011-10-28 01:11:35 +00001964 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001965 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001966
1967 StringExtractorGDBRemote response;
1968 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001969 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1970
Greg Claytonc574ede2011-03-10 02:26:48 +00001971 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async))
Greg Clayton513c26c2011-01-29 07:10:55 +00001972 {
1973 char packet_cmd = response.GetChar(0);
1974
1975 if (packet_cmd == 'W' || packet_cmd == 'X')
1976 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00001977 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00001978 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00001979 exit_status = response.GetHexU8();
1980 }
1981 else
1982 {
1983 if (log)
1984 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
1985 exit_string.assign("got unexpected response to k packet: ");
1986 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00001987 }
1988 }
1989 else
1990 {
Jim Inghambabfc382012-06-06 00:32:39 +00001991 if (log)
1992 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
1993 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00001994 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001995
1996 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00001997 }
Jim Inghambabfc382012-06-06 00:32:39 +00001998 else
1999 {
2000 if (log)
2001 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00002002 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002003 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002004 }
Jim Inghambabfc382012-06-06 00:32:39 +00002005 else
2006 {
2007 // If we missed setting the exit status on the way out, do it here.
2008 // NB set exit status can be called multiple times, the first one sets the status.
2009 exit_string.assign("destroying when not connected to debugserver");
2010 }
2011
2012 SetExitStatus(exit_status, exit_string.c_str());
2013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002015 KillDebugserverProcess ();
2016 return error;
2017}
2018
Greg Clayton8cda7f02013-05-21 21:55:59 +00002019void
2020ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2021{
2022 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2023 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2024 if (did_exec)
2025 {
2026 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2027 if (log)
2028 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2029
2030 m_thread_list_real.Clear();
2031 m_thread_list.Clear();
2032 BuildDynamicRegisterInfo (true);
2033 m_gdb_comm.ResetDiscoverableSettings();
2034 }
2035 m_last_stop_packet = response;
2036}
2037
2038
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002039//------------------------------------------------------------------
2040// Process Queries
2041//------------------------------------------------------------------
2042
2043bool
2044ProcessGDBRemote::IsAlive ()
2045{
Greg Clayton10177aa2010-12-08 05:08:21 +00002046 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002047}
2048
2049addr_t
2050ProcessGDBRemote::GetImageInfoAddress()
2051{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002052 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053}
2054
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055//------------------------------------------------------------------
2056// Process Memory
2057//------------------------------------------------------------------
2058size_t
2059ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2060{
2061 if (size > m_max_memory_size)
2062 {
2063 // Keep memory read sizes down to a sane limit. This function will be
2064 // called multiple times in order to complete the task by
2065 // lldb_private::Process so it is ok to do this.
2066 size = m_max_memory_size;
2067 }
2068
2069 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002070 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002071 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002072 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002073 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 {
Greg Clayton576d8832011-03-22 04:00:09 +00002075 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002076 {
2077 error.Clear();
2078 return response.GetHexBytes(buf, size, '\xdd');
2079 }
Greg Clayton576d8832011-03-22 04:00:09 +00002080 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002081 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002082 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002083 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002084 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002085 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002086 }
2087 else
2088 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002089 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090 }
2091 return 0;
2092}
2093
2094size_t
2095ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2096{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002097 if (size > m_max_memory_size)
2098 {
2099 // Keep memory read sizes down to a sane limit. This function will be
2100 // called multiple times in order to complete the task by
2101 // lldb_private::Process so it is ok to do this.
2102 size = m_max_memory_size;
2103 }
2104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002106 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002107 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 StringExtractorGDBRemote response;
Greg Claytonc574ede2011-03-10 02:26:48 +00002109 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110 {
Greg Clayton576d8832011-03-22 04:00:09 +00002111 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112 {
2113 error.Clear();
2114 return size;
2115 }
Greg Clayton576d8832011-03-22 04:00:09 +00002116 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002117 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002118 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002119 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002120 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002121 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 +00002122 }
2123 else
2124 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002125 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 }
2127 return 0;
2128}
2129
2130lldb::addr_t
2131ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2132{
Greg Clayton2a48f522011-05-14 01:50:35 +00002133 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2134
Greg Clayton70b57652011-05-15 01:25:55 +00002135 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002136 switch (supported)
2137 {
2138 case eLazyBoolCalculate:
2139 case eLazyBoolYes:
2140 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2141 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2142 return allocated_addr;
2143
2144 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002145 // Call mmap() to create memory in the inferior..
2146 unsigned prot = 0;
2147 if (permissions & lldb::ePermissionsReadable)
2148 prot |= eMmapProtRead;
2149 if (permissions & lldb::ePermissionsWritable)
2150 prot |= eMmapProtWrite;
2151 if (permissions & lldb::ePermissionsExecutable)
2152 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002153
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002154 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2155 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2156 m_addr_to_mmap_size[allocated_addr] = size;
2157 else
2158 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002159 break;
2160 }
2161
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002163 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164 else
2165 error.Clear();
2166 return allocated_addr;
2167}
2168
2169Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002170ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2171 MemoryRegionInfo &region_info)
2172{
2173
2174 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2175 return error;
2176}
2177
2178Error
Johnny Chen64637202012-05-23 21:09:52 +00002179ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2180{
2181
2182 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2183 return error;
2184}
2185
2186Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002187ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2188{
2189 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2190 return error;
2191}
2192
2193Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002194ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2195{
2196 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002197 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2198
2199 switch (supported)
2200 {
2201 case eLazyBoolCalculate:
2202 // We should never be deallocating memory without allocating memory
2203 // first so we should never get eLazyBoolCalculate
2204 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2205 break;
2206
2207 case eLazyBoolYes:
2208 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002209 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002210 break;
2211
2212 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002213 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002214 {
2215 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002216 if (pos != m_addr_to_mmap_size.end() &&
2217 InferiorCallMunmap(this, addr, pos->second))
2218 m_addr_to_mmap_size.erase (pos);
2219 else
Daniel Malead01b2952012-11-29 21:49:15 +00002220 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002221 }
2222 break;
2223 }
2224
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 return error;
2226}
2227
2228
2229//------------------------------------------------------------------
2230// Process STDIO
2231//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232size_t
2233ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2234{
2235 if (m_stdio_communication.IsConnected())
2236 {
2237 ConnectionStatus status;
2238 m_stdio_communication.Write(src, src_len, status, NULL);
2239 }
2240 return 0;
2241}
2242
2243Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002244ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245{
2246 Error error;
2247 assert (bp_site != NULL);
2248
Greg Clayton5160ce52013-03-27 23:08:40 +00002249 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002250 user_id_t site_id = bp_site->GetID();
2251 const addr_t addr = bp_site->GetLoadAddress();
2252 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002253 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254
2255 if (bp_site->IsEnabled())
2256 {
2257 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002258 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 +00002259 return error;
2260 }
2261 else
2262 {
2263 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2264
Greg Claytoneb023e72013-10-11 19:48:25 +00002265 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 {
2267 // Try and set hardware breakpoint, and if that fails, fall through
2268 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002269 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002271 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272 {
2273 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002274 bp_site->SetType (BreakpointSite::eHardware);
Greg Claytoneb023e72013-10-11 19:48:25 +00002275 }
2276 else
2277 {
2278 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002280 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002281 else
2282 {
2283 error.SetErrorString("hardware breakpoints are not supported");
2284 }
2285 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002286 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002287 else if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002289 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2290 {
2291 bp_site->SetEnabled(true);
2292 bp_site->SetType (BreakpointSite::eExternal);
2293 return error;
2294 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002295 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002296
2297 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 }
2299
2300 if (log)
2301 {
2302 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002303 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 bp_site->GetLoadAddress(),
2305 err_string ? err_string : "NULL");
2306 }
2307 // We shouldn't reach here on a successful breakpoint enable...
2308 if (error.Success())
2309 error.SetErrorToGenericError();
2310 return error;
2311}
2312
2313Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002314ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315{
2316 Error error;
2317 assert (bp_site != NULL);
2318 addr_t addr = bp_site->GetLoadAddress();
2319 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002320 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002322 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323
2324 if (bp_site->IsEnabled())
2325 {
2326 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2327
Greg Clayton8b82f082011-04-12 05:54:46 +00002328 BreakpointSite::Type bp_type = bp_site->GetType();
2329 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002331 case BreakpointSite::eSoftware:
2332 error = DisableSoftwareBreakpoint (bp_site);
2333 break;
2334
2335 case BreakpointSite::eHardware:
2336 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2337 error.SetErrorToGenericError();
2338 break;
2339
2340 case BreakpointSite::eExternal:
2341 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2342 error.SetErrorToGenericError();
2343 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002345 if (error.Success())
2346 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 }
2348 else
2349 {
2350 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002351 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 +00002352 return error;
2353 }
2354
2355 if (error.Success())
2356 error.SetErrorToGenericError();
2357 return error;
2358}
2359
Johnny Chen11309a32011-09-06 22:38:36 +00002360// Pre-requisite: wp != NULL.
2361static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002362GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002363{
2364 assert(wp);
2365 bool watch_read = wp->WatchpointRead();
2366 bool watch_write = wp->WatchpointWrite();
2367
2368 // watch_read and watch_write cannot both be false.
2369 assert(watch_read || watch_write);
2370 if (watch_read && watch_write)
2371 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002372 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002373 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002374 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002375 return eWatchpointWrite;
2376}
2377
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002379ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002380{
2381 Error error;
2382 if (wp)
2383 {
2384 user_id_t watchID = wp->GetID();
2385 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002386 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002387 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002388 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002389 if (wp->IsEnabled())
2390 {
2391 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002392 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 +00002393 return error;
2394 }
Johnny Chen11309a32011-09-06 22:38:36 +00002395
2396 GDBStoppointType type = GetGDBStoppointType(wp);
2397 // Pass down an appropriate z/Z packet...
2398 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399 {
Johnny Chen11309a32011-09-06 22:38:36 +00002400 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2401 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002402 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002403 return error;
2404 }
2405 else
2406 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407 }
Johnny Chen11309a32011-09-06 22:38:36 +00002408 else
2409 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 }
2411 else
2412 {
Johnny Chen01a67862011-10-14 00:42:25 +00002413 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 }
2415 if (error.Success())
2416 error.SetErrorToGenericError();
2417 return error;
2418}
2419
2420Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002421ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422{
2423 Error error;
2424 if (wp)
2425 {
2426 user_id_t watchID = wp->GetID();
2427
Greg Clayton5160ce52013-03-27 23:08:40 +00002428 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429
2430 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002431
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002433 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434
Johnny Chen11309a32011-09-06 22:38:36 +00002435 if (!wp->IsEnabled())
2436 {
2437 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002438 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 +00002439 // See also 'class WatchpointSentry' within StopInfo.cpp.
2440 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2441 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002442 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002443 return error;
2444 }
2445
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446 if (wp->IsHardware())
2447 {
Johnny Chen11309a32011-09-06 22:38:36 +00002448 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002450 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2451 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002452 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002453 return error;
2454 }
2455 else
2456 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002457 }
2458 // TODO: clear software watchpoints if we implement them
2459 }
2460 else
2461 {
Johnny Chen01a67862011-10-14 00:42:25 +00002462 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463 }
2464 if (error.Success())
2465 error.SetErrorToGenericError();
2466 return error;
2467}
2468
2469void
2470ProcessGDBRemote::Clear()
2471{
2472 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002473 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002474 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475}
2476
2477Error
2478ProcessGDBRemote::DoSignal (int signo)
2479{
2480 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002481 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482 if (log)
2483 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2484
2485 if (!m_gdb_comm.SendAsyncSignal (signo))
2486 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2487 return error;
2488}
2489
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002490Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002491ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492{
2493 Error error;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002494 uint16_t port = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002495 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2496 {
2497 // If we locate debugserver, keep that located version around
2498 static FileSpec g_debugserver_file_spec;
2499
Han Ming Ong84647042012-02-25 01:07:38 +00002500 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002501 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2502 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503
Greg Clayton91a9b2472013-12-04 19:19:12 +00002504 error = GDBRemoteCommunication::StartDebugserverProcess ("localhost:0",
2505 debugserver_launch_info,
2506 port);
2507
2508 if (error.Success ())
2509 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002510 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002511 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002512
2513 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2514 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002515
2516 if (error.Fail())
2517 {
2518 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2519
2520 if (log)
2521 log->Printf("failed to start debugserver process: %s", error.AsCString());
2522 return error;
2523 }
2524
2525 char connect_url[128];
2526 snprintf (connect_url, sizeof(connect_url), "connect://localhost:%u", port);
2527
2528 error = ConnectToDebugserver (connect_url);
2529
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002530 }
2531 return error;
2532}
2533
2534bool
2535ProcessGDBRemote::MonitorDebugserverProcess
2536(
2537 void *callback_baton,
2538 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002539 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002540 int signo, // Zero for no signal
2541 int exit_status // Exit value of process if signal is zero
2542)
2543{
Greg Claytone4e45922011-11-16 05:37:56 +00002544 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2545 // and might not exist anymore, so we need to carefully try to get the
2546 // target for this process first since we have a race condition when
2547 // we are done running between getting the notice that the inferior
2548 // process has died and the debugserver that was debugging this process.
2549 // In our test suite, we are also continually running process after
2550 // process, so we must be very careful to make sure:
2551 // 1 - process object hasn't been deleted already
2552 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002553
2554 // "debugserver_pid" argument passed in is the process ID for
2555 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002556 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002557
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002558 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002559
Greg Claytone4e45922011-11-16 05:37:56 +00002560 // Get a shared pointer to the target that has a matching process pointer.
2561 // This target could be gone, or the target could already have a new process
2562 // object inside of it
2563 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2564
Greg Clayton6779606a2011-01-22 23:43:18 +00002565 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002566 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 +00002567
Greg Claytone4e45922011-11-16 05:37:56 +00002568 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002569 {
Greg Claytone4e45922011-11-16 05:37:56 +00002570 // We found a process in a target that matches, but another thread
2571 // might be in the process of launching a new process that will
2572 // soon replace it, so get a shared pointer to the process so we
2573 // can keep it alive.
2574 ProcessSP process_sp (target_sp->GetProcessSP());
2575 // Now we have a shared pointer to the process that can't go away on us
2576 // so we now make sure it was the same as the one passed in, and also make
2577 // sure that our previous "process *" didn't get deleted and have a new
2578 // "process *" created in its place with the same pointer. To verify this
2579 // we make sure the process has our debugserver process ID. If we pass all
2580 // of these tests, then we are sure that this process is the one we were
2581 // looking for.
2582 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583 {
Greg Claytone4e45922011-11-16 05:37:56 +00002584 // Sleep for a half a second to make sure our inferior process has
2585 // time to set its exit status before we set it incorrectly when
2586 // both the debugserver and the inferior process shut down.
2587 usleep (500000);
2588 // If our process hasn't yet exited, debugserver might have died.
2589 // If the process did exit, the we are reaping it.
2590 const StateType state = process->GetState();
2591
2592 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2593 state != eStateInvalid &&
2594 state != eStateUnloaded &&
2595 state != eStateExited &&
2596 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597 {
Greg Claytone4e45922011-11-16 05:37:56 +00002598 char error_str[1024];
2599 if (signo)
2600 {
2601 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2602 if (signal_cstr)
2603 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2604 else
2605 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2606 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002607 else
Greg Claytone4e45922011-11-16 05:37:56 +00002608 {
2609 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2610 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002611
Greg Claytone4e45922011-11-16 05:37:56 +00002612 process->SetExitStatus (-1, error_str);
2613 }
2614 // Debugserver has exited we need to let our ProcessGDBRemote
2615 // know that it no longer has a debugserver instance
2616 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002617 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618 }
2619 return true;
2620}
2621
2622void
2623ProcessGDBRemote::KillDebugserverProcess ()
2624{
Greg Claytonfbb76342013-11-20 21:07:01 +00002625 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2627 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002628 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002629 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2630 }
2631}
2632
2633void
2634ProcessGDBRemote::Initialize()
2635{
2636 static bool g_initialized = false;
2637
2638 if (g_initialized == false)
2639 {
2640 g_initialized = true;
2641 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2642 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002643 CreateInstance,
2644 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002645
2646 Log::Callbacks log_callbacks = {
2647 ProcessGDBRemoteLog::DisableLog,
2648 ProcessGDBRemoteLog::EnableLog,
2649 ProcessGDBRemoteLog::ListLogCategories
2650 };
2651
2652 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2653 }
2654}
2655
Greg Clayton7f982402013-07-15 22:54:20 +00002656void
2657ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2658{
2659 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2660 {
2661 const bool is_global_setting = true;
2662 PluginManager::CreateSettingForProcessPlugin (debugger,
2663 GetGlobalPluginProperties()->GetValueProperties(),
2664 ConstString ("Properties for the gdb-remote process plug-in."),
2665 is_global_setting);
2666 }
2667}
2668
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002669bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002670ProcessGDBRemote::StartAsyncThread ()
2671{
Greg Clayton5160ce52013-03-27 23:08:40 +00002672 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673
2674 if (log)
2675 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002676
2677 Mutex::Locker start_locker(m_async_thread_state_mutex);
2678 if (m_async_thread_state == eAsyncThreadNotStarted)
2679 {
2680 // Create a thread that watches our internal state and controls which
2681 // events make it to clients (into the DCProcess event queue).
2682 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2683 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2684 {
2685 m_async_thread_state = eAsyncThreadRunning;
2686 return true;
2687 }
2688 else
2689 return false;
2690 }
2691 else
2692 {
2693 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2694 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2695 if (log)
2696 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2697 if (m_async_thread_state == eAsyncThreadRunning)
2698 return true;
2699 else
2700 return false;
2701 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702}
2703
2704void
2705ProcessGDBRemote::StopAsyncThread ()
2706{
Greg Clayton5160ce52013-03-27 23:08:40 +00002707 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708
2709 if (log)
2710 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2711
Jim Ingham455fa5c2012-11-01 01:15:33 +00002712 Mutex::Locker start_locker(m_async_thread_state_mutex);
2713 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002715 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2716
2717 // This will shut down the async thread.
2718 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2719
2720 // Stop the stdio thread
2721 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2722 {
2723 Host::ThreadJoin (m_async_thread, NULL, NULL);
2724 }
2725 m_async_thread_state = eAsyncThreadDone;
2726 }
2727 else
2728 {
2729 if (log)
2730 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 }
2732}
2733
2734
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002735thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736ProcessGDBRemote::AsyncThread (void *arg)
2737{
2738 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2739
Greg Clayton5160ce52013-03-27 23:08:40 +00002740 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002742 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
2744 Listener listener ("ProcessGDBRemote::AsyncThread");
2745 EventSP event_sp;
2746 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2747 eBroadcastBitAsyncThreadShouldExit;
2748
2749 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2750 {
Greg Clayton71337622011-02-24 22:24:29 +00002751 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2752
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 bool done = false;
2754 while (!done)
2755 {
2756 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002757 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002758 if (listener.WaitForEvent (NULL, event_sp))
2759 {
2760 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002761 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762 {
Greg Clayton71337622011-02-24 22:24:29 +00002763 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002764 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 +00002765
Greg Clayton71337622011-02-24 22:24:29 +00002766 switch (event_type)
2767 {
2768 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769 {
Greg Clayton71337622011-02-24 22:24:29 +00002770 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002771
Greg Clayton71337622011-02-24 22:24:29 +00002772 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 {
Greg Clayton71337622011-02-24 22:24:29 +00002774 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2775 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2776 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002777 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778
Greg Clayton71337622011-02-24 22:24:29 +00002779 if (::strstr (continue_cstr, "vAttach") == NULL)
2780 process->SetPrivateState(eStateRunning);
2781 StringExtractorGDBRemote response;
2782 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002783
Greg Clayton0772ded2012-05-16 02:48:06 +00002784 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2785 // The thread ID list might be contained within the "response", or the stop reply packet that
2786 // caused the stop. So clear it now before we give the stop reply packet to the process
2787 // using the process->SetLastStopPacket()...
2788 process->ClearThreadIDList ();
2789
Greg Clayton71337622011-02-24 22:24:29 +00002790 switch (stop_state)
2791 {
2792 case eStateStopped:
2793 case eStateCrashed:
2794 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002795 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002796 process->SetPrivateState (stop_state);
2797 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798
Greg Clayton71337622011-02-24 22:24:29 +00002799 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002800 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002801 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002802 response.SetFilePos(1);
2803 process->SetExitStatus(response.GetHexU8(), NULL);
2804 done = true;
2805 break;
2806
2807 case eStateInvalid:
2808 process->SetExitStatus(-1, "lost connection");
2809 break;
2810
2811 default:
2812 process->SetPrivateState (stop_state);
2813 break;
2814 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815 }
2816 }
Greg Clayton71337622011-02-24 22:24:29 +00002817 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818
Greg Clayton71337622011-02-24 22:24:29 +00002819 case eBroadcastBitAsyncThreadShouldExit:
2820 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002821 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002822 done = true;
2823 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824
Greg Clayton71337622011-02-24 22:24:29 +00002825 default:
2826 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002827 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 +00002828 done = true;
2829 break;
2830 }
2831 }
2832 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2833 {
2834 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2835 {
2836 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002837 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 }
2840 }
2841 else
2842 {
2843 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002844 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 +00002845 done = true;
2846 }
2847 }
2848 }
2849
2850 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002851 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852
2853 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2854 return NULL;
2855}
2856
Greg Claytone996fd32011-03-08 22:40:15 +00002857//uint32_t
2858//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2859//{
2860// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2861// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2862// if (m_local_debugserver)
2863// {
2864// return Host::ListProcessesMatchingName (name, matches, pids);
2865// }
2866// else
2867// {
2868// // FIXME: Implement talking to the remote debugserver.
2869// return 0;
2870// }
2871//
2872//}
2873//
Jim Ingham1c823b42011-01-22 01:33:44 +00002874bool
2875ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2876 lldb_private::StoppointCallbackContext *context,
2877 lldb::user_id_t break_id,
2878 lldb::user_id_t break_loc_id)
2879{
2880 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2881 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00002882 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00002883 if (log)
2884 log->Printf("Hit New Thread Notification breakpoint.");
2885 return false;
2886}
2887
2888
2889bool
2890ProcessGDBRemote::StartNoticingNewThreads()
2891{
Greg Clayton5160ce52013-03-27 23:08:40 +00002892 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00002893 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002894 {
Greg Clayton4116e932012-05-15 02:33:01 +00002895 if (log && log->GetVerbose())
2896 log->Printf("Enabled noticing new thread breakpoint.");
2897 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002898 }
Greg Clayton4116e932012-05-15 02:33:01 +00002899 else
Jim Ingham1c823b42011-01-22 01:33:44 +00002900 {
Greg Clayton4116e932012-05-15 02:33:01 +00002901 PlatformSP platform_sp (m_target.GetPlatform());
2902 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002903 {
Greg Clayton4116e932012-05-15 02:33:01 +00002904 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2905 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002906 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00002907 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00002908 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2909 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002910 }
2911 else
2912 {
2913 if (log)
2914 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00002915 }
2916 }
2917 }
Greg Clayton4116e932012-05-15 02:33:01 +00002918 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00002919}
2920
2921bool
2922ProcessGDBRemote::StopNoticingNewThreads()
2923{
Greg Clayton5160ce52013-03-27 23:08:40 +00002924 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00002925 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00002926 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00002927
2928 if (m_thread_create_bp_sp)
2929 m_thread_create_bp_sp->SetEnabled(false);
2930
Jim Ingham1c823b42011-01-22 01:33:44 +00002931 return true;
2932}
2933
Jason Molenda5e8534e2012-10-03 01:29:34 +00002934lldb_private::DynamicLoader *
2935ProcessGDBRemote::GetDynamicLoader ()
2936{
2937 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00002938 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00002939 return m_dyld_ap.get();
2940}
Jim Ingham1c823b42011-01-22 01:33:44 +00002941
Greg Clayton998255b2012-10-13 02:07:45 +00002942
Greg Clayton02686b82012-10-15 22:42:16 +00002943class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00002944{
2945private:
2946
2947public:
Greg Clayton02686b82012-10-15 22:42:16 +00002948 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00002949 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00002950 "process plugin packet history",
2951 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00002952 NULL)
2953 {
2954 }
2955
Greg Clayton02686b82012-10-15 22:42:16 +00002956 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00002957 {
2958 }
2959
2960 bool
2961 DoExecute (Args& command, CommandReturnObject &result)
2962 {
Greg Clayton02686b82012-10-15 22:42:16 +00002963 const size_t argc = command.GetArgumentCount();
2964 if (argc == 0)
2965 {
2966 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
2967 if (process)
2968 {
2969 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
2970 result.SetStatus (eReturnStatusSuccessFinishResult);
2971 return true;
2972 }
2973 }
2974 else
2975 {
2976 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
2977 }
2978 result.SetStatus (eReturnStatusFailed);
2979 return false;
2980 }
2981};
2982
2983class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
2984{
2985private:
2986
2987public:
2988 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
2989 CommandObjectParsed (interpreter,
2990 "process plugin packet send",
2991 "Send a custom packet through the GDB remote protocol and print the answer. "
2992 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
2993 NULL)
2994 {
2995 }
2996
2997 ~CommandObjectProcessGDBRemotePacketSend ()
2998 {
2999 }
3000
3001 bool
3002 DoExecute (Args& command, CommandReturnObject &result)
3003 {
3004 const size_t argc = command.GetArgumentCount();
3005 if (argc == 0)
3006 {
3007 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3008 result.SetStatus (eReturnStatusFailed);
3009 return false;
3010 }
3011
3012 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3013 if (process)
3014 {
Han Ming Ong84145852012-11-26 20:42:03 +00003015 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003016 {
Han Ming Ong84145852012-11-26 20:42:03 +00003017 const char *packet_cstr = command.GetArgumentAtIndex(0);
3018 bool send_async = true;
3019 StringExtractorGDBRemote response;
3020 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3021 result.SetStatus (eReturnStatusSuccessFinishResult);
3022 Stream &output_strm = result.GetOutputStream();
3023 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003024 std::string &response_str = response.GetStringRef();
3025
Han Ming Ong399289e2013-06-21 19:56:59 +00003026 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003027 {
3028 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3029 }
3030
Han Ming Ong84145852012-11-26 20:42:03 +00003031 if (response_str.empty())
3032 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3033 else
3034 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003035 }
Greg Clayton02686b82012-10-15 22:42:16 +00003036 }
Greg Clayton998255b2012-10-13 02:07:45 +00003037 return true;
3038 }
3039};
3040
Greg Claytonba4a0a52013-02-01 23:03:47 +00003041class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3042{
3043private:
3044
3045public:
3046 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3047 CommandObjectRaw (interpreter,
3048 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003049 "Send a qRcmd packet through the GDB remote protocol and print the response."
3050 "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 +00003051 NULL)
3052 {
3053 }
3054
3055 ~CommandObjectProcessGDBRemotePacketMonitor ()
3056 {
3057 }
3058
3059 bool
3060 DoExecute (const char *command, CommandReturnObject &result)
3061 {
3062 if (command == NULL || command[0] == '\0')
3063 {
3064 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3065 result.SetStatus (eReturnStatusFailed);
3066 return false;
3067 }
3068
3069 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3070 if (process)
3071 {
3072 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003073 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003074 packet.PutBytesAsRawHex8(command, strlen(command));
3075 const char *packet_cstr = packet.GetString().c_str();
3076
3077 bool send_async = true;
3078 StringExtractorGDBRemote response;
3079 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3080 result.SetStatus (eReturnStatusSuccessFinishResult);
3081 Stream &output_strm = result.GetOutputStream();
3082 output_strm.Printf (" packet: %s\n", packet_cstr);
3083 const std::string &response_str = response.GetStringRef();
3084
3085 if (response_str.empty())
3086 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3087 else
3088 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3089 }
3090 return true;
3091 }
3092};
3093
Greg Clayton02686b82012-10-15 22:42:16 +00003094class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3095{
3096private:
3097
3098public:
3099 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3100 CommandObjectMultiword (interpreter,
3101 "process plugin packet",
3102 "Commands that deal with GDB remote packets.",
3103 NULL)
3104 {
3105 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3106 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003107 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003108 }
3109
3110 ~CommandObjectProcessGDBRemotePacket ()
3111 {
3112 }
3113};
Greg Clayton998255b2012-10-13 02:07:45 +00003114
3115class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3116{
3117public:
3118 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3119 CommandObjectMultiword (interpreter,
3120 "process plugin",
3121 "A set of commands for operating on a ProcessGDBRemote process.",
3122 "process plugin <subcommand> [<subcommand-options>]")
3123 {
3124 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3125 }
3126
3127 ~CommandObjectMultiwordProcessGDBRemote ()
3128 {
3129 }
3130};
3131
Greg Clayton998255b2012-10-13 02:07:45 +00003132CommandObject *
3133ProcessGDBRemote::GetPluginCommandObject()
3134{
3135 if (!m_command_sp)
3136 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3137 return m_command_sp.get();
3138}