blob: 3c5525d4ba752925360e0ab912cfb2baca73b508 [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 Clayton3dedae12013-12-06 21:45:27 +0000361 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
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 Clayton3dedae12013-12-06 21:45:27 +0000620 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Claytonb766a732011-02-04 01:58:07 +0000621 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000622 if (!m_target.GetArchitecture().IsValid())
623 {
624 if (m_gdb_comm.GetProcessArchitecture().IsValid())
625 {
626 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
627 }
628 else
629 {
630 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
631 }
Carlo Kok74389122013-10-14 07:09:13 +0000632 }
633
Greg Claytondd0e5a52011-06-02 22:22:38 +0000634 const StateType state = SetThreadStopInfo (m_last_stop_packet);
Greg Claytonb766a732011-02-04 01:58:07 +0000635 if (state == eStateStopped)
636 {
637 SetPrivateState (state);
638 }
639 else
Daniel Malead01b2952012-11-29 21:49:15 +0000640 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 +0000641 }
642 else
Daniel Malead01b2952012-11-29 21:49:15 +0000643 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 +0000644 }
Jason Molenda16d127c2012-05-03 22:37:30 +0000645
646 if (error.Success()
647 && !GetTarget().GetArchitecture().IsValid()
648 && m_gdb_comm.GetHostArchitecture().IsValid())
649 {
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000650 // Prefer the *process'* architecture over that of the *host*, if available.
651 if (m_gdb_comm.GetProcessArchitecture().IsValid())
652 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
653 else
654 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
Jason Molenda16d127c2012-05-03 22:37:30 +0000655 }
656
Greg Claytonb766a732011-02-04 01:58:07 +0000657 return error;
658}
659
660Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661ProcessGDBRemote::WillLaunchOrAttach ()
662{
663 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 m_stdio_communication.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 return error;
666}
667
668//----------------------------------------------------------------------
669// Process Control
670//----------------------------------------------------------------------
671Error
Jean-Daniel Dupas7782de92013-12-09 22:52:50 +0000672ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673{
Greg Clayton4957bf62010-09-30 21:49:03 +0000674 Error error;
Greg Clayton982c9762011-11-03 21:22:33 +0000675
676 uint32_t launch_flags = launch_info.GetFlags().Get();
677 const char *stdin_path = NULL;
678 const char *stdout_path = NULL;
679 const char *stderr_path = NULL;
680 const char *working_dir = launch_info.GetWorkingDirectory();
681
682 const ProcessLaunchInfo::FileAction *file_action;
683 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
684 if (file_action)
685 {
686 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
687 stdin_path = file_action->GetPath();
688 }
689 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
690 if (file_action)
691 {
692 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
693 stdout_path = file_action->GetPath();
694 }
695 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
696 if (file_action)
697 {
698 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
699 stderr_path = file_action->GetPath();
700 }
701
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
703 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
704 // ::LogSetLogFile ("/dev/stdout");
Greg Clayton5160ce52013-03-27 23:08:40 +0000705 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706
Greg Clayton982c9762011-11-03 21:22:33 +0000707 ObjectFile * object_file = exe_module->GetObjectFile();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 if (object_file)
709 {
Greg Clayton71337622011-02-24 22:24:29 +0000710 // Make sure we aren't already connected?
711 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000713 error = LaunchAndConnectToDebugserver (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000714 }
715
716 if (error.Success())
717 {
718 lldb_utility::PseudoTerminal pty;
719 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000720
721 // If the debugserver is local and we aren't disabling STDIO, lets use
722 // a pseudo terminal to instead of relying on the 'O' packets for stdio
723 // since 'O' packets can really slow down debugging if the inferior
724 // does a lot of output.
Greg Claytonf58c2692011-06-24 22:32:10 +0000725 PlatformSP platform_sp (m_target.GetPlatform());
726 if (platform_sp && platform_sp->IsHost() && !disable_stdio)
Greg Clayton71337622011-02-24 22:24:29 +0000727 {
728 const char *slave_name = NULL;
729 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 {
Greg Clayton71337622011-02-24 22:24:29 +0000731 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
732 slave_name = pty.GetSlaveName (NULL, 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 }
Greg Clayton71337622011-02-24 22:24:29 +0000734 if (stdin_path == NULL)
735 stdin_path = slave_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736
Greg Clayton71337622011-02-24 22:24:29 +0000737 if (stdout_path == NULL)
738 stdout_path = slave_name;
739
740 if (stderr_path == NULL)
741 stderr_path = slave_name;
742 }
743
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000744 // Set STDIN to /dev/null if we want STDIO disabled or if either
745 // STDOUT or STDERR have been set to something and STDIN hasn't
746 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000747 stdin_path = "/dev/null";
748
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000749 // Set STDOUT to /dev/null if we want STDIO disabled or if either
750 // STDIN or STDERR have been set to something and STDOUT hasn't
751 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000752 stdout_path = "/dev/null";
753
Greg Clayton5f2a4f92011-03-02 21:34:46 +0000754 // Set STDERR to /dev/null if we want STDIO disabled or if either
755 // STDIN or STDOUT have been set to something and STDERR hasn't
756 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path)))
Greg Clayton71337622011-02-24 22:24:29 +0000757 stderr_path = "/dev/null";
758
759 if (stdin_path)
760 m_gdb_comm.SetSTDIN (stdin_path);
761 if (stdout_path)
762 m_gdb_comm.SetSTDOUT (stdout_path);
763 if (stderr_path)
764 m_gdb_comm.SetSTDERR (stderr_path);
765
766 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
767
Greg Claytonc4103b32011-05-08 04:53:50 +0000768 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
Greg Clayton71337622011-02-24 22:24:29 +0000769
770 if (working_dir && working_dir[0])
771 {
772 m_gdb_comm.SetWorkingDir (working_dir);
773 }
774
775 // Send the environment and the program + arguments after we connect
Greg Clayton982c9762011-11-03 21:22:33 +0000776 const Args &environment = launch_info.GetEnvironmentEntries();
777 if (environment.GetArgumentCount())
Greg Clayton71337622011-02-24 22:24:29 +0000778 {
Greg Clayton982c9762011-11-03 21:22:33 +0000779 size_t num_environment_entries = environment.GetArgumentCount();
780 for (size_t i=0; i<num_environment_entries; ++i)
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000781 {
Greg Clayton982c9762011-11-03 21:22:33 +0000782 const char *env_entry = environment.GetArgumentAtIndex(i);
783 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
Greg Clayton71337622011-02-24 22:24:29 +0000784 break;
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000785 }
Greg Clayton71337622011-02-24 22:24:29 +0000786 }
Greg Claytonb0b9fe62010-08-03 00:35:52 +0000787
Greg Claytonc574ede2011-03-10 02:26:48 +0000788 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10);
Greg Claytonfbb76342013-11-20 21:07:01 +0000789 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
Greg Clayton71337622011-02-24 22:24:29 +0000790 if (arg_packet_err == 0)
791 {
792 std::string error_str;
Greg Claytonc574ede2011-03-10 02:26:48 +0000793 if (m_gdb_comm.GetLaunchSuccess (error_str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000795 SetID (m_gdb_comm.GetCurrentProcessID ());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796 }
797 else
798 {
Greg Clayton71337622011-02-24 22:24:29 +0000799 error.SetErrorString (error_str.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800 }
Greg Clayton71337622011-02-24 22:24:29 +0000801 }
802 else
803 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000804 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
Greg Clayton71337622011-02-24 22:24:29 +0000805 }
Greg Clayton8b45bee2011-08-10 22:05:39 +0000806
807 m_gdb_comm.SetPacketTimeout (old_packet_timeout);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808
Greg Clayton71337622011-02-24 22:24:29 +0000809 if (GetID() == LLDB_INVALID_PROCESS_ID)
810 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000811 if (log)
812 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Clayton71337622011-02-24 22:24:29 +0000813 KillDebugserverProcess ();
814 return error;
815 }
816
Greg Clayton3dedae12013-12-06 21:45:27 +0000817 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton71337622011-02-24 22:24:29 +0000818 {
Jason Molendac62bd7b2013-12-21 05:20:36 +0000819 if (!m_target.GetArchitecture().IsValid())
820 {
821 if (m_gdb_comm.GetProcessArchitecture().IsValid())
822 {
823 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
824 }
825 else
826 {
827 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
828 }
Carlo Kok74389122013-10-14 07:09:13 +0000829 }
830
Greg Claytondd0e5a52011-06-02 22:22:38 +0000831 SetPrivateState (SetThreadStopInfo (m_last_stop_packet));
Greg Clayton71337622011-02-24 22:24:29 +0000832
833 if (!disable_stdio)
834 {
835 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
Greg Claytonee95ed52011-11-17 22:14:31 +0000836 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
Greg Clayton71337622011-02-24 22:24:29 +0000837 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838 }
839 }
Greg Claytonc235ac72011-08-09 05:20:29 +0000840 else
841 {
Johnny Chen4c1e9202011-08-09 18:56:45 +0000842 if (log)
843 log->Printf("failed to connect to debugserver: %s", error.AsCString());
Greg Claytonc235ac72011-08-09 05:20:29 +0000844 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845 }
846 else
847 {
848 // Set our user ID to an invalid process ID.
849 SetID(LLDB_INVALID_PROCESS_ID);
Greg Clayton982c9762011-11-03 21:22:33 +0000850 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
851 exe_module->GetFileSpec().GetFilename().AsCString(),
852 exe_module->GetArchitecture().GetArchitectureName());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854 return error;
Greg Clayton4957bf62010-09-30 21:49:03 +0000855
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000856}
857
858
859Error
Greg Claytonb766a732011-02-04 01:58:07 +0000860ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861{
862 Error error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000863 // Only connect if we have a valid connect URL
864
865 if (connect_url && connect_url[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000867 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
868 if (conn_ap.get())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000869 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000870 const uint32_t max_retry_count = 50;
871 uint32_t retry_count = 0;
872 while (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000874 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
875 {
876 m_gdb_comm.SetConnection (conn_ap.release());
877 break;
878 }
879 else if (error.WasInterrupted())
880 {
881 // If we were interrupted, don't keep retrying.
882 break;
883 }
884
885 retry_count++;
886
887 if (retry_count >= max_retry_count)
888 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889
Greg Clayton00fe87b2013-12-05 22:58:22 +0000890 usleep (100000);
891 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892 }
893 }
894
895 if (!m_gdb_comm.IsConnected())
896 {
897 if (error.Success())
898 error.SetErrorString("not connected to remote gdb server");
899 return error;
900 }
901
Greg Clayton32e0a752011-03-30 18:16:51 +0000902 // We always seem to be able to open a connection to a local port
903 // so we need to make sure we can then send data to it. If we can't
904 // then we aren't actually connected to anything, so try and do the
905 // handshake with the remote GDB server and make sure that goes
906 // alright.
Greg Claytonfb909312013-11-23 01:58:15 +0000907 if (!m_gdb_comm.HandshakeWithServer (&error))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908 {
Greg Clayton32e0a752011-03-30 18:16:51 +0000909 m_gdb_comm.Disconnect();
910 if (error.Success())
911 error.SetErrorString("not connected to remote gdb server");
912 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000913 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000914 m_gdb_comm.GetThreadSuffixSupported ();
Greg Clayton44633992012-04-10 03:22:03 +0000915 m_gdb_comm.GetListThreadsInStopReplySupported ();
Greg Clayton32e0a752011-03-30 18:16:51 +0000916 m_gdb_comm.GetHostInfo ();
917 m_gdb_comm.GetVContSupported ('c');
Jim Inghamcd16df92012-07-20 21:37:13 +0000918 m_gdb_comm.GetVAttachOrWaitSupported();
Jim Ingham03afad82012-07-02 05:40:07 +0000919
920 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
921 for (size_t idx = 0; idx < num_cmds; idx++)
922 {
923 StringExtractorGDBRemote response;
Jim Ingham03afad82012-07-02 05:40:07 +0000924 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
925 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000926 return error;
927}
928
929void
930ProcessGDBRemote::DidLaunchOrAttach ()
931{
Greg Clayton5160ce52013-03-27 23:08:40 +0000932 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +0000933 if (log)
934 log->Printf ("ProcessGDBRemote::DidLaunch()");
Greg Clayton93d3c8332011-02-16 04:46:07 +0000935 if (GetID() != LLDB_INVALID_PROCESS_ID)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936 {
Greg Clayton513c26c2011-01-29 07:10:55 +0000937 BuildDynamicRegisterInfo (false);
Greg Clayton3af9ea52010-11-18 05:57:03 +0000938
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939 // See if the GDB server supports the qHostInfo information
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000940
Jason Molendaf17b5ac2012-12-19 02:54:03 +0000941 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture();
942
943 // See if the GDB server supports the qProcessInfo packet, if so
944 // prefer that over the Host information as it will be more specific
945 // to our process.
946
947 if (m_gdb_comm.GetProcessArchitecture().IsValid())
948 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture();
949
Greg Claytond314e812011-03-23 00:09:55 +0000950 if (gdb_remote_arch.IsValid())
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000951 {
Greg Claytond314e812011-03-23 00:09:55 +0000952 ArchSpec &target_arch = GetTarget().GetArchitecture();
953
954 if (target_arch.IsValid())
955 {
956 // If the remote host is ARM and we have apple as the vendor, then
957 // ARM executables and shared libraries can have mixed ARM architectures.
958 // You can have an armv6 executable, and if the host is armv7, then the
959 // system will load the best possible architecture for all shared libraries
960 // it has, so we really need to take the remote host architecture as our
961 // defacto architecture in this case.
962
963 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm &&
964 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
965 {
966 target_arch = gdb_remote_arch;
967 }
968 else
969 {
970 // Fill in what is missing in the triple
971 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple();
972 llvm::Triple &target_triple = target_arch.GetTriple();
Greg Clayton70b57652011-05-15 01:25:55 +0000973 if (target_triple.getVendorName().size() == 0)
974 {
Greg Claytond314e812011-03-23 00:09:55 +0000975 target_triple.setVendor (remote_triple.getVendor());
976
Greg Clayton70b57652011-05-15 01:25:55 +0000977 if (target_triple.getOSName().size() == 0)
978 {
979 target_triple.setOS (remote_triple.getOS());
Greg Claytond314e812011-03-23 00:09:55 +0000980
Greg Clayton70b57652011-05-15 01:25:55 +0000981 if (target_triple.getEnvironmentName().size() == 0)
982 target_triple.setEnvironment (remote_triple.getEnvironment());
983 }
984 }
Greg Claytond314e812011-03-23 00:09:55 +0000985 }
986 }
987 else
988 {
989 // The target doesn't have a valid architecture yet, set it from
990 // the architecture we got from the remote GDB server
991 target_arch = gdb_remote_arch;
992 }
Greg Clayton0d0c12a2011-02-09 03:09:55 +0000993 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994 }
995}
996
997void
998ProcessGDBRemote::DidLaunch ()
999{
1000 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001}
1002
1003Error
Greg Claytonc982c762010-07-09 20:39:50 +00001004ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005{
Han Ming Ong84647042012-02-25 01:07:38 +00001006 ProcessAttachInfo attach_info;
1007 return DoAttachToProcessWithID(attach_pid, attach_info);
1008}
1009
1010Error
1011ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1012{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013 Error error;
1014 // Clear out and clean up from any current state
1015 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1017 {
Greg Clayton71337622011-02-24 22:24:29 +00001018 // Make sure we aren't already connected?
1019 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001021 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001022
1023 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024 {
Greg Clayton71337622011-02-24 22:24:29 +00001025 const char *error_string = error.AsCString();
1026 if (error_string == NULL)
1027 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1028
1029 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001030 }
Greg Clayton71337622011-02-24 22:24:29 +00001031 }
1032
1033 if (error.Success())
1034 {
1035 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00001036 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
Greg Clayton3b608422011-11-19 02:11:30 +00001037 SetID (attach_pid);
Greg Clayton71337622011-02-24 22:24:29 +00001038 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039 }
1040 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001041 return error;
1042}
1043
1044size_t
1045ProcessGDBRemote::AttachInputReaderCallback
1046(
1047 void *baton,
1048 InputReader *reader,
1049 lldb::InputReaderAction notification,
1050 const char *bytes,
1051 size_t bytes_len
1052)
1053{
1054 if (notification == eInputReaderGotToken)
1055 {
1056 ProcessGDBRemote *gdb_process = (ProcessGDBRemote *)baton;
1057 if (gdb_process->m_waiting_for_attach)
1058 gdb_process->m_waiting_for_attach = false;
1059 reader->SetIsDone(true);
1060 return 1;
1061 }
1062 return 0;
1063}
1064
1065Error
Han Ming Ong84647042012-02-25 01:07:38 +00001066ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, bool wait_for_launch, const ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067{
1068 Error error;
1069 // Clear out and clean up from any current state
1070 Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072 if (process_name && process_name[0])
1073 {
Greg Clayton71337622011-02-24 22:24:29 +00001074 // Make sure we aren't already connected?
1075 if (!m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076 {
Greg Clayton91a9b2472013-12-04 19:19:12 +00001077 error = LaunchAndConnectToDebugserver (attach_info);
Greg Clayton71337622011-02-24 22:24:29 +00001078
Greg Clayton71337622011-02-24 22:24:29 +00001079 if (error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080 {
Greg Clayton71337622011-02-24 22:24:29 +00001081 const char *error_string = error.AsCString();
1082 if (error_string == NULL)
1083 error_string = "unable to launch " DEBUGSERVER_BASENAME;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084
Greg Clayton71337622011-02-24 22:24:29 +00001085 SetExitStatus (-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 }
Greg Clayton71337622011-02-24 22:24:29 +00001087 }
1088
1089 if (error.Success())
1090 {
1091 StreamString packet;
1092
1093 if (wait_for_launch)
Jim Inghamcd16df92012-07-20 21:37:13 +00001094 {
1095 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1096 {
1097 packet.PutCString ("vAttachWait");
1098 }
1099 else
1100 {
1101 if (attach_info.GetIgnoreExisting())
1102 packet.PutCString("vAttachWait");
1103 else
1104 packet.PutCString ("vAttachOrWait");
1105 }
1106 }
Greg Clayton71337622011-02-24 22:24:29 +00001107 else
1108 packet.PutCString("vAttachName");
1109 packet.PutChar(';');
1110 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1111
1112 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1113
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114 }
1115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 return error;
1117}
1118
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119
Greg Claytonfbb76342013-11-20 21:07:01 +00001120bool
1121ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr)
1122{
1123 m_gdb_comm.Disconnect();
1124 return Process::SetExitStatus (exit_status, cstr);
1125}
1126
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127void
1128ProcessGDBRemote::DidAttach ()
1129{
Greg Claytonb766a732011-02-04 01:58:07 +00001130 DidLaunchOrAttach ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131}
1132
Greg Clayton90ba8112012-12-05 00:16:59 +00001133
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134Error
1135ProcessGDBRemote::WillResume ()
1136{
Greg Clayton71fc2a32011-02-12 06:28:37 +00001137 m_continue_c_tids.clear();
1138 m_continue_C_tids.clear();
1139 m_continue_s_tids.clear();
1140 m_continue_S_tids.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 return Error();
1142}
1143
1144Error
1145ProcessGDBRemote::DoResume ()
1146{
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001147 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001148 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Greg Clayton6d093452011-02-05 02:25:06 +00001149 if (log)
1150 log->Printf ("ProcessGDBRemote::Resume()");
Greg Claytone5219662010-12-03 06:02:24 +00001151
1152 Listener listener ("gdb-remote.resume-packet-sent");
1153 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1154 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00001155 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1156
Greg Claytond1d06e42013-04-20 00:27:58 +00001157 const size_t num_threads = GetThreadList().GetSize();
1158
Greg Clayton71fc2a32011-02-12 06:28:37 +00001159 StreamString continue_packet;
1160 bool continue_packet_error = false;
1161 if (m_gdb_comm.HasAnyVContSupport ())
1162 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001163 if (m_continue_c_tids.size() == num_threads)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001164 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001165 // All threads are continuing, just send a "c" packet
1166 continue_packet.PutCString ("c");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001167 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001168 else
1169 {
1170 continue_packet.PutCString ("vCont");
Greg Clayton71fc2a32011-02-12 06:28:37 +00001171
Greg Claytond1d06e42013-04-20 00:27:58 +00001172 if (!m_continue_c_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001173 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001174 if (m_gdb_comm.GetVContSupported ('c'))
1175 {
1176 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)
1177 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1178 }
1179 else
1180 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001181 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001182
1183 if (!continue_packet_error && !m_continue_C_tids.empty())
1184 {
1185 if (m_gdb_comm.GetVContSupported ('C'))
1186 {
1187 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)
1188 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1189 }
1190 else
1191 continue_packet_error = true;
1192 }
Greg Claytone5219662010-12-03 06:02:24 +00001193
Greg Claytond1d06e42013-04-20 00:27:58 +00001194 if (!continue_packet_error && !m_continue_s_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001195 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001196 if (m_gdb_comm.GetVContSupported ('s'))
1197 {
1198 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)
1199 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1200 }
1201 else
1202 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001203 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001204
1205 if (!continue_packet_error && !m_continue_S_tids.empty())
Greg Clayton71fc2a32011-02-12 06:28:37 +00001206 {
Greg Claytond1d06e42013-04-20 00:27:58 +00001207 if (m_gdb_comm.GetVContSupported ('S'))
1208 {
1209 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)
1210 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1211 }
1212 else
1213 continue_packet_error = true;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001214 }
Greg Claytond1d06e42013-04-20 00:27:58 +00001215
1216 if (continue_packet_error)
1217 continue_packet.GetString().clear();
Greg Clayton71fc2a32011-02-12 06:28:37 +00001218 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001219 }
1220 else
1221 continue_packet_error = true;
1222
1223 if (continue_packet_error)
1224 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001225 // Either no vCont support, or we tried to use part of the vCont
1226 // packet that wasn't supported by the remote GDB server.
1227 // We need to try and make a simple packet that can do our continue
Greg Clayton71fc2a32011-02-12 06:28:37 +00001228 const size_t num_continue_c_tids = m_continue_c_tids.size();
1229 const size_t num_continue_C_tids = m_continue_C_tids.size();
1230 const size_t num_continue_s_tids = m_continue_s_tids.size();
1231 const size_t num_continue_S_tids = m_continue_S_tids.size();
1232 if (num_continue_c_tids > 0)
1233 {
1234 if (num_continue_c_tids == num_threads)
1235 {
1236 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001237 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001238 continue_packet.PutChar ('c');
1239 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001240 }
1241 else if (num_continue_c_tids == 1 &&
1242 num_continue_C_tids == 0 &&
1243 num_continue_s_tids == 0 &&
1244 num_continue_S_tids == 0 )
1245 {
1246 // Only one thread is continuing
Greg Clayton8b82f082011-04-12 05:54:46 +00001247 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001248 continue_packet.PutChar ('c');
Greg Clayton0c74e782011-06-24 03:21:43 +00001249 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001250 }
1251 }
1252
Greg Clayton0c74e782011-06-24 03:21:43 +00001253 if (continue_packet_error && num_continue_C_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001254 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001255 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1256 num_continue_C_tids > 0 &&
1257 num_continue_s_tids == 0 &&
1258 num_continue_S_tids == 0 )
Greg Clayton71fc2a32011-02-12 06:28:37 +00001259 {
1260 const int continue_signo = m_continue_C_tids.front().second;
Greg Clayton0c74e782011-06-24 03:21:43 +00001261 // Only one thread is continuing
Greg Clayton71fc2a32011-02-12 06:28:37 +00001262 if (num_continue_C_tids > 1)
1263 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001264 // More that one thread with a signal, yet we don't have
1265 // vCont support and we are being asked to resume each
1266 // thread with a signal, we need to make sure they are
1267 // all the same signal, or we can't issue the continue
1268 // accurately with the current support...
1269 if (num_continue_C_tids > 1)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001270 {
Greg Clayton0c74e782011-06-24 03:21:43 +00001271 continue_packet_error = false;
1272 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1273 {
1274 if (m_continue_C_tids[i].second != continue_signo)
1275 continue_packet_error = true;
1276 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001277 }
Greg Clayton0c74e782011-06-24 03:21:43 +00001278 if (!continue_packet_error)
1279 m_gdb_comm.SetCurrentThreadForRun (-1);
1280 }
1281 else
1282 {
1283 // Set the continue thread ID
1284 continue_packet_error = false;
1285 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001286 }
1287 if (!continue_packet_error)
1288 {
1289 // Add threads continuing with the same signo...
Greg Clayton71fc2a32011-02-12 06:28:37 +00001290 continue_packet.Printf("C%2.2x", continue_signo);
1291 }
1292 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001293 }
1294
Greg Clayton0c74e782011-06-24 03:21:43 +00001295 if (continue_packet_error && num_continue_s_tids > 0)
Greg Clayton71fc2a32011-02-12 06:28:37 +00001296 {
1297 if (num_continue_s_tids == num_threads)
1298 {
1299 // All threads are resuming...
Greg Clayton8b82f082011-04-12 05:54:46 +00001300 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton0c74e782011-06-24 03:21:43 +00001301 continue_packet.PutChar ('s');
1302 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001303 }
1304 else if (num_continue_c_tids == 0 &&
1305 num_continue_C_tids == 0 &&
1306 num_continue_s_tids == 1 &&
1307 num_continue_S_tids == 0 )
1308 {
1309 // Only one thread is stepping
Greg Clayton8b82f082011-04-12 05:54:46 +00001310 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
Greg Clayton71fc2a32011-02-12 06:28:37 +00001311 continue_packet.PutChar ('s');
Greg Clayton0c74e782011-06-24 03:21:43 +00001312 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001313 }
1314 }
1315
1316 if (!continue_packet_error && num_continue_S_tids > 0)
1317 {
1318 if (num_continue_S_tids == num_threads)
1319 {
1320 const int step_signo = m_continue_S_tids.front().second;
1321 // Are all threads trying to step with the same signal?
Greg Clayton0c74e782011-06-24 03:21:43 +00001322 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001323 if (num_continue_S_tids > 1)
1324 {
1325 for (size_t i=1; i<num_threads; ++i)
1326 {
1327 if (m_continue_S_tids[i].second != step_signo)
1328 continue_packet_error = true;
1329 }
1330 }
1331 if (!continue_packet_error)
1332 {
1333 // Add threads stepping with the same signo...
Greg Clayton8b82f082011-04-12 05:54:46 +00001334 m_gdb_comm.SetCurrentThreadForRun (-1);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001335 continue_packet.Printf("S%2.2x", step_signo);
1336 }
1337 }
1338 else if (num_continue_c_tids == 0 &&
1339 num_continue_C_tids == 0 &&
1340 num_continue_s_tids == 0 &&
1341 num_continue_S_tids == 1 )
1342 {
1343 // Only one thread is stepping with signal
Greg Clayton8b82f082011-04-12 05:54:46 +00001344 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
Greg Clayton71fc2a32011-02-12 06:28:37 +00001345 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
Greg Clayton0c74e782011-06-24 03:21:43 +00001346 continue_packet_error = false;
Greg Clayton71fc2a32011-02-12 06:28:37 +00001347 }
1348 }
1349 }
1350
1351 if (continue_packet_error)
1352 {
1353 error.SetErrorString ("can't make continue packet for this resume");
1354 }
1355 else
1356 {
1357 EventSP event_sp;
1358 TimeValue timeout;
1359 timeout = TimeValue::Now();
1360 timeout.OffsetWithSeconds (5);
Jim Inghamb1e2e842012-04-12 18:49:31 +00001361 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread))
1362 {
1363 error.SetErrorString ("Trying to resume but the async thread is dead.");
1364 if (log)
1365 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1366 return error;
1367 }
1368
Greg Clayton71fc2a32011-02-12 06:28:37 +00001369 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1370
1371 if (listener.WaitForEvent (&timeout, event_sp) == false)
Jim Inghamb1e2e842012-04-12 18:49:31 +00001372 {
Greg Clayton71fc2a32011-02-12 06:28:37 +00001373 error.SetErrorString("Resume timed out.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00001374 if (log)
1375 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1376 }
1377 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1378 {
1379 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1380 if (log)
1381 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1382 return error;
1383 }
Greg Clayton71fc2a32011-02-12 06:28:37 +00001384 }
Greg Claytone5219662010-12-03 06:02:24 +00001385 }
1386
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001387 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388}
1389
Greg Clayton9e920902012-04-10 02:25:43 +00001390void
1391ProcessGDBRemote::ClearThreadIDList ()
1392{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001393 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001394 m_thread_ids.clear();
1395}
1396
1397bool
1398ProcessGDBRemote::UpdateThreadIDList ()
1399{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001400 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001401 bool sequence_mutex_unavailable = false;
1402 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1403 if (sequence_mutex_unavailable)
1404 {
Greg Clayton9e920902012-04-10 02:25:43 +00001405 return false; // We just didn't get the list
1406 }
1407 return true;
1408}
1409
Greg Clayton9fc13552012-04-10 00:18:59 +00001410bool
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001411ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001412{
1413 // locker will keep a mutex locked until it goes out of scope
Greg Clayton5160ce52013-03-27 23:08:40 +00001414 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
Greg Clayton73b472d2010-10-27 03:32:59 +00001415 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
Daniel Malead01b2952012-11-29 21:49:15 +00001416 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Greg Clayton9e920902012-04-10 02:25:43 +00001417
1418 size_t num_thread_ids = m_thread_ids.size();
1419 // The "m_thread_ids" thread ID list should always be updated after each stop
1420 // reply packet, but in case it isn't, update it here.
1421 if (num_thread_ids == 0)
1422 {
1423 if (!UpdateThreadIDList ())
1424 return false;
1425 num_thread_ids = m_thread_ids.size();
1426 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001428 ThreadList old_thread_list_copy(old_thread_list);
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001429 if (num_thread_ids > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430 {
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001431 for (size_t i=0; i<num_thread_ids; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001432 {
Greg Clayton9e920902012-04-10 02:25:43 +00001433 tid_t tid = m_thread_ids[i];
Greg Clayton160c9d82013-05-01 21:54:04 +00001434 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001435 if (!thread_sp)
Jim Inghamdee1bc92013-06-22 00:27:45 +00001436 {
Jim Ingham4f465cf2012-10-10 18:32:14 +00001437 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001438 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1439 log->Printf(
1440 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1441 __FUNCTION__,
1442 thread_sp.get(),
1443 thread_sp->GetID());
1444 }
1445 else
1446 {
1447 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1448 log->Printf(
1449 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1450 __FUNCTION__,
1451 thread_sp.get(),
1452 thread_sp->GetID());
1453 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001454 new_thread_list.AddThread(thread_sp);
Greg Claytonadc00cb2011-05-20 23:38:13 +00001455 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456 }
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001457
1458 // Whatever that is left in old_thread_list_copy are not
1459 // present in new_thread_list. Remove non-existent threads from internal id table.
1460 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1461 for (size_t i=0; i<old_num_thread_ids; i++)
1462 {
1463 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1464 if (old_thread_sp)
1465 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001466 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001467 m_thread_id_to_index_id_map.erase(old_thread_id);
1468 }
1469 }
1470
Greg Clayton9fc13552012-04-10 00:18:59 +00001471 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001472}
1473
1474
1475StateType
1476ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
1477{
Greg Claytondd0e5a52011-06-02 22:22:38 +00001478 stop_packet.SetFilePos (0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001479 const char stop_type = stop_packet.GetChar();
1480 switch (stop_type)
1481 {
1482 case 'T':
1483 case 'S':
1484 {
Greg Clayton15fc2be2013-05-21 01:00:52 +00001485 // This is a bit of a hack, but is is required. If we did exec, we
1486 // need to clear our thread lists and also know to rebuild our dynamic
1487 // register info before we lookup and threads and populate the expedited
1488 // register values so we need to know this right away so we can cleanup
1489 // and update our registers.
Greg Clayton8cda7f02013-05-21 21:55:59 +00001490 const uint32_t stop_id = GetStopID();
1491 if (stop_id == 0)
Greg Claytone576ab22011-02-15 00:19:15 +00001492 {
1493 // Our first stop, make sure we have a process ID, and also make
1494 // sure we know about our registers
1495 if (GetID() == LLDB_INVALID_PROCESS_ID)
1496 {
Greg Claytonc574ede2011-03-10 02:26:48 +00001497 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
Greg Claytone576ab22011-02-15 00:19:15 +00001498 if (pid != LLDB_INVALID_PROCESS_ID)
1499 SetID (pid);
1500 }
1501 BuildDynamicRegisterInfo (true);
1502 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001503 // Stop with signal and thread info
1504 const uint8_t signo = stop_packet.GetHexU8();
1505 std::string name;
1506 std::string value;
1507 std::string thread_name;
Greg Claytona658fd22011-06-04 01:26:29 +00001508 std::string reason;
1509 std::string description;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510 uint32_t exc_type = 0;
Greg Clayton896dff62010-07-23 16:45:51 +00001511 std::vector<addr_t> exc_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001513 ThreadSP thread_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001514 ThreadGDBRemote *gdb_thread = NULL;
Greg Clayton3e06bd92011-01-09 21:07:35 +00001515
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001516 while (stop_packet.GetNameColonValue(name, value))
1517 {
1518 if (name.compare("metype") == 0)
1519 {
1520 // exception type in big endian hex
1521 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16);
1522 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001523 else if (name.compare("medata") == 0)
1524 {
1525 // exception data in big endian hex
1526 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16));
1527 }
1528 else if (name.compare("thread") == 0)
1529 {
1530 // thread in big endian hex
Greg Clayton9e920902012-04-10 02:25:43 +00001531 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001532 // m_thread_list_real does have its own mutex, but we need to
1533 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1534 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1535 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1536 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
Greg Clayton160c9d82013-05-01 21:54:04 +00001537
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001538 if (!thread_sp)
Greg Claytond1d06e42013-04-20 00:27:58 +00001539 {
Greg Claytone576ab22011-02-15 00:19:15 +00001540 // Create the thread if we need to
Jim Ingham4f465cf2012-10-10 18:32:14 +00001541 thread_sp.reset (new ThreadGDBRemote (*this, tid));
Jim Inghamdee1bc92013-06-22 00:27:45 +00001542 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1543 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1544 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1545 __FUNCTION__,
1546 thread_sp.get(),
1547 thread_sp->GetID());
1548
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001549 m_thread_list_real.AddThread(thread_sp);
Greg Claytone576ab22011-02-15 00:19:15 +00001550 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001551 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1552
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001553 }
Greg Clayton9e920902012-04-10 02:25:43 +00001554 else if (name.compare("threads") == 0)
1555 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001556 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001557 m_thread_ids.clear();
Greg Clayton44633992012-04-10 03:22:03 +00001558 // A comma separated list of all threads in the current
1559 // process that includes the thread for this stop reply
1560 // packet
Greg Clayton9e920902012-04-10 02:25:43 +00001561 size_t comma_pos;
1562 lldb::tid_t tid;
1563 while ((comma_pos = value.find(',')) != std::string::npos)
1564 {
1565 value[comma_pos] = '\0';
1566 // thread in big endian hex
1567 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1568 if (tid != LLDB_INVALID_THREAD_ID)
1569 m_thread_ids.push_back (tid);
1570 value.erase(0, comma_pos + 1);
1571
1572 }
1573 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1574 if (tid != LLDB_INVALID_THREAD_ID)
1575 m_thread_ids.push_back (tid);
1576 }
Greg Claytonde9d0492011-01-08 03:17:57 +00001577 else if (name.compare("hexname") == 0)
1578 {
1579 StringExtractor name_extractor;
1580 // Swap "value" over into "name_extractor"
1581 name_extractor.GetStringRef().swap(value);
1582 // Now convert the HEX bytes into a string value
1583 name_extractor.GetHexByteString (value);
1584 thread_name.swap (value);
1585 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001586 else if (name.compare("name") == 0)
1587 {
1588 thread_name.swap (value);
1589 }
Greg Clayton6f35f5c2010-09-09 06:32:46 +00001590 else if (name.compare("qaddr") == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001591 {
1592 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16);
1593 }
Greg Claytona658fd22011-06-04 01:26:29 +00001594 else if (name.compare("reason") == 0)
1595 {
1596 reason.swap(value);
1597 }
1598 else if (name.compare("description") == 0)
1599 {
1600 StringExtractor desc_extractor;
1601 // Swap "value" over into "name_extractor"
1602 desc_extractor.GetStringRef().swap(value);
1603 // Now convert the HEX bytes into a string value
1604 desc_extractor.GetHexByteString (thread_name);
1605 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001606 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1]))
1607 {
1608 // We have a register number that contains an expedited
1609 // register value. Lets supply this register to our thread
1610 // so it won't have to go and read it.
Greg Clayton160c9d82013-05-01 21:54:04 +00001611 if (gdb_thread)
Greg Clayton3e06bd92011-01-09 21:07:35 +00001612 {
1613 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16);
1614
1615 if (reg != UINT32_MAX)
1616 {
1617 StringExtractor reg_value_extractor;
1618 // Swap "value" over into "reg_value_extractor"
1619 reg_value_extractor.GetStringRef().swap(value);
Greg Clayton160c9d82013-05-01 21:54:04 +00001620 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor))
Greg Claytone576ab22011-02-15 00:19:15 +00001621 {
1622 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'",
1623 name.c_str(),
1624 reg,
1625 reg,
1626 reg_value_extractor.GetStringRef().c_str(),
1627 stop_packet.GetStringRef().c_str());
1628 }
Greg Clayton3e06bd92011-01-09 21:07:35 +00001629 }
1630 }
1631 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001633
1634 if (thread_sp)
1635 {
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001636 // Clear the stop info just in case we don't set it to anything
1637 thread_sp->SetStopInfo (StopInfoSP());
1638
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001639 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
Jim Inghamdd2fe7a2011-01-28 02:23:12 +00001640 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001641 if (exc_type != 0)
1642 {
Greg Clayton1a65ae12011-01-25 23:55:37 +00001643 const size_t exc_data_size = exc_data.size();
Greg Claytonf4b47e12010-08-04 01:40:35 +00001644
Greg Clayton160c9d82013-05-01 21:54:04 +00001645 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1646 exc_type,
1647 exc_data_size,
1648 exc_data_size >= 1 ? exc_data[0] : 0,
1649 exc_data_size >= 2 ? exc_data[1] : 0,
1650 exc_data_size >= 3 ? exc_data[2] : 0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001651 }
Greg Claytona658fd22011-06-04 01:26:29 +00001652 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001653 {
Greg Claytona658fd22011-06-04 01:26:29 +00001654 bool handled = false;
Greg Clayton8cda7f02013-05-21 21:55:59 +00001655 bool did_exec = false;
Greg Claytona658fd22011-06-04 01:26:29 +00001656 if (!reason.empty())
1657 {
1658 if (reason.compare("trace") == 0)
1659 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001660 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Greg Claytona658fd22011-06-04 01:26:29 +00001661 handled = true;
1662 }
1663 else if (reason.compare("breakpoint") == 0)
1664 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001665 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1666 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Greg Claytona658fd22011-06-04 01:26:29 +00001667 if (bp_site_sp)
1668 {
1669 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1670 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1671 // 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 +00001672 handled = true;
Greg Clayton160c9d82013-05-01 21:54:04 +00001673 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001674 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001675 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001676 }
1677 else
1678 {
1679 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001680 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001681 }
1682 }
1683
Greg Claytona658fd22011-06-04 01:26:29 +00001684 }
1685 else if (reason.compare("trap") == 0)
1686 {
1687 // Let the trap just use the standard signal stop reason below...
1688 }
1689 else if (reason.compare("watchpoint") == 0)
1690 {
1691 break_id_t watch_id = LLDB_INVALID_WATCH_ID;
1692 // TODO: locate the watchpoint somehow...
Greg Clayton160c9d82013-05-01 21:54:04 +00001693 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id));
Greg Claytona658fd22011-06-04 01:26:29 +00001694 handled = true;
1695 }
1696 else if (reason.compare("exception") == 0)
1697 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001698 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001699 handled = true;
1700 }
Greg Clayton15fc2be2013-05-21 01:00:52 +00001701 else if (reason.compare("exec") == 0)
1702 {
Greg Clayton8cda7f02013-05-21 21:55:59 +00001703 did_exec = true;
Greg Clayton15fc2be2013-05-21 01:00:52 +00001704 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
1705 handled = true;
1706 }
Greg Claytona658fd22011-06-04 01:26:29 +00001707 }
1708
Greg Clayton15fc2be2013-05-21 01:00:52 +00001709 if (signo && did_exec == false)
Greg Claytona658fd22011-06-04 01:26:29 +00001710 {
1711 if (signo == SIGTRAP)
1712 {
1713 // Currently we are going to assume SIGTRAP means we are either
1714 // hitting a breakpoint or hardware single stepping.
Jim Ingham54cc6e42012-07-11 21:41:19 +00001715 handled = true;
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001716 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
Greg Clayton160c9d82013-05-01 21:54:04 +00001717 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
Jim Ingham54cc6e42012-07-11 21:41:19 +00001718
Greg Claytona658fd22011-06-04 01:26:29 +00001719 if (bp_site_sp)
1720 {
1721 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1722 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1723 // 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 +00001724 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
Greg Claytona658fd22011-06-04 01:26:29 +00001725 {
Hafiz Abid Qadeer85a4daf2013-10-18 10:04:33 +00001726 if(m_breakpoint_pc_offset != 0)
1727 thread_sp->GetRegisterContext()->SetPC(pc);
Greg Clayton160c9d82013-05-01 21:54:04 +00001728 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
Jim Ingham54cc6e42012-07-11 21:41:19 +00001729 }
1730 else
1731 {
1732 StopInfoSP invalid_stop_info_sp;
Greg Clayton160c9d82013-05-01 21:54:04 +00001733 thread_sp->SetStopInfo (invalid_stop_info_sp);
Greg Claytona658fd22011-06-04 01:26:29 +00001734 }
1735 }
Jim Ingham54cc6e42012-07-11 21:41:19 +00001736 else
Greg Claytona658fd22011-06-04 01:26:29 +00001737 {
Jim Ingham4dc613b2012-10-27 02:52:04 +00001738 // If we were stepping then assume the stop was the result of the trace. If we were
1739 // not stepping then report the SIGTRAP.
1740 // FIXME: We are still missing the case where we single step over a trap instruction.
Greg Clayton160c9d82013-05-01 21:54:04 +00001741 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1742 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
Jim Ingham4dc613b2012-10-27 02:52:04 +00001743 else
Greg Clayton160c9d82013-05-01 21:54:04 +00001744 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo));
Greg Claytona658fd22011-06-04 01:26:29 +00001745 }
1746 }
1747 if (!handled)
Greg Clayton160c9d82013-05-01 21:54:04 +00001748 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo));
Jason Molenda8214b012013-04-25 01:33:46 +00001749 }
Greg Claytona658fd22011-06-04 01:26:29 +00001750
1751 if (!description.empty())
1752 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001753 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
Greg Claytona658fd22011-06-04 01:26:29 +00001754 if (stop_info_sp)
1755 {
1756 stop_info_sp->SetDescription (description.c_str());
Greg Clayton3418c852011-08-10 02:10:13 +00001757 }
Greg Claytona658fd22011-06-04 01:26:29 +00001758 else
1759 {
Greg Clayton160c9d82013-05-01 21:54:04 +00001760 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
Greg Claytona658fd22011-06-04 01:26:29 +00001761 }
1762 }
1763 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001764 }
1765 return eStateStopped;
1766 }
1767 break;
1768
1769 case 'W':
1770 // process exited
1771 return eStateExited;
1772
1773 default:
1774 break;
1775 }
1776 return eStateInvalid;
1777}
1778
1779void
1780ProcessGDBRemote::RefreshStateAfterStop ()
1781{
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001782 Mutex::Locker locker(m_thread_list_real.GetMutex());
Greg Clayton9e920902012-04-10 02:25:43 +00001783 m_thread_ids.clear();
1784 // Set the thread stop info. It might have a "threads" key whose value is
1785 // a list of all thread IDs in the current process, so m_thread_ids might
1786 // get set.
1787 SetThreadStopInfo (m_last_stop_packet);
1788 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
1789 if (m_thread_ids.empty())
1790 {
1791 // No, we need to fetch the thread list manually
1792 UpdateThreadIDList();
1793 }
1794
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 // Let all threads recover from stopping and do any clean up based
1796 // on the previous thread state (if any).
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001797 m_thread_list_real.RefreshStateAfterStop();
Greg Clayton9e920902012-04-10 02:25:43 +00001798
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001799}
1800
1801Error
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001802ProcessGDBRemote::DoHalt (bool &caused_stop)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803{
1804 Error error;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00001805
Greg Clayton6ed95942011-01-22 07:12:45 +00001806 bool timed_out = false;
1807 Mutex::Locker locker;
Greg Clayton513c26c2011-01-29 07:10:55 +00001808
1809 if (m_public_state.GetValue() == eStateAttaching)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001810 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001811 // We are being asked to halt during an attach. We need to just close
1812 // our file handle and debugserver will go away, and we can be done...
1813 m_gdb_comm.Disconnect();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001814 }
Greg Clayton513c26c2011-01-29 07:10:55 +00001815 else
1816 {
Greg Clayton2687cd12012-03-29 01:55:41 +00001817 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
Greg Clayton513c26c2011-01-29 07:10:55 +00001818 {
1819 if (timed_out)
1820 error.SetErrorString("timed out sending interrupt packet");
1821 else
1822 error.SetErrorString("unknown error sending interrupt packet");
1823 }
Greg Clayton2687cd12012-03-29 01:55:41 +00001824
1825 caused_stop = m_gdb_comm.GetInterruptWasSent ();
Greg Clayton513c26c2011-01-29 07:10:55 +00001826 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001827 return error;
1828}
1829
1830Error
Jim Inghamacff8952013-05-02 00:27:30 +00001831ProcessGDBRemote::DoDetach(bool keep_stopped)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001832{
1833 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001834 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Greg Clayton594e5ed2010-09-27 21:07:38 +00001835 if (log)
Jim Inghamacff8952013-05-02 00:27:30 +00001836 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
1837
Greg Clayton594e5ed2010-09-27 21:07:38 +00001838 DisableAllBreakpointSites ();
1839
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001840 m_thread_list.DiscardThreadPlans();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001841
Jim Inghamacff8952013-05-02 00:27:30 +00001842 error = m_gdb_comm.Detach (keep_stopped);
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001843 if (log)
Greg Clayton594e5ed2010-09-27 21:07:38 +00001844 {
Jim Inghamacff8952013-05-02 00:27:30 +00001845 if (error.Success())
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001846 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
1847 else
Jim Inghamacff8952013-05-02 00:27:30 +00001848 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
Greg Clayton594e5ed2010-09-27 21:07:38 +00001849 }
Jim Inghamacff8952013-05-02 00:27:30 +00001850
1851 if (!error.Success())
1852 return error;
1853
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001854 // Sleep for one second to let the process get all detached...
Greg Clayton594e5ed2010-09-27 21:07:38 +00001855 StopAsyncThread ();
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001856
Greg Clayton58d1c9a2010-10-18 04:14:23 +00001857 SetPrivateState (eStateDetached);
1858 ResumePrivateStateThread();
1859
1860 //KillDebugserverProcess ();
Greg Clayton594e5ed2010-09-27 21:07:38 +00001861 return error;
1862}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001863
Jim Ingham43c555d2012-07-04 00:35:43 +00001864
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865Error
1866ProcessGDBRemote::DoDestroy ()
1867{
1868 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00001869 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001870 if (log)
1871 log->Printf ("ProcessGDBRemote::DoDestroy()");
1872
Jim Ingham43c555d2012-07-04 00:35:43 +00001873 // There is a bug in older iOS debugservers where they don't shut down the process
1874 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
1875 // this can cause problems with restarting. So we check to see if any of our threads are stopped
1876 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
1877 // destroy it again.
1878 //
1879 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
1880 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
1881 // the debugservers with this bug are equal. There really should be a better way to test this!
1882 //
1883 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
1884 // get called here to destroy again and we're still at a breakpoint or exception, then we should
1885 // just do the straight-forward kill.
1886 //
1887 // And of course, if we weren't able to stop the process by the time we get here, it isn't
1888 // necessary (or helpful) to do any of this.
1889
1890 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
1891 {
1892 PlatformSP platform_sp = GetTarget().GetPlatform();
1893
1894 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
1895 if (platform_sp
1896 && platform_sp->GetName()
Greg Clayton57abc5d2013-05-10 21:47:16 +00001897 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
Jim Ingham43c555d2012-07-04 00:35:43 +00001898 {
1899 if (m_destroy_tried_resuming)
1900 {
1901 if (log)
1902 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again.");
1903 }
1904 else
1905 {
1906 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
1907 // but we really need it to happen here and it doesn't matter if we do it twice.
1908 m_thread_list.DiscardThreadPlans();
1909 DisableAllBreakpointSites();
1910
1911 bool stop_looks_like_crash = false;
1912 ThreadList &threads = GetThreadList();
1913
1914 {
Jim Ingham45350372012-09-11 00:08:52 +00001915 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001916
1917 size_t num_threads = threads.GetSize();
1918 for (size_t i = 0; i < num_threads; i++)
1919 {
1920 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001921 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001922 StopReason reason = eStopReasonInvalid;
1923 if (stop_info_sp)
1924 reason = stop_info_sp->GetStopReason();
1925 if (reason == eStopReasonBreakpoint
1926 || reason == eStopReasonException)
1927 {
1928 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001929 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
1930 thread_sp->GetProtocolID(),
Jim Ingham43c555d2012-07-04 00:35:43 +00001931 stop_info_sp->GetDescription());
1932 stop_looks_like_crash = true;
1933 break;
1934 }
1935 }
1936 }
1937
1938 if (stop_looks_like_crash)
1939 {
1940 if (log)
1941 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
1942 m_destroy_tried_resuming = true;
1943
1944 // If we are going to run again before killing, it would be good to suspend all the threads
1945 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
1946 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
1947 // have to run the risk of letting those threads proceed a bit.
1948
1949 {
Jim Ingham45350372012-09-11 00:08:52 +00001950 Mutex::Locker locker(threads.GetMutex());
Jim Ingham43c555d2012-07-04 00:35:43 +00001951
1952 size_t num_threads = threads.GetSize();
1953 for (size_t i = 0; i < num_threads; i++)
1954 {
1955 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
Greg Clayton6e0ff1a2013-05-09 01:55:29 +00001956 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
Jim Ingham43c555d2012-07-04 00:35:43 +00001957 StopReason reason = eStopReasonInvalid;
1958 if (stop_info_sp)
1959 reason = stop_info_sp->GetStopReason();
1960 if (reason != eStopReasonBreakpoint
1961 && reason != eStopReasonException)
1962 {
1963 if (log)
Greg Clayton160c9d82013-05-01 21:54:04 +00001964 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
1965 thread_sp->GetProtocolID());
Jim Ingham43c555d2012-07-04 00:35:43 +00001966 thread_sp->SetResumeState(eStateSuspended);
1967 }
1968 }
1969 }
1970 Resume ();
1971 return Destroy();
1972 }
1973 }
1974 }
1975 }
1976
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977 // Interrupt if our inferior is running...
Jim Inghambabfc382012-06-06 00:32:39 +00001978 int exit_status = SIGABRT;
1979 std::string exit_string;
1980
Greg Clayton6ed95942011-01-22 07:12:45 +00001981 if (m_gdb_comm.IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982 {
Jim Inghamaab78372011-10-28 01:11:35 +00001983 if (m_public_state.GetValue() != eStateAttaching)
Greg Clayton6779606a2011-01-22 23:43:18 +00001984 {
Greg Clayton513c26c2011-01-29 07:10:55 +00001985
1986 StringExtractorGDBRemote response;
1987 bool send_async = true;
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00001988 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3);
1989
Greg Clayton3dedae12013-12-06 21:45:27 +00001990 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
Greg Clayton513c26c2011-01-29 07:10:55 +00001991 {
1992 char packet_cmd = response.GetChar(0);
1993
1994 if (packet_cmd == 'W' || packet_cmd == 'X')
1995 {
Greg Clayton09c3e3d2011-12-06 04:51:14 +00001996 SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00001997 ClearThreadIDList ();
Jim Inghambabfc382012-06-06 00:32:39 +00001998 exit_status = response.GetHexU8();
1999 }
2000 else
2001 {
2002 if (log)
2003 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2004 exit_string.assign("got unexpected response to k packet: ");
2005 exit_string.append(response.GetStringRef());
Greg Clayton513c26c2011-01-29 07:10:55 +00002006 }
2007 }
2008 else
2009 {
Jim Inghambabfc382012-06-06 00:32:39 +00002010 if (log)
2011 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2012 exit_string.assign("failed to send the k packet");
Greg Clayton513c26c2011-01-29 07:10:55 +00002013 }
Filipe Cabecinhas9e106052012-08-22 13:25:58 +00002014
2015 m_gdb_comm.SetPacketTimeout(old_packet_timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002016 }
Jim Inghambabfc382012-06-06 00:32:39 +00002017 else
2018 {
2019 if (log)
2020 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
Jim Inghamcfc09352012-07-27 23:57:19 +00002021 exit_string.assign ("killed or interrupted while attaching.");
Jim Inghambabfc382012-06-06 00:32:39 +00002022 }
Greg Clayton6779606a2011-01-22 23:43:18 +00002023 }
Jim Inghambabfc382012-06-06 00:32:39 +00002024 else
2025 {
2026 // If we missed setting the exit status on the way out, do it here.
2027 // NB set exit status can be called multiple times, the first one sets the status.
2028 exit_string.assign("destroying when not connected to debugserver");
2029 }
2030
2031 SetExitStatus(exit_status, exit_string.c_str());
2032
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002033 StopAsyncThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002034 KillDebugserverProcess ();
2035 return error;
2036}
2037
Greg Clayton8cda7f02013-05-21 21:55:59 +00002038void
2039ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2040{
2041 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex);
2042 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2043 if (did_exec)
2044 {
2045 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2046 if (log)
2047 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2048
2049 m_thread_list_real.Clear();
2050 m_thread_list.Clear();
2051 BuildDynamicRegisterInfo (true);
2052 m_gdb_comm.ResetDiscoverableSettings();
2053 }
2054 m_last_stop_packet = response;
2055}
2056
2057
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002058//------------------------------------------------------------------
2059// Process Queries
2060//------------------------------------------------------------------
2061
2062bool
2063ProcessGDBRemote::IsAlive ()
2064{
Greg Clayton10177aa2010-12-08 05:08:21 +00002065 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066}
2067
2068addr_t
2069ProcessGDBRemote::GetImageInfoAddress()
2070{
Jason Molenda6ba6d3d2013-01-30 04:39:32 +00002071 return m_gdb_comm.GetShlibInfoAddr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002072}
2073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074//------------------------------------------------------------------
2075// Process Memory
2076//------------------------------------------------------------------
2077size_t
2078ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2079{
2080 if (size > m_max_memory_size)
2081 {
2082 // Keep memory read sizes down to a sane limit. This function will be
2083 // called multiple times in order to complete the task by
2084 // lldb_private::Process so it is ok to do this.
2085 size = m_max_memory_size;
2086 }
2087
2088 char packet[64];
Daniel Malead01b2952012-11-29 21:49:15 +00002089 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
Andy Gibbsa297a972013-06-19 19:04:53 +00002090 assert (packet_len + 1 < (int)sizeof(packet));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002091 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002092 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002093 {
Greg Clayton576d8832011-03-22 04:00:09 +00002094 if (response.IsNormalResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095 {
2096 error.Clear();
2097 return response.GetHexBytes(buf, size, '\xdd');
2098 }
Greg Clayton576d8832011-03-22 04:00:09 +00002099 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002100 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002101 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002102 error.SetErrorStringWithFormat("GDB server does not support reading memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002104 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105 }
2106 else
2107 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002108 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109 }
2110 return 0;
2111}
2112
2113size_t
2114ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2115{
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002116 if (size > m_max_memory_size)
2117 {
2118 // Keep memory read sizes down to a sane limit. This function will be
2119 // called multiple times in order to complete the task by
2120 // lldb_private::Process so it is ok to do this.
2121 size = m_max_memory_size;
2122 }
2123
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124 StreamString packet;
Daniel Malead01b2952012-11-29 21:49:15 +00002125 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
Greg Clayton7fb56d02011-02-01 01:31:41 +00002126 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002127 StringExtractorGDBRemote response;
Greg Clayton3dedae12013-12-06 21:45:27 +00002128 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129 {
Greg Clayton576d8832011-03-22 04:00:09 +00002130 if (response.IsOKResponse())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002131 {
2132 error.Clear();
2133 return size;
2134 }
Greg Clayton576d8832011-03-22 04:00:09 +00002135 else if (response.IsErrorResponse())
Greg Claytonb9d5df52012-12-06 22:49:16 +00002136 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
Greg Clayton576d8832011-03-22 04:00:09 +00002137 else if (response.IsUnsupportedResponse())
Greg Clayton9944cd72012-09-19 01:46:31 +00002138 error.SetErrorStringWithFormat("GDB server does not support writing memory");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139 else
Greg Clayton9944cd72012-09-19 01:46:31 +00002140 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 +00002141 }
2142 else
2143 {
Jim Ingham35579dd2013-06-03 19:34:01 +00002144 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145 }
2146 return 0;
2147}
2148
2149lldb::addr_t
2150ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2151{
Greg Clayton2a48f522011-05-14 01:50:35 +00002152 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2153
Greg Clayton70b57652011-05-15 01:25:55 +00002154 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
Greg Clayton2a48f522011-05-14 01:50:35 +00002155 switch (supported)
2156 {
2157 case eLazyBoolCalculate:
2158 case eLazyBoolYes:
2159 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2160 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2161 return allocated_addr;
2162
2163 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002164 // Call mmap() to create memory in the inferior..
2165 unsigned prot = 0;
2166 if (permissions & lldb::ePermissionsReadable)
2167 prot |= eMmapProtRead;
2168 if (permissions & lldb::ePermissionsWritable)
2169 prot |= eMmapProtWrite;
2170 if (permissions & lldb::ePermissionsExecutable)
2171 prot |= eMmapProtExec;
Greg Clayton2a48f522011-05-14 01:50:35 +00002172
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002173 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2174 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2175 m_addr_to_mmap_size[allocated_addr] = size;
2176 else
2177 allocated_addr = LLDB_INVALID_ADDRESS;
Greg Clayton2a48f522011-05-14 01:50:35 +00002178 break;
2179 }
2180
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002181 if (allocated_addr == LLDB_INVALID_ADDRESS)
Daniel Malead01b2952012-11-29 21:49:15 +00002182 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183 else
2184 error.Clear();
2185 return allocated_addr;
2186}
2187
2188Error
Greg Clayton46fb5582011-11-18 07:03:08 +00002189ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
2190 MemoryRegionInfo &region_info)
2191{
2192
2193 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
2194 return error;
2195}
2196
2197Error
Johnny Chen64637202012-05-23 21:09:52 +00002198ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
2199{
2200
2201 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
2202 return error;
2203}
2204
2205Error
Enrico Granataf04a2192012-07-13 23:18:48 +00002206ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
2207{
2208 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after));
2209 return error;
2210}
2211
2212Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002213ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
2214{
2215 Error error;
Greg Clayton70b57652011-05-15 01:25:55 +00002216 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2217
2218 switch (supported)
2219 {
2220 case eLazyBoolCalculate:
2221 // We should never be deallocating memory without allocating memory
2222 // first so we should never get eLazyBoolCalculate
2223 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
2224 break;
2225
2226 case eLazyBoolYes:
2227 if (!m_gdb_comm.DeallocateMemory (addr))
Daniel Malead01b2952012-11-29 21:49:15 +00002228 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002229 break;
2230
2231 case eLazyBoolNo:
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002232 // Call munmap() to deallocate memory in the inferior..
Greg Clayton70b57652011-05-15 01:25:55 +00002233 {
2234 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
Peter Collingbourne99f9aa02011-06-03 20:40:38 +00002235 if (pos != m_addr_to_mmap_size.end() &&
2236 InferiorCallMunmap(this, addr, pos->second))
2237 m_addr_to_mmap_size.erase (pos);
2238 else
Daniel Malead01b2952012-11-29 21:49:15 +00002239 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
Greg Clayton70b57652011-05-15 01:25:55 +00002240 }
2241 break;
2242 }
2243
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002244 return error;
2245}
2246
2247
2248//------------------------------------------------------------------
2249// Process STDIO
2250//------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251size_t
2252ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
2253{
2254 if (m_stdio_communication.IsConnected())
2255 {
2256 ConnectionStatus status;
2257 m_stdio_communication.Write(src, src_len, status, NULL);
2258 }
2259 return 0;
2260}
2261
2262Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002263ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002264{
2265 Error error;
2266 assert (bp_site != NULL);
2267
Greg Clayton5160ce52013-03-27 23:08:40 +00002268 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 user_id_t site_id = bp_site->GetID();
2270 const addr_t addr = bp_site->GetLoadAddress();
2271 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002272 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273
2274 if (bp_site->IsEnabled())
2275 {
2276 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002277 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 +00002278 return error;
2279 }
2280 else
2281 {
2282 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2283
Greg Claytoneb023e72013-10-11 19:48:25 +00002284 if (bp_site->HardwareRequired())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285 {
2286 // Try and set hardware breakpoint, and if that fails, fall through
2287 // and set a software breakpoint?
Greg Clayton8b82f082011-04-12 05:54:46 +00002288 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002290 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291 {
2292 bp_site->SetEnabled(true);
Greg Clayton8b82f082011-04-12 05:54:46 +00002293 bp_site->SetType (BreakpointSite::eHardware);
Greg Claytoneb023e72013-10-11 19:48:25 +00002294 }
2295 else
2296 {
2297 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002300 else
2301 {
2302 error.SetErrorString("hardware breakpoints are not supported");
2303 }
2304 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002305 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002306 else if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002308 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
2309 {
2310 bp_site->SetEnabled(true);
2311 bp_site->SetType (BreakpointSite::eExternal);
2312 return error;
2313 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002315
2316 return EnableSoftwareBreakpoint (bp_site);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317 }
2318
2319 if (log)
2320 {
2321 const char *err_string = error.AsCString();
Jim Ingham299c0c12013-02-15 02:06:30 +00002322 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 bp_site->GetLoadAddress(),
2324 err_string ? err_string : "NULL");
2325 }
2326 // We shouldn't reach here on a successful breakpoint enable...
2327 if (error.Success())
2328 error.SetErrorToGenericError();
2329 return error;
2330}
2331
2332Error
Jim Ingham299c0c12013-02-15 02:06:30 +00002333ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334{
2335 Error error;
2336 assert (bp_site != NULL);
2337 addr_t addr = bp_site->GetLoadAddress();
2338 user_id_t site_id = bp_site->GetID();
Greg Clayton5160ce52013-03-27 23:08:40 +00002339 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002341 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342
2343 if (bp_site->IsEnabled())
2344 {
2345 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
2346
Greg Clayton8b82f082011-04-12 05:54:46 +00002347 BreakpointSite::Type bp_type = bp_site->GetType();
2348 switch (bp_type)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002350 case BreakpointSite::eSoftware:
2351 error = DisableSoftwareBreakpoint (bp_site);
2352 break;
2353
2354 case BreakpointSite::eHardware:
2355 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2356 error.SetErrorToGenericError();
2357 break;
2358
2359 case BreakpointSite::eExternal:
2360 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size))
2361 error.SetErrorToGenericError();
2362 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002363 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002364 if (error.Success())
2365 bp_site->SetEnabled(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 }
2367 else
2368 {
2369 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002370 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 +00002371 return error;
2372 }
2373
2374 if (error.Success())
2375 error.SetErrorToGenericError();
2376 return error;
2377}
2378
Johnny Chen11309a32011-09-06 22:38:36 +00002379// Pre-requisite: wp != NULL.
2380static GDBStoppointType
Johnny Chen01a67862011-10-14 00:42:25 +00002381GetGDBStoppointType (Watchpoint *wp)
Johnny Chen11309a32011-09-06 22:38:36 +00002382{
2383 assert(wp);
2384 bool watch_read = wp->WatchpointRead();
2385 bool watch_write = wp->WatchpointWrite();
2386
2387 // watch_read and watch_write cannot both be false.
2388 assert(watch_read || watch_write);
2389 if (watch_read && watch_write)
2390 return eWatchpointReadWrite;
Johnny Chen6d487a92011-09-09 20:35:15 +00002391 else if (watch_read)
Johnny Chen11309a32011-09-06 22:38:36 +00002392 return eWatchpointRead;
Johnny Chen6d487a92011-09-09 20:35:15 +00002393 else // Must be watch_write, then.
Johnny Chen11309a32011-09-06 22:38:36 +00002394 return eWatchpointWrite;
2395}
2396
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002397Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002398ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399{
2400 Error error;
2401 if (wp)
2402 {
2403 user_id_t watchID = wp->GetID();
2404 addr_t addr = wp->GetLoadAddress();
Greg Clayton5160ce52013-03-27 23:08:40 +00002405 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002407 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408 if (wp->IsEnabled())
2409 {
2410 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002411 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 +00002412 return error;
2413 }
Johnny Chen11309a32011-09-06 22:38:36 +00002414
2415 GDBStoppointType type = GetGDBStoppointType(wp);
2416 // Pass down an appropriate z/Z packet...
2417 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418 {
Johnny Chen11309a32011-09-06 22:38:36 +00002419 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
2420 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002421 wp->SetEnabled(true, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002422 return error;
2423 }
2424 else
2425 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002426 }
Johnny Chen11309a32011-09-06 22:38:36 +00002427 else
2428 error.SetErrorString("watchpoints not supported");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 }
2430 else
2431 {
Johnny Chen01a67862011-10-14 00:42:25 +00002432 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 }
2434 if (error.Success())
2435 error.SetErrorToGenericError();
2436 return error;
2437}
2438
2439Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002440ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002441{
2442 Error error;
2443 if (wp)
2444 {
2445 user_id_t watchID = wp->GetID();
2446
Greg Clayton5160ce52013-03-27 23:08:40 +00002447 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448
2449 addr_t addr = wp->GetLoadAddress();
Jim Ingham1b5792e2012-12-18 02:03:49 +00002450
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002452 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453
Johnny Chen11309a32011-09-06 22:38:36 +00002454 if (!wp->IsEnabled())
2455 {
2456 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002457 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 +00002458 // See also 'class WatchpointSentry' within StopInfo.cpp.
2459 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
2460 // the watchpoint object to intelligently process this action.
Jim Ingham1b5792e2012-12-18 02:03:49 +00002461 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002462 return error;
2463 }
2464
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002465 if (wp->IsHardware())
2466 {
Johnny Chen11309a32011-09-06 22:38:36 +00002467 GDBStoppointType type = GetGDBStoppointType(wp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468 // Pass down an appropriate z/Z packet...
Johnny Chen11309a32011-09-06 22:38:36 +00002469 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
2470 {
Jim Ingham1b5792e2012-12-18 02:03:49 +00002471 wp->SetEnabled(false, notify);
Johnny Chen11309a32011-09-06 22:38:36 +00002472 return error;
2473 }
2474 else
2475 error.SetErrorString("sending gdb watchpoint packet failed");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 }
2477 // TODO: clear software watchpoints if we implement them
2478 }
2479 else
2480 {
Johnny Chen01a67862011-10-14 00:42:25 +00002481 error.SetErrorString("Watchpoint argument was NULL.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482 }
2483 if (error.Success())
2484 error.SetErrorToGenericError();
2485 return error;
2486}
2487
2488void
2489ProcessGDBRemote::Clear()
2490{
2491 m_flags = 0;
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00002492 m_thread_list_real.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002494}
2495
2496Error
2497ProcessGDBRemote::DoSignal (int signo)
2498{
2499 Error error;
Greg Clayton5160ce52013-03-27 23:08:40 +00002500 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 if (log)
2502 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
2503
2504 if (!m_gdb_comm.SendAsyncSignal (signo))
2505 error.SetErrorStringWithFormat("failed to send signal %i", signo);
2506 return error;
2507}
2508
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509Error
Greg Clayton91a9b2472013-12-04 19:19:12 +00002510ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002511{
2512 Error error;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002513 uint16_t port = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002514 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
2515 {
2516 // If we locate debugserver, keep that located version around
2517 static FileSpec g_debugserver_file_spec;
2518
Han Ming Ong84647042012-02-25 01:07:38 +00002519 ProcessLaunchInfo debugserver_launch_info;
Greg Clayton91a9b2472013-12-04 19:19:12 +00002520 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
2521 debugserver_launch_info.SetUserID(process_info.GetUserID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522
Greg Clayton00fe87b2013-12-05 22:58:22 +00002523 error = m_gdb_comm.StartDebugserverProcess (NULL,
2524 debugserver_launch_info,
2525 port);
Greg Clayton91a9b2472013-12-04 19:19:12 +00002526
2527 if (error.Success ())
2528 m_debugserver_pid = debugserver_launch_info.GetProcessID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002529 else
Greg Clayton91a9b2472013-12-04 19:19:12 +00002530 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002531
2532 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2533 StartAsyncThread ();
Greg Clayton91a9b2472013-12-04 19:19:12 +00002534
2535 if (error.Fail())
2536 {
2537 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
2538
2539 if (log)
2540 log->Printf("failed to start debugserver process: %s", error.AsCString());
2541 return error;
2542 }
2543
Greg Clayton00fe87b2013-12-05 22:58:22 +00002544 if (m_gdb_comm.IsConnected())
2545 {
2546 // Finish the connection process by doing the handshake without connecting (send NULL URL)
2547 ConnectToDebugserver (NULL);
2548 }
2549 else
2550 {
2551 char connect_url[128];
2552 snprintf (connect_url, sizeof(connect_url), "connect://localhost:%u", port);
2553 error = ConnectToDebugserver (connect_url);
2554 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00002555
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556 }
2557 return error;
2558}
2559
2560bool
2561ProcessGDBRemote::MonitorDebugserverProcess
2562(
2563 void *callback_baton,
2564 lldb::pid_t debugserver_pid,
Greg Claytone4e45922011-11-16 05:37:56 +00002565 bool exited, // True if the process did exit
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002566 int signo, // Zero for no signal
2567 int exit_status // Exit value of process if signal is zero
2568)
2569{
Greg Claytone4e45922011-11-16 05:37:56 +00002570 // The baton is a "ProcessGDBRemote *". Now this class might be gone
2571 // and might not exist anymore, so we need to carefully try to get the
2572 // target for this process first since we have a race condition when
2573 // we are done running between getting the notice that the inferior
2574 // process has died and the debugserver that was debugging this process.
2575 // In our test suite, we are also continually running process after
2576 // process, so we must be very careful to make sure:
2577 // 1 - process object hasn't been deleted already
2578 // 2 - that a new process object hasn't been recreated in its place
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002579
2580 // "debugserver_pid" argument passed in is the process ID for
2581 // debugserver that we are tracking...
Greg Clayton5160ce52013-03-27 23:08:40 +00002582 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002584 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
Greg Clayton6779606a2011-01-22 23:43:18 +00002585
Greg Claytone4e45922011-11-16 05:37:56 +00002586 // Get a shared pointer to the target that has a matching process pointer.
2587 // This target could be gone, or the target could already have a new process
2588 // object inside of it
2589 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
2590
Greg Clayton6779606a2011-01-22 23:43:18 +00002591 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002592 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 +00002593
Greg Claytone4e45922011-11-16 05:37:56 +00002594 if (target_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595 {
Greg Claytone4e45922011-11-16 05:37:56 +00002596 // We found a process in a target that matches, but another thread
2597 // might be in the process of launching a new process that will
2598 // soon replace it, so get a shared pointer to the process so we
2599 // can keep it alive.
2600 ProcessSP process_sp (target_sp->GetProcessSP());
2601 // Now we have a shared pointer to the process that can't go away on us
2602 // so we now make sure it was the same as the one passed in, and also make
2603 // sure that our previous "process *" didn't get deleted and have a new
2604 // "process *" created in its place with the same pointer. To verify this
2605 // we make sure the process has our debugserver process ID. If we pass all
2606 // of these tests, then we are sure that this process is the one we were
2607 // looking for.
2608 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002609 {
Greg Claytone4e45922011-11-16 05:37:56 +00002610 // Sleep for a half a second to make sure our inferior process has
2611 // time to set its exit status before we set it incorrectly when
2612 // both the debugserver and the inferior process shut down.
2613 usleep (500000);
2614 // If our process hasn't yet exited, debugserver might have died.
2615 // If the process did exit, the we are reaping it.
2616 const StateType state = process->GetState();
2617
2618 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
2619 state != eStateInvalid &&
2620 state != eStateUnloaded &&
2621 state != eStateExited &&
2622 state != eStateDetached)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623 {
Greg Claytone4e45922011-11-16 05:37:56 +00002624 char error_str[1024];
2625 if (signo)
2626 {
2627 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo);
2628 if (signal_cstr)
2629 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
2630 else
2631 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
2632 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633 else
Greg Claytone4e45922011-11-16 05:37:56 +00002634 {
2635 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
2636 }
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002637
Greg Claytone4e45922011-11-16 05:37:56 +00002638 process->SetExitStatus (-1, error_str);
2639 }
2640 // Debugserver has exited we need to let our ProcessGDBRemote
2641 // know that it no longer has a debugserver instance
2642 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
Greg Clayton0b76a2c2010-08-21 02:22:51 +00002643 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002644 }
2645 return true;
2646}
2647
2648void
2649ProcessGDBRemote::KillDebugserverProcess ()
2650{
Greg Claytonfbb76342013-11-20 21:07:01 +00002651 m_gdb_comm.Disconnect();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002652 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
2653 {
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002654 Host::Kill (m_debugserver_pid, SIGINT);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
2656 }
2657}
2658
2659void
2660ProcessGDBRemote::Initialize()
2661{
2662 static bool g_initialized = false;
2663
2664 if (g_initialized == false)
2665 {
2666 g_initialized = true;
2667 PluginManager::RegisterPlugin (GetPluginNameStatic(),
2668 GetPluginDescriptionStatic(),
Greg Clayton7f982402013-07-15 22:54:20 +00002669 CreateInstance,
2670 DebuggerInitialize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002671
2672 Log::Callbacks log_callbacks = {
2673 ProcessGDBRemoteLog::DisableLog,
2674 ProcessGDBRemoteLog::EnableLog,
2675 ProcessGDBRemoteLog::ListLogCategories
2676 };
2677
2678 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks);
2679 }
2680}
2681
Greg Clayton7f982402013-07-15 22:54:20 +00002682void
2683ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger)
2684{
2685 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
2686 {
2687 const bool is_global_setting = true;
2688 PluginManager::CreateSettingForProcessPlugin (debugger,
2689 GetGlobalPluginProperties()->GetValueProperties(),
2690 ConstString ("Properties for the gdb-remote process plug-in."),
2691 is_global_setting);
2692 }
2693}
2694
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002695bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696ProcessGDBRemote::StartAsyncThread ()
2697{
Greg Clayton5160ce52013-03-27 23:08:40 +00002698 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699
2700 if (log)
2701 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
Jim Ingham455fa5c2012-11-01 01:15:33 +00002702
2703 Mutex::Locker start_locker(m_async_thread_state_mutex);
2704 if (m_async_thread_state == eAsyncThreadNotStarted)
2705 {
2706 // Create a thread that watches our internal state and controls which
2707 // events make it to clients (into the DCProcess event queue).
2708 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
2709 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2710 {
2711 m_async_thread_state = eAsyncThreadRunning;
2712 return true;
2713 }
2714 else
2715 return false;
2716 }
2717 else
2718 {
2719 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and
2720 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it.
2721 if (log)
2722 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
2723 if (m_async_thread_state == eAsyncThreadRunning)
2724 return true;
2725 else
2726 return false;
2727 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728}
2729
2730void
2731ProcessGDBRemote::StopAsyncThread ()
2732{
Greg Clayton5160ce52013-03-27 23:08:40 +00002733 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734
2735 if (log)
2736 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
2737
Jim Ingham455fa5c2012-11-01 01:15:33 +00002738 Mutex::Locker start_locker(m_async_thread_state_mutex);
2739 if (m_async_thread_state == eAsyncThreadRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740 {
Jim Ingham455fa5c2012-11-01 01:15:33 +00002741 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
2742
2743 // This will shut down the async thread.
2744 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
2745
2746 // Stop the stdio thread
2747 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread))
2748 {
2749 Host::ThreadJoin (m_async_thread, NULL, NULL);
2750 }
2751 m_async_thread_state = eAsyncThreadDone;
2752 }
2753 else
2754 {
2755 if (log)
2756 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757 }
2758}
2759
2760
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002761thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762ProcessGDBRemote::AsyncThread (void *arg)
2763{
2764 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
2765
Greg Clayton5160ce52013-03-27 23:08:40 +00002766 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002768 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769
2770 Listener listener ("ProcessGDBRemote::AsyncThread");
2771 EventSP event_sp;
2772 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
2773 eBroadcastBitAsyncThreadShouldExit;
2774
2775 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
2776 {
Greg Clayton71337622011-02-24 22:24:29 +00002777 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit);
2778
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779 bool done = false;
2780 while (!done)
2781 {
2782 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002783 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002784 if (listener.WaitForEvent (NULL, event_sp))
2785 {
2786 const uint32_t event_type = event_sp->GetType();
Greg Clayton71337622011-02-24 22:24:29 +00002787 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788 {
Greg Clayton71337622011-02-24 22:24:29 +00002789 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002790 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 +00002791
Greg Clayton71337622011-02-24 22:24:29 +00002792 switch (event_type)
2793 {
2794 case eBroadcastBitAsyncContinue:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795 {
Greg Clayton71337622011-02-24 22:24:29 +00002796 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797
Greg Clayton71337622011-02-24 22:24:29 +00002798 if (continue_packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002799 {
Greg Clayton71337622011-02-24 22:24:29 +00002800 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
2801 const size_t continue_cstr_len = continue_packet->GetByteSize ();
2802 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002803 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804
Greg Clayton71337622011-02-24 22:24:29 +00002805 if (::strstr (continue_cstr, "vAttach") == NULL)
2806 process->SetPrivateState(eStateRunning);
2807 StringExtractorGDBRemote response;
2808 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002809
Greg Clayton0772ded2012-05-16 02:48:06 +00002810 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
2811 // The thread ID list might be contained within the "response", or the stop reply packet that
2812 // caused the stop. So clear it now before we give the stop reply packet to the process
2813 // using the process->SetLastStopPacket()...
2814 process->ClearThreadIDList ();
2815
Greg Clayton71337622011-02-24 22:24:29 +00002816 switch (stop_state)
2817 {
2818 case eStateStopped:
2819 case eStateCrashed:
2820 case eStateSuspended:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002821 process->SetLastStopPacket (response);
Greg Clayton71337622011-02-24 22:24:29 +00002822 process->SetPrivateState (stop_state);
2823 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824
Greg Clayton71337622011-02-24 22:24:29 +00002825 case eStateExited:
Greg Clayton09c3e3d2011-12-06 04:51:14 +00002826 process->SetLastStopPacket (response);
Greg Clayton9e920902012-04-10 02:25:43 +00002827 process->ClearThreadIDList();
Greg Clayton71337622011-02-24 22:24:29 +00002828 response.SetFilePos(1);
2829 process->SetExitStatus(response.GetHexU8(), NULL);
2830 done = true;
2831 break;
2832
2833 case eStateInvalid:
2834 process->SetExitStatus(-1, "lost connection");
2835 break;
2836
2837 default:
2838 process->SetPrivateState (stop_state);
2839 break;
2840 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841 }
2842 }
Greg Clayton71337622011-02-24 22:24:29 +00002843 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002844
Greg Clayton71337622011-02-24 22:24:29 +00002845 case eBroadcastBitAsyncThreadShouldExit:
2846 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002847 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
Greg Clayton71337622011-02-24 22:24:29 +00002848 done = true;
2849 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850
Greg Clayton71337622011-02-24 22:24:29 +00002851 default:
2852 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002853 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 +00002854 done = true;
2855 break;
2856 }
2857 }
2858 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
2859 {
2860 if (event_type & Communication::eBroadcastBitReadThreadDidExit)
2861 {
2862 process->SetExitStatus (-1, "lost connection");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002863 done = true;
Greg Clayton71337622011-02-24 22:24:29 +00002864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865 }
2866 }
2867 else
2868 {
2869 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002870 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 +00002871 done = true;
2872 }
2873 }
2874 }
2875
2876 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002877 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878
2879 process->m_async_thread = LLDB_INVALID_HOST_THREAD;
2880 return NULL;
2881}
2882
Greg Claytone996fd32011-03-08 22:40:15 +00002883//uint32_t
2884//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
2885//{
2886// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
2887// // process and ask it for the list of processes. But if we are local, we can let the Host do it.
2888// if (m_local_debugserver)
2889// {
2890// return Host::ListProcessesMatchingName (name, matches, pids);
2891// }
2892// else
2893// {
2894// // FIXME: Implement talking to the remote debugserver.
2895// return 0;
2896// }
2897//
2898//}
2899//
Jim Ingham1c823b42011-01-22 01:33:44 +00002900bool
2901ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
2902 lldb_private::StoppointCallbackContext *context,
2903 lldb::user_id_t break_id,
2904 lldb::user_id_t break_loc_id)
2905{
2906 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
2907 // run so I can stop it if that's what I want to do.
Greg Clayton5160ce52013-03-27 23:08:40 +00002908 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham1c823b42011-01-22 01:33:44 +00002909 if (log)
2910 log->Printf("Hit New Thread Notification breakpoint.");
2911 return false;
2912}
2913
2914
2915bool
2916ProcessGDBRemote::StartNoticingNewThreads()
2917{
Greg Clayton5160ce52013-03-27 23:08:40 +00002918 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Greg Clayton4116e932012-05-15 02:33:01 +00002919 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002920 {
Greg Clayton4116e932012-05-15 02:33:01 +00002921 if (log && log->GetVerbose())
2922 log->Printf("Enabled noticing new thread breakpoint.");
2923 m_thread_create_bp_sp->SetEnabled(true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002924 }
Greg Clayton4116e932012-05-15 02:33:01 +00002925 else
Jim Ingham1c823b42011-01-22 01:33:44 +00002926 {
Greg Clayton4116e932012-05-15 02:33:01 +00002927 PlatformSP platform_sp (m_target.GetPlatform());
2928 if (platform_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002929 {
Greg Clayton4116e932012-05-15 02:33:01 +00002930 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
2931 if (m_thread_create_bp_sp)
Jim Ingham1c823b42011-01-22 01:33:44 +00002932 {
Jim Ingham37cfeab2011-10-15 00:21:37 +00002933 if (log && log->GetVerbose())
Greg Clayton4116e932012-05-15 02:33:01 +00002934 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
2935 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
Jim Ingham1c823b42011-01-22 01:33:44 +00002936 }
2937 else
2938 {
2939 if (log)
2940 log->Printf("Failed to create new thread notification breakpoint.");
Jim Ingham1c823b42011-01-22 01:33:44 +00002941 }
2942 }
2943 }
Greg Clayton4116e932012-05-15 02:33:01 +00002944 return m_thread_create_bp_sp.get() != NULL;
Jim Ingham1c823b42011-01-22 01:33:44 +00002945}
2946
2947bool
2948ProcessGDBRemote::StopNoticingNewThreads()
2949{
Greg Clayton5160ce52013-03-27 23:08:40 +00002950 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Jim Ingham37cfeab2011-10-15 00:21:37 +00002951 if (log && log->GetVerbose())
Jim Ingham0e97cbc2011-02-08 05:19:01 +00002952 log->Printf ("Disabling new thread notification breakpoint.");
Greg Clayton4116e932012-05-15 02:33:01 +00002953
2954 if (m_thread_create_bp_sp)
2955 m_thread_create_bp_sp->SetEnabled(false);
2956
Jim Ingham1c823b42011-01-22 01:33:44 +00002957 return true;
2958}
2959
Jason Molenda5e8534e2012-10-03 01:29:34 +00002960lldb_private::DynamicLoader *
2961ProcessGDBRemote::GetDynamicLoader ()
2962{
2963 if (m_dyld_ap.get() == NULL)
Jason Molenda2e56a252013-05-11 03:09:05 +00002964 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Jason Molenda5e8534e2012-10-03 01:29:34 +00002965 return m_dyld_ap.get();
2966}
Jim Ingham1c823b42011-01-22 01:33:44 +00002967
Greg Clayton998255b2012-10-13 02:07:45 +00002968
Greg Clayton02686b82012-10-15 22:42:16 +00002969class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
Greg Clayton998255b2012-10-13 02:07:45 +00002970{
2971private:
2972
2973public:
Greg Clayton02686b82012-10-15 22:42:16 +00002974 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
Greg Clayton998255b2012-10-13 02:07:45 +00002975 CommandObjectParsed (interpreter,
Greg Clayton02686b82012-10-15 22:42:16 +00002976 "process plugin packet history",
2977 "Dumps the packet history buffer. ",
Greg Clayton998255b2012-10-13 02:07:45 +00002978 NULL)
2979 {
2980 }
2981
Greg Clayton02686b82012-10-15 22:42:16 +00002982 ~CommandObjectProcessGDBRemotePacketHistory ()
Greg Clayton998255b2012-10-13 02:07:45 +00002983 {
2984 }
2985
2986 bool
2987 DoExecute (Args& command, CommandReturnObject &result)
2988 {
Greg Clayton02686b82012-10-15 22:42:16 +00002989 const size_t argc = command.GetArgumentCount();
2990 if (argc == 0)
2991 {
2992 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
2993 if (process)
2994 {
2995 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
2996 result.SetStatus (eReturnStatusSuccessFinishResult);
2997 return true;
2998 }
2999 }
3000 else
3001 {
3002 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
3003 }
3004 result.SetStatus (eReturnStatusFailed);
3005 return false;
3006 }
3007};
3008
3009class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
3010{
3011private:
3012
3013public:
3014 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
3015 CommandObjectParsed (interpreter,
3016 "process plugin packet send",
3017 "Send a custom packet through the GDB remote protocol and print the answer. "
3018 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
3019 NULL)
3020 {
3021 }
3022
3023 ~CommandObjectProcessGDBRemotePacketSend ()
3024 {
3025 }
3026
3027 bool
3028 DoExecute (Args& command, CommandReturnObject &result)
3029 {
3030 const size_t argc = command.GetArgumentCount();
3031 if (argc == 0)
3032 {
3033 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
3034 result.SetStatus (eReturnStatusFailed);
3035 return false;
3036 }
3037
3038 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3039 if (process)
3040 {
Han Ming Ong84145852012-11-26 20:42:03 +00003041 for (size_t i=0; i<argc; ++ i)
Greg Clayton02686b82012-10-15 22:42:16 +00003042 {
Han Ming Ong84145852012-11-26 20:42:03 +00003043 const char *packet_cstr = command.GetArgumentAtIndex(0);
3044 bool send_async = true;
3045 StringExtractorGDBRemote response;
3046 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3047 result.SetStatus (eReturnStatusSuccessFinishResult);
3048 Stream &output_strm = result.GetOutputStream();
3049 output_strm.Printf (" packet: %s\n", packet_cstr);
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003050 std::string &response_str = response.GetStringRef();
3051
Han Ming Ong399289e2013-06-21 19:56:59 +00003052 if (strstr(packet_cstr, "qGetProfileData") != NULL)
Han Ming Ong4b6459f2013-01-18 23:11:53 +00003053 {
3054 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
3055 }
3056
Han Ming Ong84145852012-11-26 20:42:03 +00003057 if (response_str.empty())
3058 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3059 else
3060 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
Greg Clayton02686b82012-10-15 22:42:16 +00003061 }
Greg Clayton02686b82012-10-15 22:42:16 +00003062 }
Greg Clayton998255b2012-10-13 02:07:45 +00003063 return true;
3064 }
3065};
3066
Greg Claytonba4a0a52013-02-01 23:03:47 +00003067class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
3068{
3069private:
3070
3071public:
3072 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
3073 CommandObjectRaw (interpreter,
3074 "process plugin packet monitor",
Greg Claytoneee5e982013-02-14 18:39:30 +00003075 "Send a qRcmd packet through the GDB remote protocol and print the response."
3076 "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 +00003077 NULL)
3078 {
3079 }
3080
3081 ~CommandObjectProcessGDBRemotePacketMonitor ()
3082 {
3083 }
3084
3085 bool
3086 DoExecute (const char *command, CommandReturnObject &result)
3087 {
3088 if (command == NULL || command[0] == '\0')
3089 {
3090 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
3091 result.SetStatus (eReturnStatusFailed);
3092 return false;
3093 }
3094
3095 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
3096 if (process)
3097 {
3098 StreamString packet;
Greg Claytoneee5e982013-02-14 18:39:30 +00003099 packet.PutCString("qRcmd,");
Greg Claytonba4a0a52013-02-01 23:03:47 +00003100 packet.PutBytesAsRawHex8(command, strlen(command));
3101 const char *packet_cstr = packet.GetString().c_str();
3102
3103 bool send_async = true;
3104 StringExtractorGDBRemote response;
3105 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
3106 result.SetStatus (eReturnStatusSuccessFinishResult);
3107 Stream &output_strm = result.GetOutputStream();
3108 output_strm.Printf (" packet: %s\n", packet_cstr);
3109 const std::string &response_str = response.GetStringRef();
3110
3111 if (response_str.empty())
3112 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
3113 else
3114 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
3115 }
3116 return true;
3117 }
3118};
3119
Greg Clayton02686b82012-10-15 22:42:16 +00003120class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
3121{
3122private:
3123
3124public:
3125 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
3126 CommandObjectMultiword (interpreter,
3127 "process plugin packet",
3128 "Commands that deal with GDB remote packets.",
3129 NULL)
3130 {
3131 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
3132 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
Greg Claytonba4a0a52013-02-01 23:03:47 +00003133 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
Greg Clayton02686b82012-10-15 22:42:16 +00003134 }
3135
3136 ~CommandObjectProcessGDBRemotePacket ()
3137 {
3138 }
3139};
Greg Clayton998255b2012-10-13 02:07:45 +00003140
3141class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
3142{
3143public:
3144 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
3145 CommandObjectMultiword (interpreter,
3146 "process plugin",
3147 "A set of commands for operating on a ProcessGDBRemote process.",
3148 "process plugin <subcommand> [<subcommand-options>]")
3149 {
3150 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
3151 }
3152
3153 ~CommandObjectMultiwordProcessGDBRemote ()
3154 {
3155 }
3156};
3157
Greg Clayton998255b2012-10-13 02:07:45 +00003158CommandObject *
3159ProcessGDBRemote::GetPluginCommandObject()
3160{
3161 if (!m_command_sp)
3162 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
3163 return m_command_sp.get();
3164}